repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Ferrari-lee/firefox-ios
|
refs/heads/autocomplete-highlight
|
Sync/Record.swift
|
mpl-2.0
|
30
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = Logger.syncLogger
let ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60;
/**
* Immutable representation for Sync records.
*
* Envelopes consist of:
* Required: "id", "collection", "payload".
* Optional: "modified", "sortindex", "ttl".
*
* Deletedness is a property of the payload.
*/
public class Record<T: CleartextPayloadJSON> {
public let id: String
public let payload: T
public let modified: Timestamp
public let sortindex: Int
public let ttl: Int? // Seconds. Can be null, which means 'don't expire'.
// This is a hook for decryption.
// Right now it only parses the string. In subclasses, it'll parse the
// string, decrypt the contents, and return the data as a JSON object.
// From the docs:
//
// payload none string 256k
// A string containing a JSON structure encapsulating the data of the record.
// This structure is defined separately for each WBO type.
// Parts of the structure may be encrypted, in which case the structure
// should also specify a record for decryption.
//
// @seealso EncryptedRecord.
public class func payloadFromPayloadString(envelope: EnvelopeJSON, payload: String) -> T? {
return T(payload)
}
// TODO: consider using error tuples.
public class func fromEnvelope(envelope: EnvelopeJSON, payloadFactory: (String) -> T?) -> Record<T>? {
if !(envelope.isValid()) {
log.error("Invalid envelope.")
return nil
}
let payload = payloadFactory(envelope.payload)
if (payload == nil) {
log.error("Unable to parse payload.")
return nil
}
if payload!.isValid() {
return Record<T>(envelope: envelope, payload: payload!)
}
log.error("Invalid payload \(payload!.toString(true)).")
return nil
}
/**
* Accepts an envelope and a decrypted payload.
* Inputs are not validated. Use `fromEnvelope` above.
*/
convenience init(envelope: EnvelopeJSON, payload: T) {
// TODO: modified, sortindex, ttl
self.init(id: envelope.id, payload: payload, modified: envelope.modified, sortindex: envelope.sortindex)
}
init(id: GUID, payload: T, modified: Timestamp = Timestamp(time(nil)), sortindex: Int = 0, ttl: Int? = nil) {
self.id = id
self.payload = payload;
self.modified = modified
self.sortindex = sortindex
self.ttl = ttl
}
func equalIdentifiers(rec: Record) -> Bool {
return rec.id == self.id
}
// Override me.
func equalPayloads(rec: Record) -> Bool {
return equalIdentifiers(rec) && rec.payload.deleted == self.payload.deleted
}
func equals(rec: Record) -> Bool {
return rec.sortindex == self.sortindex &&
rec.modified == self.modified &&
equalPayloads(rec)
}
}
|
ddc239c028755e1049c45b7da91d4bf5
| 30.95 | 113 | 0.626917 | false | false | false | false |
LockLight/Weibo_Demo
|
refs/heads/master
|
SinaWeibo/SinaWeibo/Classes/View/Compose(发布微博)/WBPicViewCell.swift
|
mit
|
1
|
//
// WBPicViewCell.swift
// SinaWeibo
//
// Created by locklight on 17/4/12.
// Copyright © 2017年 LockLight. All rights reserved.
//
import UIKit
protocol WBPicViewCellDelegate :NSObjectProtocol{
func addOrReplacePicView(cell:WBPicViewCell)
func deletePic(cell:WBPicViewCell)
}
class WBPicViewCell: UICollectionViewCell {
//代理属性
weak var delegate:WBPicViewCellDelegate?
//图片属性
var image:UIImage?{
didSet{
if let image = image {
addOrReplaceBtn.setBackgroundImage(image, for: .normal)
addOrReplaceBtn.setBackgroundImage(image, for: .highlighted)
}else{
addOrReplaceBtn.setBackgroundImage(UIImage(named:"compose_pic_add"), for: .normal)
addOrReplaceBtn.setBackgroundImage(UIImage(named:"compose_pic_add_highlighted"),for: .highlighted )
}
deleteBtn.isHidden = image == nil
}
}
//添加或替换图片的btn
lazy var addOrReplaceBtn:UIButton = UIButton(title: nil, bgImage: "compose_pic_add", target: self, action: #selector(addOrReplacePicView))
//删除图片的btn
lazy var deleteBtn:UIButton = UIButton(title: nil, bgImage: "compose_photo_close", target: self, action: #selector(deletePic))
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WBPicViewCell{
func addOrReplacePicView(){
self.delegate?.addOrReplacePicView(cell: self)
}
func deletePic(){
self.delegate?.deletePic(cell: self)
}
}
extension WBPicViewCell{
func setupUI(){
addSubview(addOrReplaceBtn)
addSubview(deleteBtn)
addOrReplaceBtn.snp.makeConstraints { (make ) in
make.top.left.equalTo(self.contentView).offset(10)
make.right.bottom.equalTo(self.contentView).offset(-10)
}
deleteBtn.snp.makeConstraints { (make ) in
make.top.equalTo(self.contentView)
make.right.equalTo(self.snp.right).offset(-3)
}
}
}
|
7fc1a01e30eb87ce34de7db0ebe342af
| 26.3375 | 143 | 0.633288 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
Kickstarter-iOS/Features/RewardsCollection/Views/Cells/RewardCell.swift
|
apache-2.0
|
1
|
import KsApi
import Library
import Prelude
import ReactiveSwift
import UIKit
protocol RewardCellDelegate: AnyObject {
func rewardCellDidTapPledgeButton(_ rewardCell: RewardCell, rewardId: Int)
func rewardCell(_ rewardCell: RewardCell, shouldShowDividerLine show: Bool)
}
final class RewardCell: UICollectionViewCell, ValueCell {
// MARK: - Properties
private lazy var backerLabelContainer: UIView = {
UIView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var backerLabel: UILabel = {
UILabel(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
internal weak var delegate: RewardCellDelegate?
private let viewModel: RewardCellViewModelType = RewardCellViewModel()
internal let rewardCardContainerView = RewardCardContainerView(frame: .zero)
private lazy var scrollView = {
UIScrollView(frame: .zero)
|> \.delegate .~ self
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.configureViews()
self.bindViewModel()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func bindViewModel() {
super.bindViewModel()
self.backerLabelContainer.rac.hidden = self.viewModel.outputs.backerLabelHidden
self.viewModel.outputs.scrollScrollViewToTop
.observeForUI()
.observeValues { [weak self] in
guard let self = self else { return }
self.scrollView.setContentOffset(
.init(
x: self.scrollView.contentOffset.x,
y: -self.scrollView.contentInset.top
),
animated: false
)
}
}
// MARK: - Functions
private func configureViews() {
_ = (self.scrollView, self.contentView)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
_ = (self.backerLabel, self.backerLabelContainer)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToMarginsInParent()
_ = (self.backerLabelContainer, self.rewardCardContainerView)
|> ksr_addSubviewToParent()
_ = (self.rewardCardContainerView, self.scrollView)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
self.rewardCardContainerView.delegate = self
self.setupConstraints()
}
private func setupConstraints() {
self.rewardCardContainerView.pinBottomViews(to: self.contentView.layoutMarginsGuide)
let backerLabelContainerYConstraint = NSLayoutConstraint(
item: self.backerLabelContainer,
attribute: .centerY,
relatedBy: .equal,
toItem: self.rewardCardContainerView,
attribute: .top,
multiplier: 0.9,
constant: 0
)
NSLayoutConstraint.activate([
backerLabelContainerYConstraint,
self.backerLabelContainer.leftAnchor.constraint(
equalTo: self.rewardCardContainerView.leftAnchor, constant: Styles.grid(3)
),
self.rewardCardContainerView.widthAnchor.constraint(equalTo: self.contentView.widthAnchor)
])
}
override func bindStyles() {
super.bindStyles()
_ = self.contentView
|> contentViewStyle
|> checkoutBackgroundStyle
_ = self.backerLabelContainer
|> \.backgroundColor .~ .ksr_trust_500
|> roundedStyle(cornerRadius: Styles.grid(1))
|> \.layoutMargins .~ .init(topBottom: Styles.grid(1), leftRight: Styles.grid(2))
_ = self.backerLabel
|> \.text %~ { _ in Strings.Your_selection() }
|> \.font .~ UIFont.ksr_footnote().weighted(.medium)
|> \.textColor .~ .ksr_white
_ = self.scrollView
|> scrollViewStyle
}
internal func configureWith(value: RewardCardViewData) {
self.viewModel.inputs.configure(with: value)
self.rewardCardContainerView.configure(with: value)
}
override func prepareForReuse() {
super.prepareForReuse()
self.viewModel.inputs.prepareForReuse()
}
// MARK: - Accessors
func currentReward(is reward: Reward) -> Bool {
return self.rewardCardContainerView.currentReward(is: reward)
}
}
extension RewardCell: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let scrollViewTopInset = scrollView.contentInset.top
let cardContainerViewY = self.rewardCardContainerView.frame.origin.y
let yOffset = scrollView.contentOffset.y - scrollViewTopInset - cardContainerViewY
let showDivider = yOffset + scrollViewTopInset >= 0
self.delegate?.rewardCell(self, shouldShowDividerLine: showDivider)
}
}
// MARK: - RewardCardViewDelegate
extension RewardCell: RewardCardViewDelegate {
func rewardCardView(_: RewardCardView, didTapWithRewardId rewardId: Int) {
self.delegate?.rewardCellDidTapPledgeButton(self, rewardId: rewardId)
}
}
// MARK: - Styles
private let contentViewStyle: ViewStyle = { view in
view
|> \.layoutMargins .~ .init(all: Styles.grid(3))
}
private let scrollViewStyle: ScrollStyle = { scrollView in
scrollView
|> \.backgroundColor .~ .clear
|> \.contentInset .~ .init(topBottom: Styles.grid(6))
|> \.showsVerticalScrollIndicator .~ false
|> \.contentInsetAdjustmentBehavior .~ UIScrollView.ContentInsetAdjustmentBehavior.never
}
|
05c880a832841b6a60bc9cb0142daae7
| 27.554945 | 96 | 0.703675 | false | false | false | false |
samodom/TestableUIKit
|
refs/heads/master
|
TestableUIKit/UIResponder/UIView/UICollectionView/UICollectionViewMoveSectionSpy.swift
|
mit
|
1
|
//
// UICollectionViewMoveSectionSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/21/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import UIKit
import TestSwagger
import FoundationSwagger
public extension UICollectionView {
private static let moveSectionCalledKeyString = UUIDKeyString()
private static let moveSectionCalledKey =
ObjectAssociationKey(moveSectionCalledKeyString)
private static let moveSectionCalledReference =
SpyEvidenceReference(key: moveSectionCalledKey)
private static let moveSectionFromSectionKeyString = UUIDKeyString()
private static let moveSectionFromSectionKey =
ObjectAssociationKey(moveSectionFromSectionKeyString)
private static let moveSectionFromSectionReference =
SpyEvidenceReference(key: moveSectionFromSectionKey)
private static let moveSectionToSectionKeyString = UUIDKeyString()
private static let moveSectionToSectionKey =
ObjectAssociationKey(moveSectionToSectionKeyString)
private static let moveSectionToSectionReference =
SpyEvidenceReference(key: moveSectionToSectionKey)
private static let moveSectionCoselectors = SpyCoselectors(
methodType: .instance,
original: #selector(UICollectionView.moveSection(_:toSection:)),
spy: #selector(UICollectionView.spy_moveSection(_:toSection:))
)
/// Spy controller for ensuring that a collection view has had `moveSection(_:toSection:)` called on it.
public enum MoveSectionSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UICollectionView.self
public static let vector = SpyVector.direct
public static let coselectors: Set = [moveSectionCoselectors]
public static let evidence: Set = [
moveSectionCalledReference,
moveSectionFromSectionReference,
moveSectionToSectionReference
]
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `moveSection(_:toSection:)`
dynamic public func spy_moveSection(_ fromSection: Int, toSection: Int) {
moveSectionCalled = true
moveSectionFromSection = fromSection
moveSectionToSection = toSection
spy_moveSection(fromSection, toSection: toSection)
}
/// Indicates whether the `moveSection(_:toSection:)` method has been called on this object.
public final var moveSectionCalled: Bool {
get {
return loadEvidence(with: UICollectionView.moveSectionCalledReference) as? Bool ?? false
}
set {
saveEvidence(true, with: UICollectionView.moveSectionCalledReference)
}
}
/// Provides the source section passed to `moveSection(_:toSection:)` if called.
public final var moveSectionFromSection: Int? {
get {
return loadEvidence(with: UICollectionView.moveSectionFromSectionReference) as? Int
}
set {
let reference = UICollectionView.moveSectionFromSectionReference
guard let section = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(section, with: reference)
}
}
/// Provides the destination section passed to `moveSection(_:toSection:)` if called.
public final var moveSectionToSection: Int? {
get {
return loadEvidence(with: UICollectionView.moveSectionToSectionReference) as? Int
}
set {
let reference = UICollectionView.moveSectionToSectionReference
guard let section = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(section, with: reference)
}
}
}
|
9a5374e5b6b5409756478fde77fa695c
| 34.324074 | 108 | 0.694102 | false | false | false | false |
IAskWind/IAWExtensionTool
|
refs/heads/master
|
Pods/Easy/Easy/Classes/Core/EasyNavigationController.swift
|
mit
|
1
|
//
// EasyNavigationController.swift
// Easy
//
// Created by OctMon on 2018/10/12.
//
import UIKit
#if canImport(RTRootNavigationController)
import RTRootNavigationController
public extension Easy {
typealias NavigationController = EasyNavigationController
}
public class EasyNavigationController: RTRootNavigationController {
deinit { EasyLog.debug(toDeinit) }
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
useSystemBackBarButtonItem = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
useSystemBackBarButtonItem = true
}
}
#endif
/// 拦截返回按钮
private protocol EasyNavigationShouldPopOnBackButton {
func navigationShouldPopOnBackButton() -> Bool
func navigationPopOnBackHandler() -> Void
}
extension UIViewController: EasyNavigationShouldPopOnBackButton {
/// 拦截返回按钮, 返回false无法返回
@objc open func navigationShouldPopOnBackButton() -> Bool {
return true
}
/// 拦截返回事件, 可自定义点击 返回按钮后的事件
@objc open func navigationPopOnBackHandler() {
self.navigationController?.popViewController(animated: true)
}
}
extension UINavigationController: UINavigationBarDelegate {
open func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
if let items = navigationBar.items, viewControllers.count < items.count { return true }
var shouldPop = true
let vc = topViewController
if let topVC = vc, topVC.responds(to: #selector(navigationShouldPopOnBackButton)) {
shouldPop = topVC.navigationShouldPopOnBackButton()
}
if shouldPop {
if let topVC = vc, topVC.responds(to: #selector(navigationPopOnBackHandler)) {
EasyApp.runInMain {
topVC.navigationPopOnBackHandler()
}
} else {
EasyApp.runInMain {
self.popViewController(animated: true)
}
}
} else {
for subview in navigationBar.subviews {
if subview.alpha > 0.0 && subview.alpha < 1.0 {
UIView.animate(withDuration: 0.25, animations: {
subview.alpha = 1.0
})
}
}
}
return false
}
}
class EasyFullScreenPopGesture: NSObject {
static func open() -> Void {
UIViewController.vcFullScreenInit()
UINavigationController.navFullScreenInit()
}
}
private class _FullScreenPopGestureDelegate: NSObject, UIGestureRecognizerDelegate {
weak var navigationController: UINavigationController?
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let navController = self.navigationController else { return false }
// 忽略没有控制器可以 push 的时候
guard navController.viewControllers.count > 1 else {
return false
}
// 控制器不允许交互弹出时忽略
guard let topViewController = navController.viewControllers.last, !topViewController.interactivePopDisabled else {
return false
}
if let isTransitioning = navController.value(forKey: "_isTransitioning") as? Bool, isTransitioning {
return false
}
guard let panGesture = gestureRecognizer as? UIPanGestureRecognizer else {
return false
}
// 始位置超出最大允许初始距离时忽略
let beginningLocation = panGesture.location(in: gestureRecognizer.view)
let maxAllowedInitialDistance = topViewController.interactivePopMaxAllowedInitialDistanceToLeftEdge
if maxAllowedInitialDistance > 0, beginningLocation.x > maxAllowedInitialDistance { return false }
let translation = panGesture.translation(in: gestureRecognizer.view)
let isLeftToRight = UIApplication.shared.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirection.leftToRight
let multiplier: CGFloat = isLeftToRight ? 1 : -1
if (translation.x * multiplier) <= 0 {
return false
}
return true
}
}
extension UIViewController {
fileprivate static func vcFullScreenInit() {
let appear_originalMethod = class_getInstanceMethod(self, #selector(viewWillAppear(_:)))
let appear_swizzledMethod = class_getInstanceMethod(self, #selector(_viewWillAppear))
method_exchangeImplementations(appear_originalMethod!, appear_swizzledMethod!)
let disappear_originalMethod = class_getInstanceMethod(self, #selector(viewWillDisappear(_:)))
let disappear_swizzledMethod = class_getInstanceMethod(self, #selector(_viewWillDisappear))
method_exchangeImplementations(disappear_originalMethod!, disappear_swizzledMethod!)
}
private struct Key {
static var interactivePopDisabled: Void?
static var maxAllowedInitialDistance: Void?
static var prefersNavigationBarHidden: Void?
static var willAppearInjectHandler: Void?
}
fileprivate var interactivePopDisabled: Bool {
get { return (objc_getAssociatedObject(self, &Key.interactivePopDisabled) as? Bool) ?? false }
set { objc_setAssociatedObject(self, &Key.interactivePopDisabled, newValue, .OBJC_ASSOCIATION_ASSIGN) }
}
fileprivate var interactivePopMaxAllowedInitialDistanceToLeftEdge: CGFloat {
get { return (objc_getAssociatedObject(self, &Key.maxAllowedInitialDistance) as? CGFloat) ?? 0.00 }
set { objc_setAssociatedObject(self, &Key.maxAllowedInitialDistance, max(0, newValue), .OBJC_ASSOCIATION_COPY) }
}
fileprivate var prefersNavigationBarHidden: Bool {
get {
guard let bools = objc_getAssociatedObject(self, &Key.prefersNavigationBarHidden) as? Bool else { return false }
return bools
}
set {
objc_setAssociatedObject(self, &Key.prefersNavigationBarHidden, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
fileprivate var willAppearInjectHandler: ViewControllerWillAppearInjectHandler? {
get { return objc_getAssociatedObject(self, &Key.willAppearInjectHandler) as? ViewControllerWillAppearInjectHandler }
set { objc_setAssociatedObject(self, &Key.willAppearInjectHandler, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
@objc fileprivate func _viewWillAppear(_ animated: Bool) {
self._viewWillAppear(animated)
self.willAppearInjectHandler?(self, animated)
}
@objc fileprivate func _viewWillDisappear(animated: Bool) {
self._viewWillDisappear(animated: animated)
let vc = self.navigationController?.viewControllers.last
if vc != nil, vc!.prefersNavigationBarHidden, !self.prefersNavigationBarHidden {
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
}
}
private typealias ViewControllerWillAppearInjectHandler = (_ viewController: UIViewController, _ animated: Bool) -> Void
extension UINavigationController {
fileprivate static func navFullScreenInit() {
let originalSelector = #selector(pushViewController(_:animated:))
let swizzledSelector = #selector(_pushViewController)
guard let originalMethod = class_getInstanceMethod(self, originalSelector) else { return }
guard let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else { return }
let success = class_addMethod(self.classForCoder(), originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if success {
class_replaceMethod(self.classForCoder(), swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
private struct Key {
static var cmd: Void?
static var popGestureRecognizerDelegate: Void?
static var fullscreenPopGestureRecognizer: Void?
static var viewControllerBasedNavigationBarAppearanceEnabled: Void?
}
@objc private func _pushViewController(_ viewController: UIViewController, animated: Bool) {
if self.interactivePopGestureRecognizer?.view?.gestureRecognizers?.contains(self.fullscreenPopGestureRecognizer) == false {
self.interactivePopGestureRecognizer?.view?.addGestureRecognizer(self.fullscreenPopGestureRecognizer)
guard let internalTargets = self.interactivePopGestureRecognizer?.value(forKey: "targets") as? [NSObject] else { return }
guard let internalTarget = internalTargets.first!.value(forKey: "target") else { return } // internalTargets?.first?.value(forKey: "target") else { return }
let internalAction = NSSelectorFromString("handleNavigationTransition:")
self.fullscreenPopGestureRecognizer.delegate = self.popGestureRecognizerDelegate
self.fullscreenPopGestureRecognizer.addTarget(internalTarget, action: internalAction)
self.interactivePopGestureRecognizer?.isEnabled = false
}
self.setupViewControllerBasedNavigationBarAppearanceIfNeeded(viewController)
if !self.viewControllers.contains(viewController) {
self._pushViewController(viewController, animated: animated)
}
}
private func setupViewControllerBasedNavigationBarAppearanceIfNeeded(_ appearingViewController: UIViewController) -> Void {
guard self.viewControllerBasedNavigationBarAppearanceEnabled else {
return
}
let Handler: ViewControllerWillAppearInjectHandler = { [weak self] (vc, animated) in
self.unwrapped({ $0.setNavigationBarHidden(vc.prefersNavigationBarHidden, animated: animated) })
}
appearingViewController.willAppearInjectHandler = Handler
if let disappearingViewController = self.viewControllers.last, disappearingViewController.willAppearInjectHandler.isNone {
disappearingViewController.willAppearInjectHandler = Handler
}
}
private var fullscreenPopGestureRecognizer: UIPanGestureRecognizer {
guard let pan = objc_getAssociatedObject(self, &Key.fullscreenPopGestureRecognizer) as? UIPanGestureRecognizer else {
let gesture = UIPanGestureRecognizer()
gesture.maximumNumberOfTouches = 1
objc_setAssociatedObject(self, &Key.fullscreenPopGestureRecognizer, gesture, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return gesture
}
return pan
}
private var popGestureRecognizerDelegate: _FullScreenPopGestureDelegate {
guard let delegate = objc_getAssociatedObject(self, &Key.popGestureRecognizerDelegate) as? _FullScreenPopGestureDelegate else {
let delegate = _FullScreenPopGestureDelegate()
delegate.navigationController = self
objc_setAssociatedObject(self, &Key.popGestureRecognizerDelegate, delegate, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return delegate
}
return delegate
}
private var viewControllerBasedNavigationBarAppearanceEnabled: Bool {
get {
guard let enabel = objc_getAssociatedObject(self, &Key.viewControllerBasedNavigationBarAppearanceEnabled) as? Bool else {
self.viewControllerBasedNavigationBarAppearanceEnabled = true
return true
}
return enabel
}
set {
objc_setAssociatedObject(self, &Key.viewControllerBasedNavigationBarAppearanceEnabled, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
}
|
2f67347eb7ca98ecbf520241e9729e87
| 40.75945 | 168 | 0.689269 | false | false | false | false |
dreamsxin/swift
|
refs/heads/master
|
test/IRGen/objc_structs.swift
|
apache-2.0
|
3
|
// RUN: rm -rf %t && mkdir %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
import gizmo
// CHECK: [[NSRECT:%VSC6NSRect]] = type <{ [[NSPOINT:%VSC7NSPoint]], [[NSSIZE:%VSC6NSSize]] }>
// CHECK: [[NSPOINT]] = type <{ [[DOUBLE:%Sd]], [[DOUBLE]] }>
// CHECK: [[DOUBLE]] = type <{ double }>
// CHECK: [[NSSIZE]] = type <{ [[DOUBLE]], [[DOUBLE]] }>
// CHECK: [[GIZMO:%CSo5Gizmo]] = type opaque
// CHECK: [[NSSTRING:%CSo8NSString]] = type opaque
// CHECK: [[NSVIEW:%CSo6NSView]] = type opaque
// CHECK: define hidden void @_TF12objc_structs8getFrame{{.*}}([[NSRECT]]* noalias nocapture sret, [[GIZMO]]*) {{.*}} {
func getFrame(_ g: Gizmo) -> NSRect {
// CHECK: load i8*, i8** @"\01L_selector(frame)"
// CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}})
return g.frame()
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs8setFrame{{.*}}(%CSo5Gizmo*, %VSC6NSRect* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func setFrame(_ g: Gizmo, frame: NSRect) {
// CHECK: load i8*, i8** @"\01L_selector(setFrame:)"
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}})
g.setFrame(frame)
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs8makeRect{{.*}}([[NSRECT]]* noalias nocapture sret, double, double, double, double)
func makeRect(_ a: Double, b: Double, c: Double, d: Double) -> NSRect {
// CHECK: call void @NSMakeRect(%struct.NSRect* noalias nocapture sret {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}})
return NSMakeRect(a,b,c,d)
}
// CHECK: }
// CHECK: define hidden [[stringLayout:[^@]*]] @_TF12objc_structs14stringFromRect{{.*}}(%VSC6NSRect* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func stringFromRect(_ r: NSRect) -> String {
// CHECK: call [[OPAQUE0:.*]]* @NSStringFromRect(%struct.NSRect* byval align 8 {{.*}})
return NSStringFromRect(r)
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs9insetRect{{.*}}([[NSRECT]]* noalias nocapture sret, %VSC6NSRect* noalias nocapture dereferenceable({{.*}}), double, double)
func insetRect(_ r: NSRect, x: Double, y: Double) -> NSRect {
// CHECK: call void @NSInsetRect(%struct.NSRect* noalias nocapture sret {{.*}}, %struct.NSRect* byval align 8 {{.*}}, double {{.*}}, double {{.*}})
return NSInsetRect(r, x, y)
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs19convertRectFromBase{{.*}}([[NSRECT]]* noalias nocapture sret, [[NSVIEW]]*, [[NSRECT]]* noalias nocapture dereferenceable({{.*}}))
func convertRectFromBase(_ v: NSView, r: NSRect) -> NSRect {
// CHECK: load i8*, i8** @"\01L_selector(convertRectFromBase:)", align 8
// CHECK: call void bitcast (void ()* @objc_msgSend_stret to void ([[NSRECT]]*, [[OPAQUE0:.*]]*, i8*, [[NSRECT]]*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[OPAQUE0:.*]]* {{.*}}, i8* {{.*}}, [[NSRECT]]* byval align 8 {{.*}})
return v.convertRect(fromBase: r)
}
// CHECK: }
// CHECK: define hidden void @_TF12objc_structs20useStructOfNSStringsFVSC17StructOfNSStringsS0_(%VSC17StructOfNSStrings* noalias nocapture sret, %VSC17StructOfNSStrings* noalias nocapture dereferenceable({{.*}}))
// CHECK: call void @useStructOfNSStringsInObjC(%struct.StructOfNSStrings* noalias nocapture sret {{%.*}}, %struct.StructOfNSStrings* byval align 8 {{%.*}})
func useStructOfNSStrings(_ s: StructOfNSStrings) -> StructOfNSStrings {
return useStructOfNSStringsInObjC(s)
}
|
0258af723b824bc5c24c78f57dd60580
| 54.235294 | 231 | 0.638179 | false | false | false | false |
SaberVicky/LoveStory
|
refs/heads/master
|
LoveStory/Feature/Publish/LSRecordSoundViewController.swift
|
mit
|
1
|
//
// LSRecordSoundViewController.swift
// LoveStory
//
// Created by songlong on 2017/1/12.
// Copyright © 2017年 com.Saber. All rights reserved.
//
import UIKit
import AVFoundation
import Qiniu
import SVProgressHUD
class LSRecordSoundViewController: UIViewController {
let player = AVPlayer(url: URL(string: "http://ojae83ylm.bkt.clouddn.com/28466c0ed87411e6b1045254005b67a6.caf")!)
var audioRecorder:AVAudioRecorder!
var audioPlayer:AVAudioPlayer!
var theSoundUrl: String?
var publishSoundUrl: String?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupAV()
setupUI()
}
func setupAV() {
let recordSettings = [AVSampleRateKey : NSNumber(value: Float(44100.0)),//声音采样率
AVFormatIDKey : NSNumber(value: Int32(kAudioFormatMPEG4AAC)),//编码格式
AVNumberOfChannelsKey : NSNumber(value: 1),//采集音轨
AVEncoderAudioQualityKey : NSNumber(value: Int32(AVAudioQuality.max.rawValue))]//音频质量
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioRecorder = AVAudioRecorder(url: self.directoryURL()!, settings: recordSettings)
} catch let error as NSError {
LSPrint(error.localizedDescription)
}
}
func setupUI() {
let startBtn = UIButton()
startBtn.setTitle("开始录音", for: .normal)
startBtn.setTitleColor(.black, for: .normal)
startBtn.addTarget(self, action: #selector(LSRecordSoundViewController.startRecord), for: .touchUpInside)
let stopBtn = UIButton()
stopBtn.setTitle("停止录音", for: .normal)
stopBtn.setTitleColor(.black, for: .normal)
stopBtn.addTarget(self, action: #selector(LSRecordSoundViewController.stopRecord), for: .touchUpInside)
let playBtn = UIButton()
playBtn.setTitle("开始播放", for: .normal)
playBtn.setTitleColor(.black, for: .normal)
playBtn.addTarget(self, action: #selector(LSRecordSoundViewController.playRecord), for: .touchUpInside)
let pauseBtn = UIButton()
pauseBtn.setTitle("暂停播放", for: .normal)
pauseBtn.setTitleColor(.black, for: .normal)
pauseBtn.addTarget(self, action: #selector(LSRecordSoundViewController.pauseRecord), for: .touchUpInside)
view.addSubview(startBtn)
view.addSubview(stopBtn)
view.addSubview(playBtn)
view.addSubview(pauseBtn)
startBtn.snp.makeConstraints { (make) in
make.top.equalTo(20)
make.centerX.equalTo(self.view)
}
stopBtn.snp.makeConstraints { (make) in
make.top.equalTo(startBtn.snp.bottom).offset(20)
make.centerX.equalTo(self.view)
}
playBtn.snp.makeConstraints { (make) in
make.top.equalTo(stopBtn.snp.bottom).offset(20)
make.centerX.equalTo(self.view)
}
pauseBtn.snp.makeConstraints { (make) in
make.top.equalTo(playBtn.snp.bottom).offset(20)
make.centerX.equalTo(self.view)
}
}
func startRecord() {
if !audioRecorder.isRecording {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(true)
audioRecorder.record()
LSPrint("record!")
} catch let error as NSError {
LSPrint(error.localizedDescription)
}
}
}
func stopRecord() {
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(false)
LSPrint("stop!")
} catch let error as NSError {
LSPrint(error.localizedDescription)
}
uploadSound()
}
func playRecord() {
player.play()
if !audioRecorder.isRecording {
do {
try audioPlayer = AVAudioPlayer(contentsOf: audioRecorder.url)
audioPlayer.play()
LSPrint("play!!")
} catch let error as NSError {
LSPrint(error.localizedDescription)
}
}
}
func pauseRecord() {
if !audioRecorder.isRecording {
do {
try audioPlayer = AVAudioPlayer(contentsOf: audioRecorder.url)
audioPlayer.pause()
LSPrint("pause!!")
} catch let error as NSError {
LSPrint(error.localizedDescription)
}
}
}
func directoryURL() -> URL? {
//根据时间设置存储文件名
// let currentDateTime = NSDate()
// let formatter = DateFormatter()
// formatter.dateFormat = "ddMMyyyyHHmmss"
// let recordingName = formatter.string(from: currentDateTime as Date)+".caf"
// print(recordingName)
let recordingName = "theSound.caf"
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = urls[0] as NSURL
let soundURL = documentDirectory.appendingPathComponent(recordingName)//将音频文件名称追加在可用路径上形成音频文件的保存路径
theSoundUrl = soundURL?.absoluteString
let index = theSoundUrl?.index((theSoundUrl?.startIndex)!, offsetBy: 7)
theSoundUrl = theSoundUrl?.substring(from: index!)
LSPrint(theSoundUrl)
return soundURL
}
func uploadSound() {
LSNetworking.sharedInstance.request(method: .GET, URLString: API_GET_QINIU_PARAMS, parameters: ["type" : "sound"], success: { (task, responseObject) in
let config = QNConfiguration.build({ (builder) in
builder?.setZone(QNZone.zone1())
})
let dic = responseObject as! NSDictionary
let token : String = dic["token"] as! String
let key : String = dic["key"] as! String
self.publishSoundUrl = dic["img_url"] as? String
let option = QNUploadOption(progressHandler: { (key, percent) in
LSPrint("percent = \(percent)")
})
let upManager = QNUploadManager(configuration: config)
upManager?.putFile(self.theSoundUrl, key: key, token: token, complete: { (info, key, resp) in
if (info?.isOK)! {
SVProgressHUD.showSuccess(withStatus: "上传成功")
self.publish()
} else {
SVProgressHUD.showError(withStatus: "上传失败")
}
LSPrint(info)
LSPrint(resp)
}, option: option)
}, failure: { (task, error) in
print(error)
})
}
func publish() {
}
}
|
78ad15d5ce5ccc1cb83407bd81a8a98c
| 32.942584 | 159 | 0.576825 | false | false | false | false |
BeezleLabs/HackerTracker-iOS
|
refs/heads/main
|
hackertracker/FSConferenceDataController.swift
|
gpl-2.0
|
1
|
//
// FSConferenceDataController.swift
// hackertracker
//
// Created by Christopher Mays on 6/19/19.
// Copyright © 2019 Beezle Labs. All rights reserved.
//
import Firebase
import FirebaseStorage
import Foundation
enum HTError: Error {
case speakerNil
case confItemNil
}
extension HTError: LocalizedError {
var errorDescription: String? {
switch self {
case .speakerNil:
return "Speaker items were nil"
case .confItemNil:
return "Conference items were nil"
}
}
}
class UpdateToken {
let collectionValue: Any
init(_ collection: Any) {
collectionValue = collection
}
}
class FSConferenceDataController {
static let shared = FSConferenceDataController()
var db: Firestore
var storage: Storage
let conferenceQuery: Query?
init() {
let settings = FirestoreSettings()
settings.isPersistenceEnabled = true
db = Firestore.firestore()
db.settings = settings
storage = Storage.storage()
conferenceQuery = db.collection("conferences")
}
func requestConferences(updateHandler: @escaping (Result<[ConferenceModel], Error>) -> Void) -> UpdateToken {
let query = db.collection("conferences").order(by: "start_date", descending: true)
let conferences = Collection<ConferenceModel>(query: query)
conferences.listen { _ in
updateHandler(Result<[ConferenceModel], Error>.success(conferences.items))
}
return UpdateToken(conferences)
}
func requestConferenceByCode(forCode conCode: String, updateHandler: @escaping (Result<ConferenceModel, Error>) -> Void) -> UpdateToken {
let query = db.collection("conferences").whereField("code", isEqualTo: conCode)
let conferences = Collection<ConferenceModel>(query: query)
conferences.listen { _ in
if let firstConferenceItem = conferences.items.first {
updateHandler(Result<ConferenceModel, Error>.success(firstConferenceItem))
} else {
updateHandler(Result<ConferenceModel, Error>.failure(HTError.confItemNil))
}
}
return UpdateToken(conferences)
}
func requestEvents(forConference conference: ConferenceModel, updateHandler: @escaping (Result<[UserEventModel], Error>) -> Void) -> UpdateToken {
let query = document(forConference: conference).collection("events")
return requestEvents(forConference: conference, query: query, updateHandler: updateHandler)
}
func requestEvents(forConference conference: ConferenceModel, eventId: Int, updateHandler: @escaping (Result<UserEventModel, Error>) -> Void) -> UpdateToken {
var event: HTEventModel?
var bookmark: Bookmark?
let query = document(forConference: conference).collection("events").whereField("id", isEqualTo: eventId)
let events = Collection<HTEventModel>(query: query)
events.listen { _ in
event = events.items.first
if let event = event {
updateHandler(Result<UserEventModel, Error>.success(UserEventModel(event: event, bookmark: bookmark ?? Bookmark(id: String(event.id), value: false))))
}
}
guard AnonymousSession.shared.user != nil else {
return UpdateToken(events)
}
let bookmarksToken = AnonymousSession.shared.requestFavorites { result in
switch result {
case let .success(updatedBookmarks):
bookmark = updatedBookmarks.first(where: { bookmark -> Bool in
bookmark.id == String(eventId)
})
if let event = event, let bookmark = bookmark {
updateHandler(Result<UserEventModel, Error>.success(UserEventModel(event: event, bookmark: bookmark)))
}
case .failure:
NSLog("TODO Error")
}
}
return UpdateToken([events, bookmarksToken as Any])
}
func requestSpeaker(forConference conference: ConferenceModel, speakerId: Int, updateHandler: @escaping (Result<HTSpeaker, Error>) -> Void) -> UpdateToken {
let query = document(forConference: conference).collection("speakers").whereField("id", isEqualTo: speakerId)
let speakers = Collection<HTSpeaker>(query: query)
speakers.listen { _ in
if let speaker = speakers.items.first {
updateHandler(Result<HTSpeaker, Error>.success(speaker))
} else {
updateHandler(Result<HTSpeaker, Error>.failure(HTError.speakerNil))
}
}
return UpdateToken(speakers)
}
func requestSpeakers(forConference conference: ConferenceModel, updateHandler: @escaping (Result<[HTSpeaker], Error>) -> Void) -> UpdateToken {
let query = document(forConference: conference).collection("speakers").order(by: "name")
let speakers = Collection<HTSpeaker>(query: query)
speakers.listen { _ in
updateHandler(Result<[HTSpeaker], Error>.success(speakers.items))
}
return UpdateToken(speakers)
}
func requestEvents(forConference conference: ConferenceModel,
limit: Int? = nil,
descending: Bool = false,
updateHandler: @escaping (Result<[UserEventModel], Error>) -> Void) -> UpdateToken {
var query: Query?
query = document(forConference: conference).collection("events").order(by: "begin_timestamp", descending: descending).limit(to: limit ?? Int.max)
return requestEvents(forConference: conference, query: query, updateHandler: updateHandler)
}
func requestEvents(forConference conference: ConferenceModel,
startDate: Date,
limit: Int? = nil,
descending: Bool = false,
updateHandler: @escaping (Result<[UserEventModel], Error>) -> Void) -> UpdateToken {
var query: Query?
query = document(forConference: conference).collection("events").whereField("begin_timestamp", isGreaterThan: startDate).order(by: "begin_timestamp", descending: descending).limit(to: limit ?? Int.max)
return requestEvents(forConference: conference, query: query, updateHandler: updateHandler)
}
func requestEvents(forConference conference: ConferenceModel,
inDate: Date,
limit: Int? = nil,
descending: Bool = false,
updateHandler: @escaping (Result<[UserEventModel], Error>) -> Void) -> UpdateToken {
var query: Query?
let calendar = Calendar.current
let start = inDate
let end = calendar.date(byAdding: .day, value: 1, to: start) ?? Date()
query = document(forConference: conference).collection("events").whereField("begin_timestamp", isGreaterThanOrEqualTo: start).whereField("begin_timestamp", isLessThan: end).order(by: "begin_timestamp", descending: descending).limit(to: limit ?? Int.max)
return requestEvents(forConference: conference, query: query, updateHandler: updateHandler)
}
func requestEvents(forConference conference: ConferenceModel,
endDate: Date,
limit: Int? = nil,
descending: Bool = false,
updateHandler: @escaping (Result<[UserEventModel], Error>) -> Void) -> UpdateToken {
let query = document(forConference: conference).collection("events").whereField("end_timestamp", isGreaterThan: endDate).order(by: "end_timestamp", descending: descending).limit(to: limit ?? Int.max)
return requestEvents(forConference: conference, query: query, updateHandler: updateHandler)
}
private func requestEvents(forConference _: ConferenceModel,
query: Query?,
updateHandler: @escaping (Result<[UserEventModel], Error>) -> Void) -> UpdateToken {
var events: [HTEventModel]?
var bookmarks: [Bookmark]?
let eventsToken = Collection<HTEventModel>(query: query!)
eventsToken.listen { _ in
events = eventsToken.items
if let events = events, let bookmarks = bookmarks {
updateHandler(Result<[UserEventModel], Error>.success(self.createUserEvents(events: events, bookmarks: bookmarks)))
}
}
guard AnonymousSession.shared.user != nil else {
return UpdateToken(eventsToken)
}
let bookmarksToken = AnonymousSession.shared.requestFavorites { result in
switch result {
case let .success(updatedBookmarks):
bookmarks = updatedBookmarks
if let events = events, let bookmarks = bookmarks {
updateHandler(Result<[UserEventModel], Error>.success(self.createUserEvents(events: events, bookmarks: bookmarks)))
}
case .failure:
NSLog("TODO Error")
}
}
return UpdateToken([eventsToken, bookmarksToken as Any])
}
func createUserEvents(events: [HTEventModel], bookmarks: [Bookmark]) -> [UserEventModel] {
var bookmarkIndex = [String: Bookmark]()
for bookmark in bookmarks {
bookmarkIndex[bookmark.id] = bookmark
}
return events.map { eventModel -> UserEventModel in
UserEventModel(event: eventModel, bookmark: bookmarkIndex[String(eventModel.id)] ?? Bookmark(id: String(eventModel.id), value: false))
}
}
func requestLocations(forConference conference: ConferenceModel, updateHandler: @escaping (Result<[HTLocationModel], Error>) -> Void) -> UpdateToken {
let query = document(forConference: conference).collection("locations")
let events = Collection<HTLocationModel>(query: query)
events.listen { _ in
updateHandler(Result<[HTLocationModel], Error>.success(events.items))
}
return UpdateToken(events)
}
func requestFavorites(forConference conference: ConferenceModel,
session: AnonymousSession,
updateHandler: @escaping (Result<[Bookmark], Error>) -> Void) -> UpdateToken? {
guard let user = session.user else {
return nil
}
let query = document(forConference: conference).collection("users").document(user.uid).collection("bookmarks")
let bookmarks = Collection<Bookmark>(query: query)
bookmarks.listen { _ in
updateHandler(Result<[Bookmark], Error>.success(bookmarks.items))
}
return UpdateToken(bookmarks)
}
func setFavorite(forConference conference: ConferenceModel,
eventModel: HTEventModel,
isFavorite: Bool,
session: AnonymousSession,
updateHandler: @escaping (Error?) -> Void) {
guard let user = session.user else {
return
}
document(forConference: conference).collection("users").document(user.uid).collection("bookmarks").document(String(eventModel.id)).setData([
"id": String(eventModel.id),
"value": isFavorite,
]) { err in
if let err = err {
updateHandler(err)
} else {
updateHandler(nil)
}
}
}
func requestEventTypes(forConference conference: ConferenceModel, updateHandler: @escaping (Result<[HTEventType], Error>) -> Void) -> UpdateToken {
let query = document(forConference: conference).collection("types").order(by: "name", descending: false)
let types = Collection<HTEventType>(query: query)
types.listen { _ in
updateHandler(Result<[HTEventType], Error>.success(types.items))
}
return UpdateToken(types)
}
func requestTags(forConference conference: ConferenceModel, updateHandler: @escaping (Result<[HTTagType], Error>) -> Void) -> UpdateToken {
let query = document(forConference: conference).collection("tagtypes").order(by: "sort_order", descending: false)
let tagTypes = Collection<HTTagType>(query: query)
tagTypes.listen { _ in
updateHandler(Result<[HTTagType], Error>.success(tagTypes.items))
}
return UpdateToken(tagTypes)
}
func requestArticles(forConference conference: ConferenceModel,
limit: Int? = nil,
descending: Bool = false,
updateHandler: @escaping (Result<[HTArticleModel], Error>) -> Void) -> UpdateToken {
var query: Query?
query = document(forConference: conference).collection("articles").order(by: "updated_at", descending: descending).limit(to: limit ?? Int.max)
let articles = Collection<HTArticleModel>(query: query!)
articles.listen { _ in
updateHandler(Result<[HTArticleModel], Error>.success(articles.items))
}
return UpdateToken(articles)
}
func requestFAQs(forConference conference: ConferenceModel,
limit: Int? = nil,
descending: Bool = false,
updateHandler: @escaping (Result<[HTFAQModel], Error>) -> Void) -> UpdateToken {
var query: Query?
query = document(forConference: conference).collection("faqs").order(by: "id", descending: descending).limit(to: limit ?? Int.max)
let faqs = Collection<HTFAQModel>(query: query!)
faqs.listen { _ in
updateHandler(Result<[HTFAQModel], Error>.success(faqs.items))
}
return UpdateToken(faqs)
}
func requestVendors(forConference conference: ConferenceModel,
limit: Int? = nil,
descending: Bool = false,
updateHandler: @escaping (Result<[HTVendorModel], Error>) -> Void) -> UpdateToken {
var query: Query?
query = document(forConference: conference).collection("vendors").order(by: "name", descending: descending).limit(to: limit ?? Int.max)
let vendors = Collection<HTVendorModel>(query: query!)
vendors.listen { _ in
updateHandler(Result<[HTVendorModel], Error>.success(vendors.items))
}
return UpdateToken(vendors)
}
private func document(forConference conference: ConferenceModel) -> DocumentReference {
return db.collection("conferences").document(conference.code)
}
}
|
b9eba35ab8ab20592bd253b852caaa23
| 42.772455 | 261 | 0.62606 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/WalletPayload/Sources/WalletPayloadKit/Services/Creator/WalletCreator.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import Foundation
import MetadataKit
import ObservabilityKit
import ToolKit
import WalletCore
public enum WalletCreateError: LocalizedError, Equatable {
case genericFailure
case expectedEncodedPayload
case encryptionFailure
case uuidFailure
case verificationFailure(EncryptAndVerifyError)
case mnemonicFailure(MnemonicProviderError)
case encodingError(WalletEncodingError)
case networkError(NetworkError)
case legacyError(LegacyWalletCreationError)
case usedAccountsFinderError(UsedAccountsFinderError)
}
struct WalletCreationContext: Equatable {
let mnemonic: String
let guid: String
let sharedKey: String
let accountName: String
let totalAccounts: Int
}
typealias UUIDProvider = () -> AnyPublisher<(guid: String, sharedKey: String), WalletCreateError>
typealias GenerateWalletProvider = (WalletCreationContext) -> Result<NativeWallet, WalletCreateError>
typealias GenerateWrapperProvider = (NativeWallet, String, WalletVersion) -> Wrapper
typealias ProcessWalletCreation = (
_ context: WalletCreationContext,
_ email: String,
_ password: String,
_ language: String,
_ recaptchaToken: String?,
_ siteKey: String
) -> AnyPublisher<WalletCreation, WalletCreateError>
public protocol WalletCreatorAPI {
/// Creates a new wallet using the given email and password.
/// - Returns: `AnyPublisher<WalletCreation, WalletCreateError>`
func createWallet(
email: String,
password: String,
accountName: String,
recaptchaToken: String?,
siteKey: String,
language: String
) -> AnyPublisher<WalletCreation, WalletCreateError>
/// Imports and creates a new wallet from the mnemonic and using the given email and password.
/// - Returns: `AnyPublisher<WalletCreation, WalletCreateError>`
func importWallet(
mnemonic: String,
email: String,
password: String,
accountName: String,
language: String
) -> AnyPublisher<WalletCreation, WalletCreateError>
}
final class WalletCreator: WalletCreatorAPI {
private let entropyService: RNGServiceAPI
private let walletEncoder: WalletEncodingAPI
private let encryptor: PayloadCryptoAPI
private let createWalletRepository: CreateWalletRepositoryAPI
private let usedAccountsFinder: UsedAccountsFinderAPI
private let operationQueue: DispatchQueue
private let tracer: LogMessageServiceAPI
private let uuidProvider: UUIDProvider
private let generateWallet: GenerateWalletProvider
private let generateWrapper: GenerateWrapperProvider
private let logger: NativeWalletLoggerAPI
private let checksumProvider: (Data) -> String
private let processWalletCreation: ProcessWalletCreation
init(
entropyService: RNGServiceAPI,
walletEncoder: WalletEncodingAPI,
encryptor: PayloadCryptoAPI,
createWalletRepository: CreateWalletRepositoryAPI,
usedAccountsFinder: UsedAccountsFinderAPI,
operationQueue: DispatchQueue,
logger: NativeWalletLoggerAPI,
tracer: LogMessageServiceAPI,
uuidProvider: @escaping UUIDProvider,
generateWallet: @escaping GenerateWalletProvider,
generateWrapper: @escaping GenerateWrapperProvider,
checksumProvider: @escaping (Data) -> String
) {
self.uuidProvider = uuidProvider
self.walletEncoder = walletEncoder
self.encryptor = encryptor
self.createWalletRepository = createWalletRepository
self.usedAccountsFinder = usedAccountsFinder
self.operationQueue = operationQueue
self.logger = logger
self.tracer = tracer
self.entropyService = entropyService
self.generateWallet = generateWallet
self.generateWrapper = generateWrapper
self.checksumProvider = checksumProvider
processWalletCreation = provideProcessCreationOfWallet(
walletEncoder: walletEncoder,
encryptor: encryptor,
createWalletRepository: createWalletRepository,
logger: logger,
generateWallet: generateWallet,
generateWrapper: generateWrapper,
checksumProvider: checksumProvider
)
}
func createWallet(
email: String,
password: String,
accountName: String,
recaptchaToken: String?,
siteKey: String,
language: String = "en"
) -> AnyPublisher<WalletCreation, WalletCreateError> {
provideMnemonic(
strength: .normal,
queue: operationQueue,
entropyProvider: entropyService.generateEntropy(count:)
)
.mapError(WalletCreateError.mnemonicFailure)
.receive(on: operationQueue)
.flatMap { [uuidProvider] mnemonic -> AnyPublisher<WalletCreationContext, WalletCreateError> in
uuidProvider()
.map { guid, sharedKey in
WalletCreationContext(
mnemonic: mnemonic,
guid: guid,
sharedKey: sharedKey,
accountName: accountName,
totalAccounts: 1
)
}
.eraseToAnyPublisher()
}
.flatMap { [processWalletCreation] context -> AnyPublisher<WalletCreation, WalletCreateError> in
processWalletCreation(
context,
email,
password,
language,
recaptchaToken,
siteKey
)
}
.logErrorOrCrash(tracer: tracer)
.eraseToAnyPublisher()
}
func importWallet(
mnemonic: String,
email: String,
password: String,
accountName: String,
language: String
) -> AnyPublisher<WalletCreation, WalletCreateError> {
hdWallet(from: mnemonic)
.subscribe(on: operationQueue)
.receive(on: operationQueue)
.map(\.seed.toHexString)
.map { masterNode -> (MetadataKit.PrivateKey, MetadataKit.PrivateKey) in
let legacy = deriveMasterAccountKey(masterNode: masterNode, type: .legacy)
let bech32 = deriveMasterAccountKey(masterNode: masterNode, type: .segwit)
return (legacy, bech32)
}
.flatMap { [usedAccountsFinder] legacy, bech32 -> AnyPublisher<Int, WalletCreateError> in
usedAccountsFinder
.findUsedAccounts(
batch: 10,
xpubRetriever: generateXpub(legacyKey: legacy, bech32Key: bech32)
)
.map { totalAccounts in
// we still need to create one account in case account discovery returned zero.
max(1, totalAccounts)
}
.mapError(WalletCreateError.usedAccountsFinderError)
.eraseToAnyPublisher()
}
.flatMap { [uuidProvider] totalAccounts -> AnyPublisher<WalletCreationContext, WalletCreateError> in
uuidProvider()
.map { guid, sharedKey in
WalletCreationContext(
mnemonic: mnemonic,
guid: guid,
sharedKey: sharedKey,
accountName: accountName,
totalAccounts: totalAccounts
)
}
.eraseToAnyPublisher()
}
.flatMap { [processWalletCreation] context -> AnyPublisher<WalletCreation, WalletCreateError> in
processWalletCreation(
context,
email,
password,
language,
nil,
""
)
}
.logErrorOrCrash(tracer: tracer)
.eraseToAnyPublisher()
}
func hdWallet(
from mnemonic: String
) -> AnyPublisher<WalletCore.HDWallet, WalletCreateError> {
Deferred {
Future<WalletCore.HDWallet, WalletCreateError> { promise in
switch getHDWallet(from: mnemonic) {
case .success(let wallet):
promise(.success(wallet))
case .failure(let error):
promise(.failure(error))
}
}
}
.eraseToAnyPublisher()
}
}
/// Final process for creating a wallet
/// 1. Create the wallet and wrapper
/// 2. Encrypt and verify the wrapper
/// 3. Encode the wrapper payload
/// 4. Create the wallet on the backend
/// 5. Return a `WalletCreation` or failure if any
// swiftlint:disable function_parameter_count
private func provideProcessCreationOfWallet(
walletEncoder: WalletEncodingAPI,
encryptor: PayloadCryptoAPI,
createWalletRepository: CreateWalletRepositoryAPI,
logger: NativeWalletLoggerAPI,
generateWallet: @escaping GenerateWalletProvider,
generateWrapper: @escaping GenerateWrapperProvider,
checksumProvider: @escaping (Data) -> String
) -> ProcessWalletCreation {
{ context, email, password, language, recaptchaToken, siteKey -> AnyPublisher<WalletCreation, WalletCreateError> in
generateWallet(context)
.map { wallet -> Wrapper in
generateWrapper(wallet, language, WalletVersion.v4)
}
.publisher
.eraseToAnyPublisher()
.flatMap { [walletEncoder, encryptor, logger] wrapper
-> AnyPublisher<EncodedWalletPayload, WalletCreateError> in
encryptAndVerifyWrapper(
walletEncoder: walletEncoder,
encryptor: encryptor,
logger: logger,
password: password,
wrapper: wrapper
)
.mapError(WalletCreateError.verificationFailure)
.eraseToAnyPublisher()
}
.flatMap { [walletEncoder, checksumProvider] payload
-> AnyPublisher<WalletCreationPayload, WalletCreateError> in
walletEncoder.encode(payload: payload, applyChecksum: checksumProvider)
.mapError(WalletCreateError.encodingError)
.eraseToAnyPublisher()
}
.flatMap { [createWalletRepository] payload -> AnyPublisher<WalletCreationPayload, WalletCreateError> in
createWalletRepository.createWallet(
email: email,
payload: payload,
recaptchaToken: recaptchaToken,
siteKey: siteKey
)
.map { _ in payload }
.mapError(WalletCreateError.networkError)
.eraseToAnyPublisher()
}
.map { payload in
WalletCreation(
guid: payload.guid,
sharedKey: payload.sharedKey,
password: password
)
}
.eraseToAnyPublisher()
}
}
/// Provides UUIDs to be used as guid and sharedKey in wallet creation
/// - Returns: `AnyPublisher<(guid: String, sharedKey: String), WalletCreateError>`
func uuidProvider() -> AnyPublisher<(guid: String, sharedKey: String), WalletCreateError> {
let guid = UUID().uuidString.lowercased()
let sharedKey = UUID().uuidString.lowercased()
guard guid.count == 36 || sharedKey.count == 36 else {
return .failure(.uuidFailure)
}
return .just((guid, sharedKey))
}
/// (LegacyKey, Bech32Key) -> (DerivationType, Index) -> String
func generateXpub(
legacyKey: MetadataKit.PrivateKey,
bech32Key: MetadataKit.PrivateKey
) -> XpubRetriever {
{ type, index -> String in
switch type {
case .legacy:
return legacyKey.derive(at: .hardened(UInt32(index))).xpub
case .segwit:
return bech32Key.derive(at: .hardened(UInt32(index))).xpub
}
}
}
|
a69c131b824f5c00684d32af227c7c01
| 36.552147 | 119 | 0.613462 | false | false | false | false |
nathan-hekman/Stupefy
|
refs/heads/master
|
Stupefy/Utils/Utils.swift
|
mit
|
1
|
/**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
import BMSCore
class Utils: NSObject {
/**
Method gets a key from a plist, both specified in parameters
- parameter plist: String
- parameter key: String
- returns: Bool?
*/
class func getBoolValueWithKeyFromPlist(_ plist: String, key: String) -> Bool? {
if let path: String = Bundle.main.path(forResource: plist, ofType: "plist"),
let keyList = NSDictionary(contentsOfFile: path),
let key = keyList.object(forKey: key) as? Bool {
return key
}
return nil
}
/**
Method gets a key from a plist, both specified in parameters
- parameter plist: String
- parameter key: String
- returns: String
*/
class func getStringValueWithKeyFromPlist(_ plist: String, key: String) -> String? {
if let path: String = Bundle.main.path(forResource: plist, ofType: "plist"),
let keyList = NSDictionary(contentsOfFile: path),
let key = keyList.object(forKey: key) as? String {
return key
}
return nil
}
/**
Method returns an instance of the Main.storyboard
- returns: UIStoryboard
*/
class func mainStoryboard() -> UIStoryboard {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
return storyboard
}
/**
Method returns an instance of the storyboard defined by the storyboardName String parameter
- parameter storyboardName: UString
- returns: UIStoryboard
*/
class func storyboardBoardWithName(_ storyboardName: String) -> UIStoryboard {
let storyboard = UIStoryboard(name: storyboardName, bundle: Bundle.main)
return storyboard
}
/**
Method returns an instance of the view controller defined by the vcName paramter from the storyboard defined by the storyboardName parameter
- parameter vcName: String
- parameter storyboardName: String
- returns: UIViewController?
*/
class func vcWithNameFromStoryboardWithName(_ vcName: String, storyboardName: String) -> UIViewController? {
let storyboard = storyboardBoardWithName(storyboardName)
return storyboard.instantiateViewController(withIdentifier: vcName)
}
/**
Method returns an instance of a nib defined by the name String parameter
- parameter name: String
- returns: UINib?
*/
class func nib(_ name: String) -> UINib? {
let nib: UINib? = UINib(nibName: name, bundle: Bundle.main)
return nib
}
/**
Method registers a nib name defined by the nibName String parameter with the collectionView given by the collectionView parameter
- parameter nibName: String
- parameter collectionView: UICollectionView
*/
class func registerNibWith(_ nibName: String, collectionView: UICollectionView) {
let nib = Utils.nib(nibName)
collectionView.register(nib, forCellWithReuseIdentifier: nibName)
}
class func registerNibWith(_ nibName: String, tableView: UITableView) {
let nib = Utils.nib(nibName)
tableView.register(nib, forCellReuseIdentifier: nibName)
}
/**
Method registers a supplementary element of kind nib defined by the nibName String parameter and the kind String parameter with the collectionView parameter
- parameter nibName: String
- parameter kind: String
- parameter collectionView: UICollectionView
*/
class func registerSupplementaryElementOfKindNibWithCollectionView(_ nibName: String, kind: String, collectionView: UICollectionView) {
let nib = Utils.nib(nibName)
collectionView.register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: nibName)
}
/**
Method converts a string to a dictionary
- parameter text: String
- returns: [String : Any]?
*/
class func convertStringToDictionary(_ text: String) -> [String : Any]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String : Any]
return json
} catch {
print(NSLocalizedString("Convert String To Dictionary Error", comment: ""))
}
}
return nil
}
/**
Method converts a response to a dictionary
- parameter response: Response?
- returns: [String : Any]
*/
class func convertResponseToDictionary(_ response: Response?) -> [String : Any]? {
if let resp = response {
if let responseText = resp.responseText {
return convertStringToDictionary(responseText)
} else {
return nil
}
} else {
return nil
}
}
/**
Method takes in a label and a spacing value and kerns the labels text to this value
- parameter label: UILabel
- parameter spacingValue: CGFloat
*/
class func kernLabelString(_ label: UILabel, spacingValue: CGFloat) {
if let text = label.text {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSKernAttributeName, value: spacingValue, range: NSRange(location: 0, length: attributedString.length))
label.attributedText = attributedString
}
}
/**
Method takes in latitude and longitude and formats these coordinates into a fancy format
- parameter latitude: Double
- parameter longitude: Double
- returns: String
*/
class func coordinateString(_ latitude: Double, longitude: Double) -> String {
var latSeconds = Int(latitude * 3600)
let latDegrees = latSeconds / 3600
latSeconds = abs(latSeconds % 3600)
let latMinutes = latSeconds / 60
latSeconds %= 60
var longSeconds = Int(longitude * 3600)
let longDegrees = longSeconds / 3600
longSeconds = abs(longSeconds % 3600)
let longMinutes = longSeconds / 60
longSeconds %= 60
return String(format:"%d° %d' %d\" %@, %d° %d' %d\" %@",
latDegrees,
latMinutes,
latSeconds, {return latDegrees >= 0 ? NSLocalizedString("N", comment: "first letter of the word North") : NSLocalizedString("S", comment: "first letter of the word South")}(),
longDegrees,
longMinutes,
longSeconds, {return longDegrees >= 0 ? NSLocalizedString("E", comment: "first letter of the word East") : NSLocalizedString("W", comment: "first letter of the word West")}() )
}
}
|
11276b7938b0cddf196d147f8c98435f
| 32.552511 | 198 | 0.641399 | false | false | false | false |
armcknight/TrigKit
|
refs/heads/master
|
TrigKit/CartesianCoordinate2D.swift
|
mit
|
1
|
//
// CartesianCoordinate2D.swift
// TrigKit
//
// Created by Andrew McKnight on 3/4/17.
// Copyright © 2017 Andrew McKnight. All rights reserved.
//
import Foundation
public struct CartesianCoordinate2D {
public let x: Double
public let y: Double
public init(x: Double, y: Double) {
self.x = x
self.y = y
}
init(x: CGFloat, y: CGFloat) {
self.x = Double(x)
self.y = Double(y)
}
}
public extension CartesianCoordinate2D {
func distance(to coordinate: CartesianCoordinate2D) -> Double {
return sqrt(pow(x - coordinate.x, 2) + pow(y - coordinate.y, 2))
}
func angle(to b: CartesianCoordinate2D) -> Angle {
let xDist = x - b.x
let yDist = y - b.y
let angle = atan2(yDist, xDist) + .pi
return Angle(radians: angle)
}
}
// MARK: CGPoint conversions
extension CartesianCoordinate2D {
public init(cgPoint: CGPoint, size: CGSize) {
let x = cgPoint.x - size.width / 2
let y = size.height / 2 - cgPoint.y
self = CartesianCoordinate2D(x: x, y: y)
}
public func cgPoint(_ canvasSize: CGSize) -> CGPoint {
let x = CGFloat(self.x) + canvasSize.width / 2
let y = canvasSize.height / 2 - CGFloat(self.y)
return CGPoint(x: x, y: y);
}
}
|
227089603fbc87f1754c027c742b9795
| 21.355932 | 72 | 0.595906 | false | false | false | false |
NicholasTD07/SwiftDailyAPI
|
refs/heads/develop
|
SwiftDailyAPITests/Specs/ReadmeCodeSpecs.swift
|
mit
|
1
|
//
// ReadmeCodeSpecs.swift
// SwiftDailyAPI
//
// Created by Nicholas Tian on 4/06/2015.
// Copyright (c) 2015 nickTD. All rights reserved.
//
import Quick
import Nimble
import SwiftDailyAPI
class ReadmeCodeSpecs: QuickSpec {
override func spec() {
describe("Code in README.md") {
it("runs") {
// Setup
var latestDaily: LatestDaily?
var daily: Daily?
var news: News?
var newsExtra: NewsExtra?
var shortComments, longComments: Comments?
// Given
let newsId = 4772308
let date = NSDate.dateFromString("20150525", format: DailyConstants.dateFormat)!
let api = DailyAPI(userAgent: "SwiftDailyAPI_ReadMe")
// When
api.latestDaily { latestDailyFromAPI in
latestDaily = latestDailyFromAPI
print(latestDaily?.news)
print(latestDaily?.topNews)
}
api.daily(forDate: date) { dailyFromAPI in
daily = dailyFromAPI
print(daily?.news)
}
api.news(newsId) { newsFromAPI in
news = newsFromAPI
print(news?.newsId)
print(news?.title)
}
api.newsExtra(newsId) { newsExtraFromAPI in
newsExtra = newsExtraFromAPI
print(newsExtra?.popularity)
print(newsExtra?.comments)
}
api.comments(newsId, shortCommentsHandler: { comments in
shortComments = comments
print(shortComments?.comments)
}, longCommentsHandler: { comments in
longComments = comments
print(longComments?.comments)
})
// Then
expect(latestDaily).toEventuallyNot(beNil(), timeout: 10)
expect(daily).toEventuallyNot(beNil(), timeout: 10)
expect(news).toEventuallyNot(beNil(), timeout: 10)
expect(newsExtra).toEventuallyNot(beNil(), timeout: 10)
expect(shortComments).toEventuallyNot(beNil(), timeout: 10)
expect(longComments).toEventuallyNot(beNil(), timeout: 10)
}
}
}
}
|
c76ff2de976a14b27f411ff71a845baa
| 27.633803 | 88 | 0.610428 | false | true | false | false |
coach-plus/ios
|
refs/heads/master
|
Floral/Pods/Hero/Sources/Transition/HeroTransition+UINavigationControllerDelegate.swift
|
mit
|
3
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
extension HeroTransition: UINavigationControllerDelegate {
public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if let previousNavigationDelegate = navigationController.previousNavigationDelegate {
previousNavigationDelegate.navigationController?(navigationController, willShow: viewController, animated: animated)
}
}
public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
if let previousNavigationDelegate = navigationController.previousNavigationDelegate {
previousNavigationDelegate.navigationController?(navigationController, didShow: viewController, animated: animated)
}
}
public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
guard !isTransitioning else { return nil }
self.state = .notified
self.isPresenting = operation == .push
self.fromViewController = fromViewController ?? fromVC
self.toViewController = toViewController ?? toVC
self.inNavigationController = true
return self
}
public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactiveTransitioning
}
}
|
4de97662e12f181046c6ea4c4cd3f315
| 53.078431 | 252 | 0.793691 | false | false | false | false |
TonnyTao/HowSwift
|
refs/heads/develop
|
Example/Pods/RxSwift/RxSwift/Traits/Infallible/Infallible+Operators.swift
|
gpl-3.0
|
4
|
//
// Infallible+Operators.swift
// RxSwift
//
// Created by Shai Mishali on 27/08/2020.
// Copyright © 2020 Krunoslav Zaher. All rights reserved.
//
// MARK: - Static allocation
extension InfallibleType {
/**
Returns an infallible sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting infallible sequence.
- returns: An infallible sequence containing the single specified element.
*/
public static func just(_ element: Element) -> Infallible<Element> {
Infallible(.just(element))
}
/**
Returns an infallible sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting infallible sequence.
- parameter scheduler: Scheduler to send the single element on.
- returns: An infallible sequence containing the single specified element.
*/
public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Infallible<Element> {
Infallible(.just(element, scheduler: scheduler))
}
/**
Returns a non-terminating infallible sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An infallible sequence whose observers will never get called.
*/
public static func never() -> Infallible<Element> {
Infallible(.never())
}
/**
Returns an empty infallible sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An infallible sequence with no elements.
*/
public static func empty() -> Infallible<Element> {
Infallible(.empty())
}
/**
Returns an infallible sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> Infallible<Element>)
-> Infallible<Element> {
Infallible(.deferred { try observableFactory().asObservable() })
}
}
// MARK: From & Of
extension Infallible {
/**
This method creates a new Infallible instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription.
- returns: The Infallible sequence whose elements are pulled from the given arguments.
*/
public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> {
Infallible(Observable.from(elements, scheduler: scheduler))
}
}
extension Infallible {
/**
Converts an array to an Infallible sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The Infallible sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from(_ array: [Element], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> {
Infallible(Observable.from(array, scheduler: scheduler))
}
/**
Converts a sequence to an Infallible sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The Infallible sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from<Sequence: Swift.Sequence>(_ sequence: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Infallible<Element> where Sequence.Element == Element {
Infallible(Observable.from(sequence, scheduler: scheduler))
}
}
// MARK: - Filter
extension InfallibleType {
/**
Filters the elements of an observable sequence based on a predicate.
- seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html)
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (Element) -> Bool)
-> Infallible<Element> {
Infallible(asObservable().filter(predicate))
}
}
// MARK: - Map
extension InfallibleType {
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<Result>(_ transform: @escaping (Element) -> Result)
-> Infallible<Result> {
Infallible(asObservable().map(transform))
}
/**
Projects each element of an observable sequence into an optional form and filters all optional results.
- parameter transform: A transform function to apply to each source element and which returns an element or nil.
- returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source.
*/
public func compactMap<Result>(_ transform: @escaping (Element) -> Result?)
-> Infallible<Result> {
Infallible(asObservable().compactMap(transform))
}
}
// MARK: - Distinct
extension InfallibleType where Element: Comparable {
/**
Returns an observable sequence that contains only distinct contiguous elements according to equality operator.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
public func distinctUntilChanged()
-> Infallible<Element> {
Infallible(asObservable().distinctUntilChanged())
}
}
extension InfallibleType {
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
public func distinctUntilChanged<Key: Equatable>(_ keySelector: @escaping (Element) throws -> Key)
-> Infallible<Element> {
Infallible(self.asObservable().distinctUntilChanged(keySelector, comparer: { $0 == $1 }))
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence.
*/
public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool)
-> Infallible<Element> {
Infallible(self.asObservable().distinctUntilChanged({ $0 }, comparer: comparer))
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence.
*/
public func distinctUntilChanged<K>(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool)
-> Infallible<Element> {
Infallible(asObservable().distinctUntilChanged(keySelector, comparer: comparer))
}
/**
Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path
*/
public func distinctUntilChanged<Property: Equatable>(at keyPath: KeyPath<Element, Property>) ->
Infallible<Element> {
Infallible(asObservable().distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] })
}
}
// MARK: - Throttle
extension InfallibleType {
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().debounce(dueTime, scheduler: scheduler))
}
/**
Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration.
This operator makes sure that no two elements are emitted in less then dueTime.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().throttle(dueTime, latest: latest, scheduler: scheduler))
}
}
// MARK: - FlatMap
extension InfallibleType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMap(selector))
}
/**
Projects each element of an observable sequence into a new sequence of observable sequences and then
transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
It is a combination of `map` + `switchLatest` operator
- seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an
Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
public func flatMapLatest<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMapLatest(selector))
}
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
If element is received while there is some projected observable sequence being merged it will simply be ignored.
- seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated.
*/
public func flatMapFirst<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMapFirst(selector))
}
}
// MARK: - Concat
extension InfallibleType {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat<Source: ObservableConvertibleType>(_ second: Source) -> Infallible<Element> where Source.Element == Element {
Infallible(Observable.concat([self.asObservable(), second.asObservable()]))
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Infallible<Element>
where Sequence.Element == Infallible<Element> {
Infallible(Observable.concat(sequence.map { $0.asObservable() }))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Infallible<Element>
where Collection.Element == Infallible<Element> {
Infallible(Observable.concat(collection.map { $0.asObservable() }))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Infallible<Element> ...) -> Infallible<Element> {
Infallible(Observable.concat(sources.map { $0.asObservable() }))
}
/**
Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
public func concatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().concatMap(selector))
}
}
// MARK: - Merge
extension InfallibleType {
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Infallible<Element> where Collection.Element == Infallible<Element> {
Infallible(Observable.concat(sources.map { $0.asObservable() }))
}
/**
Merges elements from all infallible sequences from array into a single infallible sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of infallible sequences to merge.
- returns: The infallible sequence that merges the elements of the infallible sequences.
*/
public static func merge(_ sources: [Infallible<Element>]) -> Infallible<Element> {
Infallible(Observable.merge(sources.map { $0.asObservable() }))
}
/**
Merges elements from all infallible sequences into a single infallible sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of infallible sequences to merge.
- returns: The infallible sequence that merges the elements of the infallible sequences.
*/
public static func merge(_ sources: Infallible<Element>...) -> Infallible<Element> {
Infallible(Observable.merge(sources.map { $0.asObservable() }))
}
}
// MARK: - Do
extension Infallible {
/**
Invokes an action for each event in the infallible sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter afterCompleted: Action to invoke after graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Infallible<Element> {
Infallible(asObservable().do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose))
}
}
// MARK: - Scan
extension InfallibleType {
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<Seed>(into seed: Seed, accumulator: @escaping (inout Seed, Element) -> Void)
-> Infallible<Seed> {
Infallible(asObservable().scan(into: seed, accumulator: accumulator))
}
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<Seed>(_ seed: Seed, accumulator: @escaping (Seed, Element) -> Seed)
-> Infallible<Seed> {
Infallible(asObservable().scan(seed, accumulator: accumulator))
}
}
// MARK: - Start with
extension InfallibleType {
/**
Prepends a value to an observable sequence.
- seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html)
- parameter element: Element to prepend to the specified sequence.
- returns: The source sequence prepended with the specified values.
*/
public func startWith(_ element: Element) -> Infallible<Element> {
Infallible(asObservable().startWith(element))
}
}
// MARK: - Take and Skip {
extension InfallibleType {
/**
Returns the elements from the source observable sequence until the other observable sequence produces an element.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter other: Observable sequence that terminates propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public func take<Source: InfallibleType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().take(until: other.asObservable()))
}
/**
Returns the elements from the source observable sequence until the other observable sequence produces an element.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter other: Observable sequence that terminates propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public func take<Source: ObservableType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().take(until: other))
}
/**
Returns elements from an observable sequence until the specified condition is true.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter predicate: A function to test each element for a condition.
- parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`.
- returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes.
*/
public func take(until predicate: @escaping (Element) throws -> Bool,
behavior: TakeBehavior = .exclusive)
-> Infallible<Element> {
Infallible(asObservable().take(until: predicate, behavior: behavior))
}
/**
Returns elements from an observable sequence as long as a specified condition is true.
- seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html)
- parameter predicate: A function to test each element for a condition.
- returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
public func take(while predicate: @escaping (Element) throws -> Bool,
behavior: TakeBehavior = .exclusive)
-> Infallible<Element> {
Infallible(asObservable().take(while: predicate, behavior: behavior))
}
/**
Returns a specified number of contiguous elements from the start of an observable sequence.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter count: The number of elements to return.
- returns: An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
public func take(_ count: Int) -> Infallible<Element> {
Infallible(asObservable().take(count))
}
/**
Takes elements for the specified duration from the start of the infallible source sequence, using the specified scheduler to run timers.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An infallible sequence with the elements taken during the specified duration from the start of the source sequence.
*/
public func take(for duration: RxTimeInterval, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().take(for: duration, scheduler: scheduler))
}
/**
Bypasses elements in an infallible sequence as long as a specified condition is true and then returns the remaining elements.
- seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html)
- parameter predicate: A function to test each element for a condition.
- returns: An infallible sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
public func skip(while predicate: @escaping (Element) throws -> Bool) -> Infallible<Element> {
Infallible(asObservable().skip(while: predicate))
}
/**
Returns the elements from the source infallible sequence that are emitted after the other infallible sequence produces an element.
- seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html)
- parameter other: Infallible sequence that starts propagation of elements of the source sequence.
- returns: An infallible sequence containing the elements of the source sequence that are emitted after the other sequence emits an item.
*/
public func skip<Source: ObservableType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().skip(until: other))
}
}
// MARK: - Share
extension InfallibleType {
/**
Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer.
This operator is equivalent to:
* `.whileConnected`
```
// Each connection will have it's own subject instance to store replay events.
// Connections will be isolated from each another.
source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount()
```
* `.forever`
```
// One subject will store replay events for all connections to source.
// Connections won't be isolated from each another.
source.multicast(Replay.create(bufferSize: replay)).refCount()
```
It uses optimized versions of the operators for most common operations.
- parameter replay: Maximum element count of the replay buffer.
- parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum.
- seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html)
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected)
-> Infallible<Element> {
Infallible(asObservable().share(replay: replay, scope: scope))
}
}
// MARK: - withUnretained
extension InfallibleType {
/**
Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence.
In the case the provided object cannot be retained successfully, the seqeunce will complete.
- note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle.
- parameter obj: The object to provide an unretained reference on.
- parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence.
- returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence.
*/
public func withUnretained<Object: AnyObject, Out>(
_ obj: Object,
resultSelector: @escaping (Object, Element) -> Out
) -> Infallible<Out> {
Infallible(self.asObservable().withUnretained(obj, resultSelector: resultSelector))
}
/**
Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence.
In the case the provided object cannot be retained successfully, the seqeunce will complete.
- note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle.
- parameter obj: The object to provide an unretained reference on.
- returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence.
*/
public func withUnretained<Object: AnyObject>(_ obj: Object) -> Infallible<(Object, Element)> {
withUnretained(obj) { ($0, $1) }
}
}
extension InfallibleType {
// MARK: - withLatestFrom
/**
Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- note: Elements emitted by self before the second source has emitted any values will be omitted.
- parameter second: Second observable source.
- parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<Source: InfallibleType, ResultType>(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Infallible<ResultType> {
Infallible(self.asObservable().withLatestFrom(second.asObservable(), resultSelector: resultSelector))
}
/**
Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element.
- seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html)
- note: Elements emitted by self before the second source has emitted any values will be omitted.
- parameter second: Second observable source.
- returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function.
*/
public func withLatestFrom<Source: InfallibleType>(_ second: Source) -> Infallible<Source.Element> {
withLatestFrom(second) { $1 }
}
}
|
a8c0f2181d7ed2120a656bae459d42be
| 47.7173 | 320 | 0.725359 | false | false | false | false |
jeevanRao7/Swift_Playgrounds
|
refs/heads/master
|
Swift Playgrounds/Basics/Arrays.playground/Contents.swift
|
mit
|
1
|
/*
* Swift 3.1
* Basics : Arrays
* Apple Doc Ref : https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
*/
import Foundation
//Initialize array of certain type.
var someInts = [Int]()
//To append a single element to the end of a mutable array
someInts.append(3)
//empty array with Array Literal '[]'. Note : Still array is of type [Int]
someInts = []
//Create array with default value
var threeDoubles = Array(repeating: 0.0, count: 3)
print(threeDoubles)
//Create array
//1. By adding 2 arrays together
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
var sixDoubles = threeDoubles + anotherThreeDoubles
print(sixDoubles)
//2. By array literals
var shoppingList:[String] = ["Eggs", "Milk"]
//Modify array
//Number of elements in the array
shoppingList.count
shoppingList.append("Flour")
shoppingList.count
//Add elements by 'Addition assignment' operator
shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
//Check for empty array
shoppingList.isEmpty
someInts.isEmpty
//Retrieve array from index
var firstItem = shoppingList[0]
//Change the existing value at a given index
shoppingList[0] = "Six Eggs"
//Change a range of values at once. Note : even if the replacement set of values has a different length than the range you are replacing.
print(shoppingList)
shoppingList[4...6] = ["Banana","Apple"]
print(shoppingList)
//Insert element at specified index
shoppingList.insert("Maple Syrup", at: 0)
//Remove element at specified index
let mapleSyrup = shoppingList.remove(at: 0)
print("Removed item : \(mapleSyrup)")
//Better approach : Remove element from last / first element of array
let SixEggs = shoppingList.removeFirst()
print("Removed item : \(SixEggs)")
let apples = shoppingList.removeLast()
print("Removed item : \(apples)")
//Iterating over an array for-in loop.
print("Iterating over array \n")
for item in shoppingList {
print(item)
}
//If we need index of each item as well as its value, use enumerated(). It returns 'Tuple' as (index, item)
for (index, value) in shoppingList.enumerated() {
print("Item \(value) at index \(index)")
}
|
41a5c3e7a88edf27717879091f6aea34
| 24.494253 | 141 | 0.734445 | false | false | false | false |
PerfectServers/Perfect-Authentication-Server
|
refs/heads/master
|
Sources/PerfectAuthServer/utility/makeRequest.swift
|
apache-2.0
|
1
|
//
// makeRequest.swift
// Perfect-App-Template
//
// Created by Jonathan Guthrie on 2017-02-22.
//
//
import Foundation
import PerfectLib
import PerfectCURL
import cURL
import PerfectHTTP
extension Utility {
/// The function that triggers the specific interaction with a remote server
/// Parameters:
/// - method: The HTTP Method enum, i.e. .get, .post
/// - route: The route required
/// - body: The JSON formatted sring to sent to the server
/// Response:
/// "data" - [String:Any]
static func makeRequest(
_ method: HTTPMethod,
_ url: String,
body: String = "",
encoding: String = "JSON",
bearerToken: String = ""
) -> ([String:Any]) {
let curlObject = CURL(url: url)
curlObject.setOption(CURLOPT_HTTPHEADER, s: "Accept: application/json")
curlObject.setOption(CURLOPT_HTTPHEADER, s: "Cache-Control: no-cache")
curlObject.setOption(CURLOPT_USERAGENT, s: "PerfectAPI2.0")
if !bearerToken.isEmpty {
curlObject.setOption(CURLOPT_HTTPHEADER, s: "Authorization: Bearer \(bearerToken)")
}
switch method {
case .post :
let byteArray = [UInt8](body.utf8)
curlObject.setOption(CURLOPT_POST, int: 1)
curlObject.setOption(CURLOPT_POSTFIELDSIZE, int: byteArray.count)
curlObject.setOption(CURLOPT_COPYPOSTFIELDS, v: UnsafeMutablePointer(mutating: byteArray))
if encoding == "form" {
curlObject.setOption(CURLOPT_HTTPHEADER, s: "Content-Type: application/x-www-form-urlencoded")
} else {
curlObject.setOption(CURLOPT_HTTPHEADER, s: "Content-Type: application/json")
}
default: //.get :
curlObject.setOption(CURLOPT_HTTPGET, int: 1)
}
var header = [UInt8]()
var bodyIn = [UInt8]()
var code = 0
var data = [String: Any]()
var raw = [String: Any]()
var perf = curlObject.perform()
defer { curlObject.close() }
while perf.0 {
if let h = perf.2 {
header.append(contentsOf: h)
}
if let b = perf.3 {
bodyIn.append(contentsOf: b)
}
perf = curlObject.perform()
}
if let h = perf.2 {
header.append(contentsOf: h)
}
if let b = perf.3 {
bodyIn.append(contentsOf: b)
}
let _ = perf.1
// assamble the body from a binary byte array to a string
let content = String(bytes:bodyIn, encoding:String.Encoding.utf8)
// parse the body data into a json convertible
do {
if (content?.characters.count)! > 0 {
if (content?.starts(with:"["))! {
let arr = try content?.jsonDecode() as! [Any]
data["response"] = arr
} else {
data = try content?.jsonDecode() as! [String : Any]
}
}
return data
} catch {
return [:]
}
}
}
|
91cc09fb44622cdd00569758ddc48fda
| 23.415094 | 98 | 0.660355 | false | false | false | false |
beneiltis/SwiftCharts
|
refs/heads/master
|
Examples/Examples/Examples/BarsPlusMinusWithGradientExample.swift
|
apache-2.0
|
5
|
//
// BarsPlusMinusWithGradientExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class BarsPlusMinusWithGradientExample: UIViewController {
private var chart: Chart? // arc
private let gradientPicker: GradientPicker // to pick the colors of the bars
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
self.gradientPicker = GradientPicker(width: 200)
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
let vals: [(title: String, val: CGFloat)] = [
("U", -75),
("T", -65),
("S", -50),
("R", -45),
("Q", -40),
("P", -30),
("O", -20),
("N", -10),
("M", -5),
("L", -0),
("K", 10),
("J", 15),
("I", 20),
("H", 30),
("G", 35),
("F", 40),
("E", 50),
("D", 60),
("C", 65),
("B", 70),
("A", 75)
]
let (minVal: CGFloat, maxVal: CGFloat) = vals.reduce((min: CGFloat(0), max: CGFloat(0))) {tuple, val in
(min: min(tuple.min, val.val), max: max(tuple.max, val.val))
}
let length: CGFloat = maxVal - minVal
let zero = ChartAxisValueFloat(0)
let bars: [ChartBarModel] = Array(enumerate(vals)).map {index, tuple in
let percentage = (tuple.val - minVal - 0.01) / length // FIXME without -0.01 bar with 1 (100 perc) is black
let color = self.gradientPicker.colorForPercentage(percentage).colorWithAlphaComponent(0.6)
return ChartBarModel(constant: ChartAxisValueFloat(CGFloat(index)), axisValue1: zero, axisValue2: ChartAxisValueFloat(tuple.val), bgColor: color)
}
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let xValues = Array(stride(from: -80, through: 80, by: 20)).map {ChartAxisValueFloat($0, labelSettings: labelSettings)}
let yValues =
[ChartAxisValueString(order: -1)] +
Array(enumerate(vals)).map {index, tuple in ChartAxisValueString(tuple.0, order: index, labelSettings: labelSettings)} +
[ChartAxisValueString(order: vals.count)]
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
// calculate coords space in the background to keep UI smooth
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let coordsSpace = ChartCoordsSpaceLeftTopSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
dispatch_async(dispatch_get_main_queue()) {
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let barsLayer = ChartBarsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, bars: bars, horizontal: true, barWidth: Env.iPad ? 40 : 16, animDuration: 0.5)
var settings = ChartGuideLinesLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: .X, settings: settings)
// create x zero guideline as view to be in front of the bars
let dummyZeroXChartPoint = ChartPoint(x: ChartAxisValueFloat(0), y: ChartAxisValueFloat(0))
let xZeroGuidelineLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: [dummyZeroXChartPoint], viewGenerator: {(chartPointModel, layer, chart) -> UIView? in
let width: CGFloat = 2
let v = UIView(frame: CGRectMake(chartPointModel.screenLoc.x - width / 2, innerFrame.origin.y, width, innerFrame.size.height))
v.backgroundColor = UIColor(red: 1, green: 69 / 255, blue: 0, alpha: 1)
return v
})
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
barsLayer,
xZeroGuidelineLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
}
private class GradientPicker {
let gradientImg: UIImage
lazy var imgData: UnsafePointer<UInt8> = {
let provider = CGImageGetDataProvider(self.gradientImg.CGImage)
let pixelData = CGDataProviderCopyData(provider)
return CFDataGetBytePtr(pixelData)
}()
init(width: CGFloat) {
var gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = CGRectMake(0, 0, width, 1)
gradient.colors = [UIColor.redColor().CGColor, UIColor.yellowColor().CGColor, UIColor.cyanColor().CGColor, UIColor.blueColor().CGColor]
gradient.startPoint = CGPointMake(0, 0.5)
gradient.endPoint = CGPointMake(1.0, 0.5)
let imgHeight = 1
let imgWidth = Int(gradient.bounds.size.width)
let bitmapBytesPerRow = imgWidth * 4
let bitmapByteCount = bitmapBytesPerRow * imgHeight
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate (nil,
imgWidth,
imgHeight,
8,
bitmapBytesPerRow,
colorSpace,
bitmapInfo)
UIGraphicsBeginImageContext(gradient.bounds.size)
gradient.renderInContext(context)
let gradientImg = UIImage(CGImage: CGBitmapContextCreateImage(context))!
UIGraphicsEndImageContext()
self.gradientImg = gradientImg
}
func colorForPercentage(percentage: CGFloat) -> UIColor {
let data = self.imgData
let xNotRounded = self.gradientImg.size.width * percentage
let x = 4 * (floor(abs(xNotRounded / 4)))
let pixelIndex = Int(x * 4)
let color = UIColor(
red: CGFloat(data[pixelIndex + 0]) / 255.0,
green: CGFloat(data[pixelIndex + 1]) / 255.0,
blue: CGFloat(data[pixelIndex + 2]) / 255.0,
alpha: CGFloat(data[pixelIndex + 3]) / 255.0
)
return color
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
|
456fc0103cafae9f0204332b751e6730
| 40.204301 | 214 | 0.558847 | false | false | false | false |
jimhqin/AlertSheet
|
refs/heads/master
|
AlertSheetDemo/RootViewController.swift
|
mit
|
1
|
//
// RootViewController.swift
// AlertSheetDemo
//
// Created by JQ@Onbeep on 7/17/15.
// Copyright (c) 2015 jimqin. All rights reserved.
//
import UIKit
struct DemoButtonAppearance {
static let width = 200
static let height = 44
static let topMargin = 44
static let cornerRadius: CGFloat = 11.0
}
final class RootViewController: UIViewController, AlertSheetDelegate {
override func loadView() {
let applicationFrame = UIScreen.mainScreen().applicationFrame
let contentView = UIView(frame: applicationFrame)
contentView.backgroundColor = .whiteColor()
view = contentView
let demoButton = DemoButton(frame: .zero)
demoButton.addTarget(self, action: "didPressDemoButton", forControlEvents: .TouchUpInside)
view.addSubview(demoButton)
demoButton.translatesAutoresizingMaskIntoConstraints = false
let viewsDictionary = ["demoButton": demoButton]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:[demoButton(\(DemoButtonAppearance.width))]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: viewsDictionary
)
view.addConstraints(horizontalConstraints)
let centerHorizontallyStoryView = centerHorizontallyConstraint(forView: viewsDictionary["demoButton"]!)
view.addConstraint(centerHorizontallyStoryView)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-\(DemoButtonAppearance.topMargin)-[demoButton(\(DemoButtonAppearance.height))]",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: viewsDictionary
)
view.addConstraints(verticalConstraints)
}
func didPressDemoButton() {
if view.viewWithTag(1) != nil {
return
}
let alertSheet = AlertSheet(
title: "Network Error",
message: "You appear to be offline. Check your connection and try again.",
buttonTitle: "DISMISS",
image: nil
)
alertSheet.delegate = self
alertSheet.tag = 1
alertSheet.showInView(view)
}
private func centerHorizontallyConstraint(forView view: UIView) -> NSLayoutConstraint {
let constraint = NSLayoutConstraint(
item: view,
attribute: .CenterX,
relatedBy: .Equal,
toItem: view.superview!,
attribute: .CenterX,
multiplier: 1.0,
constant: 0.0
)
return constraint
}
// MARK: - AlertSheetDelegate Protocol
func alertSheet(alertSheet: AlertSheet, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
case 0: alertSheet.dismiss()
default: alertSheet.dismiss()
}
}
}
|
a9a56e9d6cd6857f5ba7b0f069b07c5e
| 30.72043 | 111 | 0.631864 | false | false | false | false |
clemler/Calculator
|
refs/heads/master
|
Calculator/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Calculator
//
// Created by ctlemler on 11/10/15.
// Copyright © 2015 Chris Lemler. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
@IBAction func appendDigit(sender: UIButton) {
let dot = "."
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
if (digit == dot) && display.text!.containsString(dot) {
return
}
display.text = display.text! + digit
}
else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
var operandStack = Array<Double>()
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
print("operandStack = \(operandStack)")
}
// Clear the stack, reset the display, and put
// the calculator back to its original state
@IBAction func clear(sender: UIButton) {
userIsInTheMiddleOfTypingANumber = false
display.text = ""
operandStack.removeAll()
print("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
// If user has entered a number, then selected an operation,
// make certain the number has been pushed on to the operandStack
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operation {
case "×": performOperation({$0 * $1})
case "÷": performOperation({$1 / $0})
case "+": performOperation({$0 + $1})
case "−": performOperation({$1 - $0})
case "√": performOperation({ sqrt($0) })
case "sin": performOperation({ sin($0) })
case "cos": performOperation({ cos($0) })
case "𝛑": performOperation({ sqrt($0) })
default: break
}
}
func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
@nonobjc
func performOperation(operation: (Double) -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
}
|
44156000a8a7ff43df0cf38d6f21f383
| 27.969072 | 90 | 0.56726 | false | false | false | false |
TimBroddin/meteor-ios
|
refs/heads/master
|
Examples/Todos/Todos/AppDelegate.swift
|
mit
|
2
|
// Copyright (c) 2014-2015 Martijn Walraven
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreData
import Meteor
let Meteor = METCoreDataDDPClient(serverURL: NSURL(string: "wss://meteor-ios-todos.meteor.com/websocket")!)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Meteor.connect()
let splitViewController = self.window!.rootViewController as! UISplitViewController
splitViewController.preferredDisplayMode = .AllVisible
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let listViewController = masterNavigationController.topViewController as! ListsViewController
listViewController.managedObjectContext = Meteor.mainQueueManagedObjectContext
return true
}
// MARK: - UISplitViewControllerDelegate
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
if let todosViewController = (secondaryViewController as? UINavigationController)?.topViewController as? TodosViewController {
if todosViewController.listID == nil {
return true
}
}
return false
}
}
|
0bbc4e01f5c99bc303a85e05049dfb7f
| 44.732143 | 220 | 0.783678 | false | false | false | false |
esttorhe/Moya
|
refs/heads/master
|
Source/Moya+Alamofire.swift
|
mit
|
2
|
import Foundation
import Alamofire
public typealias Manager = Alamofire.Manager
/// Choice of parameter encoding.
public typealias ParameterEncoding = Alamofire.ParameterEncoding
/// Make the Alamofire Request type conform to our type, to prevent leaking Alamofire to plugins.
extension Request: RequestType { }
/// Internal token that can be used to cancel requests
public final class CancellableToken: Cancellable , CustomDebugStringConvertible {
let cancelAction: () -> Void
let request : Request?
private(set) var canceled: Bool = false
private var lock: OSSpinLock = OS_SPINLOCK_INIT
public func cancel() {
OSSpinLockLock(&lock)
defer { OSSpinLockUnlock(&lock) }
guard !canceled else { return }
canceled = true
cancelAction()
}
init(action: () -> Void){
self.cancelAction = action
self.request = nil
}
init(request : Request){
self.request = request
self.cancelAction = {
request.cancel()
}
}
public var debugDescription: String {
guard let request = self.request else {
return "Empty Request"
}
return request.debugDescription
}
}
|
3801dbecf8bc5a57c060b5af0c5df879
| 25.531915 | 97 | 0.643144 | false | false | false | false |
LinShiwei/WeatherDemo
|
refs/heads/master
|
Carthage/Checkouts/Nimble/Tests/Nimble/Matchers/RaisesExceptionTest.swift
|
apache-2.0
|
23
|
import XCTest
import Nimble
#if _runtime(_ObjC) && !SWIFT_PACKAGE
class RaisesExceptionTest: XCTestCase, XCTestCaseProvider {
var allTests: [(String, () throws -> Void)] {
return [
("testPositiveMatches", testPositiveMatches),
("testPositiveMatchesWithClosures", testPositiveMatchesWithClosures),
("testNegativeMatches", testNegativeMatches),
("testNegativeMatchesDoNotCallClosureWithoutException", testNegativeMatchesDoNotCallClosureWithoutException),
("testNegativeMatchesWithClosure", testNegativeMatchesWithClosure),
]
}
var anException = NSException(name: "laugh", reason: "Lulz", userInfo: ["key": "value"])
func testPositiveMatches() {
expect { self.anException.raise() }.to(raiseException())
expect { self.anException.raise() }.to(raiseException(named: "laugh"))
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz"))
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]))
}
func testPositiveMatchesWithClosures() {
expect { self.anException.raise() }.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal("laugh"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh") { (exception: NSException) in
expect(exception.name).to(beginWith("lau"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz") { (exception: NSException) in
expect(exception.name).to(beginWith("lau"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]) { (exception: NSException) in
expect(exception.name).to(beginWith("lau"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh") { (exception: NSException) in
expect(exception.name).toNot(beginWith("as"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz") { (exception: NSException) in
expect(exception.name).toNot(beginWith("df"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]) { (exception: NSException) in
expect(exception.name).toNot(beginWith("as"))
})
}
func testNegativeMatches() {
failsWithErrorMessage("expected to raise exception with name <foo>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException(named: "foo"))
}
failsWithErrorMessage("expected to raise exception with name <laugh> with reason <bar>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "bar"))
}
failsWithErrorMessage(
"expected to raise exception with name <laugh> with reason <Lulz> with userInfo <{k = v;}>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["k": "v"]))
}
failsWithErrorMessage("expected to raise any exception, got no exception") {
expect { self.anException }.to(raiseException())
}
failsWithErrorMessage("expected to not raise any exception, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException())
}
failsWithErrorMessage("expected to raise exception with name <laugh> with reason <Lulz>, got no exception") {
expect { self.anException }.to(raiseException(named: "laugh", reason: "Lulz"))
}
failsWithErrorMessage("expected to raise exception with name <bar> with reason <Lulz>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException(named: "bar", reason: "Lulz"))
}
failsWithErrorMessage("expected to not raise exception with name <laugh>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException(named: "laugh"))
}
failsWithErrorMessage("expected to not raise exception with name <laugh> with reason <Lulz>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException(named: "laugh", reason: "Lulz"))
}
failsWithErrorMessage("expected to not raise exception with name <laugh> with reason <Lulz> with userInfo <{key = value;}>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]))
}
}
func testNegativeMatchesDoNotCallClosureWithoutException() {
failsWithErrorMessage("expected to raise exception that satisfies block, got no exception") {
expect { self.anException }.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to raise exception with name <foo> that satisfies block, got no exception") {
expect { self.anException }.to(raiseException(named: "foo") { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to raise exception with name <foo> with reason <ha> that satisfies block, got no exception") {
expect { self.anException }.to(raiseException(named: "foo", reason: "ha") { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to raise exception with name <foo> with reason <Lulz> with userInfo <{}> that satisfies block, got no exception") {
expect { self.anException }.to(raiseException(named: "foo", reason: "Lulz", userInfo: [:]) { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to not raise any exception, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException())
}
}
func testNegativeMatchesWithClosure() {
failsWithErrorMessage("expected to raise exception that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
let innerFailureMessage = "expected to begin with <fo>, got <laugh>"
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <laugh> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "laugh") { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <lol> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "lol") { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <laugh> with reason <Lulz> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz") { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <lol> with reason <wrong> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "lol", reason: "wrong") { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <laugh> with reason <Lulz> with userInfo <{key = value;}> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]) { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <lol> with reason <Lulz> with userInfo <{}> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "lol", reason: "Lulz", userInfo: [:]) { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
}
}
#endif
|
7ab7fd099a186ef12f8f149d2adc1b1f
| 57.903614 | 244 | 0.637145 | false | true | false | false |
bennokress/DateTimePicker
|
refs/heads/master
|
DateTimePicker/DateTimePicker.swift
|
mit
|
1
|
//
// DateTimePicker.swift
// DateTimePicker
//
// Created by Benno Kress on 04.12.16.
// Copyright © 2016 it-economics. All rights reserved.
//
import UIKit
@objc public class DateTimePicker: UIView {
// MARK: - Public Variables
public var contentHeight: CGFloat = 413
public var backgroundViewColor: UIColor = .clear {
didSet {
backgroundColor = backgroundViewColor
}
}
public var highlightColor = UIColor(red: 0/255.0, green: 199.0/255.0, blue: 194.0/255.0, alpha: 1) {
didSet {
todayButton.setTitleColor(highlightColor, for: .normal)
colonLabel.textColor = highlightColor
}
}
public var darkColor = UIColor(red: 0, green: 22.0/255.0, blue: 39.0/255.0, alpha: 1)
public var daysBackgroundColor = UIColor(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, alpha: 1)
var didLayoutAtOnce = false
public override func layoutSubviews() {
super.layoutSubviews()
// For the first time view will be layouted manually before show
// For next times we need relayout it because of screen rotation etc.
if !didLayoutAtOnce {
didLayoutAtOnce = true
} else {
self.configurePicker()
}
}
public var selectedDate = Date() {
didSet {
resetDateTitle()
}
}
public var timeInterval = 1 {
didSet {
resetDateTitle()
}
}
public var dateFormat = "H 'hours and' mm 'minutes on' MMMM dd" {
didSet {
resetDateTitle()
}
}
public var todayButtonTitle = "Today" {
didSet {
todayButton.setTitle(todayButtonTitle, for: .normal)
let size = todayButton.sizeThatFits(CGSize(width: 0, height: 44.0)).width + 10.0
todayButton.frame = CGRect(x: contentView.frame.width - size, y: 0, width: size, height: 44)
}
}
public var doneButtonTitle = "Done" {
didSet {
doneButton.setTitle(doneButtonTitle, for: .normal)
}
}
public var completionHandler: ((Date) -> Void)?
// MARK: - Private Variables
internal var hourTableView: UITableView!
internal var minuteTableView: UITableView!
internal var dayCollectionView: UICollectionView!
private var contentView: UIView!
private var dateTitleLabel: UILabel!
private var todayButton: UIButton!
private var doneButton: UIButton!
private var colonLabel: UILabel!
private var minimumDate: Date!
private var maximumDate: Date!
internal var calendar: Calendar = .current
internal var dates: [Date]! = []
internal var components: DateComponents! {
didSet {
if let hour = components.hour {
hourTableView.selectRow(at: IndexPath(row: hour, section: 0), animated: true, scrollPosition: .middle)
}
if let minute = components.minute {
minuteTableView.selectRow(at: IndexPath(row: minute / timeInterval, section: 0), animated: true, scrollPosition: .middle)
}
}
}
// MARK: - Configuration of UI Elements
private func configuredContentView() -> UIView {
contentView = UIView(frame: CGRect(x: 0,
y: frame.height,
width: frame.width,
height: contentHeight))
contentView.layer.shadowColor = UIColor(white: 0, alpha: 0.3).cgColor
contentView.layer.shadowOffset = CGSize(width: 0, height: -2.0)
contentView.layer.shadowRadius = 1.5
contentView.layer.shadowOpacity = 0.5
contentView.backgroundColor = .white
contentView.isHidden = true
return contentView
}
private func configuredTitleView() -> UIView {
let titleView = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: contentView.frame.width, height: 44)))
titleView.backgroundColor = .white
return titleView
}
private func configuredDateTitleLabel() -> UILabel {
dateTitleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
dateTitleLabel.font = UIFont.systemFont(ofSize: 15)
dateTitleLabel.textColor = darkColor
dateTitleLabel.textAlignment = .center
resetDateTitle()
return dateTitleLabel
}
private func configuredTodayButton() -> UIButton {
todayButton = UIButton(type: .system)
todayButton.setTitle(todayButtonTitle, for: .normal)
todayButton.setTitleColor(highlightColor, for: .normal)
todayButton.addTarget(self, action: #selector(DateTimePicker.setToday), for: .touchUpInside)
todayButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
todayButton.isHidden = self.minimumDate.compare(Date()) == .orderedDescending || self.maximumDate.compare(Date()) == .orderedAscending
let size = todayButton.sizeThatFits(CGSize(width: 0, height: 44.0)).width + 10.0
todayButton.frame = CGRect(x: contentView.frame.width - size, y: 0, width: size, height: 44)
return todayButton
}
private func configuredDayCollectionView() -> UICollectionView {
let layout = StepCollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 10
layout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: 75, height: 80)
dayCollectionView = UICollectionView(frame: CGRect(x: 0, y: 44, width: contentView.frame.width, height: 100), collectionViewLayout: layout)
dayCollectionView.backgroundColor = daysBackgroundColor
dayCollectionView.showsHorizontalScrollIndicator = false
dayCollectionView.register(DateCollectionViewCell.self, forCellWithReuseIdentifier: "dateCell")
dayCollectionView.dataSource = self
dayCollectionView.delegate = self
let inset = (dayCollectionView.frame.width - 75) / 2
dayCollectionView.contentInset = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
return dayCollectionView
}
private func configuredDayCollectionBorderView(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> UIView {
let borderTopView = UIView(frame: CGRect(x: x, y: y, width: width, height: height))
borderTopView.backgroundColor = darkColor.withAlphaComponent(0.2)
return borderTopView
}
private func configuredDoneButton() -> UIButton {
doneButton = UIButton(type: .system)
doneButton.frame = CGRect(x: 10, y: contentView.frame.height - 10 - 44, width: contentView.frame.width - 20, height: 44)
doneButton.setTitle(doneButtonTitle, for: .normal)
doneButton.setTitleColor(.white, for: .normal)
doneButton.backgroundColor = darkColor.withAlphaComponent(0.5)
doneButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13)
doneButton.layer.cornerRadius = 3
doneButton.layer.masksToBounds = true
doneButton.addTarget(self, action: #selector(DateTimePicker.dismissView), for: .touchUpInside)
return doneButton
}
private func configuredHourTableView(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> UITableView {
hourTableView = UITableView(frame: CGRect(x: x, y: y, width: width, height: height))
hourTableView.rowHeight = 36
hourTableView.contentInset = UIEdgeInsetsMake(hourTableView.frame.height / 2, 0, hourTableView.frame.height / 2, 0)
hourTableView.showsVerticalScrollIndicator = false
hourTableView.separatorStyle = .none
hourTableView.delegate = self
hourTableView.dataSource = self
return hourTableView
}
private func configuredMinuteTableView(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> UITableView {
minuteTableView = UITableView(frame: CGRect(x: x, y: y, width: width, height: height))
minuteTableView.rowHeight = 36
minuteTableView.contentInset = UIEdgeInsetsMake(minuteTableView.frame.height / 2, 0, minuteTableView.frame.height / 2, 0)
minuteTableView.showsVerticalScrollIndicator = false
minuteTableView.separatorStyle = .none
minuteTableView.delegate = self
minuteTableView.dataSource = self
return minuteTableView
}
private func configuredColonLabel(x: Int, y: Int, width: Int, height: Int, centerX: CGFloat, centerY: CGFloat) -> UILabel {
colonLabel = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
colonLabel.center = CGPoint(x: centerX, y: centerY)
colonLabel.text = ":"
colonLabel.font = UIFont.boldSystemFont(ofSize: 18)
colonLabel.textColor = highlightColor
colonLabel.textAlignment = .center
return colonLabel
}
private func configuredTimeSeparator(x: Int, y: Int, width: Int, height: Int, centerX: CGFloat, centerY: CGFloat) -> UIView {
let separatorView = UIView(frame: CGRect(x: x, y: y, width: width, height: height))
separatorView.backgroundColor = darkColor.withAlphaComponent(0.2)
separatorView.center = CGPoint(x: centerX, y: centerY)
return separatorView
}
// MARK: - Assemble and Display Picker
@objc open class func show(inView superview: UIView? = UIApplication.shared.keyWindow, selected: Date? = nil, minimumDate: Date? = nil, maximumDate: Date? = nil, timeInterval: Int = 1) -> DateTimePicker {
let dateTimePicker = DateTimePicker()
dateTimePicker.timeInterval = timeInterval
dateTimePicker.selectedDate = selected ?? Date()
let defaultDateBound: TimeInterval = 3600 * 24 * 365 * 20 // 20 years
dateTimePicker.minimumDate = minimumDate ?? Date(timeIntervalSinceNow: -defaultDateBound)
dateTimePicker.maximumDate = maximumDate ?? Date(timeIntervalSinceNow: defaultDateBound)
assert(dateTimePicker.minimumDate.compare(dateTimePicker.maximumDate) == .orderedAscending, "Minimum date should be earlier than maximum date")
assert(dateTimePicker.minimumDate.compare(dateTimePicker.selectedDate) != .orderedDescending, "Selected date should be later or equal to minimum date")
assert(dateTimePicker.selectedDate.compare(dateTimePicker.maximumDate) != .orderedDescending, "Selected date should be earlier or equal to maximum date")
dateTimePicker.configurePicker(inView: superview)
superview?.addSubview(dateTimePicker)
return dateTimePicker
}
private func configurePicker(inView superview: UIView? = UIApplication.shared.keyWindow) {
guard let superview = superview else { return }
if self.contentView != nil {
self.contentView.removeFromSuperview()
}
let superViewSize = CGSize(width: superview.bounds.width, height: superview.bounds.height)
self.contentHeight = superViewSize.height - CGFloat(120.0)
self.frame = CGRect(x: 0,
y: 0,
width: superViewSize.width,
height: superViewSize.height)
let contentView = configuredContentView()
addSubview(contentView)
let titleView = configuredTitleView()
contentView.addSubview(titleView)
let dateTitleLabel = configuredDateTitleLabel()
titleView.addSubview(dateTitleLabel)
let todayButton = configuredTodayButton()
titleView.addSubview(todayButton)
let dayCollectionView = configuredDayCollectionView()
contentView.addSubview(dayCollectionView)
// top & bottom borders on day collection view
let borderTopView = configuredDayCollectionBorderView(
x: 0,
y: titleView.frame.height,
width: titleView.frame.width,
height: 1
)
contentView.addSubview(borderTopView)
let borderBottomView = configuredDayCollectionBorderView(
x: 0,
y: dayCollectionView.frame.origin.y + dayCollectionView.frame.height,
width: titleView.frame.width,
height: 1
)
contentView.addSubview(borderBottomView)
let doneButton = configuredDoneButton()
contentView.addSubview(doneButton)
// hour table view
let hourTableView = configuredHourTableView(
x: contentView.frame.width / 2 - 60,
y: borderBottomView.frame.origin.y + 2,
width: 60,
height: doneButton.frame.origin.y - borderBottomView.frame.origin.y - 10
)
contentView.addSubview(hourTableView)
// minute table view
let minuteTableView = configuredMinuteTableView(
x: contentView.frame.width / 2,
y: borderBottomView.frame.origin.y + 2,
width: 60,
height: doneButton.frame.origin.y - borderBottomView.frame.origin.y - 10
)
contentView.addSubview(minuteTableView)
// colon
let colonLabel = configuredColonLabel(
x: 0,
y: 0,
width: 10,
height: 36,
centerX: contentView.frame.width / 2,
centerY: (doneButton.frame.origin.y - borderBottomView.frame.origin.y - 10) / 2 + borderBottomView.frame.origin.y
)
contentView.addSubview(colonLabel)
// time separators
// let timeSeperatorTopView = configuredTimeSeparator(
// x: 0,
// y: 0,
// width: 90,
// height: 1,
// centerX: contentView.frame.width / 2,
// centerY: borderBottomView.frame.origin.y + 36
// )
// contentView.addSubview(timeSeperatorTopView)
//
// let timeSeperatorBottomView = configuredTimeSeparator(
// x: 0,
// y: 0,
// width: 90,
// height: 1,
// centerX: contentView.frame.width / 2,
// centerY: timeSeperatorTopView.frame.origin.y + 36
// )
// contentView.addSubview(timeSeperatorBottomView)
// fill date
fillDates(fromDate: minimumDate, toDate: maximumDate)
updateCollectionView(to: selectedDate)
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/YYYY"
for date in dates {
if formatter.string(from: date) == formatter.string(from: selectedDate) {
dayCollectionView.selectItem(at: IndexPath(row: dates.index(of: date)!, section: 0), animated: true, scrollPosition: .centeredHorizontally)
break
}
}
components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: selectedDate)
contentView.isHidden = false
resetTime()
// animate to show contentView
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.4, options: .curveEaseIn, animations: {
self.contentView.frame = CGRect(x: 0,
y: self.frame.height - self.contentHeight,
width: self.frame.width,
height: self.contentHeight)
}, completion: nil)
}
// MARK: - Helper Functions
func setToday() {
selectedDate = Date()
resetTime()
}
func resetTime() {
components = calendar.dateComponents([.day, .month, .year, .hour, .minute], from: selectedDate)
updateCollectionView(to: selectedDate)
if let hour = components.hour {
hourTableView.selectRow(at: IndexPath(row: hour + 24, section: 0), animated: true, scrollPosition: .middle)
}
if let minute = components.minute {
let expectedRow = minute == 0 ? (120 / timeInterval) : ((minute + 60) / timeInterval) // workaround for issue when minute = 0
minuteTableView.selectRow(at: IndexPath(row: expectedRow, section: 0), animated: true, scrollPosition: .middle)
}
}
func resetDateTitle() {
guard dateTitleLabel != nil else {
return
}
let formatter = DateFormatter()
formatter.dateFormat = dateFormat
dateTitleLabel.text = formatter.string(from: selectedDate)
dateTitleLabel.sizeToFit()
dateTitleLabel.center = CGPoint(x: contentView.frame.width / 2, y: 22)
}
func fillDates(fromDate: Date, toDate: Date) {
var dates: [Date] = []
var days = DateComponents()
var dayCount = 0
repeat {
days.day = dayCount
dayCount += 1
guard let date = calendar.date(byAdding: days, to: fromDate) else {
break;
}
if date.compare(toDate) == .orderedDescending {
break
}
dates.append(date)
} while (true)
self.dates = dates
dayCollectionView.reloadData()
if let index = self.dates.index(of: selectedDate) {
dayCollectionView.selectItem(at: IndexPath(row: index, section: 0), animated: true, scrollPosition: .centeredHorizontally)
}
}
func updateCollectionView(to currentDate: Date) {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/YYYY"
for i in 0..<dates.count {
let date = dates[i]
if formatter.string(from: date) == formatter.string(from: currentDate) {
let indexPath = IndexPath(row: i, section: 0)
dayCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
self.dayCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
})
break
}
}
}
func dismissView() {
UIView.animate(withDuration: 0.3, animations: {
// animate to show contentView
self.contentView.frame = CGRect(x: 0,
y: self.frame.height,
width: self.frame.width,
height: self.contentHeight)
}) { (completed) in
self.completionHandler?(self.selectedDate)
self.removeFromSuperview()
}
}
}
extension DateTimePicker: UITableViewDataSource, UITableViewDelegate {
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableView == hourTableView ? 24 * 3 : 60 * 3 // 3 times to ensure infinite scrolling
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "timeCell") ?? UITableViewCell(style: .default, reuseIdentifier: "timeCell")
cell.selectedBackgroundView = UIView()
cell.textLabel?.textAlignment = tableView == hourTableView ? .right : .left
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
cell.textLabel?.textColor = darkColor.withAlphaComponent(0.4)
cell.textLabel?.highlightedTextColor = highlightColor
// add module operation to set value same
cell.textLabel?.text = String(format: "%02i", (tableView == hourTableView ? (indexPath.row % 24) : (indexPath.row * timeInterval) % 60))
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
if tableView == hourTableView {
components.hour = (indexPath.row - 24) % 24
} else if tableView == minuteTableView {
components.minute = (indexPath.row - (60 / timeInterval)) % (60 / timeInterval)
}
if let selected = calendar.date(from: components) {
selectedDate = selected
}
}
// for infinite scrolling, use modulo operation.
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard scrollView != dayCollectionView else { return }
let totalHeight = scrollView.contentSize.height
let visibleHeight = totalHeight / 3.0
if scrollView.contentOffset.y < visibleHeight || scrollView.contentOffset.y > visibleHeight + visibleHeight {
let positionValueLoss = scrollView.contentOffset.y - CGFloat(Int(scrollView.contentOffset.y))
let heightValueLoss = visibleHeight - CGFloat(Int(visibleHeight))
let modifiedPotisionY = CGFloat(Int( scrollView.contentOffset.y ) % Int( visibleHeight ) + Int( visibleHeight )) - positionValueLoss - heightValueLoss
scrollView.contentOffset.y = modifiedPotisionY
}
}
}
extension DateTimePicker: UICollectionViewDataSource, UICollectionViewDelegate {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dates.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dateCell", for: indexPath) as! DateCollectionViewCell
let date = dates[indexPath.item]
cell.populateItem(date: date, highlightColor: highlightColor, darkColor: darkColor)
return cell
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// workaround to center to every cell including ones near margins
if let cell = collectionView.cellForItem(at: indexPath) {
let offset = CGPoint(x: cell.center.x - collectionView.frame.width / 2, y: 0)
collectionView.setContentOffset(offset, animated: true)
}
// update selected dates
let date = dates[indexPath.item]
let dayComponent = calendar.dateComponents([.day, .month, .year], from: date)
components.day = dayComponent.day
components.month = dayComponent.month
components.year = dayComponent.year
if let selected = calendar.date(from: components) {
selectedDate = selected
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
alignScrollView(scrollView)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
alignScrollView(scrollView)
}
}
func alignScrollView(_ scrollView: UIScrollView) {
if let collectionView = scrollView as? UICollectionView {
let centerPoint = CGPoint(x: collectionView.center.x + collectionView.contentOffset.x, y: 50);
if let indexPath = collectionView.indexPathForItem(at: centerPoint) {
// automatically select this item and center it to the screen
// set animated = false to avoid unwanted effects
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .top)
if let cell = collectionView.cellForItem(at: indexPath) {
let offset = CGPoint(x: cell.center.x - collectionView.frame.width / 2, y: 0)
collectionView.setContentOffset(offset, animated: false)
}
// update selected date
let date = dates[indexPath.item]
let dayComponent = calendar.dateComponents([.day, .month, .year], from: date)
components.day = dayComponent.day
components.month = dayComponent.month
components.year = dayComponent.year
if let selected = calendar.date(from: components) {
selectedDate = selected
}
}
} else if let tableView = scrollView as? UITableView {
let relativeOffset = CGPoint(x: 0, y: tableView.contentOffset.y + tableView.contentInset.top )
// change row from var to let.
let row = round(relativeOffset.y / tableView.rowHeight)
tableView.selectRow(at: IndexPath(row: Int(row), section: 0), animated: true, scrollPosition: .middle)
// add 24 to hour and 60 to minute, because datasource now has buffer at top and bottom.
if tableView == hourTableView {
components.hour = Int(row - 24)%24
} else if tableView == minuteTableView {
components.minute = Int(row - CGFloat(60 / timeInterval)) % (60 / timeInterval)
}
if let selected = calendar.date(from: components) {
selectedDate = selected
}
}
}
}
|
dc80009556a92cff2471012ae0267727
| 39.754358 | 208 | 0.620431 | false | false | false | false |
edx/edx-app-ios
|
refs/heads/master
|
Source/CourseUpgradeHandler.swift
|
apache-2.0
|
1
|
//
// CourseUpgradeHandler.swift
// edX
//
// Created by Saeed Bashir on 8/16/21.
// Copyright © 2021 edX. All rights reserved.
//
import Foundation
class CourseUpgradeHandler: NSObject {
enum CourseUpgradeState {
case initial
case basket
case checkout
case payment
case verify
case complete
case error(PurchaseError)
}
typealias Environment = OEXAnalyticsProvider & OEXConfigProvider & NetworkManagerProvider & ReachabilityProvider & OEXInterfaceProvider
typealias UpgradeCompletionHandler = (CourseUpgradeState) -> Void
private var environment: Environment? = nil
private var completion: UpgradeCompletionHandler?
private var course: OEXCourse?
private var basketID: Int = 0
private var courseSku: String = ""
private var state: CourseUpgradeState = .initial {
didSet {
completion?(state)
}
}
static let shared = CourseUpgradeHandler()
func upgradeCourse(_ course: OEXCourse, environment: Environment, completion: UpgradeCompletionHandler?) {
self.completion = completion
self.environment = environment
self.course = course
state = .initial
guard let coursePurchaseSku = UpgradeSKUManager.shared.courseSku(for: course) else {
state = .error(.generalError)
return
}
courseSku = coursePurchaseSku
addToBasket { [weak self] orderBasket in
if let basketID = orderBasket?.basketID {
self?.basketID = basketID
self?.checkout()
} else {
self?.state = .error(.basketError)
}
}
}
func upgradeCourse(_ courseID: String, environment: Environment, completion: UpgradeCompletionHandler?) {
guard let course = environment.interface?.enrollmentForCourse(withID: courseID)?.course else {
state = .error(.generalError)
return
}
upgradeCourse(course, environment: environment, completion: completion)
}
private func addToBasket(completion: @escaping (OrderBasket?) -> ()) {
state = .basket
let baseURL = CourseUpgradeAPI.baseURL
let request = CourseUpgradeAPI.basketAPI(with: courseSku)
environment?.networkManager.taskForRequest(base: baseURL, request) { response in
completion(response.data)
}
}
private func checkout() {
// Checkout API
// Perform the inapp purchase on success
guard basketID > 0 else {
state = .error(.checkoutError)
return
}
state = .checkout
let baseURL = CourseUpgradeAPI.baseURL
let request = CourseUpgradeAPI.checkoutAPI(basketID: basketID)
environment?.networkManager.taskForRequest(base: baseURL, request) { [weak self] response in
if response.error == nil {
self?.makePayment()
} else {
self?.state = .error(.checkoutError)
}
}
}
private func makePayment() {
state = .payment
PaymentManager.shared.purchaseProduct(courseSku) { [weak self] (success: Bool, receipt: String?, error: PurchaseError?) in
if let receipt = receipt, success {
self?.verifyPayment(receipt)
} else {
self?.state = .error(error ?? .paymentError)
}
}
}
private func verifyPayment(_ receipt: String) {
state = .verify
// Execute API, pass the payment receipt to complete the course upgrade
let baseURL = CourseUpgradeAPI.baseURL
let request = CourseUpgradeAPI.executeAPI(basketID: basketID, productID: courseSku, receipt: receipt)
environment?.networkManager.taskForRequest(base: baseURL, request){ [weak self] response in
if response.error == nil {
PaymentManager.shared.markPurchaseComplete(self?.course?.course_id ?? "", type: .purchase)
self?.state = .complete
} else {
self?.state = .error(.verifyReceiptError)
}
}
}
}
|
b0cb866e998cfabe7b0aaa3a4a0605fc
| 31.719697 | 139 | 0.594582 | false | false | false | false |
rudkx/swift
|
refs/heads/main
|
test/Interop/Cxx/stdlib/use-std-vector.swift
|
apache-2.0
|
1
|
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop)
//
// REQUIRES: executable_test
//
// Enable this everywhere once we have a solution for modularizing libstdc++: rdar://87654514
// REQUIRES: OS=macosx
import StdlibUnittest
import StdVector
import std.vector
var StdVectorTestSuite = TestSuite("StdVector")
extension Vector : RandomAccessCollection {
public var startIndex: Int { 0 }
public var endIndex: Int { size() }
}
StdVectorTestSuite.test("init") {
let v = Vector()
expectEqual(v.size(), 0)
expectTrue(v.empty())
}
StdVectorTestSuite.test("push back") {
var v = Vector()
var _42: CInt = 42
v.push_back(&_42)
expectEqual(v.size(), 1)
expectFalse(v.empty())
expectEqual(v[0], 42)
}
func fill(vector v: inout Vector) {
var _1: CInt = 1, _2: CInt = 2, _3: CInt = 3
v.push_back(&_1)
v.push_back(&_2)
v.push_back(&_3)
}
// TODO: in some configurations the stdlib emits a "initializeWithCopy" where the arguments
// have incorrect indirection: rdar://87728422 and rdar://87805795
// StdVectorTestSuite.test("for loop") {
// var v = Vector()
// fill(vector: &v)
//
// var count: CInt = 1
// for e in v {
// expectEqual(e, count)
// count += 1
// }
// expectEqual(count, 4)
// }
StdVectorTestSuite.test("map") {
var v = Vector()
fill(vector: &v)
let a = v.map { $0 + 5 }
expectEqual(a, [6, 7, 8])
}
runAllTests()
|
4246f7cec7760c8f548ea572f93ecb73
| 22.190476 | 93 | 0.625599 | false | true | false | false |
lquigley/Game
|
refs/heads/master
|
Game/Game/SpriteKit/Nodes/SKYBaddie.swift
|
mit
|
1
|
//
// SKYBaddie.swift
// Sky High
//
// Created by Luke Quigley on 2/20/15.
// Copyright (c) 2015 VOKAL. All rights reserved.
//
import SpriteKit
enum SKYBaddieDirection : Int {
case Left
case Right
}
class SKYBaddie: SKSpriteNode {
var direction:SKYBaddieDirection!
override init(texture: SKTexture!, color: UIColor!, size: CGSize) {
super.init(texture: texture, color: color, size: size)
self.name = "BadNode"
let intDirection = arc4random_uniform(2)
switch intDirection {
case 0:
direction = SKYBaddieDirection.Left
break
default:
direction = SKYBaddieDirection.Right
break
}
self.physicsBody = SKPhysicsBody(circleOfRadius: CGRectGetWidth(self.frame) / 2)
self.physicsBody!.allowsRotation = true
self.physicsBody!.density = 400
self.physicsBody!.categoryBitMask = 0x3
self.physicsBody!.collisionBitMask = 0x1
}
var velocity:CGFloat {
get {
return 0
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
f7baded841efc6180cf5e410ae1223e1
| 21.773585 | 88 | 0.589892 | false | false | false | false |
dnevera/IMProcessing
|
refs/heads/master
|
IMPTests/IMPGeometryTest/IMPlaygrounds/IMPGeometry.playground/Pages/Lookup.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import Foundation
import Accelerate
import simd
public extension Float {
public func lerp(final final:Float, t:Float) -> Float {
return (1-t)*self + t*final
}
}
func sample(value value:Float, table:[Float], start:Int) -> Float{
var x:Float = 0
var y:Float = 1
let v = table[start]
if abs(v - value) <= 1e-4 {
return v
}
if v < value {
for i in start..<table.count {
let nv = table[i]
if abs(value - nv) <= 1e-6 {
return value
}
else if nv > value {
y = nv
break
}
x = nv
}
}
else {
for i in start.stride(to: 0, by: -1) {
let nv = table[i]
if abs(value - nv) <= 1e-6 {
return value
}
else if nv < value {
x = nv
break
}
y = nv
}
}
return x.lerp(final: y, t: value)
}
sample(value: 0.01, table: [Float](arrayLiteral: 0, 0.1, 0.3, 0.6, 0.7, 1), start: 2)
|
51a82899af59f813521d699ded3424e7
| 19.163934 | 85 | 0.4 | false | false | false | false |
rechsteiner/Parchment
|
refs/heads/main
|
Parchment/Classes/PagingCollectionViewLayout.swift
|
mit
|
1
|
import UIKit
/// A custom `UICollectionViewLayout` subclass responsible for
/// defining the layout for all the `PagingItem` cells. You can
/// subclass this type if you need further customization outside what
/// is provided by customization properties on `PagingViewController`.
///
/// To create your own `PagingViewControllerLayout` you need to
/// override the `menuLayoutClass` property on `PagingViewController`.
/// Then you can override the methods you normally would to update the
/// layout attributes for each cell.
///
/// The layout has two decoration views; one for the border at the
/// bottom and one for the view that indicates the currently selected
/// `PagingItem`. You can customize their layout attributes by
/// updating the `indicatorLayoutAttributes` and
/// `borderLayoutAttributes` properties.
open class PagingCollectionViewLayout: UICollectionViewLayout, PagingLayout {
// MARK: Public Properties
/// An instance that stores all the customization that is applied
/// to the `PagingViewController`.
public var options = PagingOptions() {
didSet {
optionsChanged(oldValue: oldValue)
}
}
/// The current state of the menu items. Indicates whether an item
/// is currently selected or is scrolling to another item. Can be
/// used to get the distance and progress of any ongoing transition.
public var state: PagingState = .empty
/// The `PagingItem`'s that are currently visible in the collection
/// view. The items in this array are not necessarily the same as
/// the `visibleCells` property on `UICollectionView`.
public var visibleItems = PagingItems(items: [])
/// A dictionary containing all the layout attributes for a given
/// `IndexPath`. This will be generated in the `prepare()` call when
/// the layout is invalidated with the correct invalidation context.
public private(set) var layoutAttributes: [IndexPath: PagingCellLayoutAttributes] = [:]
/// The layout attributes for the selected item indicator. This is
/// updated whenever the layout is invalidated.
public private(set) var indicatorLayoutAttributes: PagingIndicatorLayoutAttributes?
/// The layout attributes for the bottom border view. This is
/// updated whenever the layout is invalidated.
public private(set) var borderLayoutAttributes: PagingBorderLayoutAttributes?
/// The `InvalidatedState` is used to represent what to invalidate
/// in a collection view layout based on the invalidation context.
public var invalidationState: InvalidationState = .everything
open override var collectionViewContentSize: CGSize {
return contentSize
}
open override class var layoutAttributesClass: AnyClass {
return PagingCellLayoutAttributes.self
}
open override var flipsHorizontallyInOppositeLayoutDirection: Bool {
return true
}
// MARK: Initializers
public required override init() {
super.init()
configure()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
// MARK: Internal Properties
internal var sizeCache: PagingSizeCache?
// MARK: Private Properties
private var view: UICollectionView {
return collectionView!
}
private var range: Range<Int> {
return 0 ..< view.numberOfItems(inSection: 0)
}
private var adjustedMenuInsets: UIEdgeInsets {
return UIEdgeInsets(
top: options.menuInsets.top,
left: options.menuInsets.left + safeAreaInsets.left,
bottom: options.menuInsets.bottom,
right: options.menuInsets.right + safeAreaInsets.right
)
}
private var safeAreaInsets: UIEdgeInsets {
if options.includeSafeAreaInsets, #available(iOS 11.0, *) {
return view.safeAreaInsets
} else {
return .zero
}
}
/// Cache used to store the preferred item size for each self-sizing
/// cell. PagingItem identifier is used as the key.
private var preferredSizeCache: [Int: CGFloat] = [:]
private(set) var contentInsets: UIEdgeInsets = .zero
private var contentSize: CGSize = .zero
private let PagingIndicatorKind = "PagingIndicatorKind"
private let PagingBorderKind = "PagingBorderKind"
// MARK: Public Methods
open override func prepare() {
super.prepare()
switch invalidationState {
case .everything:
layoutAttributes = [:]
borderLayoutAttributes = nil
indicatorLayoutAttributes = nil
createLayoutAttributes()
createDecorationLayoutAttributes()
case .sizes:
layoutAttributes = [:]
createLayoutAttributes()
case .nothing:
break
}
updateBorderLayoutAttributes()
updateIndicatorLayoutAttributes()
invalidationState = .nothing
}
open override func invalidateLayout() {
super.invalidateLayout()
invalidationState = .everything
}
open override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) {
super.invalidateLayout(with: context)
invalidationState = invalidationState + InvalidationState(context)
}
open override func invalidationContext(forPreferredLayoutAttributes _: UICollectionViewLayoutAttributes, withOriginalAttributes _: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutInvalidationContext {
let context = PagingInvalidationContext()
context.invalidateSizes = true
return context
}
open override func shouldInvalidateLayout(forPreferredLayoutAttributes preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> Bool {
switch options.menuItemSize {
// Invalidate the layout and update the layout attributes with the
// preferred width for each cell. The preferred size is based on
// the layout constraints in each cell.
case .selfSizing where originalAttributes is PagingCellLayoutAttributes:
if preferredAttributes.frame.width != originalAttributes.frame.width {
let pagingItem = visibleItems.pagingItem(for: originalAttributes.indexPath)
preferredSizeCache[pagingItem.identifier] = preferredAttributes.frame.width
return true
}
return false
default:
return false
}
}
open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let layoutAttributes = self.layoutAttributes[indexPath] else { return nil }
layoutAttributes.progress = progressForItem(at: layoutAttributes.indexPath)
return layoutAttributes
}
open override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
switch elementKind {
case PagingIndicatorKind:
return indicatorLayoutAttributes
case PagingBorderKind:
return borderLayoutAttributes
default:
return super.layoutAttributesForDecorationView(ofKind: elementKind, at: indexPath)
}
}
open override func layoutAttributesForElements(in _: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes: [UICollectionViewLayoutAttributes] = Array(self.layoutAttributes.values)
for attributes in layoutAttributes {
if let pagingAttributes = attributes as? PagingCellLayoutAttributes {
pagingAttributes.progress = progressForItem(at: attributes.indexPath)
}
}
let indicatorAttributes = layoutAttributesForDecorationView(
ofKind: PagingIndicatorKind,
at: IndexPath(item: 0, section: 0)
)
let borderAttributes = layoutAttributesForDecorationView(
ofKind: PagingBorderKind,
at: IndexPath(item: 1, section: 0)
)
if let indicatorAttributes = indicatorAttributes {
layoutAttributes.append(indicatorAttributes)
}
if let borderAttributes = borderAttributes {
layoutAttributes.append(borderAttributes)
}
return layoutAttributes
}
// MARK: Private Methods
private func optionsChanged(oldValue: PagingOptions) {
var shouldInvalidateLayout: Bool = false
if options.borderClass != oldValue.borderClass {
registerBorderClass()
shouldInvalidateLayout = true
}
if options.indicatorClass != oldValue.indicatorClass {
registerIndicatorClass()
shouldInvalidateLayout = true
}
if options.borderColor != oldValue.borderColor {
shouldInvalidateLayout = true
}
if options.indicatorColor != oldValue.indicatorColor {
shouldInvalidateLayout = true
}
if shouldInvalidateLayout {
invalidateLayout()
}
}
private func configure() {
registerBorderClass()
registerIndicatorClass()
}
private func registerIndicatorClass() {
register(options.indicatorClass, forDecorationViewOfKind: PagingIndicatorKind)
}
private func registerBorderClass() {
register(options.borderClass, forDecorationViewOfKind: PagingBorderKind)
}
private func createLayoutAttributes() {
guard let sizeCache = sizeCache else { return }
var layoutAttributes: [IndexPath: PagingCellLayoutAttributes] = [:]
var previousFrame: CGRect = .zero
previousFrame.origin.x = adjustedMenuInsets.left - options.menuItemSpacing
for index in 0 ..< view.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: index, section: 0)
let attributes = PagingCellLayoutAttributes(forCellWith: indexPath)
let x = previousFrame.maxX + options.menuItemSpacing
let y = adjustedMenuInsets.top
let pagingItem = visibleItems.pagingItem(for: indexPath)
if sizeCache.implementsSizeDelegate {
var width = sizeCache.itemSize(for: pagingItem)
let selectedWidth = sizeCache.itemWidthSelected(for: pagingItem)
if let currentPagingItem = state.currentPagingItem, currentPagingItem.isEqual(to: pagingItem) {
width = tween(from: selectedWidth, to: width, progress: abs(state.progress))
} else if let upcomingPagingItem = state.upcomingPagingItem, upcomingPagingItem.isEqual(to: pagingItem) {
width = tween(from: width, to: selectedWidth, progress: abs(state.progress))
}
attributes.frame = CGRect(x: x, y: y, width: width, height: options.menuItemSize.height)
} else {
switch options.menuItemSize {
case let .fixed(width, height):
attributes.frame = CGRect(x: x, y: y, width: width, height: height)
case let .sizeToFit(minWidth, height):
attributes.frame = CGRect(x: x, y: y, width: minWidth, height: height)
case let .selfSizing(estimatedWidth, height):
if let actualWidth = preferredSizeCache[pagingItem.identifier] {
attributes.frame = CGRect(x: x, y: y, width: actualWidth, height: height)
} else {
attributes.frame = CGRect(x: x, y: y, width: estimatedWidth, height: height)
}
}
}
previousFrame = attributes.frame
layoutAttributes[indexPath] = attributes
}
// When the menu items all can fit inside the bounds we need to
// reposition the items based on the current options
if previousFrame.maxX - adjustedMenuInsets.left < view.bounds.width {
switch options.menuItemSize {
case let .sizeToFit(_, height) where sizeCache.implementsSizeDelegate == false:
let insets = adjustedMenuInsets.left + adjustedMenuInsets.right
let spacing = (options.menuItemSpacing * CGFloat(range.upperBound - 1))
let width = (view.bounds.width - insets - spacing) / CGFloat(range.upperBound)
previousFrame = .zero
previousFrame.origin.x = adjustedMenuInsets.left - options.menuItemSpacing
for attributes in layoutAttributes.values.sorted(by: { $0.indexPath < $1.indexPath }) {
let x = previousFrame.maxX + options.menuItemSpacing
let y = adjustedMenuInsets.top
attributes.frame = CGRect(x: x, y: y, width: width, height: height)
previousFrame = attributes.frame
}
// When using sizeToFit the content will always be as wide as
// the bounds so there is not possible to center the items. In
// all the other cases we want to center them if the menu
// alignment is set to .center
default:
if case .center = options.menuHorizontalAlignment {
// Subtract the menu insets as they should not have an effect on
// whether or not we should center the items.
let offset = (view.bounds.width - previousFrame.maxX - adjustedMenuInsets.left) / 2
for attributes in layoutAttributes.values {
attributes.frame = attributes.frame.offsetBy(dx: offset, dy: 0)
}
}
}
}
if case .center = options.selectedScrollPosition {
let attributes = layoutAttributes.values.sorted(by: { $0.indexPath < $1.indexPath })
if let first = attributes.first, let last = attributes.last {
let insetLeft = (view.bounds.width / 2) - (first.bounds.width / 2)
let insetRight = (view.bounds.width / 2) - (last.bounds.width / 2)
for attributes in layoutAttributes.values {
attributes.frame = attributes.frame.offsetBy(dx: insetLeft, dy: 0)
}
contentInsets = UIEdgeInsets(
top: 0,
left: insetLeft + adjustedMenuInsets.left,
bottom: 0,
right: insetRight + adjustedMenuInsets.right
)
contentSize = CGSize(
width: previousFrame.maxX + insetLeft + insetRight + adjustedMenuInsets.right,
height: view.bounds.height
)
}
} else {
contentInsets = adjustedMenuInsets
contentSize = CGSize(
width: previousFrame.maxX + adjustedMenuInsets.right,
height: view.bounds.height
)
}
self.layoutAttributes = layoutAttributes
}
private func createDecorationLayoutAttributes() {
if case .visible = options.indicatorOptions {
indicatorLayoutAttributes = PagingIndicatorLayoutAttributes(
forDecorationViewOfKind: PagingIndicatorKind,
with: IndexPath(item: 0, section: 0)
)
}
if case .visible = options.borderOptions {
borderLayoutAttributes = PagingBorderLayoutAttributes(
forDecorationViewOfKind: PagingBorderKind,
with: IndexPath(item: 1, section: 0)
)
}
}
private func updateBorderLayoutAttributes() {
borderLayoutAttributes?.configure(options)
borderLayoutAttributes?.update(
contentSize: collectionViewContentSize,
bounds: collectionView?.bounds ?? .zero,
safeAreaInsets: safeAreaInsets
)
}
private func updateIndicatorLayoutAttributes() {
guard let currentPagingItem = state.currentPagingItem else { return }
indicatorLayoutAttributes?.configure(options)
let currentIndexPath = visibleItems.indexPath(for: currentPagingItem)
let upcomingIndexPath = upcomingIndexPathForIndexPath(currentIndexPath)
if let upcomingIndexPath = upcomingIndexPath {
let progress = abs(state.progress)
let to = PagingIndicatorMetric(
frame: indicatorFrameForIndex(upcomingIndexPath.item),
insets: indicatorInsetsForIndex(upcomingIndexPath.item),
spacing: indicatorSpacingForIndex(upcomingIndexPath.item)
)
if let currentIndexPath = currentIndexPath {
let from = PagingIndicatorMetric(
frame: indicatorFrameForIndex(currentIndexPath.item),
insets: indicatorInsetsForIndex(currentIndexPath.item),
spacing: indicatorSpacingForIndex(currentIndexPath.item)
)
indicatorLayoutAttributes?.update(from: from, to: to, progress: progress)
} else if let from = indicatorMetricForFirstItem() {
indicatorLayoutAttributes?.update(from: from, to: to, progress: progress)
} else if let from = indicatorMetricForLastItem() {
indicatorLayoutAttributes?.update(from: from, to: to, progress: progress)
}
} else if let metric = indicatorMetricForFirstItem() {
indicatorLayoutAttributes?.update(to: metric)
} else if let metric = indicatorMetricForLastItem() {
indicatorLayoutAttributes?.update(to: metric)
}
}
private func indicatorMetricForFirstItem() -> PagingIndicatorMetric? {
guard let currentPagingItem = state.currentPagingItem else { return nil }
if let first = visibleItems.items.first {
if currentPagingItem.isBefore(item: first) {
return PagingIndicatorMetric(
frame: indicatorFrameForIndex(-1),
insets: indicatorInsetsForIndex(-1),
spacing: indicatorSpacingForIndex(-1)
)
}
}
return nil
}
private func indicatorMetricForLastItem() -> PagingIndicatorMetric? {
guard let currentPagingItem = state.currentPagingItem else { return nil }
if let last = visibleItems.items.last {
if last.isBefore(item: currentPagingItem) {
return PagingIndicatorMetric(
frame: indicatorFrameForIndex(visibleItems.items.count),
insets: indicatorInsetsForIndex(visibleItems.items.count),
spacing: indicatorSpacingForIndex(visibleItems.items.count)
)
}
}
return nil
}
private func progressForItem(at indexPath: IndexPath) -> CGFloat {
guard let currentPagingItem = state.currentPagingItem else { return 0 }
let currentIndexPath = visibleItems.indexPath(for: currentPagingItem)
if let currentIndexPath = currentIndexPath {
if indexPath.item == currentIndexPath.item {
return 1 - abs(state.progress)
}
}
if let upcomingIndexPath = upcomingIndexPathForIndexPath(currentIndexPath) {
if indexPath.item == upcomingIndexPath.item {
return abs(state.progress)
}
}
return 0
}
private func upcomingIndexPathForIndexPath(_ indexPath: IndexPath?) -> IndexPath? {
if let upcomingPagingItem = state.upcomingPagingItem, let upcomingIndexPath = visibleItems.indexPath(for: upcomingPagingItem) {
return upcomingIndexPath
} else if let indexPath = indexPath {
if indexPath.item == range.lowerBound {
return IndexPath(item: indexPath.item - 1, section: 0)
} else if indexPath.item == range.upperBound - 1 {
return IndexPath(item: indexPath.item + 1, section: 0)
}
}
return indexPath
}
private func indicatorSpacingForIndex(_: Int) -> UIEdgeInsets {
if case let .visible(_, _, insets, _) = options.indicatorOptions {
return insets
}
return UIEdgeInsets.zero
}
private func indicatorInsetsForIndex(_ index: Int) -> PagingIndicatorMetric.Inset {
if case let .visible(_, _, _, insets) = options.indicatorOptions {
if index == 0, range.upperBound == 1 {
return .both(insets.left, insets.right)
} else if index == range.lowerBound {
return .left(insets.left)
} else if index >= range.upperBound - 1 {
return .right(insets.right)
}
}
return .none
}
private func indicatorFrameForIndex(_ index: Int) -> CGRect {
if index < range.lowerBound {
let frame = frameForIndex(0)
return frame.offsetBy(dx: -frame.width, dy: 0)
} else if index > range.upperBound - 1 {
let frame = frameForIndex(visibleItems.items.count - 1)
return frame.offsetBy(dx: frame.width, dy: 0)
}
return frameForIndex(index)
}
private func frameForIndex(_ index: Int) -> CGRect {
guard
let sizeCache = sizeCache,
let attributes = layoutAttributes[IndexPath(item: index, section: 0)] else { return .zero }
var frame = CGRect(
x: attributes.center.x - attributes.bounds.midX,
y: attributes.center.y - attributes.bounds.midY,
width: attributes.bounds.width,
height: attributes.bounds.height
)
if sizeCache.implementsSizeDelegate {
let indexPath = IndexPath(item: index, section: 0)
let pagingItem = visibleItems.pagingItem(for: indexPath)
if let upcomingPagingItem = state.upcomingPagingItem, let currentPagingItem = state.currentPagingItem {
if upcomingPagingItem.isEqual(to: pagingItem) || currentPagingItem.isEqual(to: pagingItem) {
frame.size.width = sizeCache.itemWidthSelected(for: pagingItem)
}
}
}
return frame
}
}
|
8b317e9044582fa3d5f4de989c6e7058
| 39.284173 | 216 | 0.634208 | false | false | false | false |
taketo1024/SwiftyAlgebra
|
refs/heads/develop
|
Sources/SwmCore/Matrix/MatrixIF.swift
|
cc0-1.0
|
1
|
//
// MatrixInterafce.swift
//
//
// Created by Taketo Sano.
//
public typealias ColVectorIF<Impl: MatrixImpl, n: SizeType> = MatrixIF<Impl, n, _1>
public typealias RowVectorIF<Impl: MatrixImpl, m: SizeType> = MatrixIF<Impl, _1, m>
public typealias AnySizeMatrixIF<Impl: MatrixImpl> = MatrixIF<Impl, anySize, anySize>
public typealias AnySizeColVectorIF<Impl: MatrixImpl> = ColVectorIF<Impl, anySize>
public typealias AnySizeRowVectorIF<Impl: MatrixImpl> = RowVectorIF<Impl, anySize>
public struct MatrixIF<Impl: MatrixImpl, n: SizeType, m: SizeType>: MathSet {
public typealias BaseRing = Impl.BaseRing
public typealias Initializer = Impl.Initializer
public var impl: Impl
public init(_ impl: Impl) {
assert(n.isArbitrary || n.intValue == impl.size.rows)
assert(m.isArbitrary || m.intValue == impl.size.cols)
self.impl = impl
}
@inlinable
public init(size: MatrixSize, initializer: ( (Int, Int, BaseRing) -> Void ) -> Void) {
self.init(Impl(size: size, initializer: initializer))
}
@inlinable
public init<S: Sequence>(size: MatrixSize, grid: S) where S.Element == BaseRing {
self.init(Impl(size: size, grid: grid))
}
@inlinable
public init<S: Sequence>(size: MatrixSize, entries: S) where S.Element == MatrixEntry<BaseRing> {
self.init(Impl(size: size, entries: entries))
}
@inlinable
public static func zero(size: MatrixSize) -> Self {
self.init(Impl.zero(size: size))
}
@inlinable
public static func identity(size: MatrixSize) -> Self {
self.init(Impl.identity(size: size))
}
@inlinable
public static func unit(size: MatrixSize, at: (Int, Int)) -> Self {
self.init(Impl.unit(size: size, at: at))
}
@inlinable
public subscript(i: Int, j: Int) -> BaseRing {
get {
impl[i, j]
} set {
impl[i, j] = newValue
}
}
@inlinable
public subscript(rowRange: Range<Int>, colRange: Range<Int>) -> MatrixIF<Impl, anySize, anySize> {
self.submatrix(rowRange: rowRange, colRange: colRange)
}
@inlinable
public var size: (rows: Int, cols: Int) {
impl.size
}
@inlinable
public var isSquare: Bool {
size.rows == size.cols
}
@inlinable
public var isZero: Bool {
impl.isZero
}
@inlinable
public var isIdentity: Bool {
impl.isIdentity
}
@inlinable
public var transposed: MatrixIF<Impl, m, n> {
.init(impl.transposed)
}
@inlinable
public func rowVector(_ i: Int) -> MatrixIF<Impl, _1, m> {
.init(impl.rowVector(i))
}
@inlinable
public func colVector(_ j: Int) -> MatrixIF<Impl, n, _1> {
.init(impl.colVector(j))
}
@inlinable
public func submatrix(rowRange: CountableRange<Int>) -> MatrixIF<Impl, anySize, m> {
.init(impl.submatrix(rowRange: rowRange))
}
@inlinable
public func submatrix(colRange: CountableRange<Int>) -> MatrixIF<Impl, n, anySize> {
.init(impl.submatrix(colRange: colRange))
}
@inlinable
public func submatrix(rowRange: CountableRange<Int>, colRange: CountableRange<Int>) -> MatrixIF<Impl, anySize, anySize> {
.init(impl.submatrix(rowRange: rowRange, colRange: colRange))
}
@inlinable
public func concat<m1>(_ B: MatrixIF<Impl, n, m1>) -> MatrixIF<Impl, n, anySize> {
.init(impl.concat(B.impl))
}
@inlinable
public func stack<n1>(_ B: MatrixIF<Impl, n1, m>) -> MatrixIF<Impl, anySize, m> {
.init(impl.stack(B.impl))
}
@inlinable
public func permuteRows(by p: Permutation<n>) -> Self {
.init(impl.permuteRows(by: p.asAnySize))
}
@inlinable
public func permuteCols(by q: Permutation<m>) -> Self {
.init(impl.permuteCols(by: q.asAnySize))
}
@inlinable
public func permute(rowsBy p: Permutation<n>, colsBy q: Permutation<m>) -> Self {
.init(impl.permute(rowsBy: p.asAnySize, colsBy: q.asAnySize))
}
@inlinable
public func serialize() -> [BaseRing] {
impl.serialize()
}
@inlinable
public static func ==(a: Self, b: Self) -> Bool {
a.impl == b.impl
}
@inlinable
public static func +(a: Self, b: Self) -> Self {
.init(a.impl + b.impl)
}
@inlinable
public prefix static func -(a: Self) -> Self {
.init(-a.impl)
}
@inlinable
public static func -(a: Self, b: Self) -> Self {
.init(a.impl - b.impl)
}
@inlinable
public static func *(r: BaseRing, a: Self) -> Self {
.init(r * a.impl)
}
@inlinable
public static func *(a: Self, r: BaseRing) -> Self {
.init(a.impl * r)
}
@inlinable
public static func * <p>(a: MatrixIF<Impl, n, m>, b: MatrixIF<Impl, m, p>) -> MatrixIF<Impl, n, p> {
.init(a.impl * b.impl)
}
@inlinable
public static func ⊕ <n1, m1>(A: MatrixIF<Impl, n, m>, B: MatrixIF<Impl, n1, m1>) -> MatrixIF<Impl, anySize, anySize> {
.init(A.impl ⊕ B.impl)
}
@inlinable
public static func ⊗ <n1, m1>(A: MatrixIF<Impl, n, m>, B: MatrixIF<Impl, n1, m1>) -> MatrixIF<Impl, anySize, anySize> {
.init(A.impl ⊗ B.impl)
}
@inlinable
public static func *(p: Permutation<n>, a: Self) -> Self {
a.permuteRows(by: p)
}
@inlinable
public static func *(a: Self, p: Permutation<m>) -> Self {
a.permuteCols(by: p)
}
@inlinable
public func `as`<n1, m1>(_ type: MatrixIF<Impl, n1, m1>.Type) -> MatrixIF<Impl, n1, m1> {
MatrixIF<Impl, n1, m1>(impl)
}
@inlinable
public var asAnySizeMatrix: AnySizeMatrixIF<Impl> {
`as`(AnySizeMatrixIF.self)
}
@inlinable
public func convert<OtherImpl, n1, m1>(to type: MatrixIF<OtherImpl, n1, m1>.Type) -> MatrixIF<OtherImpl, n1, m1>
where OtherImpl.BaseRing == BaseRing {
.init(OtherImpl.init(size: size, entries: nonZeroEntries))
}
@inlinable
public var nonZeroEntries: AnySequence<MatrixEntry<BaseRing>> {
impl.nonZeroEntries
}
@inlinable
public func mapNonZeroEntries(_ f: @escaping (Int, Int, BaseRing) -> BaseRing) -> Self {
.init(impl.mapNonZeroEntries(f))
}
@inlinable
public var description: String {
impl.description
}
@inlinable
public var detailDescription: String {
impl.detailDescription
}
public static var symbol: String {
func str(_ t: SizeType.Type) -> String {
t.isFixed ? "\(t.intValue)" : "any"
}
if m.intValue == 1 {
return "ColVec<\(BaseRing.symbol); \(str(n.self))>"
}
if n.intValue == 1 {
return "RowVec<\(BaseRing.symbol); \(str(n.self))>"
}
return "Mat<\(BaseRing.symbol); \(str(n.self)), \(str(n.self))>"
}
}
// MARK: Square Matrix
extension MatrixIF where n == m { // n, m: possibly anySize
@inlinable
public var isInvertible: Bool {
impl.isInvertible
}
@inlinable
public var inverse: Self? {
impl.inverse.flatMap{ .init($0) }
}
@inlinable
public var determinant: BaseRing {
impl.determinant
}
@inlinable
public var trace: BaseRing {
impl.trace
}
}
// MARK: ColVector
extension MatrixIF where m == _1 { // n: possibly anySize
public typealias ColInitializer = (Int, BaseRing) -> Void
public init(size n: Int, initializer s: @escaping (ColInitializer) -> Void) {
self.init(Impl(size: (n, 1)) { setEntry in
s { (i, a) in
setEntry(i, 0, a)
}
})
}
@inlinable
public init(size n: Int, grid: [BaseRing]) {
self.init(Impl.init(size: (n, 1), grid: grid))
}
@inlinable
public init<S: Sequence>(size n: Int, colEntries: S) where S.Element == ColEntry<BaseRing> {
self.init(size: (n, 1), entries: colEntries.map{ (i, a) in MatrixEntry(i, 0, a) })
}
@inlinable
public static func zero(size n: Int) -> Self {
.init(Impl.zero(size: (n, 1)))
}
@inlinable
public static func unit(size n: Int, at i: Int) -> Self {
.init(Impl.unit(size: (n, 1), at: (i, 0)))
}
@inlinable
public subscript(index: Int) -> BaseRing {
get {
self[index, 0]
} set {
self[index, 0] = newValue
}
}
@inlinable
public subscript(range: Range<Int>) -> MatrixIF<Impl, anySize, _1> {
submatrix(rowRange: range)
}
@inlinable
public static func •(_ left: Self, _ right: Self) -> BaseRing {
assert(left.size == right.size)
return (0 ..< left.size.rows).sum { i in left[i] * right[i] }
}
@inlinable
public var nonZeroColEntries: AnySequence<ColEntry<BaseRing>> {
AnySequence(nonZeroEntries.lazy.map{ (i, _, a) in (i, a)})
}
@inlinable
public var asAnySizeColVector: AnySizeColVectorIF<Impl> {
`as`(AnySizeColVectorIF.self)
}
}
// MARK: RowVector
extension MatrixIF where n == _1 { // m: possibly anySize
public typealias RowInitializer = (Int, BaseRing) -> Void
public init(size m: Int, initializer s: @escaping (RowInitializer) -> Void) {
self.init(Impl(size: (1, m)) { setEntry in
s { (j, a) in
setEntry(0, j, a)
}
})
}
@inlinable
public init(size m: Int, grid: [BaseRing]) {
self.init(Impl.init(size: (1, m), grid: grid))
}
@inlinable
public init<S: Sequence>(size m: Int, rowEntries: S) where S.Element == RowEntry<BaseRing> {
self.init(size: (1, m), entries: rowEntries.map{ (j, a) in MatrixEntry(0, j, a) })
}
@inlinable
public static func zero(size m: Int) -> Self {
.init(Impl.zero(size: (1, m)))
}
@inlinable
public static func unit(size m: Int, at j: Int) -> Self {
.init(Impl.unit(size: (1, m), at: (0, j)))
}
@inlinable
public subscript(index: Int) -> BaseRing {
get {
self[0, index]
} set {
self[0, index] = newValue
}
}
@inlinable
public subscript(range: Range<Int>) -> MatrixIF<Impl, _1, anySize> {
submatrix(colRange: range)
}
@inlinable
public static func •(_ left: Self, _ right: Self) -> BaseRing {
assert(left.size == right.size)
return (0 ..< left.size.rows).sum { i in left[i] * right[i] }
}
@inlinable
public var nonZeroRowEntries: AnySequence<RowEntry<BaseRing>> {
AnySequence(nonZeroEntries.lazy.map{ (_, j, a) in (j, a)})
}
@inlinable
public var asAnySizeRowVector: AnySizeRowVectorIF<Impl> {
`as`(AnySizeRowVectorIF.self)
}
}
// MARK: Fixed-size Matrix
extension MatrixIF: AdditiveGroup, Module, ExpressibleByArrayLiteral where n: FixedSizeType, m: FixedSizeType {
public typealias ArrayLiteralElement = BaseRing
@inlinable
public static var size: MatrixSize {
(n.intValue, m.intValue)
}
@inlinable
public init(initializer: @escaping (Initializer) -> Void) {
self.init(size: Self.size, initializer: initializer)
}
@inlinable
public init<S: Sequence>(grid: S) where S.Element == BaseRing {
self.init(size: Self.size, grid: grid)
}
@inlinable
public init<S: Sequence>(entries: S) where S.Element == MatrixEntry<BaseRing> {
self.init(size: Self.size, entries: entries)
}
@inlinable
public init(arrayLiteral elements: ArrayLiteralElement...) {
self.init(grid: elements)
}
@inlinable
public static var zero: Self {
.zero(size: Self.size)
}
@inlinable
public static var identity: Self {
.identity(size: Self.size)
}
@inlinable
public static func scalar(_ a: BaseRing) -> Self {
.init(Impl.scalar(size: Self.size, value: a))
}
@inlinable
public static func unit(_ i: Int, _ j: Int) -> Self {
.unit(size: Self.size, at: (i, j))
}
public static func diagonal(_ entries: BaseRing...) -> Self {
self.init { setEntry in
entries.enumerated().forEach { (i, a) in
setEntry(i, i, a)
}
}
}
}
// MARK: Fixed-size Square Matrix
extension MatrixIF: Multiplicative, Monoid, Ring where n == m, n: FixedSizeType {
@inlinable
public init(from a : 𝐙) {
self.init(Impl.scalar(size: Self.size, value: BaseRing.init(from: a)))
}
@inlinable
public var isInvertible: Bool {
impl.isInvertible
}
@inlinable
public var inverse: Self? {
impl.inverse.flatMap{ .init($0) }
}
@inlinable
public var determinant: BaseRing {
impl.determinant
}
@inlinable
public var trace: BaseRing {
impl.trace
}
}
// MARK: Fixed-size ColVector
extension MatrixIF where n: FixedSizeType, m == _1 {
public init(initializer s: @escaping (ColInitializer) -> Void) {
self.init { setEntry in
s { (i, a) in
setEntry(i, 0, a)
}
}
}
}
// MARK: Fixed-size RowVector
extension MatrixIF where n == _1, m: FixedSizeType {
public init(initializer s: @escaping (RowInitializer) -> Void) {
self.init { setEntry in
s { (j, a) in
setEntry(0, j, a)
}
}
}
}
// MARK: 1x1 Matrix
extension MatrixIF where n == m, n == _1 {
@inlinable
public var asScalar: BaseRing {
self[0, 0]
}
}
// MARK: Sparse Matrix
extension MatrixIF where Impl: SparseMatrixImpl {
@inlinable
public var numberOfNonZeros: Int {
impl.numberOfNonZeros
}
@inlinable
public var density: Double {
impl.density
}
}
// MARK: Random
extension MatrixIF where BaseRing: Randomable {
public static func random(size: MatrixSize) -> Self {
.init(size: size, grid: (0 ..< size.rows * size.cols).map{_ in .random() } )
}
}
extension MatrixIF where BaseRing: RangeRandomable {
public static func random(size: MatrixSize, in range: Range<BaseRing.RangeBound>) -> Self {
.init(size: size, grid: (0 ..< size.rows * size.cols).map{_ in .random(in: range) } )
}
public static func random(size: MatrixSize, in range: ClosedRange<BaseRing.RangeBound>) -> Self {
.init(size: size, grid: (0 ..< size.rows * size.cols).map{_ in .random(in: range) } )
}
}
extension MatrixIF: Randomable where BaseRing: Randomable, n: FixedSizeType, m: FixedSizeType {
public static func random() -> MatrixIF<Impl, n, m> {
random(size: Self.size)
}
}
extension MatrixIF: RangeRandomable where BaseRing: RangeRandomable, n: FixedSizeType, m: FixedSizeType {
public static func random(in range: Range<BaseRing.RangeBound>) -> Self {
random(size: Self.size, in: range)
}
public static func random(in range: ClosedRange<BaseRing.RangeBound>) -> Self {
random(size: Self.size, in: range)
}
}
|
0ec429706cbd4612ce636b03daa93231
| 25.827225 | 126 | 0.579951 | false | false | false | false |
spark/photon-tinker-ios
|
refs/heads/master
|
Photon-Tinker/Mesh/ControlPanel/Gen3SetupControlPanelWifiViewController.swift
|
apache-2.0
|
1
|
//
// Created by Raimundas Sakalauskas on 2019-03-15.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
class Gen3SetupControlPanelWifiViewController : Gen3SetupControlPanelRootViewController {
private let refreshControl = UIRefreshControl()
override var allowBack: Bool {
get {
return true
}
set {
super.allowBack = newValue
}
}
override var customTitle: String {
return Gen3SetupStrings.ControlPanel.Wifi.Title
}
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
tableView.addSubview(refreshControl)
}
refreshControl.tintColor = ParticleStyle.SecondaryTextColor
refreshControl.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged)
}
@objc private func refreshData(_ sender: Any) {
self.fadeContent(animated: true, showSpinner: false)
self.callback(.wifi)
}
override func resume(animated: Bool) {
self.prepareContent()
super.resume(animated: animated)
self.tableView.refreshControl?.endRefreshing()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.prepareContent()
self.tableView.reloadData()
}
override func prepareContent() {
if (self.context.targetDevice.wifiNetworkInfo != nil) {
cells = [[.wifiInfoSSID, .wifiInfoChannel, .wifiInfoRSSI], [.actionNewWifi, .actionManageWifi]]
} else {
cells = [[.wifiInfoSSID], [.actionNewWifi, .actionManageWifi]]
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return Gen3SetupStrings.ControlPanel.Wifi.NetworkInfo
default:
return ""
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
}
|
3db3b7a105509d6af74c481d884ba05d
| 26.225 | 107 | 0.632231 | false | false | false | false |
santosli/100-Days-of-Swift-3
|
refs/heads/master
|
Project 37/Project 37/SLCollectionViewController.swift
|
apache-2.0
|
1
|
//
// SLCollectionViewController.swift
// Project 37
//
// Created by Santos on 25/01/2017.
// Copyright © 2017 santos. All rights reserved.
//
import UIKit
private let reuseIdentifier = "imageCell"
class SLCollectionViewController: UICollectionViewController {
let segueIdetifier = "showLargeImage"
let imageCount = 8
let width = UIScreen.main.bounds.size.width
var sourceCell: UICollectionViewCell?
override func viewDidLoad() {
super.viewDidLoad()
//set up layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: width/2, height: width/2)
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView?.collectionViewLayout = layout
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.delegate = self
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return imageCount
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SLImageCollectionViewCell
cell.layer.borderWidth = 0.5
cell.layer.borderColor = UIColor(red:0.83, green:0.87, blue:0.92, alpha:1.00).cgColor
cell.imageView.backgroundColor = .white
cell.imageView.image = UIImage(named: String(indexPath.row + 1) + ".png")
return cell
}
}
extension SLCollectionViewController: UINavigationControllerDelegate {
//MARK: - Navigation
//In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == segueIdetifier, let destination = segue.destination as? SLImageViewController {
let cell = sender as! UICollectionViewCell
let indexPath = self.collectionView!.indexPath(for: cell)
destination.imageName = String((indexPath?.row)! + 1) + ".png"
sourceCell = cell
}
}
@IBAction func unwindToViewController (sender: UIStoryboardSegue){
}
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransitionManager(operation: operation)
}
}
|
7830df6610dcd15a885b8090ee15a550
| 33.155556 | 246 | 0.692258 | false | false | false | false |
871553223/TestGit
|
refs/heads/master
|
Carthage/Checkouts/Fx/Fx/Disposable.swift
|
apache-2.0
|
41
|
//
// Disposable.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
/// Represents something that can be “disposed,” usually associated with freeing
/// resources or canceling work.
public protocol Disposable: class {
/// Whether this disposable has been disposed already.
var disposed: Bool { get }
func dispose()
}
/// A disposable that only flips `disposed` upon disposal, and performs no other
/// work.
public final class SimpleDisposable: Disposable {
private let _disposed = Atomic(false)
public var disposed: Bool {
return _disposed.value
}
public init() {}
public func dispose() {
_disposed.value = true
}
}
/// A disposable that will run an action upon disposal.
public final class ActionDisposable: Disposable {
private let action: Atomic<(() -> ())?>
public var disposed: Bool {
return action.value == nil
}
/// Initializes the disposable to run the given action upon disposal.
public init(action: () -> ()) {
self.action = Atomic(action)
}
public func dispose() {
let oldAction = action.swap(nil)
oldAction?()
}
}
/// A disposable that will dispose of any number of other disposables.
public final class CompositeDisposable: Disposable {
private let disposables: Atomic<Bag<Disposable>?>
/// Represents a handle to a disposable previously added to a
/// CompositeDisposable.
public final class DisposableHandle {
private let bagToken: Atomic<RemovalToken?>
private weak var disposable: CompositeDisposable?
private static let empty = DisposableHandle()
private init() {
self.bagToken = Atomic(nil)
}
private init(bagToken: RemovalToken, disposable: CompositeDisposable) {
self.bagToken = Atomic(bagToken)
self.disposable = disposable
}
/// Removes the pointed-to disposable from its CompositeDisposable.
///
/// This is useful to minimize memory growth, by removing disposables
/// that are no longer needed.
public func remove() {
if let token = bagToken.swap(nil) {
disposable?.disposables.modify { bag in
guard let immutableBag = bag else { return nil }
var mutableBag = immutableBag
mutableBag.removeValueForToken(token)
return mutableBag
}
}
}
}
public var disposed: Bool {
return disposables.value == nil
}
/// Initializes a CompositeDisposable containing the given sequence of
/// disposables.
public init<S: SequenceType where S.Generator.Element == Disposable>(_ disposables: S) {
var bag: Bag<Disposable> = Bag()
for disposable in disposables {
bag.insert(disposable)
}
self.disposables = Atomic(bag)
}
/// Initializes an empty CompositeDisposable.
public convenience init() {
self.init([])
}
public func dispose() {
if let ds = disposables.swap(nil) {
for d in ds.reverse() {
d.dispose()
}
}
}
/// Adds the given disposable to the list, then returns a handle which can
/// be used to opaquely remove the disposable later (if desired).
public func addDisposable(d: Disposable?) -> DisposableHandle {
guard let d = d else {
return DisposableHandle.empty
}
var handle: DisposableHandle? = nil
disposables.modify { ds in
guard let immutableDs = ds else { return nil }
var mutableDs = immutableDs
let token = mutableDs.insert(d)
handle = DisposableHandle(bagToken: token, disposable: self)
return mutableDs
}
if let handle = handle {
return handle
} else {
d.dispose()
return DisposableHandle.empty
}
}
/// Adds an ActionDisposable to the list.
public func addDisposable(action: () -> ()) -> DisposableHandle {
return addDisposable(ActionDisposable(action: action))
}
}
/// A disposable that, upon deinitialization, will automatically dispose of
/// another disposable.
public final class ScopedDisposable: Disposable {
/// The disposable which will be disposed when the ScopedDisposable
/// deinitializes.
public let innerDisposable: Disposable
public var disposed: Bool {
return innerDisposable.disposed
}
/// Initializes the receiver to dispose of the argument upon
/// deinitialization.
public init(_ disposable: Disposable) {
innerDisposable = disposable
}
deinit {
dispose()
}
public func dispose() {
innerDisposable.dispose()
}
}
/// A disposable that will optionally dispose of another disposable.
public final class SerialDisposable: Disposable {
private struct State {
var innerDisposable: Disposable? = nil
var disposed = false
}
private let state = Atomic(State())
public var disposed: Bool {
return state.value.disposed
}
/// The inner disposable to dispose of.
///
/// Whenever this property is set (even to the same value!), the previous
/// disposable is automatically disposed.
public var innerDisposable: Disposable? {
get {
return state.value.innerDisposable
}
set(d) {
let oldState = state.modify { state in
var mutableState = state
mutableState.innerDisposable = d
return mutableState
}
oldState.innerDisposable?.dispose()
if oldState.disposed {
d?.dispose()
}
}
}
/// Initializes the receiver to dispose of the argument when the
/// SerialDisposable is disposed.
public init(_ disposable: Disposable? = nil) {
innerDisposable = disposable
}
public func dispose() {
let orig = state.swap(State(innerDisposable: nil, disposed: true))
orig.innerDisposable?.dispose()
}
}
/// Adds the right-hand-side disposable to the left-hand-side
/// `CompositeDisposable`.
///
/// disposable += producer
/// .filter { ... }
/// .map { ... }
/// .start(observer)
///
public func +=(lhs: CompositeDisposable, rhs: Disposable?) -> CompositeDisposable.DisposableHandle {
return lhs.addDisposable(rhs)
}
|
eb0c100da3df2d185a99ff70fcc0f04d
| 23.444915 | 100 | 0.703241 | false | false | false | false |
Sharelink/Bahamut
|
refs/heads/master
|
Bahamut/SharelinkAppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Bahamut
//
// Created by AlexChow on 15/7/27.
// Copyright (c) 2015年 GStudio. All rights reserved.
//
import UIKit
import CoreData
import EVReflection
import ImagePicker
import CoreMotion
class Sharelink
{
static func mainBundle() -> NSBundle{
if isSDKVersion
{
if let path = NSBundle.mainBundle().pathForResource("SharelinkKernel", ofType: "bundle")
{
if let bundle = NSBundle(path: path)
{
return bundle
}
}
fatalError("No Kernel Resource Bundle")
}else
{
return NSBundle.mainBundle()
}
}
private(set) static var isSDKVersion:Bool = false
static func isProductVersion() -> Bool{
return !isSDKVersion
}
}
@objc
public class SharelinkAppDelegate: UIResponder, UIApplicationDelegate {
public static func startSharelink()
{
MainNavigationController.start()
}
public var window: UIWindow?
public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
configureSharelinkBundle()
configContryAndLang()
configureAliOSSManager()
configureBahamutCmd()
configureBahamutRFKit()
configureImagePicker()
#if APP_VERSION
if Sharelink.isProductVersion()
{
configureUMessage(launchOptions)
configureUmeng()
configureShareSDK()
initQuPai()
}
#endif
loadUI()
return true
}
var isSDKVersion:Bool
{
return true
}
private func configureBahamutCmd()
{
BahamutCmd.signBahamutCmdSchema("sharelink")
}
private func configureAliOSSManager()
{
AliOSSManager.sharedInstance.initManager(SharelinkConfig.bahamutConfig.aliOssAccessKey, aliOssSecretKey: SharelinkConfig.bahamutConfig.aliOssSecretKey)
}
private func configureBahamutRFKit()
{
BahamutRFKit.appkey = SharelinkRFAppKey
BahamutRFKit.setRFKitAppVersion(SharelinkVersion)
}
private func configureSharelinkBundle()
{
Sharelink.isSDKVersion = isSDKVersion
let config = BahamutConfigObject(dictionary: BahamutConfigJson)
SharelinkConfig.bahamutConfig = config
}
private func configContryAndLang()
{
let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode)
SharelinkSetting.contry = countryCode!.description
if(countryCode!.description == "CN")
{
SharelinkSetting.lang = "ch"
}else{
SharelinkSetting.lang = "en"
}
}
private func loadUI()
{
dispatch_async(dispatch_get_main_queue()) { () -> Void in
ChatViewController.instanceFromStoryBoard()
UserProfileViewController.instanceFromStoryBoard()
UIEditTextPropertyViewController.instanceFromStoryBoard()
}
}
private func configureImagePicker()
{
dispatch_async(dispatch_get_main_queue()) { () -> Void in
let mmanger = CMMotionManager()
if self.isSDKVersion == false
{
NSLog("AccelerometerActive:\(mmanger.accelerometerActive)")
}
Configuration.cancelButtonTitle = "CANCEL".localizedString()
Configuration.doneButtonTitle = "DONE".localizedString()
Configuration.settingsTitle = "SETTING".localizedString()
Configuration.noCameraTitle = "CAMERA_NOT_AVAILABLE".localizedString()
Configuration.noImagesTitle = "NO_IMAGES_AVAILABLE".localizedString()
}
}
//MARK:PRODUCTION ONLY
#if APP_VERSION
private func configureUMessage(launchOptions: [NSObject: AnyObject]?)
{
if let options = launchOptions{
UMessage.startWithAppkey(SharelinkConfig.bahamutConfig.umengAppkey, launchOptions: options)
}else{
UMessage.startWithAppkey(SharelinkConfig.bahamutConfig.umengAppkey, launchOptions: [NSObject: AnyObject]())
}
UMessage.registerForRemoteNotifications()
UMessage.setAutoAlert(false)
}
private func initQuPai()
{
}
private func configureUmeng()
{
#if RELEASE
UMAnalyticsConfig.sharedInstance().appKey = SharelinkConfig.bahamutConfig.umengAppkey
MobClick.setAppVersion(SharelinkVersion)
MobClick.setEncryptEnabled(true)
MobClick.setLogEnabled(false)
MobClick.startWithConfigure(UMAnalyticsConfig.sharedInstance())
#endif
}
private func configureShareSDK()
{
dispatch_async(dispatch_get_main_queue()) { () -> Void in
ShareSDK.registerApp(SharelinkConfig.bahamutConfig.shareSDKAppkey)
if(SharelinkSetting.contry == "CN")
{
self.connectChinaApps()
self.connectGlobalApps()
}else{
self.connectGlobalApps()
self.connectChinaApps()
}
//SMS Mail
ShareSDK.connectSMS()
ShareSDK.connectMail()
ShareSDK.ssoEnabled(true)
}
}
private func connectGlobalApps()
{
//Facebook
//ShareSDK.connectFacebookWithAppKey(SharelinkConfig.bahamutConfig.facebookAppkey, appSecret: SharelinkConfig.bahamutConfig.facebookAppScrect)
//WhatsApp
ShareSDK.connectWhatsApp()
}
private func connectChinaApps()
{
//微信登陆的时候需要初始化
ShareSDK.connectWeChatSessionWithAppId(SharelinkConfig.bahamutConfig.wechatAppkey, appSecret: SharelinkConfig.bahamutConfig.wechatAppScrect, wechatCls: WXApi.classForCoder())
ShareSDK.connectWeChatTimelineWithAppId(SharelinkConfig.bahamutConfig.wechatAppkey, appSecret: SharelinkConfig.bahamutConfig.wechatAppScrect, wechatCls: WXApi.classForCoder())
//添加QQ应用 注册网址 http://mobile.qq.com/api/
ShareSDK.connectQQWithAppId(SharelinkConfig.bahamutConfig.qqAppkey, qqApiCls: QQApiInterface.classForCoder())
//Weibo
// ShareSDK.connectSinaWeiboWithAppKey(SharelinkConfig.bahamutConfig.weiboAppkey, appSecret: SharelinkConfig.bahamutConfig.weiboAppScrect, redirectUri: "https://api.weibo.com/oauth2/default.html",weiboSDKCls: WeiboSDK.classForCoder())
}
#endif
//MARK: AppDelegate
public func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
#if APP_VERSION
UMessage.registerDeviceToken(deviceToken)
#endif
SharelinkSetting.deviceToken = deviceToken.description
.stringByReplacingOccurrencesOfString("<", withString: "")
.stringByReplacingOccurrencesOfString(">", withString: "")
.stringByReplacingOccurrencesOfString(" ", withString: "")
ChicagoClient.sharedInstance.registDeviceToken(SharelinkSetting.deviceToken)
}
public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
#if APP_VERSION
UMessage.didReceiveRemoteNotification(userInfo)
#endif
}
public func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
NSLog("%@", error.description)
}
public func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
if url.scheme == BahamutCmd.cmdUrlSchema
{
return handleSharelinkUrl(url)
}else
{
#if APP_VERSION
return ShareSDK.handleOpenURL(url, wxDelegate: self)
#else
return true
#endif
}
}
public func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if url.scheme == BahamutCmd.cmdUrlSchema
{
return handleSharelinkUrl(url)
}else
{
#if APP_VERSION
return ShareSDK.handleOpenURL(url, sourceApplication: sourceApplication, annotation: annotation, wxDelegate: self)
#else
return true
#endif
}
}
public func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
return handleSharelinkUrl(url)
}
private func handleSharelinkUrl(url:NSURL) -> Bool
{
if url.scheme == BahamutCmd.cmdUrlSchema
{
let cmd = BahamutCmd.getCmdFromUrl(url.absoluteString)
BahamutCmdManager.sharedInstance.pushCmd(cmd)
}
return true
}
public func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
public func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
PersistentManager.sharedInstance.saveAll()
ChicagoClient.sharedInstance.inBackground()
}
public func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
public func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
if ServiceContainer.isAllServiceReady
{
ServiceContainer.getService(UserService).getNewLinkMessageFromServer()
ServiceContainer.getService(ShareService).getNewShareMessageFromServer()
ServiceContainer.getService(ChatService).getMessageFromServer()
ChicagoClient.sharedInstance.reConnect()
if UserService.lastRefreshLinkedUserTime == nil || UserService.lastRefreshLinkedUserTime.timeIntervalSinceNow < -1000 * 3600 * 3
{
UserService.lastRefreshLinkedUserTime = NSDate()
ServiceContainer.getService(UserService).refreshMyLinkedUsers()
}
BahamutCmdManager.sharedInstance.handleCmdQueue()
}
}
public func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
PersistentManager.sharedInstance.saveAll()
}
public func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask
{
if let presentedVc = self.window?.rootViewController?.presentedViewController as? OrientationsNavigationController
{
return presentedVc.supportedViewOrientations()
}
return UIInterfaceOrientationMask.Portrait
}
}
|
1aca97cb95f13e015f122cc62fd95c41
| 35.41018 | 285 | 0.658581 | false | true | false | false |
languageininteraction/VowelSpaceTravel
|
refs/heads/master
|
mobile/Vowel Space Travel iOS/Vowel Space Travel iOS/Constants.swift
|
gpl-2.0
|
1
|
//
// Constants.swift
// Vowel Space Travel iOS
//
// Created by Wessel Stoop on 10/04/15.
// Copyright (c) 2015 Radboud University. All rights reserved.
//
import UIKit
import Foundation
let kDevelopmentMode = true
let kSpeedUpDownload = kDevelopmentMode ? true : false
let kOnlyOneStimulus = kDevelopmentMode ? true : false
let kShowTouchLocation = kDevelopmentMode ? false : false
let kShowPlanetsForExampleUser = kDevelopmentMode ? false : false
let kWebserviceURL = kDevelopmentMode ? "http://applejack.science.ru.nl/vowelspacetravel/" : "http://applejack.science.ru.nl/vowelspacetravel/"
let kWebserviceUsername = kDevelopmentMode ? "[email protected]" : "[email protected]"
let kWebserviceUserPassword = kDevelopmentMode ? "1234" : "1234"
let kFeedbackSoundVolume : Float = 0.2
let kTimeBeforeStimuli : Double = 1
let kTimeBetweenStimuli : Double = 1.8
let kTimeBetweenStimuliWhenShowingTheExample : Double = 4
let kPauseBetweenRounds : Double = 6
let kNumberOfStimuliInRound : Int = 15
let kMaxNumberOfTargetsInRound : Int = 6
let kCachedStimuliLocation : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask,true)[0] + "/Caches/"
let kSoundFileExtension = ".wav"
let kBackgroundColor : UIColor = UIColor(hue: 0.83, saturation: 0.2, brightness: 0.57, alpha: 1)
|
3606897a94c84173e55ec25864755dc3
| 38.647059 | 173 | 0.78248 | false | false | false | false |
colemancda/HTTP-Server
|
refs/heads/master
|
Representor/HTTP/HTTPDeserializer.swift
|
mit
|
1
|
public struct HTTPDeserializer {
public typealias Deserialize = HTTPResponse -> Representor<HTTPTransition>?
public static func jsonDeserializer(deserialize: JSON -> Representor<HTTPTransition>?) -> (HTTPResponse -> Representor<HTTPTransition>?) {
return { response in
if let json = try? JSONParser.parse(response.body) {
return deserialize(json)
}
return nil
}
}
public static var deserializers: [String: Deserialize] = [
"application/hal+json": HTTPDeserializer.jsonDeserializer { json in
return deserializeHAL(json)
},
// "application/vnd.siren+json": HTTPDeserializer.jsonDeserializer { json in
//
// return deserializeSiren(json)
//
// },
]
public static var preferredContentTypes: [String] = [
"application/vnd.siren+json",
"application/hal+json",
]
public static func deserialize(response: HTTPResponse) -> Representor<HTTPTransition>? {
if let contentType = response.contentType {
if let deserialize = HTTPDeserializer.deserializers[contentType] {
return deserialize(response)
}
}
return nil
}
}
|
99280d892b5ae76d2760f44cc4017468
| 21.964912 | 142 | 0.593583 | false | false | false | false |
AssistoLab/DropDown
|
refs/heads/master
|
Demo/ViewController.swift
|
mit
|
2
|
//
// ViewController.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
import DropDown
class ViewController: UIViewController {
//MARK: - Properties
@IBOutlet weak var chooseArticleButton: UIButton!
@IBOutlet weak var amountButton: UIButton!
@IBOutlet weak var chooseButton: UIButton!
@IBOutlet weak var centeredDropDownButton: UIButton!
@IBOutlet weak var rightBarButton: UIBarButtonItem!
let textField = UITextField()
//MARK: - DropDown's
let chooseArticleDropDown = DropDown()
let amountDropDown = DropDown()
let chooseDropDown = DropDown()
let centeredDropDown = DropDown()
let rightBarDropDown = DropDown()
lazy var dropDowns: [DropDown] = {
return [
self.chooseArticleDropDown,
self.amountDropDown,
self.chooseDropDown,
self.centeredDropDown,
self.rightBarDropDown
]
}()
//MARK: - Actions
@IBAction func chooseArticle(_ sender: AnyObject) {
chooseArticleDropDown.show()
}
@IBAction func changeAmount(_ sender: AnyObject) {
amountDropDown.show()
}
@IBAction func choose(_ sender: AnyObject) {
chooseDropDown.show()
}
@IBAction func showCenteredDropDown(_ sender: AnyObject) {
centeredDropDown.show()
}
@IBAction func showBarButtonDropDown(_ sender: AnyObject) {
rightBarDropDown.show()
}
@IBAction func changeDIsmissMode(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: dropDowns.forEach { $0.dismissMode = .automatic }
case 1: dropDowns.forEach { $0.dismissMode = .onTap }
default: break;
}
}
@IBAction func changeDirection(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: dropDowns.forEach { $0.direction = .any }
case 1: dropDowns.forEach { $0.direction = .bottom }
case 2: dropDowns.forEach { $0.direction = .top }
default: break;
}
}
@IBAction func changeUI(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: setupDefaultDropDown()
case 1: customizeDropDown(self)
default: break;
}
}
@IBAction func showKeyboard(_ sender: AnyObject) {
textField.becomeFirstResponder()
}
@IBAction func hideKeyboard(_ sender: AnyObject) {
view.endEditing(false)
}
func setupDefaultDropDown() {
DropDown.setupDefaultAppearance()
dropDowns.forEach {
$0.cellNib = UINib(nibName: "DropDownCell", bundle: Bundle(for: DropDownCell.self))
$0.customCellConfiguration = nil
}
}
func customizeDropDown(_ sender: AnyObject) {
let appearance = DropDown.appearance()
appearance.cellHeight = 60
appearance.backgroundColor = UIColor(white: 1, alpha: 1)
appearance.selectionBackgroundColor = UIColor(red: 0.6494, green: 0.8155, blue: 1.0, alpha: 0.2)
// appearance.separatorColor = UIColor(white: 0.7, alpha: 0.8)
appearance.cornerRadius = 10
appearance.shadowColor = UIColor(white: 0.6, alpha: 1)
appearance.shadowOpacity = 0.9
appearance.shadowRadius = 25
appearance.animationduration = 0.25
appearance.textColor = .darkGray
// appearance.textFont = UIFont(name: "Georgia", size: 14)
if #available(iOS 11.0, *) {
appearance.setupMaskedCorners([.layerMaxXMaxYCorner, .layerMinXMaxYCorner])
}
dropDowns.forEach {
/*** FOR CUSTOM CELLS ***/
$0.cellNib = UINib(nibName: "MyCell", bundle: nil)
$0.customCellConfiguration = { (index: Index, item: String, cell: DropDownCell) -> Void in
guard let cell = cell as? MyCell else { return }
// Setup your custom UI components
cell.logoImageView.image = UIImage(named: "logo_\(index % 10)")
}
/*** ---------------- ***/
}
}
//MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
setupDropDowns()
dropDowns.forEach { $0.dismissMode = .onTap }
dropDowns.forEach { $0.direction = .any }
view.addSubview(textField)
}
//MARK: - Setup
func setupDropDowns() {
setupChooseArticleDropDown()
setupAmountDropDown()
setupChooseDropDown()
setupCenteredDropDown()
setupRightBarDropDown()
}
func setupChooseArticleDropDown() {
chooseArticleDropDown.anchorView = chooseArticleButton
// Will set a custom with instead of anchor view width
// dropDown.width = 100
// By default, the dropdown will have its origin on the top left corner of its anchor view
// So it will come over the anchor view and hide it completely
// If you want to have the dropdown underneath your anchor view, you can do this:
chooseArticleDropDown.bottomOffset = CGPoint(x: 0, y: chooseArticleButton.bounds.height)
// You can also use localizationKeysDataSource instead. Check the docs.
chooseArticleDropDown.dataSource = [
"iPhone SE | Black | 64G",
"Samsung S7",
"Huawei P8 Lite Smartphone 4G",
"Asus Zenfone Max 4G",
"Apple Watwh | Sport Edition"
]
// Action triggered on selection
chooseArticleDropDown.selectionAction = { [weak self] (index, item) in
self?.chooseArticleButton.setTitle(item, for: .normal)
}
chooseArticleDropDown.multiSelectionAction = { [weak self] (indices, items) in
print("Muti selection action called with: \(items)")
if items.isEmpty {
self?.chooseArticleButton.setTitle("", for: .normal)
}
}
// Action triggered on dropdown cancelation (hide)
// dropDown.cancelAction = { [unowned self] in
// // You could for example deselect the selected item
// self.dropDown.deselectRowAtIndexPath(self.dropDown.indexForSelectedRow)
// self.actionButton.setTitle("Canceled", forState: .Normal)
// }
// You can manually select a row if needed
// dropDown.selectRowAtIndex(3)
}
func setupAmountDropDown() {
amountDropDown.anchorView = amountButton
// By default, the dropdown will have its origin on the top left corner of its anchor view
// So it will come over the anchor view and hide it completely
// If you want to have the dropdown underneath your anchor view, you can do this:
amountDropDown.bottomOffset = CGPoint(x: 0, y: amountButton.bounds.height)
// You can also use localizationKeysDataSource instead. Check the docs.
amountDropDown.dataSource = [
"10 €",
"20 €",
"30 €",
"40 €",
"50 €",
"60 €",
"70 €",
"80 €",
"90 €",
"100 €",
"110 €",
"120 €"
]
// Action triggered on selection
amountDropDown.selectionAction = { [weak self] (index, item) in
self?.amountButton.setTitle(item, for: .normal)
}
}
func setupChooseDropDown() {
chooseDropDown.anchorView = chooseButton
// By default, the dropdown will have its origin on the top left corner of its anchor view
// So it will come over the anchor view and hide it completely
// If you want to have the dropdown underneath your anchor view, you can do this:
chooseDropDown.bottomOffset = CGPoint(x: 0, y: chooseButton.bounds.height)
// You can also use localizationKeysDataSource instead. Check the docs.
chooseDropDown.dataSource = [
"Lorem ipsum dolor",
"sit amet consectetur",
"cadipisci en..."
]
// Action triggered on selection
chooseDropDown.selectionAction = { [weak self] (index, item) in
self?.chooseButton.setTitle(item, for: .normal)
}
}
func setupCenteredDropDown() {
// Not setting the anchor view makes the drop down centered on screen
// centeredDropDown.anchorView = centeredDropDownButton
// You can also use localizationKeysDataSource instead. Check the docs.
centeredDropDown.dataSource = [
"The drop down",
"Is centered on",
"the view because",
"it has no anchor view defined.",
"Click anywhere to dismiss."
]
centeredDropDown.selectionAction = { [weak self] (index, item) in
self?.centeredDropDownButton.setTitle(item, for: .normal)
}
}
func setupRightBarDropDown() {
rightBarDropDown.anchorView = rightBarButton
// You can also use localizationKeysDataSource instead. Check the docs.
rightBarDropDown.dataSource = [
"Menu 1",
"Menu 2",
"Menu 3",
"Menu 4"
]
}
}
|
e6460bca8771a38921c1ca31ef191904
| 27.533569 | 98 | 0.69548 | false | false | false | false |
fabiomassimo/GAuth
|
refs/heads/master
|
GAuthTests/GoogleAuthenticatorSpec.swift
|
mit
|
1
|
//
// GoogleAuthenticatorSpec.swift
// GoogleAuthenticator
//
// Created by Fabio Milano on 14/06/16.
// Copyright © 2016 Touchwonders. All rights reserved.
//
import Foundation
import Result
@testable import GAuth
public struct TokenMock {
public let accessToken: String
public let refreshToken: String?
public let expiresIn: NSTimeInterval?
public let isExpired: Bool
public let isValid: Bool
public let scopes: [String]?
static func expiredToken() -> TokenMock {
return TokenMock(accessToken: "ACCESS_TOKEN", refreshToken: "REFRESH_TOKEN", expiresIn: 3600, isExpired: true, isValid: false, scopes: ["test_scope"])
}
static func validToken() -> TokenMock {
return TokenMock(accessToken: "ACCESS_TOKEN", refreshToken: "REFRESH_TOKEN", expiresIn: 3600, isExpired: false, isValid: true, scopes: ["test_scope"])
}
}
enum TokenFeatures {
case Valid
case Expired
}
public class OAuthMockClient {
/// The client ID.
public let clientID: String
/// The client secret.
public let clientSecret: String
/// The authorize URL.
public let authorizeURL: NSURL
/// The token URL.
public let tokenURL: NSURL?
/// The redirect URL.
public let redirectURL: NSURL?
public let scopes: [String]
public var token: TokenMock?
init(tokenFeatures: TokenFeatures, clientID: String = "CLIENT_ID", clientSecret: String = "CLIENT_SECRET",
authorizeURL: NSURL = NSURL(string: "http://authorizeurl.touchwonders.com")!, tokenURL: NSURL = NSURL(string: "http://tokenurl.touchwonders.com")!,
redirectURL: NSURL = NSURL(string: "http://redirecturl.touchwonders.com")!,
scopes: [String] = ["test_scope"]) {
self.clientID = clientID
self.clientSecret = clientSecret
self.authorizeURL = authorizeURL
self.tokenURL = tokenURL
self.redirectURL = redirectURL
self.scopes = scopes
switch tokenFeatures {
case .Valid:
self.token = TokenMock.validToken()
case .Expired:
self.token = TokenMock.expiredToken()
}
}
var nextOAuthClientError: GoogleAuthenticatorError?
}
extension TokenMock: AuthorizedToken { }
extension GoogleAuthenticatorError: GoogleAuthenticatorErrorAdapter {
public var googleAuthenticatorError: GoogleAuthenticatorError {
return self
}
}
extension GoogleAuthenticatorClient {
public func invalidateClientNextRequestWithError(error: GoogleAuthenticatorError) -> Void {
let client = oauthClient as! OAuthMockClient
client.nextOAuthClientError = GoogleAuthenticatorError.AuthorizationPending
}
}
extension OAuthMockClient: GoogleAuthenticatorOAuthClient {
public typealias OAuthClientType = OAuthMockClient
public typealias TokenType = TokenMock
public typealias Failure = GoogleAuthenticatorError
public static func Google(clientID clientID: String, clientSecret: String, bundleIdentifier: String, scope: GoogleServiceScope) -> OAuthMockClient {
return OAuthMockClient(tokenFeatures: TokenFeatures.Valid)
}
public func googleAuthenticatorRefreshToken(completion: Result<TokenType, GoogleAuthenticatorError> -> Void) {
if let nextOAuthClientError = nextOAuthClientError {
self.nextOAuthClientError = nil
completion(.Failure(nextOAuthClientError))
return
}
self.token = TokenMock.validToken()
completion(.Success(token!))
}
public func googleAuthenticatorAuthorize(completion: Result<TokenType, GoogleAuthenticatorError> -> Void) {
if let nextOAuthClientError = nextOAuthClientError {
self.nextOAuthClientError = nil
completion(.Failure(nextOAuthClientError))
return
}
completion(.Success(token!))
}
public func googleAuthenticatorAuthorizeDeviceCode(deviceCode: String, completion: Result<TokenType, GoogleAuthenticatorError> -> Void) {
if let nextOAuthClientError = nextOAuthClientError {
self.nextOAuthClientError = nil
completion(.Failure(nextOAuthClientError))
return
}
completion(.Success(token!))
}
}
|
20a96fcf28534f6963ac9b70449ce1df
| 30.148936 | 158 | 0.670918 | false | false | false | false |
nakau1/Formations
|
refs/heads/master
|
Formations/Sources/Modules/Team/Views/Edit/TeamEditViewController.swift
|
apache-2.0
|
1
|
// =============================================================================
// Formations
// Copyright 2017 yuichi.nakayasu All rights reserved.
// =============================================================================
import UIKit
import Rswift
// MARK: - Controller Definition -
class TeamEditViewController: UIViewController {
// MARK: ファクトリメソッド
class func create(for team: Team?) -> UIViewController {
return R.storyboard.teamEditViewController.instantiate(self) { vc in
if let team = team {
vc.team = team
} else {
let newTeam = Realm.Team.create()
vc.team = newTeam
vc.isAdd = true
}
}
}
enum Row {
case header(title: String)
case name
case internationalName
case shortenedName
case color
case image
static var rows: [Row] {
return [
.header(title: "チーム名"),
.name, .internationalName, .shortenedName,
.header(title: "チームカラー"),
.color,
.header(title: "チーム画像"),
.image,
]
}
var placeholderText: String {
switch self {
case .name: return "チーム名"
case .internationalName: return "チーム名(英語表記)"
case .shortenedName: return "短縮名"
default: return ""
}
}
var hintText: String {
switch self {
case .name: return "チーム名を入力します\n(\(TeamModel.maxlenOfName)文字以内)"
case .internationalName: return "チームのの国際上の名称を英字で入力します\n(\(TeamModel.maxlenOfInternationalName)文字以内)"
case .shortenedName: return "チームを表す\(TeamModel.fixlenOfShortenedName)文字のアルファベットを入力します\n(例 : 日本代表 = JPN)"
default: return ""
}
}
}
@IBOutlet fileprivate weak var tableView: UITableView!
private var isAdd = false
private var team: Team!
override func viewDidLoad() {
super.viewDidLoad()
prepareNavigationBar()
prepareUserInterface()
prepareBackgroundView()
prepareTableView()
prepareTeam()
}
private func prepareUserInterface() {
self.title = isAdd ? "新しいチームの作成" : "チーム設定"
if !isAdd {
navigationItem.rightBarButtonItem = nil
}
}
private func prepareBackgroundView() {
let image = team.loadTeamImage().teamImage?.retina
BackgroundView.notifyChangeImage(image)
}
private func prepareTableView() {
tableView.estimatedRowHeight = 64
tableView.rowHeight = UITableViewAutomaticDimension
tableView.registerEditHeaderCell()
}
private func prepareTeam() {
Realm.Team.clearValidateResults(team)
}
@IBAction func didTapCompleteButton() {
AlertDialog.showConfirmNewSave(
from: self,
targetName: "チーム",
save: { [unowned self] in
Realm.Team.save(self.team)
Realm.Team.notifyChange()
self.dismiss()
},
dispose: { [unowned self] in
Image.delete(category: .teams, id: self.team.id)
self.dismiss()
}
)
}
}
// MARK: - UITableViewDataSource & UITableViewDelegate
extension TeamEditViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Row.rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = Row.rows[indexPath.row]
let cell: TeamEditTableViewCell
switch row {
case .header(let title):
return tableView.dequeueReusableEditHeaderCell(title: title, for: indexPath)
case .name, .internationalName:
cell = R.reuseIdentifier.teamEditName.reuse(tableView)
case .shortenedName:
cell = R.reuseIdentifier.teamEditShortName.reuse(tableView)
case .color:
cell = R.reuseIdentifier.teamEditColor.reuse(tableView)
case .image:
cell = R.reuseIdentifier.teamEditImage.reuse(tableView)
}
cell.row = row
cell.team = team
cell.delegate = self
return cell
}
}
// MARK: - TableViewDelegate
extension TeamEditViewController: TeamEditTableViewDelegate {
func didEditName(value: String) {
if Realm.Team.validateName(value, of: team) {
Realm.Team.write(team) {
$0.name = value
Realm.Team.notifyChange()
}
}
tableView.reloadData()
}
func didEditInternationalName(value: String) {
if Realm.Team.validateInternationalName(value, of: team) {
Realm.Team.write(team) {
$0.internationalName = value
}
}
tableView.reloadData()
}
func didEditShortenedName(value: String) {
if Realm.Team.validateShortenedName(value, of: team) {
Realm.Team.write(team) {
$0.shortenedName = value.uppercased()
}
}
tableView.reloadData()
}
func didTapMainColor() {
ColorPicker.show(from: self, defaultColor: team.mainColor) { [unowned self] color in
Realm.Team.write(self.team) { $0.mainColor = color }
Realm.Team.notifyChange()
self.tableView.reloadData()
}
}
func didTapSubColor() {
ColorPicker.show(from: self, defaultColor: team.subColor) { [unowned self] color in
Realm.Team.write(self.team) { $0.subColor = color }
self.tableView.reloadData()
}
}
func didTapOption1Color() {
AlertDialog.showOptionColorMenu(
from: self,
delete: {
Realm.Team.write(self.team) { $0.option1Color = nil }
self.tableView.reloadData()
},
change: {
ColorPicker.show(from: self, defaultColor: self.team.option1Color) { [unowned self] color in
Realm.Team.write(self.team) { $0.option1Color = color }
self.tableView.reloadData()
}
}
)
}
func didTapOption2Color() {
AlertDialog.showOptionColorMenu(
from: self,
delete: {
Realm.Team.write(self.team) { $0.option2Color = nil }
self.tableView.reloadData()
},
change: {
ColorPicker.show(from: self, defaultColor: self.team.option2Color) { [unowned self] color in
Realm.Team.write(self.team) { $0.option2Color = color }
self.tableView.reloadData()
}
}
)
}
func didTapEmblemImage() {
ImagePicker.show(from: self) { [unowned self] image in
self.updateEmblemImage(image)
}
}
func didTapTeamImage() {
ImagePicker.show(from: self) { [unowned self] image in
self.updateTeamImage(image)
}
}
func didTapEmblemImageHelp() {
let vc = TeamEditHelpViewController.create(mode: .emblemImage, delete: {
self.updateEmblemImage(nil)
})
Popup.show(vc, from: self, options: PopupOptions(.bottomDraw(height: 380)))
}
func didTapTeamImageHelp() {
let vc = TeamEditHelpViewController.create(mode: .teamImage, delete: {
self.updateTeamImage(nil)
})
Popup.show(vc, from: self, options: PopupOptions(.bottomDraw(height: 380)))
}
}
extension TeamEditViewController {
private func updateEmblemImage(_ image: UIImage?) {
let emblem = Image.teamEmblem(id: self.team.id)
emblem.save(image)
self.team.emblemImage = image
let smallEmblem = Image.teamSmallEmblem(id: self.team.id)
smallEmblem.save(image)
self.team.smallEmblemImage = image
Realm.Team.notifyChange()
self.tableView.reloadData()
}
private func updateTeamImage(_ image: UIImage?) {
let teamImage = Image.teamImage(id: self.team.id)
teamImage.save(image)
self.team.teamImage = image
BackgroundView.notifyChangeImage(image)
self.tableView.reloadData()
}
}
// MARK: - CellDelegate -
protocol TeamEditTableViewDelegate: class {
func didEditName(value: String)
func didEditInternationalName(value: String)
func didEditShortenedName(value: String)
func didTapMainColor()
func didTapSubColor()
func didTapOption1Color()
func didTapOption2Color()
func didTapEmblemImage()
func didTapTeamImage()
func didTapEmblemImageHelp()
func didTapTeamImageHelp()
}
// MARK: - Cells -
// MARK: Base
class TeamEditTableViewCell: UITableViewCell {
var row: TeamEditViewController.Row!
var team: Team!
weak var delegate: TeamEditTableViewDelegate?
}
// MARK: - Name
class TeamEditNameTableViewCell: TeamEditTableViewCell, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var hintLabel: UILabel!
@IBOutlet weak var errorLabel: UILabel!
override var row: TeamEditViewController.Row! {
didSet {
textField.placeholder = row.placeholderText
hintLabel.text = row.hintText
errorLabel.text = ""
}
}
override var team: Team! {
didSet {
let row: TeamEditViewController.Row = self.row
switch row {
case .name: textField.text = team.name
case .internationalName: textField.text = team.internationalName
case .shortenedName: textField.text = team.shortenedName
default: break
}
switch row {
case .name: errorLabel.text = Realm.Team.validateResultOfName(team)
case .internationalName: errorLabel.text = Realm.Team.validateResultOfInternationalName(team)
case .shortenedName: errorLabel.text = Realm.Team.validateResultOfShortenedName(team)
default: break
}
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.isFirstResponder {
textField.resignFirstResponder()
}
return true
}
@IBAction private func didChangeTextField() {
let value = textField.text ?? ""
let row: TeamEditViewController.Row = self.row
switch row {
case .name: delegate?.didEditName(value: value)
case .internationalName: delegate?.didEditInternationalName(value: value)
case .shortenedName: delegate?.didEditShortenedName(value: value)
default: break
}
}
}
// MARK: - Color
class TeamEditColorTableViewCell: TeamEditTableViewCell {
@IBOutlet var colorButtons: [CircleColorButton]!
override var team: Team! {
didSet {
colorButtons.enumerated().forEach { i, button in
let button = colorButtons[i]
switch i {
case 0: button.buttonColor = team.mainColor
case 1: button.buttonColor = team.subColor
case 2: button.buttonColor = team.option1Color
case 3: button.buttonColor = team.option2Color
default: break
}
}
}
}
@IBAction private func didTapColorButton(_ colorButton: UIButton) {
switch colorButton.tag {
case 0: delegate?.didTapMainColor()
case 1: delegate?.didTapSubColor()
case 2: delegate?.didTapOption1Color()
case 3: delegate?.didTapOption2Color()
default: break
}
}
}
// MARK: - Image
class TeamEditImageTableViewCell: TeamEditTableViewCell {
@IBOutlet weak var emblemImageButton: UIButton!
@IBOutlet weak var teamImageButton: UIButton!
override var team: Team! {
didSet {
emblemImageButton.setImage(team.loadEmblemImage().emblemImage, for: .normal)
teamImageButton.setImage(team.loadTeamImage().teamImage, for: .normal)
}
}
@IBAction private func didTapEmblemImageButton() {
delegate?.didTapEmblemImage()
}
@IBAction private func didTapTeamImageButton() {
delegate?.didTapTeamImage()
}
@IBAction private func didTapEmblemImageHelpButton() {
delegate?.didTapEmblemImageHelp()
}
@IBAction private func didTapTeamImageHelpButton() {
delegate?.didTapTeamImageHelp()
}
}
|
b50a3cdfb516c9b40a970d80212f8bb9
| 30.11271 | 120 | 0.576461 | false | false | false | false |
aaronsakowski/BSImagePicker
|
refs/heads/master
|
Pod/Classes/Controller/PhotosViewController.swift
|
mit
|
2
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import Photos
final class PhotosViewController : UICollectionViewController, UIPopoverPresentationControllerDelegate, UITableViewDelegate, UICollectionViewDelegate, AssetsDelegate, UINavigationControllerDelegate {
var selectionClosure: ((asset: PHAsset) -> Void)?
var deselectionClosure: ((asset: PHAsset) -> Void)?
var cancelClosure: ((assets: [PHAsset]) -> Void)?
var finishClosure: ((assets: [PHAsset]) -> Void)?
var settings: BSImagePickerSettings = Settings()
lazy var doneBarButton: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "doneButtonPressed:")
}()
lazy var cancelBarButton: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancelButtonPressed:")
}()
lazy var albumTitleView: AlbumTitleView = {
let albumTitleView = self.bundle.loadNibNamed("AlbumTitleView", owner: self, options: nil).first as! AlbumTitleView
albumTitleView.albumButton.addTarget(self, action: "albumButtonPressed:", forControlEvents: .TouchUpInside)
return albumTitleView
}()
private let expandAnimator = ZoomAnimator()
private let shrinkAnimator = ZoomAnimator()
private var photosDataSource: PhotosDataSource?
private var albumsDataSource: AlbumsDataSource?
private var doneBarButtonTitle: String?
private var isVisible = true
private lazy var bundle: NSBundle = {
// Get path for BSImagePicker bundle
// Forcefull unwraps on purpose, if these aren't present the code wouldn't work as it should anyways
// So I'll accept the crash in that case :)
let bundlePath = NSBundle(forClass: PhotosViewController.self).pathForResource("BSImagePicker", ofType: "bundle")!
return NSBundle(path: bundlePath)!
}()
private lazy var albumsViewController: AlbumsViewController? = {
let storyboard = UIStoryboard(name: "Albums", bundle: self.bundle)
let vc = storyboard.instantiateInitialViewController() as? AlbumsViewController
vc?.modalPresentationStyle = .Popover
vc?.preferredContentSize = CGSize(width: 320, height: 300)
vc?.tableView.dataSource = self.albumsDataSource
vc?.tableView.delegate = self
return vc
}()
private lazy var previewViewContoller: PreviewViewController? = {
return PreviewViewController(nibName: nil, bundle: nil)
}()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func loadView() {
super.loadView()
// Set an empty title to get < back button
title = " "
// Setup albums data source
albumsDataSource = AlbumsDataSource()
albumsDataSource?.selectObjectAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))
albumsDataSource?.delegate = self
photosDataSource = PhotosDataSource(settings: settings)
// TODO: Break out into method. Is duplicated in didSelectTableView
if let album = albumsDataSource?.selections().first {
// Update album title
albumTitleView.albumTitle = album.localizedTitle
// Pass it on to photos data source
photosDataSource?.fetchResultsForAsset(album)
}
// Hook up data source
photosDataSource?.delegate = self
collectionView?.dataSource = photosDataSource
collectionView?.delegate = self
// Enable multiple selection
collectionView?.allowsMultipleSelection = true
// Add buttons
navigationItem.leftBarButtonItem = cancelBarButton
navigationItem.rightBarButtonItem = doneBarButton
navigationItem.titleView = albumTitleView
// Add long press recognizer
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "collectionViewLongPressed:")
longPressRecognizer.minimumPressDuration = 0.5
collectionView?.addGestureRecognizer(longPressRecognizer)
// Set navigation controller delegate
navigationController?.delegate = self
}
// MARK: Appear/Disappear
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateDoneButton()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
isVisible = true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
isVisible = false
}
// MARK: Button actions
func cancelButtonPressed(sender: UIBarButtonItem) {
if let closure = cancelClosure, let assets = photosDataSource?.selections() {
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
closure(assets: assets)
})
}
dismissViewControllerAnimated(true, completion: nil)
}
func doneButtonPressed(sender: UIBarButtonItem) {
if let closure = finishClosure, let assets = photosDataSource?.selections() {
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
closure(assets: assets)
})
}
dismissViewControllerAnimated(true, completion: nil)
}
func albumButtonPressed(sender: UIButton) {
if let albumsViewController = albumsViewController, let popVC = albumsViewController.popoverPresentationController {
popVC.permittedArrowDirections = .Up
popVC.sourceView = sender
let senderRect = sender.convertRect(sender.frame, fromView: sender.superview)
let sourceRect = CGRect(x: senderRect.origin.x, y: senderRect.origin.y + (albumTitleView.frame.size.height / 2), width: senderRect.size.width, height: senderRect.size.height)
popVC.sourceRect = sourceRect
popVC.delegate = self
albumsViewController.tableView.reloadData()
presentViewController(albumsViewController, animated: true, completion: nil)
}
}
func collectionViewLongPressed(sender: UIGestureRecognizer) {
if sender.state == .Began {
// Disable recognizer while we are figuring out location and pushing preview
sender.enabled = false
collectionView?.userInteractionEnabled = false
// Calculate which index path long press came from
let location = sender.locationInView(collectionView)
let indexPath = collectionView?.indexPathForItemAtPoint(location)
if let vc = previewViewContoller, let indexPath = indexPath, let cell = collectionView?.cellForItemAtIndexPath(indexPath) as? PhotoCell, let asset = cell.asset {
// Setup fetch options to be synchronous
let options = PHImageRequestOptions()
options.synchronous = true
// Load image for preview
if let imageView = vc.imageView {
PHCachingImageManager.defaultManager().requestImageForAsset(asset, targetSize:imageView.frame.size, contentMode: .AspectFit, options: options) { (result, _) in
imageView.image = result
}
}
// Setup animation
expandAnimator.sourceImageView = cell.imageView
expandAnimator.destinationImageView = vc.imageView
shrinkAnimator.sourceImageView = vc.imageView
shrinkAnimator.destinationImageView = cell.imageView
navigationController?.pushViewController(vc, animated: true)
}
// Re-enable recognizer
sender.enabled = true
collectionView?.userInteractionEnabled = true
}
}
// MARK: Traits
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if let collectionViewFlowLayout = collectionViewLayout as? UICollectionViewFlowLayout, let collectionViewWidth = collectionView?.bounds.size.width, photosDataSource = photosDataSource {
let itemSpacing: CGFloat = 1.0
let cellsPerRow = settings.cellsPerRow(verticalSize: traitCollection.verticalSizeClass, horizontalSize: traitCollection.horizontalSizeClass)
collectionViewFlowLayout.minimumInteritemSpacing = itemSpacing
collectionViewFlowLayout.minimumLineSpacing = itemSpacing
let width = (collectionViewWidth / CGFloat(cellsPerRow)) - itemSpacing
let itemSize = CGSize(width: width, height: width)
collectionViewFlowLayout.itemSize = itemSize
photosDataSource.imageSize = itemSize
}
}
// MARK: UIPopoverPresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
return true
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Update selected album
albumsDataSource?.selectObjectAtIndexPath(indexPath)
// Notify photos data source
if let album = albumsDataSource?.selections().first {
// Update album title
albumTitleView.albumTitle = album.localizedTitle
// Pass it on to photos data source
photosDataSource?.fetchResultsForAsset(album)
}
// Dismiss album selection
albumsViewController?.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return isVisible && photosDataSource?.selectionCount() < settings.maxNumberOfSelections
}
override func collectionView(collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return isVisible
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// Select asset)
photosDataSource?.selectObjectAtIndexPath(indexPath)
// Set selection number
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PhotoCell, let count = photosDataSource?.selectionCount() {
if let selectionCharacter = settings.selectionCharacter {
cell.selectionString = String(selectionCharacter)
} else {
cell.selectionString = String(count)
}
}
// Update done button
updateDoneButton()
// Call selection closure
if let closure = selectionClosure, let asset = photosDataSource?[indexPath.section][indexPath.row] as? PHAsset {
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
closure(asset: asset)
})
}
}
override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
// Deselect asset
photosDataSource?.deselectObjectAtIndexPath(indexPath)
// Update done button
updateDoneButton()
// Reload selected cells to update their selection number
if let photosDataSource = photosDataSource {
UIView.setAnimationsEnabled(false)
collectionView.reloadItemsAtIndexPaths(photosDataSource.selectedIndexPaths())
syncSelectionInDataSource(photosDataSource, withCollectionView: collectionView)
UIView.setAnimationsEnabled(true)
}
// Call deselection closure
if let closure = deselectionClosure, let asset = photosDataSource?[indexPath.section][indexPath.row] as? PHAsset {
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
closure(asset: asset)
})
}
}
// MARK: AssetsDelegate
func didUpdateAssets(sender: AnyObject, incrementalChange: Bool, insert: [NSIndexPath], delete: [NSIndexPath], change: [NSIndexPath]) {
// May come on a background thread, so dispatch to main
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// Reload table view or collection view?
if let sender = sender as? PhotosDataSource {
if let collectionView = self.collectionView {
if incrementalChange {
// Update
collectionView.deleteItemsAtIndexPaths(delete)
collectionView.insertItemsAtIndexPaths(insert)
collectionView.reloadItemsAtIndexPaths(change)
} else {
// Reload & scroll to top if significant change
collectionView.reloadData()
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: .None, animated: false)
}
// Sync selection
if let photosDataSource = self.photosDataSource {
self.syncSelectionInDataSource(photosDataSource, withCollectionView: collectionView)
}
}
} else if let sender = sender as? AlbumsDataSource {
if incrementalChange {
// Update
self.albumsViewController?.tableView?.deleteRowsAtIndexPaths(delete, withRowAnimation: .Automatic)
self.albumsViewController?.tableView?.insertRowsAtIndexPaths(insert, withRowAnimation: .Automatic)
self.albumsViewController?.tableView?.reloadRowsAtIndexPaths(change, withRowAnimation: .Automatic)
} else {
// Reload
self.albumsViewController?.tableView?.reloadData()
}
}
})
}
// MARK: Private helper methods
func updateDoneButton() {
// Get selection count
if let numberOfSelectedAssets = photosDataSource?.selectionCount() {
// Find right button
if let subViews = navigationController?.navigationBar.subviews {
for view in subViews {
if let btn = view as? UIButton where checkIfRightButtonItem(btn) {
// Store original title if we havn't got it
if doneBarButtonTitle == nil {
doneBarButtonTitle = btn.titleForState(.Normal)
}
// Update title
if numberOfSelectedAssets > 0 {
btn.bs_setTitleWithoutAnimation("\(doneBarButtonTitle!) (\(numberOfSelectedAssets))", forState: .Normal)
} else {
btn.bs_setTitleWithoutAnimation(doneBarButtonTitle!, forState: .Normal)
}
// Stop loop
break
}
}
}
// Enabled
if numberOfSelectedAssets > 0 {
doneBarButton.enabled = true
} else {
doneBarButton.enabled = false
}
}
}
// Check if a give UIButton is the right UIBarButtonItem in the navigation bar
// Somewhere along the road, our UIBarButtonItem gets transformed to an UINavigationButton
// A private apple class that subclasses UIButton
func checkIfRightButtonItem(btn: UIButton) -> Bool {
var isRightButton = false
if let rightButton = navigationItem.rightBarButtonItem {
// Store previous values
var wasRightEnabled = rightButton.enabled
var wasButtonEnabled = btn.enabled
// Set a known state for both buttons
rightButton.enabled = false
btn.enabled = false
// Change one and see if other also changes
rightButton.enabled = true
isRightButton = btn.enabled
// Reset
rightButton.enabled = wasRightEnabled
btn.enabled = wasButtonEnabled
}
return isRightButton
}
func syncSelectionInDataSource(dataSource: PhotosDataSource, withCollectionView collectionView: UICollectionView) {
// Get indexpaths of selected assets
let indexPaths = dataSource.selectedIndexPaths()
// Loop through them and set them as selected in the collection view
for indexPath in indexPaths {
collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
}
// MARK: UINavigationControllerDelegate
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == .Push {
return expandAnimator
} else {
return shrinkAnimator
}
}
}
|
cbdd4ec4f54aaa876ba9e0e5cfc235cd
| 42.782313 | 281 | 0.635125 | false | false | false | false |
XSega/Words
|
refs/heads/master
|
Words/WordsAPIDataManager.swift
|
mit
|
1
|
//
// WordsAPIDataManager.swift
// Words
//
// Created by Sergey Ilyushin on 10/08/2017.
// Copyright © 2017 Sergey Ilyushin. All rights reserved.
//
import Foundation
protocol IWordsAPIDataManager: class {
func requestUserWords(email: String, token: String, completionHandler: (([UserWord]) -> Void)?, errorHandler: ((Error) -> Void)?)
}
class WordsAPIDataManager: IWordsAPIDataManager {
// MARK:- Public vars
var api: IWordsAPI!
init(api: IWordsAPI) {
self.api = api
}
func requestUserWords(email: String, token: String, completionHandler: (([UserWord]) -> Void)?, errorHandler: ((Error) -> Void)?) {
let succesHandler = {[unowned self](apiWords: [APIUserWord]) in
let words = self.userWordFromAPI(apiWords: apiWords)
completionHandler?(words)
}
let wrongHandler = {(error: Error) in
print(error.localizedDescription)
errorHandler?(error)
}
api.requestUserWords(email: email, token: token, completionHandler: succesHandler, errorHandler: wrongHandler)
}
// MARK:- Load meaning from Skyeng user words
fileprivate func userWordFromAPI(apiWords: [APIUserWord]) -> [UserWord] {
var words = [UserWord]()
for apiWord in apiWords {
let progress = (1 - apiWord.progress) * 10
let word = UserWord(identifier: apiWord.identifier, progress: Int(progress))
words.append(word)
}
return words
}
}
|
d1bcebd3e32d922f02d4bd7ff6ab80cb
| 31.446809 | 135 | 0.630164 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
test/SILGen/switch_var.swift
|
apache-2.0
|
11
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func runced(x x: Int) -> Bool { return true }
func funged(x x: Int) -> Bool { return true }
func ansed(x x: Int) -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func foos() -> String { return "" }
func bars() -> String { return "" }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
func a(x x: Int) {}
func b(x x: Int) {}
func c(x x: Int) {}
func d(x x: Int) {}
func a(x x: String) {}
func b(x x: String) {}
func aa(x x: (Int, Int)) {}
func bb(x x: (Int, Int)) {}
func cc(x x: (Int, Int)) {}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// When all of the bindings in a column are immutable, don't emit a mutable
// box. <rdar://problem/15873365>
// CHECK-LABEL: sil hidden @_TF10switch_var8test_letFT_T_ : $@convention(thin) () -> () {
func test_let() {
// CHECK: [[FOOS:%.*]] = function_ref @_TF10switch_var4foosFT_SS
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: retain_value [[VAL]]
// CHECK: function_ref @_TF10switch_var6runcedFT_Sb
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
switch foos() {
case let x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[A:%.*]] = function_ref @_TF10switch_var1aFT1xSS_T_
// CHECK: retain_value [[VAL]]
// CHECK: apply [[A]]([[VAL]])
// CHECK: release_value [[VAL]]
// CHECK: release_value [[VAL]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: release_value [[VAL]]
// CHECK: br [[TRY_CASE2:bb[0-9]+]]
// CHECK: [[TRY_CASE2]]:
// CHECK: retain_value [[VAL]]
// CHECK: function_ref @_TF10switch_var6fungedFT_Sb
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[B:%.*]] = function_ref @_TF10switch_var1bFT1xSS_T_
// CHECK: retain_value [[VAL]]
// CHECK: apply [[B]]([[VAL]])
// CHECK: release_value [[VAL]]
// CHECK: release_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: retain_value [[VAL]]
// CHECK: function_ref @_TF10switch_var4barsFT_SS
// CHECK: retain_value [[VAL]]
// CHECK: cond_br {{%.*}}, [[YES_CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// CHECK: [[YES_CASE3]]:
// CHECK: release_value [[VAL]]
// CHECK: release_value [[VAL]]
// ExprPatterns implicitly contain a 'let' binding.
case bars():
// CHECK: function_ref @_TF10switch_var1cFT_T_
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: release_value [[VAL]]
// CHECK: br [[LEAVE_CASE3:bb[0-9]+]]
// CHECK: [[LEAVE_CASE3]]:
case _:
// CHECK: release_value [[VAL]]
// CHECK: function_ref @_TF10switch_var1dFT_T_
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// If one of the bindings is a "var", allocate a box for the column.
// CHECK-LABEL: sil hidden @_TF10switch_var18test_mixed_let_varFT_T_ : $@convention(thin) () -> () {
func test_mixed_let_var() {
// CHECK: [[FOOS:%.*]] = function_ref @_TF10switch_var4foosFT_SS
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
switch foos() {
case let x where runced():
// CHECK: [[A:%.*]] = function_ref @_TF10switch_var1aFT1xSS_T_
// CHECK: retain_value [[VAL]]
// CHECK: apply [[A]]([[VAL]])
a(x: x)
case let y where funged():
// CHECK: [[B:%.*]] = function_ref @_TF10switch_var1bFT1xSS_T_
// CHECK: retain_value [[VAL]]
// CHECK: apply [[B]]([[VAL]])
b(x: y)
case bars():
c()
case _:
d()
}
}
|
87f7718394493df2bee027aca968f633
| 29.133333 | 100 | 0.548918 | false | false | false | false |
deege/deegeu-ios-swift-make-phone-talk
|
refs/heads/master
|
deegeu-ios-swift-make-phone-talk/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// deegeu-ios-swift-make-phone-talk
//
// Created by Daniel Spiess on 11/13/15.
// Copyright © 2015 Daniel Spiess. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, AVSpeechSynthesizerDelegate {
let speechSynthesizer = AVSpeechSynthesizer()
var speechVoice : AVSpeechSynthesisVoice?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
speechSynthesizer.delegate = self
// This is a hack since the following line doesn't work. You also need to
// make sure the voices are downloaded.
//speechUtterance.voice = AVSpeechSynthesisVoice(language: "en-AU")
let voices = AVSpeechSynthesisVoice.speechVoices()
for voice in voices {
if "en-AU" == voice.language {
self.speechVoice = voice
break;
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// This is the action called when the user presses the button.
@IBAction func speak(sender: AnyObject) {
let speechUtterance = AVSpeechUtterance(string: "How can you tell which one of your friends has the new iPhone 6s plus?")
// set the voice
speechUtterance.voice = self.speechVoice
// rate is 0.0 to 1.0 (default defined by AVSpeechUtteranceDefaultSpeechRate)
speechUtterance.rate = 0.1
// multiplier is between >0.0 and 2.0 (default 1.0)
speechUtterance.pitchMultiplier = 1.25
// Volume from 0.0 to 1.0 (default 1.0)
speechUtterance.volume = 0.75
// Delays before and after saying the phrase
speechUtterance.preUtteranceDelay = 0.0
speechUtterance.postUtteranceDelay = 0.0
speechSynthesizer.speakUtterance(speechUtterance)
// Give the answer, but with a different voice
let speechUtterance2 = AVSpeechUtterance(string: "Don't worry, they'll tell you.")
speechUtterance2.voice = self.speechVoice
speechSynthesizer.speakUtterance(speechUtterance2)
}
// Called before speaking an utterance
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didStartSpeechUtterance utterance: AVSpeechUtterance) {
print("About to say '\(utterance.speechString)'");
}
// Called when the synthesizer is finished speaking the utterance
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didFinishSpeechUtterance utterance: AVSpeechUtterance) {
print("Finished saying '\(utterance.speechString)");
}
// This method is called before speaking each word in the utterance.
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
let startIndex = utterance.speechString.startIndex.advancedBy(characterRange.location)
let endIndex = startIndex.advancedBy(characterRange.length)
print("Will speak the word '\(utterance.speechString.substringWithRange(startIndex..<endIndex))'");
}
}
|
297536d4464525d52ac418e1941e37e1
| 37.55814 | 146 | 0.679131 | false | false | false | false |
FuzzyHobbit/bitcoin-swift
|
refs/heads/master
|
BitcoinSwiftTests/MessageHeaderTests.swift
|
apache-2.0
|
1
|
//
// MessageHeaderTests.swift
// BitcoinSwift
//
// Created by Kevin Greene on 8/24/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import BitcoinSwift
import XCTest
class MessageHeaderTests: XCTestCase {
let network = Message.Network.MainNet
let command = Message.Command.Version
let headerBytes: [UInt8] = [
0xf9, 0xbe, 0xb4, 0xd9, // network (little-endian)
0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x00, // "version" command
0x02, 0x00, 0x00, 0x00, // payload size (little-endian)
0xf1, 0x58, 0x13, 0xfa] // payload checksum
var headerData: NSData!
var header: Message.Header!
override func setUp() {
super.setUp()
headerData = NSData(bytes: headerBytes, length: headerBytes.count)
header = Message.Header(network: network,
command: command,
payloadLength: 2,
payloadChecksum: 0xfa1358f1)
}
func testMessageHeaderEncoding() {
XCTAssertEqual(header.bitcoinData, headerData)
}
func testMessageHeaderDecoding() {
let stream = NSInputStream(data: headerData)
stream.open()
if let testHeader = Message.Header.fromBitcoinStream(stream) {
XCTAssertEqual(testHeader, header)
} else {
XCTFail("Failed to parse message header")
}
XCTAssertFalse(stream.hasBytesAvailable)
stream.close()
}
}
|
7dce49c19965186b9d4a37282cefaed6
| 27.979592 | 98 | 0.656338 | false | true | false | false |
lllyyy/LY
|
refs/heads/master
|
U17-master/U17/U17/Procedure/Comic/View/UGuessLikeTCell.swift
|
mit
|
1
|
//
// UGuessLikeTCell.swift
// U17
//
// Created by charles on 2017/11/27.
// Copyright © 2017年 None. All rights reserved.
//
import UIKit
typealias UGuessLikeTCellDidSelectClosure = (_ comic: ComicModel) -> Void
class UGuessLikeTCell: UBaseTableViewCell {
private var didSelectClosure: UGuessLikeTCellDidSelectClosure?
private lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10)
layout.scrollDirection = .horizontal
let cw = UICollectionView(frame: .zero, collectionViewLayout: layout)
cw.backgroundColor = self.contentView.backgroundColor
cw.delegate = self
cw.dataSource = self
cw.isScrollEnabled = false
cw.register(cellType: UComicCCell.self)
return cw
}()
override func configUI() {
let titileLabel = UILabel().then{
$0.text = "猜你喜欢"
}
contentView.addSubview(titileLabel)
titileLabel.snp.makeConstraints{
$0.top.left.right.equalToSuperview().inset(UIEdgeInsetsMake(15, 15, 15, 15))
$0.height.equalTo(20)
}
contentView.addSubview(collectionView)
collectionView.snp.makeConstraints {
$0.top.equalTo(titileLabel.snp.bottom).offset(5)
$0.left.bottom.right.equalToSuperview()
}
}
var model: GuessLikeModel? {
didSet {
self.collectionView.reloadData()
}
}
}
extension UGuessLikeTCell: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return model?.comics?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = floor((collectionView.frame.width - 50) / 4)
let height = collectionView.frame.height - 10
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: UComicCCell.self)
cell.style = .withTitle
cell.model = model?.comics?[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let comic = model?.comics?[indexPath.row],
let didSelectClosure = didSelectClosure else { return }
didSelectClosure(comic)
}
func didSelectClosure(_ closure: UGuessLikeTCellDidSelectClosure?) {
didSelectClosure = closure
}
}
|
a97be7c5360b65b6ecc7f82cd4f14587
| 33.035714 | 160 | 0.667716 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/Lumia/Lumia/Component/ScrollExample/SimpleScrollView.swift
|
mit
|
1
|
import UIKit
class SimpleScrollView: UIView {
var contentView: UIView? {
didSet {
oldValue?.removeFromSuperview()
if let contentView = contentView {
addSubview(contentView)
contentView.frame = CGRect(origin: contentOrigin, size: contentSize)
}
}
}
var contentSize: CGSize = .zero {
didSet {
contentView?.frame.size = contentSize
}
}
var contentOffset: CGPoint = .zero {
didSet {
contentView?.frame.origin = contentOrigin
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private
private enum State {
case `default`
case dragging(initialOffset: CGPoint)
}
private var contentOrigin: CGPoint { return CGPoint(x: -contentOffset.x, y: -contentOffset.y) }
private var contentOffsetBounds: CGRect {
let width = contentSize.width - bounds.width
let height = contentSize.height - bounds.height
return CGRect(x: 0, y: 0, width: width, height: height)
}
private let panRecognizer = UIPanGestureRecognizer()
private var lastPan: Date?
private var state: State = .default
private var contentOffsetAnimation: TimerAnimation?
private func setup() {
addGestureRecognizer(panRecognizer)
panRecognizer.addTarget(self, action: #selector(handlePanRecognizer))
}
@objc private func handlePanRecognizer(_ sender: UIPanGestureRecognizer) {
let newPan = Date()
switch sender.state {
case .began:
stopOffsetAnimation()
state = .dragging(initialOffset: contentOffset)
case .changed:
let translation = sender.translation(in: self)
if case .dragging(let initialOffset) = state {
contentOffset = clampOffset(initialOffset - translation)
}
case .ended:
state = .default
// Pan gesture recognizers report a non-zero terminal velocity even
// when the user had stopped dragging:
// https://stackoverflow.com/questions/19092375/how-to-determine-true-end-velocity-of-pan-gesture
// In virtually all cases, the pan recognizer seems to call this
// handler at intervals of less than 100ms while the user is
// dragging, so if this call occurs outside that window, we can
// assume that the user had stopped, and finish scrolling without
// deceleration.
let userHadStoppedDragging = newPan.timeIntervalSince(lastPan ?? newPan) >= 0.1
let velocity: CGPoint = userHadStoppedDragging ? .zero : sender.velocity(in: self)
completeGesture(withVelocity: -velocity)
case .cancelled, .failed:
state = .default
case .possible:
break
@unknown default:
fatalError()
}
lastPan = newPan
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// Freeze the scroll view at its current position so that the user can
// interact with its content or scroll it.
stopOffsetAnimation()
}
private func stopOffsetAnimation() {
contentOffsetAnimation?.invalidate()
contentOffsetAnimation = nil
}
private func startDeceleration(withVelocity velocity: CGPoint) {
let d = UIScrollView.DecelerationRate.normal.rawValue
let parameters = DecelerationTimingParameters(initialValue: contentOffset, initialVelocity: velocity,
decelerationRate: d, threshold: 0.5)
let destination = parameters.destination
let intersection = getIntersection(rect: contentOffsetBounds, segment: (contentOffset, destination))
let duration: TimeInterval
if let intersection = intersection, let intersectionDuration = parameters.duration(to: intersection) {
duration = intersectionDuration
} else {
duration = parameters.duration
}
contentOffsetAnimation = TimerAnimation(
duration: duration,
animations: { [weak self] _, time in
self?.contentOffset = parameters.value(at: time)
},
completion: { [weak self] finished in
guard finished && intersection != nil else { return }
let velocity = parameters.velocity(at: duration)
self?.bounce(withVelocity: velocity)
})
}
private func bounce(withVelocity velocity: CGPoint) {
let restOffset = contentOffset.clamped(to: contentOffsetBounds)
let displacement = contentOffset - restOffset
let threshold = 0.5 / UIScreen.main.scale
let spring = Spring(mass: 1, stiffness: 100, dampingRatio: 1)
let parameters = SpringTimingParameters(spring: spring,
displacement: displacement,
initialVelocity: velocity,
threshold: threshold)
contentOffsetAnimation = TimerAnimation(
duration: parameters.duration,
animations: { [weak self] _, time in
self?.contentOffset = restOffset + parameters.value(at: time)
})
}
private func clampOffset(_ offset: CGPoint) -> CGPoint {
let rubberBand = RubberBand(dims: bounds.size, bounds: contentOffsetBounds)
return rubberBand.clamp(offset)
}
private func completeGesture(withVelocity velocity: CGPoint) {
if contentOffsetBounds.containsIncludingBorders(contentOffset) {
startDeceleration(withVelocity: velocity)
} else {
bounce(withVelocity: velocity)
}
}
}
|
9c6ba4fbec4ff2118f13d7d237065742
| 34.971591 | 110 | 0.586005 | false | false | false | false |
pixyzehn/EsaKit
|
refs/heads/master
|
Sources/EsaKit/Models/EsaError.swift
|
mit
|
1
|
//
// EsaError.swift
// EsaKit
//
// Created by pixyzehn on 2016/11/22.
// Copyright © 2016 pixyzehn. All rights reserved.
//
import Foundation
/// An error from the API.
public struct EsaError: Error, AutoEquatable, AutoHashable {
public let error: String
public let message: String
enum Key: String {
case error
case message
}
public init(error: String, message: String = "") {
self.error = error
self.message = message
}
}
extension EsaError: CustomStringConvertible {
public var description: String {
return message
}
}
extension EsaError: Decodable {
public static func decode(json: Any) throws -> EsaError {
guard let dictionary = json as? [String: Any] else {
throw DecodeError.invalidFormat(json: json)
}
guard let error = dictionary[Key.error.rawValue] as? String else {
throw DecodeError.missingValue(key: Key.error.rawValue, actualValue: dictionary[Key.error.rawValue])
}
guard let message = dictionary[Key.message.rawValue] as? String else {
throw DecodeError.missingValue(key: Key.message.rawValue, actualValue: dictionary[Key.message.rawValue])
}
return EsaError(
error: error,
message: message
)
}
}
|
1affe5952469b27380dd8338cbd8230d
| 24.615385 | 116 | 0.635135 | false | false | false | false |
MichaelJordanYang/JDYangDouYuZB
|
refs/heads/master
|
JDYDouYuZb/JDYDouYuZb/Application/Classes/Tools/Extenstion(给系统的类做扩展)/UIBarButtonItem-Extension.swift
|
mit
|
1
|
//
// UIBarButtonItem-Extension.swift
// JDYDouYuZb
//
// Created by xiaoyang on 2016/12/29.
// Copyright © 2016年 JDYang. All rights reserved.
//
//导入UIKit框架才能用CG开头的东西
import UIKit
//给系统类做扩展
extension UIBarButtonItem{
/*
扩充类方法
class func createItem(imageName : String, hightImageName : String, size : CGSize) ->UIBarButtonItem{ //返回一个UIBarButtonItem
//创建按钮
let btn = UIButton()
//设置按钮属性
btn.setImage(UIImage(named: imageName), for: .normal)
btn.setImage(UIImage(named: hightImageName), for: .highlighted)
//给按钮设置尺寸
btn.frame = CGRect(origin: CGPoint.zero, size: size)
//将自定义按钮返回出去
return UIBarButtonItem(customView: btn)
}
*/
//扩充构造函数
//遍历构造函数: 1> 以convenience开头 2>在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName : String, hightImageName : String = "", size : CGSize = CGSize.zero) {
//创建按钮
let btn = UIButton()
//设置按钮图片
btn.setImage(UIImage(named: imageName), for: .normal)
if hightImageName != "" {
btn.setImage(UIImage(named: hightImageName), for: .highlighted)
}
//给按钮设置尺寸
if size == CGSize.zero {
btn.sizeToFit()
}else{
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
//创建UIBarButtonItem
self.init(customView : btn)
}
}
|
cc02149eb7b52c28fb4784af4877dda9
| 25.285714 | 126 | 0.57337 | false | false | false | false |
slabgorb/Tiler
|
refs/heads/master
|
Tiler/ImageViewCell.swift
|
mit
|
1
|
//
// ImageViewCell.swift
// Tiler
//
// Created by Keith Avery on 4/1/16.
// Copyright © 2016 Keith Avery. All rights reserved.
//
import UIKit
class ImageViewCell: UICollectionViewCell {
func setItem(item: ImageItem) {
let imageView: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height))
imageView.image = UIImage(named: item.name)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.addSubview(imageView)
self.backgroundColor = UIColor.whiteColor()
self.layer.borderColor = UIColor.blackColor().CGColor
self.layer.borderWidth = 1
}
}
|
6cbd672055562ff7a2c0496386b9050c
| 28.217391 | 129 | 0.686012 | false | false | false | false |
wwq0327/iOS9Example
|
refs/heads/master
|
DemoLists/DemoLists/HomeTableViewController.swift
|
apache-2.0
|
1
|
//
// HomeTableViewController.swift
// DemoLists
//
// Created by wyatt on 15/12/3.
// Copyright © 2015年 Wanqing Wang. All rights reserved.
//
import UIKit
class HomeTableViewController: UITableViewController {
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()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
// override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// // #warning Incomplete implementation, return the number of rows
// return 10
// }
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
d91891f9d6dd50d7404e5acb3751acb6
| 33.168421 | 157 | 0.685767 | false | false | false | false |
synergistic-fantasy/wakeonlan-osx
|
refs/heads/master
|
WakeOnLAN-OSX/Controllers/EditComputerViewController.swift
|
gpl-3.0
|
1
|
//
// EditComputerViewController.swift
// WakeOnLAN-OSX
//
// Created by Mario Estrella on 12/22/15.
// Copyright © 2015 Synergistic Fantasy LLC. All rights reserved.
//
import Cocoa
class EditComputerViewController: InputDialogViewController {
// MARK: - Variables
@IBOutlet weak var editCompName: NSTextField!
@IBOutlet weak var editMacAddr: NSTextField!
@IBOutlet weak var editIpAddr: NSTextField!
@IBOutlet weak var editSubnet: NSComboBox!
@IBOutlet weak var editButtonState: NSButton!
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
editButtonState.enabled = false
editSubnet.addItemsWithObjectValues(listOfSubnets)
loadComputer()
// Do view setup here.
}
override func controlTextDidChange(obj: NSNotification) {
validateFields()
}
// MARK: - Button Actions
@IBAction func cancel(sender: AnyObject) {
dismissViewController(self)
}
@IBAction func edit(sender: AnyObject) {
if currentComputer.compName! == editCompName.stringValue.uppercaseString {
editComputer()
saveItem()
dismissViewController(self)
} else if currentComputer.macAddress! == editMacAddr.stringValue.uppercaseString {
editComputer()
saveItem()
dismissViewController(self)
} else if isDuplicate(editCompName.stringValue.uppercaseString, currentMac: editMacAddr.stringValue.uppercaseString) {
editButtonState.enabled = false
} else {
editComputer()
saveItem()
dismissViewController(self)
}
}
func editComputer() {
currentComputer.compName = editCompName.stringValue.uppercaseString
currentComputer.macAddress = editMacAddr.stringValue.uppercaseString
currentComputer.ipAddress = editIpAddr.stringValue
if editIpAddr.stringValue == "" {
currentComputer.subnet = ""
} else {
currentComputer.subnet = editSubnet.stringValue
}
}
// MARK: - Functions
func loadComputer() {
editCompName.stringValue = currentComputer.compName!
editMacAddr.stringValue = currentComputer.macAddress!
editIpAddr.stringValue = currentComputer.ipAddress!
editSubnet.stringValue = currentComputer.subnet!
validateFields()
}
func validateFields() {
textFieldValidation(editCompName, type: .name)
textFieldValidation(editMacAddr, type: .mac)
textFieldValidation(editIpAddr, type: .ip)
buttonState(editButtonState)
}
}
|
bedce70534a0f9569ec0713665eb0faa
| 27.957895 | 126 | 0.640131 | false | false | false | false |
ozgur/AutoLayoutAnimation
|
refs/heads/master
|
autolayoutanimation/NestedObjectMapperViewController.swift
|
mit
|
1
|
//
// NestedObjectMapperViewController.swift
// AutoLayoutAnimation
//
// Created by Ozgur Vatansever on 10/20/15.
// Copyright © 2015 Techshed. All rights reserved.
//
import UIKit
import ObjectMapper
import Cartography
extension Mapper {
}
class NestedObjectMapperViewController: UIViewController {
@IBOutlet fileprivate weak var imageView: UIImageView!
convenience init() {
self.init(nibName: "NestedObjectMapperViewController", bundle: Bundle.main)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
edgesForExtendedLayout = UIRectEdge()
title = "Nesting Objects"
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let city = Mapper<City>().map(readJSONFile("City"))
imageView.image = city?.image
}
}
class ZipcodeTransform: TransformType {
typealias Object = [String]
typealias JSON = String
func transformFromJSON(_ value: AnyObject?) -> [String]? {
if let value = value as? String {
return value.components(separatedBy: ",").map { value in
return value.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
return nil
}
func transformToJSON(_ value: [String]?) -> String? {
guard let value = value else {
return nil
}
return value.joined(separator: ",")
}
}
class City: Mappable {
var name: String!
var state: String!
var population: Int!
var zipcode: [String]!
var image: UIImage!
var elevation: Float!
var water: Float!
var land: Float!
var government: CityGovernment!
required init?(_ map: Map) {
}
func mapping(_ map: Map) {
name <- map["name"]
state <- map["state"]
population <- map["population"]
zipcode <- (map["zipcode"], ZipcodeTransform())
elevation <- map["area.elevation"]
water <- map["area.water"]
land <- map["area.land"]
government <- map["government"]
let imageTransform = TransformOf<UIImage, String>(
fromJSON: { (imageName) -> UIImage? in
guard let imageName = imageName else {
return nil
}
let image = UIImage(named: imageName)
image?.accessibilityIdentifier = imageName
return image
},
toJSON: { (image) -> String? in
return image?.accessibilityIdentifier
}
)
image <- (map["image"], imageTransform)
}
}
class CityGovernment: CustomStringConvertible, Mappable {
var type: String!
var mayor: String!
var supervisors: [String]!
required init?(_ map: Map) {
}
func mapping(_ map: Map) {
type <- map["type"]
mayor <- map["mayor"]
supervisors <- map["supervisors"]
}
var description: String {
return "<Government: \(type) | \(mayor)>"
}
}
|
11e8bd123804edf36381240caf64fb62
| 21.860656 | 80 | 0.642166 | false | false | false | false |
mayongl/CS193P
|
refs/heads/master
|
Smashtag/Smashtag/TweetTableViewController.swift
|
apache-2.0
|
1
|
//
// TweetTableViewController.swift
// Smashtag
//
// Created by Yonglin Ma on 4/8/17.
// Copyright © 2017 Sixlivesleft. All rights reserved.
//
import UIKit
import Twitter
class TweetTableViewController: UITableViewController, UITextFieldDelegate {
private var tweets = [Array<Twitter.Tweet>]() {
didSet {
//print(tweets)
}
}
var searchText: String? {
didSet {
searchTextField?.text = searchText
searchTextField?.resignFirstResponder()
lastTwitterRequest = nil // REFRESHING
tweets.removeAll()
tableView.reloadData()
searchForTweets()
title = searchText
}
}
func insertTweets(_ newTweets: [Twitter.Tweet]) {
self.tweets.insert(newTweets, at: 0)
self.tableView.insertSections([0], with: .fade)
}
//MARK: Updating the Table
private func twitterRequest() -> Twitter.Request? {
if let query = searchText, !query.isEmpty {
return Twitter.Request(search: query, count: 100)
}
return nil
}
private var lastTwitterRequest: Twitter.Request?
private func searchForTweets() {
if let request = lastTwitterRequest?.newer ?? twitterRequest() {
lastTwitterRequest = request
request.fetchTweets { [weak self] newTweets in
DispatchQueue.main.async {
if request == self?.lastTwitterRequest {
self?.insertTweets(newTweets)
}
self?.refreshControl?.endRefreshing()
}
}
} else {
self.refreshControl?.endRefreshing()
}
}
@IBAction func refresh(_ sender: UIRefreshControl) {
searchForTweets()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
// 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()
//searchText = "#standford"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var searchTextField: UITextField! {
didSet {
searchTextField.delegate = self
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == searchTextField {
searchText = searchTextField.text
}
return true
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return tweets.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return tweets[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Tweet", for: indexPath)
// Configure the cell...
let tweet: Twitter.Tweet = tweets[indexPath.section][indexPath.row]
if let tweetCell = cell as? TweetTableViewCell {
tweetCell.tweet = tweet
}
// cell.textLabel?.text = tweet.text
// cell.detailTextLabel?.text = tweet.user.name
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "\(tweets.count-section)"
}
/*
// 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.
}
*/
}
|
35fd9d4d9e4553087e1fcde412fa1a4e
| 31.561798 | 137 | 0.617322 | false | false | false | false |
notjosh/SnapshotTestingDemo
|
refs/heads/master
|
SnapshotTestingDemoTests/BWIconViewSpec.swift
|
mit
|
1
|
//
// BWIconViewSpec.swift
// SnapshotTestingDemo
//
// Created by joshua may on 9/07/2015.
// Copyright © 2015 notjosh, inc. All rights reserved.
//
import Quick
import Nimble
import Nimble_Snapshots
import UIKit
class BWIconViewSpec: QuickSpec {
override func spec() {
describe("in BWMeasurementIconView", { () -> () in
var view:BWMeasurementIconView?
beforeEach({ () -> () in
view = BWMeasurementIconView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// defaults
view!.color = UIColor.blueColor()
view!.path = UIBezierPath(ovalInRect: view!.bounds)
})
it("works") {
// expect(view!).to(recordSnapshot())
expect(view!).to(haveValidSnapshot())
}
// these prove less and less valuable and harder to maintain, but here for the demo:
it("scales image") {
view!.iconScale = 2
// expect(view!).to(recordSnapshot())
expect(view!).to(haveValidSnapshot())
}
it("colours image") {
view!.backgroundColor = UIColor.yellowColor()
view!.color = UIColor.redColor()
// expect(view!).to(recordSnapshot())
expect(view!).to(haveValidSnapshot())
}
it("does path stuff") {
view!.path = UIBezierPath(ovalInRect: CGRect(x: 20, y: 10, width: 40, height: 60))
// expect(view!).to(recordSnapshot())
expect(view!).to(haveValidSnapshot())
}
});
}
}
|
82b21b142706e9d5d91fc99e86caf683
| 28.714286 | 98 | 0.524639 | false | false | false | false |
lzpfmh/actor-platform
|
refs/heads/master
|
actor-apps/app-ios/ActorCore/Conversions.swift
|
mit
|
1
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
extension NSData {
func toJavaBytes() -> IOSByteArray {
return IOSByteArray(bytes: UnsafePointer<jbyte>(self.bytes), count: UInt(self.length))
}
func readUInt8() -> UInt8 {
var raw: UInt8 = 0;
self.getBytes(&raw, length: 1)
return raw
}
func readUInt8(offset: Int) -> UInt8 {
var raw: UInt8 = 0;
self.getBytes(&raw, range: NSMakeRange(offset, 1))
return raw
}
func readUInt32() -> UInt32 {
var raw: UInt32 = 0;
self.getBytes(&raw, length: 4)
return raw.bigEndian
}
func readUInt32(offset: Int) -> UInt32 {
var raw: UInt32 = 0;
self.getBytes(&raw, range: NSMakeRange(offset, 4))
return raw.bigEndian
}
func readNSData(offset: Int, len: Int) -> NSData {
return self.subdataWithRange(NSMakeRange(Int(offset), Int(len)))
}
}
extension ACMessage {
var isOut: Bool {
get {
return Actor.myUid() == self.senderId
}
}
}
//extension ACAuthStateEnum {
//
//}
//
////public func ==(lhs: ACAuthStateEnum, rhs: ACAuthStateEnum) -> Bool {
//// return lhs.ordinal() == rhs.ordinal()
////}
extension JavaUtilAbstractCollection : SequenceType {
public func generate() -> NSFastGenerator {
return NSFastGenerator(self)
}
}
extension ACPeer {
var isGroup: Bool {
get {
return UInt(self.peerType.ordinal()) == ACPeerType.GROUP.rawValue
}
}
}
extension NSMutableData {
func appendUInt32(value: UInt32) {
var raw = value.bigEndian
self.appendBytes(&raw, length: 4)
}
func appendByte(value: UInt8) {
var raw = value
self.appendBytes(&raw, length: 1)
}
}
extension jlong {
func toNSNumber() -> NSNumber {
return NSNumber(longLong: self)
}
}
extension jint {
func toNSNumber() -> NSNumber {
return NSNumber(int: self)
}
}
extension JavaLangLong {
func toNSNumber() -> NSNumber {
return NSNumber(longLong: self.longLongValue())
}
}
extension ARListEngineRecord {
func dbQuery() -> AnyObject {
if (self.getQuery() == nil) {
return NSNull()
} else {
return self.getQuery().lowercaseString
}
}
}
extension NSMutableData {
/** Convenient way to append bytes */
internal func appendBytes(arrayOfBytes: [UInt8]) {
self.appendBytes(arrayOfBytes, length: arrayOfBytes.count)
}
}
extension NSData {
public func checksum() -> UInt16 {
var s:UInt32 = 0;
var bytesArray = self.bytes();
for (var i = 0; i < bytesArray.count; i++) {
s = s + UInt32(bytesArray[i])
}
s = s % 65536;
return UInt16(s);
}
}
extension JavaUtilArrayList {
func toSwiftArray<T>() -> [T] {
var res = [T]()
for i in 0..<self.size() {
res.append(self.getWithInt(i) as! T)
}
return res
}
func toSwiftArray() -> [AnyObject] {
var res = [AnyObject]()
for i in 0..<self.size() {
res.append(self.getWithInt(i))
}
return res
}
}
extension IOSObjectArray {
func toSwiftArray<T>() -> [T] {
var res = [T]()
for i in 0..<self.length() {
res.append(self.objectAtIndex(UInt(i)) as! T)
}
return res
}
func toSwiftArray() -> [AnyObject] {
var res = [AnyObject]()
for i in 0..<self.length() {
res.append(self.objectAtIndex(UInt(i)))
}
return res
}
}
extension NSData {
public var hexString: String {
return self.toHexString()
}
func toHexString() -> String {
let count = self.length / sizeof(UInt8)
var bytesArray = [UInt8](count: count, repeatedValue: 0)
self.getBytes(&bytesArray, length:count * sizeof(UInt8))
var s:String = "";
for byte in bytesArray {
s = s + (NSString(format:"%02X", byte) as String)
}
return s;
}
func bytes() -> [UInt8] {
let count = self.length / sizeof(UInt8)
var bytesArray = [UInt8](count: count, repeatedValue: 0)
self.getBytes(&bytesArray, length:count * sizeof(UInt8))
return bytesArray
}
class public func withBytes(bytes: [UInt8]) -> NSData {
return NSData(bytes: bytes, length: bytes.count)
}
}
|
fa1835e03cb8896be59f6b9714f4e47b
| 21.930348 | 94 | 0.551649 | false | false | false | false |
djfink-carglass/analytics-ios
|
refs/heads/dev
|
AnalyticsTests/UserDefaultsStorageTest.swift
|
mit
|
2
|
//
// UserDefaultsStorageTest.swift
// Analytics
//
// Copyright © 2016 Segment. All rights reserved.
//
import Quick
import Nimble
import Analytics
class UserDefaultsStorageTest : QuickSpec {
override func spec() {
var storage : SEGUserDefaultsStorage!
beforeEach {
// let crypto = SEGAES256Crypto(password: "thetrees")
// storage = SEGUserDefaultsStorage(defaults: NSUserDefaults.standardUserDefaults(), namespacePrefix: "segment", crypto: crypto)
// storage = SEGUserDefaultsStorage(defaults: NSUserDefaults.standardUserDefaults(), namespacePrefix: nil, crypto: crypto)
storage = SEGUserDefaultsStorage(defaults: UserDefaults.standard, namespacePrefix: nil, crypto: nil)
}
it("persists and loads data") {
let dataIn = "segment".data(using: String.Encoding.utf8)!
storage.setData(dataIn, forKey: "mydata")
let dataOut = storage.data(forKey: "mydata")
expect(dataOut) == dataIn
let strOut = String(data: dataOut!, encoding: .utf8)
expect(strOut) == "segment"
}
it("persists and loads string") {
let str = "san francisco"
storage.setString(str, forKey: "city")
expect(storage.string(forKey: "city")) == str
storage.removeKey("city")
expect(storage.string(forKey: "city")).to(beNil())
}
it("persists and loads array") {
let array = [
"san francisco",
"new york",
"tallinn",
]
storage.setArray(array, forKey: "cities")
expect(storage.array(forKey: "cities") as? Array<String>) == array
storage.removeKey("cities")
expect(storage.array(forKey: "cities")).to(beNil())
}
it("persists and loads dictionary") {
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
storage.setDictionary(dict, forKey: "cityMap")
expect(storage.dictionary(forKey: "cityMap") as? Dictionary<String, String>) == dict
storage.removeKey("cityMap")
expect(storage.dictionary(forKey: "cityMap")).to(beNil())
}
it("should work with crypto") {
let crypto = SEGAES256Crypto(password: "thetrees")
let s = SEGUserDefaultsStorage(defaults: UserDefaults.standard, namespacePrefix: nil, crypto: crypto)
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
s.setDictionary(dict, forKey: "cityMap")
expect(s.dictionary(forKey: "cityMap") as? Dictionary<String, String>) == dict
s.removeKey("cityMap")
expect(s.dictionary(forKey: "cityMap")).to(beNil())
}
it("should work with namespace") {
let crypto = SEGAES256Crypto(password: "thetrees")
let s = SEGUserDefaultsStorage(defaults: UserDefaults.standard, namespacePrefix: "segment", crypto: crypto)
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
s.setDictionary(dict, forKey: "cityMap")
expect(s.dictionary(forKey: "cityMap") as? Dictionary<String, String>) == dict
s.removeKey("cityMap")
expect(s.dictionary(forKey: "cityMap")).to(beNil())
}
afterEach {
storage.resetAll()
}
}
}
|
5b3952f0bd56c0c0337e44ec7c71e720
| 31.106796 | 133 | 0.619595 | false | false | false | false |
rodrigo-lima/ThenKit
|
refs/heads/master
|
Sources/Logger.swift
|
mit
|
1
|
//
// Logger.swift
// ThenKit
//
// Created by Rodrigo Lima on 8/18/15.
// Copyright © 2015 Rodrigo. All rights reserved.
//
// very simple logger
import Foundation
extension String {
var NS: NSString { return (self as NSString) }
}
public struct Logger {
// colors
public enum Color: String {
case black = "0;30m"
case blue = "0;34m"
case green = "0;32m"
case cyan = "0;36m"
case red = "0;31m"
case purple = "0;35m"
case brown = "0;33m"
case gray = "0;37m"
case darkGray = "1;30m"
case lightBlue = "1;34m"
case lightGreen = "1;32m"
case lightCyan = "1;36m"
case lightRed = "1;31m"
case lightPurple = "1;35m"
case yellow = "1;33m"
case white = "1;37m"
}
struct Escape {
static let begin = "\u{001b}["
static let reset = Escape.begin + "0m"
static func escaped(color: Color, _ someString: String) -> String {
return begin + color.rawValue + someString + reset
}
}
/// Level of log message to aid in the filtering of logs
public enum Level: Int, CustomStringConvertible {
/// Messages intended only for debug mode
case debug = 3
/// Messages intended to warn of potential errors
case warn = 2
/// Critical error messagees
case error = 1
/// Log level to turn off all logging
case none = 0
public var description: String {
switch self {
case .debug: return "DEBG"
case .warn: return "WARN"
case .error: return "ERRR"
case .none: return "...."
}
}
}
private static let timestampFormatter: DateFormatter = {
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS zzz"
return fmt
}()
private static func callerDetails(_ fn: String, _ file: String, _ ln: Int) -> String {
let f = file.NS.lastPathComponent.NS.deletingPathExtension
return "[\(f):\(fn):\(ln)]"
}
private static func prepareMessage(level: Level, callerDetails: String, message: String) -> String {
let t = Thread.isMainThread ? "MAIN" : Thread.current.name ?? String(format: "%p", Thread.current)
return "\(level)|\(timestampFormatter.string(from: Date()))@\(t) | \(callerDetails) | \(message) "
}
/// What is the max level to be logged
///
/// Any logs under the given log level will be ignored
public static var logLevel: Level = .debug// for now
// log it
public static func escaped(color: Color, _ messageBlock: @autoclosure () -> String?,
functionName: String=#function, fileName: String=#file, lineNumber: Int=#line) {
if let msg = messageBlock() {
let full = prepareMessage(level: .none, // for colored messages, just skip log level
callerDetails: callerDetails(functionName, fileName, lineNumber),
message: msg)
print(Escape.escaped(color: color, full))
}
}
// when no specific log level is passed, let's assume .DEBUG
public static func log(level: Level = .debug, _ messageBlock: @autoclosure () -> String?,
functionName: String=#function, fileName: String=#file, lineNumber: Int=#line) {
if level.rawValue <= Logger.logLevel.rawValue, let msg = messageBlock() {
let full = prepareMessage(level: level,
callerDetails: callerDetails(functionName, fileName, lineNumber),
message: msg)
switch level {
case .warn:
print(Escape.escaped(color: .yellow, full))
case .error:
print(Escape.escaped(color: .red, full))
default:
print(Escape.reset + full)
}
}
}
}
/** EOF **/
|
5e70c79f1af844620010d7adb9599901
| 33.262712 | 111 | 0.551323 | false | false | false | false |
cliqz-oss/browser-ios
|
refs/heads/development
|
Client/Cliqz/Frontend/Browser/WebView/CliqzWebView.swift
|
mpl-2.0
|
2
|
//
// CliqzWebView.swift
// Client
//
// Created by Sahakyan on 8/3/16.
// Copyright © 2016 Mozilla. All rights reserved.
//
import Foundation
import WebKit
import Shared
let kNotificationAllWebViewsDeallocated = "kNotificationAllWebViewsDeallocated"
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class ContainerWebView : WKWebView {
weak var legacyWebView: CliqzWebView?
}
var globalContainerWebView = ContainerWebView()
var nullWKNavigation: WKNavigation = WKNavigation()
@objc class HandleJsWindowOpen : NSObject {
static func open(_ url: String) {
postAsyncToMain(0) { // we now know JS callbacks can be off main
guard let wv = getCurrentWebView() else { return }
let current = wv.url
if SettingsPrefs.shared.getBlockPopupsPref() {
guard let lastTappedTime = wv.lastTappedTime else { return }
if fabs(lastTappedTime.timeIntervalSinceNow) > 0.75 { // outside of the 3/4 sec time window and we ignore it
return
}
}
wv.lastTappedTime = nil
if let _url = URL(string: url, relativeTo: current) {
let isPrivate = getApp().browserViewController.tabManager.selectedTab?.isPrivate ?? false
getApp().browserViewController.openURLInNewTab(_url, isPrivate: isPrivate)
}
}
}
}
class WebViewToUAMapper {
static fileprivate let idToWebview = NSMapTable<AnyObject, CliqzWebView>(keyOptions: NSPointerFunctions.Options(), valueOptions: [.weakMemory])
static func setId(_ uniqueId: Int, webView: CliqzWebView) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
idToWebview.setObject(webView, forKey: uniqueId as AnyObject)
}
static func removeWebViewWithId(_ uniqueId: Int) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
idToWebview.removeObject(forKey: uniqueId as AnyObject)
}
static func idToWebView(_ uniqueId: Int?) -> CliqzWebView? {
return idToWebview.object(forKey: uniqueId as AnyObject) as? CliqzWebView
}
static func userAgentToWebview(_ userAgent: String?) -> CliqzWebView? {
// synchronize code from this point on.
objc_sync_enter(self)
defer { objc_sync_exit(self) }
guard let userAgent = userAgent else { return nil }
guard let loc = userAgent.range(of: "_id/") else {
// the first created webview doesn't have this id set (see webviewBuiltinUserAgent to explain)
return idToWebview.object(forKey: 1 as AnyObject) as? CliqzWebView
}
let keyString = userAgent.substring(with: loc.upperBound..<userAgent.index(loc.upperBound, offsetBy: 6)) // .upperBound..<index.index(loc.upperBound, offsetBy: 6))
guard let key = Int(keyString) else { return nil }
return idToWebview.object(forKey: key as AnyObject) as? CliqzWebView
}
}
struct CliqzWebViewConstants {
static let kNotificationWebViewLoadCompleteOrFailed = "kNotificationWebViewLoadCompleteOrFailed"
static let kNotificationPageInteractive = "kNotificationPageInteractive"
}
protocol CliqzWebViewDelegate: class {
func updateTabUrl(url: URL?)
}
class CliqzWebView: UIWebView {
weak var navigationDelegate: WKNavigationDelegate?
weak var UIDelegate: WKUIDelegate?
weak var webViewDelegate: CliqzWebViewDelegate?
lazy var configuration: CliqzWebViewConfiguration = { return CliqzWebViewConfiguration(webView: self) }()
lazy var backForwardList: WebViewBackForwardList = { return WebViewBackForwardList(webView: self) } ()
var progress: WebViewProgress?
var allowsBackForwardNavigationGestures: Bool = false
fileprivate let lockQueue = DispatchQueue(label: "com.cliqz.webView.lockQueue", attributes: [])
fileprivate static var containerWebViewForCallbacks = { return ContainerWebView() }()
// This gets set as soon as it is available from the first UIWebVew created
fileprivate static var webviewBuiltinUserAgent: String?
fileprivate var _url: (url: Foundation.URL?, isReliableSource: Bool, prevUrl: Foundation.URL?) = (nil, false, nil)
func setUrl(_ url: Foundation.URL?, reliableSource: Bool) {
_url.prevUrl = _url.url
_url.isReliableSource = reliableSource
if url?.absoluteString.endsWith("?") ?? false {
if let noQuery = url?.absoluteString.components(separatedBy: "?")[0] {
_url.url = Foundation.URL(string: noQuery)
}
} else {
_url.url = url
}
self.url = _url.url
}
dynamic var url: Foundation.URL? /*{
get {
return _url.url
}
}*/
var _loading: Bool = false
override internal dynamic var isLoading: Bool {
get {
if internalLoadingEndedFlag {
// we detected load complete internally –UIWebView sometimes stays in a loading state (i.e. bbc.com)
return false
}
return _loading
}
set {
_loading = newValue
}
}
var _canGoBack: Bool = false
override internal dynamic var canGoBack: Bool {
get {
return _canGoBack
}
set {
_canGoBack = newValue
}
}
var _canGoForward: Bool = false
override internal dynamic var canGoForward: Bool {
get {
return _canGoForward
}
set {
_canGoForward = newValue
}
}
dynamic var estimatedProgress: Double = 0
var title: String = "" {
didSet {
if let item = backForwardList.currentItem {
item.title = title
}
}
}
var knownFrameContexts = Set<NSObject>()
var prevDocumentLocation = ""
var internalLoadingEndedFlag: Bool = false;
var removeProgressObserversOnDeinit: ((UIWebView) -> Void)?
var triggeredLocationCheckTimer = Timer()
var lastTappedTime: Date?
static var modifyLinksScript: WKUserScript?
override class func initialize() {
// Added for modifying page links with target blank to open in new tabs
let path = Bundle.main.path(forResource: "ModifyLinksForNewTab", ofType: "js")!
let source = try! NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String
modifyLinksScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
}
init(frame: CGRect, configuration: WKWebViewConfiguration) {
super.init(frame: frame)
commonInit()
}
// Anti-Tracking
var uniqueId = -1
var unsafeRequests = 0 {
didSet {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationBadRequestDetected), object: self.uniqueId)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
deinit {
CliqzWebView.allocCounter -= 1
if (CliqzWebView.allocCounter == 0) {
NotificationCenter.default.post(name: Notification.Name(rawValue: kNotificationAllWebViewsDeallocated), object: nil)
print("NO LIVE WEB VIEWS")
}
WebViewToUAMapper.removeWebViewWithId(self.uniqueId)
_ = Try(withTry: {
self.removeProgressObserversOnDeinit?(self)
}) { (exception) -> Void in
debugPrint("Failed remove: \(exception)")
}
}
func goToBackForwardListItem(item: LegacyBackForwardListItem) {
if let index = backForwardList.backList.index(of: item) {
let backCount = backForwardList.backList.count - index
for _ in 0..<backCount {
goBack()
}
} else if let index = backForwardList.forwardList.index(of: item) {
for _ in 0..<(index + 1) {
goForward()
}
}
}
func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((AnyObject?, NSError?) -> Void)?) {
ensureMainThread() {
let wrapped = "var result = \(javaScriptString); JSON.stringify(result)"
let evaluatedstring = self.stringByEvaluatingJavaScript(from: wrapped)
var result: AnyObject?
if let dict = self.convertStringToDictionary(evaluatedstring) {
result = dict as AnyObject?
} else {
// in case the result was not dictionary, return the original response (reverse JSON stringify)
result = self.reverseStringify(evaluatedstring) as AnyObject?
}
completionHandler?(result, NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, userInfo: nil))
}
}
override func loadRequest(_ request: URLRequest) {
if let url = request.url,
!ReaderModeUtils.isReaderModeURL(url) {
unsafeRequests = 0
}
super.loadRequest(request)
}
func loadingCompleted() {
if internalLoadingEndedFlag {
return
}
internalLoadingEndedFlag = true
self.configuration.userContentController.injectJsIntoPage()
guard let docLoc = self.stringByEvaluatingJavaScript(from: "document.location.href") else { return }
if docLoc != self.prevDocumentLocation {
if !(self.url?.absoluteString.startsWith(WebServer.sharedInstance.base) ?? false) && !docLoc.startsWith(WebServer.sharedInstance.base) {
self.title = self.stringByEvaluatingJavaScript(from: "document.title") ?? Foundation.URL(string: docLoc)?.baseDomain() ?? ""
}
if let nd = self.navigationDelegate {
globalContainerWebView.legacyWebView = self
nd.webView?(globalContainerWebView, didFinish: nullWKNavigation)
}
}
self.prevDocumentLocation = docLoc
NotificationCenter.default.post(name: Notification.Name(rawValue: CliqzWebViewConstants.kNotificationWebViewLoadCompleteOrFailed), object: self)
}
var customUserAgent:String? /*{
willSet {
if self.customUserAgent == newValue || newValue == nil {
return
}
self.customUserAgent = newValue == nil ? nil : kDesktopUserAgent
// The following doesn't work, we need to kill and restart the webview, and restore its history state
// for this setting to take effect
// let defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
// defaults.registerDefaults(["UserAgent": (self.customUserAgent ?? "")])
}
}*/
func reloadFromOrigin() {
self.reload()
}
func updateUnsafeRequestsCount(_ newCount: Int) {
lockQueue.sync {
self.unsafeRequests = newCount
}
}
// On page load, the contentSize of the webview is updated (**). If the webview has not been notified of a page change (i.e. shouldStartLoadWithRequest was never called) then 'loading' will be false, and we should check the page location using JS.
// (** Not always updated, particularly on back/forward. For instance load duckduckgo.com, then google.com, and go back. No content size change detected.)
func contentSizeChangeDetected() {
if triggeredLocationCheckTimer.isValid {
return
}
// Add a time delay so that multiple calls are aggregated
triggeredLocationCheckTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeoutCheckLocation), userInfo: nil, repeats: false)
}
// Pushstate navigation may require this case (see brianbondy.com), as well as sites for which simple pushstate detection doesn't work:
// youtube and yahoo news are examples of this (http://stackoverflow.com/questions/24297929/javascript-to-listen-for-url-changes-in-youtube-html5-player)
@objc func timeoutCheckLocation() {
func shouldUpdateUrl(_ currentUrl: String, newLocation: String) -> Bool {
if newLocation == currentUrl || newLocation.contains("about:") || newLocation.contains("//localhost") || url?.host != Foundation.URL(string: newLocation)?.host {
return false
}
return true
}
func tryUpdateUrl() {
guard let location = self.stringByEvaluatingJavaScript(from: "window.location.href"), let currentUrl = url?.absoluteString, shouldUpdateUrl(currentUrl, newLocation: location) else {
return
}
let newUrl = Foundation.URL(string: location)
self.webViewDelegate?.updateTabUrl(url: newUrl)
setUrl(newUrl, reliableSource: false)
progress?.reset()
}
DispatchQueue.main.async {
tryUpdateUrl()
}
}
override func goBack() {
super.goBack()
self.canGoForward = true
}
override func goForward() {
super.goForward()
self.canGoBack = true
}
// MARK:- Private methods
fileprivate class func isTopFrameRequest(_ request:URLRequest) -> Bool {
return request.url == request.mainDocumentURL
}
static var allocCounter = 0
fileprivate func commonInit() {
CliqzWebView.allocCounter += 1
delegate = self
scalesPageToFit = true
generateUniqueUserAgent()
Engine.sharedInstance.getWebRequest().newTabCreated(self.uniqueId, webView: self)
progress = WebViewProgress(parent: self)
let refresh = UIRefreshControl()
refresh.bounds = CGRect(x: 0, y: -10, width: refresh.bounds.size.width, height: refresh.bounds.size.height)
refresh.tintColor = UIColor.black
refresh.addTarget(self, action: #selector(refreshWebView), for: UIControlEvents.valueChanged)
self.scrollView.addSubview(refresh)
// built-in userScripts
self.configuration.userContentController.addUserScript(CliqzWebView.modifyLinksScript!)
}
// Needed to identify webview in url protocol
func generateUniqueUserAgent() {
// synchronize code from this point on.
objc_sync_enter(self)
defer { objc_sync_exit(self) }
struct StaticCounter {
static var counter = 0
}
StaticCounter.counter += 1
if let webviewBuiltinUserAgent = CliqzWebView.webviewBuiltinUserAgent {
let userAgent = webviewBuiltinUserAgent + String(format:" _id/%06d", StaticCounter.counter)
let defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
defaults.register(defaults: ["UserAgent": userAgent ])
self.uniqueId = StaticCounter.counter
WebViewToUAMapper.setId(uniqueId, webView:self)
} else {
if StaticCounter.counter > 1 {
// We shouldn't get here, we allow the first webview to have no user agent, and we special-case the look up. The first webview inits the UA from its built in defaults
// If we get to more than one, just use a hard coded user agent, to avoid major bugs
let device = UIDevice.current.userInterfaceIdiom == .phone ? "iPhone" : "iPad"
CliqzWebView.webviewBuiltinUserAgent = "Mozilla/5.0 (\(device)) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75"
}
self.uniqueId = 1
WebViewToUAMapper.idToWebview.setObject(self, forKey: 1 as AnyObject) // the first webview, we don't have the user agent just yet
}
}
fileprivate func convertStringToDictionary(_ text: String?) -> [String:AnyObject]? {
if let data = text?.data(using: String.Encoding.utf8), text?.characters.count > 0 {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
return json
} catch {
debugPrint("Something went wrong")
}
}
return nil
}
fileprivate func reverseStringify(_ text: String?) -> String? {
guard text != nil else {
return nil
}
let length = text!.characters.count
if length > 2 {
let startIndex = text?.characters.index(after: (text?.startIndex)!)
let endIndex = text?.characters.index(before: (text?.endIndex)!)
return text!.substring(with: Range(startIndex! ..< endIndex!))
} else {
return text
}
}
fileprivate func updateObservableAttributes() {
self.isLoading = super.isLoading
self.canGoBack = super.canGoBack
self.canGoForward = super.canGoForward
}
@objc fileprivate func refreshWebView(_ refresh: UIRefreshControl) {
refresh.endRefreshing()
self.reload()
}
}
extension CliqzWebView: UIWebViewDelegate {
class LegacyNavigationAction : WKNavigationAction {
var writableRequest: URLRequest
var writableType: WKNavigationType
init(type: WKNavigationType, request: URLRequest) {
writableType = type
writableRequest = request
super.init()
}
override var request: URLRequest { get { return writableRequest} }
override var navigationType: WKNavigationType { get { return writableType } }
override var sourceFrame: WKFrameInfo {
get { return WKFrameInfo() }
}
}
func webView(_ webView: UIWebView,shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType ) -> Bool {
guard let url = request.url else { return false }
internalLoadingEndedFlag = false
if CliqzWebView.webviewBuiltinUserAgent == nil {
CliqzWebView.webviewBuiltinUserAgent = request.value(forHTTPHeaderField: "User-Agent")
assert(CliqzWebView.webviewBuiltinUserAgent != nil)
}
if url.scheme == "newtab" {
if let delegate = self.UIDelegate,
let absoluteStr = url.absoluteString.removingPercentEncoding {
let startIndex = absoluteStr.characters.index(absoluteStr.startIndex, offsetBy: (url.scheme?.characters.count)! + 1)
let newURL = Foundation.URL(string: absoluteStr.substring(from: startIndex))!
let newRequest = URLRequest(url: newURL)
delegate.webView!(globalContainerWebView, createWebViewWith: WKWebViewConfiguration(), for: LegacyNavigationAction(type: WKNavigationType(rawValue: navigationType.rawValue)!, request: newRequest), windowFeatures: WKWindowFeatures())
}
return false
}
if let progressCheck = progress?.shouldStartLoadWithRequest(request, navigationType: navigationType), !progressCheck {
return false
}
var result = true
if let nd = navigationDelegate {
let action = LegacyNavigationAction(type: WKNavigationType(rawValue: navigationType.rawValue)!, request: request)
globalContainerWebView.legacyWebView = self
nd.webView?(globalContainerWebView, decidePolicyFor: action, decisionHandler: { (policy:WKNavigationActionPolicy) -> Void in
result = policy == .allow
})
}
let locationChanged = CliqzWebView.isTopFrameRequest(request) && url.absoluteString != self.url?.absoluteString
if locationChanged {
setUrl(url, reliableSource: true)
}
updateObservableAttributes()
return result
}
func webViewDidStartLoad(_ webView: UIWebView) {
backForwardList.update()
progress?.webViewDidStartLoad()
if let nd = self.navigationDelegate {
globalContainerWebView.legacyWebView = self
nd.webView?(globalContainerWebView, didCommit: nullWKNavigation)
if !AboutUtils.isAboutHomeURL(self.url) {
nd.webView?(globalContainerWebView, didStartProvisionalNavigation: nullWKNavigation)
}
}
updateObservableAttributes()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
guard let pageInfo = stringByEvaluatingJavaScript(from: "document.readyState.toLowerCase() + '|' + document.title") else {
return
}
backForwardList.update()
// prevent the default context menu on UIWebView
stringByEvaluatingJavaScript(from: "document.body.style.webkitTouchCallout='none';")
let pageInfoArray = pageInfo.components(separatedBy: "|")
let readyState = pageInfoArray.first // ;debugPrint("readyState:\(readyState)")
if let t = pageInfoArray.last, !t.isEmpty {
title = t
}
progress?.webViewDidFinishLoad(readyState)
updateObservableAttributes()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
// The error may not be the main document that failed to load. Check if the failing URL matches the URL being loaded
if let errorUrl = (error as NSError).userInfo[NSURLErrorFailingURLErrorKey] as? Foundation.URL {
var handled = false
if (error as NSError).code == -1009 /*kCFURLErrorNotConnectedToInternet*/ {
let cache = URLCache.shared.cachedResponse(for: URLRequest(url: errorUrl))
if let html = cache?.data.utf8EncodedString, html.characters.count > 100 {
loadHTMLString(html, baseURL: errorUrl)
handled = true
}
}
if !handled && url?.absoluteString == errorUrl.absoluteString {
if let nd = navigationDelegate {
globalContainerWebView.legacyWebView = self
nd.webView?(globalContainerWebView, didFail: nullWKNavigation, withError: error)
}
}
}
NotificationCenter.default
.post(name: Notification.Name(rawValue: CliqzWebViewConstants.kNotificationWebViewLoadCompleteOrFailed), object: self)
progress?.didFailLoadWithError()
updateObservableAttributes()
}
}
|
c07a4785fa3e713ec0d5bf19314d4e0a
| 35.186047 | 251 | 0.673338 | false | false | false | false |
jacobwhite/firefox-ios
|
refs/heads/master
|
Client/Telemetry/UnifiedTelemetry.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import Telemetry
//
// 'Unified Telemetry' is the name for Mozilla's telemetry system
//
class UnifiedTelemetry {
private func migratePathComponentInDocumentsDirectory(_ pathComponent: String, to destinationSearchPath: FileManager.SearchPathDirectory) {
guard let oldPath = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(pathComponent).path, FileManager.default.fileExists(atPath: oldPath) else {
return
}
print("Migrating \(pathComponent) from ~/Documents to \(destinationSearchPath)")
guard let newPath = try? FileManager.default.url(for: destinationSearchPath, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent(pathComponent).path else {
print("Unable to get destination path \(destinationSearchPath) to move \(pathComponent)")
return
}
do {
try FileManager.default.moveItem(atPath: oldPath, toPath: newPath)
print("Migrated \(pathComponent) to \(destinationSearchPath) successfully")
} catch let error as NSError {
print("Unable to move \(pathComponent) to \(destinationSearchPath): \(error.localizedDescription)")
}
}
init(profile: Profile) {
migratePathComponentInDocumentsDirectory("MozTelemetry-Default-core", to: .cachesDirectory)
migratePathComponentInDocumentsDirectory("MozTelemetry-Default-mobile-event", to: .cachesDirectory)
migratePathComponentInDocumentsDirectory("eventArray-MozTelemetry-Default-mobile-event.json", to: .cachesDirectory)
NotificationCenter.default.addObserver(self, selector: #selector(uploadError), name: Telemetry.notificationReportError, object: nil)
let telemetryConfig = Telemetry.default.configuration
telemetryConfig.appName = "Fennec"
telemetryConfig.userDefaultsSuiteName = AppInfo.sharedContainerIdentifier
telemetryConfig.dataDirectory = .cachesDirectory
telemetryConfig.updateChannel = AppConstants.BuildChannel.rawValue
let sendUsageData = profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true
telemetryConfig.isCollectionEnabled = sendUsageData
telemetryConfig.isUploadEnabled = sendUsageData
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.blockPopups", withDefaultValue: true)
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.saveLogins", withDefaultValue: true)
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.showClipboardBar", withDefaultValue: false)
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.settings.closePrivateTabs", withDefaultValue: false)
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASPocketStoriesVisible", withDefaultValue: true)
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASBookmarkHighlightsVisible", withDefaultValue: true)
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASRecentHighlightsVisible", withDefaultValue: true)
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.normalbrowsing", withDefaultValue: true)
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.privatebrowsing", withDefaultValue: true)
telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.strength", withDefaultValue: "basic")
let prefs = profile.prefs
Telemetry.default.beforeSerializePing(pingType: CorePingBuilder.PingType) { (inputDict) -> [String: Any?] in
var outputDict = inputDict // make a mutable copy
if let newTabChoice = prefs.stringForKey(NewTabAccessors.PrefKey) {
outputDict["defaultNewTabExperience"] = newTabChoice as AnyObject?
}
if let chosenEmailClient = prefs.stringForKey(PrefsKeys.KeyMailToOption) {
outputDict["defaultMailClient"] = chosenEmailClient as AnyObject?
}
return outputDict
}
Telemetry.default.beforeSerializePing(pingType: MobileEventPingBuilder.PingType) { (inputDict) -> [String: Any?] in
var outputDict = inputDict
var settings: [String: String?] = inputDict["settings"] as? [String: String?] ?? [:]
let searchEngines = SearchEngines(prefs: profile.prefs, files: profile.files)
settings["defaultSearchEngine"] = searchEngines.defaultEngine.engineID ?? "custom"
if let windowBounds = UIApplication.shared.keyWindow?.bounds {
settings["windowWidth"] = String(describing: windowBounds.width)
settings["windowHeight"] = String(describing: windowBounds.height)
}
outputDict["settings"] = settings
return outputDict
}
Telemetry.default.add(pingBuilderType: CorePingBuilder.self)
Telemetry.default.add(pingBuilderType: MobileEventPingBuilder.self)
}
@objc func uploadError(notification: NSNotification) {
guard !DeviceInfo.isSimulator(), let error = notification.userInfo?["error"] as? NSError else { return }
Sentry.shared.send(message: "Upload Error", tag: SentryTag.unifiedTelemetry, severity: .info, description: error.debugDescription)
}
}
// Enums for Event telemetry.
extension UnifiedTelemetry {
public enum EventCategory: String {
case action = "action"
}
public enum EventMethod: String {
case add = "add"
case background = "background"
case change = "change"
case delete = "delete"
case drag = "drag"
case drop = "drop"
case foreground = "foreground"
case open = "open"
case press = "press"
case scan = "scan"
case tap = "tap"
case view = "view"
}
public enum EventObject: String {
case app = "app"
case bookmark = "bookmark"
case bookmarksPanel = "bookmarks-panel"
case keyCommand = "key-command"
case locationBar = "location-bar"
case qrCodeText = "qr-code-text"
case qrCodeURL = "qr-code-url"
case readerModeCloseButton = "reader-mode-close-button"
case readerModeOpenButton = "reader-mode-open-button"
case readingListItem = "reading-list-item"
case setting = "setting"
case tab = "tab"
case trackingProtectionStatistics = "tracking-protection-statistics"
case trackingProtectionWhitelist = "tracking-protection-whitelist"
case url = "url"
}
public enum EventValue: String {
case activityStream = "activity-stream"
case appMenu = "app-menu"
case awesomebarResults = "awesomebar-results"
case bookmarksPanel = "bookmarks-panel"
case browser = "browser"
case homePanel = "home-panel"
case homePanelTabButton = "home-panel-tab-button"
case markAsRead = "mark-as-read"
case markAsUnread = "mark-as-unread"
case pageActionMenu = "page-action-menu"
case readerModeToolbar = "reader-mode-toolbar"
case readingListPanel = "reading-list-panel"
case shareExtension = "share-extension"
case shareMenu = "share-menu"
case tabTray = "tab-tray"
case topTabs = "top-tabs"
}
public static func recordEvent(category: EventCategory, method: EventMethod, object: EventObject, value: EventValue, extras: [String: Any?]? = nil) {
Telemetry.default.recordEvent(category: category.rawValue, method: method.rawValue, object: object.rawValue, value: value.rawValue, extras: extras)
}
public static func recordEvent(category: EventCategory, method: EventMethod, object: EventObject, value: String? = nil, extras: [String: Any?]? = nil) {
Telemetry.default.recordEvent(category: category.rawValue, method: method.rawValue, object: object.rawValue, value: value, extras: extras)
}
}
|
45f2873a8a718308ae60dd99bb3a65de
| 49.662577 | 237 | 0.700775 | false | true | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro
|
refs/heads/master
|
Parse Dashboard for iOS/ViewControllers/Core/Object/ObjectSelectorController.swift
|
mit
|
1
|
//
// ObjectSelectorViewController.swift
// Parse Dashboard for iOS
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 12/17/17.
//
import UIKit
import IGListKit
import AlertHUDKit
protocol ObjectSelectorViewControllerDelegate: AnyObject {
func objectSelector(_ viewController: ObjectSelectorViewController, didSelect object: ParseLiteObject, for key: String)
}
final class ObjectSelectorViewController: ListSearchViewController, UICollectionViewDelegate {
// MARK: - Properties
let schema: PFSchema
var query = "limit=1000&order=-updatedAt"
weak var delegate: ObjectSelectorViewControllerDelegate?
fileprivate var searchKey: String = .objectId
private let selectionKey: String
private weak var previousViewController: UIViewController?
// MARK: - Initialization
init(selecting key: String, in schema: PFSchema) {
self.schema = schema
self.selectionKey = key
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .darkPurpleBackground
setupNavigationItem()
title = schema.name
adapter.collectionViewDelegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Toast(text: "Select an object to assign to key `\(selectionKey)`").present(self, animated: true, duration: 5)
}
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: parent)
if let controllers = (parent as? UINavigationController)?.viewControllers {
previousViewController = controllers[controllers.count - 2]
} else {
if previousViewController is ObjectViewController {
navigationController?.navigationBar.tintColor = .logoTint
navigationController?.navigationBar.barTintColor = .white
} else if previousViewController is ObjectBuilderViewController {
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.barTintColor = .darkPurpleBackground
}
}
}
// MARK: - Networking
override func loadObjectsInBackground() {
super.loadObjectsInBackground()
ParseLite.shared.get("/classes/" + schema.name, query: "?" + query) { [weak self] (result, json) in
defer { self?.isLoading = false }
guard result.success else {
self?.handleError(result.error)
return
}
guard let results = json?["results"] as? [[String: AnyObject]] else { return }
self?.objects = results.map {
let object = ParseLiteObject($0, schema: self?.schema)
object.displayKey = self?.searchKey ?? .objectId
return object
}
}
}
// MARK: - UICollectionViewDelegate
override func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
let sectionController = super.listAdapter(listAdapter, sectionControllerFor: object)
if let classSectionController = sectionController as? ClassSectionController {
classSectionController.presentOnSelection = false
}
return sectionController
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let object = adapter.object(atSection: indexPath.section) as? ParseLiteObject else { return }
delegate?.objectSelector(self, didSelect: object, for: selectionKey)
}
// MARK: - Search Filtering
override func filteredObjects(for text: String) -> [ListDiffable] {
guard let objects = objects as? [ParseLiteObject] else { return [] }
return objects.filter {
var contains = $0.id.lowercased().contains(text.lowercased())
contains = $0.createdAt.lowercased().contains(text.lowercased()) || contains
contains = $0.updatedAt.lowercased().contains(text.lowercased()) || contains
if contains { return true }
for key in $0.keys {
if let value = $0.value(forKey: key) as? String {
let contains = value.lowercased().contains(text.lowercased())
if contains { return true }
}
}
return false
}
}
// MARK: - Setup
func setupNavigationItem() {
navigationController?.navigationBar.tintColor = .logoTint
navigationController?.navigationBar.barTintColor = .white
navigationItem.rightBarButtonItems = [
UIBarButtonItem(image: UIImage(named: "Filter"),
style: .plain,
target: self,
action: #selector(presentQueryFilterController(sender:)))
]
}
// MARK: - User Actions
@objc
func presentQueryFilterController(sender: AnyObject) {
let queryVC = QueryViewController(schema, searchKey: searchKey, query: query)
queryVC.delegate = self
let navVC = NavigationController(rootViewController: queryVC)
if UIDevice.current.userInterfaceIdiom == .phone {
navVC.modalPresentationStyle = .popover
navVC.popoverPresentationController?.permittedArrowDirections = .up
navVC.popoverPresentationController?.delegate = self
navVC.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItems?.last
} else if UIDevice.current.userInterfaceIdiom == .pad {
navVC.modalPresentationStyle = .formSheet
}
present(navVC, animated: true, completion: nil)
}
}
// MARK: - UIPopoverPresentationControllerDelegate
extension ObjectSelectorViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
}
// MARK: - QueryDelegate
extension ObjectSelectorViewController: QueryDelegate {
func query(didChangeWith query: String, searchKey: String) {
if self.query != query {
self.query = query
self.searchKey = searchKey
loadObjectsInBackground()
} else {
self.searchKey = searchKey
guard let parseObjects = objects as? [ParseLiteObject] else { return }
parseObjects.forEach { $0.displayKey = searchKey }
adapter.reloadData(completion: nil)
}
}
}
|
35aad1a63cae7860c924b04048134e1e
| 37.727273 | 142 | 0.654312 | false | false | false | false |
pkadams67/PKA-Project---Puff-Dragon
|
refs/heads/master
|
Puff Magic/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Puff Dragon
//
// Created by Paul Kirk Adams on 4/21/16.
// Copyright © 2016 Paul Kirk Adams. All rights reserved.
//
import UIKit
import Crashlytics
import Fabric
import LaunchKit
import FBSDKCoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Fabric.sharedSDK().debug = true
Fabric.with([Crashlytics.self])
// TODO: Move this to where you establish a user session
self.logUser()
// Initialize LaunchKit
LaunchKit.launchWithToken("5BVpp5-2e7tKRD1ldaPRZK6gpJcWYaW_oWEEwvcJOqRL")
LaunchKit.sharedInstance().debugMode = true
LaunchKit.sharedInstance().verboseLogging = true
// Uncomment for release build (remembers whether user showed onboarding)
let defaults = NSUserDefaults.standardUserDefaults()
let hasShownOnboarding = defaults.boolForKey("shownOnboardingBefore")
if !hasShownOnboarding {
let lk = LaunchKit.sharedInstance()
lk.presentOnboardingUIOnWindow(self.window!) { _ in
print("Showed onboarding!")
defaults.setBool(true, forKey: "shownOnboardingBefore")
}
}
// Uncomment for debugging (always shows onboarding)
// let lk = LaunchKit.sharedInstance()
// lk.presentOnboardingUIOnWindow(self.window!) { _ in
// print("Showed onboarding!")
// }
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func logUser() {
// TODO: Use the current user's information
// You can call any combination of these three methods
Crashlytics.sharedInstance().setUserEmail("[email protected]")
Crashlytics.sharedInstance().setUserIdentifier("12345")
Crashlytics.sharedInstance().setUserName("Test User")
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application (application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
func applicationWillTerminate(application: UIApplication) {
}
}
|
49f2d173f80cb281806f7832882b46b7
| 32.926829 | 158 | 0.69867 | false | false | false | false |
NoryCao/zhuishushenqi
|
refs/heads/master
|
zhuishushenqi/TXTReader/Community/QSCommunityViewController.swift
|
mit
|
1
|
//
// QSCommunityViewController.swift
// zhuishushenqi
//
// Created yung on 2017/4/24.
// Copyright © 2017年 QS. All rights reserved.
//
// Template generated by Juanpe Catalán @JuanpeCMiOS
//
import UIKit
class QSCommunityViewController: UIViewController, QSCommunityViewProtocol,UITableViewDataSource,UITableViewDelegate ,Refreshable{
var presenter: QSCommunityPresenterProtocol?
var discusses:[BookComment] = []
var comments:[BookComment] = []
var selectedIndex = 0
lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y: kNavgationBarHeight + 40, width: ScreenWidth, height: ScreenHeight - kNavgationBarHeight - 40), style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .singleLine
tableView.qs_registerCellNib(QSDiscussCell.self)
tableView.qs_registerCellNib(HotCommentCell.self)
tableView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
initRefreshHeader(tableView) {
if self.selectedIndex == 0{
self.presenter?.refreshData()
}else {
self.presenter?.refreshComments()
}
}
initRefreshFooter(tableView) {
if self.selectedIndex == 0{
self.presenter?.requestMore()
}else{
self.presenter?.requestMoreComments()
}
}
setupSubviews()
presenter?.viewDidLoad()
}
func setupSubviews(){
let segment = UISegmentedControl(frame: CGRect(x: self.view.bounds.width/4, y: kNavgationBarHeight + 5, width: self.view.bounds.width/2, height: 30))
segment.insertSegment(withTitle: "讨论", at: 0, animated: false)
segment.insertSegment(withTitle: "书评", at: 1, animated: false)
segment.selectedSegmentIndex = 0
segment.tintColor = UIColor.red
segment.backgroundColor = UIColor.white
segment.addTarget(self, action: #selector(segmentAction(seg:)), for: .valueChanged)
self.view.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
self.view.addSubview(segment)
self.view.addSubview(tableView)
self.automaticallyAdjustsScrollViewInsets = false
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if selectedIndex == 0{
return discusses.count
}
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if selectedIndex == 0{
let cell = tableView.qs_dequeueReusableCell(QSDiscussCell.self)
cell?.model = discusses[indexPath.row]
return cell!
}else{
let cell = tableView.qs_dequeueReusableCell(HotCommentCell.self)
cell?.model = comments[indexPath.row]
cell?.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
return cell!
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if selectedIndex == 0{
return 70
}else {
return 127
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.001
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
@objc func segmentAction(seg:UISegmentedControl){
if selectedIndex == seg.selectedSegmentIndex {
return
}
selectedIndex = seg.selectedSegmentIndex
if selectedIndex == 0{
if discusses.count == 0 {
self.presenter?.refreshData()
}
}else if selectedIndex == 1 {
if comments.count == 0 {
self.presenter?.refreshComments()
}
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
presenter?.didSelectCell(indexPath: indexPath)
}
func showPosts(posts: [BookComment]) {
self.discusses = posts
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
self.tableView.reloadData()
}
func showComments(comments: [BookComment]) {
self.comments = comments
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
self.tableView.reloadData()
}
func showEmpty() {
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
}
func showTitle(title: String) {
self.title = title
}
}
|
d2e776738bd7b615112649880cdd7190
| 32.601307 | 171 | 0.618362 | false | false | false | false |
sinss/LCFramework
|
refs/heads/master
|
LCFramework/Extensions/NSNumber+extension.swift
|
mit
|
1
|
//
// extensions.swift
// extensionSample
//
// Created by Leo Chang on 7/8/14.
// Copyright (c) 2014 Perfectidea. All rights reserved.
//
import Foundation
extension NSNumber {
/**
convert a NSNumber as a display string with comma
*/
func toDisplayNumber(digit : NSInteger) -> NSString {
var formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
formatter.roundingMode = NSNumberFormatterRoundingMode.RoundHalfUp
formatter.maximum = digit
return formatter.stringFromNumber(self)!
}
/**
*/
func toDisplayPercentage(digit : NSInteger) -> NSString {
var formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.PercentStyle
formatter.roundingMode = NSNumberFormatterRoundingMode.RoundHalfUp
formatter.maximumFractionDigits = digit
return formatter.stringFromNumber(self)!
}
/**
return a rounding number
*/
func rounding(digit : NSInteger) -> NSNumber {
var formatter = NSNumberFormatter()
formatter.roundingMode = NSNumberFormatterRoundingMode.RoundHalfUp
formatter.maximumFractionDigits = digit
formatter.minimumFractionDigits = digit
var string : NSString = formatter.stringFromNumber(self)!
return NSNumber(double : string.doubleValue);
}
/**
return a ceiling number
*/
func ceiling(digit : NSInteger) -> NSNumber {
var formatter = NSNumberFormatter()
formatter.roundingMode = NSNumberFormatterRoundingMode.RoundCeiling
formatter.maximumFractionDigits = digit
formatter.minimumFractionDigits = digit
var string : NSString = formatter.stringFromNumber(self)!
return NSNumber(double : string.doubleValue);
}
/**
return a flooring number
*/
func flooring(digit : NSInteger) -> NSNumber {
var formatter = NSNumberFormatter()
formatter.roundingMode = NSNumberFormatterRoundingMode.RoundFloor
formatter.maximumFractionDigits = digit
formatter.minimumFractionDigits = digit
var string : NSString = formatter.stringFromNumber(self)!
return NSNumber(double : string.doubleValue)
}
}
|
c564e687e1c644333c4b06e05a1dceab
| 31.28169 | 75 | 0.681362 | false | false | false | false |
SusanDoggie/Doggie
|
refs/heads/main
|
Sources/DoggieGraphics/Serialization/FixedNumber.swift
|
mit
|
1
|
//
// FixedNumber.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@frozen
@usableFromInline
struct Fixed8Number<BitPattern: FixedWidthInteger & ByteCodable>: BinaryFixedPoint, ByteCodable {
@usableFromInline
typealias RepresentingValue = Double
@usableFromInline
var bitPattern: BitPattern
@inlinable
@inline(__always)
init(bitPattern: BitPattern) {
self.bitPattern = bitPattern
}
@inlinable
@inline(__always)
static var fractionBitCount: Int {
return 8
}
}
extension Fixed8Number: SignedNumeric where BitPattern: SignedNumeric {
}
@frozen
@usableFromInline
struct Fixed14Number<BitPattern: FixedWidthInteger & ByteCodable>: BinaryFixedPoint, ByteCodable {
@usableFromInline
typealias RepresentingValue = Double
@usableFromInline
var bitPattern: BitPattern
@inlinable
@inline(__always)
init(bitPattern: BitPattern) {
self.bitPattern = bitPattern
}
@inlinable
@inline(__always)
static var fractionBitCount: Int {
return 14
}
}
extension Fixed14Number: SignedNumeric where BitPattern: SignedNumeric {
}
@frozen
@usableFromInline
struct Fixed16Number<BitPattern: FixedWidthInteger & ByteCodable>: BinaryFixedPoint, ByteCodable {
@usableFromInline
typealias RepresentingValue = Double
@usableFromInline
var bitPattern: BitPattern
@inlinable
@inline(__always)
init(bitPattern: BitPattern) {
self.bitPattern = bitPattern
}
@inlinable
@inline(__always)
static var fractionBitCount: Int {
return 16
}
}
extension Fixed16Number: SignedNumeric where BitPattern: SignedNumeric {
}
@frozen
@usableFromInline
struct Fixed30Number<BitPattern: FixedWidthInteger & ByteCodable>: BinaryFixedPoint, ByteCodable {
@usableFromInline
typealias RepresentingValue = Double
@usableFromInline
var bitPattern: BitPattern
@inlinable
@inline(__always)
init(bitPattern: BitPattern) {
self.bitPattern = bitPattern
}
@inlinable
@inline(__always)
static var fractionBitCount: Int {
return 30
}
}
extension Fixed30Number: SignedNumeric where BitPattern: SignedNumeric {
}
|
6a71e15443ef60dd43a540c90b9a012e
| 24.887218 | 98 | 0.704328 | false | false | false | false |
feighter09/Cloud9
|
refs/heads/master
|
SoundCloud Pro/LFSectionedTableViewDataSource.swift
|
lgpl-3.0
|
1
|
//
// LFSectionedTableViewDataSource.swift
// ScholarsAd
//
// Created by Austin Feight on 3/22/15.
// Copyright (c) 2015 ScholarsAd. All rights reserved.
//
import UIKit
typealias LFSectionedConstructTableCellBlock = (UITableViewCell, AnyObject, Int) -> Void
class LFSectionedTableViewDataSource: NSObject, UITableViewDataSource {
var sectionHeaders = [String]()
var dataItems = [[AnyObject]]()
private var defaultCellIdentifier: String
private var cellIdentifiers = [Int: String]()
private var constructCellBlock: LFSectionedConstructTableCellBlock
init(defaultCellIdentifier: String, constructCellBlock: LFSectionedConstructTableCellBlock)
{
self.defaultCellIdentifier = defaultCellIdentifier
self.constructCellBlock = constructCellBlock
}
}
// MARK: - Interface
extension LFSectionedTableViewDataSource {
func dataItemForIndexPath(indexPath: NSIndexPath) -> AnyObject
{
return dataItems[indexPath.section][indexPath.row]
}
func setCellIdentifier(identifier: String, forSection section: Int)
{
cellIdentifiers[section] = identifier
}
func identifierForIndexPath(indexPath: NSIndexPath) -> String!
{
return cellIdentifiers[indexPath.section] ?? defaultCellIdentifier
}
}
// MARK: - Data Source Methods
extension LFSectionedTableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return dataItems.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
if sectionHeaders.count > 0 && sectionHeaders[section] != "" {
return sectionHeaders[section]
}
return nil
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return dataItems[section].count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let identifier = identifierForIndexPath(indexPath)
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
let data: AnyObject = dataItemForIndexPath(indexPath)
constructCellBlock(cell, data, indexPath.section)
cell.tag = indexPath.row
return cell
}
}
|
ee6aba5b7c1d93f1b649fda02b88b995
| 27.487179 | 105 | 0.748875 | false | false | false | false |
dmegahan/Destiny.gg-for-iOS
|
refs/heads/master
|
Destiny.ggTests/GeneralTests.swift
|
apache-2.0
|
1
|
//
// GeneralTests.swift
// Destiny.gg
//
// Created by Daniel Megahan on 4/26/17.
// Copyright © 2017 Daniel Megahan. All rights reserved.
//
import XCTest
@testable import Destiny_gg
class GeneralTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testVideoClassInitializer(){
let title:String = "Test Title";
let videoType:String = "Test Video";
let previewURL:String = "destiny.gg/bigscreen";
let length:String = "666";
let recordedAt:String = "12/25/2017 00:00:00";
let views:NSNumber = 667;
let videoURL:String = "destiny.gg";
let video:Video = Video(_title: title, _videoType: videoType, _previewURL: previewURL, _length: length, _recordedAt: recordedAt, _views: views, _videoURL: videoURL);
XCTAssertEqual(title, video.title);
XCTAssertEqual(videoType, video.videoType);
XCTAssertEqual(previewURL, video.previewURL);
XCTAssertEqual(length, video.length);
XCTAssertEqual(recordedAt, video.recordedAt);
XCTAssertEqual(views, video.views);
XCTAssertEqual(videoURL, video.videoURL);
}
func testGetAPIKeys(){
let configFile = Config();
XCTAssertNotNil(configFile)
let clientID:String = configFile.getClientID();
let clientSecret:String = configFile.getClientSecret();
let youtubeKey:String = configFile.getYoutubeAPIKey();
XCTAssertNotNil(clientID);
XCTAssertNotNil(clientSecret);
XCTAssertNotNil(youtubeKey);
}
}
|
52337d22d4a3222f74c67ddfa523acac
| 33.777778 | 173 | 0.65016 | false | true | false | false |
mark-randall/Forms
|
refs/heads/master
|
Pod/Classes/Forms/FormViewModel.swift
|
mit
|
1
|
//
// FormViewModel.swift
// Forms
//
// The MIT License (MIT)
//
// Created by mrandall on 12/02/15.
// Copyright © 2015 mrandall. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public class FormViewModelValidator {
//Validates self.iputs or inputs provided as inputs parameter
//
// - Parameter inputs: [FormInputViewModelProtocol]
// - Returns [FormInputViewModelObservable] which are invalid
public static func validate(inputs inputs: [FormInputViewModelObservable]) -> [FormInputViewModelObservable] {
let invalidInputs = inputs.filter {
//Requires generic covariance / dynamic dispatch support
//Not supported as of Swift 2.1
//if let viewModel = $0 as? FormInputValidatable { } is not supported
//select textinput
if let viewModel = $0 as? FormSelectInputViewModel<String> {
return !viewModel.validate()
}
//select bool input
if let viewModel = $0 as? FormSelectInputViewModel<Bool> {
return !viewModel.validate()
}
//select date
if let viewModel = $0 as? FormSelectInputViewModel<NSDate> {
return !viewModel.validate()
}
//select any
if let viewModel = $0 as? FormSelectInputViewModel<Any> {
return !viewModel.validate()
}
//date inputs
if let viewModel = $0 as? FormInputViewModel<NSDate> {
return !viewModel.validate()
}
//text inputs
if let viewModel = $0 as? FormInputViewModel<String> {
return !viewModel.validate()
}
//double inputs
if let viewModel = $0 as? FormInputViewModel<Double> {
return !viewModel.validate()
}
//int inputs
if let viewModel = $0 as? FormInputViewModel<Int> {
return !viewModel.validate()
}
//checkbox inputs
if let viewModel = $0 as? FormInputViewModel<Bool> {
return !viewModel.validate()
}
return true
}
return invalidInputs
}
}
|
9b0e23c339f2943a424bd7365230893d
| 36.215054 | 114 | 0.597399 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/Lumia/Lumia/Component/UltraDrawerView/Sources/Demo/ShapeHeaderView.swift
|
mit
|
1
|
import UIKit
final class ShapeHeaderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
addSubview(button)
button.tintColor = .black
button.backgroundColor = .randomLight
button.setTitle("Favourite shapes", for: .normal)
button.titleLabel?.font = .boldSystemFont(ofSize: 24)
button.contentHorizontalAlignment = .left
button.contentEdgeInsets.left = 16
button.addTarget(self, action: #selector(handleButton), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
button.topAnchor.constraint(equalTo: topAnchor).isActive = true
button.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
button.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
button.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
addSubview(separator)
separator.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
separator.translatesAutoresizingMaskIntoConstraints = false
separator.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
separator.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
separator.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
separator.heightAnchor.constraint(equalToConstant: 1 / UIScreen.main.scale).isActive = true
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private let button = UIButton(type: .system)
private let separator = UIView()
@objc private func handleButton() {
button.backgroundColor = .randomLight
}
}
|
b7746674331515635ab60fcb07079784
| 37.489362 | 99 | 0.684909 | false | false | false | false |
Rochester-Ting/DouyuTVDemo
|
refs/heads/master
|
RRDouyuTV/RRDouyuTV/Classes/Home(首页)/RAchorModel.swift
|
mit
|
1
|
//
// RAchorModel.swift
// RRDouyuTV
//
// Created by 丁瑞瑞 on 15/10/16.
// Copyright © 2016年 Rochester. All rights reserved.
//
import UIKit
class RAchorModel: NSObject {
// 主播名字
var nickname : String = ""
// 房间名字
var room_name : String = ""
// 背景图片
var vertical_src :String = ""
// 在线观看人数
var online : Int = 0
// 房间ID
var room_id : Int = 0
// 是否是手机直播
var isVertical : Int = 0
// 所属游戏分组
var game_name : String = ""
/// 房间ID
// 所在地区
var anchor_city : String = ""
init(dict : [String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
|
95d94bbe585adc1471c651a8e299e055
| 17.55 | 72 | 0.537736 | false | false | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/GalleryThumbsControl.swift
|
gpl-2.0
|
1
|
//
// GalleryThumbsControl.swift
// Telegram
//
// Created by keepcoder on 10/11/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
class GalleryThumbsControl: ViewController {
private let interactions: GalleryInteractions
var afterLayoutTransition:((Bool)->Void)? = nil
init(interactions: GalleryInteractions) {
self.interactions = interactions
super.init(frame: NSMakeRect(0, 0, 400, 80))
}
private(set) var items:[MGalleryItem] = []
func layoutItems(with items: [MGalleryItem], selectedIndex selected: Int, animated: Bool) -> UpdateTransition<MGalleryItem> {
let current: MGalleryItem? = selected > items.count - 1 || selected < 0 ? nil : items[selected]
var newItems:[MGalleryItem] = []
var isForceInstant: Bool = false
for item in items {
if case .instantMedia = item.entry {
isForceInstant = true
newItems = items
break
}
}
if !isForceInstant, let current = current {
switch current.entry {
case .message(let entry):
if let message = entry.message {
if let groupInfo = message.groupInfo {
newItems.append(current)
var next: Int = selected + 1
var prev: Int = selected - 1
var prevFilled: Bool = prev < 0
var nextFilled: Bool = next >= items.count
while !prevFilled || !nextFilled {
if !prevFilled {
prevFilled = items[prev].entry.message?.groupInfo != groupInfo
if !prevFilled {
newItems.insert(items[prev], at: 0)
}
prev -= 1
}
if !nextFilled {
nextFilled = items[next].entry.message?.groupInfo != groupInfo
if !nextFilled {
newItems.append(items[next])
}
next += 1
}
prevFilled = prevFilled || prev < 0
nextFilled = nextFilled || next >= items.count
}
}
}
case .instantMedia:
newItems = items
case .photo:
newItems = items
case .secureIdDocument:
newItems = items
}
}
if newItems.count == 1 {
newItems = []
}
let (deleteIndices, indicesAndItems, updateIndices) = mergeListsStableWithUpdates(leftList: self.items, rightList: newItems)
for rdx in deleteIndices.reversed() {
genericView.removeItem(at: rdx, animated: animated)
self.items.remove(at: rdx)
}
for (idx, item, _) in indicesAndItems {
genericView.insertItem(item, at: idx, isSelected: current?.stableId == item.stableId, animated: animated, callback: { [weak self] item in
self?.interactions.select(item)
})
self.items.insert(item, at: idx)
}
for (idx, item, _) in updateIndices {
let item = item
genericView.updateItem(item, at: idx)
self.items[idx] = item
}
for i in 0 ..< self.items.count {
if current?.stableId == self.items[i].stableId {
genericView.layoutItems(selectedIndex: i, animated: animated)
break
}
}
genericView.updateHighlight()
if self.items.count <= 1 {
genericView.change(opacity: 0, animated: animated, completion: { [weak self] completed in
if completed {
self?.genericView.isHidden = true
}
})
} else {
genericView.isHidden = false
genericView.change(opacity: 1, animated: animated)
}
afterLayoutTransition?(animated)
return UpdateTransition<MGalleryItem>(deleted: deleteIndices, inserted: indicesAndItems.map {($0.0, $0.1)}, updated: updateIndices.map {($0.0, $0.1)})
}
deinit {
var bp:Int = 0
bp += 1
}
var genericView:GalleryThumbsControlView {
return view as! GalleryThumbsControlView
}
override func viewClass() -> AnyClass {
return GalleryThumbsControlView.self
}
}
|
ccd2b832ae94dcabcf463d6ba6c2d7c9
| 32.359477 | 158 | 0.472766 | false | false | false | false |
SwiftArchitect/TGPControls
|
refs/heads/master
|
TGPControls/TGPCamelLabels.swift
|
mit
|
2
|
import UIKit
// Interface builder hides the IBInspectable for UIControl
#if TARGET_INTERFACE_BUILDER
public class TGPCamelLabels_INTERFACE_BUILDER:UIView {
}
#else // !TARGET_INTERFACE_BUILDER
public class TGPCamelLabels_INTERFACE_BUILDER:UIControl {
}
#endif // TARGET_INTERFACE_BUILDER
@IBDesignable
public class TGPCamelLabels: TGPCamelLabels_INTERFACE_BUILDER {
let validAttributes = [NSLayoutAttribute.top.rawValue, // 3
NSLayoutAttribute.centerY.rawValue, // 10
NSLayoutAttribute.bottom.rawValue] // 4
// Only used if labels.count < 1
@IBInspectable public var tickCount:Int {
get {
return names.count
}
set {
// Put some order to tickCount: 1 >= count >= 128
let count = max(1, min(newValue, 128))
debugNames(count: count)
layoutTrack()
}
}
@IBInspectable public var ticksDistance:CGFloat = 44.0 {
didSet {
ticksDistance = max(0, ticksDistance)
layoutTrack()
}
}
@IBInspectable public var value:UInt = 0 {
didSet {
dockEffect(duration: animationDuration)
}
}
@IBInspectable public var upFontName:String? = nil {
didSet {
layoutTrack()
}
}
@IBInspectable public var upFontSize:CGFloat = 12 {
didSet {
layoutTrack()
}
}
@IBInspectable public var upFontColor:UIColor? = nil {
didSet {
layoutTrack()
}
}
@IBInspectable public var downFontName:String? = nil {
didSet {
layoutTrack()
}
}
@IBInspectable public var downFontSize:CGFloat = 12 {
didSet {
layoutTrack()
}
}
@IBInspectable public var downFontColor:UIColor? = nil {
didSet {
layoutTrack()
}
}
@IBInspectable public var numberOfLinesInLabel:Int = 1 {
didSet {
layoutTrack()
}
}
// Label off-center to the left and right of the slider
// expressed in label width. 0: none, -1/2: half outside, 1/2; half inside
@IBInspectable public var offCenter:CGFloat = 0 {
didSet {
layoutTrack()
}
}
// Label margins to the left and right of the slider
@IBInspectable public var insets:NSInteger = 0 {
didSet {
layoutTrack()
}
}
// Where should emphasized labels be drawn (10: centerY, 3: top, 4: bottom)
// By default, emphasized labels are animated towards the top of the frame.
// This creates the dock effect (camel). They can also be centered vertically, or move down (reverse effect).
@IBInspectable public var emphasisLayout:Int = NSLayoutAttribute.top.rawValue {
didSet {
if !validAttributes.contains(emphasisLayout) {
emphasisLayout = NSLayoutAttribute.top.rawValue
}
layoutTrack()
}
}
// Where should regular labels be drawn (10: centerY, 3: top, 4: bottom)
// By default, emphasized labels are animated towards the bottom of the frame.
// This creates the dock effect (camel). They can also be centered vertically, or move up (reverse effect).
@IBInspectable public var regularLayout:Int = NSLayoutAttribute.bottom.rawValue {
didSet {
if !validAttributes.contains(regularLayout) {
regularLayout = NSLayoutAttribute.bottom.rawValue
}
layoutTrack()
}
}
// MARK: @IBInspectable adapters
public var emphasisLayoutAttribute:NSLayoutAttribute {
get {
return NSLayoutAttribute(rawValue: emphasisLayout) ?? .top
}
set {
emphasisLayout = newValue.rawValue
}
}
public var regularLayoutAttribute:NSLayoutAttribute {
get {
return NSLayoutAttribute(rawValue: regularLayout) ?? .bottom
}
set {
regularLayout = newValue.rawValue
}
}
// MARK: Properties
public var names:[String] = [] { // Will dictate the number of ticks
didSet {
assert(names.count > 0)
layoutTrack()
}
}
// When bounds change, recalculate layout
override public var bounds: CGRect {
didSet {
layoutTrack()
setNeedsDisplay()
}
}
public var animationDuration:TimeInterval = 0.15
// Private
var lastValue = NSNotFound
var emphasizedLabels:[UILabel] = []
var regularLabels:[UILabel] = []
var localeCharacterDirection = CFLocaleLanguageDirection.leftToRight
// MARK: UIView
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initProperties()
}
override init(frame: CGRect) {
super.init(frame: frame)
initProperties()
}
// clickthrough
public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
for view in subviews {
if !view.isHidden &&
view.alpha > 0.0 &&
view.isUserInteractionEnabled &&
view.point(inside: convert(point, to: view), with: event) {
return true
}
}
return false
}
// MARK: TGPCamelLabels
func initProperties() {
if let systemLocale = CFLocaleCopyCurrent(),
let localeIdentifier = CFLocaleGetIdentifier(systemLocale) {
localeCharacterDirection = CFLocaleGetLanguageCharacterDirection(localeIdentifier.rawValue)
}
debugNames(count: 10)
layoutTrack()
}
func debugNames(count:Int) {
// Dynamic property, will create an array with labels, generally for debugging purposes
var array:[String] = []
for iterate in 1...count {
array.append("\(iterate)")
}
names = array
}
func layoutTrack() {
func insetLabel(_ label:UILabel?, withInset inset:NSInteger, andMultiplier multiplier:CGFloat) {
assert(label != nil)
if let label = label {
label.frame = {
var frame = label.frame
frame.origin.x += frame.size.width * multiplier
frame.origin.x += CGFloat(inset)
return frame
}()
}
}
for label in emphasizedLabels {
label.removeFromSuperview()
}
emphasizedLabels = []
for label in regularLabels {
label.removeFromSuperview()
}
regularLabels = []
let count = names.count
if count > 0 {
var centerX = (bounds.width - (CGFloat(count - 1) * ticksDistance))/2.0
if .rightToLeft == localeCharacterDirection {
centerX = bounds.width - centerX
}
let tickSpacing = (.rightToLeft == localeCharacterDirection)
? -ticksDistance
: ticksDistance
let centerY = bounds.height / 2.0
for name in names {
let upLabel = UILabel.init()
upLabel.numberOfLines = numberOfLinesInLabel
emphasizedLabels.append(upLabel)
upLabel.text = name
if let upFontName = upFontName {
upLabel.font = UIFont.init(name: upFontName, size: upFontSize)
} else {
upLabel.font = UIFont.boldSystemFont(ofSize: upFontSize)
}
if let textColor = upFontColor ?? tintColor {
upLabel.textColor = textColor
}
upLabel.sizeToFit()
upLabel.center = CGPoint(x: centerX, y: centerY)
upLabel.frame = {
var frame = upLabel.frame
frame.origin.y = bounds.height - frame.height
return frame
}()
upLabel.alpha = 0.0
addSubview(upLabel)
let dnLabel = UILabel.init()
dnLabel.numberOfLines = numberOfLinesInLabel
regularLabels.append(dnLabel)
dnLabel.text = name
if let downFontName = downFontName {
dnLabel.font = UIFont.init(name:downFontName, size:downFontSize)
} else {
dnLabel.font = UIFont.boldSystemFont(ofSize: downFontSize)
}
dnLabel.textColor = downFontColor ?? UIColor.gray
dnLabel.sizeToFit()
dnLabel.center = CGPoint(x:centerX, y:centerY)
dnLabel.frame = {
var frame = dnLabel.frame
frame.origin.y = bounds.height - frame.height
return frame
}()
addSubview(dnLabel)
centerX += tickSpacing
}
// Fix left and right label, if there are at least 2 labels
if names.count > 1 {
let localeInsets = (.rightToLeft == localeCharacterDirection)
? -insets
: insets
let localeOffCenter = (.rightToLeft == localeCharacterDirection)
? -offCenter
: offCenter
insetLabel(emphasizedLabels.first, withInset: localeInsets, andMultiplier: localeOffCenter)
insetLabel(emphasizedLabels.last, withInset: -localeInsets, andMultiplier: -localeOffCenter)
insetLabel(regularLabels.first, withInset: localeInsets, andMultiplier: localeOffCenter)
insetLabel(regularLabels.last, withInset: -localeInsets, andMultiplier: -localeOffCenter)
}
dockEffect(duration:0.0)
}
}
func dockEffect(duration:TimeInterval)
{
let emphasized = Int(value)
// Unlike the National Parks from which it is inspired, this Dock Effect
// does not abruptly change from BOLD to plain. Instead, we have 2 sets of
// labels, which are faded back and forth, in unisson.
// - BOLD to plain
// - Black to gray
// - high to low
// Each animation picks up where the previous left off
let moveBlock:() -> Void = {
// De-emphasize almost all
for (idx, label) in self.emphasizedLabels.enumerated() {
if emphasized != idx {
self.verticalAlign(aView: label,
alpha: 0,
attribute: self.regularLayoutAttribute)
}
}
for (idx, label) in self.regularLabels.enumerated() {
if emphasized != idx {
self.verticalAlign(aView: label,
alpha: 1,
attribute: self.regularLayoutAttribute)
}
}
// Emphasize the selection
if emphasized < self.emphasizedLabels.count {
self.verticalAlign(aView: self.emphasizedLabels[emphasized],
alpha:1,
attribute: self.emphasisLayoutAttribute)
}
if emphasized < self.regularLabels.count {
self.verticalAlign(aView: self.regularLabels[emphasized],
alpha:0,
attribute: self.emphasisLayoutAttribute)
}
}
if duration > 0 {
UIView.animate(withDuration: duration,
delay: 0,
options: [.beginFromCurrentState, .curveLinear],
animations: moveBlock,
completion: nil)
} else {
moveBlock()
}
}
func verticalAlign(aView:UIView, alpha:CGFloat, attribute layout:NSLayoutAttribute) {
switch layout {
case .top:
aView.frame = {
var frame = aView.frame
frame.origin.y = 0
return frame
}()
case .bottom:
aView.frame = {
var frame = aView.frame
frame.origin.y = bounds.height - frame.height
return frame
}()
default: // .center
aView.frame = {
var frame = aView.frame
frame.origin.y = (bounds.height - frame.height) / 2
return frame
}()
}
aView.alpha = alpha
}
}
extension TGPCamelLabels : TGPControlsTicksProtocol {
public func tgpTicksDistanceChanged(ticksDistance: CGFloat, sender: AnyObject) {
self.ticksDistance = ticksDistance
}
public func tgpValueChanged(value: UInt) {
self.value = value
}
}
|
07f766f4b5e9facc2f5e3f6fb2e263a8
| 31.263027 | 113 | 0.54184 | false | false | false | false |
elpassion/el-space-ios
|
refs/heads/master
|
ELSpace/Screens/Hub/Activity/Type/Chooser/ChooserActivityTypesViewController.swift
|
gpl-3.0
|
1
|
import UIKit
import RxSwift
protocol ChooserActivityTypesViewControlling {
var selected: Observable<ReportType> { get }
var select: AnyObserver<ReportType> { get }
}
class ChooserActivityTypesViewController: UIViewController, ChooserActivityTypesViewControlling {
init(viewModel: ChooserActivityTypesViewModeling) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = ChooserActivityTypesView()
}
override func viewDidLoad() {
super.viewDidLoad()
addActivityTypes()
}
// MARK: ActivityTypeViewControlling
var selected: Observable<ReportType> {
return selectedTypeSubject.asObservable().unwrap()
}
var select: AnyObserver<ReportType> {
return AnyObserver(eventHandler: { [weak self] event in
guard let type = event.element else { return }
let reportTypeViewModel = self?.viewModel.activityTypeViewModels.filter { $0.type == type }.first
reportTypeViewModel?.isSelected.accept(true)
})
}
// MARK: Privates
private let viewModel: ChooserActivityTypesViewModeling
private let selectedTypeSubject = BehaviorSubject<ReportType?>(value: nil)
private let disposeBag = DisposeBag()
private var activityTypesView: ChooserActivityTypesView! {
return view as? ChooserActivityTypesView
}
private func addActivityTypes() {
activityTypesView.typeViews = createActivityTypeViews()
}
private func createActivityTypeViews() -> [ActivityTypeView] {
return viewModel.activityTypeViewModels.map { viewModel in
let view = ActivityTypeView()
view.titleLabel.text = viewModel.title
view.titleLabel.textColor = self.titleColorForState(false)
view.imageView.image = viewModel.imageUnselected
view.isUserInteractionEnabled = viewModel.isUserInteractionEnabled
view.alpha = viewModel.isUserInteractionEnabled ? 1.0 : 0.5
viewModel.isSelected
.subscribe(onNext: { [weak view, weak self] isSelected in
view?.imageView.image = isSelected ? viewModel.imageSelected : viewModel.imageUnselected
view?.titleLabel.textColor = self?.titleColorForState(isSelected)
if isSelected { self?.selectedTypeSubject.onNext(viewModel.type) }
})
.disposed(by: disposeBag)
view.button.rx.tap
.map { true }
.bind(to: viewModel.isSelected)
.disposed(by: disposeBag)
return view
}
}
private func titleColorForState(_ isSelected: Bool) -> UIColor? {
return isSelected ? UIColor(color: .purpleBCAEF8) : UIColor(color: .grayB3B3B8)
}
}
|
7972ccd4cd6e56327f2aa16c9926de14
| 34.25 | 109 | 0.658561 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new
|
refs/heads/master
|
Source/JSONFormBuilder.swift
|
apache-2.0
|
2
|
//
// JSONFormBuilder.swift
// edX
//
// Created by Michael Katz on 9/29/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
import edXCore
private func equalsCaseInsensitive(lhs: String, _ rhs: String) -> Bool {
return lhs.caseInsensitiveCompare(rhs) == .OrderedSame
}
/** Model for the built form must allow for reads and updates */
protocol FormData {
func valueForField(key: String) -> String?
func displayValueForKey(key: String) -> String?
func setValue(value: String?, key: String)
}
/** Decorate the cell with the model object */
protocol FormCell {
func applyData(field: JSONFormBuilder.Field, data: FormData)
}
private func loadJSON(jsonFile: String) throws -> JSON {
var js: JSON
if let filePath = NSBundle.mainBundle().pathForResource(jsonFile, ofType: "json") {
if let data = NSData(contentsOfFile: filePath) {
var error: NSError?
js = JSON(data: data, error: &error)
if error != nil { throw error! }
} else {
js = JSON(NSNull())
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
} else {
js = JSON(NSNull())
throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: nil)
}
return js
}
/** Function to turn a specialized JSON file (https://openedx.atlassian.net/wiki/display/MA/Profile+Forms) into table rows, with various editor views and view controllers */
class JSONFormBuilder {
/** Show a segmented control from a limited set of options */
class SegmentCell: UITableViewCell, FormCell {
static let Identifier = "JSONForm.SwitchCell"
let titleLabel = UILabel()
let descriptionLabel = UILabel()
let typeControl = UISegmentedControl()
var values = [String]()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(titleLabel)
contentView.addSubview(typeControl)
contentView.addSubview(descriptionLabel)
titleLabel.textAlignment = .Natural
descriptionLabel.textAlignment = .Natural
descriptionLabel.numberOfLines = 0
descriptionLabel.preferredMaxLayoutWidth = 200 //value doesn't seem to matter as long as it's small enough
titleLabel.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(contentView.snp_leadingMargin)
make.top.equalTo(contentView.snp_topMargin)
make.trailing.equalTo(contentView.snp_trailingMargin)
}
typeControl.snp_makeConstraints { (make) -> Void in
make.top.equalTo(titleLabel.snp_bottom).offset(6)
make.leading.equalTo(contentView.snp_leadingMargin)
make.trailing.equalTo(contentView.snp_trailingMargin)
}
descriptionLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(typeControl.snp_bottom).offset(6)
make.leading.equalTo(contentView.snp_leadingMargin)
make.trailing.equalTo(contentView.snp_trailingMargin)
make.bottom.equalTo(contentView.snp_bottomMargin)
}
}
func applyData(field: JSONFormBuilder.Field, data: FormData) {
let titleStyle = OEXTextStyle(weight: .Normal, size: .Base, color: OEXStyles.sharedStyles().neutralBlackT())
let descriptionStyle = OEXMutableTextStyle(weight: .Light, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark())
descriptionStyle.lineBreakMode = .ByTruncatingTail
titleLabel.attributedText = titleStyle.attributedStringWithText(field.title)
descriptionLabel.attributedText = descriptionStyle.attributedStringWithText(field.instructions)
if let hint = field.accessibilityHint {
typeControl.accessibilityHint = hint
}
values.removeAll(keepCapacity: true)
typeControl.removeAllSegments()
if let optionsValues = field.options?["values"]?.arrayObject {
for valueDict in optionsValues {
let title = valueDict["name"] as! String
let value = valueDict["value"] as! String
typeControl.insertSegmentWithTitle(title, atIndex: values.count, animated: false)
values.append(value)
}
}
if let val = data.valueForField(field.name), selectedIndex = values.indexOf(val) {
typeControl.selectedSegmentIndex = selectedIndex
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/** Show a cell that provides a long list of options in a new viewcontroller */
class OptionsCell: UITableViewCell, FormCell {
static let Identifier = "JSONForm.OptionsCell"
private let choiceView = ChoiceLabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
func setup() {
accessoryType = .DisclosureIndicator
contentView.addSubview(choiceView)
choiceView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(contentView).inset(UIEdgeInsets(top: 0, left: StandardHorizontalMargin, bottom: 0, right: StandardHorizontalMargin))
}
}
func applyData(field: Field, data: FormData) {
choiceView.titleText = Strings.formLabel(label: field.title!)
choiceView.valueText = data.displayValueForKey(field.name) ?? field.placeholder ?? ""
}
}
/** Show an editable text area in a new view */
class TextAreaCell: UITableViewCell, FormCell {
static let Identifier = "JSONForm.TextAreaCell"
private let choiceView = ChoiceLabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
func setup() {
accessoryType = .DisclosureIndicator
contentView.addSubview(choiceView)
choiceView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(contentView).inset(UIEdgeInsets(top: 0, left: StandardHorizontalMargin, bottom: 0, right: StandardHorizontalMargin))
}
}
func applyData(field: Field, data: FormData) {
choiceView.titleText = Strings.formLabel(label: field.title ?? "")
let placeholderText = field.placeholder
choiceView.valueText = data.valueForField(field.name) ?? placeholderText ?? ""
}
}
/** Add the cell types to the tableview */
static func registerCells(tableView: UITableView) {
tableView.registerClass(OptionsCell.self, forCellReuseIdentifier: OptionsCell.Identifier)
tableView.registerClass(TextAreaCell.self, forCellReuseIdentifier: TextAreaCell.Identifier)
tableView.registerClass(SegmentCell.self, forCellReuseIdentifier: SegmentCell.Identifier)
}
/** Fields parsed out of the json. Each field corresponds to it's own row with specialized editor */
struct Field {
enum FieldType: String {
case Select = "select"
case TextArea = "textarea"
case Switch = "switch"
init?(jsonVal: String?) {
if let str = jsonVal {
if let type = FieldType(rawValue: str) {
self = type
} else {
return nil
}
} else {
return nil
}
}
var cellIdentifier: String {
switch self {
case .Select:
return OptionsCell.Identifier
case .TextArea:
return TextAreaCell.Identifier
case .Switch:
return SegmentCell.Identifier
}
}
}
//Field Data types Supported by the form builder
enum DataType : String {
case StringType = "string"
case CountryType = "country"
case LanguageType = "language"
init(_ rawValue: String?) {
guard let val = rawValue else { self = .StringType; return }
switch val {
case "country":
self = .CountryType
case "language":
self = .LanguageType
default:
self = .StringType
}
}
}
let type: FieldType
let name: String
var cellIdentifier: String { return type.cellIdentifier }
var title: String?
let instructions: String?
let subInstructions: String?
let accessibilityHint: String?
let options: [String: JSON]?
let dataType: DataType
let defaultValue: String?
let placeholder: String?
init (json: JSON) {
type = FieldType(jsonVal: json["type"].string)!
title = json["label"].string
name = json["name"].string!
instructions = json["instructions"].string
subInstructions = json["sub_instructions"].string
options = json["options"].dictionary
dataType = DataType(json["data_type"].string)
defaultValue = json["default"].string
accessibilityHint = json["accessibility_hint"].string
placeholder = json["placeholder"].string
}
private func attributedChooserRow(icon: Icon, title: String, value: String?) -> NSAttributedString {
let iconStyle = OEXTextStyle(weight: .Normal, size: .Base, color: OEXStyles.sharedStyles().neutralBase())
let icon = icon.attributedTextWithStyle(iconStyle)
let titleStyle = OEXTextStyle(weight: .Normal, size: .Base, color: OEXStyles.sharedStyles().neutralBlackT())
let titleAttrStr = titleStyle.attributedStringWithText(" " + title)
let valueStyle = OEXTextStyle(weight: .Normal, size: .Base, color: OEXStyles.sharedStyles().neutralDark())
let valAttrString = valueStyle.attributedStringWithText(value)
return NSAttributedString.joinInNaturalLayout([icon, titleAttrStr, valAttrString])
}
private func selectAction(data: FormData, controller: UIViewController) {
let selectionController = JSONFormTableViewController<String>()
var tableData = [ChooserDatum<String>]()
if let rangeMin:Int = options?["range_min"]?.int, rangeMax:Int = options?["range_max"]?.int {
let range = rangeMin...rangeMax
let titles = range.map { String($0)} .reverse()
tableData = titles.map { ChooserDatum(value: $0, title: $0, attributedTitle: nil) }
} else if let file = options?["reference"]?.string {
do {
let json = try loadJSON(file)
if let values = json.array {
tableData = values.map { ChooserDatum(value: $0["value"].string!, title: $0["name"].string, attributedTitle: nil)}
}
} catch {
Logger.logError("JSON", "Error parsing JSON: \(error)")
}
}
var defaultRow = -1
let allowsNone = options?["allows_none"]?.bool ?? false
if allowsNone {
let noneTitle = Strings.Profile.noField(fieldName: title!.oex_lowercaseStringInCurrentLocale())
tableData.insert(ChooserDatum(value: "--", title: noneTitle, attributedTitle: nil), atIndex: 0)
defaultRow = 0
}
if let alreadySetValue = data.valueForField(name) {
defaultRow = tableData.indexOf { equalsCaseInsensitive($0.value, alreadySetValue) } ?? defaultRow
}
if dataType == .CountryType {
if let id = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as? String {
let countryName = NSLocale.currentLocale().displayNameForKey(NSLocaleCountryCode, value: id)
let title = attributedChooserRow(Icon.Country, title: Strings.Profile.currentLocationLabel, value: countryName)
tableData.insert(ChooserDatum(value: id, title: nil, attributedTitle: title), atIndex: 0)
if defaultRow >= 0 { defaultRow += 1 }
}
} else if dataType == .LanguageType {
if let id = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String {
let languageName = NSLocale.currentLocale().displayNameForKey(NSLocaleLanguageCode, value: id)
let title = attributedChooserRow(Icon.Comment, title: Strings.Profile.currentLanguageLabel, value: languageName)
tableData.insert(ChooserDatum(value: id, title: nil, attributedTitle: title), atIndex: 0)
if defaultRow >= 0 { defaultRow += 1 }
}
}
let dataSource = ChooserDataSource(data: tableData)
dataSource.selectedIndex = defaultRow
selectionController.dataSource = dataSource
selectionController.title = title
selectionController.instructions = instructions
selectionController.subInstructions = subInstructions
selectionController.doneChoosing = { value in
if allowsNone && value != nil && value! == "--" {
data.setValue(nil, key: self.name)
} else {
data.setValue(value, key: self.name)
}
}
controller.navigationController?.pushViewController(selectionController, animated: true)
}
/** What happens when the user selects the row */
func takeAction(data: FormData, controller: UIViewController) {
switch type {
case .Select:
selectAction(data, controller: controller)
case .TextArea:
let text = data.valueForField(name)
let textController = JSONFormBuilderTextEditorViewController(text: text, placeholder: placeholder)
textController.title = title
textController.doneEditing = { value in
if value == "" {
data.setValue(nil, key: self.name)
} else {
data.setValue(value, key: self.name)
}
}
controller.navigationController?.pushViewController(textController, animated: true)
case .Switch:
//no action on cell selection - let control in cell handle action
break;
}
}
}
let json: JSON
lazy var fields: [Field]? = {
return self.json["fields"].array?.map { return Field(json: $0) }
}()
init?(jsonFile: String) {
do {
json = try loadJSON(jsonFile)
} catch {
json = JSON(NSNull())
return nil
}
}
init(json: JSON) {
self.json = json
}
}
|
cfe8a339b79812689bc6c1dc36ccd3b6
| 40.361809 | 173 | 0.570283 | false | false | false | false |
rhx/gir2swift
|
refs/heads/main
|
Sources/libgir2swift/models/gir elements/GirArgument.swift
|
bsd-2-clause
|
1
|
//
// GirArgument.swift
// gir2swift
//
// Created by Rene Hexel on 25/03/2016.
// Copyright © 2016, 2017, 2018, 2019, 2020, 2022 Rene Hexel. All rights reserved.
//
import SwiftLibXML
extension GIR {
/// data type representing a function/method argument or return type
public class Argument: CType {
public override var kind: String { return "Argument" }
/// is this an instance parameter or return type?
public let instance: Bool
/// is this a varargs (...) parameter?
public let _varargs: Bool
/// is this a nullable parameter or return type?
public let isNullable: Bool
/// is this a parameter that can be ommitted?
public let allowNone: Bool
/// is this an optional (out) parameter?
public let isOptional: Bool
/// is this a caller-allocated (out) parameter?
public let callerAllocates: Bool
/// model of ownership transfer used
public let ownershipTransfer: OwnershipTransfer
/// whether this is an `in`, `out`, or `inout` parameter
public let direction: ParameterDirection
/// indicate whether the given parameter is varargs
public var varargs: Bool {
return _varargs || name.hasPrefix("...")
}
/// default constructor
/// - Parameters:
/// - name: The name of the `Argument` to initialise
/// - cname: C identifier
/// - type: The corresponding, underlying GIR type
/// - instance: `true` if this is an instance parameter
/// - comment: Documentation text for the type
/// - introspectable: Set to `true` if introspectable
/// - deprecated: Documentation on deprecation status if non-`nil`
/// - varargs: `true` if this is a varargs `(...)` parameter
/// - isNullable: `true` if this is a nullable parameter or return type
/// - allowNone: `true` if this parameter can be omitted
/// - isOptional: `true` if this is an optional (out) parameter
/// - callerAllocates: `true` if this is caller allocated
/// - ownershipTransfer: model of ownership transfer used
/// - direction: whether this is an `in`, `out`, or `inout` paramete
public init(name: String, cname:String, type: TypeReference, instance: Bool, comment: String, introspectable: Bool = false, deprecated: String? = nil, varargs: Bool = false, isNullable: Bool = false, allowNone: Bool = false, isOptional: Bool = false, callerAllocates: Bool = false, ownershipTransfer: OwnershipTransfer = .none, direction: ParameterDirection = .in) {
self.instance = instance
_varargs = varargs
self.isNullable = isNullable
self.allowNone = allowNone
self.isOptional = isOptional
self.callerAllocates = callerAllocates
self.ownershipTransfer = ownershipTransfer
self.direction = direction
super.init(name: name, cname: cname, type: type, comment: comment, introspectable: introspectable, deprecated: deprecated)
}
/// XML constructor
public init(node: XMLElement, at index: Int, defaultDirection: ParameterDirection = .in) {
instance = node.name.hasPrefix("instance")
_varargs = node.children.lazy.first(where: { $0.name == "varargs"}) != nil
let allowNone = node.attribute(named: "allow-none")
if let allowNone = allowNone, !allowNone.isEmpty && allowNone != "0" && allowNone != "false" {
self.allowNone = true
} else {
self.allowNone = false
}
if let nullable = node.attribute(named: "nullable") ?? allowNone, !nullable.isEmpty && nullable != "0" && nullable != "false" {
isNullable = true
} else {
isNullable = false
}
if let optional = node.attribute(named: "optional") ?? allowNone, !optional.isEmpty && optional != "0" && optional != "false" {
isOptional = true
} else {
isOptional = false
}
if let callerAlloc = node.attribute(named: "caller-allocates"), !callerAlloc.isEmpty && callerAlloc != "0" && callerAlloc != "false" {
callerAllocates = true
} else {
callerAllocates = false
}
ownershipTransfer = node.attribute(named: "transfer-ownership").flatMap { OwnershipTransfer(rawValue: $0) } ?? .none
direction = node.attribute(named: "direction").flatMap { ParameterDirection(rawValue: $0) } ?? defaultDirection
super.init(fromChildrenOf: node, at: index)
}
/// XML constructor for functions/methods/callbacks
public init(node: XMLElement, at index: Int, varargs: Bool, defaultDirection: ParameterDirection = .in) {
instance = node.name.hasPrefix("instance")
_varargs = varargs
let allowNone = node.attribute(named: "allow-none")
if let allowNone = allowNone, !allowNone.isEmpty && allowNone != "0" && allowNone != "false" {
self.allowNone = true
} else {
self.allowNone = false
}
if let nullable = node.attribute(named: "nullable") ?? allowNone, nullable != "0" && nullable != "false" {
isNullable = true
} else {
isNullable = false
}
if let optional = node.attribute(named: "optional") ?? allowNone, optional != "0" && optional != "false" {
isOptional = true
} else {
isOptional = false
}
if let callerAlloc = node.attribute(named: "caller-allocates"), callerAlloc != "0" && callerAlloc != "false" {
callerAllocates = true
} else {
callerAllocates = false
}
ownershipTransfer = node.attribute(named: "transfer-ownership").flatMap { OwnershipTransfer(rawValue: $0) } ?? .none
direction = node.attribute(named: "direction").flatMap { ParameterDirection(rawValue: $0) } ?? defaultDirection
super.init(node: node, at: index)
}
}
}
|
66051873b9b94f696e8b39936a2378fb
| 49.798387 | 374 | 0.587236 | false | false | false | false |
kelvin13/maxpng
|
refs/heads/master
|
benchmarks/compression/swift/main.swift
|
gpl-3.0
|
1
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
import PNG
#if os(macOS)
import func Darwin.nanosleep
import struct Darwin.timespec
import func Darwin.clock
import var Darwin.CLOCKS_PER_SEC
func clock() -> Int
{
.init(Darwin.clock())
}
#elseif os(Linux)
import func Glibc.nanosleep
import struct Glibc.timespec
import func Glibc.clock
import var Glibc.CLOCKS_PER_SEC
func clock() -> Int
{
Glibc.clock()
}
#else
#warning("clock() function not imported for this platform, internal benchmarks not built (please open an issue at https://github.com/kelvin13/swift-png/issues)")
#endif
#if os(macOS) || os(Linux)
// internal benchmarking functions, to measure module boundary overhead
enum Benchmark
{
enum Encode
{
struct Blob
{
private(set)
var buffer:[UInt8] = []
}
}
}
extension Benchmark.Encode.Blob:PNG.Bytestream.Destination
{
mutating
func write(_ data:[UInt8]) -> Void?
{
self.buffer.append(contentsOf: data)
return ()
}
}
extension Benchmark.Encode
{
static
func rgba8(level:Int, path:String, trials:Int) -> ([(time:Int, hash:Int)], Int)
{
guard let image:PNG.Data.Rectangular = try? .decompress(path: path)
else
{
fatalError("failed to decode test image '\(path)'")
}
let results:[(time:Int, size:Int, hash:Int)] = (0 ..< trials).map
{
_ in
// sleep for 0.1s between runs to emulate a “cold” start
nanosleep([timespec.init(tv_sec: 0, tv_nsec: 100_000_000)], nil)
var blob:Blob = .init()
do
{
let start:Int = clock()
try image.compress(stream: &blob, level: level)
let stop:Int = clock()
return (stop - start, blob.buffer.count, .init(blob.buffer.last ?? 0))
}
catch let error
{
fatalError("\(error)")
}
}
return (results.map{ (time: $0.time, hash: $0.hash) }, results.map(\.size).min() ?? 0)
}
}
func main() throws
{
guard CommandLine.arguments.count == 4,
let level:Int = Int.init(CommandLine.arguments[1]),
let trials:Int = Int.init(CommandLine.arguments[3])
else
{
fatalError("usage: \(CommandLine.arguments.first ?? "") <compression-level:0 ... 9> <image> <trials>")
}
let path:String = CommandLine.arguments[2]
guard 0 ... 13 ~= level
else
{
fatalError("compression level must be an integer from 0 to 13")
}
#if INTERNAL_BENCHMARKS
let (results, size):([(time:Int, hash:Int)], Int) =
__Entrypoint.Benchmark.Encode.rgba8(level: level, path: path, trials: trials)
#else
let (results, size):([(time:Int, hash:Int)], Int) =
Benchmark.Encode.rgba8(level: level, path: path, trials: trials)
#endif
let string:String = results.map
{
"\(1000.0 * .init($0.time) / .init(CLOCKS_PER_SEC))"
}.joined(separator: " ")
print("\(string), \(size)")
}
try main()
#endif
|
c844ec0cd7d165757d324e6972286579
| 25.873016 | 165 | 0.567336 | false | false | false | false |
alblue/swift
|
refs/heads/master
|
stdlib/public/core/ArrayBufferProtocol.swift
|
apache-2.0
|
2
|
//===--- ArrayBufferProtocol.swift ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// The underlying buffer for an ArrayType conforms to
/// `_ArrayBufferProtocol`. This buffer does not provide value semantics.
@usableFromInline
internal protocol _ArrayBufferProtocol
: MutableCollection, RandomAccessCollection
where Indices == Range<Int> {
/// Create an empty buffer.
init()
/// Adopt the entire buffer, presenting it at the provided `startIndex`.
init(_buffer: _ContiguousArrayBuffer<Element>, shiftedToStartIndex: Int)
init(copying buffer: Self)
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@discardableResult
__consuming func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element>
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the `self`
/// buffer store `minimumCapacity` elements, returns that buffer.
/// Otherwise, returns `nil`.
///
/// - Note: The result's firstElementAddress may not match ours, if we are a
/// _SliceBuffer.
///
/// - Note: This function must remain mutating; otherwise the buffer
/// may acquire spurious extra references, which will cause
/// unnecessary reallocation.
mutating func requestUniqueMutableBackingBuffer(
minimumCapacity: Int
) -> _ContiguousArrayBuffer<Element>?
/// Returns `true` iff this buffer is backed by a uniquely-referenced mutable
/// _ContiguousArrayBuffer.
///
/// - Note: This function must remain mutating; otherwise the buffer
/// may acquire spurious extra references, which will cause
/// unnecessary reallocation.
mutating func isMutableAndUniquelyReferenced() -> Bool
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>?
/// Replace the given `subRange` with the first `newCount` elements of
/// the given collection.
///
/// - Precondition: This buffer is backed by a uniquely-referenced
/// `_ContiguousArrayBuffer`.
mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newCount: Int,
elementsOf newValues: __owned C
) where C : Collection, C.Element == Element
/// Returns a `_SliceBuffer` containing the elements in `bounds`.
subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get }
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Precondition: Such contiguous storage exists or the buffer is empty.
mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R
/// The number of elements the buffer stores.
override var count: Int { get set }
/// The number of elements the buffer can store without reallocation.
var capacity: Int { get }
/// An object that keeps the elements stored in this buffer alive.
var owner: AnyObject { get }
/// A pointer to the first element.
///
/// - Precondition: The elements are known to be stored contiguously.
var firstElementAddress: UnsafeMutablePointer<Element> { get }
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { get }
/// Returns a base address to which you can add an index `i` to get the
/// address of the corresponding element at `i`.
var subscriptBaseAddress: UnsafeMutablePointer<Element> { get }
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
var identity: UnsafeRawPointer { get }
}
extension _ArrayBufferProtocol where Indices == Range<Int>{
@inlinable
internal var subscriptBaseAddress: UnsafeMutablePointer<Element> {
return firstElementAddress
}
// Make sure the compiler does not inline _copyBuffer to reduce code size.
@inline(never)
@usableFromInline
internal init(copying buffer: Self) {
let newBuffer = _ContiguousArrayBuffer<Element>(
_uninitializedCount: buffer.count, minimumCapacity: buffer.count)
buffer._copyContents(
subRange: buffer.indices,
initializing: newBuffer.firstElementAddress)
self = Self( _buffer: newBuffer, shiftedToStartIndex: buffer.startIndex)
}
@inlinable
internal mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newCount: Int,
elementsOf newValues: __owned C
) where C : Collection, C.Element == Element {
_sanityCheck(startIndex == 0, "_SliceBuffer should override this function.")
let oldCount = self.count
let eraseCount = subrange.count
let growth = newCount - eraseCount
self.count = oldCount + growth
let elements = self.subscriptBaseAddress
let oldTailIndex = subrange.upperBound
let oldTailStart = elements + oldTailIndex
let newTailIndex = oldTailIndex + growth
let newTailStart = oldTailStart + growth
let tailCount = oldCount - subrange.upperBound
if growth > 0 {
// Slide the tail part of the buffer forwards, in reverse order
// so as not to self-clobber.
newTailStart.moveInitialize(from: oldTailStart, count: tailCount)
// Assign over the original subrange
var i = newValues.startIndex
for j in subrange {
elements[j] = newValues[i]
newValues.formIndex(after: &i)
}
// Initialize the hole left by sliding the tail forward
for j in oldTailIndex..<newTailIndex {
(elements + j).initialize(to: newValues[i])
newValues.formIndex(after: &i)
}
_expectEnd(of: newValues, is: i)
}
else { // We're not growing the buffer
// Assign all the new elements into the start of the subrange
var i = subrange.lowerBound
var j = newValues.startIndex
for _ in 0..<newCount {
elements[i] = newValues[j]
i += 1
newValues.formIndex(after: &j)
}
_expectEnd(of: newValues, is: j)
// If the size didn't change, we're done.
if growth == 0 {
return
}
// Move the tail backward to cover the shrinkage.
let shrinkage = -growth
if tailCount > shrinkage { // If the tail length exceeds the shrinkage
// Assign over the rest of the replaced range with the first
// part of the tail.
newTailStart.moveAssign(from: oldTailStart, count: shrinkage)
// Slide the rest of the tail back
oldTailStart.moveInitialize(
from: oldTailStart + shrinkage, count: tailCount - shrinkage)
}
else { // Tail fits within erased elements
// Assign over the start of the replaced range with the tail
newTailStart.moveAssign(from: oldTailStart, count: tailCount)
// Destroy elements remaining after the tail in subrange
(newTailStart + tailCount).deinitialize(
count: shrinkage - tailCount)
}
}
}
}
|
a7150885e3ffcab70c77fd2942b5f2a4
| 36.036866 | 80 | 0.6811 | false | false | false | false |
makma/cloud-sdk-swift
|
refs/heads/master
|
Example/KenticoCloud/ViewControllers/Cafe/CafesViewController.swift
|
mit
|
1
|
//
// CafesViewController.swift
// KenticoCloud
//
// Created by [email protected] on 08/16/2017.
// Copyright © 2017 Kentico Software. All rights reserved.
//
import UIKit
import KenticoCloud
import AlamofireImage
class CafesViewController: ListingBaseViewController, UITableViewDataSource {
// MARK: Properties
private let contentType = "cafe"
private var screenName = "CafesView"
var cafes: [Cafe] = []
@IBOutlet var tableView: UITableView!
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
}
override func viewDidAppear(_ animated: Bool) {
if cafes.count == 0 {
getCafes()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Delegates
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cafes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cafeCell") as! CafeTableViewCell
cell.photo.addBorder()
let cafe = cafes[indexPath.row]
cell.cafeTitle.text = cafe.city
cell.cafeSubtitle.text = "\(cafe.street ?? "") \(cafe.phone ?? "")"
if let imageUrl = cafe.imageUrl {
let url = URL(string: imageUrl)
cell.photo.af_setImage(withURL: url!)
} else {
cell.photo.image = UIImage(named: "noContent")
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "cafeDetailSegue" {
let cafeDetailViewController = segue.destination
as! CafeDetailViewController
let indexPath = self.tableView.indexPathForSelectedRow!
cafeDetailViewController.cafe = cafes[indexPath.row]
let cell = self.tableView.cellForRow(at: indexPath) as! CafeTableViewCell
cafeDetailViewController.image = cell.photo.image
}
if let index = self.tableView.indexPathForSelectedRow{
self.tableView.deselectRow(at: index, animated: true)
}
}
// MARK: Outlet actions
@IBAction func refreshTable(_ sender: Any) {
getCafes()
}
// MARK: Getting items
private func getCafes() {
self.showLoader(message: "Loading cafes...")
let cloudClient = DeliveryClient.init(projectId: AppConstants.projectId)
let typeQueryParameter = QueryParameter.init(parameterKey: QueryParameterKey.type, parameterValue: contentType)
cloudClient.getItems(modelType: Cafe.self, queryParameters: [typeQueryParameter]) { (isSuccess, itemsResponse, error) in
if isSuccess {
if let cafes = itemsResponse?.items {
self.cafes = cafes
self.tableView.reloadData()
}
} else {
if let error = error {
print(error)
}
}
DispatchQueue.main.async {
self.finishLoadingItems()
}
}
}
func finishLoadingItems() {
self.hideLoader()
self.tableView.refreshControl?.endRefreshing()
UIView.animate(withDuration: 0.3, animations: {
self.tableView.contentOffset = CGPoint.zero
})
}
}
|
64ee475cfd13648a0abb13ef107d3eda
| 28.015385 | 128 | 0.58404 | false | false | false | false |
Cu-Toof/RealmObjc
|
refs/heads/dev
|
Carthage/Checkouts/realm-cocoa/RealmSwift/Results.swift
|
apache-2.0
|
33
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// 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 Realm
// MARK: MinMaxType
/**
Types of properties which can be used with the minimum and maximum value APIs.
- see: `min(ofProperty:)`, `max(ofProperty:)`
*/
public protocol MinMaxType {}
extension NSNumber: MinMaxType {}
extension Double: MinMaxType {}
extension Float: MinMaxType {}
extension Int: MinMaxType {}
extension Int8: MinMaxType {}
extension Int16: MinMaxType {}
extension Int32: MinMaxType {}
extension Int64: MinMaxType {}
extension Date: MinMaxType {}
extension NSDate: MinMaxType {}
// MARK: AddableType
/**
Types of properties which can be used with the sum and average value APIs.
- see: `sum(ofProperty:)`, `average(ofProperty:)`
*/
public protocol AddableType {}
extension NSNumber: AddableType {}
extension Double: AddableType {}
extension Float: AddableType {}
extension Int: AddableType {}
extension Int8: AddableType {}
extension Int16: AddableType {}
extension Int32: AddableType {}
extension Int64: AddableType {}
/**
`Results` is an auto-updating container type in Realm returned from object queries.
`Results` can be queried with the same predicates as `List<T>`, and you can chain queries to further filter query
results.
`Results` always reflect the current state of the Realm on the current thread, including during write transactions on
the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over
the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be
excluded by the filter during the enumeration.
`Results` are lazily evaluated the first time they are accessed; they only run queries when the result of the query is
requested. This means that chaining several temporary `Results` to sort and filter your data does not perform any
unnecessary work processing the intermediate state.
Once the results have been evaluated or a notification block has been added, the results are eagerly kept up-to-date,
with the work done to keep them up-to-date done on a background thread whenever possible.
Results instances cannot be directly instantiated.
*/
public final class Results<T: Object>: NSObject, NSFastEnumeration {
internal let rlmResults: RLMResults<RLMObject>
/// A human-readable description of the objects represented by the results.
public override var description: String {
let type = "Results<\(rlmResults.objectClassName)>"
return gsub(pattern: "RLMResults <0x[a-z0-9]+>", template: type, string: rlmResults.description) ?? type
}
// MARK: Fast Enumeration
/// :nodoc:
public func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>,
objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>!,
count len: Int) -> Int {
return Int(rlmResults.countByEnumerating(with: state, objects: buffer, count: UInt(len)))
}
/// The type of the objects described by the results.
public typealias Element = T
// MARK: Properties
/// The Realm which manages this results. Note that this property will never return `nil`.
public var realm: Realm? { return Realm(rlmResults.realm) }
/**
Indicates if the results are no longer valid.
The results becomes invalid if `invalidate()` is called on the containing `realm`. An invalidated results can be
accessed, but will always be empty.
*/
public var isInvalidated: Bool { return rlmResults.isInvalidated }
/// The number of objects in the results.
public var count: Int { return Int(rlmResults.count) }
// MARK: Initializers
internal init(_ rlmResults: RLMResults<RLMObject>) {
self.rlmResults = rlmResults
}
// MARK: Index Retrieval
/**
Returns the index of the given object in the results, or `nil` if the object is not present.
*/
public func index(of object: T) -> Int? {
return notFoundToNil(index: rlmResults.index(of: object.unsafeCastToRLMObject()))
}
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicate: The predicate with which to filter the objects.
*/
public func index(matching predicate: NSPredicate) -> Int? {
return notFoundToNil(index: rlmResults.indexOfObject(with: predicate))
}
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat,
argumentArray: args)))
}
// MARK: Object Retrieval
/**
Returns the object at the given `index`.
- parameter index: The index.
*/
public subscript(position: Int) -> T {
throwForNegativeIndex(position)
return unsafeBitCast(rlmResults.object(at: UInt(position)), to: T.self)
}
/// Returns the first object in the results, or `nil` if the results are empty.
public var first: T? { return unsafeBitCast(rlmResults.firstObject(), to: Optional<T>.self) }
/// Returns the last object in the results, or `nil` if the results are empty.
public var last: T? { return unsafeBitCast(rlmResults.lastObject(), to: Optional<T>.self) }
// MARK: KVC
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the results.
- parameter key: The name of the property whose values are desired.
*/
public override func value(forKey key: String) -> Any? {
return value(forKeyPath: key)
}
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the results.
- parameter keyPath: The key path to the property whose values are desired.
*/
public override func value(forKeyPath keyPath: String) -> Any? {
return rlmResults.value(forKeyPath: keyPath)
}
/**
Invokes `setValue(_:forKey:)` on each of the objects represented by the results using the specified `value` and
`key`.
- warning: This method may only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
public override func setValue(_ value: Any?, forKey key: String) {
return rlmResults.setValue(value, forKeyPath: key)
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func filter(_ predicateFormat: String, _ args: Any...) -> Results<T> {
return Results<T>(rlmResults.objects(with: NSPredicate(format: predicateFormat, argumentArray: args)))
}
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicate: The predicate with which to filter the objects.
*/
public func filter(_ predicate: NSPredicate) -> Results<T> {
return Results<T>(rlmResults.objects(with: predicate))
}
// MARK: Sorting
/**
Returns a `Results` containing the objects represented by the results, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<T> {
return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
}
/**
Returns a `Results` containing the objects represented by the results, but sorted.
Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byProperty: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter property: The name of the property to sort by.
- parameter ascending: The direction to sort in.
*/
@available(*, deprecated, renamed: "sorted(byKeyPath:ascending:)")
public func sorted(byProperty property: String, ascending: Bool = true) -> Results<T> {
return sorted(byKeyPath: property, ascending: ascending)
}
/**
Returns a `Results` containing the objects represented by the results, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor {
return Results<T>(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the results, or `nil` if the results are empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<U: MinMaxType>(ofProperty property: String) -> U? {
return rlmResults.min(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the maximum (highest) value of the given property among all the results, or `nil` if the results are empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func max<U: MinMaxType>(ofProperty property: String) -> U? {
return rlmResults.max(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the sum of the values of a given property over all the results.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<U: AddableType>(ofProperty property: String) -> U {
return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property))
}
/**
Returns the average value of a given property over all the results, or `nil` if the results are empty.
- warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average<U: AddableType>(ofProperty property: String) -> U? {
return rlmResults.average(ofProperty: property).map(dynamicBridgeCast)
}
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.addNotificationBlock { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `stop()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<Results>) -> Void) -> NotificationToken {
return rlmResults.addNotificationBlock { _, change, error in
block(RealmCollectionChange.fromObjc(value: self, change: change, error: error))
}
}
}
extension Results: RealmCollection {
// MARK: Sequence Support
/// Returns a `RLMIterator` that yields successive elements in the results.
public func makeIterator() -> RLMIterator<T> {
return RLMIterator(collection: rlmResults)
}
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return count }
public func index(after i: Int) -> Int { return i + 1 }
public func index(before i: Int) -> Int { return i - 1 }
/// :nodoc:
public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) ->
NotificationToken {
let anyCollection = AnyRealmCollection(self)
return rlmResults.addNotificationBlock { _, change, error in
block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error))
}
}
}
// MARK: AssistedObjectiveCBridgeable
extension Results: AssistedObjectiveCBridgeable {
static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Results {
return Results(objectiveCValue as! RLMResults)
}
var bridged: (objectiveCValue: Any, metadata: Any?) {
return (objectiveCValue: rlmResults, metadata: nil)
}
}
// MARK: Unavailable
extension Results {
@available(*, unavailable, renamed: "isInvalidated")
public var invalidated: Bool { fatalError() }
@available(*, unavailable, renamed: "index(matching:)")
public func index(of predicate: NSPredicate) -> Int? { fatalError() }
@available(*, unavailable, renamed: "index(matching:_:)")
public func index(of predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() }
@available(*, unavailable, renamed: "sorted(byKeyPath:ascending:)")
public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() }
@available(*, unavailable, renamed: "sorted(by:)")
public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor {
fatalError()
}
@available(*, unavailable, renamed: "min(ofProperty:)")
public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() }
@available(*, unavailable, renamed: "max(ofProperty:)")
public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() }
@available(*, unavailable, renamed: "sum(ofProperty:)")
public func sum<U: AddableType>(_ property: String) -> U { fatalError() }
@available(*, unavailable, renamed: "average(ofProperty:)")
public func average<U: AddableType>(_ property: String) -> U? { fatalError() }
}
|
446ca1d019719c7abadd2617841e3d47
| 39.632385 | 120 | 0.684851 | false | false | false | false |
RicardoDaSilvaSouza/StudyProjects
|
refs/heads/master
|
RSSAvaliacaoIntro/RSSAvaliacaoIntro/RSSFormFillViewController.swift
|
apache-2.0
|
1
|
//
// RSSFormFillViewController.swift
// RSSAvaliacaoIntro
//
// Created by Usuário Convidado on 23/02/16.
// Copyright © 2016 Usuário Convidado. All rights reserved.
//
import UIKit
class RSSFormFillViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var tfName: UITextField!
@IBOutlet weak var tfEmail: UITextField!
@IBOutlet weak var tfPhoneNumber: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
tfName.delegate = self
tfEmail.delegate = self
tfPhoneNumber.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func tapNext(sender: UIButton) {
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if(textField == tfName){
tfEmail.becomeFirstResponder()
} else if(textField == tfEmail){
tfPhoneNumber.becomeFirstResponder()
} else {
tfPhoneNumber.resignFirstResponder()
}
return false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let viewController: RSSFormDetailViewController = segue.destinationViewController as! RSSFormDetailViewController
viewController.theName = tfName.text
viewController.theEmail = tfEmail.text
viewController.thePhoneNumber = tfPhoneNumber.text
}
}
|
d4d4b7b0953a4607b13421e8e6f12a7e
| 30.06 | 121 | 0.678042 | false | false | false | false |
aryaxt/MagicalMapper
|
refs/heads/master
|
Example/Example/ServiceClient/AlamofireAndMagicalMapperClient.swift
|
mit
|
1
|
//
// File.swift
// Example
//
// Created by Aryan on 8/31/14.
// Copyright (c) 2014 aryaxt. All rights reserved.
//
import Foundation
import CoreData
import MagicalMapper
public class AlamofireAndMagicalMapperClient {
class var sharedInstance : AlamofireAndMagicalMapperClient {
struct Static {
static let instance : AlamofireAndMagicalMapperClient = AlamofireAndMagicalMapperClient()
}
return Static.instance
}
let mapper: MagicalMapper
init() {
mapper = MagicalMapper(managedObjectContext: CoreDataManager.sharedInstance.managedObjectContext!)
setupMapping()
}
/*
* These 2 methods are all we need to make any http call and persist data into core data
* Makes http call gets a list of dictionaries and mapps them to the specifid managed object type
*/
public func fetchObjects <T: NSManagedObject>(method: Method, url: String, type: T.Type, completion: (results: [T]?, error: NSError?) -> ()) -> Request {
return Manager.sharedInstance
.request(method, url, parameters: nil, encoding: .JSON)
.responseJSON { request, response, JSON, error in
if let anError = error {
completion(results: nil, error: nil)
}
else {
if JSON == nil || JSON!.count == 0 {
completion(results: [], error: nil)
}
var managedObjects = self.mapper.mapDictionaries(JSON as [[String: AnyObject]], toType: type)
completion(results: managedObjects, error: nil)
}
}
}
/*
* These 2 methods are all we need to make any http call and persist data into core data
* Makes http call gets a list of dictionaries and mapps them to the specifid managed object type
*/
public func fetchObject <T: NSManagedObject>(method: Method, url: String, type: T.Type, completion: (results: T?, error: NSError?) -> ()) -> Request {
return Manager.sharedInstance
.request(method, url, parameters: nil, encoding: ParameterEncoding.JSON)
.responseJSON {(request, response, JSON, error) in
if let anError = error {
completion(results: nil, error: nil)
}
else {
if JSON == nil {
completion(results: nil, error: nil)
}
var managedObject = self.mapper.mapDictionary(JSON as [String: AnyObject], toType: type)
completion(results: managedObject, error: nil)
}
}
}
public func setupMapping () {
// Setting unique identifier for insert/update records
mapper.addUniqueIdentifiersForEntity(Repository.self, identifiers: "id")
mapper.addUniqueIdentifiersForEntity(Owner.self, identifiers: "id")
// NOTE
//
// If we named our model properties the same as keys coming back from the server
// the code below would not be needed and ALL mapping would be automatic
mapper[Repository.self] = [
"open_issues_count" : "openIssuesCount",
"created_at" : "createdAt"
]
mapper[Owner.self] = [
"login" : "username",
"avatar_url" : "avatarUrl"
]
}
}
|
f450f18aba9eb9f97df603d4ef04548a
| 34.127451 | 157 | 0.560424 | false | false | false | false |
MadAppGang/refresher
|
refs/heads/master
|
Refresher/PullToRefreshView.swift
|
mit
|
1
|
//
// PullToRefreshView.swift
//
// Copyright (c) 2014 Josip Cavar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import QuartzCore
private var KVOContext = "RefresherKVOContext"
private let ContentOffsetKeyPath = "contentOffset"
public enum PullToRefreshViewState {
case Loading
case PullToRefresh
case ReleaseToRefresh
}
public protocol PullToRefreshViewDelegate {
func pullToRefreshAnimationDidStart(view: PullToRefreshView)
func pullToRefreshAnimationDidEnd(view: PullToRefreshView)
func pullToRefresh(view: PullToRefreshView, progressDidChange progress: CGFloat)
func pullToRefresh(view: PullToRefreshView, stateDidChange state: PullToRefreshViewState)
}
public class PullToRefreshView: UIView {
private var scrollViewBouncesDefaultValue: Bool = false
private var scrollViewInsetsDefaultValue: UIEdgeInsets = UIEdgeInsetsZero
private var animator: PullToRefreshViewDelegate
private var action: (() -> ()) = {}
private var previousOffset: CGFloat = 0
public var disabled = false {
didSet {
hidden = disabled
stopAnimating(false)
if disabled == true {
if loading == true {
loading = false
}
animator.pullToRefresh(self, stateDidChange: .PullToRefresh)
animator.pullToRefresh(self, progressDidChange: 0)
}
}
}
internal var loading: Bool = false {
didSet {
if loading {
startAnimating(true)
} else {
stopAnimating(true)
}
}
}
//MARK: Object lifecycle methods
convenience init(action :(() -> ()), frame: CGRect) {
var bounds = frame
bounds.origin.y = 0
let animator = Animator(frame: bounds)
self.init(frame: frame, animator: animator)
self.action = action;
addSubview(animator.animatorView)
}
convenience init(action :(() -> ()), frame: CGRect, animator: PullToRefreshViewDelegate, subview: UIView) {
self.init(frame: frame, animator: animator)
self.action = action;
subview.frame = self.bounds
addSubview(subview)
}
convenience init(action :(() -> ()), frame: CGRect, animator: PullToRefreshViewDelegate) {
self.init(frame: frame, animator: animator)
self.action = action;
}
init(frame: CGRect, animator: PullToRefreshViewDelegate) {
self.animator = animator
super.init(frame: frame)
self.autoresizingMask = .FlexibleWidth
}
public required init?(coder aDecoder: NSCoder) {
self.animator = Animator(frame: CGRectZero)
super.init(coder: aDecoder)
// Currently it is not supported to load view from nib
}
deinit {
let scrollView = superview as? UIScrollView
scrollView?.removeObserver(self, forKeyPath: ContentOffsetKeyPath, context: &KVOContext)
}
//MARK: UIView methods
public override func willMoveToSuperview(newSuperview: UIView!) {
superview?.removeObserver(self, forKeyPath: ContentOffsetKeyPath, context: &KVOContext)
if let scrollView = newSuperview as? UIScrollView {
scrollView.addObserver(self, forKeyPath: ContentOffsetKeyPath, options: .Initial, context: &KVOContext)
scrollViewBouncesDefaultValue = scrollView.bounces
scrollViewInsetsDefaultValue = scrollView.contentInset
}
}
//MARK: KVO methods
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<()>) {
if (context == &KVOContext) {
if let scrollView = superview as? UIScrollView where object as? NSObject == scrollView {
if keyPath == ContentOffsetKeyPath && disabled == false {
let offsetWithoutInsets = previousOffset + scrollViewInsetsDefaultValue.top
if (offsetWithoutInsets < -self.frame.size.height) {
if (scrollView.dragging == false && loading == false) {
loading = true
} else if (loading) {
animator.pullToRefresh(self, stateDidChange: .Loading)
} else {
animator.pullToRefresh(self, stateDidChange: .ReleaseToRefresh)
animator.pullToRefresh(self, progressDidChange: -offsetWithoutInsets / self.frame.size.height)
}
} else if (loading) {
animator.pullToRefresh(self, stateDidChange: .Loading)
} else if (offsetWithoutInsets < 0) {
animator.pullToRefresh(self, stateDidChange: .PullToRefresh)
animator.pullToRefresh(self, progressDidChange: -offsetWithoutInsets / self.frame.size.height)
}
previousOffset = scrollView.contentOffset.y
}
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
//MARK: PullToRefreshView methods
internal func startAnimating(animated:Bool) {
let scrollView = superview as! UIScrollView
var insets = scrollView.contentInset
if scrollView.сonnectionLostView?.hidden == true {
insets.top += self.frame.size.height
// we need to restore previous offset because we will animate scroll view insets and regular scroll view animating is not applied then
scrollView.contentOffset.y = previousOffset
}
scrollView.bounces = false
if animated == true {
UIView.animateWithDuration(0.3, delay: 0, options:[], animations: {
scrollView.contentInset = insets
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -insets.top)
}, completion: {finished in
self.animator.pullToRefreshAnimationDidStart(self)
self.action()
})
} else {
scrollView.contentInset = insets
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -insets.top)
self.animator.pullToRefreshAnimationDidStart(self)
self.action()
}
}
internal func stopAnimating(animated:Bool) {
self.animator.pullToRefreshAnimationDidEnd(self)
let scrollView = superview as! UIScrollView
scrollView.bounces = self.scrollViewBouncesDefaultValue
if animated == true {
UIView.animateWithDuration(0.3, animations: {
if scrollView.сonnectionLostView?.hidden == true {
scrollView.contentInset = self.scrollViewInsetsDefaultValue
}
}) { finished in
self.animator.pullToRefresh(self, progressDidChange: 0)
}
} else {
if scrollView.сonnectionLostView?.hidden == true {
scrollView.contentInset = self.scrollViewInsetsDefaultValue
}
self.animator.pullToRefresh(self, progressDidChange: 0)
}
}
}
|
822435ace7342cc877f3cc3c9d79daa0
| 37.198198 | 162 | 0.627476 | false | false | false | false |
marekhac/WczasyNadBialym-iOS
|
refs/heads/master
|
WczasyNadBialym/WczasyNadBialym/Models/Network/Accommodation/API+Accommodation.swift
|
gpl-3.0
|
1
|
//
// API+Accommodation.swift
// WczasyNadBialym
//
// Created by Marek Hać on 21.02.2017.
// Copyright © 2017 Marek Hać. All rights reserved.
//
import Foundation
extension API {
struct Accommodation {
// MARK: Controller Keys
struct Controller {
static let Accommodation = "noclegi/"
}
// MARK: Methods
struct Method {
static let ListBasic = "lista"
static let Details = "details"
static let Pictures = "pobierz-liste-zdjec"
static let Features = "wyposazenie"
}
// MARK: Method Keys
struct ParameterKey {
static let Kind = "typ"
static let Id = "id"
}
}
}
|
302c4480d27ddd59db4406ca163c20ff
| 21.194444 | 55 | 0.50438 | false | false | false | false |
iOS-mamu/SS
|
refs/heads/master
|
P/Library/Eureka/Source/Rows/CheckRow.swift
|
mit
|
1
|
//
// CheckRow.swift
// Eureka
//
// Created by Martin Barreto on 2/23/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
// MARK: CheckCell
public final class CheckCell : Cell<Bool>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func update() {
super.update()
accessoryType = row.value == true ? .checkmark : .none
editingAccessoryType = accessoryType
selectionStyle = .default
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
if row.isDisabled {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 0.3)
selectionStyle = .none
}
else {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
}
}
public override func setup() {
super.setup()
accessoryType = .checkmark
editingAccessoryType = accessoryType
}
public override func didSelect() {
row.value = row.value ?? false ? false : true
row.deselect()
row.updateCell()
}
}
// MARK: CheckRow
open class _CheckRow: Row<Bool, CheckCell> {
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
}
///// Boolean row that has a checkmark as accessoryType
public final class CheckRow: _CheckRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
|
1edf3538b83d88c47284c820c30fdeb0
| 25.347826 | 87 | 0.605061 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
test/SourceKit/CodeComplete/complete_moduleimportdepth.swift
|
apache-2.0
|
10
|
import ImportsImportsFoo
import FooHelper.FooHelperExplicit
func test() {
let x = 1
#^A^#
}
// RUN: %complete-test -hide-none -group=none -tok=A %s -raw -- -I %S/Inputs -F %S/../Inputs/libIDE-mock-sdk > %t
// RUN: FileCheck %s < %t
// Swift == 1
// CHECK-LABEL: key.name: "abs(x:)",
// CHECK-NEXT: key.sourcetext: "abs(<#T##x: T##T#>)",
// CHECK-NEXT: key.description: "abs(x: T)",
// CHECK-NEXT: key.typename: "T",
// CHECK-NEXT: key.doc.brief: "Return the absolute value of x.",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 1,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK: key.associated_usrs: "s:Fs3absuRxs16SignedNumberTyperFxx",
// CHECK-NEXT: key.modulename: "Swift"
// CHECK-NEXT: },
// FooHelper.FooHelperExplicit == 1
// CHECK-LABEL: key.name: "fooHelperExplicitFrameworkFunc1(a:)",
// CHECK-NEXT: key.sourcetext: "fooHelperExplicitFrameworkFunc1(<#T##a: Int32##Int32#>)",
// CHECK-NEXT: key.description: "fooHelperExplicitFrameworkFunc1(a: Int32)",
// CHECK-NEXT: key.typename: "Int32",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 1,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK: key.associated_usrs: "c:@F@fooHelperExplicitFrameworkFunc1",
// CHECK-NEXT: key.modulename: "FooHelper.FooHelperExplicit"
// CHECK-NEXT: },
// ImportsImportsFoo == 1
// CHECK-LABEL: key.name: "importsImportsFoo()",
// CHECK-NEXT: key.sourcetext: "importsImportsFoo()",
// CHECK-NEXT: key.description: "importsImportsFoo()",
// CHECK-NEXT: key.typename: "Void",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 1,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK: key.associated_usrs: "c:@F@importsImportsFoo",
// CHECK-NEXT: key.modulename: "ImportsImportsFoo"
// CHECK-NEXT: },
// Bar == 2
// CHECK-LABEL: key.name: "BarForwardDeclaredClass",
// CHECK-NEXT: key.sourcetext: "BarForwardDeclaredClass",
// CHECK-NEXT: key.description: "BarForwardDeclaredClass",
// CHECK-NEXT: key.typename: "BarForwardDeclaredClass",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 2,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK: key.associated_usrs: "c:objc(cs)BarForwardDeclaredClass",
// CHECK-NEXT: key.modulename: "Bar"
// CHECK-NEXT: },
// ImportsFoo == 2
// CHECK-LABEL: key.name: "importsFoo()",
// CHECK-NEXT: key.sourcetext: "importsFoo()",
// CHECK-NEXT: key.description: "importsFoo()",
// CHECK-NEXT: key.typename: "Void",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 2,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK: key.associated_usrs: "c:@F@importsFoo",
// CHECK-NEXT: key.modulename: "ImportsFoo"
// CHECK-NEXT: },
// Foo == FooSub == 3
// CHECK-LABEL: key.name: "FooClassBase",
// CHECK-NEXT: key.sourcetext: "FooClassBase",
// CHECK-NEXT: key.description: "FooClassBase",
// CHECK-NEXT: key.typename: "FooClassBase",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 3,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK: key.associated_usrs: "c:objc(cs)FooClassBase",
// CHECK-NEXT: key.modulename: "Foo"
// CHECK-NEXT: },
// CHECK-LABEL: key.name: "FooSubEnum1",
// CHECK-NEXT: key.sourcetext: "FooSubEnum1",
// CHECK-NEXT: key.description: "FooSubEnum1",
// CHECK-NEXT: key.typename: "FooSubEnum1",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 3,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK: key.associated_usrs: "c:@E@FooSubEnum1",
// CHECK-NEXT: key.modulename: "Foo.FooSub"
// CHECK-NEXT: },
// FooHelper == 4
// FIXME: rdar://problem/20230030
// We're picking up the implicit import of FooHelper used to attach FooHelperExplicit to.
// xCHECK-LABEL: key.name: "FooHelperUnnamedEnumeratorA2",
// xCHECK-NEXT: key.sourcetext: "FooHelperUnnamedEnumeratorA2",
// xCHECK-NEXT: key.description: "FooHelperUnnamedEnumeratorA2",
// xCHECK-NEXT: key.typename: "Int",
// xCHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// xCHECK-NEXT: key.moduleimportdepth: 4,
// xCHECK-NEXT: key.num_bytes_to_erase: 0,
// xCHECK: key.associated_usrs: "c:FooHelper.h@Ea@FooHelperUnnamedEnumeratorA2",
// xCHECK-NEXT: key.modulename: "FooHelper"
// xCHECK-NEXT: },
|
6fe2fc59e6cfc9880f67a7feed6c3440
| 41.803738 | 113 | 0.691266 | false | false | false | false |
Basadev/MakeSchoolNotes
|
refs/heads/master
|
Frameworks/ConvenienceKit/ConvenienceKit/ConvenienceKitTests/UIKit/PresentViewControllerAnywhere.swift
|
apache-2.0
|
2
|
//
// PresentViewControllerAnywhere.swift
// ConvenienceKit
//
// Created by Benjamin Encz on 4/10/15.
// Copyright (c) 2015 Benjamin Encz. All rights reserved.
//
import Foundation
import UIKit
import Quick
import Nimble
import ConvenienceKit
class PresentViewControllerAnywhereSpec : QuickSpec {
override func spec() {
describe("UIViewController PresentAnywhere Extension") {
context("when used on a plain view controller") {
it("presents the controller on the plain view controller") {
let uiApplication = UIApplication.sharedApplication()
var window = UIApplication.sharedApplication().windows[0] as! UIWindow
let presentedViewController = UIViewController()
window.rootViewController = UIViewController()
let rootViewController = window.rootViewController!
rootViewController.presentViewControllerFromTopViewController(presentedViewController)
expect(presentedViewController.presentingViewController).to(equal(rootViewController))
}
}
// context("when used on a navigation view controller") {
//
// it("presents it on the first content view controller when only one is added") {
// let uiApplication = UIApplication.sharedApplication()
// let window = UIApplication.sharedApplication().windows[0] as! UIWindow
// let firstContentViewController = UIViewController()
// let secondContentViewController = UIViewController()
// let navigationController = UINavigationController(rootViewController: firstContentViewController)
// navigationController.pushViewController(secondContentViewController, animated: false)
// window.rootViewController = navigationController
//
// window.addSubview(navigationController.view)
//
// let presentedViewController = UIViewController()
// let rootViewController = window.rootViewController!
// rootViewController.presentViewControllerFromTopViewController(presentedViewController)
//
//// expect(presentedViewController.presentingViewController).to(equal(secondContentViewController))
// }
// }
// context("when used on a modally presented view controller") {
//
// it("presents it on the modal view controller") {
// let uiApplication = UIApplication.sharedApplication()
// var window = UIApplication.sharedApplication().windows[0] as! UIWindow
// window.rootViewController = UIViewController()
//
// let modalViewController = UIViewController()
// let presentedViewController = UIViewController()
//
// window.rootViewController?.presentViewController(modalViewController, animated: false, completion: nil)
//
// window.rootViewController?.presentViewControllerFromTopViewController(presentedViewController)
//
// expect(presentedViewController.presentingViewController).to(equal(modalViewController))
// }
//
// }
}
}
}
|
3cec1bf5b1eee55afd18f8422d1f8923
| 39.333333 | 115 | 0.682035 | false | false | false | false |
roothybrid7/SharedKit
|
refs/heads/master
|
Sources/SharedKit/RGBColorModel/RGBHexParser.swift
|
mit
|
1
|
//
// RGBHexParser.swift
// SharedKit
//
// Created by Satoshi Ohki on 2016/10/09.
//
//
import Foundation
/// A type that supports to parse a color hex string to UInt.
public protocol RGBHexParsable {
static var rgbHexExpression: NSRegularExpression { get }
/// A target value that should be parsed.
var value: String { get set }
/// A parsed result value of a target value.
var parsed: UInt? { get }
}
/**
A structure is a parser that parse a color hex string to UInt value.
#000000->0
#000->0
*/
public struct RGBHexParser: RGBHexParsable, ExpressibleByStringLiteral {
private static let rgbPattern = "([0-9a-f])"
public static let rgbHexExpression: NSRegularExpression = try! NSRegularExpression(pattern: rgbPattern, options: [.caseInsensitive]) // swiftlint:disable:this force_try
public var value: String
public init(hexString value: String) {
self.value = value
}
public init(stringLiteral value: String) {
self.init(hexString: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(hexString: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(hexString: value)
}
public var parsed: UInt? {
var code = value
if value.hasPrefix("#") {
code = value.substring(to: value.index(before: value.endIndex))
}
let matches = type(of: self).rgbHexExpression.matches(in: code, range: NSRange(location: 0, length: code.characters.count))
if matches.count != 3 && matches.count != 6 {
return nil
} else if matches.count == 3 {
code = matches.map { (code as NSString).substring(with: $0.rangeAt(1)) }.map { $0 + $0 }.joined()
}
let scanner = Scanner(string: code)
var result: UInt32 = 0
scanner.scanHexInt32(&result)
return UInt(result)
}
}
|
4bf2bcb59644551e990234c4ced64562
| 28.409091 | 174 | 0.636785 | false | false | false | false |
jkiley129/Artfull
|
refs/heads/master
|
Artfull/ARTMapGalleryViewController.swift
|
mit
|
1
|
//
// ARTMapGalleryViewController.swift
// Artfull
//
// Created by Joseph Kiley on 12/2/15.
// Copyright © 2015 Joseph Kiley. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import AddressBook
import Parse
class ARTMapGalleryViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var userTrackingBarButton: MKUserTrackingBarButtonItem!
var locationText = ""
var locationDetailText = ""
var galleryLocation: CLLocationCoordinate2D!
let locationManager = CLLocationManager ()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.tintColor = UIColor.blackColor()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestWhenInUseAuthorization()
mapView.delegate = self
mapView.showsUserLocation = true
let query = PFQuery(className: "Galleries")
// Add conditions
query.whereKeyExists("Images")
query.whereKeyExists("Gallery_Name")
query.whereKeyExists("Neighborhood")
query.whereKeyExists("Category")
// Order the results
query.orderByAscending("createdAt")
// Cache results
query.cachePolicy = .CacheElseNetwork
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil
{
//Sucess fetching object
print(objects?.count)
if let objects = objects where objects.count > 0
{
// objects is not nil
for object in objects
{
print("object[Location] = \(object["Location"])")
if let newLocationText = object["Gallery_Name"] as? String,
let newLocationDetailText = object["Neighborhood"] as? String,
let newGalleryLocation = object["Location"] as? PFGeoPoint
{
let latitude: CLLocationDegrees = newGalleryLocation.latitude
let longitude: CLLocationDegrees = newGalleryLocation.longitude
let location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let gallery = GalleryAnnotation(
title: newLocationText,
locationName: newLocationDetailText,
coordinate: location, galleryObject: object)
self.mapView.addAnnotation(gallery)
}
}
}
else
{
//objects is nil
}
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
locationManager.startUpdatingLocation()
}
func queueUpDataAndPopulatePins () {
let query = PFQuery(className: "Galleries")
// Add conditions
query.whereKeyExists("Location")
query.whereKeyExists("Gallery_Name")
query.whereKeyExists("Neighborhood")
// Order the results
query.orderByAscending("createdAt")
// Cache results
query.cachePolicy = .CacheElseNetwork
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil { //Sucess fetching object
print(objects?.count)
if let objects = objects where objects.count > 0 { // objects is not nil
for object in objects{
if let gallery = GalleryAnnotation(galleryObject: object){
self.mapView.addAnnotation(gallery)
}
}
}
else {
//objects is nil
}
}
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
print("Current location: \(location)")
if userTrackingBarButton.mapView == nil
{
userTrackingBarButton.mapView = mapView
}
let userCoordinate = location.coordinate
let mySpan = MKCoordinateSpanMake(0.08, 0.08)
let myRegion = MKCoordinateRegionMake(userCoordinate, mySpan)
mapView.setRegion(myRegion, animated: true)
mapView.showsUserLocation = true
locationManager.stopUpdatingLocation()
} else {
// handle error
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error finding location: \(error.localizedDescription)")
}
@IBAction func resetMapCurrentLocation(sender: AnyObject) {
mapView.userTrackingMode = MKUserTrackingMode.Follow
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
print(view.annotation!.title)
print(view.annotation!.subtitle)
if let galleryAnnotation = view.annotation as? GalleryAnnotation{
let destinationVC = storyboard?.instantiateViewControllerWithIdentifier("GalleryDetailTable") as! ARTGalleryDetailTableViewController
destinationVC.galleryObj = galleryAnnotation.galleryObject
navigationController?.pushViewController(destinationVC, animated: true)
}
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
}
let button = UIButton(type: .DetailDisclosure)
pinView?.rightCalloutAccessoryView = button
return pinView
}
}
|
66c71ad8db0c12df5639cbb92303e225
| 33.536946 | 149 | 0.554985 | false | false | false | false |
mbernson/HomeControl.iOS
|
refs/heads/master
|
HomeControl/Domain/Message.swift
|
mit
|
1
|
//
// Message.swift
// HomeControl
//
// Created by Mathijs Bernson on 19/03/16.
// Copyright © 2016 Duckson. All rights reserved.
//
import Foundation
import UIKit
import MQTTClient
struct Message {
static let encoding = String.Encoding.utf8
enum QoS {
case atMostOnce
case atLeastOnce
case exactlyOnce
static func fromMqttQoS(_ mqttQos: MQTTQosLevel) -> QoS {
switch mqttQos {
case .atLeastOnce: return QoS.atLeastOnce
case .exactlyOnce: return QoS.exactlyOnce
case .atMostOnce: return QoS.atMostOnce
}
}
}
let topic: Topic
let payload: Data?
let qos: QoS
let retain: Bool
init(topic: Topic, payload: Data? = nil, qos: QoS = .atLeastOnce, retain: Bool = false) {
self.topic = topic
self.payload = payload
self.qos = qos
self.retain = retain
}
init(topic: Topic, payloadString: String? = nil, qos: QoS = .atLeastOnce, retain: Bool = false) {
self.topic = topic
self.payload = payloadString?.data(using: Message.encoding)
self.qos = qos
self.retain = retain
}
func asBoolean() -> Bool? {
guard let payload = payloadString else { return nil }
switch payload {
case "on", "yes", "1", "true":
return true
case "off", "no", "0", "false":
return false
default:
print("failed to convert payload '\(payload)' to a boolean")
return nil
}
}
func asNumber() -> Float? {
guard let payload = payloadString else { return nil }
return Float(payload)
}
func asColor() -> UIColor? {
return UIColor.clear
}
}
extension Message {
var payloadString: String? {
guard let data = payload else { return nil }
return String(data: data, encoding: Message.encoding)
}
var mqttQos: MQTTQosLevel {
switch qos {
case .atLeastOnce: return MQTTQosLevel.atLeastOnce
case .exactlyOnce: return MQTTQosLevel.exactlyOnce
case .atMostOnce: return MQTTQosLevel.atMostOnce
}
}
}
|
01a062be215b9530cd85c692b477dddf
| 22.176471 | 99 | 0.650761 | false | false | false | false |
AppLovin/iOS-SDK-Demo
|
refs/heads/master
|
Swift Demo App/iOS-SDK-Demo/ALDemoBannerZoneViewController.swift
|
mit
|
1
|
//
// ALDemoBannerZoneViewController.swift
// iOS-SDK-Demo-Swift
//
// Created by Suyash Saxena on 6/19/18.
// Copyright © 2018 AppLovin. All rights reserved.
//
import UIKit
import AppLovinSDK
class ALDemoBannerZoneViewController : ALDemoBaseViewController
{
let kBannerHeight: CGFloat = 50
private let adView = ALAdView(size: ALAdSize.banner, zoneIdentifier: "YOUR_ZONE_ID")
@IBOutlet weak var loadButton: UIBarButtonItem!
// MARK: View Lifecycle
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
// Optional: Implement the ad delegates to receive ad events.
adView.adLoadDelegate = self
adView.adDisplayDelegate = self
adView.adEventDelegate = self
adView.translatesAutoresizingMaskIntoConstraints = false
// Call loadNextAd() to start showing ads
adView.loadNextAd()
// Center the banner and anchor it to the bottom of the screen.
view.addSubview(adView)
view.addConstraints([
constraint(with: adView, attribute: .leading),
constraint(with: adView, attribute: .trailing),
constraint(with: adView, attribute: .bottom),
NSLayoutConstraint(item: adView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: kBannerHeight)
])
}
override func viewDidDisappear(_ animated: Bool)
{
super.viewDidDisappear(animated)
adView.adLoadDelegate = nil
adView.adDisplayDelegate = nil
adView.adEventDelegate = nil
}
private func constraint(with adView: ALAdView, attribute: NSLayoutConstraint.Attribute) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: adView,
attribute: attribute,
relatedBy: .equal,
toItem: view,
attribute: attribute,
multiplier: 1.0,
constant: 0.0)
}
@IBAction func loadNextAd()
{
adView.loadNextAd()
loadButton.isEnabled = false
}
}
extension ALDemoBannerZoneViewController : ALAdLoadDelegate
{
func adService(_ adService: ALAdService, didLoad ad: ALAd)
{
log("Banner Loaded")
}
func adService(_ adService: ALAdService, didFailToLoadAdWithError code: Int32)
{
// Look at ALErrorCodes.h for list of error codes
log("Banner failed to load with error code \(code)")
loadButton.isEnabled = true
}
}
extension ALDemoBannerZoneViewController : ALAdDisplayDelegate
{
func ad(_ ad: ALAd, wasDisplayedIn view: UIView)
{
log("Banner Displayed")
loadButton.isEnabled = true
}
func ad(_ ad: ALAd, wasHiddenIn view: UIView)
{
log("Banner Dismissed")
}
func ad(_ ad: ALAd, wasClickedIn view: UIView)
{
log("Banner Clicked")
}
}
extension ALDemoBannerZoneViewController : ALAdViewEventDelegate
{
func ad(_ ad: ALAd, didPresentFullscreenFor adView: ALAdView)
{
log("Banner did present fullscreen")
}
func ad(_ ad: ALAd, willDismissFullscreenFor adView: ALAdView)
{
log("Banner will dismiss fullscreen")
}
func ad(_ ad: ALAd, didDismissFullscreenFor adView: ALAdView)
{
log("Banner did dismiss fullscreen")
}
func ad(_ ad: ALAd, willLeaveApplicationFor adView: ALAdView)
{
log("Banner will leave application")
}
func ad(_ ad: ALAd, didReturnToApplicationFor adView: ALAdView)
{
log("Banner did return to application")
}
func ad(_ ad: ALAd, didFailToDisplayIn adView: ALAdView, withError code: ALAdViewDisplayErrorCode)
{
log("Banner did fail to display with error code: \(code)")
}
}
|
32bb3d26dd99fca5cf680f99379b3054
| 28.027586 | 113 | 0.584937 | false | false | false | false |
niekang/WeiBo
|
refs/heads/master
|
WeiBo/Class/Utils/NKRefresh/NKRefreshView.swift
|
apache-2.0
|
1
|
//
// NKRefreshView.swift
// NKRefresh
//
// Created by 聂康 on 2017/6/25.
// Copyright © 2017年 聂康. All rights reserved.
//
import UIKit
enum NKRefreshState {
case idle
case pulling
case willRefresh
case refreshing
}
class NKRefreshView: UIView {
@IBOutlet weak var leftImageView: UIImageView?
@IBOutlet weak var stateLabel: UILabel?
@IBOutlet weak var indicator: UIActivityIndicatorView?
/// 父视图的高度
var parentViewHeight: CGFloat = 0
var state:NKRefreshState = .idle {
didSet{
switch state {
case .idle:
leftImageView?.isHidden = false
stateLabel?.text = "下拉刷新..."
indicator?.stopAnimating()
UIView.animate(withDuration: 0.5, animations: {
self.leftImageView?.transform = CGAffineTransform.identity
})
case .pulling:
stateLabel?.text = "再拉就刷新啦!"
UIView.animate(withDuration: 0.5, animations: {
self.leftImageView?.transform = CGAffineTransform.identity
})
case .willRefresh:
stateLabel?.text = "松手就刷新了"
UIView.animate(withDuration: 0.5, animations: {
self.leftImageView?.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
})
case .refreshing:
stateLabel?.text = "正在刷新..."
leftImageView?.isHidden = true
indicator?.isHidden = false
indicator?.startAnimating()
}
}
}
class func refreshView() -> NKRefreshView{
let nib = UINib(nibName: "NKMTRefreshView", bundle: nil)
let v = nib.instantiate(withOwner: nil, options: nil).first as! NKRefreshView
return v
}
}
|
b2eefb387e180eb92078efbf6f66cef8
| 26.405797 | 104 | 0.55156 | false | false | false | false |
kwkhaw/SwiftAnyPic
|
refs/heads/master
|
SwiftAnyPic/AppDelegate.swift
|
cc0-1.0
|
1
|
import UIKit
import Parse
//import ParseCrashReporting
import ParseFacebookUtils
import MBProgressHUD
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, NSURLConnectionDataDelegate, UITabBarControllerDelegate {
var window: UIWindow?
var networkStatus: Reachability.NetworkStatus?
var homeViewController: PAPHomeViewController?
var activityViewController: PAPActivityFeedViewController?
var welcomeViewController: PAPWelcomeViewController?
var tabBarController: PAPTabBarController?
var navController: UINavigationController?
private var firstLaunch: Bool = true
// MARK:- UIApplicationDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// ****************************************************************************
// Parse initialization
// FIXME: CrashReporting currently query to cydia:// ParseCrashReporting.enable()
Parse.setApplicationId("PklSbwxITu46cOumt6tdWw8Jtg2urg0vj0CrbLr0", clientKey: "ML2sjwLC7k1RCujNCRP7fxG2HpUxtwzdIR1ElOe7")
PFFacebookUtils.initializeFacebook()
// TODO: V4 PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
// ****************************************************************************
// Track app open.
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
if application.applicationIconBadgeNumber != 0 {
application.applicationIconBadgeNumber = 0
PFInstallation.currentInstallation().saveInBackground()
}
let defaultACL: PFACL = PFACL()
// Enable public read access by default, with any newly created PFObjects belonging to the current user
defaultACL.setPublicReadAccess(true)
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser: true)
// Set up our app's global UIAppearance
self.setupAppearance()
// Use Reachability to monitor connectivity
self.monitorReachability()
self.welcomeViewController = PAPWelcomeViewController()
self.navController = UINavigationController(rootViewController: self.welcomeViewController!)
self.navController!.navigationBarHidden = true
self.window!.rootViewController = self.navController
self.window!.makeKeyAndVisible()
self.handlePush(launchOptions)
return true
}
// TODO: V4
// func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
// return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
// }
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
var wasHandled = false
if PFFacebookUtils.session() != nil {
wasHandled = wasHandled || FBAppCall.handleOpenURL(url, sourceApplication: sourceApplication, withSession: PFFacebookUtils.session())
} else {
wasHandled = wasHandled || FBAppCall.handleOpenURL(url, sourceApplication: sourceApplication)
}
wasHandled = wasHandled || handleActionURL(url)
return wasHandled
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
if (application.applicationIconBadgeNumber != 0) {
application.applicationIconBadgeNumber = 0
}
let currentInstallation = PFInstallation.currentInstallation()
currentInstallation.setDeviceTokenFromData(deviceToken)
currentInstallation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code != 3010 { // 3010 is for the iPhone Simulator
print("Application failed to register for push notifications: \(error)")
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
NSNotificationCenter.defaultCenter().postNotificationName(PAPAppDelegateApplicationDidReceiveRemoteNotification, object: nil, userInfo: userInfo)
if UIApplication.sharedApplication().applicationState != UIApplicationState.Active {
// Track app opens due to a push notification being acknowledged while the app wasn't active.
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
if PFUser.currentUser() != nil {
// FIXME: Looks so lengthy, any better way?
if self.tabBarController!.viewControllers!.count > PAPTabBarControllerViewControllerIndex.ActivityTabBarItemIndex.rawValue {
let tabBarItem: UITabBarItem = self.tabBarController!.viewControllers![PAPTabBarControllerViewControllerIndex.ActivityTabBarItemIndex.rawValue].tabBarItem
if let currentBadgeValue: String = tabBarItem.badgeValue where currentBadgeValue.length > 0 {
tabBarItem.badgeValue = String(Int(currentBadgeValue)! + 1)
} else {
tabBarItem.badgeValue = "1"
}
}
}
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
// Clear badge and update installation, required for auto-incrementing badges.
if application.applicationIconBadgeNumber != 0 {
application.applicationIconBadgeNumber = 0
PFInstallation.currentInstallation().saveInBackground()
}
// Clears out all notifications from Notification Center.
UIApplication.sharedApplication().cancelAllLocalNotifications()
application.applicationIconBadgeNumber = 1
application.applicationIconBadgeNumber = 0
FBAppCall.handleDidBecomeActiveWithSession(PFFacebookUtils.session())
// TODO: V4 FBSDKAppEvents.activateApp()
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - UITabBarControllerDelegate
func tabBarController(aTabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
// The empty UITabBarItem behind our Camera button should not load a view controller
return viewController != aTabBarController.viewControllers![PAPTabBarControllerViewControllerIndex.EmptyTabBarItemIndex.rawValue]
}
// MARK:- AppDelegate
func isParseReachable() -> Bool {
return self.networkStatus != .NotReachable
}
func presentLoginViewController(animated: Bool = true) {
self.welcomeViewController!.presentLoginViewController(animated)
}
func presentTabBarController() {
self.tabBarController = PAPTabBarController()
self.homeViewController = PAPHomeViewController(style: UITableViewStyle.Plain)
self.homeViewController!.firstLaunch = firstLaunch
self.activityViewController = PAPActivityFeedViewController(style: UITableViewStyle.Plain)
let homeNavigationController: UINavigationController = UINavigationController(rootViewController: self.homeViewController!)
let emptyNavigationController: UINavigationController = UINavigationController()
let activityFeedNavigationController: UINavigationController = UINavigationController(rootViewController: self.activityViewController!)
let homeTabBarItem: UITabBarItem = UITabBarItem(title: NSLocalizedString("Home", comment: "Home"), image: UIImage(named: "IconHome.png")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "IconHomeSelected.png")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal))
homeTabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.boldSystemFontOfSize(13)], forState: UIControlState.Selected)
homeTabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0), NSFontAttributeName: UIFont.boldSystemFontOfSize(13)], forState: UIControlState.Normal)
let activityFeedTabBarItem: UITabBarItem = UITabBarItem(title: NSLocalizedString("Activity", comment: "Activity"), image: UIImage(named: "IconTimeline.png")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal), selectedImage: UIImage(named: "IconTimelineSelected.png")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal))
activityFeedTabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.boldSystemFontOfSize(13)], forState: UIControlState.Selected)
activityFeedTabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0), NSFontAttributeName: UIFont.boldSystemFontOfSize(13)], forState: UIControlState.Normal)
homeNavigationController.tabBarItem = homeTabBarItem
activityFeedNavigationController.tabBarItem = activityFeedTabBarItem
tabBarController!.delegate = self
tabBarController!.viewControllers = [homeNavigationController, emptyNavigationController, activityFeedNavigationController]
navController!.setViewControllers([welcomeViewController!, tabBarController!], animated: false)
// Register for Push Notitications
let userNotificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
}
func logOut() {
// clear cache
PAPCache.sharedCache.clear()
// clear NSUserDefaults
NSUserDefaults.standardUserDefaults().removeObjectForKey(kPAPUserDefaultsCacheFacebookFriendsKey)
NSUserDefaults.standardUserDefaults().removeObjectForKey(kPAPUserDefaultsActivityFeedViewControllerLastRefreshKey)
NSUserDefaults.standardUserDefaults().synchronize()
// Unsubscribe from push notifications by removing the user association from the current installation.
PFInstallation.currentInstallation().removeObjectForKey(kPAPInstallationUserKey)
PFInstallation.currentInstallation().saveInBackground()
// Clear all caches
PFQuery.clearAllCachedResults()
// Log out
PFUser.logOut()
FBSession.setActiveSession(nil)
// V4??? FBSDKAccessToken.currentAccessToken().tokenString
// clear out cached data, view controllers, etc
navController!.popToRootViewControllerAnimated(false)
presentLoginViewController()
self.homeViewController = nil;
self.activityViewController = nil;
}
// MARK: - ()
// Set up appearance parameters to achieve Anypic's custom look and feel
func setupAppearance() {
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
UINavigationBar.appearance().tintColor = UIColor(red: 254.0/255.0, green: 149.0/255.0, blue: 50.0/255.0, alpha: 1.0)
UINavigationBar.appearance().barTintColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
UINavigationBar.appearance().titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.whiteColor() ]
UIButton.appearanceWhenContainedInInstancesOfClasses([UINavigationBar.self]).setTitleColor(UIColor(red: 254.0/255.0, green: 149.0/255.0, blue: 50.0/255.0, alpha: 1.0), forState: UIControlState.Normal)
UIBarButtonItem.appearance().setTitleTextAttributes([ NSForegroundColorAttributeName: UIColor(red: 254.0/255.0, green: 149.0/255.0, blue: 50.0/255.0, alpha: 1.0) ], forState: UIControlState.Normal)
UISearchBar.appearance().tintColor = UIColor(red: 254.0/255.0, green: 149.0/255.0, blue: 50.0/255.0, alpha: 1.0)
}
func monitorReachability() {
guard let reachability = Reachability(hostname: "api.parse.com") else {
return
}
reachability.whenReachable = { (reach: Reachability) in
self.networkStatus = reach.currentReachabilityStatus
if self.isParseReachable() && PFUser.currentUser() != nil && self.homeViewController!.objects!.count == 0 {
// Refresh home timeline on network restoration. Takes care of a freshly installed app that failed to load the main timeline under bad network conditions.
// In this case, they'd see the empty timeline placeholder and have no way of refreshing the timeline unless they followed someone.
self.homeViewController!.loadObjects()
}
}
reachability.whenUnreachable = { (reach: Reachability) in
self.networkStatus = reach.currentReachabilityStatus
}
reachability.startNotifier()
}
func handlePush(launchOptions: [NSObject: AnyObject]?) {
// If the app was launched in response to a push notification, we'll handle the payload here
guard let remoteNotificationPayload = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] else { return }
NSNotificationCenter.defaultCenter().postNotificationName(PAPAppDelegateApplicationDidReceiveRemoteNotification, object: nil, userInfo: remoteNotificationPayload)
if PFUser.currentUser() == nil {
return
}
// If the push notification payload references a photo, we will attempt to push this view controller into view
if let photoObjectId = remoteNotificationPayload[kPAPPushPayloadPhotoObjectIdKey] as? String where photoObjectId.characters.count > 0 {
shouldNavigateToPhoto(PFObject(outDataWithObjectId: photoObjectId))
return
}
// If the push notification payload references a user, we will attempt to push their profile into view
guard let fromObjectId = remoteNotificationPayload[kPAPPushPayloadFromUserObjectIdKey] as? String where fromObjectId.characters.count > 0 else { return }
let query: PFQuery? = PFUser.query()
query!.cachePolicy = PFCachePolicy.CacheElseNetwork
query!.getObjectInBackgroundWithId(fromObjectId, block: { (user, error) in
if error == nil {
let homeNavigationController = self.tabBarController!.viewControllers![PAPTabBarControllerViewControllerIndex.HomeTabBarItemIndex.rawValue] as? UINavigationController
self.tabBarController!.selectedViewController = homeNavigationController
let accountViewController = PAPAccountViewController(user: user as! PFUser)
print("Presenting account view controller with user: \(user!)")
homeNavigationController!.pushViewController(accountViewController, animated: true)
}
})
}
func autoFollowTimerFired(aTimer: NSTimer) {
MBProgressHUD.hideHUDForView(navController!.presentedViewController!.view, animated: true)
MBProgressHUD.hideHUDForView(homeViewController!.view, animated: true)
self.homeViewController!.loadObjects()
}
func shouldProceedToMainInterface(user: PFUser)-> Bool{
MBProgressHUD.hideHUDForView(navController!.presentedViewController!.view, animated: true)
self.presentTabBarController()
self.navController!.dismissViewControllerAnimated(true, completion: nil)
return true
}
func handleActionURL(url: NSURL) -> Bool {
if url.host == kPAPLaunchURLHostTakePicture {
if PFUser.currentUser() != nil {
return tabBarController!.shouldPresentPhotoCaptureController()
}
} else {
// FIXME: Is it working? if ([[url fragment] rangeOfString:@"^pic/[A-Za-z0-9]{10}$" options:NSRegularExpressionSearch].location != NSNotFound) {
if url.fragment!.rangeOfString("^pic/[A-Za-z0-9]{10}$" , options: [.RegularExpressionSearch]) != nil {
let photoObjectId: String = url.fragment!.subString(4, length: 10)
if photoObjectId.length > 0 {
print("WOOP: %@", photoObjectId)
shouldNavigateToPhoto(PFObject(outDataWithObjectId: photoObjectId))
return true
}
}
}
return false
}
func shouldNavigateToPhoto(var targetPhoto: PFObject) {
for photo: PFObject in homeViewController!.objects as! [PFObject] {
if photo.objectId == targetPhoto.objectId {
targetPhoto = photo
break
}
}
// if we have a local copy of this photo, this won't result in a network fetch
targetPhoto.fetchIfNeededInBackgroundWithBlock() { (object, error) in
if (error == nil) {
let homeNavigationController = self.tabBarController!.viewControllers![PAPTabBarControllerViewControllerIndex.HomeTabBarItemIndex.rawValue] as? UINavigationController
self.tabBarController!.selectedViewController = homeNavigationController
let detailViewController = PAPPhotoDetailsViewController(photo: object!)
homeNavigationController!.pushViewController(detailViewController, animated: true)
}
}
}
func autoFollowUsers() {
firstLaunch = true
PFCloud.callFunctionInBackground("autoFollowUsers", withParameters: nil, block: { (_, error) in
if error != nil {
print("Error auto following users: \(error)")
}
MBProgressHUD.hideHUDForView(self.navController!.presentedViewController!.view, animated:false)
self.homeViewController!.loadObjects()
})
}
}
|
41708f79b1a532ce5aeffe7ba1eec6ca
| 52.386667 | 346 | 0.706394 | false | false | false | false |
Moliholy/devslopes-smack-animation
|
refs/heads/master
|
Carthage/Checkouts/socket.io-client-swift/Source/SocketStringReader.swift
|
apache-2.0
|
8
|
//
// SocketStringReader.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 07.09.15.
//
// 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.
struct SocketStringReader {
let message: String
var currentIndex: String.UTF16View.Index
var hasNext: Bool {
return currentIndex != message.utf16.endIndex
}
var currentCharacter: String {
return String(UnicodeScalar(message.utf16[currentIndex])!)
}
init(message: String) {
self.message = message
currentIndex = message.utf16.startIndex
}
@discardableResult
mutating func advance(by: Int) -> String.UTF16View.Index {
currentIndex = message.utf16.index(currentIndex, offsetBy: by)
return currentIndex
}
mutating func read(count: Int) -> String {
let readString = String(message.utf16[currentIndex..<message.utf16.index(currentIndex, offsetBy: count)])!
advance(by: count)
return readString
}
mutating func readUntilOccurence(of string: String) -> String {
let substring = message.utf16[currentIndex..<message.utf16.endIndex]
guard let foundIndex = substring.index(of: string.utf16.first!) else {
currentIndex = message.utf16.endIndex
return String(substring)!
}
advance(by: substring.distance(from: substring.startIndex, to: foundIndex) + 1)
return String(substring[substring.startIndex..<foundIndex])!
}
mutating func readUntilEnd() -> String {
return read(count: message.utf16.distance(from: currentIndex, to: message.utf16.endIndex))
}
}
|
52230b3e00b75b60c2b605d061070c3f
| 35.424658 | 114 | 0.703272 | false | false | false | false |
WalterCreazyBear/Swifter30
|
refs/heads/master
|
Timer/Timer/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Timer
//
// Created by 熊伟 on 2017/6/24.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
enum TimerStatue {
case inited
case running
case stoped
}
class BGTimer :NSObject{
var counter: Double
var timer: Timer
override init() {
counter = 0.0
timer = Timer()
}
}
class ViewController: UIViewController {
var mainLabel:UILabel = UILabel()
var lapLabel:UILabel = UILabel()
var playPauseButton:UIButton!
var lapResetButton:UIButton!
var tableView:UITableView!
var mainTimer:BGTimer!
var lapTimer:BGTimer!
var timerStatue:TimerStatue = .inited
let cellIdentify :String = "cell"
var laps:Array<String> = Array.init()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.setupTimeLabel()
self.setupButtons()
self.setupTableView()
self.setupTimers()
}
func setupTimers() {
mainTimer = BGTimer.init()
mainTimer.timer = Timer.scheduledTimer(timeInterval: 0.035, target: self, selector: #selector(self.updateMainTimer), userInfo: nil, repeats: true)
lapTimer = BGTimer.init()
lapTimer.timer = Timer.scheduledTimer(timeInterval: 0.035, target: self, selector: #selector(self.updateLapTimer), userInfo: nil, repeats: true)
RunLoop.current.add(mainTimer.timer, forMode: .commonModes)
RunLoop.current.add(lapTimer.timer, forMode: .commonModes)
mainTimer.timer.fireDate = Date.distantFuture
lapTimer.timer.fireDate = Date.distantFuture
}
func resetTimer(_ timer: BGTimer, label: UILabel) {
timer.counter = 0.0
label.text = "00:00:00"
}
func updateMainTimer() {
ViewController.updateLabel(mainTimer, label: mainLabel)
}
func updateLapTimer() {
ViewController.updateLabel(lapTimer, label: lapLabel)
}
func setupTableView() {
tableView = UITableView.init(frame: CGRect.init(x: 0, y: 200, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-200))
tableView.backgroundColor = UIColor.white
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentify)
self.view.addSubview(tableView)
}
func setupButtons() {
playPauseButton = UIButton.init(frame: CGRect.init(x: 30, y: 150, width: 100, height: 50))
playPauseButton.setTitleColor(UIColor.black, for: .normal)
playPauseButton.setTitle("Start", for: .normal)
playPauseButton.layer.borderColor = UIColor.gray.cgColor
playPauseButton.layer.cornerRadius = 5
playPauseButton.layer.borderWidth = 1
playPauseButton.addTarget(self, action: #selector(self.handlePlayPauseButtonClicked(sender:)), for: .touchUpInside)
self.view.addSubview(playPauseButton)
lapResetButton = UIButton.init(frame: CGRect.init(x: UIScreen.main.bounds.width-130, y: 150, width: 100, height: 50))
lapResetButton.setTitleColor(UIColor.gray, for: .normal)
lapResetButton.setTitle("Lap", for: .normal)
lapResetButton.layer.borderColor = UIColor.gray.cgColor
lapResetButton.layer.cornerRadius = 5
lapResetButton.layer.borderWidth = 1
lapResetButton.isEnabled = false
lapResetButton.addTarget(self, action: #selector(self.handleLapResetButtonClicked(sender:)), for: .touchUpInside)
self.view.addSubview(lapResetButton)
}
func setupTimeLabel() {
mainLabel.frame = CGRect.init(x: 0, y: 80, width: UIScreen.main.bounds.width, height: 20)
mainLabel.textAlignment = .center
mainLabel.textColor = UIColor.black
mainLabel.text = "00:00:00"
mainLabel.font = UIFont.systemFont(ofSize: 18)
self.view.addSubview(mainLabel)
lapLabel.frame = CGRect.init(x: 0, y: 40, width: UIScreen.main.bounds.width, height: 16)
lapLabel.textAlignment = .center
lapLabel.textColor = UIColor.black
lapLabel.text = "00:00:00"
lapLabel.font = UIFont.systemFont(ofSize: 14)
self.view.addSubview(lapLabel)
}
func updateButtonStatue() {
switch timerStatue {
case .inited:
playPauseButton.setTitle("Start", for: .normal)
lapResetButton.setTitle("Lap", for: .normal)
lapResetButton.isEnabled = false
lapResetButton.setTitleColor(UIColor.gray, for: .normal)
case .running:
playPauseButton.setTitle("Stop", for: .normal)
lapResetButton.setTitle("Lap", for: .normal)
lapResetButton.isEnabled = true
lapResetButton.setTitleColor(UIColor.black, for: .normal)
case .stoped:
playPauseButton.setTitle("Start", for: .normal)
lapResetButton.setTitle("Reset", for: .normal)
lapResetButton.isEnabled = true
lapResetButton.setTitleColor(UIColor.black, for: .normal)
}
}
//MARK: - Button actions
@objc
func handlePlayPauseButtonClicked(sender:UIButton) {
if(timerStatue == .inited)
{
timerStatue = .running
self.updateButtonStatue()
mainTimer.timer.fireDate = Date.distantPast
lapTimer.timer.fireDate = Date.distantPast
}
else if(timerStatue == .running)
{
timerStatue = .stoped
self.updateButtonStatue()
mainTimer.timer.fireDate = Date.distantFuture
lapTimer.timer.fireDate = Date.distantFuture
}
else if(timerStatue == .stoped)
{
timerStatue = .running
self.updateButtonStatue()
mainTimer.timer.fireDate = Date.distantPast
lapTimer.timer.fireDate = Date.distantPast
}
}
@objc
func handleLapResetButtonClicked(sender:UIButton) {
if(timerStatue == .running)
{
laps.append(lapLabel.text ?? "")
self.resetTimer(lapTimer, label: lapLabel)
tableView.reloadData()
}
else if(timerStatue == .stoped)
{
timerStatue = .inited
self.updateButtonStatue()
laps.removeAll()
tableView.reloadData()
self.resetTimer(mainTimer, label: mainLabel)
self.resetTimer(lapTimer, label: lapLabel)
}
}
class func updateLabel(_ stopwatch:BGTimer, label:UILabel) {
stopwatch.counter = stopwatch.counter + 0.035
var minutes: String = "\((Int)(stopwatch.counter / 60))"
if (Int)(stopwatch.counter / 60) < 10 {
minutes = "0\((Int)(stopwatch.counter / 60))"
}
var seconds: String = String(format: "%.2f", (stopwatch.counter.truncatingRemainder(dividingBy: 60)))
if stopwatch.counter.truncatingRemainder(dividingBy: 60) < 10 {
seconds = "0" + seconds
}
label.text = minutes + ":" + seconds
}
}
extension ViewController:UITableViewDelegate,UITableViewDataSource
{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return laps.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentify, for: indexPath)
guard laps.count>indexPath.row else { return cell }
cell.textLabel?.text = laps[indexPath.row]
return cell
}
}
|
9542faa6c5840b7c8f2b0381d4eb2e86
| 30.61753 | 154 | 0.621094 | false | false | false | false |
IngmarStein/swift
|
refs/heads/master
|
validation-test/compiler_crashers_fixed/01401-swift-typebase-getdesugaredtype.swift
|
apache-2.0
|
11
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func a<T where T: NSObject {
return "foobar"""ab""".Element == f<T, V, let t: d = Int>) -> {
protocol b {
class func d.Type) -> {
enum S) -> Void>(")).a(A, (A.h: [T, let g = Swift.substringWithRange() {
let c: P {
}
}
protocol b {
typealias d: e?) {
}
func i> (self.startIndex, range: Int = F
var a(b: b = Swift.h : ("
typealias e
|
136f98ca72c71359e8cd8b243b5742cd
| 31.863636 | 78 | 0.672199 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
refs/heads/develop
|
Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/TextFormatScanner.swift
|
apache-2.0
|
3
|
// Sources/SwiftProtobuf/TextFormatScanner.swift - Text format decoding
//
// Copyright (c) 2014 - 2019 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Test format decoding engine.
///
// -----------------------------------------------------------------------------
import Foundation
private let asciiBell = UInt8(7)
private let asciiBackspace = UInt8(8)
private let asciiTab = UInt8(9)
private let asciiNewLine = UInt8(10)
private let asciiVerticalTab = UInt8(11)
private let asciiFormFeed = UInt8(12)
private let asciiCarriageReturn = UInt8(13)
private let asciiZero = UInt8(ascii: "0")
private let asciiOne = UInt8(ascii: "1")
private let asciiThree = UInt8(ascii: "3")
private let asciiSeven = UInt8(ascii: "7")
private let asciiNine = UInt8(ascii: "9")
private let asciiColon = UInt8(ascii: ":")
private let asciiPeriod = UInt8(ascii: ".")
private let asciiPlus = UInt8(ascii: "+")
private let asciiComma = UInt8(ascii: ",")
private let asciiSemicolon = UInt8(ascii: ";")
private let asciiDoubleQuote = UInt8(ascii: "\"")
private let asciiSingleQuote = UInt8(ascii: "\'")
private let asciiBackslash = UInt8(ascii: "\\")
private let asciiForwardSlash = UInt8(ascii: "/")
private let asciiHash = UInt8(ascii: "#")
private let asciiUnderscore = UInt8(ascii: "_")
private let asciiQuestionMark = UInt8(ascii: "?")
private let asciiSpace = UInt8(ascii: " ")
private let asciiOpenSquareBracket = UInt8(ascii: "[")
private let asciiCloseSquareBracket = UInt8(ascii: "]")
private let asciiOpenCurlyBracket = UInt8(ascii: "{")
private let asciiCloseCurlyBracket = UInt8(ascii: "}")
private let asciiOpenAngleBracket = UInt8(ascii: "<")
private let asciiCloseAngleBracket = UInt8(ascii: ">")
private let asciiMinus = UInt8(ascii: "-")
private let asciiLowerA = UInt8(ascii: "a")
private let asciiUpperA = UInt8(ascii: "A")
private let asciiLowerB = UInt8(ascii: "b")
private let asciiLowerE = UInt8(ascii: "e")
private let asciiUpperE = UInt8(ascii: "E")
private let asciiLowerF = UInt8(ascii: "f")
private let asciiUpperF = UInt8(ascii: "F")
private let asciiLowerI = UInt8(ascii: "i")
private let asciiLowerL = UInt8(ascii: "l")
private let asciiLowerN = UInt8(ascii: "n")
private let asciiLowerR = UInt8(ascii: "r")
private let asciiLowerS = UInt8(ascii: "s")
private let asciiLowerT = UInt8(ascii: "t")
private let asciiUpperT = UInt8(ascii: "T")
private let asciiLowerU = UInt8(ascii: "u")
private let asciiLowerV = UInt8(ascii: "v")
private let asciiLowerX = UInt8(ascii: "x")
private let asciiLowerY = UInt8(ascii: "y")
private let asciiLowerZ = UInt8(ascii: "z")
private let asciiUpperZ = UInt8(ascii: "Z")
private func fromHexDigit(_ c: UInt8) -> UInt8? {
if c >= asciiZero && c <= asciiNine {
return c - asciiZero
}
if c >= asciiUpperA && c <= asciiUpperF {
return c - asciiUpperA + UInt8(10)
}
if c >= asciiLowerA && c <= asciiLowerF {
return c - asciiLowerA + UInt8(10)
}
return nil
}
// Protobuf Text encoding assumes that you're working directly
// in UTF-8. So this implementation converts the string to UTF8,
// then decodes it into a sequence of bytes, then converts
// it back into a string.
private func decodeString(_ s: String) -> String? {
var out = [UInt8]()
var bytes = s.utf8.makeIterator()
while let byte = bytes.next() {
switch byte {
case asciiBackslash: // backslash
if let escaped = bytes.next() {
switch escaped {
case asciiZero...asciiSeven: // 0...7
// C standard allows 1, 2, or 3 octal digits.
let savedPosition = bytes
let digit1 = escaped
let digit1Value = digit1 - asciiZero
if let digit2 = bytes.next(),
digit2 >= asciiZero && digit2 <= asciiSeven {
let digit2Value = digit2 - asciiZero
let innerSavedPosition = bytes
if let digit3 = bytes.next(),
digit3 >= asciiZero && digit3 <= asciiSeven {
let digit3Value = digit3 - asciiZero
let n = digit1Value * 64 + digit2Value * 8 + digit3Value
out.append(n)
} else {
let n = digit1Value * 8 + digit2Value
out.append(n)
bytes = innerSavedPosition
}
} else {
let n = digit1Value
out.append(n)
bytes = savedPosition
}
case asciiLowerX: // "x"
// Unlike C/C++, protobuf only allows 1 or 2 digits here:
if let byte = bytes.next(), let digit = fromHexDigit(byte) {
var n = digit
let savedPosition = bytes
if let byte = bytes.next(), let digit = fromHexDigit(byte) {
n = n &* 16 + digit
} else {
// No second digit; reset the iterator
bytes = savedPosition
}
out.append(n)
} else {
return nil // Hex escape must have at least 1 digit
}
case asciiLowerA: // \a
out.append(asciiBell)
case asciiLowerB: // \b
out.append(asciiBackspace)
case asciiLowerF: // \f
out.append(asciiFormFeed)
case asciiLowerN: // \n
out.append(asciiNewLine)
case asciiLowerR: // \r
out.append(asciiCarriageReturn)
case asciiLowerT: // \t
out.append(asciiTab)
case asciiLowerV: // \v
out.append(asciiVerticalTab)
case asciiDoubleQuote,
asciiSingleQuote,
asciiQuestionMark,
asciiBackslash: // " ' ? \
out.append(escaped)
default:
return nil // Unrecognized escape
}
} else {
return nil // Input ends with backslash
}
default:
out.append(byte)
}
}
// There has got to be an easier way to convert a [UInt8] into a String.
return out.withUnsafeBufferPointer { ptr in
if let addr = ptr.baseAddress {
return utf8ToString(bytes: addr, count: ptr.count)
} else {
return String()
}
}
}
///
/// TextFormatScanner has no public members.
///
internal struct TextFormatScanner {
internal var extensions: ExtensionMap?
private var p: UnsafeRawPointer
private var end: UnsafeRawPointer
private var doubleParser = DoubleParser()
internal var complete: Bool {
mutating get {
return p == end
}
}
internal init(utf8Pointer: UnsafeRawPointer, count: Int, extensions: ExtensionMap? = nil) {
p = utf8Pointer
end = p + count
self.extensions = extensions
skipWhitespace()
}
/// Skip whitespace
private mutating func skipWhitespace() {
while p != end {
let u = p[0]
switch u {
case asciiSpace,
asciiTab,
asciiNewLine,
asciiCarriageReturn: // space, tab, NL, CR
p += 1
case asciiHash: // # comment
p += 1
while p != end {
// Skip until end of line
let c = p[0]
p += 1
if c == asciiNewLine || c == asciiCarriageReturn {
break
}
}
default:
return
}
}
}
/// Return a buffer containing the raw UTF8 for an identifier.
/// Assumes that you already know the current byte is a valid
/// start of identifier.
private mutating func parseUTF8Identifier() -> UnsafeRawBufferPointer {
let start = p
loop: while p != end {
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ,
asciiZero...asciiNine,
asciiUnderscore:
p += 1
default:
break loop
}
}
let s = UnsafeRawBufferPointer(start: start, count: p - start)
skipWhitespace()
return s
}
/// Return a String containing the next identifier.
private mutating func parseIdentifier() -> String {
let buff = parseUTF8Identifier()
let s = utf8ToString(bytes: buff.baseAddress!, count: buff.count)
// Force-unwrap is OK: we never have invalid UTF8 at this point.
return s!
}
/// Parse the rest of an [extension_field_name] in the input, assuming the
/// initial "[" character has already been read (and is in the prefix)
/// This is also used for AnyURL, so we include "/", "."
private mutating func parseExtensionKey() -> String? {
let start = p
if p == end {
return nil
}
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ:
p += 1
default:
return nil
}
while p != end {
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ,
asciiZero...asciiNine,
asciiUnderscore,
asciiPeriod,
asciiForwardSlash:
p += 1
case asciiCloseSquareBracket: // ]
return utf8ToString(bytes: start, count: p - start)
default:
return nil
}
}
return nil
}
/// Scan a string that encodes a byte field, return a count of
/// the number of bytes that should be decoded from it
private mutating func validateAndCountBytesFromString(terminator: UInt8, sawBackslash: inout Bool) throws -> Int {
var count = 0
let start = p
sawBackslash = false
while p != end {
let byte = p[0]
p += 1
if byte == terminator {
p = start
return count
}
switch byte {
case asciiBackslash: // "\\"
sawBackslash = true
if p != end {
let escaped = p[0]
p += 1
switch escaped {
case asciiZero...asciiSeven: // '0'...'7'
// C standard allows 1, 2, or 3 octal digits.
if p != end, p[0] >= asciiZero, p[0] <= asciiSeven {
p += 1
if p != end, p[0] >= asciiZero, p[0] <= asciiSeven {
if escaped > asciiThree {
// Out of range octal: three digits and first digit is greater than 3
throw TextFormatDecodingError.malformedText
}
p += 1
}
}
count += 1
case asciiLowerX: // 'x' hexadecimal escape
if p != end && fromHexDigit(p[0]) != nil {
p += 1
if p != end && fromHexDigit(p[0]) != nil {
p += 1
}
} else {
throw TextFormatDecodingError.malformedText // Hex escape must have at least 1 digit
}
count += 1
case asciiLowerA, // \a ("alert")
asciiLowerB, // \b
asciiLowerF, // \f
asciiLowerN, // \n
asciiLowerR, // \r
asciiLowerT, // \t
asciiLowerV, // \v
asciiSingleQuote, // \'
asciiDoubleQuote, // \"
asciiQuestionMark, // \?
asciiBackslash: // \\
count += 1
default:
throw TextFormatDecodingError.malformedText // Unrecognized escape
}
}
default:
count += 1
}
}
throw TextFormatDecodingError.malformedText
}
/// Protobuf Text format uses C ASCII conventions for
/// encoding byte sequences, including the use of octal
/// and hexadecimal escapes.
///
/// Assumes that validateAndCountBytesFromString() has already
/// verified the correctness. So we get to avoid error checks here.
private mutating func parseBytesFromString(terminator: UInt8, into data: inout Data) {
data.withUnsafeMutableBytes {
(body: UnsafeMutableRawBufferPointer) in
if var out = body.baseAddress, body.count > 0 {
while p[0] != terminator {
let byte = p[0]
p += 1
switch byte {
case asciiBackslash: // "\\"
let escaped = p[0]
p += 1
switch escaped {
case asciiZero...asciiSeven: // '0'...'7'
// C standard allows 1, 2, or 3 octal digits.
let digit1Value = escaped - asciiZero
let digit2 = p[0]
if digit2 >= asciiZero, digit2 <= asciiSeven {
p += 1
let digit2Value = digit2 - asciiZero
let digit3 = p[0]
if digit3 >= asciiZero, digit3 <= asciiSeven {
p += 1
let digit3Value = digit3 - asciiZero
out[0] = digit1Value &* 64 + digit2Value * 8 + digit3Value
out += 1
} else {
out[0] = digit1Value * 8 + digit2Value
out += 1
}
} else {
out[0] = digit1Value
out += 1
}
case asciiLowerX: // 'x' hexadecimal escape
// We already validated, so we know there's at least one digit:
var n = fromHexDigit(p[0])!
p += 1
if let digit = fromHexDigit(p[0]) {
n = n &* 16 &+ digit
p += 1
}
out[0] = n
out += 1
case asciiLowerA: // \a ("alert")
out[0] = asciiBell
out += 1
case asciiLowerB: // \b
out[0] = asciiBackspace
out += 1
case asciiLowerF: // \f
out[0] = asciiFormFeed
out += 1
case asciiLowerN: // \n
out[0] = asciiNewLine
out += 1
case asciiLowerR: // \r
out[0] = asciiCarriageReturn
out += 1
case asciiLowerT: // \t
out[0] = asciiTab
out += 1
case asciiLowerV: // \v
out[0] = asciiVerticalTab
out += 1
default:
out[0] = escaped
out += 1
}
default:
out[0] = byte
out += 1
}
}
p += 1 // Consume terminator
}
}
}
/// Assumes the leading quote has already been consumed
private mutating func parseStringSegment(terminator: UInt8) -> String? {
let start = p
var sawBackslash = false
while p != end {
let c = p[0]
if c == terminator {
let s = utf8ToString(bytes: start, count: p - start)
p += 1
skipWhitespace()
if let s = s, sawBackslash {
return decodeString(s)
} else {
return s
}
}
p += 1
if c == asciiBackslash { // \
if p == end {
return nil
}
sawBackslash = true
p += 1
}
}
return nil // Unterminated quoted string
}
internal mutating func nextUInt() throws -> UInt64 {
if p == end {
throw TextFormatDecodingError.malformedNumber
}
let c = p[0]
p += 1
if c == asciiZero { // leading '0' precedes octal or hex
if p[0] == asciiLowerX { // 'x' => hex
p += 1
var n: UInt64 = 0
while p != end {
let digit = p[0]
let val: UInt64
switch digit {
case asciiZero...asciiNine: // 0...9
val = UInt64(digit - asciiZero)
case asciiLowerA...asciiLowerF: // a...f
val = UInt64(digit - asciiLowerA + 10)
case asciiUpperA...asciiUpperF:
val = UInt64(digit - asciiUpperA + 10)
case asciiLowerU: // trailing 'u'
p += 1
skipWhitespace()
return n
default:
skipWhitespace()
return n
}
if n > UInt64.max / 16 {
throw TextFormatDecodingError.malformedNumber
}
p += 1
n = n * 16 + val
}
skipWhitespace()
return n
} else { // octal
var n: UInt64 = 0
while p != end {
let digit = p[0]
if digit == asciiLowerU { // trailing 'u'
p += 1
skipWhitespace()
return n
}
if digit < asciiZero || digit > asciiSeven {
skipWhitespace()
return n // not octal digit
}
let val = UInt64(digit - asciiZero)
if n > UInt64.max / 8 {
throw TextFormatDecodingError.malformedNumber
}
p += 1
n = n * 8 + val
}
skipWhitespace()
return n
}
} else if c > asciiZero && c <= asciiNine { // 1...9
var n = UInt64(c - asciiZero)
while p != end {
let digit = p[0]
if digit == asciiLowerU { // trailing 'u'
p += 1
skipWhitespace()
return n
}
if digit < asciiZero || digit > asciiNine {
skipWhitespace()
return n // not a digit
}
let val = UInt64(digit - asciiZero)
if n > UInt64.max / 10 || n * 10 > UInt64.max - val {
throw TextFormatDecodingError.malformedNumber
}
p += 1
n = n * 10 + val
}
skipWhitespace()
return n
}
throw TextFormatDecodingError.malformedNumber
}
internal mutating func nextSInt() throws -> Int64 {
if p == end {
throw TextFormatDecodingError.malformedNumber
}
let c = p[0]
if c == asciiMinus { // -
p += 1
// character after '-' must be digit
let digit = p[0]
if digit < asciiZero || digit > asciiNine {
throw TextFormatDecodingError.malformedNumber
}
let n = try nextUInt()
let limit: UInt64 = 0x8000000000000000 // -Int64.min
if n >= limit {
if n > limit {
// Too large negative number
throw TextFormatDecodingError.malformedNumber
} else {
return Int64.min // Special case for Int64.min
}
}
return -Int64(bitPattern: n)
} else {
let n = try nextUInt()
if n > UInt64(bitPattern: Int64.max) {
throw TextFormatDecodingError.malformedNumber
}
return Int64(bitPattern: n)
}
}
internal mutating func nextStringValue() throws -> String {
var result: String
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
throw TextFormatDecodingError.malformedText
}
p += 1
if let s = parseStringSegment(terminator: c) {
result = s
} else {
throw TextFormatDecodingError.malformedText
}
while true {
if p == end {
return result
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
return result
}
p += 1
if let s = parseStringSegment(terminator: c) {
result.append(s)
} else {
throw TextFormatDecodingError.malformedText
}
}
}
/// Protobuf Text Format allows a single bytes field to
/// contain multiple quoted strings. The values
/// are separately decoded and then concatenated:
/// field1: "bytes" 'more bytes'
/// "and even more bytes"
internal mutating func nextBytesValue() throws -> Data {
// Get the first string's contents
var result: Data
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
throw TextFormatDecodingError.malformedText
}
p += 1
var sawBackslash = false
let n = try validateAndCountBytesFromString(terminator: c, sawBackslash: &sawBackslash)
if sawBackslash {
result = Data(count: n)
parseBytesFromString(terminator: c, into: &result)
} else {
result = Data(bytes: p, count: n)
p += n + 1 // Skip string body + close quote
}
// If there are more strings, decode them
// and append to the result:
while true {
skipWhitespace()
if p == end {
return result
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
return result
}
p += 1
var sawBackslash = false
let n = try validateAndCountBytesFromString(terminator: c, sawBackslash: &sawBackslash)
if sawBackslash {
var b = Data(count: n)
parseBytesFromString(terminator: c, into: &b)
result.append(b)
} else {
result.append(Data(bytes: p, count: n))
p += n + 1 // Skip string body + close quote
}
}
}
// Tries to identify a sequence of UTF8 characters
// that represent a numeric floating-point value.
private mutating func tryParseFloatString() -> Double? {
guard p != end else {return nil}
let start = p
var c = p[0]
if c == asciiMinus {
p += 1
guard p != end else {p = start; return nil}
c = p[0]
}
switch c {
case asciiZero: // '0' as first character is not allowed followed by digit
p += 1
guard p != end else {break}
c = p[0]
if c >= asciiZero && c <= asciiNine {
p = start
return nil
}
case asciiPeriod: // '.' as first char only if followed by digit
p += 1
guard p != end else {p = start; return nil}
c = p[0]
if c < asciiZero || c > asciiNine {
p = start
return nil
}
case asciiOne...asciiNine:
break
default:
p = start
return nil
}
loop: while p != end {
let c = p[0]
switch c {
case asciiZero...asciiNine,
asciiPeriod,
asciiPlus,
asciiMinus,
asciiLowerE,
asciiUpperE: // 0...9, ., +, -, e, E
p += 1
case asciiLowerF: // f
// proto1 allowed floats to be suffixed with 'f'
let d = doubleParser.utf8ToDouble(bytes: UnsafeRawBufferPointer(start: start, count: p - start))
// Just skip the 'f'
p += 1
skipWhitespace()
return d
default:
break loop
}
}
let d = doubleParser.utf8ToDouble(bytes: UnsafeRawBufferPointer(start: start, count: p - start))
skipWhitespace()
return d
}
// Skip specified characters if they all match
private mutating func skipOptionalCharacters(bytes: [UInt8]) {
let start = p
for b in bytes {
if p == end || p[0] != b {
p = start
return
}
p += 1
}
}
// Skip following keyword if it matches (case-insensitively)
// the given keyword (specified as a series of bytes).
private mutating func skipOptionalKeyword(bytes: [UInt8]) -> Bool {
let start = p
for b in bytes {
if p == end {
p = start
return false
}
var c = p[0]
if c >= asciiUpperA && c <= asciiUpperZ {
// Convert to lower case
// (Protobuf text keywords are case insensitive)
c += asciiLowerA - asciiUpperA
}
if c != b {
p = start
return false
}
p += 1
}
if p == end {
return true
}
let c = p[0]
if ((c >= asciiUpperA && c <= asciiUpperZ)
|| (c >= asciiLowerA && c <= asciiLowerZ)) {
p = start
return false
}
skipWhitespace()
return true
}
// If the next token is the identifier "nan", return true.
private mutating func skipOptionalNaN() -> Bool {
return skipOptionalKeyword(bytes:
[asciiLowerN, asciiLowerA, asciiLowerN])
}
// If the next token is a recognized spelling of "infinity",
// return Float.infinity or -Float.infinity
private mutating func skipOptionalInfinity() -> Float? {
if p == end {
return nil
}
let c = p[0]
let negated: Bool
if c == asciiMinus {
negated = true
p += 1
} else {
negated = false
}
let inf = [asciiLowerI, asciiLowerN, asciiLowerF]
let infinity = [asciiLowerI, asciiLowerN, asciiLowerF, asciiLowerI,
asciiLowerN, asciiLowerI, asciiLowerT, asciiLowerY]
if (skipOptionalKeyword(bytes: inf)
|| skipOptionalKeyword(bytes: infinity)) {
return negated ? -Float.infinity : Float.infinity
}
return nil
}
internal mutating func nextFloat() throws -> Float {
if let d = tryParseFloatString() {
return Float(d)
}
if skipOptionalNaN() {
return Float.nan
}
if let inf = skipOptionalInfinity() {
return inf
}
throw TextFormatDecodingError.malformedNumber
}
internal mutating func nextDouble() throws -> Double {
if let d = tryParseFloatString() {
return d
}
if skipOptionalNaN() {
return Double.nan
}
if let inf = skipOptionalInfinity() {
return Double(inf)
}
throw TextFormatDecodingError.malformedNumber
}
internal mutating func nextBool() throws -> Bool {
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
p += 1
let result: Bool
switch c {
case asciiZero:
result = false
case asciiOne:
result = true
case asciiLowerF, asciiUpperF:
if p != end {
let alse = [asciiLowerA, asciiLowerL, asciiLowerS, asciiLowerE]
skipOptionalCharacters(bytes: alse)
}
result = false
case asciiLowerT, asciiUpperT:
if p != end {
let rue = [asciiLowerR, asciiLowerU, asciiLowerE]
skipOptionalCharacters(bytes: rue)
}
result = true
default:
throw TextFormatDecodingError.malformedText
}
if p == end {
return result
}
switch p[0] {
case asciiSpace,
asciiTab,
asciiNewLine,
asciiCarriageReturn,
asciiHash,
asciiComma,
asciiSemicolon,
asciiCloseSquareBracket,
asciiCloseCurlyBracket,
asciiCloseAngleBracket:
skipWhitespace()
return result
default:
throw TextFormatDecodingError.malformedText
}
}
internal mutating func nextOptionalEnumName() throws -> UnsafeRawBufferPointer? {
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
switch p[0] {
case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ:
return parseUTF8Identifier()
default:
return nil
}
}
/// Any URLs are syntactically (almost) identical to extension
/// keys, so we share the code for those.
internal mutating func nextOptionalAnyURL() throws -> String? {
return try nextOptionalExtensionKey()
}
/// Returns next extension key or nil if end-of-input or
/// if next token is not an extension key.
///
/// Throws an error if the next token starts with '[' but
/// cannot be parsed as an extension key.
///
/// Note: This accepts / characters to support Any URL parsing.
/// Technically, Any URLs can contain / characters and extension
/// key names cannot. But in practice, accepting / chracters for
/// extension keys works fine, since the result just gets rejected
/// when the key is looked up.
internal mutating func nextOptionalExtensionKey() throws -> String? {
skipWhitespace()
if p == end {
return nil
}
if p[0] == asciiOpenSquareBracket { // [
p += 1
if let s = parseExtensionKey() {
if p == end || p[0] != asciiCloseSquareBracket {
throw TextFormatDecodingError.malformedText
}
// Skip ]
p += 1
skipWhitespace()
return s
} else {
throw TextFormatDecodingError.malformedText
}
}
return nil
}
/// Returns text of next regular key or nil if end-of-input.
/// This considers an extension key [keyname] to be an
/// error, so call nextOptionalExtensionKey first if you
/// want to handle extension keys.
///
/// This is only used by map parsing; we should be able to
/// rework that to use nextFieldNumber instead.
internal mutating func nextKey() throws -> String? {
skipWhitespace()
if p == end {
return nil
}
let c = p[0]
switch c {
case asciiOpenSquareBracket: // [
throw TextFormatDecodingError.malformedText
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ,
asciiOne...asciiNine: // a...z, A...Z, 1...9
return parseIdentifier()
default:
throw TextFormatDecodingError.malformedText
}
}
/// Parse a field name, look it up, and return the corresponding
/// field number.
///
/// returns nil at end-of-input
///
/// Throws if field name cannot be parsed or if field name is
/// unknown.
///
/// This function accounts for as much as 2/3 of the total run
/// time of the entire parse.
internal mutating func nextFieldNumber(names: _NameMap) throws -> Int? {
if p == end {
return nil
}
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ: // a...z, A...Z
let key = parseUTF8Identifier()
if let fieldNumber = names.number(forProtoName: key) {
return fieldNumber
} else {
throw TextFormatDecodingError.unknownField
}
case asciiOne...asciiNine: // 1-9 (field numbers are 123, not 0123)
var fieldNum = Int(c) - Int(asciiZero)
p += 1
while p != end {
let c = p[0]
if c >= asciiZero && c <= asciiNine {
fieldNum = fieldNum &* 10 &+ (Int(c) - Int(asciiZero))
} else {
break
}
p += 1
}
skipWhitespace()
if names.names(for: fieldNum) != nil {
return fieldNum
} else {
// It was a number that isn't a known field.
// The C++ version (TextFormat::Parser::ParserImpl::ConsumeField()),
// supports an option to file or skip the field's value (this is true
// of unknown names or numbers).
throw TextFormatDecodingError.unknownField
}
default:
break
}
throw TextFormatDecodingError.malformedText
}
private mutating func skipRequiredCharacter(_ c: UInt8) throws {
skipWhitespace()
if p != end && p[0] == c {
p += 1
skipWhitespace()
} else {
throw TextFormatDecodingError.malformedText
}
}
internal mutating func skipRequiredComma() throws {
try skipRequiredCharacter(asciiComma)
}
internal mutating func skipRequiredColon() throws {
try skipRequiredCharacter(asciiColon)
}
private mutating func skipOptionalCharacter(_ c: UInt8) -> Bool {
if p != end && p[0] == c {
p += 1
skipWhitespace()
return true
}
return false
}
internal mutating func skipOptionalColon() -> Bool {
return skipOptionalCharacter(asciiColon)
}
internal mutating func skipOptionalEndArray() -> Bool {
return skipOptionalCharacter(asciiCloseSquareBracket)
}
internal mutating func skipOptionalBeginArray() -> Bool {
return skipOptionalCharacter(asciiOpenSquareBracket)
}
internal mutating func skipOptionalObjectEnd(_ c: UInt8) -> Bool {
return skipOptionalCharacter(c)
}
internal mutating func skipOptionalSeparator() {
if p != end {
let c = p[0]
if c == asciiComma || c == asciiSemicolon { // comma or semicolon
p += 1
skipWhitespace()
}
}
}
/// Returns the character that should end this field.
/// E.g., if object starts with "{", returns "}"
internal mutating func skipObjectStart() throws -> UInt8 {
if p != end {
let c = p[0]
p += 1
skipWhitespace()
switch c {
case asciiOpenCurlyBracket: // {
return asciiCloseCurlyBracket // }
case asciiOpenAngleBracket: // <
return asciiCloseAngleBracket // >
default:
break
}
}
throw TextFormatDecodingError.malformedText
}
}
|
370bc8ff9ed8e0d068c3ef95a6a0286d
| 32.507892 | 118 | 0.500804 | false | false | false | false |
halo/LinkLiar
|
refs/heads/master
|
LinkLiar/Classes/DefaultSubmenu.swift
|
mit
|
1
|
/*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Cocoa
class DefaultSubmenu {
func update() {
updateStates()
updateEnability()
updateAddress()
}
private func updateStates() {
ignoreItem.state = NSControl.StateValue(rawValue: Config.instance.unknownInterface.action == .ignore ? 1 : 0)
randomizeItem.state = NSControl.StateValue(rawValue: Config.instance.unknownInterface.action == .random ? 1 : 0)
specifyItem.state = NSControl.StateValue(rawValue: Config.instance.unknownInterface.action == .specify ? 1 : 0)
originalizeItem.state = NSControl.StateValue(rawValue: Config.instance.unknownInterface.action == .original ? 1 : 0)
}
private func updateEnability() {
self.enableAll(ConfigWriter.isWritable)
}
private func updateAddress() {
specifiedAddressItem.isHidden = Config.instance.unknownInterface.action != .specify
guard let address = Config.instance.unknownInterface.address else { return }
specifiedAddressItem.title = address.formatted
}
private func enableAll(_ enableOrDisable: Bool) {
ignoreItem.isEnabled = enableOrDisable
randomizeItem.isEnabled = enableOrDisable
specifyItem.isEnabled = enableOrDisable
originalizeItem.isEnabled = enableOrDisable
}
lazy var menuItem: NSMenuItem = {
let item = NSMenuItem(title: "Default", action: nil, keyEquivalent: "")
item.target = Controller.self
item.submenu = self.defaultSubMenuItem
item.toolTip = "Interfaces marked as \"Default\" have this value."
self.update()
return item
}()
private lazy var defaultSubMenuItem: NSMenu = {
let submenu: NSMenu = NSMenu()
submenu.autoenablesItems = false
submenu.addItem(self.ignoreItem)
submenu.addItem(self.randomizeItem)
submenu.addItem(self.specifyItem)
submenu.addItem(self.originalizeItem)
submenu.addItem(NSMenuItem.separator())
submenu.addItem(self.specifiedAddressItem)
return submenu
}()
private lazy var ignoreItem: NSMenuItem = {
let item = NSMenuItem(title: "Do nothing", action: #selector(Controller.ignoreDefaultInterface), keyEquivalent: "")
item.target = Controller.self
item.toolTip = "New Interfaces will not be modified in any way."
return item
}()
private lazy var randomizeItem: NSMenuItem = {
let item = NSMenuItem(title: "Random", action: #selector(Controller.randomizeDefaultInterface), keyEquivalent: "")
item.target = Controller.self
item.toolTip = "Randomize the MAC address of new Interfaces."
return item
}()
private lazy var specifyItem: NSMenuItem = {
let item = NSMenuItem(title: "Define manually", action: #selector(Controller.specifyDefaultInterface), keyEquivalent: "")
item.target = Controller.self
item.toolTip = "Assign a specific MAC address to new Interfaces."
return item
}()
private lazy var originalizeItem: NSMenuItem = {
let item = NSMenuItem(title: "Keep original", action: #selector(Controller.originalizeDefaultInterface), keyEquivalent: "")
item.target = Controller.self
item.toolTip = "Ensure new Interfaces are kept at their original hardware MAC address."
return item
}()
private lazy var specifiedAddressItem: NSMenuItem = {
let item = NSMenuItem(title: "Loading...", action: nil, keyEquivalent: "")
item.isEnabled = false
item.isHidden = true
item.toolTip = "The specific MAC address assigned to new Interfaces."
return item
}()
}
|
d0d4910ad6b577fa056c5c97c93a4d5e
| 41.364486 | 133 | 0.736819 | false | true | false | false |
gskbyte/rubberband
|
refs/heads/master
|
rubberband/ViewController.swift
|
apache-2.0
|
1
|
import UIKit
enum SecondaryPosition {
case Unconfigured
case Bottom
case Top
}
class ViewController: UIViewController, UIScrollViewDelegate {
let offsetToSwitch : CGFloat = 120
let scrollHeights : Array<CGFloat> = [800, 1000, 1000, 2000, 700, 1000];
var currentScrollViewIndex : Int = 0
var primaryScroll : UIScrollView!
var secondaryScroll : UIScrollView!
var lastScrollY : CGFloat = 0
var secondaryPosition : SecondaryPosition = .Unconfigured
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.yellowColor()
self.primaryScroll = UIScrollView()
self.primaryScroll.frame.size = self.view.frame.size
self.view.addSubview(self.primaryScroll)
self.secondaryScroll = UIScrollView()
self.secondaryScroll.frame.size = self.view.frame.size
self.view.addSubview(self.secondaryScroll)
self.view.bringSubviewToFront(self.primaryScroll)
self.setupScrollView(self.primaryScroll, index: self.currentScrollViewIndex)
self.primaryScroll.delegate = self
}
func setupScrollView(scrollView: UIScrollView, index: Int) {
scrollView.contentOffset = CGPointZero
scrollView.contentSize = CGSizeMake(self.view.frame.width, self.scrollHeights[index])
if index%2 == 0 {
scrollView.backgroundColor = UIColor.orangeColor()
} else {
scrollView.backgroundColor = UIColor.redColor()
}
}
func setupSecondaryScrollWithIndex(index: Int, position: SecondaryPosition) {
self.setupScrollView(self.secondaryScroll, index: index)
var frame = self.secondaryScroll.frame
if position == .Top {
frame.origin.y = self.view.frame.size.height
} else if position == .Bottom {
frame.origin.y = -self.view.frame.size.height
}
self.secondaryScroll.frame = frame
self.secondaryPosition = position
self.view.bringSubviewToFront(self.secondaryScroll)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let remainingBottom = scrollView.contentSize.height - scrollView.frame.height - scrollView.contentOffset.y
// configure secondary scrollView if reaching end
if offsetY < self.lastScrollY && offsetY < 3 && self.currentScrollViewIndex > 0 && self.secondaryPosition != .Top {
self.setupSecondaryScrollWithIndex(self.currentScrollViewIndex - 1, position: .Top)
} else if offsetY > self.lastScrollY && remainingBottom < 3 && self.currentScrollViewIndex < self.scrollHeights.count - 1 && self.secondaryPosition != .Bottom {
self.setupSecondaryScrollWithIndex(self.currentScrollViewIndex + 1, position: .Bottom)
}
// check if we need to move secondary scrollview, or switch to it
// could be cleaner and merged with the code above
if offsetY < 0 && self.currentScrollViewIndex > 0 {
if offsetY < -offsetToSwitch {
self.switchToSecondaryView()
} else {
self.secondaryScroll.frame.origin.y = -self.view.frame.height - offsetY
}
} else if remainingBottom < 0 && self.currentScrollViewIndex < self.scrollHeights.count - 1 {
if remainingBottom < -offsetToSwitch {
self.switchToSecondaryView()
} else {
self.secondaryScroll.frame.origin.y = self.view.frame.height + remainingBottom
}
}
self.lastScrollY = scrollView.contentOffset.y
}
func switchToSecondaryView() {
self.primaryScroll.userInteractionEnabled = false
self.secondaryScroll.userInteractionEnabled = false
self.primaryScroll.delegate = nil
var primaryFrame = self.primaryScroll.frame
if self.secondaryPosition == .Top {
primaryFrame.origin.y = self.view.frame.size.height
self.secondaryPosition = .Bottom
self.currentScrollViewIndex -= 1
} else if self.secondaryPosition == .Bottom {
primaryFrame.origin.y = -self.view.frame.size.height
self.secondaryPosition = .Top
self.currentScrollViewIndex += 1
}
UIView.animateWithDuration(0.3,
animations: { () -> Void in
self.primaryScroll.frame = primaryFrame
self.secondaryScroll.frame.origin.y = 0
})
{ (finished : Bool) -> Void in
swap(&self.primaryScroll, &self.secondaryScroll)
self.view.bringSubviewToFront(self.secondaryScroll)
self.primaryScroll.delegate = self
self.primaryScroll.userInteractionEnabled = true
self.secondaryScroll.userInteractionEnabled = true
}
}
}
|
b941233aead4daf3f75c93e91f60233b
| 38.739837 | 168 | 0.651391 | false | false | false | false |
Sillyplus/swifter
|
refs/heads/master
|
Sources/Swifter/HttpRouter.swift
|
bsd-3-clause
|
3
|
//
// HttpRouter.swift
// Swifter
// Copyright (c) 2015 Damian Kołakowski. All rights reserved.
//
import Foundation
public class HttpRouter {
private var handlers: [(pattern: [String], handler: HttpServer.Handler)] = []
public func routes() -> [String] {
return handlers.map { $0.pattern.joinWithSeparator("/") }
}
public func register(path: String, handler: HttpServer.Handler) {
handlers.append((path.split("/"), handler))
handlers.sortInPlace { $0.0.pattern.count < $0.1.pattern.count }
}
public func unregister(path: String) {
let p = path.split("/")
handlers = handlers.filter { (pattern, handler) -> Bool in
return pattern != p
}
}
public func select(url: String) -> ([String: String], HttpServer.Handler)? {
let urlTokens = url.split("/")
for (pattern, handler) in handlers {
if let params = matchParams(pattern, valueTokens: urlTokens) {
return (params, handler)
}
}
return nil
}
public func matchParams(patternTokens: [String], valueTokens: [String]) -> [String: String]? {
var params = [String: String]()
for index in 0..<valueTokens.count {
if index >= patternTokens.count {
return nil
}
let patternToken = patternTokens[index]
let valueToken = valueTokens[index]
if patternToken.isEmpty {
if patternToken != valueToken {
return nil
}
}
if patternToken.characters.first == ":" {
#if os(Linux)
params[patternToken.substringFromIndex(1)] = valueToken
#else
params[patternToken.substringFromIndex(patternToken.characters.startIndex.successor())] = valueToken
#endif
} else {
if patternToken != valueToken {
return nil
}
}
}
return params
}
}
|
87a3e87fa74cd87f04ed561720cffc23
| 30.121212 | 116 | 0.549172 | false | false | false | false |
cfilipov/MuscleBook
|
refs/heads/master
|
MuscleBook/PunchcardCell.swift
|
gpl-3.0
|
1
|
/*
Muscle Book
Copyright (C) 2016 Cristian Filipov
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 Eureka
@objc class PunchcardDelegate: NSObject, EFCalendarGraphDataSource {
func numberOfDataPointsInCalendarGraph(calendarGraph: EFCalendarGraph!) -> UInt {
return 364
}
func calendarGraph(calendarGraph: EFCalendarGraph!, valueForDate date: NSDate!, daysAfterStartDate: UInt, daysBeforeEndDate: UInt) -> AnyObject! {
return 0
}
}
class PunchcardCell : Cell<PunchcardDelegate>, CellType {
let punchcardView: EFCalendarGraph = {
let v = EFCalendarGraph(endDate: NSDate())
v.baseColor = UIColor.redColor()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
height = { 60 }
}
override func setup() {
super.setup()
row.title = nil
selectionStyle = .None
contentView.addSubview(punchcardView)
let views : [String: AnyObject] = ["punchcardView": punchcardView]
contentView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[punchcardView]|",
options: [],
metrics: nil,
views: views
)
)
contentView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-15-[punchcardView]-15-|",
options: [],
metrics: nil,
views: views
)
)
punchcardView.dataSource = row.value
punchcardView.reloadData()
}
override func update() {
row.title = nil
super.update()
}
}
final class PunchcardRow: Row<PunchcardDelegate, PunchcardCell>, RowType {
required init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
}
|
637222ce28d9fe61f24912cf70897dd3
| 29.604651 | 150 | 0.642341 | false | false | false | false |
seanwoodward/IBAnimatable
|
refs/heads/master
|
IBAnimatable/ActivityIndicatorAnimationPacman.swift
|
mit
|
1
|
//
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationPacman: ActivityIndicatorAnimating {
// MARK: Properties
private let duration: CFTimeInterval = 0.5
private let circleDuration: CFTimeInterval = 1
private var size: CGSize = .zero
private let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
// MARK: ActivityIndicatorAnimating
public func configAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
self.size = size
circleInLayer(layer, color: color)
pacmanInLayer(layer, color: color)
}
}
// MARK: - Pacman
private extension ActivityIndicatorAnimationPacman {
func pacmanInLayer(layer: CALayer, color: UIColor) {
let pacmanSize = 2 * size.width / 3
let pacman = ActivityIndicatorShape.Pacman.createLayerWith(size: CGSize(width: pacmanSize, height: pacmanSize), color: color)
let animation = pacmanAnimation
let frame = CGRect(
x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2 + size.height / 2 - pacmanSize / 2,
width: pacmanSize,
height: pacmanSize
)
pacman.frame = frame
pacman.addAnimation(animation, forKey: "animation")
layer.addSublayer(pacman)
}
var pacmanAnimation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [strokeStartAnimation, strokeEndAnimation]
animation.duration = duration
animation.repeatCount = .infinity
animation.removedOnCompletion = false
return animation
}
var strokeStartAnimation: CAKeyframeAnimation {
let strokeStartAnimation = CAKeyframeAnimation(keyPath: "strokeStart")
strokeStartAnimation.keyTimes = [0, 0.5, 1]
strokeStartAnimation.timingFunctions = [timingFunction, timingFunction]
strokeStartAnimation.values = [0.125, 0, 0.125]
strokeStartAnimation.duration = duration
return strokeStartAnimation
}
var strokeEndAnimation: CAKeyframeAnimation {
let strokeEndAnimation = CAKeyframeAnimation(keyPath: "strokeEnd")
strokeEndAnimation.keyTimes = [0, 0.5, 1]
strokeEndAnimation.timingFunctions = [timingFunction, timingFunction]
strokeEndAnimation.values = [0.875, 1, 0.875]
strokeEndAnimation.duration = duration
return strokeEndAnimation
}
}
// MARK: - Circle
private extension ActivityIndicatorAnimationPacman {
func circleInLayer(layer: CALayer, color: UIColor) {
let circleSize = size.width / 5
let circle = ActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let animation = circleAnimation
let frame = CGRect(
x: (layer.bounds.size.width - size.width) / 2 + size.width - circleSize,
y: (layer.bounds.size.height - size.height) / 2 + size.height / 2 - circleSize
/ 2,
width: circleSize,
height: circleSize
)
circle.frame = frame
circle.addAnimation(animation, forKey: "animation")
layer.addSublayer(circle)
}
var circleAnimation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [translateAnimation, opacityAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = circleDuration
animation.repeatCount = .infinity
animation.removedOnCompletion = false
return animation
}
var translateAnimation: CABasicAnimation {
let translateAnimation = CABasicAnimation(keyPath: "transform.translation.x")
translateAnimation.fromValue = 0
translateAnimation.toValue = -size.width / 2
translateAnimation.duration = circleDuration
return translateAnimation
}
var opacityAnimation: CABasicAnimation {
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 1
opacityAnimation.toValue = 0.7
opacityAnimation.duration = circleDuration
return opacityAnimation
}
}
|
b2f6900fdcc9a2358e6b6ab06d242140
| 31.991803 | 129 | 0.734907 | false | false | false | false |
SwiftFMI/iOS_2017_2018
|
refs/heads/master
|
Lectures/code/17.11.2017/UICollectionView/UICollectionView/PBJHexagonFlowLayout.swift
|
apache-2.0
|
1
|
//
// PBJHexagonFlowLayout.swift
// UICollectionView
//
// Port of https://github.com/piemonte/PBJHexagon/blob/master/Source/PBJHexagonFlowLayout.m
//
// Created by Emil Atanasov on 17.11.17.
// Copyright © 2017 SwiftFMI. All rights reserved.
//
import UIKit
public class PBJHexagonFlowLayout: UICollectionViewFlowLayout {
var itemsPerRow = 4
public init(itemsPerRow:Int) {
super.init()
self.itemsPerRow = itemsPerRow
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func prepare() {
super.prepare()
if itemsPerRow <= 0 {
itemsPerRow = 4
}
}
public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes:[UICollectionViewLayoutAttributes]? = []
let numberOfItems = (self.collectionView?.numberOfItems(inSection: 0))! - 1
for i in 0...numberOfItems {
let indexPath = IndexPath(item: i, section: 0 )
layoutAttributes?.append(self.layoutAttributesForItem(at: indexPath)!)
}
return layoutAttributes
}
public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let row = Int(floor(Double(indexPath.row) / Double(itemsPerRow) ))
let col = indexPath.row % itemsPerRow
let horiOffset = ((row % 2) != 0) ? 0 : self.itemSize.width * 0.5
let vertOffset = 0
let attributes = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
attributes.size = self.itemSize
let centerX = (Double(col) * Double(self.itemSize.width)) + (0.5 * Double(self.itemSize.width)) + Double(horiOffset)
let centerY = Double(row) * 0.75 * Double(self.itemSize.height) + 0.5 * Double(self.itemSize.height) + Double(vertOffset)
attributes.center = CGPoint( x: centerX, y: centerY)
return attributes;
}
public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return false
}
public override var collectionViewContentSize: CGSize {
let numberOfItems = (self.collectionView?.numberOfItems(inSection: 0))!
let contentWidth = Double(self.collectionView?.bounds.size.width ?? 0)
let contentHeight = ( (Double(numberOfItems) / Double(itemsPerRow) * 0.75) * Double(self.itemSize.height)) + (0.5 + Double(self.itemSize.height))
let contentSize = CGSize(width:contentWidth, height: contentHeight)
return contentSize
}
}
|
d6a6e7a8794b93f09c4b0d53d2dc14bd
| 33.871795 | 153 | 0.643015 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.