repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
banxi1988/Staff
|
Pods/BXModel/Pod/Classes/StaticTableViewAdapter.swift
|
1
|
2572
|
//
// StaticTableViewAdapter.swift
// Pods
//
// Created by Haizhen Lee on 15/12/1.
//
//
import Foundation
public protocol StaticTableViewCellAware{
var bx_height:CGFloat{ get }
var bx_shouldHighlight:Bool{ get }
}
extension UITableViewCell:StaticTableViewCellAware{
public var bx_height:CGFloat{ return 44 }
public var bx_shouldHighlight:Bool{ return true }
}
public class StaticTableViewAdapter:StaticTableViewDataSource,UITableViewDelegate{
public var referenceSectionHeaderHeight:CGFloat = 15
public var referenceSectionFooterHeight:CGFloat = 15
public var sectionHeaderView:UIView?
public var sectionFooterView:UIView?
public private(set) weak var tableView:UITableView?
public var sectionHeaderHeight:CGFloat{
return sectionHeaderView == nil ? 0:referenceSectionHeaderHeight
}
public var sectionFooterHeight:CGFloat{
return sectionFooterView == nil ? 0:referenceSectionFooterHeight
}
public var didSelectCell:((UITableViewCell,NSIndexPath) -> Void)?
public override init(cells: [UITableViewCell] = []) {
super.init(cells: cells)
}
public func bindTo(tableView:UITableView){
self.tableView = tableView
tableView.dataSource = self
tableView.delegate = self
}
// MARK:UITableViewDelegate
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
return cellAtIndexPath(indexPath).bx_height
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = cellAtIndexPath(indexPath)
self.didSelectCell?(cell,indexPath)
cell.setSelected(false, animated: true)
}
public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
return sectionHeaderHeight
}
public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
return sectionFooterHeight
}
public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{ // custom view for header. will be adjusted to default or specified header height
return sectionHeaderView
}
public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{ // custom view for footer. will be adjusted to default or specified footer height
return sectionFooterView
}
public func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let cell = cellAtIndexPath(indexPath)
return cell.bx_shouldHighlight
}
}
|
mit
|
1996782c4a5286e5a9d74f6da02558a9
| 31.1625 | 178 | 0.762442 | 5.144 | false | false | false | false |
BelledonneCommunications/linphone-iphone
|
Classes/Swift/Voip/Views/Fragments/Conference/VoipAudioOnlyParticipantCell.swift
|
1
|
4452
|
/*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import Foundation
import SnapKit
import linphonesw
class VoipAudioOnlyParticipantCell: UICollectionViewCell {
// Layout Constants
static let cell_height = 80.0
static let avatar_size = 40.0
static let mute_size = 30
let corner_radius = 6.7
let common_margin = 10.0
let avatar = Avatar(color:VoipTheme.voipBackgroundColor, textStyle: VoipTheme.call_generated_avatar_small)
let paused = UIImageView(image: UIImage(named: "voip_pause")?.tinted(with: .white))
let muted = MicMuted(VoipAudioOnlyParticipantCell.mute_size)
let joining = RotatingSpinner()
let displayName = StyledLabel(VoipTheme.conference_participant_name_font_as)
var participantData: ConferenceParticipantDeviceData? = nil {
didSet {
if let data = participantData {
self.updateElements()
data.isJoining.clearObservers()
data.isJoining.observe { _ in
self.updateElements()
}
data.isInConference.clearObservers()
data.isInConference.observe { _ in
self.updateElements()
}
data.participantDevice.address.map {
avatar.fillFromAddress(address: $0)
if let displayName = $0.addressBookEnhancedDisplayName() {
self.displayName.text = displayName
}
}
data.isSpeaking.clearObservers()
data.isSpeaking.observe { _ in
self.updateElements(skipVideo: true)
}
data.micMuted.clearObservers()
data.micMuted.observe { _ in
self.updateElements(skipVideo: true)
}
}
}
}
func updateElements(skipVideo:Bool = false) {
if let data = participantData {
// background
contentView.backgroundColor = data.isMe ? VoipTheme.voipParticipantMeBackgroundColor.get() : VoipTheme.voipParticipantBackgroundColor.get()
// Avatar
self.avatar.isHidden = data.isInConference.value != true && data.isJoining.value != true
// Pause
self.paused.isHidden = data.isInConference.value == true || data.isJoining.value == true
// Border for active speaker
self.layer.borderWidth = data.isSpeaking.value == true ? 2 : 0
// Joining indicator
if (data.isJoining.value == true) {
self.joining.isHidden = false
self.joining.startRotation()
} else {
self.joining.isHidden = true
self.joining.stopRotation()
}
// Muted
self.muted.isHidden = data.micMuted.value != true
}
}
override init(frame:CGRect) {
super.init(frame:.zero)
contentView.height(VoipAudioOnlyParticipantCell.cell_height).matchParentSideBorders().done()
layer.cornerRadius = corner_radius
clipsToBounds = true
layer.borderColor = VoipTheme.primary_color.cgColor
contentView.addSubview(avatar)
avatar.size(w: VoipCallCell.avatar_size, h: VoipCallCell.avatar_size).centerY().alignParentLeft(withMargin: common_margin).done()
contentView.addSubview(paused)
paused.layer.cornerRadius = VoipAudioOnlyParticipantCell.avatar_size/2
paused.clipsToBounds = true
paused.backgroundColor = VoipTheme.voip_gray
paused.size(w: VoipAudioOnlyParticipantCell.avatar_size, h: VoipAudioOnlyParticipantCell.avatar_size).alignParentLeft(withMargin: common_margin).centerY().done()
contentView.addSubview(displayName)
displayName.centerY().toRightOf(avatar,withLeftMargin: common_margin).done()
displayName.numberOfLines = 3
contentView.addSubview(muted)
muted.alignParentRight(withMargin: common_margin).toRightOf(displayName,withLeftMargin: common_margin).centerY().done()
contentView.addSubview(joining)
joining.alignParentRight(withMargin: common_margin).toRightOf(displayName,withLeftMargin: common_margin).centerY().done()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
ff1f6ab6c4b2d20c732d05b122e2de52
| 31.26087 | 163 | 0.734501 | 3.747475 | false | false | false | false |
ask-fm/AFMActionSheet
|
Pod/Classes/AFMActionSheetController.swift
|
1
|
17802
|
//
// ActionSheetViewController.swift
// askfm
//
// Created by Ilya Alesker on 26/08/15.
// Copyright (c) 2015 Ask.fm Europe, Ltd. All rights reserved.
//
import UIKit
@IBDesignable
open class AFMActionSheetController: UIViewController {
public enum ControllerStyle : Int {
case actionSheet
case alert
}
@IBInspectable open var outsideGestureShouldDismiss: Bool = true
@IBInspectable open var minControlHeight: Int = 50 {
didSet { self.updateUI() }
}
@IBInspectable open var minTitleHeight: Int = 50 {
didSet { self.updateUI() }
}
@IBInspectable open var spacing: Int = 4 {
didSet { self.updateUI() }
}
@IBInspectable open var horizontalMargin: Int = 16 {
didSet { self.updateUI() }
}
@IBInspectable open var verticalMargin: Int = 16 {
didSet { self.updateUI() }
}
@IBInspectable open var cornerRadius: Int = 10 {
didSet { self.updateUI() }
}
@IBInspectable open var backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.5) {
didSet { self.updateUI() }
}
@IBInspectable open var spacingColor: UIColor = UIColor.clear {
didSet { self.updateUI() }
}
private var topMargin: Int {
let statusBarHeight = Int(UIApplication.shared.statusBarFrame.height)
return statusBarHeight > self.verticalMargin ? statusBarHeight : self.verticalMargin
}
open var dismissCompletionBlock: (() -> ())?
let controllerStyle: ControllerStyle
public private(set) var actions: [AFMAction] = []
public private(set) var actionControls: [UIControl] = []
public private(set) var cancelControls: [UIControl] = []
public private(set) var titleView: UIView?
private var actionControlConstraints: [NSLayoutConstraint] = []
private var cancelControlConstraints: [NSLayoutConstraint] = []
private var actionSheetTransitioningDelegate: UIViewControllerTransitioningDelegate?
var actionGroupView: UIView = UIView()
var cancelGroupView: UIView = UIView()
// MARK: Initializers
public init(style: ControllerStyle, transitioningDelegate: UIViewControllerTransitioningDelegate) {
self.controllerStyle = style
super.init(nibName: nil, bundle: nil)
self.setupViews()
self.setup(transitioningDelegate)
}
public convenience init(style: ControllerStyle) {
self.init(style: style, transitioningDelegate: AFMActionSheetTransitioningDelegate())
}
public convenience init(transitioningDelegate: UIViewControllerTransitioningDelegate) {
self.init(style: .actionSheet, transitioningDelegate: transitioningDelegate)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self.controllerStyle = .actionSheet
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.setupViews()
self.setup(AFMActionSheetTransitioningDelegate())
}
required public init?(coder aDecoder: NSCoder) {
self.controllerStyle = .actionSheet
super.init(coder: aDecoder)
self.setupViews()
self.setup(AFMActionSheetTransitioningDelegate())
}
private func setupViews() {
self.setupGroupViews()
self.setupGestureRecognizers()
self.view.backgroundColor = self.backgroundColor
}
private func setupGestureRecognizers() {
if let gestureRecognizers = self.view.gestureRecognizers {
for gestureRecognizer in gestureRecognizers {
self.view.removeGestureRecognizer(gestureRecognizer)
}
}
let swipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(AFMActionSheetController.recognizeGestures(_:)))
swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.down
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AFMActionSheetController.recognizeGestures(_:)))
tapGestureRecognizer.cancelsTouchesInView = false
self.view.addGestureRecognizer(swipeGestureRecognizer)
self.view.addGestureRecognizer(tapGestureRecognizer)
}
open func setup(_ transitioningDelegate: UIViewControllerTransitioningDelegate) {
self.modalPresentationStyle = .custom
self.actionSheetTransitioningDelegate = transitioningDelegate
self.transitioningDelegate = self.actionSheetTransitioningDelegate
}
// MARK: Adding actions
private func setup(_ control: UIControl, with action: AFMAction) {
control.isEnabled = action.enabled
control.addTarget(self, action:#selector(AFMActionSheetController.handleTaps(_:)), for: .touchUpInside)
control.tag = self.actions.count
}
@objc
open func add(_ action: AFMAction, with control: UIControl, andActionIsCancelling isCancellingAction: Bool) {
self.setup(control, with: action)
self.actions.append(action)
if isCancellingAction {
self.cancelControls.append(control)
} else {
self.actionControls.append(control)
}
self.addToGroupView(control, andActionIsCancelling: isCancellingAction)
}
@objc
open func insert(_ action: AFMAction, with control: UIControl, at position: Int, andActionIsCancelling isCancellingAction: Bool) {
if isCancellingAction {
guard position <= self.cancelControls.count else { return }
} else {
guard position <= self.actionControls.count else { return }
}
self.setup(control, with: action)
self.actions.append(action)
if isCancellingAction {
self.cancelControls.insert(control, at: position)
} else {
self.actionControls.insert(control, at: position)
}
self.addToGroupView(control, andActionIsCancelling: isCancellingAction)
}
@objc
open func add(title: UIView) {
self.titleView = title
self.titleView!.translatesAutoresizingMaskIntoConstraints = false
self.actionGroupView.addSubview(self.titleView!)
self.updateContraints()
}
private func addToGroupView(_ control: UIControl, andActionIsCancelling isCancellingAction: Bool) {
if self.controllerStyle == .actionSheet {
self.addToGroupViewForActionSheet(control, andActionIsCancelling: isCancellingAction)
} else if self.controllerStyle == .alert {
self.addToGroupViewForAlert(control, andActionIsCancelling: isCancellingAction)
}
}
private func addToGroupViewForActionSheet(_ control: UIControl, andActionIsCancelling isCancellingAction: Bool) {
control.translatesAutoresizingMaskIntoConstraints = false
if isCancellingAction {
self.cancelGroupView.addSubview(control)
} else {
self.actionGroupView.addSubview(control)
}
self.updateContraints()
}
private func addToGroupViewForAlert(_ control: UIControl, andActionIsCancelling isCancellingAction: Bool) {
control.translatesAutoresizingMaskIntoConstraints = false
self.actionGroupView.addSubview(control)
self.updateContraints()
}
private func actionControlsWithTitle() -> [UIView] {
var views: [UIView] = self.actionControls
if let titleView = self.titleView {
views.insert(titleView, at: 0)
}
return views
}
// MARK: Control positioning and updating
func updateContraints() {
if self.controllerStyle == .actionSheet {
self.updateContraintsForActionSheet()
} else if self.controllerStyle == .alert {
self.updateContraintsForAlert()
}
}
func updateContraintsForActionSheet() {
self.cancelGroupView.removeConstraints(self.cancelControlConstraints)
self.cancelControlConstraints = self.constraints(for: self.cancelControls)
self.cancelGroupView.addConstraints(self.cancelControlConstraints)
self.actionGroupView.removeConstraints(self.actionControlConstraints)
self.actionControlConstraints = self.constraints(for: self.actionControlsWithTitle())
self.actionGroupView.addConstraints(self.actionControlConstraints)
}
func updateContraintsForAlert() {
var views: [UIView] = self.actionControlsWithTitle()
let cancelViews: [UIView] = self.cancelControls
views.append(contentsOf: cancelViews)
self.actionGroupView.removeConstraints(self.actionControlConstraints)
self.actionControlConstraints = self.constraints(for: views)
self.actionGroupView.addConstraints(self.actionControlConstraints)
}
private func setupGroupViews() {
if self.controllerStyle == .actionSheet {
self.setupGroupViewsForActionSheet()
} else if self.controllerStyle == .alert {
self.setupGroupViewsForAlert()
}
self.actionGroupView.backgroundColor = self.spacingColor
self.cancelGroupView.backgroundColor = self.spacingColor
}
private func setupGroupViewsForActionSheet() {
let setupGroupView: (UIView) -> Void = { groupView in
groupView.removeFromSuperview()
self.view.addSubview(groupView)
groupView.clipsToBounds = true
groupView.layer.cornerRadius = CGFloat(self.cornerRadius)
groupView.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-margin-[groupView]-margin-|",
options: NSLayoutFormatOptions(),
metrics: ["margin": self.horizontalMargin],
views: ["groupView": groupView])
)
}
setupGroupView(self.actionGroupView)
setupGroupView(self.cancelGroupView)
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=topMargin)-[actionGroupView]-margin-[cancelGroupView]-margin-|",
options: NSLayoutFormatOptions(),
metrics: ["topMargin": self.topMargin, "margin": self.verticalMargin],
views: ["actionGroupView": self.actionGroupView, "cancelGroupView": self.cancelGroupView])
)
}
private func setupGroupViewsForAlert() {
self.actionGroupView.removeFromSuperview()
self.view.addSubview(self.actionGroupView)
self.actionGroupView.clipsToBounds = true
self.actionGroupView.layer.cornerRadius = CGFloat(self.cornerRadius)
self.actionGroupView.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-margin-[groupView]-margin-|",
options: NSLayoutFormatOptions(),
metrics: ["margin": self.horizontalMargin],
views: ["groupView": self.actionGroupView])
)
self.view.addConstraint(NSLayoutConstraint(item: self.actionGroupView,
attribute: .centerY,
relatedBy: .equal,
toItem: self.view,
attribute: .centerY,
multiplier: 1,
constant: 0))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=margin)-[actionGroupView]-(>=margin)-|",
options: NSLayoutFormatOptions(),
metrics: ["margin": self.topMargin],
views: ["actionGroupView": self.actionGroupView]))
}
private func constraints(for views: [UIView]) -> [NSLayoutConstraint] {
var constraints: [NSLayoutConstraint] = []
var sibling: UIView?
// we want to position controls from top to bottom
for view in views.reversed() {
let isLast = view == views.first
constraints.append(contentsOf: self.horizontalConstraints(for: view))
constraints.append(contentsOf: self.verticalConstraints(for: view, withSibling: sibling, andIsLast: isLast))
sibling = view
}
return constraints
}
private func horizontalConstraints(for view: UIView) -> [NSLayoutConstraint] {
return NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|",
options: NSLayoutFormatOptions(),
metrics: nil,
views: ["view": view])
}
private func verticalConstraints(for view: UIView, withSibling sibling: UIView?, andIsLast isLast: Bool) -> [NSLayoutConstraint] {
var constraints: [NSLayoutConstraint] = []
let height = view != self.titleView ? self.minControlHeight : self.minTitleHeight
if let sibling = sibling {
let format = "V:[view(>=height)]-spacing-[sibling]"
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: format,
options: NSLayoutFormatOptions(),
metrics: ["spacing": self.spacing, "height": height],
views: ["view": view, "sibling": sibling]) )
} else {
let format = "V:[view(>=height)]-0-|"
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: format,
options: NSLayoutFormatOptions(),
metrics: ["height": height],
views: ["view": view]) )
}
if isLast {
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]",
options: NSLayoutFormatOptions(),
metrics: nil,
views: ["view": view]) )
}
return constraints
}
private func updateUI() {
self.view.backgroundColor = self.backgroundColor
self.view.removeConstraints(self.view.constraints)
self.setupGroupViews()
self.updateContraints()
}
// MARK: Event handling
@objc func handleTaps(_ sender: UIControl) {
let index = sender.tag
let action = self.actions[index]
if action.enabled {
self.disableControls()
self.dismiss(animated: true, completion: { [unowned self] in
self.enableControls()
self.dismissCompletionBlock?()
action.handler?(action)
})
}
}
func enableControls() {
self.setUserInteractionOnControlsEnabled(true, controls: self.actionControls)
self.setUserInteractionOnControlsEnabled(true, controls: self.cancelControls)
}
func disableControls() {
self.setUserInteractionOnControlsEnabled(false, controls: self.actionControls)
self.setUserInteractionOnControlsEnabled(false, controls: self.cancelControls)
}
func setUserInteractionOnControlsEnabled(_ enabled: Bool, controls: [UIControl]) {
for control in controls {
control.isUserInteractionEnabled = enabled
}
}
@objc func recognizeGestures(_ gestureRecognizer: UIGestureRecognizer) {
let point = gestureRecognizer.location(in: self.view)
let view = self.view.hitTest(point, with: nil)
if (view == self.view && self.outsideGestureShouldDismiss) {
self.disableControls()
self.dismiss(animated: true, completion: { [unowned self] in
self.enableControls()
self.dismissCompletionBlock?()
})
}
}
}
// MARK: - Helpers for adding views
extension AFMActionSheetController {
@objc
open func add(_ action: AFMAction) {
let control = UIButton.control(with: action)
self.add(action, with: control)
}
@objc
open func add(cancelling action: AFMAction) {
let control = UIButton.control(with: action)
self.add(cancelling: action, with: control)
}
@objc
open func add(_ action: AFMAction, with control: UIControl) {
self.add(action, with: control, andActionIsCancelling: false)
}
@objc
open func add(cancelling action: AFMAction, with control: UIControl) {
self.add(action, with: control, andActionIsCancelling: true)
}
@objc
open func insert(_ action: AFMAction, at position: Int) {
let control = UIButton.control(with: action)
self.insert(action, with: control, at: position)
}
@objc
open func insert(cancelling action: AFMAction, at position: Int) {
let control = UIButton.control(with: action)
self.insert(cancelling: action, with: control, at: position)
}
@objc
open func insert(_ action: AFMAction, with control: UIControl, at position: Int) {
self.insert(action, with: control, at: position, andActionIsCancelling: false)
}
@objc
open func insert(cancelling action: AFMAction, with control: UIControl, at position: Int) {
self.insert(action, with: control, at: position, andActionIsCancelling: true)
}
@objc
open func add(titleLabelWith text: String) {
let label = UILabel.title(with: text)
self.add(title: label)
}
}
// MARK: - Default control
extension UIButton {
class func control(with action: AFMAction) -> UIButton {
let button = UIButton()
button.backgroundColor = UIColor.white
button.setTitle(action.title, for: UIControlState())
button.setTitleColor(UIColor.darkText, for: UIControlState())
button.setTitleColor(UIColor.darkText.withAlphaComponent(0.5), for: .disabled)
button.setTitleColor(UIColor.red, for: .highlighted)
return button
}
}
extension UILabel {
class func title(with text: String) -> UILabel {
let title = UILabel()
title.text = text
title.textAlignment = .center
title.backgroundColor = UIColor.white
return title
}
}
|
mit
|
2468fd086caaf0fae7c7ca15c2f293cf
| 35.479508 | 154 | 0.66324 | 5.011824 | false | false | false | false |
instacrate/Subber-api
|
Sources/App/StripeCollection.swift
|
2
|
13477
|
//
// StripeCollection.swift
// subber-api
//
// Created by Hakon Hanesand on 1/1/17.
//
//
import Foundation
import HTTP
import Routing
import Vapor
extension Sequence where Iterator.Element == Bool {
public func all() -> Bool {
return reduce(true) { $0 && $1 }
}
}
extension NodeConvertible {
public func makeResponse() throws -> Response {
return try Response(status: .ok, json: self.makeNode().makeJSON())
}
}
extension Sequence where Iterator.Element == (key: String, value: String) {
func reduceDictionary() -> [String : String] {
return flatMap { $0 }.reduce([:]) { (_dict, tuple) in
var dict = _dict
dict.updateValue(tuple.1, forKey: tuple.0)
return dict
}
}
}
fileprivate func stripeKeyPathFor(base: String, appending: String) -> String {
if base.characters.count == 0 {
return appending
}
return "\(base)[\(appending)]"
}
extension Node {
var isLeaf : Bool {
switch self {
case .array(_), .object(_):
return false
case .bool(_), .bytes(_), .string(_), .number(_), .null:
return true
}
}
func collected() throws -> [String : String] {
return collectLeaves(prefix: "")
}
private func collectLeaves(prefix: String) -> [String : String] {
switch self {
case let .array(nodes):
return nodes.map { $0.collectLeaves(prefix: prefix) }.joined().reduceDictionary()
case let .object(object):
return object.map { $1.collectLeaves(prefix: stripeKeyPathFor(base: prefix, appending: $0)) }.joined().reduceDictionary()
case .bool(_), .bytes(_), .string(_), .number(_):
return [prefix : string ?? ""]
case .null:
return [:]
}
}
}
class StripeCollection: RouteCollection, EmptyInitializable {
required init() { }
typealias Wrapped = HTTP.Responder
func build<B: RouteBuilder>(_ builder: B) where B.Value == Wrapped {
builder.group("stripe") { stripe in
stripe.group("coupons") { coupon in
coupon.get(String.self) { request, code in
let query = try Coupon.query().filter("code", code)
return try query.first() ?? Response(status: .notFound, json: JSON(Node.string("Invalid coupon code.")))
}
coupon.post() { request in
guard let email: String = try request.json().node.extract("customerEmail") else {
throw Abort.custom(status: .badRequest, message: "missing customer email")
}
let fullCode = UUID().uuidString
let code = fullCode.substring(to: fullCode.index(fullCode.startIndex, offsetBy: 8))
var coupon = try Coupon(node: ["code" : code, "discount" : 0.05, "customerEmail" : email])
let _ = try Stripe.shared.createCoupon(code: coupon.code)
try coupon.save()
return coupon
}
}
stripe.group("customer") { customer in
customer.group("sources") { sources in
// TODO : double check
sources.post("default", String.self) { request, source in
guard let id = try request.customer().stripe_id else {
throw try Abort.custom(status: .badRequest, message: "user \(request.customer().throwableId()) doesn't have a stripe account")
}
return try Stripe.shared.update(customer: id, parameters: ["default_source" : source]).makeResponse()
}
sources.post(String.self) { request, source in
guard var customer = try? request.customer() else {
throw Abort.custom(status: .forbidden, message: "Log in first.")
}
if let stripe_id = customer.stripe_id {
return try Stripe.shared.associate(source: source, withStripe: stripe_id).makeResponse()
} else {
let stripeCustomer = try Stripe.shared.createNormalAccount(email: customer.email, source: source, local_id: customer.id?.int)
customer.stripe_id = stripeCustomer.id
try customer.save()
return try stripeCustomer.makeResponse()
}
}
sources.delete(String.self) { request, source in
guard let customer = try? request.customer() else {
throw Abort.custom(status: .forbidden, message: "Log in first.")
}
guard let id = customer.stripe_id else {
throw Abort.custom(status: .badRequest, message: "User \(customer.id!.int!) doesn't have a stripe account.")
}
return try Stripe.shared.delete(payment: source, from: id).makeResponse()
}
sources.get() { request in
guard let customer = try? request.customer(), let stripeId = customer.stripe_id else {
throw Abort.badRequest
}
let cards = try Stripe.shared.paymentInformation(for: stripeId).map { try $0.makeNode() }
return try Node.array(cards).makeResponse()
}
}
}
stripe.get("country", "verification", String.self) { request, country_code in
guard let country = try? CountryCode(node: country_code) else {
throw Abort.custom(status: .badRequest, message: "\(country_code) is not a valid country code.")
}
return try Stripe.shared.verificationRequiremnts(for: country).makeNode().makeResponse()
}
stripe.group("vendor") { vendor in
vendor.get("disputes") { request in
return try Stripe.shared.disputes().makeNode().makeResponse()
}
vendor.post("create") { request in
var vendor = try request.vendor()
let account = try Stripe.shared.createManagedAccount(email: vendor.contactEmail, local_id: vendor.id?.int)
vendor.stripeAccountId = account.id
vendor.keys = account.keys
try vendor.save()
return try vendor.makeResponse()
}
vendor.post("acceptedtos", String.self) { request, ip in
let vendor = try request.vendor()
guard let stripe_id = vendor.stripeAccountId else {
throw Abort.custom(status: .badRequest, message: "Missing stripe id")
}
return try Stripe.shared.acceptedTermsOfService(for: stripe_id, ip: ip).makeNode().makeResponse()
}
vendor.get("verification") { request in
let vendor = try request.vendor()
guard let stripeAccountId = vendor.stripeAccountId else {
throw Abort.custom(status: .badRequest, message: "Vendor does not have stripe id.")
}
let account = try Stripe.shared.vendorInformation(for: stripeAccountId)
return try account.descriptionsForNeededFields().makeResponse()
}
vendor.get("payouts") { request in
let vendor = try request.vendor()
guard let secretKey = vendor.keys?.secret else {
throw Abort.custom(status: .badRequest, message: "Vendor is missing stripe id.")
}
return try Stripe.shared.transfers(for: secretKey).makeNode().makeResponse()
}
vendor.post("verification") { request in
let vendor = try request.vendor()
guard let stripeAccountId = vendor.stripeAccountId else {
throw Abort.custom(status: .badRequest, message: "Vendor does not have stripe id")
}
let account = try Stripe.shared.vendorInformation(for: stripeAccountId)
let fieldsNeeded = account.filteredNeededFieldsWithCombinedDateOfBirth()
var node = try request.json().permit(fieldsNeeded).node
if node.nodeObject?.keys.contains(where: { $0.hasPrefix("external_account") }) ?? false {
node["external_account.object"] = "bank_account"
}
if node["legal_entity.dob"] != nil {
guard let unix = node["legal_entity.dob"]?.string else { throw Abort.custom(status: .badRequest, message: "Could not parse unix time from updates)") }
guard let timestamp = Int(unix) else { throw Abort.custom(status: .badRequest, message: "Could not get number from unix : \(unix)") }
let calendar = Calendar.current
let date = Date(timeIntervalSince1970: Double(timestamp))
node["legal_entity.dob"] = nil
node["legal_entity.dob.day"] = .string("\(calendar.component(.day, from: date))")
node["legal_entity.dob.month"] = .string("\(calendar.component(.month, from: date))")
node["legal_entity.dob.year"] = .string("\(calendar.component(.year, from: date))")
}
var updates: [String : String] = [:]
try node.nodeObject?.forEach {
guard let string = $1.string else {
throw Abort.custom(status: .badRequest, message: "could not convert object at key \($0) to string.")
}
var split = $0.components(separatedBy: ".")
if split.count == 1 {
updates[$0] = string
return
}
var key = split[0]
split.remove(at: 0)
key = key + split.reduce("") { $0 + "[\($1)]" }
updates[key] = string
}
return try Stripe.shared.updateAccount(id: stripeAccountId, parameters: updates).makeResponse()
}
vendor.post("upload", String.self) { request, _uploadReason in
let vendor = try request.vendor()
guard let uploadReason = try UploadReason(from: _uploadReason) else {
throw Abort.custom(status: .badRequest, message: "\(_uploadReason) is not an acceptable reason.")
}
if uploadReason != .identity_document {
throw Abort.custom(status: .badRequest, message: "Currently only \(UploadReason.identity_document.rawValue) is supported")
}
guard let fileField = request.formData?.allItems.first?.1 else {
throw Abort.custom(status: .badRequest, message: "Missing file to upload.")
}
guard let name = fileField.filename, let type = NSURL(fileURLWithPath: name).deletingPathExtension?.lastPathComponent, let fileType = try FileType(from: type) else {
throw Abort.custom(status: .badRequest, message: "Misisng upload file type.")
}
guard let stripeAccountId = vendor.stripeAccountId else {
throw Abort.custom(status: .badRequest, message: "Vendor with id \(vendor.id?.int ?? 0) does't have a stripe acocunt yet. Call /vendor/create/{token_id} to create one.")
}
let fileUpload = try Stripe.shared.upload(file: fileField.part.body, with: uploadReason, type: fileType)
return try Stripe.shared.updateAccount(id: stripeAccountId, parameters: ["legal_entity[verification][document]" : fileUpload.id]).makeResponse()
}
}
}
}
}
|
mit
|
9ed16979c9aeb134ffde24f27987f136
| 43.042484 | 193 | 0.487794 | 5.49633 | false | false | false | false |
DataArt/SmartSlides
|
PresentatorS/Model/AdvertiserHandler.swift
|
1
|
8834
|
//
// AdvertiserHandler.swift
// PresentatorS
//
// Created by Igor Litvinenko on 12/24/14.
// Copyright (c) 2014 Igor Litvinenko. All rights reserved.
//
import MultipeerConnectivity
class AdvertiserHandler: SessionHandler {
var manager : AdvertisingManager?
init(manager advertManager : AdvertisingManager){
manager = advertManager
super.init()
}
override func setup() {
self.commandFactory = AdviserCommandHelper()
ContentManager.sharedInstance.presentationUpdateClosure = { presentation in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
for session in self.manager!.sessions where session.peersCount > 0 {
var error: NSError?
do {
try session.sendData(SessionHandler.dataRequestForCommandType(.UpdatePresentationActiveSlide, parameters: ["name": presentation.presentationName, "page": String(presentation.currentSlide)]), toPeers: session.connectedPeers, withMode: .Reliable)
} catch let error1 as NSError {
error = error1
} catch {
fatalError()
}
if let err = error{
Logger.printLine("Updating presentation slide error \(err.localizedDescription) for session \(session.displayName) with index \(session.index)")
}
}
})
}
ContentManager.sharedInstance.onStopSharingClosure = {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
for session in self.manager!.sessions where session.peersCount > 0 {
var error: NSError?
do {
try session.sendData(SessionHandler.dataRequestForCommandType(.StopPresentation, parameters: ["wait": ""]), toPeers: session.connectedPeers, withMode: .Reliable)
} catch let error1 as NSError {
error = error1
} catch {
fatalError()
}
if let err = error{
Logger.printLine("Stopping presentation error \(err.localizedDescription) for session \(session.displayName) with index \(session.index)")
}
}
})
}
ContentManager.sharedInstance.onStartSharingClosure = { presentation in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
for session in self.manager!.sessions where session.peersCount > 0 {
var error: NSError?
do {
try session.sendData(SessionHandler.dataRequestForCommandType(.UpdateActivePresentation, parameters: ["items": presentation.presentationName, "slides_amount" : "\(presentation.slidesAmount)"]), toPeers: session.connectedPeers, withMode: .Reliable)
} catch let error1 as NSError {
error = error1
} catch {
fatalError()
}
if let err = error {
Logger.printLine("Updating active presentation error \(err.localizedDescription) for session \(session.displayName) with index \(session.index)")
}
}
})
}
}
override func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) {
Logger.printLine("\(peerID.displayName) state: \(state.rawValue) (2-connected)")
if state == .Connected && manager!.supplementarySessionNedded == true {
manager!.addSupplementaryPresentationSession()
}
}
// Received data from remote override override peer
override func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID){
self.commandFactory?.commandWithType(SessionHandler.parseResponseToDictionary(data)).execute(session, peers: [peerID])
}
}
class AdviserCommandHelper: SessionCommandFactory {
class CommandGetShared: SessionCommand {
let parameters: [String : String]?
required init(parameters: [String : String]) {
self.parameters = parameters
}
func execute(session: MCSession, peers: [MCPeerID]) -> (Bool) {
var error: NSError?
let resultString = ContentManager.sharedInstance.getSharedMaterials().joinWithSeparator(",")
let data = SessionHandler.dataRequestForCommandType(CommantType.GetSharedMaterialsList, parameters: ["items" : resultString])
let result: Bool
do {
try session.sendData(data, toPeers: peers, withMode: MCSessionSendDataMode.Reliable)
result = true
} catch let error1 as NSError {
error = error1
result = false
}
if let err = error {
Logger.printLine("\(__FUNCTION__), error: \(err.localizedDescription)")
}
return result
}
}
class CommandSendPresentation: SessionCommand {
var presentationName: String?
required init(parameters: [String : String]) {
self.presentationName = parameters["name"]
}
func execute(session: MCSession, peers: [MCPeerID]) -> (Bool) {
var result = true
if let path : String? = NSURL.CM_pathForPresentationWithName(presentationName!)?.path where presentationName != nil {
if NSFileManager.defaultManager().fileExistsAtPath(path!){
session.sendResourceAtURL(NSURL(fileURLWithPath: path!), withName: presentationName!, toPeer: peers.first!, withCompletionHandler: { (error) -> Void in
if error != nil {
Logger.printLine("Sending presentation error \(error!.localizedDescription) for session \(session.myPeerID.displayName)")
}
})
} else{
result = false
}
} else {
result = false
}
return result
}
}
class CommandGetActiveState: SessionCommand{
required init(parameters: [String : String]) { }
func execute(session: MCSession, peers: [MCPeerID]) -> (Bool) {
var parameters: [String: String]
if let presentation = ContentManager.sharedInstance.getActivePresentationState() {
parameters = ["name": presentation.presentationName, "page": String(presentation.currentSlide), "slides_amount": String(presentation.slidesAmount)]
} else {
parameters = ["name":""]
}
do {
try session.sendData(SessionHandler.dataRequestForCommandType(.GetPresentationActiveSlide, parameters: parameters), toPeers: peers, withMode: .Reliable)
return true
} catch _ {
return false
}
}
}
class CommandGetPing: SessionCommand{
required init(parameters: [String : String]) { }
func execute(session: MCSession, peers: [MCPeerID]) -> (Bool) {
do {
print("Ping received, ping sent back")
try session.sendData(SessionHandler.dataRequestForCommandType(.PingServer, parameters: nil), toPeers: peers, withMode: .Reliable)
return true
} catch let error as NSError {
print("Error sending ping: \(error)")
return false
}
}
}
func commandWithType(response: [String : String]) -> SessionCommand {
var result : SessionCommand = CommandUnknown(parameters: response)
let type = CommantType(rawValue: response["type"]!)
if let type = type {
switch type{
case .GetSharedMaterialsList:
result = CommandGetShared(parameters: response)
case .GetPresentationWithNameAndCrc:
result = CommandSendPresentation(parameters: response)
case .GetPresentationActiveSlide:
result = CommandGetActiveState(parameters: response)
case .PingServer:
result = CommandGetPing(parameters: response)
default:
result = CommandUnknown(parameters: response)
}
}
return result
}
}
|
mit
|
97dee5bfaf6d5ef6ad7e9046f2923851
| 41.681159 | 271 | 0.566674 | 5.52816 | false | false | false | false |
alickbass/ViewComponents
|
ViewComponents/ActivityIndicatorViewStyle.swift
|
1
|
1280
|
//
// ActivityIndicatorViewStyle.swift
// ViewComponents
//
// Created by Oleksii on 15/05/2017.
// Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//
import UIKit
private enum ActivityIndicatorViewStyleKey: Int, StyleKey {
case isAnimating = 700, hidesWhenStopped, activityIndicatorViewStyle, color
}
public extension AnyStyle where T: UIActivityIndicatorView {
private typealias ViewStyle<Item> = Style<T, Item, ActivityIndicatorViewStyleKey>
public static func isAnimating(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .isAnimating, sideEffect: { $1 ? $0.startAnimating() : $0.stopAnimating() }).toAnyStyle
}
public static func hidesWhenStopped(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .hidesWhenStopped, sideEffect: { $0.hidesWhenStopped = $1 }).toAnyStyle
}
public static func activityIndicatorViewStyle(_ value: UIActivityIndicatorViewStyle) -> AnyStyle<T> {
return ViewStyle(value, key: .activityIndicatorViewStyle, sideEffect: { $0.activityIndicatorViewStyle = $1 }).toAnyStyle
}
public static func color(_ value: UIColor?) -> AnyStyle<T> {
return ViewStyle(value, key: .color, sideEffect: { $0.color = $1 }).toAnyStyle
}
}
|
mit
|
a8317359d19fd4427b5faa1539acdead
| 37.757576 | 128 | 0.70602 | 4.440972 | false | false | false | false |
keatongreve/fastlane
|
fastlane/swift/LaneFileProtocol.swift
|
10
|
5388
|
//
// LaneFileProtocol.swift
// FastlaneSwiftRunner
//
// Created by Joshua Liebowitz on 8/4/17.
//
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Foundation
public protocol LaneFileProtocol: class {
var fastlaneVersion: String { get }
static func runLane(named: String, parameters: [String : String]) -> Bool
func recordLaneDescriptions()
func beforeAll()
func afterAll(currentLane: String)
func onError(currentLane: String, errorInfo: String)
}
public extension LaneFileProtocol {
var fastlaneVersion: String { return "" } // default "" because that means any is fine
func beforeAll() { } // no op by default
func afterAll(currentLane: String) { } // no op by default
func onError(currentLane: String, errorInfo: String) {} // no op by default
func recordLaneDescriptions() { } // no op by default
}
@objcMembers
public class LaneFile: NSObject, LaneFileProtocol {
private(set) static var fastfileInstance: Fastfile?
// Called before any lane is executed.
private func setupAllTheThings() {
LaneFile.fastfileInstance!.beforeAll()
}
private static func trimLaneFromName(laneName: String) -> String {
return String(laneName.prefix(laneName.count - 4))
}
private static func trimLaneWithOptionsFromName(laneName: String) -> String {
return String(laneName.prefix(laneName.count - 12))
}
private static var laneFunctionNames: [String] {
var lanes: [String] = []
var methodCount: UInt32 = 0
let methodList = class_copyMethodList(self, &methodCount)
for i in 0..<Int(methodCount) {
let selName = sel_getName(method_getName(methodList![i]))
let name = String(cString: selName)
let lowercasedName = name.lowercased()
if lowercasedName.hasSuffix("lane") || lowercasedName.hasSuffix("lanewithoptions:") {
lanes.append(name)
}
}
return lanes
}
public static var lanes: [String : String] {
var laneToMethodName: [String : String] = [:]
self.laneFunctionNames.forEach { name in
let lowercasedName = name.lowercased()
if lowercasedName.hasSuffix("lane") {
laneToMethodName[lowercasedName] = name
let lowercasedNameNoLane = trimLaneFromName(laneName: lowercasedName)
laneToMethodName[lowercasedNameNoLane] = name
} else if lowercasedName.hasSuffix("lanewithoptions:") {
let lowercasedNameNoOptions = trimLaneWithOptionsFromName(laneName: lowercasedName)
laneToMethodName[lowercasedNameNoOptions] = name
let lowercasedNameNoLane = trimLaneFromName(laneName: lowercasedNameNoOptions)
laneToMethodName[lowercasedNameNoLane] = name
}
}
return laneToMethodName
}
public static func loadFastfile() {
if self.fastfileInstance == nil {
let fastfileType: AnyObject.Type = NSClassFromString(self.className())!
let fastfileAsNSObjectType: NSObject.Type = fastfileType as! NSObject.Type
let currentFastfileInstance: Fastfile? = fastfileAsNSObjectType.init() as? Fastfile
self.fastfileInstance = currentFastfileInstance
}
}
public static func runLane(named: String, parameters: [String : String]) -> Bool {
log(message: "Running lane: \(named)")
self.loadFastfile()
guard let fastfileInstance: Fastfile = self.fastfileInstance else {
let message = "Unable to instantiate class named: \(self.className())"
log(message: message)
fatalError(message)
}
let currentLanes = self.lanes
let lowerCasedLaneRequested = named.lowercased()
guard let laneMethod = currentLanes[lowerCasedLaneRequested] else {
let laneNames = self.laneFunctionNames.map { laneFuctionName in
if laneFuctionName.hasSuffix("lanewithoptions:") {
return trimLaneWithOptionsFromName(laneName: laneFuctionName)
} else {
return trimLaneFromName(laneName: laneFuctionName)
}
}.joined(separator: ", ")
let message = "[!] Could not find lane '\(named)'. Available lanes: \(laneNames)"
log(message: message)
let shutdownCommand = ControlCommand(commandType: .cancel(cancelReason: .clientError), message: message)
_ = runner.executeCommand(shutdownCommand)
return false
}
// call all methods that need to be called before we start calling lanes
fastfileInstance.setupAllTheThings()
// We need to catch all possible errors here and display a nice message
_ = fastfileInstance.perform(NSSelectorFromString(laneMethod), with: parameters)
// only call on success
fastfileInstance.afterAll(currentLane: named)
log(message: "Done running lane: \(named) 🚀")
return true
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
|
mit
|
a7fb77d8f39443f19c3becfd1146f99a
| 37.464286 | 116 | 0.652182 | 4.529016 | false | false | false | false |
ipmobiletech/firefox-ios
|
Client/Frontend/Browser/BrowserPrintPageRenderer.swift
|
37
|
3165
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
private struct PrintedPageUX {
static let PageInsets = CGFloat(36.0)
static let PageTextFont = UIConstants.DefaultSmallFont
static let PageMarginScale = CGFloat(0.5)
}
class BrowserPrintPageRenderer: UIPrintPageRenderer {
private weak var browser: Browser?
let textAttributes = [NSFontAttributeName: PrintedPageUX.PageTextFont]
let dateString: String
required init(browser: Browser) {
self.browser = browser
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .ShortStyle
self.dateString = dateFormatter.stringFromDate(NSDate())
super.init()
self.footerHeight = PrintedPageUX.PageMarginScale * PrintedPageUX.PageInsets
self.headerHeight = PrintedPageUX.PageMarginScale * PrintedPageUX.PageInsets
if let browser = self.browser {
let formatter = browser.webView!.viewPrintFormatter()
formatter.perPageContentInsets = UIEdgeInsets(top: PrintedPageUX.PageInsets, left: PrintedPageUX.PageInsets, bottom: PrintedPageUX.PageInsets, right: PrintedPageUX.PageInsets)
addPrintFormatter(formatter, startingAtPageAtIndex: 0)
}
}
override func drawFooterForPageAtIndex(pageIndex: Int, var inRect headerRect: CGRect) {
let headerInsets = UIEdgeInsets(top: CGRectGetMinY(headerRect), left: PrintedPageUX.PageInsets, bottom: CGRectGetMaxY(paperRect) - CGRectGetMaxY(headerRect), right: PrintedPageUX.PageInsets)
headerRect = UIEdgeInsetsInsetRect(paperRect, headerInsets)
// url on left
self.drawTextAtPoint(browser!.displayURL?.absoluteString ?? "", rect: headerRect, onLeft: true)
// page number on right
let pageNumberString = "\(pageIndex + 1)"
self.drawTextAtPoint(pageNumberString, rect: headerRect, onLeft: false)
}
override func drawHeaderForPageAtIndex(pageIndex: Int, var inRect headerRect: CGRect) {
let headerInsets = UIEdgeInsets(top: CGRectGetMinY(headerRect), left: PrintedPageUX.PageInsets, bottom: CGRectGetMaxY(paperRect) - CGRectGetMaxY(headerRect), right: PrintedPageUX.PageInsets)
headerRect = UIEdgeInsetsInsetRect(paperRect, headerInsets)
// page title on left
self.drawTextAtPoint(browser!.displayTitle, rect: headerRect, onLeft: true)
// date on right
self.drawTextAtPoint(dateString, rect: headerRect, onLeft: false)
}
func drawTextAtPoint(text: String, rect:CGRect, onLeft: Bool){
let size = text.sizeWithAttributes(textAttributes)
let x, y: CGFloat
if onLeft {
x = CGRectGetMinX(rect)
y = CGRectGetMidY(rect) - size.height / 2
} else {
x = CGRectGetMaxX(rect) - size.width
y = CGRectGetMidY(rect) - size.height / 2
}
text.drawAtPoint(CGPoint(x: x, y: y), withAttributes: textAttributes)
}
}
|
mpl-2.0
|
84bfa9e9bd268e0dfc01f69a84804075
| 42.356164 | 198 | 0.701422 | 4.620438 | false | true | false | false |
piv199/LocalisysChat
|
LocalisysChat/Sources/Modules/Common/Chat/Components/Messages/BubbleMessage/TextBubbleMessage/LocalisysChatTextBubbleMessageMainView.swift
|
1
|
3391
|
//
// LocalisysChatTextBubbleMessageMainView.swift
// LocalisysChat
//
// Created by Olexii Pyvovarov on 7/3/17.
// Copyright © 2017 Olexii Pyvovarov. All rights reserved.
//
import UIKit
open class LocalisysChatTextBubbleMessageMainView: LocalisysChatBubbleMessageMainView {
public dynamic var textInsets = UIEdgeInsets(top: 3.0, left: 12.0, bottom: 3.0, right: 12.0) {
didSet { textArea.textContainerInset = textInsets }
}
// MARK: - UI
lazy var textArea: UITextView = {
let textView = UITextView()
textView.backgroundColor = .clear
textView.font = UIFont.systemFont(ofSize: 12)
textView.textColor = UIColor(white: 0.12, alpha: 1.0)
textView.isUserInteractionEnabled = false
textView.textContainerInset = self.textInsets
return textView
}()
internal var statusView: LocalisysChatMessageStatusView! {
willSet { statusView?.removeFromSuperview() }
didSet { addSubview(statusView) }
}
// MARK: - Lifecycle
public override init(frame: CGRect = .zero) {
super.init(frame: frame)
setupInitialState()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupInitialState()
}
// MARK: - Setup & Configuration
fileprivate func setupInitialState() {
addSubview(textArea)
// backgroundColor = .yellow
}
// MARK: - Methods
open func fill(text: String) {
textArea.text = text
}
open func fill(attributedText: NSAttributedString) {
textArea.attributedText = attributedText
}
// MARK: - Layout
open override func sizeThatFits(_ size: CGSize) -> CGSize {
let estimatedTextAreaSize = textArea.sizeThatFits(size)
let estimatedStatusViewSize = statusView.sizeThatFits(size)
let textAreaLines = textArea.lines(allowedWidth: size.width)
let multilineTextArea = textArea.hasMultilineText(with: estimatedTextAreaSize)
if let lastTextAreaLine = textAreaLines.last {
let estimatedLastTextAreaLineSize = (lastTextAreaLine as NSString)
.boundingRect(with: size, options: [], attributes: [NSFontAttributeName: textArea.font!], context: nil)
let spaceLeft = size.width - estimatedLastTextAreaLineSize.width - textArea.textContainerInset.horizontal - 4.0
if spaceLeft <= estimatedStatusViewSize.width {
return CGSize(width: multilineTextArea ? size.width : max(estimatedTextAreaSize.width, estimatedStatusViewSize.width),
height: estimatedTextAreaSize.height + estimatedStatusViewSize.height)
} else {
return CGSize(width: multilineTextArea ? size.width : estimatedTextAreaSize.width + estimatedStatusViewSize.width,
height: estimatedTextAreaSize.height)
}
}
return CGSize(width: multilineTextArea ? size.width : estimatedTextAreaSize.width,
height: estimatedTextAreaSize.height + estimatedStatusViewSize.height)
}
open override func layoutSubviews() {
super.layoutSubviews()
textArea.frame = bounds
let estimatedStatusViewSize = statusView.sizeThatFits(bounds.size)
statusView.frame = CGRect(x: bounds.width - estimatedStatusViewSize.width - textArea.textContainerInset.right,
y: bounds.height - estimatedStatusViewSize.height - 1.0,
width: estimatedStatusViewSize.width, height: estimatedStatusViewSize.height)
}
}
|
unlicense
|
7306a22e6db31ebc87ede02dfa204224
| 32.235294 | 126 | 0.710029 | 4.605978 | false | false | false | false |
Sajjon/SwiftIntro
|
Pods/Swinject/Sources/ServiceKey.swift
|
1
|
1435
|
//
// ServiceKey.swift
// Swinject
//
// Created by Yoichi Tagaya on 7/23/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Foundation
// MARK: ServiceKeyOptionType
public protocol ServiceKeyOptionType: CustomStringConvertible {
func isEqualTo(_ another: ServiceKeyOptionType) -> Bool
var hashValue: Int { get }
}
// MARK: - ServiceKey
internal struct ServiceKey {
internal let factoryType: FunctionType.Type
internal let name: String?
internal let option: ServiceKeyOptionType? // Used for SwinjectStoryboard or other extensions.
internal init(factoryType: FunctionType.Type, name: String? = nil, option: ServiceKeyOptionType? = nil) {
self.factoryType = factoryType
self.name = name
self.option = option
}
}
// MARK: Hashable
extension ServiceKey: Hashable {
var hashValue: Int {
return String(describing: factoryType).hashValue ^ (name?.hashValue ?? 0) ^ (option?.hashValue ?? 0)
}
}
// MARK: Equatable
func == (lhs: ServiceKey, rhs: ServiceKey) -> Bool {
return lhs.factoryType == rhs.factoryType && lhs.name == rhs.name && equalOptions(lhs.option, opt2: rhs.option)
}
private func equalOptions(_ opt1: ServiceKeyOptionType?, opt2: ServiceKeyOptionType?) -> Bool {
switch (opt1, opt2) {
case let (opt1?, opt2?): return opt1.isEqualTo(opt2)
case (nil, nil): return true
default: return false
}
}
|
gpl-3.0
|
ad8648198bf63466cf1faa340746abd5
| 28.875 | 115 | 0.691074 | 4.073864 | false | false | false | false |
Re-cover/GesPass
|
GesPassDemo/GesPass/GesPassItemView.swift
|
1
|
5749
|
//
// GesPassItemView.swift
// GesPass
//
// Created by Terry Hu. on 2016/12/31.
// Copyright © 2016年 Terry Hu. All rights reserved.
//
import UIKit
enum GesPassItemDirect: Int {
case top = 1
case rightTop
case right
case rightBottom
case bottom
case leftBottom
case left
case leftTop
}
enum GesPassItemStatus: Int {
case normal = 0
case selected
case error
case success
}
class GesPassItemView: UIView {
fileprivate var storeCalRect = CGRect()
fileprivate var angle: CGFloat?
fileprivate var options: GesPassOptions!
//计算三角形方向
var direct: GesPassItemDirect? {
willSet {
if let newValue = newValue {
angle = CGFloat(M_PI_4) * CGFloat(newValue.rawValue - 1)
setNeedsDisplay()
}
}
}
//itemView状态
var status: GesPassItemStatus = .normal {
didSet {
setNeedsDisplay()
}
}
//计算外环rect
fileprivate var calRect: CGRect {
set {
storeCalRect = newValue
}
get {
if storeCalRect.equalTo(CGRect.zero) {
let sizeWH = bounds.width - options.circleLineWidth
let originXY = options.circleLineWidth * 0.5
self.storeCalRect = CGRect(x: originXY, y: originXY, width: sizeWH, height: sizeWH)
}
return storeCalRect
}
}
//计算内环rect
fileprivate var selectedRect: CGRect {
get {
if CGRect().equalTo(CGRect.zero) {
let selectRectWH = bounds.width * options.innerCircleScale
let selectRectXY = bounds.width * (1 - options.innerCircleScale) * 0.5
return CGRect(x: selectRectXY, y: selectRectXY, width: selectRectWH, height: selectRectWH)
}
return CGRect.zero
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(options: GesPassOptions) {
self.init(frame: CGRect.zero)
self.options = options
//backgroundColor = options.backgroundColor
backgroundColor = UIColor.clear
}
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
//旋转
//transForm(context, rect: rect)
//圆环的颜色和线宽设置
configCircle(context)
//外环:普通
circleNormal(context, rect: rect)
switch status {
case .selected,.error,.success:
circleSelected(context, rect: rect)
default:
break
}
//选中情况下,绘制背景色
// if selected {
// //外环:选中
// circleSelected(context, rect: rect)
// //三角形:方向标识
// //direct(context, rect: rect)
// }
}
}
//根据三角箭头的方向旋转
func transForm(_ context: CGContext, rect: CGRect) {
let translateXY = rect.width * 0.5
//平移
context.translateBy(x: translateXY, y: translateXY)
context.rotate(by: angle ?? 0)
//再平移回来
context.translateBy(x: -translateXY, y: -translateXY)
}
//圆环的颜色和线宽设置
func configCircle(_ context: CGContext) {
//设置圆环线宽
context.setLineWidth(options.circleLineWidth)
switch status {
case .normal:
options.circleNormalColor.set()
case .selected:
options.circleSelectedColor.set()
case .error:
options.circleErrorColor.set()
case .success:
options.circleSuccessColor.set()
}
}
//外部圆环
func circleNormal(_ context: CGContext, rect: CGRect) {
//新建路径:外环
let loopPath = CGMutablePath()
//添加外环路径
loopPath.addEllipse(in: calRect)
//将路径添加到上下文中
context.addPath(loopPath)
//绘制圆环
context.strokePath()
}
//选中后的内部实心圆
func circleSelected(_ contenxt: CGContext, rect: CGRect) {
//新建路径:内环
let circlePath = CGMutablePath()
//添加内环路径
circlePath.addEllipse(in: selectedRect)
//将路径添加到上下文中
contenxt.addPath(circlePath)
//填充内部圆环
contenxt.fillPath()
}
//三角形箭头
func direct(_ ctx: CGContext, rect: CGRect) {
//新建路径:三角形
if direct == nil {
return
}
let trianglePathM = CGMutablePath()
let marginSelectedCirclev: CGFloat = 4
let w: CGFloat = 8
let h: CGFloat = 5
let topX = rect.minX + rect.width * 0.5
let topY = rect.minY + (rect.width * 0.5 - h - marginSelectedCirclev - selectedRect.height * 0.5)
trianglePathM.move(to: CGPoint(x: topX, y: topY))
//添加左边点
let leftPointX = topX - w * 0.5
let leftPointY = topY + h
trianglePathM.addLine(to: CGPoint(x: leftPointX, y: leftPointY))
//右边的点
let rightPointX = topX + w * 0.5
trianglePathM.addLine(to: CGPoint(x: rightPointX, y: leftPointY))
//将路径添加到上下文中
ctx.addPath(trianglePathM)
//填充三角形
ctx.fillPath()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
003d80bcd337b9cb1a1bacf54e23634a
| 24.117371 | 106 | 0.54785 | 4.196078 | false | false | false | false |
orlandoamorim/FamilyKey
|
Pods/Eureka/Source/Rows/Common/FieldRow.swift
|
1
|
18754
|
// FieldRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol InputTypeInitiable {
init?(string stringValue: String)
}
public protocol FieldRowConformance : FormatterConformance {
var titlePercentage : CGFloat? { get set }
var placeholder : String? { get set }
var placeholderColor : UIColor? { get set }
}
extension Int: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue, radix: 10)
}
}
extension Float: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension String: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
extension URL: InputTypeInitiable {}
extension Double: InputTypeInitiable {
public init?(string stringValue: String) {
self.init(stringValue)
}
}
open class FormatteableRow<Cell: CellType>: Row<Cell>, FormatterConformance where Cell: BaseCell, Cell: TextInputCell {
/// A formatter to be used to format the user's input
open var formatter: Formatter?
/// If the formatter should be used while the user is editing the text.
open var useFormatterDuringInput = false
open var useFormatterOnDidBeginEditing: Bool?
public required init(tag: String?) {
super.init(tag: tag)
displayValueFor = { [unowned self] value in
guard let v = value else { return nil }
guard let formatter = self.formatter else { return String(describing: v) }
if (self.cell.textInput as? UIView)?.isFirstResponder == true {
return self.useFormatterDuringInput ? formatter.editingString(for: v) : String(describing: v)
}
return formatter.string(for: v)
}
}
}
open class FieldRow<Cell: CellType>: FormatteableRow<Cell>, FieldRowConformance, KeyboardReturnHandler where Cell: BaseCell, Cell: TextFieldCell {
/// Configuration for the keyboardReturnType of this row
open var keyboardReturnType: KeyboardReturnTypeConfiguration?
/// The percentage of the cell that should be occupied by the textField
@available (*, deprecated, message: "Use titleLabelPercentage instead")
open var textFieldPercentage : CGFloat? {
get {
return titlePercentage.map { 1 - $0 }
}
set {
titlePercentage = newValue.map { 1 - $0 }
}
}
/// The percentage of the cell that should be occupied by the title (i.e. the titleLabel and optional imageView combined)
open var titlePercentage: CGFloat?
/// The placeholder for the textField
open var placeholder: String?
/// The textColor for the textField's placeholder
open var placeholderColor: UIColor?
public required init(tag: String?) {
super.init(tag: tag)
}
}
/**
* Protocol for cells that contain a UITextField
*/
public protocol TextInputCell {
var textInput: UITextInput { get }
}
public protocol TextFieldCell: TextInputCell {
var textField: UITextField! { get }
}
extension TextFieldCell {
public var textInput: UITextInput {
return textField
}
}
open class _FieldCell<T> : Cell<T>, UITextFieldDelegate, TextFieldCell where T: Equatable, T: InputTypeInitiable {
@IBOutlet public weak var textField: UITextField!
@IBOutlet public weak var titleLabel: UILabel?
fileprivate var observingTitleText = false
private var awakeFromNibCalled = false
open var dynamicConstraints = [NSLayoutConstraint]()
private var calculatedTitlePercentage: CGFloat = 0.7
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
let textField = UITextField()
self.textField = textField
textField.translatesAutoresizingMaskIntoConstraints = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel = self.textLabel
titleLabel?.translatesAutoresizingMaskIntoConstraints = false
titleLabel?.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
titleLabel?.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
contentView.addSubview(titleLabel!)
contentView.addSubview(textField)
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationWillResignActive, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard me.observingTitleText else { return }
me.titleLabel?.removeObserver(me, forKeyPath: "text")
me.observingTitleText = false
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard !me.observingTitleText else { return }
me.titleLabel?.addObserver(me, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
me.observingTitleText = true
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil) { [weak self] _ in
self?.titleLabel = self?.textLabel
self?.setNeedsUpdateConstraints()
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
awakeFromNibCalled = true
}
deinit {
textField?.delegate = nil
textField?.removeTarget(self, action: nil, for: .allEvents)
guard !awakeFromNibCalled else { return }
if observingTitleText {
titleLabel?.removeObserver(self, forKeyPath: "text")
}
imageView?.removeObserver(self, forKeyPath: "image")
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil)
}
open override func setup() {
super.setup()
selectionStyle = .none
if !awakeFromNibCalled {
titleLabel?.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
observingTitleText = true
imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
}
textField.addTarget(self, action: #selector(_FieldCell.textFieldDidChange(_:)), for: .editingChanged)
}
open override func update() {
super.update()
detailTextLabel?.text = nil
if !awakeFromNibCalled {
if let title = row.title {
textField.textAlignment = title.isEmpty ? .left : .right
textField.clearButtonMode = title.isEmpty ? .whileEditing : .never
} else {
textField.textAlignment = .left
textField.clearButtonMode = .whileEditing
}
}
textField.delegate = self
textField.text = row.displayValueFor?(row.value)
textField.isEnabled = !row.isDisabled
textField.textColor = row.isDisabled ? .gray : .black
textField.font = .preferredFont(forTextStyle: .body)
if let placeholder = (row as? FieldRowConformance)?.placeholder {
if let color = (row as? FieldRowConformance)?.placeholderColor {
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedStringKey.foregroundColor: color])
} else {
textField.placeholder = (row as? FieldRowConformance)?.placeholder
}
}
if row.isHighlighted {
textLabel?.textColor = tintColor
}
}
open override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && textField?.canBecomeFirstResponder == true
}
open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool {
return textField?.becomeFirstResponder() ?? false
}
open override func cellResignFirstResponder() -> Bool {
return textField?.resignFirstResponder() ?? true
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let obj = object as AnyObject?
if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey],
((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) &&
(changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
// MARK: Helpers
open func customConstraints() {
guard !awakeFromNibCalled else { return }
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
var views: [String: AnyObject] = ["textField": textField]
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[textField]-11-|", options: .alignAllLastBaseline, metrics: nil, views: views)
if let label = titleLabel, let text = label.text, !text.isEmpty {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[titleLabel]-11-|", options: .alignAllLastBaseline, metrics: nil, views: ["titleLabel": label])
dynamicConstraints.append(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: textField, attribute: .centerY, multiplier: 1, constant: 0))
}
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["label"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[label]-[textField]-|", options: NSLayoutFormatOptions(), metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
}
else{
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views)
}
}
else{
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["label"] = titleLabel
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-[textField]-|", options: [], metrics: nil, views: views)
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .width,
relatedBy: (row as? FieldRowConformance)?.titlePercentage != nil ? .equal : .lessThanOrEqual,
toItem: contentView,
attribute: .width,
multiplier: calculatedTitlePercentage,
constant: 0.0))
}
else{
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views)
}
}
contentView.addConstraints(dynamicConstraints)
}
open override func updateConstraints() {
customConstraints()
super.updateConstraints()
}
@objc open func textFieldDidChange(_ textField: UITextField) {
guard let textValue = textField.text else {
row.value = nil
return
}
guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
return
}
if fieldRow.useFormatterDuringInput {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
guard var selStartPos = textField.selectedTextRange?.start else { return }
let oldVal = textField.text
textField.text = row.displayValueFor?(row.value)
selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textField, oldValue: oldVal, newValue: textField.text) ?? selStartPos
textField.selectedTextRange = textField.textRange(from: selStartPos, to: selStartPos)
return
}
} else {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil
if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) {
row.value = value.pointee as? T
} else {
row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value)
}
}
}
// MARK: Helpers
private func displayValue(useFormatter: Bool) -> String? {
guard let v = row.value else { return nil }
if let formatter = (row as? FormatterConformance)?.formatter, useFormatter {
return textField?.isFirstResponder == true ? formatter.editingString(for: v) : formatter.string(for: v)
}
return String(describing: v)
}
// MARK: TextFieldDelegate
open func textFieldDidBeginEditing(_ textField: UITextField) {
formViewController()?.beginEditing(of: self)
formViewController()?.textInputDidBeginEditing(textField, cell: self)
if let fieldRowConformance = row as? FormatterConformance, let _ = fieldRowConformance.formatter, fieldRowConformance.useFormatterOnDidBeginEditing ?? fieldRowConformance.useFormatterDuringInput {
textField.text = displayValue(useFormatter: true)
} else {
textField.text = displayValue(useFormatter: false)
}
}
open func textFieldDidEndEditing(_ textField: UITextField) {
formViewController()?.endEditing(of: self)
formViewController()?.textInputDidEndEditing(textField, cell: self)
textFieldDidChange(textField)
textField.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil)
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldReturn(textField, cell: self) ?? true
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return formViewController()?.textInput(textField, shouldChangeCharactersInRange:range, replacementString:string, cell: self) ?? true
}
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
open func textFieldShouldClear(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldClear(textField, cell: self) ?? true
}
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let row = (row as? FieldRowConformance) else { return }
guard let titlePercentage = row.titlePercentage else { return }
var targetTitleWidth = bounds.size.width * titlePercentage
if let imageView = imageView, let _ = imageView.image, let titleLabel = titleLabel {
var extraWidthToSubtract = titleLabel.frame.minX - imageView.frame.minX // Left-to-right interface layout
if #available(iOS 9.0, *) {
if UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft {
extraWidthToSubtract = imageView.frame.maxX - titleLabel.frame.maxX
}
}
targetTitleWidth -= extraWidthToSubtract
}
let targetTitlePercentage = targetTitleWidth / contentView.bounds.size.width
if calculatedTitlePercentage != targetTitlePercentage {
calculatedTitlePercentage = targetTitlePercentage
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
}
|
mit
|
034b757775395713aab4716b925736fa
| 43.231132 | 204 | 0.664232 | 5.276871 | false | false | false | false |
NUKisZ/TestKitchen_1606
|
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBSearchHeaderView.swift
|
1
|
1206
|
//
// CBSearchHeaderView.swift
// TestKitchen
//
// Created by NUK on 16/8/18.
// Copyright © 2016年 NUK. All rights reserved.
//
import UIKit
class CBSearchHeaderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
//搜索框
// let searchBar = UISearchBar(frame: CGRectMake(0,0,bounds.size.width ,bounds.size.height))
// searchBar.placeholder = "输入菜名或食材搜索"
// searchBar.alpha = 0.5
//
// addSubview(searchBar)
//可以用TextField来代替
let textField = UITextField(frame: CGRectMake(40,4,bounds.size.width - 40*2,bounds.size.height-4*2))
textField.borderStyle = .RoundedRect
textField.placeholder = "输入菜名或食材搜索"
addSubview(textField)
let imageView = UIImageView.createImageView("search1")
imageView.frame = CGRectMake(0, 0, 24, 24)
textField.leftView = imageView
textField.leftViewMode = .Always
backgroundColor = UIColor(white: 0.8, alpha: 1.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
cf9080faa42ccb8eb0c0ac87465acf95
| 26.357143 | 108 | 0.62141 | 3.921502 | false | false | false | false |
dsoisson/SwiftLearningExercises
|
SwiftLearning.playground/Pages/Control Flow.xcplaygroundpage/Contents.swift
|
1
|
12292
|
/*:
[Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next)
*/
/*:
# Control Flow
*/
/*:
**Session Overview:**
Processing logic is what gives your programs personality. These decision making statements are known as control flow. Control flow statements can fork your execution path or even repeat a series of statements. Please visit the Swift Programming Language Guide section on [Control Flow](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID120) for more details on control flow.
*/
import Foundation
/*:
## The `if` and the `else` conditional statements
The simplest of the control flow statements is the `if` and `else` statements. The `if` conditional statement evaluates a boolean expression (true or false) and executes code if the result of the evaluation is `true`. If `else` is present, code is executed if the `if` statement evaluates to `false`.
*/
var grade = "A"
if grade == "A" {
print("you will get an A")
} else {
print("not an A")
}
grade = "D"
if grade == "D" {
print("you will get a D")
} else {
print("at least not a D")
}
//: You can also combine as many boolean expression on a `if` conditional statement, though using a `switch` statement if recommended for readabiliy.
if grade == "A" || grade == "B" {
print("you will get a good grade")
} else if grade == "A" {
print("you will get an average grade")
} else if grade == "D" || grade == "F" {
print("you will get a bad grade")
}
/*:
## less `if`ing and more `switch`ing
If your code has many boolean expressions to evaluate, a `switch` statement will provide more readabiliy. The `switch` compares a value of a constant or variable against a series of possible outcomes. If there is a match, provide with the `case`, the block of code is executed for the `case` only. The `switch` statement must be *exhaustive*, meaning that every possible value must be matched against one of the `switch` cases.
*/
grade = "B"
switch grade {
case "A":
print("get an A")
case "B":
print("get an B")
case "C":
print("get an C")
case "D":
print("get an D")
default:
print("get an F")
}
switch grade {
case "A", "B":
print("pass")
case "D", "F":
print("repeat")
default:
print("needs to study more")
}
//: The above `switch` statements has the `default` case which will be matched when all other cases fail.
/*:
### Fallthrough
Swift's `switch` statement matches on a single case and ends execution of the `switch` after the case body is executed. There are instances where you would want multiple cases to be matched where it's not appropriate provide the matching on the a single case.
*/
var gradeNumber = 95
var gradeLetter: String = ""
switch gradeNumber {
case 93: fallthrough
case 94: fallthrough
case 95: fallthrough
case 96: fallthrough
case 97: fallthrough
case 98: fallthrough
case 99:
gradeLetter = "A"
case 90:
gradeLetter = "A-"
case 80:
gradeLetter = "B"
case 70:
gradeLetter = "C"
case 60:
gradeLetter = "D"
case 50:
gradeLetter = "F"
default:
break // this break is needed because all cases need a body
}
print(gradeLetter)
//: `fallthrough` doesn't check the following case condition, but causes execution to move to the next statements of the following case.
//: > **Experiment**: Assign gradeNumber equal to 100 and have gradeLetter print A+.
/*:
### Interval Matching
The value in the `switch` case statement can be checked to determine if the value is included in a specified range.
*/
gradeNumber = 100
switch gradeNumber {
case 100:
gradeLetter = "A+"
case 93...99:
gradeLetter = "A"
case 90..<93:
gradeLetter = "A-"
case 80..<90:
gradeLetter = "B"
case 70..<80:
gradeLetter = "C"
case 60..<60:
gradeLetter = "D"
case 50..<60:
gradeLetter = "F"
default:
gradeLetter = ""
break // this break is needed because all cases need a body
}
print(gradeLetter)
/*:
The above `switch` case uses grade ranges to determine the grade letter as opposed to specifying each grade number.
*/
/*:
### Working with Tuples
Using the `switch` statement with tuples lets you execute code branches depending on values within the tuple.
*/
let gradeTuple = (gradeNumber, gradeLetter)
switch gradeTuple {
case (100, _):
print("You get an A+")
case (93...99, _):
print("You get an A")
case (90..<93, _):
print("You get an A-")
case (80..<90, _):
print("You get an B")
case (70..<80, _):
print("You get an C")
case (60..<60, _):
print("You get an D")
case (50..<60, _):
print("You get an F")
default:
print("You got an \(gradeTuple.0)%")
}
switch gradeTuple {
case (_, "A+"):
print("You got 100%")
case (_, "A"):
print("You got between 90% - 99%")
case (_, "B"):
print("You got between 80% - 89%")
case (_, "C"):
print("You got between 70% - 79%")
case (_, "D"):
print("You got between 60% - 69%")
case (_, "F"):
print("You got between 50% - 59%")
default:
print("You dont' get a grade")
}
/*:
The first `switch` case statement matches on the grade number providing that the grade number falls within a case range. The second `switch` matches on the grade letter.
*/
/*:
### Value Bindings
The `switch` case statement can store values into constants or variables that are only available to the `switch` case body. This is known as *value binding*, because values are bound to temporary constants or variables when a value or values are match in the case.
*/
switch gradeTuple {
case (90...100, let letter):
print("You got between 90% - 100%, or an \(letter)")
case (80..<89, let letter):
print("You got between 80% - 89%, or a \(letter)")
case (70..<79, let letter):
print("You got between 70% - 79%, or a \(letter)")
case (60..<69, let letter):
print("You got between 60% - 69%, or a \(letter)")
case (50..<59, let letter):
print("You got between 50% - 59%, or a \(letter)")
case let (number, letter):
print("You got a \(number)% or a \(letter)")
}
/*:
Here the `switch` matches on the grade number range and prints out the grade letter.
*/
/*:
### Where
You can use a `where` clause to check for even more conditions.
*/
switch gradeTuple {
case (100, _):
print("You aced it!")
case let (number, letter) where "ABCD".containsString(letter):
print("You passed!")
default:
print("You failed!")
}
/*:
Above, all we want to do is print a message from one of three cases. We use the `where` clause on the second case to see if the grade letter is contained in the array of grade letters.
*/
/*:
## Iterating using For Loops
Two `for` looping statements that let you execute code blocks a certain number of times are the `for-in` and the `for` loops.
*/
/*:
### For-In
The `for-in` loop executes a set of statements for each item in a list or sequence of items.
*/
for grade in "ABCDF".characters {
print(grade)
}
for index in 0..<5 {
print(index)
}
/*:
### For
The `for` loop executes a set of statements until a specific condition is met, usually by incrementing a counter each time the loop ends.
*/
for var index = 0; index < 5; ++index {
print(index)
}
//: The `for` loop has 3 parts:
/*:
- *Initialization* (`var index = 0`), evaluated once.
- *Condition* (`index < 5`), evaluated at the start of the each loop. If the result is `true` statements in the block are executed, if `false` the loop ends.
- *Increment* (`++index`), evaluated after all the statements in the block are executed.
*/
/*:
## Iterating using While Loops
`while` loops are recommended when the number of iterations is unknown before looping begins.
*/
/*:
### While
The `while` loop evaluates its condition at the beginning of each iteration through the loop.
*/
var index = 0
while (index < 5) {
print(index)
index++
}
//: The above `while` loop statement evaluates `index < 5`, if the result is `true` looping continues, if `false` looping ends.
/*:
### Repeat-While
The `repeat-while` loop evaluates its condition at the end of each iteration through the loop.
*/
index = 0
repeat {
print(index)
index++
} while (index < 5)
//: The above `repeat-while` loop statement executes the code block first then evaluates `index < 5`, if the result is `true` looping continues, if `false` looping ends.
/*:
## Control Transfer Statements
Control transfer statements change the sequence or order in which your code is executed, by transferring control from one block of code to another. Swift provides five control transfer statements:
- `continue`
- `break`
- `fallthrough`
- `return`, explained in [Functions](Functions)
- `throw`, explained in [Functions](Functions)
*/
/*:
### Continue
The `continue` statement tells a loop to stop and start again at the beginning of the next iteration through the loop.
*/
index = 0
repeat {
index++
if index == 3 {
continue
}
print(index)
} while (index < 5)
//: The above `repeat-while` loop statement skips the index 3, moves onto the next iteration of the loop printing 4 and 5, then ends normally.
/*:
### Break
The `break` statement ends the execution of the control flow statement. The `break` statement is used in the `switch` and loop statements to end the control flow earlier than normal.
*/
/*:
**Break in a Loop Statement**
A `break` in a loop exits the loop.
*/
index = 0
repeat {
index++
if index == 3 {
break
}
print(index)
} while (index < 5)
//: The above `repeat-while` loop statement loops until index equals 3 and exits the loop all together.
/*:
**Break in a Switch Statement**
A `break` in a `switch` is used to ignore cases.
*/
gradeNumber = 80
switch gradeNumber {
case 100:
print("A+")
case 90:
print("A")
case 80:
print("B")
case 70:
print("C")
case 60:
print("D")
case 50:
print("F")
default:
break // this break is needed because all cases need a body
}
//: The above `switch` statement needs a `break` in the `default` case because the all other values greater than 100 aren't applicable.
/*:
## API Availability
*/
if #available(iOS 9, OSX 10.11, *) {
print("statements will execute for iOS9+ and osx 10.11+")
} else {
print("statements to execute when running on lower platforms.")
}
/*:
**Exercise:** You have a secret message to send. Write a playground that can encrypt strings with an alphabetical [caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher). This cipher can ignore numbers, symbols, and whitespace.
>> **Example Output:**
* Decrypted: Nearly all men can stand adversity, but if you want to test a man's character, give him power
* Encrypted: arneyl nyy zra pna fgnaq nqirefvgl, ohg vs lbh jnag gb grfg n zna'f punenpgre, tvir uvz cbjre
>> **Constraints:**
* The encrypted and decrypted text is case sensitive
* Add a shift variable to indicate how many places to shift
*/
/*:
**Checkpoint:**
At this point, you have learned the majority of the control flow statements that enable you to make decisions and execute a set of statements zero or more times until some condition is met.
*/
/*:
**Keywords to remember:**
- `if` = evaluate an express for `true` and execute the following statements
- `else` = execute the following statements when the `if` evaluates an express to false
- `for` = to iterate
- `in` = when used with `for`, iterate over items in *something*
- `while` = execute statements indefinitely until a false expression is met
- `repeat` = used with `while`, execute statments first then loop
- `switch` = the start of matching a value on possible outcomes
- `case` = used with `switch`, a single outcome
- `default` = used with 'switch', the any outcome
- `fallthrough` = used with `switch`, execute the next case's statements
- `continue` = move on to the next iteration and don't execute the following statements
- `break` = when used with looping, stop looping and don't execute the following statements
- `where` = when used with switch, to expand matching conditions
*/
/*:
**Supporting Chapters:**
- [Control Flow](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html)
*/
/*:
[Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next)
*/
|
mit
|
ae7a4d9941f08e301db1142fe8832d35
| 31.86631 | 487 | 0.689636 | 3.744136 | false | false | false | false |
emaloney/CleanroomLogger
|
Sources/PayloadValueLogFormatter.swift
|
3
|
1401
|
//
// PayloadValueLogFormatter.swift
// CleanroomLogger
//
// Created by Evan Maloney on 1/6/17.
// Copyright © 2017 Gilt Groupe. All rights reserved.
//
/**
A `LogFormatter` that returns the message content of a `LogEntry` whose
`payload` is a `.value` value.
*/
public struct PayloadValueLogFormatter: LogFormatter
{
/**
The initializer.
*/
public init() {}
/**
Formats the passed-in `LogEntry` by returning a string representation of
its `payload` property.
- parameter entry: The `LogEntry` to be formatted.
- returns: The message content, or `nil` if `entry` doesn't have a
`payload` with a `.value` value.
*/
public func format(_ entry: LogEntry)
-> String?
{
guard case .value(let v) = entry.payload else { return nil }
guard let value = v else {
return "= nil"
}
var pieces = [String]()
pieces.append("= ")
pieces.append(String(describing: type(of: value)))
pieces.append(": ")
if let custom = value as? CustomDebugStringConvertible {
pieces.append(custom.debugDescription)
}
else if let custom = value as? CustomStringConvertible {
pieces.append(custom.description)
}
else {
pieces.append(String(describing: value))
}
return pieces.joined()
}
}
|
mit
|
b7866814c4f8b35150c97b060402d42d
| 24.925926 | 77 | 0.597143 | 4.347826 | false | false | false | false |
jordane-quincy/M2_DevMobileIos
|
JSONProject/Demo/PaymentViewController.swift
|
1
|
20534
|
//
// GeneralFormViewController.swift
// Demo
//
// Created by MAC ISTV on 28/04/2017.
// Copyright © 2017 UVHC. All rights reserved.
//
import UIKit
class PaymentViewController: UIViewController, UIPickerViewDelegate, UIScrollViewDelegate {
var scrollView = UIScrollView()
var containerView = UIView()
let realmServices = RealmServices()
var jsonModel: JsonModel? = nil
var customNavigationController: UINavigationController? = nil
var person: Person? = nil
var customParent1: SpecificFormViewController? = nil
var customParent2: SelectOptionViewController? = nil
var pX = 0
var selectedPaymentWay = ""
override func viewDidLoad() {
super.viewDidLoad()
// set up title of view
self.title = "Paiement"
// Setup Sortie de champs quand on clique à coté
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(GeneralFormViewController.dismissKeyboard))
self.view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
containerView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)
}
public func setupNavigationController (navigationController: UINavigationController){
self.customNavigationController = navigationController
}
public func setupPerson(person: Person) {
self.person = person
}
public func setupCustomParent1(customParent: SpecificFormViewController) {
self.customParent1 = customParent
}
public func setupCustomParent2(customParent: SelectOptionViewController) {
self.customParent2 = customParent
}
override func willMove(toParentViewController: UIViewController?)
{
if (toParentViewController == nil) {
if (!(self.person?.isSaved)!) {
// Reset custom parent
self.customParent1 = nil
self.customParent2 = nil
}
}
}
func validSubscription(_ sender: UIButton) {
// get data from UI for the Person Object
// Test if all requiredField are completed
let paymentWay = PaymentWay(label: self.selectedPaymentWay)
var tag = -1
if (self.selectedPaymentWay == "Compte Bancaire") {
tag = 1
}
if (self.selectedPaymentWay == "Carte Bancaire") {
tag = 2
}
if (self.selectedPaymentWay == "Paypal") {
tag = 3
}
var champManquant: Bool = false
for view in self.containerView.subviews {
if (view.tag == tag) {
if let textField = view as? CustomTextField {
if(textField.required == true && textField.text == ""){
print("Champ requis non rempli")
champManquant = true
}
let paymentAttribute = PaymentAttribute(_label: textField.label, _fieldName: textField.fieldName, _value: textField.text!)
paymentWay.addPaymentAttribute(paymentAttribute: paymentAttribute)
}
}
}
// test if they are empty required field
if(champManquant){
let alert = UIAlertController(title: "", message: "Veuillez remplir tous les champs requis (champs avec une étoile)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Fermer", style: UIAlertActionStyle.default, handler: { action in
switch action.style{
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
}
}))
self.present(alert, animated: true, completion: nil)
} else {
self.person?.setupPaymentWay(paymentWay: paymentWay)
self.person?.changeIsSavePerson()
// Save the person in realm database
realmServices.createPerson(person: self.person!)
realmServices.addSubscriberToService(title: (self.jsonModel?.title)!, subscriber: self.person!)
// Go Back to home view
self.customNavigationController?.popToRootViewController(animated: true)
}
}
func createFormCreditAccount() {
// Ajout iban
let ibanLabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20))
ibanLabel.text = "IBAN*"
ibanLabel.tag = 1
self.pX += 20
self.containerView.addSubview(ibanLabel)
// Ajout ibanField
let ibanTextField = CustomTextField(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 40))
ibanTextField.required = true
ibanTextField.fieldName = "iban"
ibanTextField.placeholder = "Completer"
ibanTextField.label = "IBAN"
ibanTextField.tag = 1
self.pX += 60
self.containerView.addSubview(ibanTextField)
// Ajout bic
let bicLabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20))
bicLabel.text = "BIC*"
bicLabel.tag = 1
self.pX += 20
self.containerView.addSubview(bicLabel)
// Ajout bicField
let bicTextField = CustomTextField(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 40))
bicTextField.required = true
bicTextField.fieldName = "bic"
bicTextField.placeholder = "Completer"
bicTextField.label = "BIC"
bicTextField.tag = 1
self.pX += 60
self.containerView.addSubview(bicTextField)
// Add Validation button
let validationButton = UIButton(frame: CGRect(x: 25, y: CGFloat(pX), width: 335, height: 30.00))
validationButton.setTitle("Valider l'inscription", for: .normal)
validationButton.addTarget(self, action: #selector(self.validSubscription(_:)), for: .touchUpInside)
validationButton.tag = 1
validationButton.setTitleColor(UIView().tintColor, for: .normal)
validationButton.backgroundColor = UIColor.clear
validationButton.titleLabel?.textAlignment = .center
validationButton.titleLabel?.numberOfLines = 0
self.pX += 40
self.containerView.addSubview(validationButton)
}
func createFormCreditCard() {
// Ajout cardNumber
let cardNumberLabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20))
cardNumberLabel.text = "Numéro de carte*"
cardNumberLabel.tag = 2
self.pX += 20
self.containerView.addSubview(cardNumberLabel)
// Ajout ibanField
let cardNumberTextField = CustomTextField(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 40))
cardNumberTextField.fieldName = "cardNumber"
cardNumberTextField.required = true
cardNumberTextField.placeholder = "Completer"
cardNumberTextField.label = "Numéro de carte"
cardNumberTextField.tag = 2
self.pX += 60
self.containerView.addSubview(cardNumberTextField)
// Ajout iban
let expirtationDateLabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20))
expirtationDateLabel.text = "Date d'expiration*"
expirtationDateLabel.tag = 2
self.pX += 20
self.containerView.addSubview(expirtationDateLabel)
// Ajout expirtation date
let expirtationDateTextField = CustomTextField(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 40))
expirtationDateTextField.required = true
expirtationDateTextField.fieldName = "expirationDate"
expirtationDateTextField.placeholder = "Completer"
expirtationDateTextField.label = "Date d'expiration"
expirtationDateTextField.tag = 2
self.pX += 60
self.containerView.addSubview(expirtationDateTextField)
// Ajout crypto
let cryptoLabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20))
cryptoLabel.text = "Cryptogramme*"
cryptoLabel.tag = 2
self.pX += 20
self.containerView.addSubview(cryptoLabel)
// Ajout ibanField
let cryptoTextField = CustomTextField(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 40))
cryptoTextField.required = true
cryptoTextField.fieldName = "crypto"
cryptoTextField.placeholder = "Completer"
cryptoTextField.label = "Cryptogramme"
cryptoTextField.tag = 2
self.pX += 60
self.containerView.addSubview(cryptoTextField)
// Ajout owner
let ownerLabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20))
ownerLabel.text = "Propriétaire*"
ownerLabel.tag = 2
self.pX += 20
self.containerView.addSubview(ownerLabel)
// Ajout ibanField
let ownerTextField = CustomTextField(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 40))
ownerTextField.required = true
ownerTextField.fieldName = "owner"
ownerTextField.placeholder = "Completer"
ownerTextField.label = "Propriétaire"
ownerTextField.tag = 2
self.pX += 60
self.containerView.addSubview(ownerTextField)
// Add Validation button
let validationButton = UIButton(frame: CGRect(x: 25, y: CGFloat(pX), width: 335, height: 30.00))
validationButton.setTitle("Valider l'inscription", for: .normal)
validationButton.addTarget(self, action: #selector(self.validSubscription(_:)), for: .touchUpInside)
validationButton.tag = 2
validationButton.setTitleColor(UIView().tintColor, for: .normal)
validationButton.backgroundColor = UIColor.clear
validationButton.titleLabel?.textAlignment = .center
validationButton.titleLabel?.numberOfLines = 0
self.pX += 40
self.containerView.addSubview(validationButton)
}
func createFormPaypal() {
// Ajout label
let paypalLabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20))
paypalLabel.text = "Numéro de compte paypal*"
paypalLabel.tag = 3
self.pX += 20
self.containerView.addSubview(paypalLabel)
// Ajout textField
let paypalTextField = CustomTextField(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 40))
paypalTextField.required = true
paypalTextField.fieldName = "paypalAccountNumber"
paypalTextField.placeholder = "Completer"
paypalTextField.label = "Numéro de compte paypal"
paypalTextField.tag = 3
self.pX += 60
self.containerView.addSubview(paypalTextField)
// Add Validation button
let validationButton = UIButton(frame: CGRect(x: 25, y: CGFloat(pX), width: 335, height: 30.00))
validationButton.setTitle("Valider l'inscription", for: .normal)
validationButton.addTarget(self, action: #selector(self.validSubscription(_:)), for: .touchUpInside)
validationButton.tag = 3
validationButton.setTitleColor(UIView().tintColor, for: .normal)
validationButton.backgroundColor = UIColor.clear
validationButton.titleLabel?.textAlignment = .center
validationButton.titleLabel?.numberOfLines = 0
self.pX += 40
self.containerView.addSubview(validationButton)
self.containerView.addSubview(validationButton)
}
func removeViewWithTag(tag: Int) {
for view in self.containerView.subviews {
if (view.tag == tag) {
view.removeFromSuperview()
}
}
if (tag == 1) {
self.pX -= 200
}
if (tag == 2) {
self.pX -= 360
}
if (tag == 3) {
self.pX -= 120
}
}
func changePaymentWay(_ sender: CustomSegmentedControl) {
var tagToRemove = -1
if (self.selectedPaymentWay == "Compte Bancaire") {
tagToRemove = 1
}
if (self.selectedPaymentWay == "Carte Bancaire") {
tagToRemove = 2
}
if (self.selectedPaymentWay == "Paypal") {
tagToRemove = 3
}
let paymentWay = sender.titleForSegment(at: sender.selectedSegmentIndex)
self.selectedPaymentWay = paymentWay!
if (paymentWay == "Compte Bancaire") {
// Remove actual form of paymentWay
self.removeViewWithTag(tag: tagToRemove)
// Create new form of the new paymentWay
self.createFormCreditAccount()
self.scrollView.contentSize = CGSize(width: 350, height: self.pX + 100)
}
else if (paymentWay == "Carte Bancaire") {
// Remove actual form of paymentWay
self.removeViewWithTag(tag: tagToRemove)
// Create new form of the new paymentWay
self.createFormCreditCard()
self.scrollView.contentSize = CGSize(width: 350, height: self.pX + 100)
}
else if (paymentWay == "Paypal") {
// Remove actual form of paymentWay
self.removeViewWithTag(tag: tagToRemove)
// Create new form of the new paymentWay
self.createFormPaypal()
self.scrollView.contentSize = CGSize(width: 350, height: self.pX + 100)
}
}
func createViewFromJson(json: JsonModel?){
self.jsonModel = json
// Setup interface
DispatchQueue.main.async() {
// Reset the view
self.view.subviews.forEach({ $0.removeFromSuperview() })
// Setup scrollview
self.scrollView = UIScrollView()
self.scrollView.delegate = self
self.view.addSubview(self.scrollView)
self.containerView = UIView()
self.scrollView.addSubview(self.containerView)
// Ajout recapMessage
let recapMessage: UILabel = UILabel(frame: CGRect(x: 20, y: 70, width: 335, height: 20.00));
recapMessage.numberOfLines = 0
recapMessage.text = "Recapitulatif abonnement :"
self.containerView.addSubview(recapMessage)
self.pX = 110
//TODO Display recap of offer choosen and option
// prepare total price
var totalPrice = 0
// affichage offre choisi
let offerMessage: UILabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20.00));
offerMessage.numberOfLines = 0
offerMessage.text = "Offre choisie :"
self.containerView.addSubview(offerMessage)
self.pX += 20
let offerChoosen: UILabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20.00));
offerChoosen.numberOfLines = 0
offerChoosen.text = " • " + (self.person?.serviceOffer?.title)! + "(" + String((self.person?.serviceOffer?.price)!) + "€)"
totalPrice += (self.person?.serviceOffer?.price)!
self.pX += 20
self.containerView.addSubview(offerChoosen)
// affichage option s'il y en a
let numberOfOptions = (self.person?.serviceOptions.count)!
if (numberOfOptions > 0) {
self.pX += 20
let optionLabel: UILabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20.00));
optionLabel.numberOfLines = 0
optionLabel.text = "Option" + (numberOfOptions > 1 ? "s " : " ") + "choisie" + (numberOfOptions > 1 ? "s" : "")
self.pX += 20
self.containerView.addSubview(optionLabel)
// Parcours des options
for option in (self.person?.serviceOptions)! {
let optionChoosen: UILabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20.00));
optionChoosen.numberOfLines = 0
optionChoosen.text = " • " + option.title + "(" + String(option.price) + "€)"
totalPrice += option.price
self.pX += 20
self.containerView.addSubview(optionChoosen)
}
}
// affichage total price
self.pX += 10
let totalPriceLabel: UILabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20.00));
totalPriceLabel.numberOfLines = 0
totalPriceLabel.text = "Prix total à payer : " + String(totalPrice) + "€"
self.pX += 20
self.containerView.addSubview(totalPriceLabel)
//Afficher depuis l'objet person (serviceoffer) le titre de l'option, le prix et prix total
// Ajout paymentMessage
let paymentMessage: UILabel = UILabel(frame: CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 20.00));
paymentMessage.numberOfLines = 0
paymentMessage.text = "Paiement :"
self.containerView.addSubview(paymentMessage)
self.pX += 40
// Choix moyen de paiement
var items : [String] = []
var cpt = 0
for paymentWay in (json?.paymentWays)! {
if (paymentWay == Payment.bankTransfer) {
items.append("Compte Bancaire")
if (cpt == 0) {
self.selectedPaymentWay = "Compte Bancaire"
}
}
else if (paymentWay == Payment.creditCard) {
items.append("Carte Bancaire")
if (cpt == 0) {
self.selectedPaymentWay = "Carte Bancaire"
}
}
else if (paymentWay == Payment.paypal) {
items.append("Paypal")
if (cpt == 0) {
self.selectedPaymentWay = "Paypal"
}
}
cpt += 1
}
let segmentedControl: CustomSegmentedControl = CustomSegmentedControl(items: items);
segmentedControl.label = "Moyen de paiment"
segmentedControl.frame = CGRect(x: 20, y: CGFloat(self.pX), width: 335, height: 30.00);
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(self.changePaymentWay(_:)), for: .valueChanged)
self.containerView.addSubview(segmentedControl)
self.pX += 50
if (items[0] == "Compte Bancaire") {
self.createFormCreditAccount()
}
else if (items[0] == "Carte Bancaire") {
self.createFormCreditCard()
}
else if (items[0] == "Paypal") {
self.createFormPaypal()
}
self.scrollView.contentSize = CGSize(width: 350, height: self.pX + 100)
}
//self.view.frame.size.height = 10000
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
let customPickerView = pickerView as? CustomPickerView
return customPickerView!.pickerData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let customPickerView = pickerView as? CustomPickerView
return customPickerView?.pickerData[row].value
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
}
|
mit
|
9cc87a64fb577be68e490c19d973d2da
| 40.778004 | 175 | 0.594501 | 4.591092 | false | false | false | false |
dcunited001/SpectraNu
|
Spectra/Meshes/BasicTessellation.swift
|
1
|
4048
|
////
//// BasicTessellationGenerators.swift
////
////
//// Created by David Conner on 3/5/16.
////
////
//
//import Foundation
//import Metal
//import ModelIO
//import Swinject
//import simd
//
//public class BasicTessellationGenerators {
// public static func loadMeshGenerators(container: Container) {
//
// }
//}
//
//// TODO: decide on whether the distinction between generators for each
//// primitive should be at the class level
//
//public class MidpointTessellationMeshGen: MeshGenerator {
// public var geometryType: MDLGeometryType = .TypeTriangles
// public var mesh: MDLMesh?
// public var numDivisions: Int = 1 // number of divisions per step
// public var numIterations: Int = 1
//
// // should this require an edge submesh?
// // - if it lacks an edge submesh, it should construct one
//
// // allow user to specify mesh generator instead of a pre-existing mesh?
// // how to specify blocks to handle parameters?
// // - like normals, anisotropy, etc
//
// public required init(container: Container, args: [String: GeneratorArg] = [:]) {
// if let meshKey = args["mesh"] {
// self.mesh = container.resolve(MDLMesh.self, name: meshKey.value)
// }
// if let geoType = args["geometryType"] {
// self.geometryType = .TypeTriangles
// }
// }
//
// public func generate(container: Container, args: [String: GeneratorArg] = [:]) -> MDLMesh {
// return MDLMesh()
// }
//}
//
//public class SierpenskiTessellationMeshGen: MeshGenerator {
// public var geometryType: MDLGeometryType = .TypeTriangles
// public var mesh: MDLMesh?
//
// public required init(container: Container, args: [String: GeneratorArg] = [:]) {
// if let meshKey = args["mesh"] {
// self.mesh = container.resolve(MDLMesh.self, name: meshKey.value)
// }
// if let geoType = args["geometryType"] {
// self.geometryType = .TypeTriangles
// }
//
// }
//
// public func generate(container: Container, args: [String: GeneratorArg] = [:]) -> MDLMesh {
// return MDLMesh()
// }
//}
//
////
//// TriangularQuadTesselationGenerator.swift
//// Pods
////
//// Created by David Conner on 10/22/15.
////
////
//
////import Foundation
////import simd
////
////public class TriangularQuadTesselationGenerator: MeshGenerator {
////
//// var rowCount: Int = 10
//// var colCount: Int = 10
////
//// public required init(args: [String: String] = [:]) {
//// if let rCount = args["rowCount"] {
//// rowCount = Int(rCount)!
//// }
//// if let cCount = args["colCount"] {
//// colCount = Int(cCount)!
//// }
//// }
////
//// public func getData(args: [String: AnyObject] = [:]) -> [String:[float4]] {
//// return [
//// "pos": getVertices(args),
//// "rgba": getColorCoords(args),
//// "tex": getTexCoords(args)
//// ]
//// }
////
//// public func getDataMaps(args: [String: AnyObject] = [:]) -> [String:[[Int]]] {
//// return [
//// "triangle_vertex_map": getTriangleVertexMap(args),
//// "face_vertex_map": getFaceVertexMap(args),
//// "face_triangle_map": getFaceTriangleMap(args)
//// ]
//// }
////
//// public func getVertices(args: [String: AnyObject] = [:]) -> [float4] {
//// return []
//// }
//// public func getColorCoords(args: [String: AnyObject] = [:]) -> [float4] {
//// return []
//// }
//// public func getTexCoords(args: [String: AnyObject] = [:]) -> [float4] {
//// return []
//// }
//// public func getTriangleVertexMap(args: [String: AnyObject] = [:]) -> [[Int]] {
//// return []
//// }
//// public func getFaceTriangleMap(args: [String: AnyObject] = [:]) -> [[Int]] {
//// return []
//// }
//// public func getFaceVertexMap(args: [String: AnyObject] = [:]) -> [[Int]] {
//// return []
//// }
////}
|
mit
|
cc92c73e1b7cc975dd4e2a594f3bd8b9
| 30.387597 | 97 | 0.553854 | 3.611062 | false | false | false | false |
LarsStegman/helios-for-reddit
|
Sources/Model/Comment.swift
|
1
|
1994
|
//
// Comment.swift
// Helios
//
// Created by Lars Stegman on 30-12-16.
// Copyright © 2016 Stegman. All rights reserved.
//
import Foundation
/// A comment
public struct Comment /*: Created, Thing, Votable*/ {
public let id: String
public static let kind: Kind = .comment
public let author: AuthorMetaData
public let distinguished: Distinguishment?
public let linkData: LinkMetaData?
public let parentId: String
public let body: String
public let edited: Edited
public var replies: Listing?
public let createdUtc: Date
public var liked: Vote
public var score: Score
public let moderationProperties: ModerationProperties?
public var saved: Bool
public let subredditData: SubredditMetaData
// public init(from decoder: Decoder) throws {
// let container = try decoder.container(keyedBy: CodingKeys.self)
// }
//
// private enum CodingKeys: String, CodingKey {
// case id
// case author
// case distinguished
// case
// }
public struct LinkMetaData: Decodable {
public let fullname: String
public let title: String
public let url: URL
public let author: String
private enum CodingKeys: String, CodingKey {
case fullname = "link_id"
case title = "link_title"
case url = "link_permalink"
case author = "link_author"
}
}
public struct AuthorMetaData: Decodable {
public let name: String
public let flairText: String?
private enum CodingKeys: String, CodingKey {
case name = "link_author"
case flairText = "author_flair_text"
}
}
public struct SubredditMetaData: Decodable {
public let name: String
public let fullname: String
private enum CodingKeys: String, CodingKey {
case name = "subreddit"
case fullname = "subreddit_id"
}
}
}
|
mit
|
5db26a07802a62ded85e38bc3599b083
| 23.304878 | 73 | 0.621174 | 4.602771 | false | false | false | false |
taoalpha/XMate
|
appcode/X-Mates/HistoryViewController.swift
|
1
|
1276
|
//
// HistoryViewController.swift
// X-Mates
//
// Created by Jiangyu Mao on 4/14/16.
// Copyright © 2016 CloudGroup. All rights reserved.
//
import UIKit
class HistoryViewController: UITableViewController {
@IBOutlet weak var openMenuBar: UIBarButtonItem!
let dummyActivities = ["Running", "Basketball", "Gym Workout", "Running"]
let dummyDates = ["Mar 21, 2016", "Mar 28, 2016", "Mar 29, 2016", " April 3, 2016"]
override func viewDidLoad() {
openMenuBar.target = self.revealViewController()
openMenuBar.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dummyActivities.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("history", forIndexPath: indexPath)
let index = indexPath.row
cell.textLabel?.text = self.dummyActivities[index]
cell.detailTextLabel?.text = self.dummyDates[index]
return cell
}
}
|
mit
|
7c092c0e7e721e0c58a2ac79f4624450
| 29.357143 | 115 | 0.74902 | 4.25 | false | false | false | false |
Mobilette/MobiletteDashboardiOS
|
Pods/PromiseKit/Categories/UIKit/UIActionSheet+Promise.swift
|
18
|
1628
|
import UIKit.UIActionSheet
#if !COCOAPODS
import PromiseKit
#endif
/**
To import the `UIActionSheet` category:
use_frameworks!
pod "PromiseKit/UIKit"
Or `UIKit` is one of the categories imported by the umbrella pod:
use_frameworks!
pod "PromiseKit"
And then in your sources:
import PromiseKit
*/
extension UIActionSheet {
public func promiseInView(view: UIView) -> Promise<Int> {
let proxy = PMKActionSheetDelegate()
delegate = proxy
proxy.retainCycle = proxy
showInView(view)
if numberOfButtons == 1 && cancelButtonIndex == 0 {
NSLog("PromiseKit: An action sheet is being promised with a single button that is set as the cancelButtonIndex. The promise *will* be cancelled which may result in unexpected behavior. See http://promisekit.org/PromiseKit-2.0-Released/ for cancellation documentation.")
}
return proxy.promise
}
public enum Error: CancellableErrorType {
case Cancelled
public var cancelled: Bool {
switch self {
case .Cancelled: return true
}
}
}
}
private class PMKActionSheetDelegate: NSObject, UIActionSheetDelegate {
let (promise, fulfill, reject) = Promise<Int>.pendingPromise()
var retainCycle: NSObject?
@objc func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
defer { retainCycle = nil }
if buttonIndex != actionSheet.cancelButtonIndex {
fulfill(buttonIndex)
} else {
reject(UIActionSheet.Error.Cancelled)
}
}
}
|
mit
|
184edc1aaf7f4491230ed926e3c85788
| 26.59322 | 281 | 0.662776 | 5.024691 | false | false | false | false |
Incipia/Conduction
|
Conduction/Classes/ConductionResource.swift
|
1
|
18104
|
//
// ConductionResource.swift
// Bindable
//
// Created by Leif Meyer on 11/16/17.
//
import Foundation
public enum ConductionResourceState<Parameter, Input, Resource> {
case empty
case fetching(id: ConductionResourceTaskID, priority: Int?, parameter: Parameter?)
case processing(id: ConductionResourceTaskID, priority: Int?, input: Input?)
case fetched(Resource?)
case invalid(Resource?)
// MARK: - Public Properties
public var priority: Int? {
switch self {
case .fetching(_, let priority, _): return priority
case .processing(_, let priority, _): return priority
default: return nil
}
}
public var parameter: Parameter? {
switch self {
case .fetching(_, _, let parameter): return parameter
default: return nil
}
}
public var input: Input? {
switch self {
case .processing(_, _, let input): return input
default: return nil
}
}
public var resource: Resource? {
switch self {
case .fetched(let resource): return resource
default: return nil
}
}
}
public typealias ConductionResourceObserver = UUID
public typealias ConductionResourceTaskID = UUID
public typealias ConductionResourceFetchBlock<Parameter, Input> = (_ parameter: Parameter?, _ priority: Int?, _ completion: @escaping (_ fetchedInput: Input?) -> Void) -> Void
public typealias ConductionResourceTransformBlock<Input, Resource> = (_ input: Input?, _ priority: Int?, _ completion: @escaping (_ resource: Resource?) -> Void) -> Void
public typealias ConductionResourceCommitBlock<Parameter, Input, Resource> = (_ state: ConductionResourceState<Parameter, Input, Resource>, _ nextState: ConductionResourceState<Parameter, Input, Resource>) -> ConductionResourceState<Parameter, Input, Resource>?
public typealias ConductionResourceObserverBlock<Resource> = (_ resource: Resource?) -> Void
fileprivate typealias ConductionResourceObserverEntry<Resource> = (id: ConductionResourceObserver, priority: Int, block: ConductionResourceObserverBlock<Resource>)
open class ConductionBaseResource<Parameter, Input, Resource> {
// MARK: - Private Properties
private var _getBlocks: [ConductionResourceObserverEntry<Resource>] = []
private var _observerBlocks: [ConductionResourceObserverEntry<Resource>] = []
private var _stateObserverBlocks: [(id: ConductionResourceObserver, priority: Int, block: (_ oldState: ConductionResourceState<Parameter, Input, Resource>, _ newState: ConductionResourceState<Parameter, Input, Resource>) -> Void)] = []
private var _getHistory: [ConductionResourceObserver] = []
private var _dispatchKey = DispatchSpecificKey<Void>()
// MARK: - Public Properties
public private(set) var state: ConductionResourceState<Parameter, Input, Resource> = .empty {
didSet {
_stateObserverBlocks.sorted { $0.priority > $1.priority }.forEach { $0.block(oldValue, state) }
}
}
public let dispatchQueue: DispatchQueue
public let defaultPriority: Int
public let fetchBlock: ConductionResourceFetchBlock<Parameter, Input>?
public let transformBlock: ConductionResourceTransformBlock<Input, Resource>?
public let commitBlock: ConductionResourceCommitBlock<Parameter, Input, Resource>
public private(set) var parameter: Parameter?
public private(set) var input: Input?
public private(set) var resource: Resource?
// MARK: - Init
public init(dispatchQueue: DispatchQueue = .main, defaultPriority: Int = 0, fetchBlock: ConductionResourceFetchBlock<Parameter, Input>? = nil, transformBlock: ConductionResourceTransformBlock<Input, Resource>? = nil, commitBlock: @escaping ConductionResourceCommitBlock<Parameter, Input, Resource> = { _, nextState in return nextState }) {
dispatchQueue.setSpecific(key: _dispatchKey, value: ())
self.dispatchQueue = dispatchQueue
self.defaultPriority = defaultPriority
self.fetchBlock = fetchBlock
self.transformBlock = transformBlock
self.commitBlock = commitBlock
}
// MARK: - Public
@discardableResult public func get(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ resource: Resource?) -> Void) -> ConductionResourceObserver {
let observer = observer ?? ConductionResourceObserver()
dispatch {
self.directGet(observer: observer, parameter: parameter, priority: priority, callNow: callNow, completion: completion)
}
return observer
}
@discardableResult public func observe(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ resource: Resource?) -> Void) -> ConductionResourceObserver {
let observer = observer ?? ConductionResourceObserver()
dispatch {
self.directObserve(observer: observer, parameter: parameter, priority: priority, callNow: callNow, completion: completion)
}
return observer
}
@discardableResult public func observeState(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ oldState: ConductionResourceState<Parameter, Input, Resource>, _ newState: ConductionResourceState<Parameter, Input, Resource>) -> Void) -> ConductionResourceObserver {
let observer = observer ?? ConductionResourceObserver()
dispatch {
self.directObserveState(observer: observer, priority: priority, callNow: callNow, completion: completion)
}
return observer
}
public func forget(_ observer: ConductionResourceObserver) {
dispatch {
self.directForget(observer)
}
}
public func forgetAll() {
dispatch {
self.directForgetAll()
}
}
public func check(completion: @escaping (_ state: ConductionResourceState<Parameter, Input, Resource>, _ priority: Int?, _ parameter: Parameter?, _ input: Input?, _ resource: Resource?) -> Void) {
dispatch {
self.directCheck(completion: completion)
}
}
public func load(parameter: Parameter? = nil) {
dispatch {
self.directLoad(parameter: parameter)
}
}
public func reload(parameter: Parameter? = nil) {
dispatch {
self.directReload(parameter: parameter)
}
}
public func clear() {
dispatch {
self.directClear()
}
}
public func expire() {
dispatch {
self.directExpire()
}
}
public func invalidate() {
dispatch {
self.directInvalidate()
}
}
public func setParameter( _ parameter: Parameter?) {
dispatch {
self.directSetParameter(parameter)
}
}
public func setInput( _ input: Input?) {
dispatch {
self.directSetInput(input)
}
}
public func setResource(_ resource: Resource?) {
dispatch {
self.directSetResource(resource)
}
}
public func dispatch(_ block: @escaping () -> Void) {
if DispatchQueue.getSpecific(key: _dispatchKey) != nil {
block()
} else {
dispatchQueue.async {
block()
}
}
}
// MARK: - Direct
open func directTransition(newState: ConductionResourceState<Parameter, Input, Resource>) {
let oldState = state
guard let nextState = commitBlock(oldState, newState) else { return }
state = nextState
switch state {
case .invalid(let resource):
self.resource = resource
_callWaitingBlocks()
forgetAll()
case .empty: break
case .fetching(let id, _, let parameter):
self.parameter = parameter
switch oldState {
case .fetching(let oldID, _, _): guard id != oldID else { return }
default: break
}
_fetch(id: id)
case .processing(let id, _, let input):
self.input = input
switch oldState {
case .processing(let oldID, _, _): guard id != oldID else { return }
default: break
}
_process(id: id)
case .fetched(let resource):
self.resource = resource
_callWaitingBlocks()
}
}
@discardableResult open func directGet(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ resource: Resource?) -> Void) -> ConductionResourceObserver {
let observer = observer ?? ConductionResourceObserver()
guard !_getHistory.contains(observer) else { return observer }
guard !callNow else {
completion(resource)
return observer
}
switch state {
case .invalid: return observer
case .fetched:
guard parameter != nil else {
completion(resource)
return observer
}
fallthrough
default:
let oldPriority = _priority()
_getBlocks = _getBlocks.filter { $0.id != observer }
_getBlocks.append((id: observer, priority: priority ?? defaultPriority, block: completion))
switch state {
case .fetching, .processing:
guard parameter != nil else {
_updatePriority(oldPriority: oldPriority)
return observer
}
fallthrough
default: directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter))
}
}
return observer
}
@discardableResult open func directObserve(observer: ConductionResourceObserver? = nil, parameter: Parameter? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ resource: Resource?) -> Void) -> ConductionResourceObserver {
let observer = observer ?? ConductionResourceObserver()
switch state {
case .invalid: return observer
default:
let oldPriority = _priority()
_observerBlocks = _observerBlocks.filter { $0.id != observer }
_observerBlocks.append((id: observer, priority: priority ?? defaultPriority, block: completion))
_updatePriority(oldPriority: oldPriority)
if let parameter = parameter {
directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter))
} else if callNow {
completion(resource)
} else {
switch state {
case .fetched:
completion(resource)
default: break
}
}
}
return observer
}
@discardableResult open func directObserveState(observer: ConductionResourceObserver? = nil, priority: Int? = nil, callNow: Bool = false, completion: @escaping (_ oldState: ConductionResourceState<Parameter, Input, Resource>, _ newState: ConductionResourceState<Parameter, Input, Resource>) -> Void) -> ConductionResourceObserver {
let observer = observer ?? ConductionResourceObserver()
switch state {
case .invalid: return observer
default:
let oldPriority = _priority()
_stateObserverBlocks = _stateObserverBlocks.filter { $0.id != observer }
_stateObserverBlocks.append((id: observer, priority: priority ?? defaultPriority, block: completion))
_updatePriority(oldPriority: oldPriority)
if callNow {
completion(state, state)
}
}
return observer
}
open func directForget(_ observer: ConductionResourceObserver) {
let oldPriority = _priority()
_getBlocks = _getBlocks.filter { $0.id != observer }
_observerBlocks = _observerBlocks.filter { $0.id != observer }
_stateObserverBlocks = _stateObserverBlocks.filter { $0.id != observer }
_getHistory = _getHistory.filter { $0 != observer }
_updatePriority(oldPriority: oldPriority)
}
open func directForgetAll() {
let oldPriority = _priority()
_getBlocks = []
_observerBlocks = []
_stateObserverBlocks = []
_getHistory = []
_updatePriority(oldPriority: oldPriority)
}
open func directCheck(completion: (_ state: ConductionResourceState<Parameter, Input, Resource>, _ priority: Int?, _ parameter: Parameter?, _ input: Input?, _ resource: Resource?) -> Void) {
completion(state, _priority(), parameter, input, resource)
}
open func directLoad(parameter: Parameter? = nil) {
switch state {
case .invalid: return
case .empty: directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter))
default: break
}
}
open func directReload(parameter: Parameter? = nil) {
switch state {
case .invalid: return
default: directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter))
}
}
open func directClear() {
parameter = nil
input = nil
resource = nil
directExpire()
}
open func directExpire() {
switch state {
case .invalid: return
case .empty: return
default: directTransition(newState: .empty)
}
}
open func directInvalidate() {
switch state {
case .invalid: return
default: directTransition(newState: .invalid(nil))
}
}
open func directSetParameter(_ parameter: Parameter?) {
directTransition(newState: .fetching(id: ConductionResourceTaskID(), priority: _priority(), parameter: parameter))
}
open func directSetInput(_ input: Input?) {
directTransition(newState: .processing(id: ConductionResourceTaskID(), priority: _priority(), input: input))
}
open func directSetResource(_ resource: Resource?) {
directTransition(newState: .fetched(resource))
}
// MARK: - Life Cycle
deinit {
dispatchQueue.setSpecific(key: _dispatchKey, value: nil)
}
// MARK: - Private
private func _priority() -> Int? {
var priority: Int? = nil
priority = _getBlocks.reduce(priority) { result, tuple in
guard let result = result else { return tuple.priority }
return max(result, tuple.priority)
}
priority = _observerBlocks.reduce(priority) { result, tuple in
guard let result = result else { return tuple.priority }
return max(result, tuple.priority)
}
priority = _stateObserverBlocks.reduce(priority) { result, tuple in
guard let result = result else { return tuple.priority }
return max(result, tuple.priority)
}
return priority
}
private func _updatePriority(oldPriority: Int?) {
let newPriority = _priority()
guard oldPriority != newPriority else { return }
switch state {
case .fetching(let id, let priority, let parameter):
guard priority != newPriority else { return }
directTransition(newState: .fetching(id: id, priority: newPriority, parameter: parameter))
case .processing(let id, let priority, let input):
guard priority != newPriority else { return }
directTransition(newState: .processing(id: id, priority: newPriority, input: input))
default: break
}
}
private func _fetch(id: ConductionResourceTaskID) {
guard let fetchBlock = fetchBlock else {
directTransition(newState: .processing(id: ConductionResourceTaskID(), priority: _priority(), input: state.parameter as? Input))
return
}
fetchBlock(state.parameter, state.priority) { input in
self.dispatch {
switch self.state {
case .fetching(let newID, _, _):
guard id == newID else { return }
self.directTransition(newState: .processing(id: ConductionResourceTaskID(), priority: self._priority(), input: input))
default: break
}
}
}
}
private func _process(id: ConductionResourceTaskID) {
guard let transformBlock = transformBlock else {
directTransition(newState: .fetched(state.input as? Resource))
return
}
transformBlock(state.input, state.priority) { resource in
self.dispatch {
switch self.state {
case .processing(let newID, _, _):
guard id == newID else { return }
self.directTransition(newState: .fetched(resource))
default: break
}
}
}
}
private func _callWaitingBlocks() {
var waitingBlocks: [ConductionResourceObserverEntry<Resource>] = _getBlocks
waitingBlocks.append(contentsOf: _observerBlocks)
waitingBlocks.sort { $0.priority > $1.priority }
_getHistory.append(contentsOf: _getBlocks.map { return $0.id })
_getBlocks = []
waitingBlocks.forEach { $0.block(resource) }
}
}
open class ConductionTransformedResource<Input, Resource>: ConductionBaseResource<Void, Input, Resource> {
public init(dispatchQueue: DispatchQueue = .main, defaultPriority: Int = 0, commitBlock: @escaping ConductionResourceCommitBlock<Void, Input, Resource> = { _, nextState in return nextState }, fetchBlock: @escaping ConductionResourceFetchBlock<Void, Input>, transformBlock: @escaping ConductionResourceTransformBlock<Input, Resource>) {
super.init(dispatchQueue: dispatchQueue, defaultPriority: defaultPriority, fetchBlock: fetchBlock, transformBlock: transformBlock, commitBlock: commitBlock)
}
}
open class ConductionResource<Resource>: ConductionBaseResource<Void, Resource, Resource> {
public init(dispatchQueue: DispatchQueue = .main, defaultPriority: Int = 0, commitBlock: @escaping ConductionResourceCommitBlock<Void, Resource, Resource> = { _, nextState in return nextState }, fetchBlock: @escaping ConductionResourceFetchBlock<Void, Resource>) {
super.init(dispatchQueue: dispatchQueue, defaultPriority: defaultPriority, fetchBlock: fetchBlock, commitBlock: commitBlock)
}
}
|
mit
|
00741e0c0a0869384081e82bf5d70a0b
| 37.519149 | 359 | 0.659357 | 4.725659 | false | false | false | false |
eugeneego/utilities-ios
|
Sources/Common/Subscription/Subscriptions.swift
|
1
|
1206
|
//
// Subscriptions
// Legacy
//
// Copyright (c) 2018 Eugene Egorov.
// License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE
//
import Foundation
public class Subscriptions<Value> {
public typealias Listener = (Value) -> Void
private var subscriptions: [String: Listener] = [:] {
didSet {
onChange?()
}
}
public var onChange: (() -> Void)?
public var isEmpty: Bool {
subscriptions.isEmpty
}
public var count: Int {
subscriptions.count
}
public var copy: Subscriptions<Value> {
let copy = Subscriptions<Value>()
copy.subscriptions = subscriptions
copy.onChange = onChange
return copy
}
public init(onChange: (() -> Void)? = nil) {
self.onChange = onChange
}
public func add(_ listener: @escaping Listener) -> Subscription {
let id = UUID().uuidString
let subscription = SimpleSubscription { [weak self] in
self?.subscriptions[id] = nil
}
subscriptions[id] = listener
return subscription
}
public func fire(_ value: Value) {
subscriptions.values.forEach { $0(value) }
}
}
|
mit
|
70b8a456df8c00e3fdaad8665b8bae95
| 21.754717 | 72 | 0.593698 | 4.568182 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/CropRegion.swift
|
1
|
1680
|
//
// CropRegion.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// The part of the image that should remain after cropping.
public enum CropRegion: String {
/// Keep the bottom of the image.
case bottom = "BOTTOM"
/// Keep the center of the image.
case center = "CENTER"
/// Keep the left of the image.
case `left` = "LEFT"
/// Keep the right of the image.
case `right` = "RIGHT"
/// Keep the top of the image.
case top = "TOP"
case unknownValue = ""
}
}
|
mit
|
c3af4ef5251937440874b90a10aed197
| 33.285714 | 81 | 0.714881 | 3.990499 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/WordPressTest/SiteCreation/SiteSegmentsCellTests.swift
|
2
|
2802
|
import XCTest
@testable import WordPress
final class SiteSegmentsCellTests: XCTestCase {
private struct MockValues {
static let identifier = Identifier(value: "101")
static let title = "Blogger"
static let subtitle = "Publish a collection of posts."
static let icon = URL(string: "https://wordpress.com/icon/blogger.png")!
}
private var cell: SiteSegmentsCell?
private var segment: SiteSegment?
override func setUp() {
super.setUp()
let json = Bundle(for: SiteSegmentTests.self).url(forResource: "site-segment", withExtension: "json")!
let data = try! Data(contentsOf: json)
let jsonDecoder = JSONDecoder()
segment = try! jsonDecoder.decode(SiteSegment.self, from: data)
let nib = Bundle.main.loadNibNamed(SiteSegmentsCell.cellReuseIdentifier(), owner: self, options: nil)
cell = nib?.first as? SiteSegmentsCell
}
override func tearDown() {
segment = nil
cell = nil
super.tearDown()
}
func testCellTitleContainsExpectedValue() {
cell?.model = segment
XCTAssertEqual(cell?.title.text, MockValues.title)
}
func testCellSubtitleContainsExpectedValue() {
cell?.model = segment
XCTAssertEqual(cell?.subtitle.text, MockValues.subtitle)
}
func testCellTitleIsTheCorrectFont() {
// SiteSegmentsCell's UILabel has `title.adjustsFontForContentSizeCategory = true`.
// We cannot relaly assert on the Label's font, since it's bond to be changed.
//
// XCTAssertEqual(cell?.title.font, WPStyleGuide.fontForTextStyle(.body, fontWeight: .semibold))
let expectedFont = WPStyleGuide.fontForTextStyle(.body, fontWeight: .semibold)
let actualFont = cell?.title.font
XCTAssertNotNil(actualFont)
XCTAssertEqual(expectedFont.fontName, actualFont!.fontName)
XCTAssertEqual(expectedFont.pointSize, actualFont!.pointSize, accuracy: 0.01)
}
func testCellSubtitleIsTheCorrectFont() {
// This approach fails both locally and on CI
//XCTAssertEqual(cell?.subtitle.font, WPStyleGuide.fontForTextStyle(.callout, fontWeight: .regular))
// This approach passes locally, but fails CI
//XCTAssertNotNil(cell?.subtitle.font)
//XCTAssertEqual(cell?.subtitle.font!, WPStyleGuide.fontForTextStyle(.callout, fontWeight: .regular))
// This approach passes locally
let expectedFont = WPStyleGuide.fontForTextStyle(.callout, fontWeight: .regular)
let actualFont = cell?.subtitle.font
XCTAssertNotNil(actualFont)
XCTAssertEqual(expectedFont.fontName, actualFont!.fontName)
XCTAssertEqual(expectedFont.pointSize, actualFont!.pointSize, accuracy: 0.01)
}
}
|
gpl-2.0
|
173dc89f57eb5919764debbd1c8a738a
| 34.468354 | 110 | 0.68344 | 4.773424 | false | true | false | false |
Ribeiro/IDZSwiftCommonCrypto
|
IDZSwiftCommonCrypto/IDZSwiftCommonCrypto/Utilities.swift
|
1
|
1634
|
//
// Utilities.swift
// IDZSwiftCommonCrypto
//
// Created by idz on 9/21/14.
// Copyright (c) 2014 iOSDeveloperZone.com. All rights reserved.
//
import Foundation
func convertHexDigit(c : UnicodeScalar) -> UInt8
{
switch c {
case UnicodeScalar("0")...UnicodeScalar("9"): return UInt8(c.value - UnicodeScalar("0").value)
case UnicodeScalar("a")...UnicodeScalar("f"): return UInt8(c.value - UnicodeScalar("a").value + 0xa)
case UnicodeScalar("A")...UnicodeScalar("F"): return UInt8(c.value - UnicodeScalar("A").value + 0xa)
default: fatalError("convertHexDigit: Invalid hex digit")
}
}
public func arrayFromHexString(s : String) -> [UInt8]
{
var g = s.unicodeScalars.generate()
var a : [UInt8] = []
while let msn = g.next()
{
if let lsn = g.next()
{
a += [ (convertHexDigit(msn) << 4 | convertHexDigit(lsn)) ]
}
else
{
fatalError("arrayFromHexString: String must contain even number of characters")
}
}
return a
}
public func dataFromHexString(s : String) -> NSData
{
let a = arrayFromHexString(s)
return NSData(bytes:a, length:a.count)
}
public func dataFromByteArray(a : [UInt8]) -> NSData
{
return NSData(bytes:a, length:a.count)
}
public func hexStringFromArray(a : [UInt8], uppercase : Bool = false) -> String
{
return a.map() { String(format:uppercase ? "%02X" : "%02x", $0) }.reduce("", +)
}
public func hexNSStringFromArray(a : [UInt8], uppercase : Bool = false) -> NSString
{
return a.map() { String(format:uppercase ? "%02X" : "%02x", $0) }.reduce("", +)
}
|
mit
|
7a008de88be17aab515f9816376105b4
| 26.711864 | 108 | 0.619339 | 3.544469 | false | false | false | false |
NobodyNada/SwiftStack
|
Tests/SwiftStackTests/AnswersTests.swift
|
1
|
6151
|
//
// AnswersTests.swift
// SwiftStack
//
// Created by FelixSFD on 14.01.17.
//
//
import XCTest
class AnswersTests: APITests {
// - MARK: Test answers
func testFetchAnswerSync() {
let id = 13371337
client.onRequest { task in
return ("{\"items\": [{\"answer_id\": \(id)}]}".data(using: .utf8), self.blankResponse(task), nil)
}
do {
let response = try client.fetchAnswer(id)
XCTAssertNotNil(response.items, "items is nil")
XCTAssertEqual(response.items?.first?.post_id, id, "id was incorrect")
} catch {
print(error)
XCTFail("fetchAnswer threw an error")
}
}
func testFetchAnswerAsync() {
expectation = expectation(description: "Fetched answer")
let id = 13371337
client.onRequest { task in
return ("{\"items\": [{\"answer_id\": \(id)}]}".data(using: .utf8), self.blankResponse(task), nil)
}
client.fetchAnswer(id, parameters: [:], backoffBehavior: .wait) {
response, error in
if error != nil {
print(error!)
XCTFail("Answer not fetched")
return
}
if response?.items?.first?.answer_id == id {
self.expectation?.fulfill()
} else {
print(response?.items ?? "no items")
XCTFail("id was incorrect")
}
}
waitForExpectations(timeout: 10, handler: nil)
}
// - MARK: Test all answers
func testFetchAllAnswersSync() {
let id = 13371337
client.onRequest { task in
return ("{\"items\": [{\"answer_id\": \(id)}]}".data(using: .utf8), self.blankResponse(task), nil)
}
do {
let response = try client.fetchAnswers()
XCTAssertNotNil(response.items, "items is nil")
XCTAssertEqual(response.items?.first?.answer_id, id, "id was incorrect")
} catch {
print(error)
XCTFail("fetchAnswers threw an error")
}
}
func testFetchAllAnswersAsync() {
expectation = expectation(description: "Fetched answers")
let id = 13371337
client.onRequest { task in
return ("{\"items\": [{\"answer_id\": \(id)}]}".data(using: .utf8), self.blankResponse(task), nil)
}
client.fetchAnswers(parameters: [:], backoffBehavior: .wait) {
response, error in
if error != nil {
print(error!)
XCTFail("Answers not fetched")
return
}
if response?.items?.first?.answer_id == id {
self.expectation?.fulfill()
} else {
print(response?.items ?? "no items")
XCTFail("id was incorrect")
}
}
waitForExpectations(timeout: 10, handler: nil)
}
// - MARK: Test comments on answer
func testFetchCommentsOnAnswerSync() {
let id = 41463556
client.onRequest { task in
return ("{\"items\": [{\"post_id\": \(id), \"comment_id\": 13371337}]}".data(using: .utf8), self.blankResponse(task), nil)
}
do {
let response = try client.fetchCommentsOn(answer: id)
XCTAssertNotNil(response.items, "items is nil")
XCTAssertEqual(response.items?.first?.post_id, id, "id was incorrect")
} catch {
print(error)
XCTFail("fetchCommentsOn(answer:) threw an error")
}
}
func testFetchCommentsOnAnswerAsync() {
expectation = expectation(description: "Fetched comments")
let id = 41463556
client.onRequest { task in
return ("{\"items\": [{\"post_id\": \(id), \"comment_id\": 13371337}]}".data(using: .utf8), self.blankResponse(task), nil)
}
client.fetchCommentsOn(answer: id, parameters: [:], backoffBehavior: .wait) {
response, error in
if error != nil {
print(error!)
XCTFail("Comments not fetched")
return
}
if response?.items?.first?.post_id == id {
self.expectation?.fulfill()
} else {
print(response?.items ?? "no items")
XCTFail("id was incorrect")
}
}
waitForExpectations(timeout: 10, handler: nil)
}
// - MARK: Test questions of answers
func testFetchQuestionOfAnswerSync() {
let id = 13371337
client.onRequest { task in
return ("{\"items\": [{\"question_id\": \(id)}]}".data(using: .utf8), self.blankResponse(task), nil)
}
do {
let response = try client.fetchQuestionOfAnswer(id)
XCTAssertNotNil(response.items, "items is nil")
XCTAssertEqual(response.items?.first?.question_id, id, "id was incorrect")
} catch {
print(error)
XCTFail("fetchQuestion threw an error")
}
}
func testFetchQuestionOfAnswerAsync() {
expectation = expectation(description: "Fetched question")
let id = 13371337
client.onRequest { task in
return ("{\"items\": [{\"question_id\": \(id)}]}".data(using: .utf8), self.blankResponse(task), nil)
}
client.fetchQuestionOfAnswer(id, parameters: [:], backoffBehavior: .wait) {
response, error in
if error != nil {
print(error!)
XCTFail("Question not fetched")
return
}
if response?.items?.first?.question_id == id {
self.expectation?.fulfill()
} else {
print(response?.items ?? "no items")
XCTFail("id was incorrect")
}
}
waitForExpectations(timeout: 10, handler: nil)
}
}
|
mit
|
1e9c95c62889b01949fa24c9aa97c406
| 28.714976 | 134 | 0.508047 | 4.72427 | false | true | false | false |
YouYue123/CarouselViewController
|
CarouselExample/Pods/CarouselViewController/Carousel/Carousel/CarouselViewController.swift
|
2
|
5282
|
//
// CarousellViewController.swift
//
// Created by youyue on 16/3/16.
// Copyright © 2016 youyue. All rights reserved.
//
import UIKit
public class CarouselViewController: UIPageViewController {
public var carouselViewControllerDelegate: CarouselViewControllerDelegate?
private var imageAmount : Int?
private var orderedViewControllers = [UIViewController]()
public func setCarouselImage(amount:Int){
self.imageAmount = amount
orderedViewControllers = [UIViewController]()
for var i in 1...amount{
guard let _ = UIImage(named: "CarouselImage\(i)") else{
i = i + 1 - 1
fatalError("Please set correct image name")
}
orderedViewControllers.append(self.newViewController(i))
}
}
override public init(transitionStyle: UIPageViewControllerTransitionStyle, navigationOrientation: UIPageViewControllerNavigationOrientation, options: [String : AnyObject]?) {
super.init(transitionStyle: transitionStyle, navigationOrientation: navigationOrientation, options: options)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
if let firstViewController = orderedViewControllers.first {
self.setViewControllers([firstViewController],
direction: .Forward,
animated: true,
completion: nil)
}
}
private func newViewController(sequence: Int) -> UIViewController {
let uiViewController = UIViewController()
uiViewController.view.frame = self.view.frame
let imageView = UIImageView()
imageView.image = UIImage(named: "CarouselImage\(sequence)")
imageView.frame = uiViewController.view.frame
uiViewController.view.addSubview(imageView)
return uiViewController
}
private func notifyCarouselDelegateOfNewIndex() {
if let firstViewController = viewControllers?.first,
let index = orderedViewControllers.indexOf(firstViewController) {
carouselViewControllerDelegate?.carouselPageViewController(didUpdatePageIndex: index)
}
}
}
// MARK: UIPageViewControllerDataSource
extension CarouselViewController: UIPageViewControllerDataSource {
public func pageViewController(pageViewController: UIPageViewController,
viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
// User is on the first view controller and swiped left to loop to
// the last view controller.
guard previousIndex >= 0 else {
return orderedViewControllers.last
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
public func pageViewController(pageViewController: UIPageViewController,
viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
// User is on the last view controller and swiped right to loop to
// the first view controller.
guard orderedViewControllersCount != nextIndex else {
return orderedViewControllers.first
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
}
//Mark: PageViewController Delegate
extension CarouselViewController : UIPageViewControllerDelegate{
public func pageViewController(pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
notifyCarouselDelegateOfNewIndex()
}
}
public protocol CarouselViewControllerDelegate {
/**
Called when the current index is updated.
- parameter carouselPageViewController: the TutorialPageViewController instance
- parameter index: the index of the currently visible page.
*/
func carouselPageViewController(didUpdatePageIndex index: Int)
}
|
mit
|
aa28343d555b7aa1e7e5cc6d3e0e9b07
| 31.207317 | 178 | 0.628669 | 6.814194 | false | false | false | false |
marklin2012/iOS_Animation
|
Section1/Chapter3/O2UIViewAnimation_starter/O2UIViewAnimation/ViewController.swift
|
2
|
5465
|
//
// ViewController.swift
// O2UIViewAnimation
//
// Created by O2.LinYi on 16/3/10.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
// a delay function
func delay(seconds seconds: Double, completion: () -> ()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * seconds))
dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
completion()
}
}
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var loginBtn: UIButton!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var headingLabel: UILabel!
@IBOutlet weak var cloud1: UIImageView!
@IBOutlet weak var cloud2: UIImageView!
@IBOutlet weak var cloud3: UIImageView!
@IBOutlet weak var cloud4: UIImageView!
// MARK: - further UI
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
let status = UIImageView(image: UIImage(named: "banner"))
let label = UILabel()
let messages = ["Connectiong ...", "Authorizing ...", "Sending credentials ...", "Failed"]
// MARK: - Lift cycle
override func viewDidLoad() {
super.viewDidLoad()
// set up the UI
loginBtn.layer.cornerRadius = 8.0
loginBtn.layer.masksToBounds = true
spinner.frame = CGRect(x: -20, y: 6, width: 20, height: 20)
spinner.startAnimating()
spinner.alpha = 0
loginBtn.addSubview(spinner)
status.hidden = true
status.center = loginBtn.center
view.addSubview(status)
label.frame = CGRect(x: 0, y: 0, width: status.frame.size.width, height: status.frame.size.height)
label.font = UIFont(name: "HelveticaNeue", size: 18)
label.textColor = UIColor(red: 0.89, green: 0.38, blue: 0, alpha: 1)
label.textAlignment = .Center
status.addSubview(label)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// set first position to move out the screen
headingLabel.center.x -= view.bounds.width
usernameField.center.x -= view.bounds.width
passwordField.center.x -= view.bounds.width
cloud1.alpha = 0.0
cloud2.alpha = 0.0
cloud3.alpha = 0.0
cloud4.alpha = 0.0
loginBtn.center.y += 30
loginBtn.alpha = 0
// present animation
UIView.animateWithDuration(0.5) { () -> Void in
self.headingLabel.center.x += self.view.bounds.width
// usernameField.center.x += view.bounds.width
}
UIView.animateWithDuration(0.5, delay: 0.3, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: { () -> Void in
self.usernameField.center.x += self.view.bounds.width
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.4, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [.CurveEaseInOut
], animations: { () -> Void in
self.passwordField.center.x += self.view.bounds.width
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.5, options: [], animations: { () -> Void in
self.cloud1.alpha = 1
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.7, options: [], animations: { () -> Void in
self.cloud2.alpha = 1
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.9, options: [], animations: { () -> Void in
self.cloud3.alpha = 1
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 1.1, options: [], animations: { () -> Void in
self.cloud4.alpha = 1
}, completion: nil)
UIView.animateWithDuration(0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [], animations: { () -> Void in
self.loginBtn.center.y -= 30
self.loginBtn.alpha = 1.0
}, completion: nil)
}
// MARK: - further methods
@IBAction func login() {
view.endEditing(true)
// add animation
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: [], animations: { () -> Void in
self.loginBtn.bounds.size.width += 80
}, completion: nil)
UIView.animateWithDuration(0.33, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in
self.loginBtn.center.y += 60
self.loginBtn.backgroundColor = UIColor(red: 0.85, green: 0.83, blue: 0.45, alpha: 1)
self.spinner.center = CGPoint(x: 40, y: self.loginBtn.frame.size.height/2)
self.spinner.alpha = 1
}, completion: nil)
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
let nextField = (textField === usernameField) ? passwordField : usernameField
nextField.becomeFirstResponder()
return true
}
}
|
mit
|
a2cfb630ee2756b8ab23249710e6afb9
| 34.012821 | 147 | 0.592274 | 4.437043 | false | false | false | false |
Aioria1314/WeiBo
|
WeiBo/WeiBo/Classes/Tools/Extension/UIView+ZXCExtension.swift
|
1
|
1236
|
//
// UIView+ZXCExtension.swift
// WeiBo
//
// Created by Aioria on 2017/3/26.
// Copyright © 2017年 Aioria. All rights reserved.
//
import UIKit
extension UIView {
var x: CGFloat {
get {
return frame.origin.x
}
set {
frame.origin.x = newValue
}
}
var y: CGFloat {
get {
return frame.origin.y
}
set {
frame.origin.y = newValue
}
}
var centerX: CGFloat {
get {
return center.x
}
set {
center.x = newValue
}
}
var centerY: CGFloat {
get {
return center.y
}
set {
center.y = newValue
}
}
var width: CGFloat {
get {
return frame.size.width
}
set {
frame.size.width = newValue
}
}
var height: CGFloat {
get {
return frame.size.height
}
set {
frame.size.height = newValue
}
}
var size: CGSize {
get {
return frame.size
}
set {
frame.size = newValue
}
}
}
|
mit
|
9d8a5f68450f8639e68d78712bc054e2
| 15.44 | 50 | 0.411192 | 4.467391 | false | false | false | false |
milseman/swift
|
stdlib/public/SDK/AVFoundation/AVCaptureDevice.swift
|
3
|
1342
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import AVFoundation // Clang module
import Foundation
#if os(iOS)
internal protocol _AVCaptureDeviceFormatSupportedColorSpaces {
@available(iOS, introduced: 10.0)
var __supportedColorSpaces: [NSNumber] { get }
}
extension _AVCaptureDeviceFormatSupportedColorSpaces {
@available(swift, obsoleted: 4.0)
@available(iOS, introduced: 10.0)
@nonobjc
public var supportedColorSpaces: [NSNumber]! {
return __supportedColorSpaces
}
@available(swift, introduced: 4.0)
@available(iOS, introduced: 10.0)
@nonobjc
public var supportedColorSpaces: [AVCaptureColorSpace] {
return __supportedColorSpaces.map { AVCaptureColorSpace(rawValue: $0.intValue)! }
}
}
@available(iOS, introduced: 10.0)
extension AVCaptureDevice.Format : _AVCaptureDeviceFormatSupportedColorSpaces {
}
#endif
|
apache-2.0
|
046d5b824930281a0a391f2eb9f62edb
| 28.822222 | 85 | 0.658718 | 4.458472 | false | false | false | false |
CherishSmile/ZYBase
|
ZYBase/Tools/ZYCustomeAlert/ExampleAlert/ZYCustomSelectAlert.swift
|
1
|
2641
|
//
// ZYCustomSelectAlert.swift
// ZYBase
//
// Created by Mzywx on 2017/3/1.
// Copyright © 2017年 Mzywx. All rights reserved.
//
import UIKit
public typealias ZYSelectAlertCompletionClosure = (Int) -> Void
open class ZYCustomSelectAlert: UIView,UITableViewDelegate,UITableViewDataSource {
public var titleArr : Array<String>!
public var completion : ZYSelectAlertCompletionClosure?
lazy var selectTab: UITableView = {
let tab = UITableView(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH-100, height: CGFloat(self.titleArr.count)*getPtH(80)), style: .plain)
tab.backgroundColor = .white
tab.layer.masksToBounds = true
tab.layer.cornerRadius = 4.0
tab.delegate = self
tab.dataSource = self
tab.bounces = false
return tab
}()
public init(_ title:String,_ selectTitles:Array<String>,_ completion:@escaping ZYSelectAlertCompletionClosure) {
super.init(frame: .zero)
self.completion = completion
titleArr = selectTitles
titleArr.insert(title, at: 0)
self.frame = CGRect(x: 50, y: (SCREEN_HEIGHT-CGFloat(self.titleArr.count)*getPtH(80))/2, width: SCREEN_WIDTH-100, height: CGFloat(self.titleArr.count)*getPtH(80))
self.addSubview(selectTab)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleArr.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cellID")
}
if indexPath.row>0 {
cell?.textLabel?.textColor = .blue;
}
cell?.textLabel?.text = titleArr[indexPath.row]
cell?.textLabel?.font = getFont(getPtW(30))
return cell!
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row>0 {
if completion != nil {
completion!(indexPath.row)
}
dismissZYAlert()
}
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return getPtH(80)
}
}
|
mit
|
076ae5ebf1334fd97876430b44d2be51
| 33.710526 | 170 | 0.643669 | 4.404007 | false | false | false | false |
jmayoralas/Sems
|
Sems/Bus/Bus16.swift
|
1
|
3504
|
//
// Bus.swift
// Z80VirtualMachineKit
//
// Created by Jose Luis Fernandez-Mayoralas on 1/5/16.
// Copyright © 2016 lomocorp. All rights reserved.
//
import Foundation
import JMZeta80
class Bus16 : BusBase, AccessibleBus {
private var paged_components : [BusComponentBase]
private var io_components : [BusComponentBase]
private var clock: Clock
init(clock: Clock, screen: VmScreen) {
self.clock = clock
let dummy_component = BusComponent(base_address: 0x0000, block_size: 0x0000)
let io_dummy_component = VoidBusComponent(
base_address: 0x0000,
block_size: 0x0000,
clock: clock,
screen: screen
)
paged_components = Array(repeating: dummy_component, count: 64)
io_components = Array(repeating: io_dummy_component, count: 0x100)
super.init(base_address: 0x0000, block_size: 0x10000)
}
override func addBusComponent(_ bus_component: BusComponentBase) {
super.addBusComponent(bus_component)
for component in self.bus_components {
let start = Int(component.getBaseAddress() / 1024)
let end = start + component.getBlockSize() / 1024 - 1
for i in start...end {
paged_components[i] = component
}
}
}
func addIOBusComponent(_ bus_component: BusComponentBase) {
// only asign non ula bus components to odd ports
if bus_component.getBaseAddress() & 0x01 == 1 {
io_components[Int(bus_component.getBaseAddress())] = bus_component
} else {
if bus_component is ULAIo {
// even ports belongs to ULA
for i in 0..<0x100 {
if (i & 0x01) == 0 {
io_components[i] = bus_component
}
}
}
}
}
override func write(_ address: UInt16, value: UInt8) {
let index_component = Int(address) / 1024
paged_components[index_component].write(address, value: value)
super.write(address, value: value)
}
override func read(_ address: UInt16) -> UInt8 {
let _ = super.read(address)
let index_component = (Int(address) & 0xFFFF) / 1024
let data = paged_components[index_component].read(address)
return data
}
func ioRead(_ address: UInt16) -> UInt8 {
clock.applyIOContention(address: address)
let _ = super.read(address)
// port addressed by low byte of address
last_data = io_components[Int(address & 0x00FF)].read(address)
return last_data
}
func ioWrite(_ address: UInt16, value: UInt8) {
clock.applyIOContention(address: address)
// port addressed by low byte of address
io_components[Int(address & 0x00FF)].write(address, value: value)
}
override func dumpFromAddress(_ fromAddress: Int, count: Int) -> [UInt8] {
var index_component = (fromAddress & 0xFFFF) / 1024
var address = fromAddress
var result = [UInt8]()
while result.count < count {
result = result + paged_components[index_component].dumpFromAddress(address, count: count - result.count)
index_component += 1
address += result.count
}
return result
}
}
|
gpl-3.0
|
bca528772a5ac168ef1e9c16d11a324d
| 30 | 117 | 0.570083 | 4.24092 | false | false | false | false |
Chaatz/iOSSwiftHelpers
|
Sources/ScheduledTimer.swift
|
1
|
5419
|
//
// ScheduledTimer.swift
// chaatz
//
// Created by Mingloan Chan on 6/3/2016.
// Copyright © 2016 Chaatz. All rights reserved.
//
import Foundation
@objc class ScheduledTimer: NSObject {
fileprivate var privateTimer: Timer?
fileprivate var gcdTimer: DispatchSourceTimer?
fileprivate var executionBlock: ((Timer?) -> ()) = { _ in }
@objc class func schedule(_ intervalFromNow: TimeInterval, block: @escaping (Timer?) -> (), timerObject: ((ScheduledTimer) -> ())? = nil) {
let sTimer = ScheduledTimer()
if #available(iOS 10.0, *) { }
else {
sTimer.executionBlock = block
}
if !Thread.isMainThread {
// Use GCD Timer
let timer =
DispatchSource.makeTimerSource(
flags: DispatchSource.TimerFlags(rawValue: UInt(0)),
queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))
timer.scheduleOneshot(deadline: DispatchTime.now() + intervalFromNow)
timer.setEventHandler {
block(nil)
if let timer = sTimer.gcdTimer {
timer.cancel()
}
}
sTimer.gcdTimer = timer
timerObject?(sTimer)
timer.resume()
}
else {
// Use NSTimer
if #available(iOS 10.0, *) {
let timer = Timer.scheduledTimer(withTimeInterval: intervalFromNow, repeats: false) { t in
block(t)
}
sTimer.privateTimer = timer
timerObject?(sTimer)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}
else {
let timer =
Timer.scheduledTimer(
timeInterval: intervalFromNow,
target: sTimer,
selector: #selector(execute(_:)),
userInfo: nil,
repeats: false)
sTimer.privateTimer = timer
timerObject?(sTimer)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}
}
}
@objc class func schedule(every interval: TimeInterval, block: @escaping (Timer?) -> (), timerObject: ((ScheduledTimer) -> ())? = nil) {
let sTimer = ScheduledTimer()
sTimer.executionBlock = block
if !Thread.isMainThread {
// Use GCD Timer
let timer =
DispatchSource.makeTimerSource(
flags: DispatchSource.TimerFlags(rawValue: UInt(0)),
queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))
let deadline = DispatchTime.now() + interval
timer.scheduleRepeating(deadline: deadline, interval: interval)
timer.setEventHandler {
block(nil)
}
sTimer.gcdTimer = timer
timerObject?(sTimer)
timer.resume()
}
else {
// Use NSTimer
if #available(iOS 10.0, *) {
let timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { t in
block(t)
}
sTimer.privateTimer = timer
timerObject?(sTimer)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}
else {
let timer =
Timer.scheduledTimer(
timeInterval: interval,
target: sTimer,
selector: #selector(execute(_:)),
userInfo: nil,
repeats: true)
sTimer.privateTimer = timer
timerObject?(sTimer)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}
}
}
@objc fileprivate func execute(_ timer: Timer) {
executionBlock(timer)
}
@objc func invalidate() {
if !Thread.isMainThread {
if let timer = gcdTimer {
timer.cancel()
}
}
else {
privateTimer?.invalidate()
}
}
@objc class func add(timer t: ScheduledTimer, to: RunLoop, forMode mode: RunLoopMode) {
if let timer = t.privateTimer {
to.add(timer, forMode: mode)
}
}
}
extension Int {
var degreesToRadians : CGFloat {
return CGFloat(self) * CGFloat(M_PI) / 180.0
}
var second: TimeInterval { return TimeInterval(self) }
var seconds: TimeInterval { return TimeInterval(self) }
var minute: TimeInterval { return TimeInterval(self * 60) }
var minutes: TimeInterval { return TimeInterval(self * 60) }
var hour: TimeInterval { return TimeInterval(self * 3600) }
var hours: TimeInterval { return TimeInterval(self * 3600) }
}
extension Double {
var second: TimeInterval { return self }
var seconds: TimeInterval { return self }
var minute: TimeInterval { return self * 60 }
var minutes: TimeInterval { return self * 60 }
var hour: TimeInterval { return self * 3600 }
var hours: TimeInterval { return self * 3600 }
}
|
mit
|
3467fbb060fa96b85180b835a5452c9e
| 32.036585 | 143 | 0.51698 | 5.174785 | false | false | false | false |
Moriquendi/WWDC15-Portfolio
|
WWDC15/WWDC15/Code/Controllers/CirclesEditorViewController.swift
|
1
|
5498
|
//
// CirclesEditorViewController.swift
// WWDC15
//
// Created by Michal Smialko on 19/04/15.
// Copyright (c) 2015 Michal Smialko. All rights reserved.
//
import UIKit
class CirclesEditorViewController: UIViewController {
var selectedIndex = -1 {
willSet {
self.deselectCirle()
}
didSet {
self.selectCircle()
}
}
var circles: Array<CircleView>
@IBOutlet weak var slider: UISlider!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
self.circles = []
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
self.circles = []
super.init(coder: aDecoder)
}
// MARK: UIViewController
func selectedCircle() -> CircleView? {
if (self.selectedIndex >= 0 && self.selectedIndex < self.circles.count) {
return self.circles[self.selectedIndex]
}
return nil
}
func deselectCirle() {
self.selectedCircle()?.selected = false
}
func selectCircle() {
self.selectedCircle()?.selected = true
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadCircles()
}
func loadCircles() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
let documentsDirectory: NSString = paths[0] as! NSString
let plistPath = documentsDirectory.stringByAppendingPathComponent("points.plist")
let data = NSArray(contentsOfFile: plistPath)
data?.enumerateObjectsUsingBlock({ (object: AnyObject!, index: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
let dict = object as! Dictionary<String, CGFloat>
let center = CGPointMake(dict["x"]!, dict["y"]!)
let size = dict["size"]!
let circle = self.addNewCircleWithSize(size, text: String(index), center: center)
let hue = CGFloat(((40 + index*4) % 360 ))/360
circle.backgroundColor = UIColor(hue: hue,
saturation: 0.70,
brightness: 0.84,
alpha: 0.8)
circle.label.hidden = true
})
}
func addNewCircleWithSize(size: CGFloat, text: String, center: CGPoint) -> CircleView {
let newCircle = CircleView()
newCircle.frame = CGRectMake(0, 0, size, size)
newCircle.label.text = String(circles.count)
circles.append(newCircle)
self.view.addSubview(newCircle)
newCircle.center = center
return newCircle
}
@IBAction func didTapAddNew(sender: AnyObject) {
self.addNewCircleWithSize(CGFloat(100),
text: String(circles.count),
center: CGPointMake(CGRectGetMidX(self.view.bounds),
CGRectGetMidY(self.view.bounds)))
self.selectedIndex = self.circles.count - 1
self.slider.value = 100
}
@IBAction func didChangeSize(slider: UISlider) {
if self.selectedIndex >= 0 && self.selectedIndex < self.circles.count {
let view = circles[self.selectedIndex]
let oldCenter = view.center
view.frame = CGRectMake(0, 0, CGFloat(slider.value), CGFloat(slider.value))
view.center = oldCenter
}
}
@IBAction func didChangeSelectedCircleIndex(sender: UITextField) {
if let circleIndex = sender.text.toInt() {
self.selectedIndex = circleIndex
}
else {
self.selectedIndex = -1
}
}
@IBAction func tapRecognized(tap: UITapGestureRecognizer) {
let point = tap.locationInView(self.view)
for (index, view) in enumerate(self.circles) {
if (CGRectContainsPoint(view.frame, point)) {
self.selectedIndex = index
break
}
}
}
@IBAction func panGestureRecognized(pan: UIPanGestureRecognizer) {
let circle = self.selectedCircle()
if (pan.state == UIGestureRecognizerState.Ended) {
circle?.frame = CGRectApplyAffineTransform(circle!.frame, circle!.transform)
circle?.transform = CGAffineTransformIdentity
}
else {
let translation = pan.translationInView(self.view)
circle?.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, translation.x, translation.y)
}
}
@IBAction func didTapSave(sender: AnyObject) {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
let documentsDirectory: NSString = paths[0] as! NSString
let plistPath = documentsDirectory.stringByAppendingPathComponent("points.plist")
let manager = NSFileManager.defaultManager()
manager.createFileAtPath(plistPath, contents: nil, attributes: nil)
let content = NSMutableArray()
for (index, view) in enumerate(self.circles) {
let dict = ["x" : view.center.x,
"y" : view.center.y,
"size" : view.bounds.size.width]
content.addObject(dict)
}
content.writeToFile(plistPath, atomically: false)
println("Saved to \(plistPath)")
}
}
|
mit
|
5d111c8870638befe8ce8296aeb82889
| 32.938272 | 124 | 0.591488 | 5.030192 | false | false | false | false |
HabitRPG/habitrpg-ios
|
Habitica Database/Habitica Database/Models/User/RealmUserNewMessages.swift
|
1
|
866
|
//
// RealmUserNewMessages.swift
// Habitica Database
//
// Created by Phillip Thelen on 13.06.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmUserNewMessages: Object, UserNewMessagesProtocol {
@objc dynamic var combinedID: String?
@objc dynamic var userID: String?
var id: String?
var name: String?
var hasNewMessages: Bool = false
override static func primaryKey() -> String {
return "combinedID"
}
convenience init(userID: String?, protocolObject: UserNewMessagesProtocol) {
self.init()
self.combinedID = (userID ?? "") + (protocolObject.id ?? "")
self.userID = userID
id = protocolObject.id
name = protocolObject.name
hasNewMessages = protocolObject.hasNewMessages
}
}
|
gpl-3.0
|
e19bcd9a064daa05bdadaf93986a0127
| 26.03125 | 80 | 0.67052 | 4.435897 | false | false | false | false |
giangbvnbgit128/AnViet
|
AnViet/Class/Helpers/Extensions/UIImage.swift
|
1
|
9552
|
//
// UIImage.swift
// TLSafone
//
// Created by Alexey Globchastyy on 15/09/14.
// Copyright (c) 2014 Alexey Globchastyy. All rights reserved.
//
import UIKit
import Accelerate
public extension UIImage {
/**
Applies a lightening (blur) effect to the image
- returns: The lightened image, or nil if error.
*/
public func applyLightEffect() -> UIImage? {
return applyBlurWithRadius(30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8)
}
/**
Applies an extra lightening (blur) effect to the image
- returns: The extra lightened image, or nil if error.
*/
public func applyExtraLightEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8)
}
/**
Applies a darkening (blur) effect to the image.
- returns: The darkened image, or nil if error.
*/
public func applyDarkEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8)
}
/**
Tints the image with the given color.
- parameter tintColor: The tint color
- returns: The tinted image, or nil if error.
*/
public func applyTintEffectWithColor(_ tintColor: UIColor) -> UIImage? {
let effectColorAlpha: CGFloat = 0.6
var effectColor = tintColor
let componentCount = tintColor.cgColor.numberOfComponents
if componentCount == 2 {
var b: CGFloat = 0
if tintColor.getWhite(&b, alpha: nil) {
effectColor = UIColor(white: b, alpha: effectColorAlpha)
}
} else {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) {
effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha)
}
}
return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil)
}
/**
Core function to create a new image with the given blur.
- parameter blurRadius: The blur radius
- parameter tintColor: The color to tint the image; optional.
- parameter saturationDeltaFactor: The delta by which to change the image saturation
- parameter maskImage: An optional image mask.
- returns: The adjusted image, or nil if error.
*/
public func applyBlurWithRadius(_ blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
//Check pre-conditions.
if size.width < 1 || size.height < 1 {
print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)")
return nil
}
guard let cgImage = self.cgImage else {
print("*** error: image must be backed by a CGImage: \(self)")
return nil
}
if maskImage != nil && maskImage!.cgImage == nil {
print("*** error: maskImage must be backed by a CGImage: \(maskImage)")
return nil
}
let __FLT_EPSILON__ = CGFloat(FLT_EPSILON)
let screenScale = UIScreen.main.scale
let imageRect = CGRect(origin: CGPoint.zero, size: size)
var effectImage = self
let hasBlur = blurRadius > __FLT_EPSILON__
let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__
if hasBlur || hasSaturationChange {
func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
let data = context.data
let width = context.width
let height = context.height
let rowBytes = context.bytesPerRow
return vImage_Buffer(data: data, height: UInt(height), width: UInt(width), rowBytes: rowBytes)
}
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
guard let effectInContext = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return self
}
effectInContext.scaleBy(x: 1.0, y: -1.0)
effectInContext.translateBy(x: 0, y: -size.height)
effectInContext.draw(cgImage, in: imageRect)
var effectInBuffer = createEffectBuffer(effectInContext)
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
guard let effectOutContext = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return self
}
var effectOutBuffer = createEffectBuffer(effectOutContext)
if hasBlur {
// A description of how to compute the box kernel width from the Gaussian
// radius (aka standard deviation) appears in the SVG spec:
// http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
// For larger values of 's' (s >= 2.0), an approximation can be used: Three
// successive box-blurs build a piece-wise quadratic convolution kernel, which
// approximates the Gaussian kernel to within roughly 3%.
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
// ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
let inputRadius = blurRadius * screenScale
// var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5))
let inputradius = inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI))
var radius = UInt32(floor((inputradius / 4) + 0.5))
if radius % 2 != 1 {
radius += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s: CGFloat = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let matrixSize = floatingPointSaturationMatrix.count
var saturationMatrix = [Int16](repeating: 0, count: matrixSize)
for i in 0..<matrixSize {
saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer,
&effectInBuffer,
saturationMatrix,
Int32(divisor),
nil,
nil,
vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer,
&effectOutBuffer,
saturationMatrix,
Int32(divisor),
nil,
nil,
vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
}
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let outputContext = UIGraphicsGetCurrentContext()
outputContext?.scaleBy(x: 1.0, y: -1.0)
outputContext?.translateBy(x: 0, y: -size.height)
// Draw base image.
outputContext?.draw(cgImage, in: imageRect)
// Draw effect image.
if hasBlur {
outputContext?.saveGState()
if let image = maskImage {
outputContext?.clip(to: imageRect, mask: image.cgImage!)
}
outputContext?.draw(effectImage.cgImage!, in: imageRect)
outputContext?.restoreGState()
}
// Add in color tint.
if let color = tintColor {
outputContext?.saveGState()
outputContext?.setFillColor(color.cgColor)
outputContext?.fill(imageRect)
outputContext?.restoreGState()
}
// Output image is ready.
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
|
apache-2.0
|
63400f68cc544d0639c471a5d59bf6a4
| 41.642857 | 152 | 0.57611 | 5.108021 | false | false | false | false |
peigen/iLife
|
iLife/Globals.swift
|
1
|
2720
|
//
// YJGlobals.swift
// PayPurse
//
// Created by zq on 14-6-10.
// Copyright (c) 2014 zq. All rights reserved.
//
import UIKit
//设备屏幕尺寸
let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height
let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width
let TOP_BAR : CGFloat = 64
let ICON_HEIGHT : CGFloat = 57
let ICON_WIDTH : CGFloat = 57
let ORIGINAL_POINT : CGFloat = 0
let VIEW_TITLE : CGFloat = 20
//App
let YJApp = UIApplication.sharedApplication().delegate as AppDelegate
//设备版本
let sysVersion:NSString = UIDevice.currentDevice().systemVersion
let isAfterIOS6 : Bool = sysVersion.floatValue >= 6.0
let isAfterIOS7 : Bool = sysVersion.floatValue >= 7.0
let isAfterIOS8 : Bool = sysVersion.floatValue >= 8.0
//color
struct RGBCOLOR
{
static func fColor(red: CGFloat, _ green: CGFloat, _ blue: CGFloat) -> UIColor
{
return UIColor(red:red/255, green: green/255, blue: blue/255, alpha: 1.0);
}
static func fColorAlpha(red: CGFloat, _ green: CGFloat, _ blue: CGFloat, _ alpha:CGFloat) -> UIColor
{
return UIColor(red:red/255, green: green/255, blue: blue/255, alpha: alpha);
}
static func fColorRGB(rgbValue:UInt32) -> UIColor
{
return UIColor(red:CGFloat((rgbValue & 0xFF0000) >> 16)/255, green: CGFloat((rgbValue & 0xFF00) >> 8)/255, blue: CGFloat((rgbValue & 0xFF))/255, alpha: 1.0);
}
static func fColorRGB(rgbValue:UInt32, _ alpha:CGFloat) -> UIColor
{
return UIColor(red:CGFloat((rgbValue & 0xFF0000) >> 16)/255, green: CGFloat((rgbValue & 0xFF00) >> 8)/255, blue: CGFloat((rgbValue & 0xFF))/255, alpha: alpha);
}
}
//可拉伸的图片
struct Resizable
{
static func ResizableImage(name:String,_ top:CGFloat,_ left:CGFloat,_ bottom:CGFloat,_ right:CGFloat) -> UIImage
{
return UIImage(named:name).resizableImageWithCapInsets(UIEdgeInsetsMake(top,left,bottom,right))
}
static func ResizableImageWithMode(name:String,_ top:CGFloat,_ left:CGFloat,_ bottom:CGFloat,_ right:CGFloat ,_ mode:UIImageResizingMode) -> UIImage
{
return UIImage(named:name).resizableImageWithCapInsets(UIEdgeInsetsMake(top,left,bottom,right),resizingMode:mode)
}
}
struct sysUrl
{
static func canOpenURLApp(url:String) -> Bool
{
return UIApplication.sharedApplication().canOpenURL(NSURL.URLWithString(url))
}
static func openURLApp(url:String) -> Bool
{
return UIApplication.sharedApplication().openURL(NSURL.URLWithString(url))
}
static func openURLTel(mobile:String) -> Bool
{
return UIApplication.sharedApplication().openURL(NSURL.URLWithString(NSString(format: "tel://%@",mobile)))
}
}
|
gpl-3.0
|
23fa2207cbf20569014c26f87fea2436
| 30.623529 | 167 | 0.684152 | 3.722992 | false | false | false | false |
nathawes/swift
|
test/IDE/print_swift_module.swift
|
1
|
2180
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/print_swift_module.swiftmodule -emit-module-doc -emit-module-doc-path %t/print_swift_module.swiftdoc %s
// RUN: %target-swift-ide-test -print-module -print-interface -no-empty-line-between-members -module-to-print=print_swift_module -I %t -source-filename=%s > %t.syn.txt
// RUN: %target-swift-ide-test -print-module -access-filter-internal -no-empty-line-between-members -module-to-print=print_swift_module -I %t -source-filename=%s > %t.syn.internal.txt
// RUN: %FileCheck %s -check-prefix=CHECK1 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK2 < %t.syn.internal.txt
public protocol P1 {
/// foo1 comment from P1
func foo1()
/// foo2 comment from P1
func foo2()
}
public class C1 : P1 {
public func foo1() {
}
/// foo2 comment from C1
public func foo2() {
}
}
/// Alias comment
public typealias Alias<T> = (T, T)
/// returnsAlias() comment
public func returnsAlias() -> Alias<Int> {
return (0, 0)
}
@_functionBuilder
struct BridgeBuilder {
static func buildBlock(_: Any...) {}
}
public struct City {
public init(@BridgeBuilder builder: () -> ()) {}
}
// CHECK1: /// Alias comment
// CHECK1-NEXT: typealias Alias<T> = (T, T)
// CHECK1: public class C1 : print_swift_module.P1 {
// CHECK1-NEXT: /// foo1 comment from P1
// CHECK1-NEXT: public func foo1()
// CHECK1-NEXT: /// foo2 comment from C1
// CHECK1-NEXT: public func foo2()
// CHECK1-NEXT: }
// CHECK1: public init(@print_swift_module.BridgeBuilder builder: () -> ())
// CHECK1: public protocol P1 {
// CHECK1-NEXT: /// foo1 comment from P1
// CHECK1-NEXT: func foo1()
// CHECK1-NEXT: /// foo2 comment from P1
// CHECK1-NEXT: func foo2()
// CHECK1-NEXT: }
// CHECK1: /// returnsAlias() comment
// CHECK1-NEXT: func returnsAlias() -> print_swift_module.Alias<Int>
// CHECK2: struct Event {
public struct Event {
public var start: Int
public var end: Int?
public var repeating: ((), Int?)
public var name = "untitled event"
// CHECK2: init(start: Int, end: Int? = nil, repeating: ((), Int?) = ((), nil), name: String = "untitled event")
}
// CHECK2: }
|
apache-2.0
|
e47ac503fb8fbba5fde7a0e023d035b8
| 30.142857 | 183 | 0.655963 | 3.036212 | false | false | false | false |
keyOfVv/Cusp
|
Cusp/Sources/PeripheralDelegate.swift
|
1
|
13688
|
//
// CuspPeripheralDelegate.swift
// Cusp
//
// Created by keyOfVv on 2/14/16.
// Copyright © 2016 com.keyofvv. All rights reserved.
//
import Foundation
import CoreBluetooth
// MARK: - CBPeripheralDelegate
extension Peripheral: CBPeripheralDelegate {
/*!
* @method peripheral:didDiscoverServices:
*
* @param peripheral The peripheral providing this information.
* @param error If an error occurred, the cause of the failure.
*
* @discussion This method returns the result of a @link discoverServices: @/link call. If the service(s) were read successfully, they can be retrieved via
* <i>peripheral</i>'s @link services @/link property.
*
*/
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
operationQ.async { () -> Void in
// multiple reqs of discovering service within a short duration will be responsed simultaneously
// 1. check if service UUID specified in req...
for req in self.serviceDiscoveringRequests {
if let uuids = req.serviceUUIDs {
// if so, check if all interested services are discovered, otherwise return directly
if !self.areServicesAvailable(uuids: uuids) {
return
}
}
}
// 2. all interested services are discovered, OR in case no service UUID specified in req...
for req in self.serviceDiscoveringRequests {
req.timedOut = false
DispatchQueue.main.async(execute: { () -> Void in
if let errorInfo = error {
dog("dicovering services failed due to \(errorInfo)")
// discovering failed
req.failure?(CuspError(err: errorInfo))
} else {
// discovering succeed, call success closure of each req
req.success?(nil)
}
})
}
// 4. once the success/failure closure called, remove the req
self.requestQ.async(execute: { () -> Void in
self.serviceDiscoveringRequests.filter { !$0.timedOut }.forEach { self.serviceDiscoveringRequests.remove($0) }
})
}
}
/*!
* @method peripheral:didDiscoverCharacteristicsForService:error:
*
* @param peripheral The peripheral providing this information.
* @param service The <code>CBService</code> object containing the characteristic(s).
* @param error If an error occurred, the cause of the failure.
*
* @discussion This method returns the result of a @link discoverCharacteristics:forService: @/link call. If the characteristic(s) were read successfully,
* they can be retrieved via <i>service</i>'s <code>characteristics</code> property.
*/
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
operationQ.async { () -> Void in
// multiple reqs of discovering characteristic within a short duration will be responsed simultaneously
// 1. check if characteristic UUID specified in req...
for req in self.characteristicDiscoveringRequests {
if let uuids = req.characteristicUUIDs {
// if so, check if all interested characteristics are discovered, otherwise return directly
if !self.areCharacteristicsAvailable(uuids: uuids, forService: service) {
return
}
}
}
// 2. all interested characteristics are discovered, OR in case no characteristic UUID specified in char-discove-req...
for req in self.characteristicDiscoveringRequests {
req.timedOut = false
DispatchQueue.main.async(execute: { () -> Void in
if let errorInfo = error {
dog("discovering characteristics of service <\(service.uuid.uuidString)> failed due to \(errorInfo)")
// discovering failed
req.failure?(CuspError(err: errorInfo))
} else {
// discovering succeed, call success closure of each req
req.success?(nil)
}
})
}
// 4. once the success/failure closure called, remove the req
self.requestQ.async(execute: { () -> Void in
self.characteristicDiscoveringRequests.filter { !$0.timedOut }.forEach { self.characteristicDiscoveringRequests.remove($0) }
})
}
}
public func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
operationQ.sync {
guard let req = (self.descriptorDiscoveringRequests.first { $0.characteristic == characteristic }) else {
fatalError("Peripheral received didDiscoverDescriptors callback has no matched descriptorDiscoveringRequest")
}
req.timedOut = false
DispatchQueue.main.async(execute: { () -> Void in
if let errorInfo = error {
// discovering failed
dog("discover descriptors for char \(characteristic.uuid.uuidString) failed due to \(errorInfo)")
req.failure?(CuspError(err: errorInfo))
} else {
// discovering succeed, call success closure of each req
dog("discover descriptors for char \(characteristic.uuid.uuidString) succeed")
req.success?(nil)
}
})
// 4. once the success/failure closure called, remove the req
self.requestQ.async(execute: { () -> Void in
self.descriptorDiscoveringRequests.remove(req)
})
}
}
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
operationQ.sync {
guard let req = (self.readDescriptorRequests.first { $0.descriptor == descriptor }) else {
fatalError("Peripheral received didUpdateValueForDescriptor callback has no matched readDescriptorRequest")
}
req.timedOut = false
DispatchQueue.main.async(execute: { () -> Void in
if let errorInfo = error {
// read failed
dog("read descriptor \(descriptor.uuid.uuidString) failed due to \(errorInfo)")
req.failure?(CuspError(err: errorInfo))
} else {
// read succeed, call success closure of each req
dog("read descriptor \(descriptor.uuid.uuidString) succeed")
req.success?(nil)
}
})
// 4. once the success/failure closure called, remove the req
self.requestQ.async(execute: { () -> Void in
self.readDescriptorRequests.remove(req)
})
}
}
public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
operationQ.sync {
guard let req = (self.writeDescriptorRequests.first { $0.descriptor == descriptor }) else {
fatalError("Peripheral received didWriteValueForDescriptor callback has no matched writeDescriptorRequest")
}
req.timedOut = false
DispatchQueue.main.async(execute: { () -> Void in
if let errorInfo = error {
// read failed
dog("write descriptor for descriptor \(descriptor.uuid.uuidString) failed due to \(errorInfo)")
req.failure?(CuspError(err: errorInfo))
} else {
// read succeed, call success closure of each req
dog("write descriptor for descriptor \(descriptor.uuid.uuidString) succeed")
req.success?(nil)
}
})
// 4. once the success/failure closure called, remove the req
self.requestQ.async(execute: { () -> Void in
self.writeDescriptorRequests.remove(req)
})
}
}
/*!
* @method peripheral:didUpdateValueForCharacteristic:error:
*
* @param peripheral The peripheral providing this information.
* @param characteristic A <code>CBCharacteristic</code> object.
* @param error If an error occurred, the cause of the failure.
*
* @discussion This method is invoked after a @link readValueForCharacteristic: @/link call, or upon receipt of a notification/indication.
*/
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
// this method is invoked after readValueForCharacteristic call or subscription...
// so it's necessary to find out whether value is read or subscirbed...
// if subscribed, then ignore read req
dog("Characteristic \(characteristic) did update value.")
operationQ.async {
if characteristic.isNotifying {
// subscription update
// find out specific subscription
guard let sub = (self.subscriptions.first { $0.characteristic === characteristic }) else {
// fatalError("Peripheral received value update via notification(s) is not referenced by subscriptions set")
return
}
// prepare to call update call back
if let errorInfo = error {
dog("updating value for char <\(characteristic.uuid.uuidString)> failed due to \(errorInfo)")
dog(errorInfo)
} else {
DispatchQueue.main.async(execute: { () -> Void in
sub.update?(characteristic.value)
})
}
} else {
// may invoked by value reading req
// find out specific req
guard let req = (self.readRequests.first { $0.characteristic == characteristic }) else {
fatalError("Peripheral received value update via read operation(s) is not referenced by subscriptions set")
}
// prepare to call back
DispatchQueue.main.async(execute: { () -> Void in
// disable timeout closure
req.timedOut = false
if let errorInfo = error {
dog("read value for char <\(characteristic.uuid.uuidString)> failed due to \(errorInfo)")
// read value failed
req.failure?(CuspError(err: errorInfo))
} else {
// read value succeed
let resp = Response()
resp.value = characteristic.value // wrap value
req.success?(resp)
}
})
}
}
}
/*!
* @method peripheral:didWriteValueForCharacteristic:error:
*
* @param peripheral The peripheral providing this information.
* @param characteristic A <code>CBCharacteristic</code> object.
* @param error If an error occurred, the cause of the failure.
*
* @discussion This method returns the result of a {@link writeValue:forCharacteristic:type:} call, when the <code>CBCharacteristicWriteWithResponse</code> type is used.
*/
public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
operationQ.async(execute: { () -> Void in
guard let req = (self.writeRequests.first { $0.characteristic == characteristic }) else {
fatalError("Peripheral received didWriteValueForCharacteristic callback has no matched writeRequest")
}
req.timedOut = false
DispatchQueue.main.async(execute: { () -> Void in
if let errorInfo = error {
dog("write value for <\(characteristic.uuid.uuidString)> failed due to \(errorInfo)")
// write failed
req.failure?(CuspError(err: errorInfo))
} else {
// write succeed
req.success?(nil)
}
})
self.requestQ.async(execute: { () -> Void in
self.writeRequests.remove(req)
})
})
}
/*!
* @method peripheral:didUpdateNotificationStateForCharacteristic:error:
*
* @param peripheral The peripheral providing this information.
* @param characteristic A <code>CBCharacteristic</code> object.
* @param error If an error occurred, the cause of the failure.
*
* @discussion This method returns the result of a @link setNotifyValue:forCharacteristic: @/link call.
*/
public func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
operationQ.sync {
switch characteristic.isNotifying {
case true:
guard let req = (self.subscribeRequests.first { $0.characteristic == characteristic }) else {
fatalError("Peripheral received didUpdateNotificationStateForCharacteristic callback has no matched subscribeRequest")
}
req.timedOut = false
DispatchQueue.main.async(execute: { () -> Void in
if let errorInfo = error {
dog("subscribe char <\(characteristic.uuid.uuidString)> failed due to \(errorInfo)")
// subscribe failed
req.failure?(CuspError(err: errorInfo))
} else {
// subscribe succeed
req.success?(nil)
self.subscriptionQ.async(execute: { () -> Void in
// create subscription object
let subscription = Subscription(characteristic: characteristic, update: req.update)
self.subscriptions.insert(subscription)
})
}
})
self.requestQ.async(execute: { () -> Void in
self.subscribeRequests.remove(req)
})
case false:
guard let req = (self.unsubscribeRequests.first { $0.characteristic == characteristic }) else {
fatalError("Peripheral received didUpdateNotificationStateForCharacteristic callback has no matched unsubscribeRequest")
}
req.timedOut = false
DispatchQueue.main.async(execute: { () -> Void in
if let errorInfo = error {
dog("unsubscribe char <\(characteristic.uuid.uuidString)> failed due to \(errorInfo)")
// unsubscribe failed
req.failure?(CuspError(err: errorInfo))
} else {
// unsubscribe succeed
req.success?(nil)
// remove subscription
self.subscriptionQ.async(execute: { () -> Void in
guard let sub = (self.subscriptions.first { $0.characteristic == characteristic }) else {
fatalError("Peripheral unsubscribed has no matched subscription")
}
self.subscriptions.remove(sub)
})
}
})
self.requestQ.async(execute: { () -> Void in
self.unsubscribeRequests.remove(req)
})
}
}
}
// TODO: 8.0+ only
public func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
operationQ.async(execute: { () -> Void in
for req in self.RSSIRequests {
req.timedOut = false
DispatchQueue.main.async(execute: { () -> Void in
if let errorInfo = error {
dog("read RSSI failed due to \(errorInfo)")
// read RSSI failed
req.failure?(CuspError(err: errorInfo))
} else {
// read RSSI succeed
let resp = Response()
resp.RSSI = RSSI
req.success?(resp)
}
})
}
self.requestQ.async {
self.RSSIRequests.filter { !$0.timedOut }.forEach { self.RSSIRequests.remove($0) }
}
})
}
}
|
mit
|
ca3c909459f28bae61fcff84b649c592
| 38.105714 | 173 | 0.693578 | 4.012606 | false | false | false | false |
LinShiwei/HealthyDay
|
HealthyDay/LocationManager.swift
|
1
|
1577
|
//
// LocationManager.swift
// HealthyDay
//
// Created by Linsw on 16/9/28.
// Copyright © 2016年 Linsw. All rights reserved.
//
import Foundation
import CoreLocation
internal final class LocationManager {
static let sharedLocationManager = LocationManager()
private let locationManager = CLLocationManager()
private init(){
}
var delegate : CLLocationManagerDelegate?{
didSet{
locationManager.delegate = delegate
}
}
internal func authorize(_ completion: @escaping (_ success:Bool) -> Void){
guard CLLocationManager.locationServicesEnabled() else{
completion(false)
print("lsw_Location services disabled. locationservicesEnabled is false")
return
}
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
completion(false)
case .authorizedWhenInUse, .authorizedAlways:
completion(true)
default:
completion(false)
}
}
internal func startUpdate(){
locationManager.startUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = true
}
internal func stopUpdate(){
locationManager.allowsBackgroundLocationUpdates = false
locationManager.stopUpdatingLocation()
}
private func initLocationParameter(){
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.distanceFilter = 10.0
}
}
|
mit
|
6db80a120b5b16eace8426cb3ffec8a8
| 28.698113 | 85 | 0.66709 | 6.007634 | false | false | false | false |
Jnosh/swift
|
stdlib/public/core/Bool.swift
|
2
|
9762
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Bool Datatype and Supporting Operators
//===----------------------------------------------------------------------===//
/// A value type whose instances are either `true` or `false`.
///
/// `Bool` represents Boolean values in Swift. Create instances of `Bool` by
/// using one of the Boolean literals `true` or `false`, or by assigning the
/// result of a Boolean method or operation to a variable or constant.
///
/// var godotHasArrived = false
///
/// let numbers = 1...5
/// let containsTen = numbers.contains(10)
/// print(containsTen)
/// // Prints "false"
///
/// let (a, b) = (100, 101)
/// let aFirst = a < b
/// print(aFirst)
/// // Prints "true"
///
/// Swift uses only simple Boolean values in conditional contexts to help avoid
/// accidental programming errors and to help maintain the clarity of each
/// control statement. Unlike in other programming languages, in Swift, integers
/// and strings cannot be used where a Boolean value is required.
///
/// For example, the following code sample does not compile, because it
/// attempts to use the integer `i` in a logical context:
///
/// var i = 5
/// while i {
/// print(i)
/// i -= 1
/// }
///
/// The correct approach in Swift is to compare the `i` value with zero in the
/// `while` statement.
///
/// while i != 0 {
/// print(i)
/// i -= 1
/// }
///
/// Using Imported Boolean values
/// =============================
///
/// The C `bool` and `Boolean` types and the Objective-C `BOOL` type are all
/// bridged into Swift as `Bool`. The single `Bool` type in Swift guarantees
/// that functions, methods, and properties imported from C and Objective-C
/// have a consistent type interface.
@_fixed_layout
public struct Bool {
@_versioned
internal var _value: Builtin.Int1
/// Creates an instance initialized to `false`.
///
/// Do not call this initializer directly. Instead, use the Boolean literal
/// `false` to create a new `Bool` instance.
@_transparent
public init() {
let zero: Int8 = 0
self._value = Builtin.trunc_Int8_Int1(zero._value)
}
@_versioned
@_transparent
internal init(_ v: Builtin.Int1) { self._value = v }
/// Creates an instance equal to the given Boolean value.
///
/// - Parameter value: The Boolean value to copy.
public init(_ value: Bool) {
self = value
}
}
extension Bool : _ExpressibleByBuiltinBooleanLiteral, ExpressibleByBooleanLiteral {
@_transparent
public init(_builtinBooleanLiteral value: Builtin.Int1) {
self._value = value
}
/// Creates an instance initialized to the specified Boolean literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use a Boolean literal. Instead, create a new `Bool` instance by
/// using one of the Boolean literals `true` or `false`.
///
/// var printedMessage = false
///
/// if !printedMessage {
/// print("You look nice today!")
/// printedMessage = true
/// }
/// // Prints "You look nice today!"
///
/// In this example, both assignments to the `printedMessage` variable call
/// this Boolean literal initializer behind the scenes.
///
/// - Parameter value: The value of the new instance.
@_transparent
public init(booleanLiteral value: Bool) {
self = value
}
}
extension Bool {
// This is a magic entry point known to the compiler.
@_transparent
public // COMPILER_INTRINSIC
func _getBuiltinLogicValue() -> Builtin.Int1 {
return _value
}
}
extension Bool : CustomStringConvertible {
/// A textual representation of the Boolean value.
public var description: String {
return self ? "true" : "false"
}
}
// This is a magic entry point known to the compiler.
@_transparent
public // COMPILER_INTRINSIC
func _getBool(_ v: Builtin.Int1) -> Bool { return Bool(v) }
extension Bool : Equatable, Hashable {
/// The hash value for the Boolean value.
///
/// Two values that are equal always have equal hash values.
///
/// - Note: The hash value is not guaranteed to be stable across different
/// invocations of the same program. Do not persist the hash value across
/// program runs.
/// - SeeAlso: `Hashable`
@_transparent
public var hashValue: Int {
return self ? 1 : 0
}
@_transparent
public static func == (lhs: Bool, rhs: Bool) -> Bool {
return Bool(Builtin.cmp_eq_Int1(lhs._value, rhs._value))
}
}
extension Bool : LosslessStringConvertible {
/// Creates a new Boolean value from the given string.
///
/// If `description` is any string other than `"true"` or `"false"`, the
/// result is `nil`. This initializer is case sensitive.
///
/// - Parameter description: A string representation of the Boolean value.
public init?(_ description: String) {
if description == "true" {
self = true
} else if description == "false" {
self = false
} else {
return nil
}
}
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
extension Bool {
/// Performs a logical NOT operation on a Boolean value.
///
/// The logical NOT operator (`!`) inverts a Boolean value. If the value is
/// `true`, the result of the operation is `false`; if the value is `false`,
/// the result is `true`.
///
/// var printedMessage = false
///
/// if !printedMessage {
/// print("You look nice today!")
/// printedMessage = true
/// }
/// // Prints "You look nice today!"
///
/// - Parameter a: The Boolean value to negate.
@_transparent
public static prefix func ! (a: Bool) -> Bool {
return Bool(Builtin.xor_Int1(a._value, true._value))
}
}
extension Bool {
/// Performs a logical AND operation on two Boolean values.
///
/// The logical AND operator (`&&`) combines two Boolean values and returns
/// `true` if both of the values are `true`. If either of the values is
/// `false`, the operator returns `false`.
///
/// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is
/// evaluated first, and the right-hand side (`rhs`) is evaluated only if
/// `lhs` evaluates to `true`. For example:
///
/// let measurements = [7.44, 6.51, 4.74, 5.88, 6.27, 6.12, 7.76]
/// let sum = measurements.reduce(0, combine: +)
///
/// if measurements.count > 0 && sum / Double(measurements.count) < 6.5 {
/// print("Average measurement is less than 6.5")
/// }
/// // Prints "Average measurement is less than 6.5"
///
/// In this example, `lhs` tests whether `measurements.count` is greater than
/// zero. Evaluation of the `&&` operator is one of the following:
///
/// - When `measurements.count` is equal to zero, `lhs` evaluates to `false`
/// and `rhs` is not evaluated, preventing a divide-by-zero error in the
/// expression `sum / Double(measurements.count)`. The result of the
/// operation is `false`.
/// - When `measurements.count` is greater than zero, `lhs` evaluates to
/// `true` and `rhs` is evaluated. The result of evaluating `rhs` is the
/// result of the `&&` operation.
///
/// - Parameters:
/// - lhs: The left-hand side of the operation.
/// - rhs: The right-hand side of the operation.
@_transparent
@inline(__always)
public static func && (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows
-> Bool {
return lhs ? try rhs() : false
}
/// Performs a logical OR operation on two Boolean values.
///
/// The logical OR operator (`||`) combines two Boolean values and returns
/// `true` if at least one of the values is `true`. If both values are
/// `false`, the operator returns `false`.
///
/// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is
/// evaluated first, and the right-hand side (`rhs`) is evaluated only if
/// `lhs` evaluates to `false`. For example:
///
/// let majorErrors: Set = ["No first name", "No last name", ...]
/// let error = ""
///
/// if error.isEmpty || !majorErrors.contains(error) {
/// print("No major errors detected")
/// } else {
/// print("Major error: \(error)")
/// }
/// // Prints "No major errors detected"
///
/// In this example, `lhs` tests whether `error` is an empty string.
/// Evaluation of the `||` operator is one of the following:
///
/// - When `error` is an empty string, `lhs` evaluates to `true` and `rhs` is
/// not evaluated, skipping the call to `majorErrors.contains(_:)`. The
/// result of the operation is `true`.
/// - When `error` is not an empty string, `lhs` evaluates to `false` and
/// `rhs` is evaluated. The result of evaluating `rhs` is the result of the
/// `||` operation.
///
/// - Parameters:
/// - lhs: The left-hand side of the operation.
/// - rhs: The right-hand side of the operation.
@_transparent
@inline(__always)
public static func || (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows
-> Bool {
return lhs ? true : try rhs()
}
}
|
apache-2.0
|
aca3910bbf8eaf73d65d4724931ad3a0
| 33.4947 | 83 | 0.604487 | 4.11378 | false | false | false | false |
sahandnayebaziz/Hypertext
|
Sources/Doctype.swift
|
1
|
1258
|
public class doctype: Renderable {
public enum Doctype: String {
case html5 = "<!DOCTYPE html>"
case html4Strict = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"
case html4Transitional = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"
case html4Frameset = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">"
case xhtml1Strict = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
case xhtml1Transitional = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
case xhtml1Frameset = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">"
case xhtml11 = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">"
}
let docType: Doctype
public var description: String { return docType.rawValue }
public init(_ docType: Doctype) { self.docType = docType }
}
|
mit
|
54411c3dc35893fb16a221e72f204a13
| 77.625 | 161 | 0.642289 | 3.090909 | false | false | false | false |
kazuhiro4949/PagingKit
|
iOS Sample/iOS Sample/IndicatorViewController.swift
|
1
|
4998
|
//
// IndicatorViewController.swift
// PagingKit
//
// Copyright (c) 2017 Kazuhiro Hayashi
//
// 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 PagingKit
class IndicatorViewController: UIViewController {
var contentViewController: PagingContentViewController!
var menuViewController: PagingMenuViewController!
var dataSource: [UIViewController] = [
{
let vc = UIStoryboard(name: "PhotoViewController", bundle: nil).instantiateInitialViewController() as! PhotoViewController
vc.image = #imageLiteral(resourceName: "Photo1")
return vc
}(),
{
let vc = UIStoryboard(name: "PhotoViewController", bundle: nil).instantiateInitialViewController() as! PhotoViewController
vc.image = #imageLiteral(resourceName: "Photo2")
return vc
}()
]
lazy var firstLoad: (() -> Void)? = { [weak self, menuViewController, contentViewController] in
menuViewController?.reloadData()
contentViewController?.reloadData()
self?.firstLoad = nil
}
override func viewDidLoad() {
super.viewDidLoad()
menuViewController?.registerFocusView(nib: UINib(nibName: "IndicatorFocusMenuView", bundle: nil))
menuViewController?.register(type: PagingMenuViewCell.self, forCellWithReuseIdentifier: "identifier")
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
firstLoad?()
}
// 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 let vc = segue.destination as? PagingContentViewController {
contentViewController = vc
contentViewController.delegate = self
contentViewController.dataSource = self
} else if let vc = segue.destination as? PagingMenuViewController {
menuViewController = vc
menuViewController.delegate = self
menuViewController.dataSource = self
}
}
}
extension IndicatorViewController: PagingMenuViewControllerDataSource {
func menuViewController(viewController: PagingMenuViewController, cellForItemAt index: Int) -> PagingMenuViewCell {
let cell = viewController.dequeueReusableCell(withReuseIdentifier: "identifier", for: index)
return cell
}
func menuViewController(viewController: PagingMenuViewController, widthForItemAt index: Int) -> CGFloat {
return viewController.view.bounds.width / CGFloat(dataSource.count)
}
func numberOfItemsForMenuViewController(viewController: PagingMenuViewController) -> Int {
return dataSource.count
}
}
extension IndicatorViewController: PagingContentViewControllerDataSource {
func numberOfItemsForContentViewController(viewController: PagingContentViewController) -> Int {
return dataSource.count
}
func contentViewController(viewController: PagingContentViewController, viewControllerAt index: Int) -> UIViewController {
return dataSource[index]
}
}
extension IndicatorViewController: PagingMenuViewControllerDelegate {
func menuViewController(viewController: PagingMenuViewController, didSelect page: Int, previousPage: Int) {
contentViewController?.scroll(to: page, animated: true)
}
}
extension IndicatorViewController: PagingContentViewControllerDelegate {
func contentViewController(viewController: PagingContentViewController, didManualScrollOn index: Int, percent: CGFloat) {
menuViewController?.scroll(index: index, percent: percent, animated: false)
}
}
|
mit
|
8ae1a7b1e632a382d90378c09ed53f8c
| 39.306452 | 134 | 0.720888 | 5.480263 | false | false | false | false |
peterobbin/atomSimulation
|
atoms/ElectronCloud.swift
|
1
|
1193
|
//
// ElectronCloud.swift
// atoms
//
// Created by Luobin Wang on 7/31/15.
// Copyright © 2015 Luobin Wang. All rights reserved.
//
import Foundation
import SpriteKit
class ElectronCloud {
let cloud = SKNode()
var mElctron = [Electron]()
var numElctron = Int()
var osciMax:CGFloat = 0.0
func setup(_pos:CGPoint){
cloud.position = _pos
cloud.name = "cloud"
cloud.zPosition = -2
numElctron = Int(random(1, max: 5))
for _ in 1...numElctron{
mElctron.append(Electron())
}
for e in mElctron {
let osciScale = random(50, max: 150)
if osciMax < osciScale { osciMax = osciScale}
cloud.addChild(e.etron)
e.setup(CGPointZero, _osciScale: osciScale)
}
//cloud.addChild(mElctron.etron)
}
func update(){
for e in mElctron{
e.update()
}
}
func random() ->CGFloat{
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(min: CGFloat, max: CGFloat) ->CGFloat{
return random() * (max - min) + min
}
}
|
mit
|
dc1c57ee7b3b299fefccf108bc889ae7
| 21.092593 | 57 | 0.528523 | 3.601208 | false | false | false | false |
blisslog/UI-Imitation-DailyBeast
|
NEWS/ViewController.swift
|
1
|
8884
|
//
// ViewController.swift
// NEWS
//
// Created by BlissLog on 2016. 1. 6..
// Copyright © 2016년 BlissLog. All rights reserved.
//
import UIKit
import MGSwipeTableCell
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, UIGestureRecognizerDelegate, MGSwipeTableCellDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var topView: UIView!
var dataManager:DataManager!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationController!.interactivePopGestureRecognizer!.delegate = self
dataManager = DataManager.sharedInstance
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func rightButtons() -> NSArray {
let btns :NSMutableArray = NSMutableArray()
// MGSwipeTableCell
let btn1 = MGSwipeButton(title: "SKIP", backgroundColor: UIColor(red: 242.0/255.0, green: 5.0/255.0, blue: 5.0/255.0, alpha: 1.0), padding:5, callback: {
(sender: MGSwipeTableCell?) -> Bool in
return true
})
btn1?.titleLabel?.font = UIFont(name: "HelveticaNeue-CondensedBlack", size: 60.0)
btn1?.sizeToFit()
btns.add(btn1)
return btns
}
func leftButtons() -> NSArray {
let btns :NSMutableArray = NSMutableArray()
// MGSwipeTableCell
let btn1 = MGSwipeButton(title: "FOLLOW\nAUTHOR", backgroundColor: UIColor(red: 191.0/255.0, green: 31.0/255.0, blue: 31.0/255.0, alpha: 1.0), padding:20, callback: {
(sender: MGSwipeTableCell?) -> Bool in
print("FOLLOW AUTHOR")
return true
})
btn1?.titleLabel?.font = UIFont(name: "HelveticaNeue-Thin", size: 15.0)
btn1?.sizeToFit()
let btn2 = MGSwipeButton(title: "SHARE\nSTORY", backgroundColor: UIColor(red: 140.0/255.0, green: 22.0/255.0, blue: 22.0/255.0, alpha: 1.0), padding:20, callback: {
(sender: MGSwipeTableCell?) -> Bool in
print("SHARE STORY")
return true
})
btn2?.titleLabel?.font = UIFont(name: "HelveticaNeue-Thin", size: 15.0)
btn2?.sizeToFit()
btns.add(btn1)
btns.add(btn2)
return btns
}
// MARK: - UITableViewdelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataManager.items.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ArticleCell = self.tableView.dequeueReusableCell(withIdentifier: "article_cell")! as! ArticleCell
let article = self.dataManager.items[indexPath.row] as Article
cell.title.text = article.title
cell.title.font = UIFont(name: "HelveticaNeue-CondensedBlack", size: 22.0)
cell.desc.text = article.desc
cell.desc.font = UIFont(name: "TimesNewRomanPSMT", size: 12.0)
if article.readed! {
cell.title.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
cell.desc.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
} else {
cell.title.textColor = UIColor.black
cell.desc.textColor = UIColor.black
}
if article.readingRate >= 1.0 {
cell.checkReaded.isHidden = false
cell.readingProgress.progress = 0.0
} else {
cell.checkReaded.isHidden = true
cell.readingProgress.progress = article.readingRate
}
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async { () -> Void in
cell.bgImage.downloadByImageUrl(article.imgUrl!, grayscale: true)
}
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! ArticleCell
let article = self.dataManager.items[indexPath.row] as Article
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async { () -> Void in
cell.bgImage.downloadByImageUrl(article.imgUrl!, grayscale: false)
}
}
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! ArticleCell
let article = self.dataManager.items[indexPath.row] as Article
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async { () -> Void in
cell.bgImage.downloadByImageUrl(article.imgUrl!, grayscale: true)
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0;
}
/*
// MARK : - Edit
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let more = UITableViewRowAction(style: .Normal, title: "More") { action, index in
print("more button tapped")
}
more.backgroundColor = UIColor.lightGrayColor()
let favorite = UITableViewRowAction(style: .Normal, title: "Favorite") { action, index in
print("favorite button tapped")
}
favorite.backgroundColor = UIColor.orangeColor()
let share = UITableViewRowAction(style: .Normal, title: "Share") { action, index in
print("share button tapped")
}
share.backgroundColor = UIColor.blueColor()
return [share, favorite, more]
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// the cells you would like the actions to appear needs to be editable
return true
}
// MARK : -
*/
// MARK: - MGSwipeTableCellDelegate
// https://github.com/MortimerGoro/MGSwipeTableCell
func swipeTableCell(_ cell: MGSwipeTableCell!, swipeButtonsFor direction: MGSwipeDirection, swipeSettings: MGSwipeSettings!, expansionSettings: MGSwipeExpansionSettings!) -> [AnyObject]! {
swipeSettings.transition = MGSwipeTransition.border
expansionSettings.buttonIndex = 0
if direction == MGSwipeDirection.leftToRight {
expansionSettings.fillOnTrigger = false
expansionSettings.threshold = 1.2
return self.leftButtons() as [AnyObject]
}
else {
expansionSettings.fillOnTrigger = true
expansionSettings.threshold = 2.0
return self.rightButtons() as [AnyObject]
}
}
func swipeTableCell(_ cell: MGSwipeTableCell!, didChange state: MGSwipeState, gestureIsActive: Bool) {
let str:NSString!
switch state {
case MGSwipeState.none: str = "None"
case MGSwipeState.swipingLeftToRight: str = "SwipingLeftToRight"
case MGSwipeState.swipingRightToLeft:
str = "SwipingRightToLeft"
cell.swipeBackgroundColor = UIColor(red: 242.0/255.0, green: 5.0/255.0, blue: 5.0/255.0, alpha: 1.0)
case MGSwipeState.expandingLeftToRight: str = "ExpandingLeftToRight"
case MGSwipeState.expandingRightToLeft: str = "ExpandingRightToLeft"
}
NSLog("Swipe state: \(str) ::: Gesture: %@", gestureIsActive ? "Active" : "Ended");
}
func swipeTableCellWillEndSwiping(_ cell: MGSwipeTableCell!) {
cell.swipeBackgroundColor = UIColor.clear
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
}
// MARK: - UINavigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
NSLog("\(segue.identifier)")
if segue.identifier == "goArticle" {
guard let indexPath = self.tableView.indexPathForSelectedRow else {
return;
}
let article = segue.destination as! ArticleViewController;
article.index = indexPath.row
}
}
}
|
mit
|
93035204bc89d67c963771f9e189cfd2
| 36.952991 | 192 | 0.627632 | 4.863636 | false | false | false | false |
alessiobrozzi/firefox-ios
|
Sync/Synchronizers/Bookmarks/Merging.swift
|
2
|
10716
|
/* 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 Deferred
import Foundation
import Shared
import Storage
import XCGLogger
private let log = Logger.syncLogger
// Because generic protocols in Swift are a pain in the ass.
public protocol BookmarkStorer: class {
// TODO: this should probably return a timestamp.
func applyUpstreamCompletionOp(_ op: UpstreamCompletionOp, itemSources: ItemSources, trackingTimesInto local: LocalOverrideCompletionOp) -> Deferred<Maybe<POSTResult>>
}
open class UpstreamCompletionOp: PerhapsNoOp {
// Upload these records from the buffer, but with these child lists.
open var amendChildrenFromBuffer: [GUID: [GUID]] = [:]
// Upload these records from the mirror, but with these child lists.
open var amendChildrenFromMirror: [GUID: [GUID]] = [:]
// Upload these records from local, but with these child lists.
open var amendChildrenFromLocal: [GUID: [GUID]] = [:]
// Upload these records as-is.
open var records: [Record<BookmarkBasePayload>] = []
open let ifUnmodifiedSince: Timestamp?
open var isNoOp: Bool {
return records.isEmpty
}
public init(ifUnmodifiedSince: Timestamp?=nil) {
self.ifUnmodifiedSince = ifUnmodifiedSince
}
}
open class BookmarksMergeResult: PerhapsNoOp {
let uploadCompletion: UpstreamCompletionOp
let overrideCompletion: LocalOverrideCompletionOp
let bufferCompletion: BufferCompletionOp
let itemSources: ItemSources
open var isNoOp: Bool {
return self.uploadCompletion.isNoOp &&
self.overrideCompletion.isNoOp &&
self.bufferCompletion.isNoOp
}
func applyToClient(_ client: BookmarkStorer, storage: SyncableBookmarks, buffer: BookmarkBufferStorage) -> Success {
return client.applyUpstreamCompletionOp(self.uploadCompletion, itemSources: self.itemSources, trackingTimesInto: self.overrideCompletion)
>>> { storage.applyLocalOverrideCompletionOp(self.overrideCompletion, itemSources: self.itemSources) }
>>> { buffer.applyBufferCompletionOp(self.bufferCompletion, itemSources: self.itemSources) }
}
init(uploadCompletion: UpstreamCompletionOp, overrideCompletion: LocalOverrideCompletionOp, bufferCompletion: BufferCompletionOp, itemSources: ItemSources) {
self.uploadCompletion = uploadCompletion
self.overrideCompletion = overrideCompletion
self.bufferCompletion = bufferCompletion
self.itemSources = itemSources
}
static func NoOp(_ itemSources: ItemSources) -> BookmarksMergeResult {
return BookmarksMergeResult(uploadCompletion: UpstreamCompletionOp(), overrideCompletion: LocalOverrideCompletionOp(), bufferCompletion: BufferCompletionOp(), itemSources: itemSources)
}
}
// MARK: - Errors.
open class BookmarksMergeError: MaybeErrorType {
fileprivate let error: Error?
init(error: Error?=nil) {
self.error = error
}
open var description: String {
return "Merge error: \(self.error)"
}
}
open class BookmarksMergeConsistencyError: BookmarksMergeError {
override open var description: String {
return "Merge consistency error"
}
}
open class BookmarksMergeErrorTreeIsUnrooted: BookmarksMergeConsistencyError {
open let roots: Set<GUID>
public init(roots: Set<GUID>) {
self.roots = roots
}
override open var description: String {
return "Tree is unrooted: roots are \(self.roots)"
}
}
enum MergeState<T> {
case unknown // Default state.
case unchanged // Nothing changed: no work needed.
case remote // Take the associated remote value.
case local // Take the associated local value.
case new(value: T) // Take this synthesized value.
var isUnchanged: Bool {
if case .unchanged = self {
return true
}
return false
}
var isUnknown: Bool {
if case .unknown = self {
return true
}
return false
}
var label: String {
switch self {
case .unknown:
return "Unknown"
case .unchanged:
return "Unchanged"
case .remote:
return "Remote"
case .local:
return "Local"
case .new:
return "New"
}
}
}
func ==<T: Equatable>(lhs: MergeState<T>, rhs: MergeState<T>) -> Bool {
switch (lhs, rhs) {
case (.unknown, .unknown):
return true
case (.unchanged, .unchanged):
return true
case (.remote, .remote):
return true
case (.local, .local):
return true
case let (.new(lh), .new(rh)):
return lh == rh
default:
return false
}
}
/**
* Using this:
*
* You get one for the root. Then you give it children for the roots
* from the mirror.
*
* Then you walk those, populating the remote and local nodes by looking
* at the left/right trees.
*
* By comparing left and right, and doing value-based comparisons if necessary,
* a merge state is decided and assigned for both value and structure.
*
* One then walks both left and right child structures (both to ensure that
* all nodes on both left and right will be visited!) recursively.
*/
class MergedTreeNode {
let guid: GUID
let mirror: BookmarkTreeNode?
var remote: BookmarkTreeNode?
var local: BookmarkTreeNode?
var hasLocal: Bool { return self.local != nil }
var hasMirror: Bool { return self.mirror != nil }
var hasRemote: Bool { return self.remote != nil }
var valueState: MergeState<BookmarkMirrorItem> = MergeState.unknown
var structureState: MergeState<BookmarkTreeNode> = MergeState.unknown
var hasDecidedChildren: Bool {
return !self.structureState.isUnknown
}
var mergedChildren: [MergedTreeNode]?
// One-sided constructors.
static func forRemote(_ remote: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode {
let n = MergedTreeNode(guid: remote.recordGUID, mirror: mirror, structureState: MergeState.remote)
n.remote = remote
n.valueState = MergeState.remote
return n
}
static func forLocal(_ local: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode {
let n = MergedTreeNode(guid: local.recordGUID, mirror: mirror, structureState: MergeState.local)
n.local = local
n.valueState = MergeState.local
return n
}
static func forUnchanged(_ mirror: BookmarkTreeNode) -> MergedTreeNode {
let n = MergedTreeNode(guid: mirror.recordGUID, mirror: mirror, structureState: MergeState.unchanged)
n.valueState = MergeState.unchanged
return n
}
init(guid: GUID, mirror: BookmarkTreeNode?, structureState: MergeState<BookmarkTreeNode>) {
self.guid = guid
self.mirror = mirror
self.structureState = structureState
}
init(guid: GUID, mirror: BookmarkTreeNode?) {
self.guid = guid
self.mirror = mirror
}
// N.B., you cannot recurse down `decidedStructure`: you'll depart from the
// merged tree. You need to use `mergedChildren` instead.
fileprivate var decidedStructure: BookmarkTreeNode? {
switch self.structureState {
case .unknown:
return nil
case .unchanged:
return self.mirror
case .remote:
return self.remote
case .local:
return self.local
case let .new(node):
return node
}
}
func asUnmergedTreeNode() -> BookmarkTreeNode {
return self.decidedStructure ?? BookmarkTreeNode.unknown(guid: self.guid)
}
// Recursive. Starts returning Unknown when nodes haven't been processed.
func asMergedTreeNode() -> BookmarkTreeNode {
guard let decided = self.decidedStructure,
let merged = self.mergedChildren else {
return BookmarkTreeNode.unknown(guid: self.guid)
}
if case .folder = decided {
let children = merged.map { $0.asMergedTreeNode() }
return BookmarkTreeNode.folder(guid: self.guid, children: children)
}
return decided
}
var isFolder: Bool {
return self.mergedChildren != nil
}
func dump(_ indent: Int) {
precondition(indent < 200)
let r: Character = "R"
let l: Character = "L"
let m: Character = "M"
let ind = indenting(indent)
print(ind, "[V: ", box(self.remote, r), box(self.mirror, m), box(self.local, l), self.guid, self.valueState.label, "]")
guard self.isFolder else {
return
}
print(ind, "[S: ", self.structureState.label, "]")
if let children = self.mergedChildren {
print(ind, " ..")
for child in children {
child.dump(indent + 2)
}
}
}
}
private func box<T>(_ x: T?, _ c: Character) -> Character {
if x == nil {
return "□"
}
return c
}
private func indenting(_ by: Int) -> String {
return String(repeating: " ", count: by)
}
class MergedTree {
var root: MergedTreeNode
var deleteLocally: Set<GUID> = Set()
var deleteRemotely: Set<GUID> = Set()
var deleteFromMirror: Set<GUID> = Set()
var acceptLocalDeletion: Set<GUID> = Set()
var acceptRemoteDeletion: Set<GUID> = Set()
var allGUIDs: Set<GUID> {
var out = Set<GUID>([self.root.guid])
func acc(_ node: MergedTreeNode) {
guard let children = node.mergedChildren else {
return
}
out.formUnion(Set(children.map { $0.guid }))
children.forEach(acc)
}
acc(self.root)
return out
}
init(mirrorRoot: BookmarkTreeNode) {
self.root = MergedTreeNode(guid: mirrorRoot.recordGUID, mirror: mirrorRoot, structureState: MergeState.unchanged)
self.root.valueState = MergeState.unchanged
}
func dump() {
print("Deleted locally: \(self.deleteLocally.joined(separator: ", "))")
print("Deleted remotely: \(self.deleteRemotely.joined(separator: ", "))")
print("Deleted from mirror: \(self.deleteFromMirror.joined(separator: ", "))")
print("Accepted local deletions: \(self.acceptLocalDeletion.joined(separator: ", "))")
print("Accepted remote deletions: \(self.acceptRemoteDeletion.joined(separator: ", "))")
print("Root: ")
self.root.dump(0)
}
}
|
mpl-2.0
|
7bd036700b7c7265418ddc6741ee4b03
| 31.271084 | 192 | 0.645977 | 4.692948 | false | false | false | false |
masukomi/fenestro
|
fenestro-cli/main.swift
|
1
|
3072
|
//
// main.swift
// fenestro-cli
//
// Created by Kåre Morstøl on 26.10.15.
// Copyright © 2015 Corporate Runaways, LLC. All rights reserved.
//
import Foundation
func parseArguments (arguments: [String]? = nil) throws -> (name: String, path: NSURL?, showversion: Bool) {
let parser = ArgumentParser()
let filePathOption = parser.add(StringArgument(short: "p", long: "path",
helptext: "Load HTML to be rendered from the specified file. Use stdin if this option is not used."))
let versionOption = parser.add(BoolArgument(short: "v", long: "version",
helptext: "Print version and load an HTML page that displays the current version of the app."))
let nameOption = parser.add(StringArgument(short: "n", long: "name",
helptext: "The name that should be displayed in the sidebar."))
if let arguments = arguments {
try parser.parse(arguments, strict: true)
} else {
try parser.parse(strict: true)
}
guard !versionOption.value else { return ("",nil,true) }
let path = filePathOption.value.map(NSURL.init)
let name = nameOption.value ?? path?.lastPathComponent ?? " .html"
return (name, path, false)
}
func verifyOrCreateFile(name: String, _ maybepath: NSURL?, contents: ReadableStream) throws -> NSURL {
if let path = maybepath {
let newpath = NSURL(fileURLWithPath: main.tempdirectory + name)
try Files.copyItemAtURL(path, toURL: newpath)
return newpath
} else {
guard !contents.isTerminal() else {
let newpath = main.tempdirectory + ".fenestroreadme"
Files.createFileAtPath(newpath, contents: nil, attributes: nil)
return NSURL(fileURLWithPath: newpath)
}
let newpath = main.tempdirectory + name
var cache = try open(forWriting: newpath)
contents.writeTo(&cache)
return NSURL(fileURLWithPath: newpath)
}
}
func getVersionNumbers () -> (version: String, build: String) {
let info = NSBundle.mainBundle().infoDictionary!
return (info["CFBundleShortVersionString"] as! String, info["CFBundleVersion"] as! String)
}
func printVersionsAndOpenPage () throws {
let numbers = getVersionNumbers()
let numbersstring = numbers.version + " (" + numbers.build + ")"
print(numbersstring)
let versionpath = main.tempdirectory + "fenestro-version.html"
let versionfile = try open(forWriting: versionpath)
versionfile.writeln("<html><body>Fenestro version " + numbersstring + "</body></html>")
versionfile.close()
try runAndPrint("open", "-b", "com.corporaterunaways.Fenestro", versionpath)
}
extension ReadableStream {
func isTerminal () -> Bool {
return run(bash: "test -t \(filehandle.fileDescriptor) && echo true") == "true"
}
}
do {
let (name, maybepath, showversion) = try parseArguments()
guard !showversion else {
try printVersionsAndOpenPage()
exit(0)
}
let path = try verifyOrCreateFile(name, maybepath, contents: main.stdin)
try runAndPrint("open", "-b", "com.corporaterunaways.Fenestro", path.path!)
} catch let error as ArgumentError {
main.stderror.writeln(error)
exit(EX_USAGE)
} catch let error as NSError {
main.stderror.writeln(error.localizedDescription)
exit(EX_USAGE)
}
|
mit
|
d6914dfa9c8a40749a18668bd87cbda4
| 31.648936 | 108 | 0.723037 | 3.361446 | false | false | false | false |
silence0201/Swift-Study
|
Swifter/21Regex.playground/Contents.swift
|
1
|
1305
|
//: Playground - noun: a place where people can play
import Foundation
struct RegexHelper {
let regex: NSRegularExpression
init(_ pattern: String) throws {
try regex = NSRegularExpression(pattern: pattern,
options: .caseInsensitive)
}
func match(_ input: String) -> Bool {
let matches = regex.matches(in: input,
options: [],
range: NSMakeRange(0, input.utf16.count))
return matches.count > 0
}
}
let mailPattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
let matcher: RegexHelper
do {
matcher = try RegexHelper(mailPattern)
}
let maybeMailAddress = "[email protected]"
if matcher.match(maybeMailAddress) {
print("有效的邮箱地址")
}
// 输出:
// 有效的邮箱地址
precedencegroup MatchPrecedence {
associativity: none
higherThan: DefaultPrecedence
}
infix operator =~: MatchPrecedence
func =~(lhs: String, rhs: String) -> Bool {
do {
return try RegexHelper(rhs).match(lhs)
} catch _ {
return false
}
}
if "[email protected]" =~
"^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" {
print("有效的邮箱地址")
}
// 输出:
// 有效的邮箱地址
|
mit
|
f9c8699abf9dcf069efc8b6671ff4a45
| 21.160714 | 77 | 0.551168 | 3.618076 | false | false | false | false |
L-Zephyr/Drafter
|
Sources/Drafter/AST/OC/ImplementationNode.swift
|
1
|
1047
|
//
// ImplementationNode.swift
// Drafter
//
// Created by LZephyr on 2018/1/24.
//
import Foundation
class ImplementationNode: Node {
var className: String = ""
var methods: [MethodNode] = []
// sourcery:inline:ImplementationNode.AutoCodable
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
className = try container.decode(String.self, forKey: .className)
methods = try container.decode([MethodNode].self, forKey: .methods)
}
init() { }
// sourcery:end
}
extension ImplementationNode {
convenience init(_ clsName: String, _ methods: [MethodNode]) {
self.init()
self.className = clsName
self.methods = methods
}
}
// MARK: - Hashable
extension ImplementationNode: Hashable {
static func ==(lhs: ImplementationNode, rhs: ImplementationNode) -> Bool {
return lhs.className == rhs.className
}
var hashValue: Int {
return className.hashValue
}
}
|
mit
|
976492ccd800ff0af0e25bf30f6ac65d
| 23.348837 | 78 | 0.645654 | 4.204819 | false | false | false | false |
shamasshahid/SSValidationTextField
|
SampleProject/SampleProject/ViewController.swift
|
1
|
2146
|
//
// ViewController.swift
// SampleProject
//
// Created by Al Shamas Tufail on 29/05/2015.
// Copyright (c) 2015 Shamas Shahid. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var emailValidationTextField: SSValidationTextField!
var phoneValidationTextField: SSValidationTextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
emailValidationTextField.validityFunction = self.isValidEmail
emailValidationTextField.becomeFirstResponder()
phoneValidationTextField = SSValidationTextField(frame: CGRectMake(200, 200, 150, 50))
phoneValidationTextField!.validityFunction = self.isValidPhone
phoneValidationTextField!.delaytime = 1
phoneValidationTextField!.errorText = "Incorrect Format"
phoneValidationTextField!.successText = "Valid Format"
phoneValidationTextField!.borderStyle = UITextBorderStyle.RoundedRect
phoneValidationTextField!.placeholder = "Phone Validation"
phoneValidationTextField!.font = UIFont.systemFontOfSize(14)
self.view.addSubview(phoneValidationTextField!)
layout(emailValidationTextField, phoneValidationTextField!) { view1, view2 in
view2.height == 50
view2.width == 150
view2.centerX == view2.superview!.centerX
view2.centerY == view2.superview!.centerY
}
}
func isValidPhone(stringValue: String) -> Bool {
let phoneRegEx = "^\\d{10}$"
var phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegEx)
return phoneTest.evaluateWithObject(stringValue)
}
func isValidEmail(stringValue: String) ->Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(stringValue)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
c67bb7a1b0c992315e24676d79999322
| 36 | 94 | 0.691519 | 5.121718 | false | true | false | false |
Nub/SwiftTools
|
SwiftReddit/ViewController.swift
|
1
|
824
|
//
// ViewController.swift
// SwiftReddit
//
// Created by Zachry Thayer on 6/3/14.
// Copyright (c) 2014 Zachry Thayer. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var textView : UITextView
override func viewDidLoad(){
super.viewDidLoad()
loadData()
}
func loadData(){
// let redditURL = NSURL.URLWithTemplate("http://reddit.com/r/{subreddit}", values: ["subreddit":"motocross"])
// redditURL.GET(){ (response: NSHTTPURLResponse, data: AnyObject) in
// if data.isKindOfClass(NSError){
// self.textView.text = "Error:\(data.description)"
// } else {
// let responseData = data as NSData
// let text = NSString(data: responseData, encoding: NSUTF8StringEncoding)
// self.textView.text = text
// }
// }
}
}
|
mit
|
70018cea89748835b1dc729cea2a82cd
| 21.888889 | 111 | 0.651699 | 3.521368 | false | false | false | false |
ahmetkgunay/AKGPushAnimator
|
Source/AKGPushAnimator.swift
|
2
|
6292
|
//
// AKGPushAnimator.swift
// AKGPushAnimatorDemo
//
// Created by AHMET KAZIM GUNAY on 30/04/2017.
// Copyright © 2017 AHMET KAZIM GUNAY. All rights reserved.
//
import UIKit
@objc public protocol AKGPushAnimatorDelegate {
@objc optional func beganTransition()
@objc optional func cancelledTransition()
@objc optional func finishedTransition()
}
public class AKGPushAnimator: NSObject {
public var isReverseTransition = false
open var delegate : AKGPushAnimatorDelegate?
// MARK: Variables with Getters
var animatorScreenWidth : CGFloat {
get {
return UIScreen.main.bounds.width
}
}
var animatorScreenHeight : CGFloat {
get {
return UIScreen.main.bounds.height
}
}
var toViewPushedFrame : CGRect {
get {
return CGRect(x : 0,
y : 0,
width : self.animatorScreenWidth,
height : self.animatorScreenHeight)
}
}
var fromViewPushedFrame : CGRect {
get {
return CGRect(x : AKGPushAnimatorConstants.Common.dismissPosition,
y : 0,
width : self.animatorScreenWidth,
height : self.animatorScreenHeight)
}
}
var fromViewPopedFrame : CGRect {
get {
return CGRect(x : self.animatorScreenWidth,
y : 0,
width : self.animatorScreenWidth,
height : self.animatorScreenHeight)
}
}
var toViewPopedFrame : CGRect {
get {
return CGRect(x : 0,
y : 0,
width : self.animatorScreenWidth,
height : self.animatorScreenHeight)
}
}
fileprivate func animate(withTransitionContext transitionContext:UIViewControllerContextTransitioning,
toView: UIView,
fromView: UIView,
duration: TimeInterval,
delay: TimeInterval,
options: UIViewAnimationOptions = [],
animations: @escaping () -> Swift.Void) {
UIView.animate(withDuration: duration,
delay: delay,
options: options,
animations: animations) { (finished) in
if (transitionContext.transitionWasCancelled) {
toView.removeFromSuperview()
self.delegate?.cancelledTransition?()
} else {
fromView.removeFromSuperview()
self.delegate?.finishedTransition?()
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
fileprivate func addShadowToView(_ toView:UIView!) -> Swift.Void {
toView.layer.shadowOpacity = AKGPushAnimatorConstants.Common.shadowOpacity
toView.layer.shadowOffset = CGSize(width:0, height:3)
toView.layer.shadowColor = AKGPushAnimatorConstants.Common.shadowColor.cgColor
let shadowRect: CGRect = toView.bounds.insetBy(dx: 0, dy: 4); // inset top/bottom
toView.layer.shadowPath = UIBezierPath(rect: shadowRect).cgPath
}
}
extension AKGPushAnimator: UIViewControllerAnimatedTransitioning {
// MARK: UIViewControllerAnimatedTransitioning
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return AKGPushAnimatorConstants.Common.duration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
guard let toVC = transitionContext.viewController(forKey: .to),
let fromVC = transitionContext.viewController(forKey: .from),
let toView = toVC.view,
let fromView = fromVC.view else { return }
addShadowToView(toView)
delegate?.beganTransition?()
if !isReverseTransition {
containerView.addSubview(fromView)
containerView.addSubview(toView)
toView.frame = CGRect(x : animatorScreenWidth,
y : toView.frame.origin.y,
width : animatorScreenWidth,
height : animatorScreenHeight)
animate(withTransitionContext: transitionContext,
toView: toView,
fromView: fromView,
duration: AKGPushAnimatorConstants.Common.duration,
delay: 0,
options: AKGPushAnimatorConstants.Push.animateOption,
animations: {
fromView.frame = self.fromViewPushedFrame
toView.frame = self.toViewPushedFrame})
}
else {
containerView.addSubview(toView)
containerView.addSubview(fromView)
toView.frame = CGRect(x : AKGPushAnimatorConstants.Common.dismissPosition,
y : toView.frame.origin.y,
width : animatorScreenWidth,
height : animatorScreenHeight)
animate(withTransitionContext: transitionContext,
toView: toView,
fromView: fromView,
duration: AKGPushAnimatorConstants.Common.duration,
delay: 0,
options: AKGPushAnimatorConstants.Pop.animateOption,
animations: {
fromView.frame = self.fromViewPopedFrame
toView.frame = self.toViewPopedFrame })
}
}
}
|
mit
|
0f5665e544498adf1675113f58470415
| 35.575581 | 116 | 0.52901 | 6.084139 | false | false | false | false |
petrone/PetroneAPI_swift
|
PetroneAPI/Packets/PetronePacketLedColor.swift
|
1
|
1351
|
//
// PetronePacketLedColor.swift
// Petrone
//
// Created by Byrobot on 2017. 8. 8..
// Copyright © 2017년 Byrobot. All rights reserved.
//
import Foundation
class PetronePacketLedColor : PetronePacket {
public var led:PetroneLedBase = PetroneLedBase()
override init() {
super.init()
size = 5
}
override func getBluetoothData() -> Data {
var sendArray = Data()
sendArray.append(PetroneDataType.LedModeColor.rawValue)
sendArray.append(led.mode)
sendArray.append(led.red)
sendArray.append(led.green)
sendArray.append(led.blue)
sendArray.append(led.interval)
return sendArray
}
override func getSerialData() -> Data {
var baseArray = Data()
baseArray.append(PetroneDataType.LedModeColor.rawValue)
baseArray.append(UInt8(size))
baseArray.append(led.mode)
baseArray.append(led.red)
baseArray.append(led.green)
baseArray.append(led.blue)
baseArray.append(led.interval)
var sendArray = Data()
sendArray.append(UInt8(0x0a))
sendArray.append(UInt8(0x55))
sendArray.append(baseArray)
sendArray.append(contentsOf: PetroneCRC.getCRC(data: baseArray, dataLength: size+2))
return sendArray
}
}
|
mit
|
826e96df518b4ebf6bc51bfc56460aee
| 26.510204 | 92 | 0.62908 | 3.77591 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/Model/Option/PollutedGarden/Plant/StrategyPoison/MOptionPollutedGardenPlantPoisonStrategyWait.swift
|
1
|
968
|
import Foundation
class MOptionPollutedGardenPlantPoisonStrategyWait:MGameStrategy<
MOptionPollutedGardenPlantPoison,
MOptionPollutedGarden>
{
private var elapsedTime:TimeInterval?
private let kDelay:TimeInterval = 0.3
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionPollutedGarden>)
{
if let startTime:TimeInterval = self.elapsedTime
{
let deltaTime:TimeInterval = elapsedTime - startTime
if deltaTime > kDelay
{
model.fade()
}
}
else
{
self.elapsedTime = elapsedTime
guard
let scene:VOptionPollutedGardenScene = scene as? VOptionPollutedGardenScene
else
{
return
}
scene.addPoison(model:model)
}
}
}
|
mit
|
ec707cb9ea6d2287a2f3e595d3ead5bb
| 23.820513 | 91 | 0.538223 | 6.205128 | false | false | false | false |
Tyrant2013/LeetCodePractice
|
LeetCodePractice/Easy/35_Search_Insert_Position.swift
|
1
|
1122
|
//
// Search_Insert_Position.swift
// LeetCodePractice
//
// Created by 庄晓伟 on 2018/2/11.
// Copyright © 2018年 Zhuang Xiaowei. All rights reserved.
//
import UIKit
/// 优化:使用二分查找法
class Search_Insert_Position: Solution {
override func ExampleTest() {
[[1,3,5,6,5],//2
[1,3,5,6,2],//1
[1,3,5,6,7],//4
[1,3,5,6,0]].forEach { nums in
let list = Array(nums.dropLast())
let target = nums.last!
print("array: \(list), target: \(target), res: \(self.searchInsert(list, target))")
}
}
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
var findIndex = -1
var insertIndex = -1
for index in 0..<nums.count {
let num = nums[index]
if num == target {
findIndex = index
break
}
if target < num {
insertIndex = index
break
}
insertIndex = index + 1
}
return findIndex != -1 ? findIndex : insertIndex
}
}
|
mit
|
62a26803cea432ec4fc8b6addca189ed
| 25.658537 | 99 | 0.482159 | 3.808362 | false | false | false | false |
zyhndesign/SDX_DG
|
sdxdg/sdxdg/MineViewController.swift
|
1
|
22612
|
//
// MineViewController.swift
// sdxdg
//
// Created by lotusprize on 16/12/14.
// Copyright © 2016年 geekTeam. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
import Charts
class MineViewController: UIViewController {
@IBOutlet var userInfoPanel: UIView!
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var userName: UILabel!
@IBOutlet var userIcon: UIImageView!
let userId = LocalDataStorageUtil.getUserIdFromUserDefaults()
var backDataIcon:UIImageView?
var backDataLabel:UILabel?
var timeSegmentControl:UISegmentedControl?
var chartView:UIImageView?
var myMatchViewIcon:UIImageView?
var myMatchViewLabel:UILabel?
var myMatchAllLabel:UILabel?
var myMatchArrowImageView:UIImageView?
var myMatchPushImageView:UIImageView?
var myMatchPushLabel:UILabel?
var myMatchFeedbackImageView:UIImageView?
var myMatchFeedbackLabel:UILabel?
var myMatchDraftImageView:UIImageView?
var myMatchDraftLabel:UILabel?
var hotMatchImageView:UIImageView?
var hotMatchLabel:UILabel?
var hotMatchALLLabel:UILabel?
var hotMatchArrowImageView:UIImageView?
var top3ImageView1:UIImageView?
var top3ImageView2:UIImageView?
var top3ImageView3:UIImageView?
var feedbackModels:[FeedbackModel] = []
let lineChart = LineChartView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let screenWidth:CGFloat = UIScreen.main.bounds.width
//let screenHeight:CGFloat = UIScreen.main.bounds.height
userName.text = LocalDataStorageUtil.getUserInfoByKey(key: "username")
let userInfoPanelGesture:UIGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(panelTapped(sender:)))
userInfoPanel.addGestureRecognizer(userInfoPanelGesture)
backDataIcon = UIImageView.init(frame: CGRect.init(x: 10, y: 15, width: 20, height: 20))
backDataIcon?.image = UIImage.init(named: "backDataIcon")
scrollView.addSubview(backDataIcon!)
backDataLabel = UILabel.init(frame: CGRect.init(x: 40, y: 15, width: 100, height: 30))
backDataLabel?.text = "反馈数据"
backDataLabel?.font = UIFont.init(name: "Helvetica", size: 12)
scrollView.addSubview(backDataLabel!)
let graphView:UIView = UIView.init(frame: CGRect.init(x: 0, y: 50, width: screenWidth, height: 230))
graphView.backgroundColor = UIColor.white
let items = ["周", "月", "年"]
timeSegmentControl = UISegmentedControl(items:items)
timeSegmentControl?.frame = CGRect.init(x: 30, y: 15, width: screenWidth - 60, height: 30)
timeSegmentControl?.selectedSegmentIndex = 0
timeSegmentControl?.tintColor = UIColor.init(red: 209/255.0, green: 214/255.0, blue: 218/255.0, alpha: 1)
timeSegmentControl?.addTarget(self, action: #selector(segmentControlClick(sender:)), for: UIControlEvents.valueChanged)
graphView.addSubview(timeSegmentControl!)
lineChart.frame = CGRect.init(x: 30, y: 55, width: screenWidth - 60, height: 160)
graphView.addSubview(lineChart)
loadStatisticsData(cycle:1)
/*
chartView = UIImageView.init(frame: CGRect.init(x: 30, y: 55, width: screenWidth - 60, height: 160))
chartView?.image = UIImage.init(named: "chartWeek")
graphView.addSubview(chartView!)
*/
scrollView.addSubview(graphView)
myMatchViewIcon = UIImageView.init(frame: CGRect.init(x: 10, y: 290, width: 20, height: 20))
myMatchViewIcon?.image = UIImage.init(named: "myMatchIcon")
scrollView.addSubview(myMatchViewIcon!)
myMatchViewLabel = UILabel.init(frame: CGRect.init(x: 40, y: 290, width: 100, height: 20))
myMatchViewLabel?.text = "我的搭配"
myMatchViewLabel?.font = UIFont.init(name: "Helvetica", size: 12)
scrollView.addSubview(myMatchViewLabel!)
let myAllMatchGesture1:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(myMatchAllClick(sender:)))
myMatchAllLabel = UILabel.init(frame: CGRect.init(x: screenWidth - 70, y: 290, width: 30, height: 20))
myMatchAllLabel?.text = "全部"
myMatchAllLabel?.font = UIFont.init(name: "Helvetica", size: 12)
myMatchAllLabel?.addGestureRecognizer(myAllMatchGesture1)
myMatchAllLabel?.isUserInteractionEnabled = true
scrollView.addSubview(myMatchAllLabel!)
let myAllMatchGesture2:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(myMatchAllClick(sender:)))
myMatchArrowImageView = UIImageView.init(frame: CGRect.init(x: screenWidth - 30, y: 293, width: 10, height: 15))
myMatchArrowImageView?.image = UIImage.init(named: "rightArrow")
myMatchArrowImageView?.addGestureRecognizer(myAllMatchGesture2)
myMatchArrowImageView?.isUserInteractionEnabled = true
scrollView.addSubview(myMatchArrowImageView!)
let myMatchView:UIView = UIView.init(frame: CGRect.init(x: 0, y: 320, width: screenWidth, height: 65))
myMatchView.backgroundColor = UIColor.white
let pushGesture:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(pushImageClick(sender:)))
pushGesture.numberOfTapsRequired = 1
myMatchPushImageView = UIImageView.init(frame: CGRect.init(x: screenWidth / 3 / 2 - 25, y: 5, width: 30, height: 30))
myMatchPushImageView?.image = UIImage.init(named: "push")
myMatchPushImageView?.isUserInteractionEnabled = true
myMatchPushImageView?.addGestureRecognizer(pushGesture)
myMatchView.addSubview(myMatchPushImageView!)
myMatchPushLabel = UILabel.init(frame: CGRect.init(x: screenWidth / 3 / 2 - 30, y: 45, width: 40, height: 20))
myMatchPushLabel?.text = "推送"
myMatchPushLabel?.textAlignment = NSTextAlignment.center
myMatchPushLabel?.font = UIFont.init(name: "Helvetica", size: 12)
myMatchView.addSubview(myMatchPushLabel!)
let backGesture:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(backImageClick(sender:)))
backGesture.numberOfTapsRequired = 1
myMatchFeedbackImageView = UIImageView.init(frame: CGRect.init(x: screenWidth / 3 + screenWidth / 3 / 2 - 25, y: 5, width: 30, height: 30))
myMatchFeedbackImageView?.image = UIImage.init(named: "feedback")
myMatchFeedbackImageView?.isUserInteractionEnabled = true
myMatchFeedbackImageView?.addGestureRecognizer(backGesture)
myMatchView.addSubview(myMatchFeedbackImageView!)
myMatchFeedbackLabel = UILabel.init(frame: CGRect.init(x: screenWidth / 3 + screenWidth / 3 / 2 - 30, y: 45, width: 40, height: 20))
myMatchFeedbackLabel?.text = "反馈"
myMatchFeedbackLabel?.textAlignment = NSTextAlignment.center
myMatchFeedbackLabel?.font = UIFont.init(name: "Helvetica", size: 12)
myMatchView.addSubview(myMatchFeedbackLabel!)
let draftGesture:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(draftImageClick(sender:)))
draftGesture.numberOfTapsRequired = 1
myMatchDraftImageView = UIImageView.init(frame: CGRect.init(x: screenWidth / 3 * 2 + screenWidth / 3 / 2 - 25, y: 5, width: 30, height: 30))
myMatchDraftImageView?.image = UIImage.init(named: "draftbox")
myMatchDraftImageView?.isUserInteractionEnabled = true
myMatchDraftImageView?.addGestureRecognizer(draftGesture)
myMatchView.addSubview(myMatchDraftImageView!)
myMatchDraftLabel = UILabel.init(frame: CGRect.init(x: screenWidth / 3 * 2 + screenWidth / 3 / 2 - 30, y: 45, width: 40, height: 20))
myMatchDraftLabel?.text = "草稿箱"
myMatchDraftLabel?.textAlignment = NSTextAlignment.center
myMatchDraftLabel?.font = UIFont.init(name: "Helvetica", size: 12)
myMatchView.addSubview(myMatchDraftLabel!)
scrollView.addSubview(myMatchView)
hotMatchImageView = UIImageView.init(frame: CGRect.init(x: 10, y: 395, width: 20, height: 20))
hotMatchImageView?.image = UIImage.init(named: "hotMatchIcon")
scrollView.addSubview(hotMatchImageView!)
hotMatchLabel = UILabel.init(frame: CGRect.init(x: 40, y: 395, width: 60, height: 20))
hotMatchLabel?.text = "热门搭配"
hotMatchLabel?.font = UIFont.init(name: "Helvetica", size: 12)
scrollView.addSubview(hotMatchLabel!)
let hotMatchGesture1:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(hotMatchAllClick(sender:)))
hotMatchALLLabel = UILabel.init(frame: CGRect.init(x: screenWidth - 70, y: 395, width: 30, height: 20))
hotMatchALLLabel?.text = "全部"
hotMatchALLLabel?.font = UIFont.init(name: "Helvetica", size: 12)
hotMatchALLLabel?.isUserInteractionEnabled = true
hotMatchALLLabel?.addGestureRecognizer(hotMatchGesture1)
scrollView.addSubview(hotMatchALLLabel!)
let hotMatchGesture2:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(hotMatchAllClick(sender:)))
hotMatchArrowImageView = UIImageView.init(frame: CGRect.init(x: screenWidth - 30, y: 398, width: 10, height: 15))
hotMatchArrowImageView?.image = UIImage.init(named: "rightArrow")
hotMatchArrowImageView?.isUserInteractionEnabled = true
hotMatchArrowImageView?.addGestureRecognizer(hotMatchGesture2)
scrollView.addSubview(hotMatchArrowImageView!)
let hotView:UIView = UIView.init(frame: CGRect.init(x: 0, y: 425, width: screenWidth, height: 130))
let borderColor:CGColor = UIColor.init(red: 253/255.0, green: 220/255.0, blue: 56/255.0, alpha: 1.0).cgColor
top3ImageView1 = UIImageView.init(frame: CGRect.init(x: 10, y: 10, width: (screenWidth - 60) / 3, height: (screenWidth - 60) / 3))
top3ImageView1?.layer.borderWidth = 1.0
top3ImageView1?.layer.borderColor = borderColor
top3ImageView1?.tag = 1
top3ImageView1?.isUserInteractionEnabled = true
top3ImageView1?.contentMode = .scaleAspectFit
top3ImageView1?.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(hotDetailViewClick(sender:))))
hotView.addSubview(top3ImageView1!)
top3ImageView2 = UIImageView.init(frame: CGRect.init(x: screenWidth / 2 - ((screenWidth - 60) / 3) / 2, y: 10, width: (screenWidth - 60) / 3, height: (screenWidth - 60) / 3))
top3ImageView2?.layer.borderWidth = 1.0
top3ImageView2?.layer.borderColor = borderColor
top3ImageView2?.tag = 2
top3ImageView2?.isUserInteractionEnabled = true
top3ImageView2?.contentMode = .scaleAspectFit
top3ImageView2?.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(hotDetailViewClick(sender:))))
hotView.addSubview(top3ImageView2!)
top3ImageView3 = UIImageView.init(frame: CGRect.init(x: ((screenWidth - 60) / 3) * 2 + 50, y: 10, width: (screenWidth - 60) / 3, height: (screenWidth - 60) / 3))
top3ImageView3?.layer.borderWidth = 1.0
top3ImageView3?.layer.borderColor = borderColor
top3ImageView3?.tag = 3
top3ImageView3?.isUserInteractionEnabled = true
top3ImageView3?.contentMode = .scaleAspectFit
top3ImageView3?.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(hotDetailViewClick(sender:))))
hotView.addSubview(top3ImageView3!)
scrollView.addSubview(hotView)
scrollView.contentSize = CGSize.init(width: screenWidth, height: 580)
self.initHotImage()
NotificationCenter.default.addObserver(self, selector:#selector(self.updateHeaderIcon(notifaction:)), name: NSNotification.Name(rawValue: "HeadIcon"), object: nil)
let headIcon:String = LocalDataStorageUtil.getUserInfoByKey(key: "headicon")
if !(headIcon == ""){
userIcon.af_setImage(withURL: URL.init(string: headIcon)!)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
NotificationCenter.default.removeObserver(self)
}
func updateHeaderIcon(notifaction: NSNotification){
let headicon:UIImage = (notifaction.object as? UIImage)!
userIcon.image = headicon
}
@IBAction func settingBtnClick(_ sender: Any) {
let view = self.storyboard?.instantiateViewController(withIdentifier: "settingView")
self.navigationController?.pushViewController(view!, animated: true)
}
func panelTapped(sender:UITapGestureRecognizer){
let view = self.storyboard?.instantiateViewController(withIdentifier: "PersonalInfoView")
self.navigationController?.pushViewController(view!, animated: true)
}
func segmentControlClick(sender:UISegmentedControl){
switch sender.selectedSegmentIndex {
case 0:
//let weeks = ["1周", "2周", "3周", "4周", "5周", "6周"]
//let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0]
//setChart(weeks, values: unitsSold)
loadStatisticsData(cycle:1)
case 1:
loadStatisticsData(cycle:2)
case 2:
loadStatisticsData(cycle:3)
default:
loadStatisticsData(cycle:1)
}
}
func myMatchAllClick(sender: Any){
print("click...")
let view:MyMatchViewController = self.storyboard?.instantiateViewController(withIdentifier: "MyMatchView") as! MyMatchViewController
view.btnInitTag = 0
self.navigationController?.pushViewController(view, animated: true)
}
func hotMatchAllClick(sender: Any){
let view = self.storyboard?.instantiateViewController(withIdentifier: "HotMatchView")
self.navigationController?.pushViewController(view!, animated: true)
}
func pushImageClick(sender:Any){
let view:MyMatchViewController = self.storyboard?.instantiateViewController(withIdentifier: "MyMatchView") as! MyMatchViewController
view.btnInitTag = 1
self.navigationController?.pushViewController(view, animated: true)
}
func backImageClick(sender:Any){
let view:MyMatchViewController = self.storyboard?.instantiateViewController(withIdentifier: "MyMatchView") as! MyMatchViewController
view.btnInitTag = 2
self.navigationController?.pushViewController(view, animated: true)
}
func draftImageClick(sender:Any){
let view:MyMatchViewController = self.storyboard?.instantiateViewController(withIdentifier: "MyMatchView") as! MyMatchViewController
view.btnInitTag = 3
self.navigationController?.pushViewController(view, animated: true)
}
func hotDetailViewClick(sender:UITapGestureRecognizer){
let tag:Int = sender.view!.tag
var feedbackModel:FeedbackModel?
if (tag == 1){
if feedbackModels.count > 0{
feedbackModel = feedbackModels[0]
}
}
else if (tag == 2){
if feedbackModels.count > 1{
feedbackModel = feedbackModels[1]
}
}
else if (tag == 3){
if feedbackModels.count > 2{
feedbackModel = feedbackModels[2]
}
}
if let feedbackModelObject = feedbackModel{
let view:HotMatchDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "HotMatchDetailView") as! HotMatchDetailViewController
view.feedbackModel = feedbackModelObject
self.navigationController?.pushViewController(view, animated: true)
}
}
func loadStatisticsData(cycle:Int){
let parameters:Parameters = ["userId":userId]
var url = "";
if (cycle == 1){
url = ConstantsUtil.APP_GET_STATISTICS_WEEK_DATA;
}
else if (cycle == 2){
url = ConstantsUtil.APP_GET_STATISTICS_MONTH_DATA;
}
else if (cycle == 3){
url = ConstantsUtil.APP_GET_STATISTICS_YEAR_DATA;
}
Alamofire.request(url,method:.get,parameters:parameters).responseJSON { response in
if let JSON = response.result.value{
let result = JSON as! NSDictionary
let dict:NSDictionary = result["object"] as! NSDictionary
var cycle:[String] = []
var unitsSold:[Double] = []
for (key, value) in dict {
cycle.append(key as! String)
print(value)
unitsSold.append((value as! NSNumber).doubleValue)
}
self.setChart(cycle, values: unitsSold)
}
}
}
func initHotImage(){
let parameters:Parameters = ["userId":userId]
Alamofire.request(ConstantsUtil.APP_MATCH_THREE_HOT_FEEDBACK_URL,method:.post,parameters:parameters).responseObject { (response: DataResponse<FeedbackServerModel>) in
let feedbackServerModel = response.result.value
if (feedbackServerModel?.resultCode == 200){
if let feedbackServerModelObject = feedbackServerModel?.object{
if (feedbackServerModelObject.count > 0){
if (feedbackServerModelObject.count == 1){
if let model1Url = feedbackServerModelObject[0].modelurl{
self.top3ImageView1?.af_setImage(withURL: URL.init(string: model1Url)!)
self.feedbackModels.append(feedbackServerModelObject[0])
}
}
else if (feedbackServerModelObject.count == 2){
if let model1Url = feedbackServerModelObject[0].modelurl{
self.top3ImageView1?.af_setImage(withURL: URL.init(string: model1Url)!)
self.feedbackModels.append(feedbackServerModelObject[0])
}
if let model2Url = feedbackServerModelObject[1].modelurl{
self.top3ImageView2?.af_setImage(withURL: URL.init(string: model2Url)!)
self.feedbackModels.append(feedbackServerModelObject[1])
}
}
else if (feedbackServerModelObject.count == 3){
if let model1Url = feedbackServerModelObject[0].modelurl{
self.top3ImageView1?.af_setImage(withURL: URL.init(string: model1Url)!)
self.feedbackModels.append(feedbackServerModelObject[0])
}
if let model2Url = feedbackServerModelObject[1].modelurl{
self.top3ImageView2?.af_setImage(withURL: URL.init(string: model2Url)!)
self.feedbackModels.append(feedbackServerModelObject[1])
}
if let model3Url = feedbackServerModelObject[2].modelurl{
self.top3ImageView3?.af_setImage(withURL: URL.init(string: model3Url)!)
self.feedbackModels.append(feedbackServerModelObject[2])
}
}
}
else{
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "无热门数据"
hud.hide(animated: true, afterDelay: 2.0)
}
}
}
}
}
func setChart(_ dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "单位:人次")
let lineChartData = LineChartData(dataSet: lineChartDataSet)
lineChart.data = lineChartData
//右下角图标描述
lineChart.chartDescription?.text = ""
lineChart.legend.textColor = UIColor.darkGray
//设置X轴坐标
lineChart.xAxis.valueFormatter = IndexAxisValueFormatter(values: dataPoints)
lineChart.xAxis.granularity = 1.0
lineChart.xAxis.labelPosition = .bottom
lineChart.xAxis.drawGridLinesEnabled = false
lineChart.xAxis.axisLineColor = UIColor.brown
lineChart.xAxis.labelTextColor = UIColor.lightGray
lineChart.rightAxis.drawAxisLineEnabled = false
//不显示右侧Y轴数字
lineChart.rightAxis.enabled = false
lineChart.leftAxis.axisLineColor = UIColor.darkGray
lineChart.leftAxis.gridColor = UIColor.lightGray
lineChart.leftAxis.labelTextColor = UIColor.lightGray
//设置双击坐标轴是否能缩放
lineChart.scaleXEnabled = false
lineChart.scaleYEnabled = false
//外圆
lineChartDataSet.setCircleColor(UIColor.init(red: 198/255.0, green: 198/255.0, blue: 198/255.0, alpha: 0.5))
lineChartDataSet.circleHoleColor = UIColor.init(red: 255/255.0, green: 200/255.0, blue: 10/255.0, alpha: 1)
lineChartDataSet.colors = [UIColor.init(red: 255/255.0, green: 200/255.0, blue: 10/255.0, alpha: 1)]
//线条上的文字
lineChartDataSet.valueColors = [UIColor.darkGray]
//添加显示动画
lineChart.animate(xAxisDuration: 1)
}
}
|
apache-2.0
|
e70d0f016ba109ced62b890940f64c03
| 46.831557 | 182 | 0.639861 | 4.63109 | false | false | false | false |
Keanyuan/SwiftContact
|
SwiftContent/SwiftContent/Classes/类和结构体/Resolution.swift
|
1
|
2202
|
//
// Resolution.swift
// SwiftContent
//
// Created by 祁志远 on 2017/6/16.
// Copyright © 2017年 祁志远. All rights reserved.
//
import UIKit
struct Resolution {
var width = 0
var height = 0
}
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double){
self = Point(x: x + deltaX, y: y + deltaY)
}
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
struct Cuboid {
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double {
return width * height * depth
}
}
class VideoMode {
//所有结构体都有一个自动生成的成员逐一构造器,用于初始化新结构体实例中成员的属性。新实例中各个属性的初始值可以通过属性的名称传递到成员逐一构造器之中:
var resolution = Resolution(width: 640, height: 480)
var interlaced = false
var frameRate = 0.0
var name: String?
//必须将延迟存储属性声明成变量(使用 var 关键字),因为属性的初始值可能在实例构造完成之后才会得到。而常量属性在构造过程完成之前必须要有初始值,因此无法声明成延迟属性。
lazy var importer = Resolution()
//与结构体不同,类实例没有默认的成员逐一构造器
// let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
// print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
}
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
|
mit
|
81a230c210e172014ba8598a7828474c
| 20.588235 | 91 | 0.580381 | 3.180243 | false | false | false | false |
angeloashmore/PromiseKitClosures
|
PromiseKitClosures.swift
|
2
|
1209
|
//
// PromiseKitClosures.swift
//
// Created by Angelo Ashmore on 6/2/15.
// Copyright (c) 2015 Angelo Ashmore. All rights reserved.
//
import Foundation
public struct PromiseKitClosures {
public static func ResultBlock<T>(#fulfill: T -> Void, reject: NSError -> Void, passthrough: T? = nil) -> (T, NSError?) -> () {
return { (result: T, error: NSError?) in
if let error = error {
reject(error)
} else {
fulfill(passthrough ?? result)
}
}
}
public static func OptionalResultBlock<T>(#fulfill: T -> Void, reject: NSError -> Void, passthrough: T? = nil) -> (T?, NSError?) -> () {
return { (result: T?, error: NSError?) in
if let error = error {
reject(error)
} else {
fulfill(passthrough ?? result!)
}
}
}
public static func ErrorBlock<T>(#fulfill: T -> Void, reject: NSError -> Void, passthrough: T) -> (NSError?) -> () {
return { (error: NSError?) in
if let error = error {
reject(error)
} else {
fulfill(passthrough)
}
}
}
}
|
mit
|
010c5a93961527e4e3477d58133c1650
| 29.225 | 140 | 0.507858 | 4.242105 | false | false | false | false |
sol/aeson
|
tests/JSONTestSuite/parsers/test_PMJSON_1_1_0/Parser.swift
|
6
|
26296
|
//
// Decoder.swift
// PMJSON
//
// Created by Kevin Ballard on 10/8/15.
// Copyright © 2016 Postmates.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
/// A streaming JSON parser that consumes a sequence of unicode scalars.
public struct JSONParser<Seq: Sequence>: Sequence where Seq.Iterator.Element == UnicodeScalar {
public init(_ seq: Seq) {
base = seq
}
/// If `true`, trailing commas in dictionaries and arrays are treated as an error.
/// Defaults to `false`.
public var strict: Bool = false
/// If `true`, the parser will parse a stream of json values with optional whitespace delimiters.
/// The default value of `false` makes the parser emit an error if there's any non-whitespace
/// characters after the first JSON value.
///
/// For example, with the input `"[1] [2,3]"`, if `streaming` is `true` the parser will emit
/// events for the second JSON array after the first one, but if `streaming` is `false` it will
/// emit an error upon encountering the second `[`.
///
/// - Note: If `streaming` is `true` and the input is empty (or contains only whitespace), the
/// parser will return `nil` instead of emitting an `.unexpectedEOF` error.
public var streaming: Bool = false
public func makeIterator() -> JSONParserIterator<Seq.Iterator> {
var iter = JSONParserIterator(base.makeIterator())
iter.strict = strict
iter.streaming = streaming
return iter
}
private let base: Seq
}
/// The iterator for `JSONParser`.
public struct JSONParserIterator<Iter: IteratorProtocol>: JSONEventIterator where Iter.Element == UnicodeScalar {
public init(_ iter: Iter) {
base = PeekIterator(iter)
}
/// If `true`, trailing commas in dictionaries and arrays are treated as an error.
/// Defaults to `false`.
public var strict: Bool = false
/// If `true`, the parser will parse a stream of json values with optional whitespace delimiters.
/// The default value of `false` makes the parser emit an error if there's any non-whitespace
/// characters after the first JSON value.
///
/// For example, with the input `"[1] [2,3]"`, if `streaming` is `true` the parser will emit
/// events for the second JSON array after the first one, but if `streaming` is `false` it will
/// emit an error upon encountering the second `[`.
///
/// - Note: If `streaming` is `true` and the input is empty (or contains only whitespace), the
/// parser will return `nil` instead of emitting an `.unexpectedEOF` error.
public var streaming: Bool = false
public mutating func next() -> JSONEvent? {
do {
// the only states that may loop are parseArrayComma, parseObjectComma, and (if streaming) parseEnd,
// which are all guaranteed to shift to other states (if they don't return) so the loop is finite
while true {
switch state {
case .parseArrayComma:
switch skipWhitespace() {
case ","?:
state = .parseArray(first: false)
continue
case "]"?:
try popStack()
return .arrayEnd
case .some:
throw error(.invalidSyntax)
case nil:
throw error(.unexpectedEOF)
}
case .parseObjectComma:
switch skipWhitespace() {
case ","?:
state = .parseObjectKey(first: false)
continue
case "}"?:
try popStack()
return .objectEnd
case .some:
throw error(.invalidSyntax)
case nil:
throw error(.unexpectedEOF)
}
case .initial:
guard let c = skipWhitespace() else {
if streaming {
state = .finished
return nil
} else {
throw error(.unexpectedEOF)
}
}
let evt = try parseValue(c)
switch evt {
case .arrayStart, .objectStart:
break
default:
state = .parseEnd
}
return evt
case .parseArray(let first):
guard let c = skipWhitespace() else { throw error(.unexpectedEOF) }
switch c {
case "]":
if !first && strict {
throw error(.trailingComma)
}
try popStack()
return .arrayEnd
case ",":
throw error(.missingValue)
default:
let evt = try parseValue(c)
switch evt {
case .arrayStart, .objectStart:
break
default:
state = .parseArrayComma
}
return evt
}
case .parseObjectKey(let first):
guard let c = skipWhitespace() else { throw error(.unexpectedEOF) }
switch c {
case "}":
if !first && strict {
throw error(.trailingComma)
}
try popStack()
return .objectEnd
case ",", ":":
throw error(.missingKey)
default:
let evt = try parseValue(c)
switch evt {
case .stringValue:
state = .parseObjectValue
default:
throw error(.nonStringKey)
}
return evt
}
case .parseObjectValue:
guard skipWhitespace() == ":" else { throw error(.expectedColon) }
guard let c = skipWhitespace() else { throw error(.unexpectedEOF) }
switch c {
case ",", "}":
throw error(.missingValue)
default:
let evt = try parseValue(c)
switch evt {
case .arrayStart, .objectStart:
break
default:
state = .parseObjectComma
}
return evt
}
case .parseEnd:
if streaming {
state = .initial
} else if skipWhitespace() != nil {
throw error(.trailingCharacters)
} else {
state = .finished
return nil
}
case .finished:
return nil
}
}
} catch let error as JSONParserError {
state = .finished
return .error(error)
} catch {
fatalError("unexpected error \(error)")
}
}
private mutating func popStack() throws {
if stack.popLast() == nil {
fatalError("exhausted stack")
}
switch stack.last {
case .array?:
state = .parseArrayComma
case .object?:
state = .parseObjectComma
case nil:
state = .parseEnd
}
}
private mutating func parseValue(_ c: UnicodeScalar) throws -> JSONEvent {
switch c {
case "[":
state = .parseArray(first: true)
stack.append(.array)
return .arrayStart
case "{":
state = .parseObjectKey(first: true)
stack.append(.object)
return .objectStart
case "\"":
var scalars = String.UnicodeScalarView()
while let c = bump() {
switch c {
case "\"":
return .stringValue(String(scalars))
case "\\":
let c = try bumpRequired()
switch c {
case "\"", "\\", "/": scalars.append(c)
case "b": scalars.append(UnicodeScalar(0x8))
case "f": scalars.append(UnicodeScalar(0xC))
case "n": scalars.append("\n" as UnicodeScalar)
case "r": scalars.append("\r" as UnicodeScalar)
case "t": scalars.append("\t" as UnicodeScalar)
case "u":
let codeUnit = try parseFourHex()
if UTF16.isLeadSurrogate(codeUnit) {
guard try (bumpRequired() == "\\" && bumpRequired() == "u") else {
throw error(.loneLeadingSurrogateInUnicodeEscape)
}
let trail = try parseFourHex()
if UTF16.isTrailSurrogate(trail) {
let lead = UInt32(codeUnit)
let trail = UInt32(trail)
// NB: The following is split up to avoid exponential time complexity in the type checker
let leadComponent: UInt32 = (lead - 0xD800) << 10
let trailComponent: UInt32 = trail - 0xDC00
let scalar = UnicodeScalar(leadComponent + trailComponent + 0x10000)!
scalars.append(scalar)
} else {
throw error(.loneLeadingSurrogateInUnicodeEscape)
}
} else {
scalars.append(UnicodeScalar(codeUnit)!)
}
default:
throw error(.invalidEscape)
}
case "\0"..."\u{1F}":
throw error(.invalidSyntax)
default:
scalars.append(c)
}
}
throw error(.unexpectedEOF)
case "-", "0"..."9":
var tempBuffer: ContiguousArray<Int8>
if let buffer = replace(&self.tempBuffer, with: nil) {
tempBuffer = buffer
tempBuffer.removeAll(keepingCapacity: true)
} else {
tempBuffer = ContiguousArray()
tempBuffer.reserveCapacity(12)
}
defer { self.tempBuffer = tempBuffer }
tempBuffer.append(Int8(truncatingBitPattern: c.value))
outerLoop: while let c = base.peek() {
switch c {
case "0"..."9":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
case ".":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
guard let c = bump(), case "0"..."9" = c else { throw error(.invalidNumber) }
tempBuffer.append(Int8(truncatingBitPattern: c.value))
loop: while let c = base.peek() {
switch c {
case "0"..."9":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
case "e", "E":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
guard let c = bump() else { throw error(.invalidNumber) }
tempBuffer.append(Int8(truncatingBitPattern: c.value))
switch c {
case "-", "+":
guard let c = bump(), case "0"..."9" = c else { throw error(.invalidNumber) }
tempBuffer.append(Int8(truncatingBitPattern: c.value))
case "0"..."9": break
default: throw error(.invalidNumber)
}
while let c = base.peek() {
switch c {
case "0"..."9":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
default:
break loop
}
}
break loop
default:
break loop
}
}
tempBuffer.append(0)
return .doubleValue(tempBuffer.withUnsafeBufferPointer({strtod($0.baseAddress, nil)}))
case "e", "E":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
guard let c = bump(), case "0"..."9" = c else { throw error(.invalidNumber) }
tempBuffer.append(Int8(truncatingBitPattern: c.value))
loop: while let c = base.peek() {
switch c {
case "0"..."9":
bump()
tempBuffer.append(Int8(truncatingBitPattern: c.value))
default:
break loop
}
}
tempBuffer.append(0)
return .doubleValue(tempBuffer.withUnsafeBufferPointer({strtod($0.baseAddress, nil)}))
default:
break outerLoop
}
}
if tempBuffer.count == 1 && tempBuffer[0] == 0x2d /* - */ {
throw error(.invalidNumber)
}
tempBuffer.append(0)
let num = tempBuffer.withUnsafeBufferPointer({ ptr -> Int64? in
errno = 0
let n = strtoll(ptr.baseAddress, nil, 10)
if n == 0 && errno != 0 {
return nil
} else {
return n
}
})
if let num = num {
return .int64Value(num)
}
// out of range, fall back to Double
return .doubleValue(tempBuffer.withUnsafeBufferPointer({strtod($0.baseAddress, nil)}))
case "t":
let line = self.line, column = self.column
guard case "r"? = bump(), case "u"? = bump(), case "e"? = bump() else {
throw JSONParserError(code: .invalidSyntax, line: line, column: column)
}
return .booleanValue(true)
case "f":
let line = self.line, column = self.column
guard case "a"? = bump(), case "l"? = bump(), case "s"? = bump(), case "e"? = bump() else {
throw JSONParserError(code: .invalidSyntax, line: line, column: column)
}
return .booleanValue(false)
case "n":
let line = self.line, column = self.column
guard case "u"? = bump(), case "l"? = bump(), case "l"? = bump() else {
throw JSONParserError(code: .invalidSyntax, line: line, column: column)
}
return .nullValue
default:
throw error(.invalidSyntax)
}
}
private mutating func skipWhitespace() -> UnicodeScalar? {
while let c = bump() {
switch c {
case " ", "\t", "\n", "\r": continue
default: return c
}
}
return nil
}
private mutating func parseFourHex() throws -> UInt16 {
var codepoint: UInt32 = 0
for _ in 0..<4 {
let c = try bumpRequired()
codepoint <<= 4
switch c {
case "0"..."9":
codepoint += c.value - 48
case "a"..."f":
codepoint += c.value - 87
case "A"..."F":
codepoint += c.value - 55
default:
throw error(.invalidEscape)
}
}
return UInt16(truncatingBitPattern: codepoint)
}
@inline(__always) @discardableResult private mutating func bump() -> UnicodeScalar? {
let c = base.next()
if c == "\n" {
line += 1
column = 0
} else {
column += 1
}
return c
}
@inline(__always) private mutating func bumpRequired() throws -> UnicodeScalar {
guard let c = bump() else { throw error(.unexpectedEOF) }
return c
}
private func error(_ code: JSONParserError.Code) -> JSONParserError {
return JSONParserError(code: code, line: line, column: column)
}
/// The line of the last emitted token.
public private(set) var line: UInt = 0
/// The column of the last emitted token.
public private(set) var column: UInt = 0
private var base: PeekIterator<Iter>
private var state: State = .initial
private var stack: [Stack] = []
private var tempBuffer: ContiguousArray<Int8>?
}
@available(*, renamed: "JSONParserIterator")
typealias JSONParserGenerator<Gen: IteratorProtocol> = JSONParserIterator<Gen> where Gen.Element == UnicodeScalar
private enum State {
/// Initial state
case initial
/// Parse an element or the end of the array
case parseArray(first: Bool)
/// Parse a comma or the end of the array
case parseArrayComma
/// Parse an object key or the end of the array
case parseObjectKey(first: Bool)
/// Parse a colon followed by an object value
case parseObjectValue
/// Parse a comma or the end of the object
case parseObjectComma
/// Parse whitespace or EOF
case parseEnd
/// Parsing has completed
case finished
}
private enum Stack {
case array
case object
}
/// A streaming JSON parser event.
public enum JSONEvent: Hashable {
/// The start of an object.
/// Inside of an object, each key/value pair is emitted as a
/// `StringValue` for the key followed by the `JSONEvent` sequence
/// that describes the value.
case objectStart
/// The end of an object.
case objectEnd
/// The start of an array.
case arrayStart
/// The end of an array.
case arrayEnd
/// A boolean value.
case booleanValue(Bool)
/// A signed 64-bit integral value.
case int64Value(Int64)
/// A double value.
case doubleValue(Double)
/// A string value.
case stringValue(String)
/// The null value.
case nullValue
/// A parser error.
case error(JSONParserError)
public var hashValue: Int {
switch self {
case .objectStart: return 1
case .objectEnd: return 2
case .arrayStart: return 3
case .arrayEnd: return 4
case .booleanValue(let b): return b.hashValue << 4 + 5
case .int64Value(let i): return i.hashValue << 4 + 6
case .doubleValue(let d): return d.hashValue << 4 + 7
case .stringValue(let s): return s.hashValue << 4 + 8
case .nullValue: return 9
case .error(let error): return error.hashValue << 4 + 10
}
}
public static func ==(lhs: JSONEvent, rhs: JSONEvent) -> Bool {
switch (lhs, rhs) {
case (.objectStart, .objectStart), (.objectEnd, .objectEnd),
(.arrayStart, .arrayStart), (.arrayEnd, .arrayEnd), (.nullValue, .nullValue):
return true
case let (.booleanValue(a), .booleanValue(b)):
return a == b
case let (.int64Value(a), .int64Value(b)):
return a == b
case let (.doubleValue(a), .doubleValue(b)):
return a == b
case let (.stringValue(a), .stringValue(b)):
return a == b
case let (.error(a), .error(b)):
return a == b
default:
return false
}
}
}
/// An iterator of `JSONEvent`s that records column/line info.
public protocol JSONEventIterator: IteratorProtocol {
/// The line of the last emitted token.
var line: UInt { get }
/// The column of the last emitted token.
var column: UInt { get }
}
@available(*, renamed: "JSONEventIterator")
public typealias JSONEventGenerator = JSONEventIterator
public struct JSONParserError: Error, Hashable, CustomStringConvertible {
/// A generic syntax error.
public static let invalidSyntax: Code = .invalidSyntax
/// An invalid number.
public static let invalidNumber: Code = .invalidNumber
/// An invalid string escape.
public static let invalidEscape: Code = .invalidEscape
/// A unicode string escape with an invalid code point.
public static let invalidUnicodeScalar: Code = .invalidUnicodeScalar
/// A unicode string escape representing a leading surrogate without
/// a corresponding trailing surrogate.
public static let loneLeadingSurrogateInUnicodeEscape: Code = .loneLeadingSurrogateInUnicodeEscape
/// A control character in a string.
public static let controlCharacterInString: Code = .controlCharacterInString
/// A comma was found where a colon was expected in an object.
public static let expectedColon: Code = .expectedColon
/// A comma or colon was found in an object without a key.
public static let missingKey: Code = .missingKey
/// An object key was found that was not a string.
public static let nonStringKey: Code = .nonStringKey
/// A comma or object end was encountered where a value was expected.
public static let missingValue: Code = .missingValue
/// A trailing comma was found in an array or object. Only emitted when `strict` mode is enabled.
public static let trailingComma: Code = .trailingComma
/// Trailing (non-whitespace) characters found after the close
/// of the root value.
/// - Note: This error cannot be thrown if the parser is in streaming mode.
public static let trailingCharacters: Code = .trailingCharacters
/// EOF was found before the root value finished parsing.
public static let unexpectedEOF: Code = .unexpectedEOF
public let code: Code
public let line: UInt
public let column: UInt
public init(code: Code, line: UInt, column: UInt) {
self.code = code
self.line = line
self.column = column
}
public var _code: Int { return code.rawValue }
public enum Code: Int {
/// A generic syntax error.
case invalidSyntax
/// An invalid number.
case invalidNumber
/// An invalid string escape.
case invalidEscape
/// A unicode string escape with an invalid code point.
case invalidUnicodeScalar
/// A unicode string escape representing a leading surrogate without
/// a corresponding trailing surrogate.
case loneLeadingSurrogateInUnicodeEscape
/// A control character in a string.
case controlCharacterInString
/// A comma was found where a colon was expected in an object.
case expectedColon
/// A comma or colon was found in an object without a key.
case missingKey
/// An object key was found that was not a string.
case nonStringKey
/// A comma or object end was encountered where a value was expected.
case missingValue
/// A trailing comma was found in an array or object. Only emitted when `strict` mode is enabled.
case trailingComma
/// Trailing (non-whitespace) characters found after the close
/// of the root value.
/// - Note: This error cannot be thrown if the parser is in streaming mode.
case trailingCharacters
/// EOF was found before the root value finished parsing.
case unexpectedEOF
public static func ~=(lhs: Code, rhs: Error) -> Bool {
if let error = rhs as? JSONParserError {
return lhs == error.code
} else {
return false
}
}
}
public var description: String {
return "JSONParserError(\(code), line: \(line), column: \(column))"
}
public var hashValue: Int {
return Int(bitPattern: line << 18) ^ Int(bitPattern: column << 4) ^ code.rawValue
}
public static func ==(lhs: JSONParserError, rhs: JSONParserError) -> Bool {
return (lhs.code, lhs.line, lhs.column) == (rhs.code, rhs.line, rhs.column)
}
}
private struct PeekIterator<Base: IteratorProtocol> {
init(_ base: Base) {
self.base = base
}
mutating func peek() -> Base.Element? {
if let elt = peeked {
return elt
}
let elt = base.next()
peeked = .some(elt)
return elt
}
mutating func next() -> Base.Element? {
if let elt = peeked {
peeked = nil
return elt
}
return base.next()
}
private var base: Base
private var peeked: Base.Element??
}
private func replace<T>(_ a: inout T, with b: T) -> T {
var b = b
swap(&a, &b)
return b
}
|
bsd-3-clause
|
0a41523eeec3e8722d711032d6dd87b3
| 38.013353 | 121 | 0.504811 | 5.330428 | false | false | false | false |
farhanpatel/firefox-ios
|
Client/Helpers/FxALoginHelper.swift
|
2
|
13787
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Account
import Deferred
import Foundation
import Shared
import SwiftyJSON
import Sync
import UserNotifications
import XCGLogger
private let applicationDidRequestUserNotificationPermissionPrefKey = "applicationDidRequestUserNotificationPermissionPrefKey"
private let log = Logger.browserLogger
private let verificationPollingInterval = DispatchTimeInterval.seconds(3)
private let verificationMaxRetries = 100 // Poll every 3 seconds for 5 minutes.
protocol FxAPushLoginDelegate : class {
func accountLoginDidFail()
func accountLoginDidSucceed(withFlags flags: FxALoginFlags)
}
/// Small struct to keep together the immediately actionable flags that the UI is likely to immediately
/// following a successful login. This is not supposed to be a long lived object.
struct FxALoginFlags {
let pushEnabled: Bool
let verified: Bool
}
enum PushNotificationError: MaybeErrorType {
case registrationFailed
case userDisallowed
case wrongOSVersion
var description: String {
switch self {
case .registrationFailed:
return "The OS was unable to complete APNS registration"
case .userDisallowed:
return "User refused permission for notifications"
case .wrongOSVersion:
return "The version of iOS is not recent enough"
}
}
}
/// This class manages the from successful login for FxAccounts to
/// asking the user for notification permissions, registering for
/// remote push notifications (APNS), then creating an account and
/// storing it in the profile.
class FxALoginHelper {
static var sharedInstance: FxALoginHelper = {
return FxALoginHelper()
}()
weak var delegate: FxAPushLoginDelegate?
fileprivate weak var profile: Profile?
fileprivate var account: FirefoxAccount!
fileprivate var accountVerified: Bool!
fileprivate var pushClient: PushClient? {
guard let pushConfiguration = self.getPushConfiguration() ?? self.profile?.accountConfiguration.pushConfiguration,
let accountConfiguration = self.profile?.accountConfiguration else {
log.error("Push server endpoint could not be found")
return nil
}
// Experimental mode needs: a) the scheme to be Fennec, and b) the accountConfiguration to be flipped in debug mode.
let experimentalMode = (pushConfiguration.label == .fennec && accountConfiguration.label == .latestDev)
return PushClient(endpointURL: pushConfiguration.endpointURL, experimentalMode: experimentalMode)
}
fileprivate var apnsTokenDeferred: Deferred<Maybe<String>>!
// This should be called when the application has started.
// This configures the helper for logging into Firefox Accounts, and
// if already logged in, checking if anything needs to be done in response
// to changing of user settings and push notifications.
func application(_ application: UIApplication, didLoadProfile profile: Profile) {
self.profile = profile
self.account = profile.getAccount()
self.apnsTokenDeferred = Deferred()
guard let account = self.account else {
// There's no account, no further action.
return loginDidFail()
}
// accountVerified is needed by delegates.
accountVerified = account.actionNeeded != .needsVerification
guard AppConstants.MOZ_FXA_PUSH else {
return loginDidSucceed()
}
if let _ = account.pushRegistration {
// We have an account, and it's already registered for push notifications.
return loginDidSucceed()
}
// Now: we have an account that does not have push notifications set up.
// however, we need to deal with cases of asking for permissions too frequently.
let asked = profile.prefs.boolForKey(applicationDidRequestUserNotificationPermissionPrefKey) ?? true
let permitted = application.currentUserNotificationSettings!.types != .none
// If we've never asked(*), then we should probably ask.
// If we've asked already, then we should not ask again.
// TODO: add UI to tell the user to go flip the Setting app.
// (*) if we asked in a prior release, and the user was ok with it, then there is no harm asking again.
// If the user denied permission, or flipped permissions in the Settings app, then
// we'll bug them once, but this is probably unavoidable.
if asked && !permitted {
return loginDidSucceed()
}
// By the time we reach here, we haven't registered for APNS
// Either we've never asked the user, or the user declined, then re-enabled
// the notification in the Settings app.
requestUserNotifications(application)
}
// This is called when the user logs into a new FxA account.
// It manages the asking for user permission for notification and registration
// for APNS and WebPush notifications.
func application(_ application: UIApplication, didReceiveAccountJSON data: JSON) {
if data["keyFetchToken"].stringValue() == nil || data["unwrapBKey"].stringValue() == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
log.error("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return self.loginDidFail()
}
assert(profile != nil, "Profile should still exist and be loaded into this FxAPushLoginStateMachine")
guard let profile = profile,
let account = FirefoxAccount.from(profile.accountConfiguration, andJSON: data) else {
return self.loginDidFail()
}
accountVerified = data["verified"].bool ?? false
self.account = account
if AppConstants.MOZ_SHOW_FXA_AVATAR {
account.updateProfile()
}
requestUserNotifications(application)
}
func getDeviceToken(_ application: UIApplication) -> Deferred<Maybe<String>> {
self.requestUserNotifications(application)
return self.apnsTokenDeferred
}
fileprivate func requestUserNotifications(_ application: UIApplication) {
if let deferred = self.apnsTokenDeferred, deferred.isFilled,
let token = deferred.value.successValue {
// If we have an account, then it'll go through ahead and register
// with autopush here.
// If not we'll just bail. The Deferred will do the rest.
return self.apnsRegisterDidSucceed(token)
}
DispatchQueue.main.async {
self.requestUserNotificationsMainThreadOnly(application)
}
}
fileprivate func requestUserNotificationsMainThreadOnly(_ application: UIApplication) {
assert(Thread.isMainThread, "requestAuthorization should be run on the main thread")
let center = UNUserNotificationCenter.current()
return center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
guard error == nil else {
return self.application(application, canDisplayUserNotifications: false)
}
self.application(application, canDisplayUserNotifications: granted)
}
}
// This is necessarily called from the AppDelegate.
// Once we have permission from the user to display notifications, we should
// try and register for APNS. If not, then start syncing.
func application(_ application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
let types = notificationSettings.types
let allowed = types != .none && types.rawValue != 0
self.application(application, canDisplayUserNotifications: allowed)
}
func application(_ application: UIApplication, canDisplayUserNotifications allowed: Bool) {
guard allowed else {
apnsTokenDeferred?.fillIfUnfilled(Maybe.failure(PushNotificationError.userDisallowed))
return readyForSyncing()
}
// Record that we have asked the user, and they have given an answer.
profile?.prefs.setBool(true, forKey: applicationDidRequestUserNotificationPermissionPrefKey)
if AppConstants.MOZ_FXA_PUSH {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
} else {
readyForSyncing()
}
}
func getPushConfiguration() -> PushConfiguration? {
let label = PushConfigurationLabel(rawValue: AppConstants.scheme)
return label?.toConfiguration()
}
func apnsRegisterDidSucceed(_ deviceToken: Data) {
let apnsToken = deviceToken.hexEncodedString
self.apnsTokenDeferred?.fillIfUnfilled(Maybe(success: apnsToken))
self.apnsRegisterDidSucceed(apnsToken)
}
fileprivate func apnsRegisterDidSucceed(_ apnsToken: String) {
guard self.account != nil else {
// If we aren't logged in to FxA at this point
// we should bail.
return loginDidFail()
}
guard let pushClient = self.pushClient else {
return pushRegistrationDidFail()
}
if let pushRegistration = account.pushRegistration {
// Currently, we don't support routine changing of push subscriptions
// then we can assume that if we've already registered with the
// push server, then we don't need to do it again.
_ = pushClient.updateUAID(apnsToken, withRegistration: pushRegistration)
return
}
pushClient.register(apnsToken).upon { res in
guard let pushRegistration = res.successValue else {
return self.pushRegistrationDidFail()
}
return self.pushRegistrationDidSucceed(apnsToken: apnsToken, pushRegistration: pushRegistration)
}
}
func apnsRegisterDidFail() {
self.apnsTokenDeferred?.fillIfUnfilled(Maybe(failure: PushNotificationError.registrationFailed))
readyForSyncing()
}
fileprivate func pushRegistrationDidSucceed(apnsToken: String, pushRegistration: PushRegistration) {
account.pushRegistration = pushRegistration
readyForSyncing()
}
fileprivate func pushRegistrationDidFail() {
readyForSyncing()
}
fileprivate func readyForSyncing() {
guard let profile = self.profile, let account = self.account else {
return loginDidFail()
}
profile.setAccount(account)
awaitVerification()
loginDidSucceed()
}
fileprivate func awaitVerification(_ attemptsLeft: Int = verificationMaxRetries) {
guard let account = account,
let profile = profile else {
return
}
if attemptsLeft == 0 {
return
}
// The only way we can tell if the account has been verified is to
// start a sync. If it works, then yay,
account.advance().upon { state in
guard state.actionNeeded == .needsVerification else {
// Verification has occurred remotely, and we can proceed.
// The state machine will have told any listening UIs that
// we're done.
return self.performVerifiedSync(profile, account: account)
}
let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass)
queue.asyncAfter(deadline: DispatchTime.now() + verificationPollingInterval) {
self.awaitVerification(attemptsLeft - 1)
}
}
}
fileprivate func loginDidSucceed() {
let flags = FxALoginFlags(pushEnabled: account?.pushRegistration != nil, verified: accountVerified)
delegate?.accountLoginDidSucceed(withFlags: flags)
}
fileprivate func loginDidFail() {
delegate?.accountLoginDidFail()
}
func performVerifiedSync(_ profile: Profile, account: FirefoxAccount) {
profile.syncManager.syncEverything(why: .didLogin)
}
}
extension FxALoginHelper {
func applicationDidDisconnect(_ application: UIApplication) {
// According to https://developer.apple.com/documentation/uikit/uiapplication/1623093-unregisterforremotenotifications
// we should be calling:
application.unregisterForRemoteNotifications()
// However, https://forums.developer.apple.com/message/179264#179264 advises against it, suggesting there is
// a 24h period after unregistering where re-registering fails. This doesn't seem to be the case (for me)
// but this may be useful to know if QA/user-testing find this a problem.
// Whatever, we should unregister from the autopush server. That means we definitely won't be getting any
// messages.
if let pushRegistration = self.account.pushRegistration,
let pushClient = self.pushClient {
_ = pushClient.unregister(pushRegistration)
}
// TODO: fix Bug 1168690, to tell Sync to delete this client and its tabs.
// i.e. upload a {deleted: true} client record.
// Tell FxA we're no longer attached.
self.account.destroyDevice()
// Cleanup the database.
self.profile?.removeAccount()
// Cleanup the FxALoginHelper.
self.account = nil
self.accountVerified = nil
self.profile?.prefs.removeObjectForKey(PendingAccountDisconnectedKey)
}
}
|
mpl-2.0
|
fbc11ff35a6e1ca7bf58bb712fb550fd
| 38.731988 | 138 | 0.67317 | 5.341728 | false | false | false | false |
Nickelfox/TemplateProject
|
ProjectFiles/Code/Helpers/Date+Helper.swift
|
1
|
849
|
//
// Date+Helper.swift
// TemplateProject
//
// Created by Ravindra Soni on 18/12/16.
// Copyright © 2016 Nickelfox. All rights reserved.
//
import Foundation
enum DateFormat: String {
case yyyyMMdd = "yyyy-MM-dd"
case ddMMyyyy = "dd-MM-yyyy"
}
struct DateHelper {
static let dateFormatter = DateFormatter()
static var today: Date {
return DateHelper.shortStringFormatter.date(from: DateHelper.shortStringFormatter.string(from: Date()))!
}
private static let internalDateFormatter = DateFormatter()
static var shortStringFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}
static func dateFormatter(format: DateFormat) -> DateFormatter {
DateHelper.internalDateFormatter.dateFormat = format.rawValue
return DateHelper.internalDateFormatter
}
}
|
mit
|
e7a408eefafa1afc875d455c319ab9cc
| 21.918919 | 106 | 0.747642 | 3.837104 | false | false | false | false |
SlackKit/SlackKit
|
SKRTMAPI/Sources/SKRTMAPI.swift
|
1
|
8468
|
//
// SKRTMAPI.swift
//
// Copyright © 2017 Peter Zignego. 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.
#if os(Linux)
import Dispatch
#endif
import Foundation
#if !COCOAPODS
import SKWebAPI
@_exported import SKCore
#endif
public protocol RTMWebSocket {
init()
var delegate: RTMDelegate? { get set }
func connect(url: URL)
func disconnect()
func sendMessage(_ message: String) throws
}
public protocol RTMAdapter: class {
func initialSetup(json: [String: Any], instance: SKRTMAPI)
func notificationForEvent(_ event: Event, type: EventType, instance: SKRTMAPI)
func connectionClosed(with error: Error, instance: SKRTMAPI)
}
public protocol RTMDelegate: class {
func didConnect()
func disconnected()
func receivedMessage(_ message: String)
}
public final class SKRTMAPI: RTMDelegate {
public var rtm: RTMWebSocket
public var adapter: RTMAdapter?
public var token = "xoxp-SLACK_AUTH_TOKEN"
internal var options: RTMOptions
public private(set) var connected = false
var ping: Double?
var pong: Double?
public init(withAPIToken token: String, options: RTMOptions = RTMOptions(), rtm: RTMWebSocket? = nil) {
self.token = token
self.options = options
if let rtm = rtm {
self.rtm = rtm
} else {
#if os(Linux)
self.rtm = VaporEngineRTM()
#else
self.rtm = StarscreamRTM()
#endif
}
self.rtm.delegate = self
}
public func connect(withInfo: Bool = true) {
if withInfo {
WebAPI.rtmStart(
token: token,
batchPresenceAware: options.noUnreads,
mpimAware: options.mpimAware,
noLatest: options.noLatest,
noUnreads: options.noUnreads,
presenceSub: options.presenceSub,
simpleLatest: options.simpleLatest,
success: {(response) in
self.connectWithResponse(response)
}, failure: { (error) in
self.adapter?.connectionClosed(with: error, instance: self)
}
)
} else {
WebAPI.rtmConnect(
token: token,
batchPresenceAware: options.batchPresenceAware,
presenceSub: options.presenceSub,
success: {(response) in
self.connectWithResponse(response)
}, failure: { (error) in
self.adapter?.connectionClosed(with: error, instance: self)
}
)
}
}
public func disconnect() {
rtm.disconnect()
}
public func sendMessage(_ message: String, channelID: String, id: String? = nil) throws {
guard connected else {
throw SlackError.rtmConnectionError
}
do {
let string = try format(message: message, channel: channelID, id: id)
try rtm.sendMessage(string)
} catch let error {
throw error
}
}
public func sendThreadedMessage(_ message: String, channelID: String, threadTs: String, broadcastReply: Bool = false) throws {
guard connected else {
throw SlackError.rtmConnectionError
}
do {
let string = try format(message: message, channel: channelID, threadTs: threadTs, broadcastReply: broadcastReply)
try rtm.sendMessage(string)
} catch let error {
throw error
}
}
private func connectWithResponse(_ response: [String: Any]) {
guard
let socketURL = response["url"] as? String,
let url = URL(string: socketURL)
else {
return
}
self.rtm.connect(url: url)
self.adapter?.initialSetup(json: response, instance: self)
}
private func format(message: String,
channel: String,
id: String? = nil,
threadTs: String? = nil,
broadcastReply: Bool = false
) throws -> String {
let json: [String: Any?] = [
"id": id ?? Date().slackTimestamp,
"type": "message",
"channel": channel,
"text": message,
"thread_ts": threadTs,
"broadcastReply": broadcastReply
]
guard
let data = try? JSONSerialization.data(withJSONObject: json.compactMapValues({$0}), options: []),
let str = String(data: data, encoding: String.Encoding.utf8)
else {
throw SlackError.clientJSONError
}
return str
}
// MARK: - RTM Ping
private func pingRTMServer() {
let pingInterval = Double(UInt64(options.pingInterval * Double(UInt64.nanosecondsPerSecond))) / Double(UInt64.nanosecondsPerSecond)
let delay = DispatchTime.now() + pingInterval
DispatchQueue.main.asyncAfter(deadline: delay) {
guard self.connected && self.isConnectionTimedOut else {
self.disconnect()
return
}
try? self.sendRTMPing()
self.pingRTMServer()
}
}
private func sendRTMPing() throws {
guard connected else {
throw SlackError.rtmConnectionError
}
let json: [String: Any] = [
"id": Date().slackTimestamp,
"type": "ping"
]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: []) else {
throw SlackError.clientJSONError
}
if let string = String(data: data, encoding: String.Encoding.utf8) {
ping = json["id"] as? Double
try rtm.sendMessage(string)
}
}
var isConnectionTimedOut: Bool {
if let pong = pong, let ping = ping {
if pong - ping < options.timeout {
return true
} else {
return false
}
} else {
return true
}
}
// MARK: RTMDelegate
public func didConnect() {
connected = true
pingRTMServer()
}
public func disconnected() {
connected = false
if options.reconnect {
connect()
} else {
adapter?.connectionClosed(with: SlackError.rtmConnectionError, instance: self)
}
}
public func receivedMessage(_ message: String) {
guard let data = message.data(using: String.Encoding.utf8) else {
return
}
if let json = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [String: Any] {
dispatch(json)
}
}
internal func dispatch(_ anEvent: [String: Any]) {
let event = Event(anEvent)
let type = event.type ?? .unknown
switch type {
case .hello:
connected = true
case .pong:
pong = event.replyTo
case .teamMigrationStarted:
connect()
case .error:
print("Error: \(anEvent)")
case .goodbye:
connect()
case .unknown:
print("Unsupported event of type: \(anEvent["type"] ?? "No Type Information")")
default:
break
}
adapter?.notificationForEvent(event, type: type, instance: self)
}
}
|
mit
|
09063b8077d9ba29e576adcad605c9ea
| 31.565385 | 139 | 0.582142 | 4.579232 | false | false | false | false |
s-aska/Justaway-for-iOS
|
Justaway/Relationship.swift
|
1
|
14140
|
//
// Relationship.swift
// Justaway
//
// Created by Shinichiro Aska on 3/15/16.
// Copyright © 2016 Shinichiro Aska. All rights reserved.
//
import Foundation
import SwiftyJSON
import KeyClip
import Async
class Relationship {
struct Static {
static var users = [String: Data]()
fileprivate static let queue = OperationQueue().serial()
}
struct Data {
var friends = [String: Bool]()
var followers = [String: Bool]()
var blocks = [String: Bool]()
var mutes = [String: Bool]()
var noRetweets = [String: Bool]()
}
class func check(_ sourceUserID: String, targetUserID: String, retweetUserID: String?, quotedUserID: String?, callback: @escaping ((_ blocking: Bool, _ muting: Bool, _ noRetweets: Bool) -> Void)) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
guard let data = Static.users[sourceUserID] else {
op.finish()
callback(false, false, false)
return
}
var blocking = data.blocks[targetUserID] ?? false
var muting = data.mutes[targetUserID] ?? false
var noRetweets = false
if let retweetUserID = retweetUserID {
noRetweets = data.noRetweets[retweetUserID] ?? false
}
if let quotedUserID = quotedUserID {
if !blocking {
blocking = data.blocks[quotedUserID] ?? false
}
if !muting {
muting = data.mutes[quotedUserID] ?? false
}
}
op.finish()
Async.main {
callback(blocking, muting, noRetweets)
}
}))
}
class func checkUser(_ sourceUserID: String, targetUserID: String, callback: @escaping ((_ relationshop: TwitterRelationship) -> Void)) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
guard let data = Static.users[sourceUserID] else {
op.finish()
Async.main {
callback(TwitterRelationship(following: false, followedBy: false, blocking: false, muting: false, wantRetweets: false))
}
return
}
let following = data.friends[targetUserID] ?? false
let followedBy = data.followers[targetUserID] ?? false
let blocking = data.blocks[targetUserID] ?? false
let muting = data.mutes[targetUserID] ?? false
let noRetweets = data.noRetweets[targetUserID] ?? false
op.finish()
Async.main {
callback(TwitterRelationship(following: following, followedBy: followedBy, blocking: blocking, muting: muting, wantRetweets: !noRetweets))
}
}))
}
class func follow(_ account: Account, targetUserID: String) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
Static.users[account.userID]?.friends[targetUserID] = true
op.finish()
}))
}
class func unfollow(_ account: Account, targetUserID: String) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
Static.users[account.userID]?.friends.removeValue(forKey: targetUserID)
op.finish()
}))
}
class func followed(_ account: Account, targetUserID: String) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
Static.users[account.userID]?.followers[targetUserID] = true
op.finish()
}))
}
class func block(_ account: Account, targetUserID: String) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
Static.users[account.userID]?.blocks[targetUserID] = true
op.finish()
}))
}
class func unblock(_ account: Account, targetUserID: String) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
Static.users[account.userID]?.blocks.removeValue(forKey: targetUserID)
op.finish()
}))
}
class func mute(_ account: Account, targetUserID: String) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
Static.users[account.userID]?.mutes[targetUserID] = true
op.finish()
}))
}
class func unmute(_ account: Account, targetUserID: String) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
Static.users[account.userID]?.mutes.removeValue(forKey: targetUserID)
op.finish()
}))
}
class func turnOffRetweets(_ account: Account, targetUserID: String) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
Static.users[account.userID]?.noRetweets[targetUserID] = true
op.finish()
}))
}
class func turnOnRetweets(_ account: Account, targetUserID: String) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
Static.users[account.userID]?.noRetweets.removeValue(forKey: targetUserID)
op.finish()
}))
}
class func setup(_ account: Account) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
if Static.users[account.userID] != nil {
op.finish()
return
}
Static.users[account.userID] = Data()
op.finish()
load(account)
}))
}
class func load(_ account: Account) {
loadFriends(account)
loadFollowers(account)
loadMutes(account)
loadNoRetweets(account)
loadBlocks(account)
}
class func loadFriends(_ account: Account) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
let cacheKey = "relationship-friends-\(account.userID)"
let now = Date(timeIntervalSinceNow: 0).timeIntervalSince1970
if let cache = KeyClip.load(cacheKey) as NSDictionary?,
let createdAt = cache["createdAt"] as? NSNumber,
let ids = cache["ids"] as? [String], (now - createdAt.doubleValue) < 600 {
NSLog("[Relationship] load cache user:\(account.screenName) friends: \(ids.count) delta:\(now - createdAt.doubleValue)")
for id in ids {
Static.users[account.userID]?.friends[id] = true
}
op.finish()
return
}
let success = { (json: JSON) -> Void in
guard let ids = json["ids"].array?.map({ $0.string ?? "" }).filter({ !$0.isEmpty }) else {
op.finish()
return
}
NSLog("[Relationship] load user:\(account.screenName) friends: \(ids.count)")
for id in ids {
Static.users[account.userID]?.friends[id] = true
}
op.finish()
_ = KeyClip.save(cacheKey, dictionary: ["ids": ids, "createdAt": Int(Date(timeIntervalSinceNow: 0).timeIntervalSince1970)])
}
account.client
.get("https://api.twitter.com/1.1/friends/ids.json", parameters: ["stringify_ids": "true"])
.responseJSON(success, failure: { (code, message, error) in
op.finish()
})
}))
}
class func loadFollowers(_ account: Account) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
let cacheKey = "relationship-followers-\(account.userID)"
let now = Date(timeIntervalSinceNow: 0).timeIntervalSince1970
if let cache = KeyClip.load(cacheKey) as NSDictionary?,
let createdAt = cache["createdAt"] as? NSNumber,
let ids = cache["ids"] as? [String], (now - createdAt.doubleValue) < 600 {
NSLog("[Relationship] load cache user:\(account.screenName) followers: \(ids.count) delta:\(now - createdAt.doubleValue)")
for id in ids {
Static.users[account.userID]?.followers[id] = true
}
op.finish()
return
}
let success = { (json: JSON) -> Void in
guard let ids = json["ids"].array?.map({ $0.string ?? "" }).filter({ !$0.isEmpty }) else {
op.finish()
return
}
NSLog("[Relationship] load user:\(account.screenName) followers: \(ids.count)")
for id in ids {
Static.users[account.userID]?.followers[id] = true
}
op.finish()
_ = KeyClip.save(cacheKey, dictionary: ["ids": ids, "createdAt": Int(Date(timeIntervalSinceNow: 0).timeIntervalSince1970)])
}
account.client
.get("https://api.twitter.com/1.1/followers/ids.json", parameters: ["stringify_ids": "true"])
.responseJSON(success, failure: { (code, message, error) in
op.finish()
})
}))
}
class func loadMutes(_ account: Account) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
let cacheKey = "relationship-mutes-\(account.userID)"
let now = Date(timeIntervalSinceNow: 0).timeIntervalSince1970
if let cache = KeyClip.load(cacheKey) as NSDictionary?,
let createdAt = cache["createdAt"] as? NSNumber,
let ids = cache["ids"] as? [String], (now - createdAt.doubleValue) < 600 {
NSLog("[Relationship] load cache user:\(account.screenName) mutes: \(ids.count) delta:\(now - createdAt.doubleValue)")
for id in ids {
Static.users[account.userID]?.mutes[id] = true
}
op.finish()
return
}
let success = { (json: JSON) -> Void in
guard let ids = json["ids"].array?.map({ $0.string ?? "" }).filter({ !$0.isEmpty }) else {
op.finish()
return
}
NSLog("[Relationship] load user:\(account.screenName) mutes: \(ids.count)")
for id in ids {
Static.users[account.userID]?.mutes[id] = true
}
op.finish()
_ = KeyClip.save(cacheKey, dictionary: ["ids": ids, "createdAt": Int(Date(timeIntervalSinceNow: 0).timeIntervalSince1970)])
}
account.client
.get("https://api.twitter.com/1.1/mutes/users/ids.json", parameters: ["stringify_ids": "true"])
.responseJSON(success, failure: { (code, message, error) in
op.finish()
})
}))
}
class func loadNoRetweets(_ account: Account) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
let cacheKey = "relationship-noRetweets-\(account.userID)"
let now = Date(timeIntervalSinceNow: 0).timeIntervalSince1970
if let cache = KeyClip.load(cacheKey) as NSDictionary?,
let createdAt = cache["createdAt"] as? NSNumber,
let ids = cache["ids"] as? [String], (now - createdAt.doubleValue) < 600 {
NSLog("[Relationship] load cache user:\(account.screenName) noRetweets: \(ids.count) delta:\(now - createdAt.doubleValue)")
for id in ids {
Static.users[account.userID]?.noRetweets[id] = true
}
op.finish()
return
}
let success = { (array: [JSON]) -> Void in
let ids = array.map({ $0.string ?? "" }).filter({ !$0.isEmpty })
NSLog("[Relationship] load user:\(account.screenName) noRetweets: \(ids.count)")
for id in ids {
Static.users[account.userID]?.noRetweets[id] = true
}
op.finish()
_ = KeyClip.save(cacheKey, dictionary: ["ids": ids, "createdAt": Int(Date(timeIntervalSinceNow: 0).timeIntervalSince1970)])
}
account.client
.get("https://api.twitter.com/1.1/friendships/no_retweets/ids.json", parameters: ["stringify_ids": "true"])
.responseJSONArray(success, failure: { (code, message, error) in
op.finish()
})
}))
}
class func loadBlocks(_ account: Account) {
Static.queue.addOperation(AsyncBlockOperation({ (op) in
let cacheKey = "relationship-blocks-\(account.userID)"
let now = Date(timeIntervalSinceNow: 0).timeIntervalSince1970
if let cache = KeyClip.load(cacheKey) as NSDictionary?,
let createdAt = cache["createdAt"] as? NSNumber,
let ids = cache["ids"] as? [String], (now - createdAt.doubleValue) < 600 {
NSLog("[Relationship] load cache user:\(account.screenName) blocks: \(ids.count) delta:\(now - createdAt.doubleValue)")
for id in ids {
Static.users[account.userID]?.blocks[id] = true
}
op.finish()
return
}
let success = { (json: JSON) -> Void in
guard let ids = json["ids"].array?.map({ $0.string ?? "" }).filter({ !$0.isEmpty }) else {
op.finish()
return
}
NSLog("[Relationship] load user:\(account.screenName) blocks: \(ids.count)")
for id in ids {
Static.users[account.userID]?.blocks[id] = true
}
op.finish()
_ = KeyClip.save(cacheKey, dictionary: ["ids": ids, "createdAt": Int(Date(timeIntervalSinceNow: 0).timeIntervalSince1970)])
}
account.client
.get("https://api.twitter.com/1.1/blocks/ids.json", parameters: ["stringify_ids": "true"])
.responseJSON(success, failure: { (code, message, error) in
op.finish()
})
}))
}
}
|
mit
|
a2d154d0c2b191547c2ca98224401a9e
| 41.587349 | 201 | 0.54233 | 4.762209 | false | false | false | false |
Johnykutty/SwiftLint
|
Source/SwiftLintFramework/Rules/CustomRules.swift
|
2
|
3421
|
//
// CustomRules.swift
// SwiftLint
//
// Created by Scott Hoyt on 1/21/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
private extension Region {
func isRuleDisabled(customRuleIdentifier: String) -> Bool {
return disabledRuleIdentifiers.contains(customRuleIdentifier)
}
}
// MARK: - CustomRulesConfiguration
public struct CustomRulesConfiguration: RuleConfiguration, Equatable {
public var consoleDescription: String { return "user-defined" }
public var customRuleConfigurations = [RegexConfiguration]()
public init() {}
public mutating func apply(configuration: Any) throws {
guard let configurationDict = configuration as? [String: Any] else {
throw ConfigurationError.unknownConfiguration
}
for (key, value) in configurationDict {
var ruleConfiguration = RegexConfiguration(identifier: key)
try ruleConfiguration.apply(configuration: value)
customRuleConfigurations.append(ruleConfiguration)
}
}
}
public func == (lhs: CustomRulesConfiguration, rhs: CustomRulesConfiguration) -> Bool {
return lhs.customRuleConfigurations == rhs.customRuleConfigurations
}
// MARK: - CustomRules
public struct CustomRules: Rule, ConfigurationProviderRule {
public static let description = RuleDescription(
identifier: "custom_rules",
name: "Custom Rules",
description: "Create custom rules by providing a regex string. " +
"Optionally specify what syntax kinds to match against, the severity " +
"level, and what message to display.")
public var configuration = CustomRulesConfiguration()
public init() {}
public func validate(file: File) -> [StyleViolation] {
var configurations = configuration.customRuleConfigurations
if configurations.isEmpty {
return []
}
if let path = file.path {
configurations = configurations.filter { config in
guard let includedRegex = config.included else { return true }
let range = NSRange(location: 0, length: path.bridge().length)
return !includedRegex.matches(in: path, options: [], range: range).isEmpty
}
}
return configurations.flatMap { configuration -> [StyleViolation] in
let pattern = configuration.regex.pattern
let excludingKinds = Array(Set(SyntaxKind.allKinds()).subtracting(configuration.matchKinds))
return file.match(pattern: pattern, excludingSyntaxKinds: excludingKinds).map({
StyleViolation(ruleDescription: configuration.description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location),
reason: configuration.message)
}).filter { violation in
let regions = file.regions().filter {
$0.contains(violation.location)
}
guard let region = regions.first else { return true }
for eachConfig in configurations where
region.isRuleDisabled(customRuleIdentifier: eachConfig.identifier) {
return false
}
return true
}
}
}
}
|
mit
|
9a3928410d9dca4fad8ac2d9479fc0cd
| 35 | 104 | 0.637427 | 5.294118 | false | true | false | false |
frankrue/AmazonS3RequestManager
|
AmazonS3RequestManager/AmazonS3RequestManager.swift
|
1
|
14740
|
//
// AmazonS3RequestManager.swift
// AmazonS3RequestManager
//
// Based on `AFAmazonS3Manager` by `Matt Thompson`
//
// Created by Anthony Miller. 2015.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
// MARK: - Information
// MARK: Error Domain
/*
The Error Domain for `ZRAPI`
*/
private let AmazonS3RequestManagerErrorDomain = "com.alamofire.AmazonS3RequestManager"
// MARK: Error Codes
/**
The error codes for the `AmazonS3RequestManagerErrorDomain`
- AccessKeyMissing: The `accessKey` for the request manager is `nil`. The `accessKey` must be set in order to make requests with `AmazonS3RequestManager`.
- SecretMissing: The secret for the request manager is `nil`. The secret must be set in order to make requests with `AmazonS3RequestManager`.
*/
public enum AmazonS3RequestManagerErrorCodes: Int {
case AccessKeyMissing = 1,
SecretMissing
}
// MARK: Amazon S3 Regions
/**
The possible Amazon Web Service regions for the client.
- USStandard: N. Virginia or Pacific Northwest
- USWest1: Oregon
- USWest2: N. California
- EUWest1: Ireland
- EUCentral1: Frankfurt
- APSoutheast1: Singapore
- APSoutheast2: Sydney
- APNortheast1: Toyko
- SAEast1: Sao Paulo
*/
public enum AmazonS3Region: String {
case USStandard = "s3.amazonaws.com",
USWest1 = "s3-us-west-1.amazonaws.com",
USWest2 = "s3-us-west-2.amazonaws.com",
EUWest1 = "s3-eu-west-1.amazonaws.com",
EUCentral1 = "s3-eu-central-1.amazonaws.com",
APSoutheast1 = "s3-ap-southeast-1.amazonaws.com",
APSoutheast2 = "s3-ap-southeast-2.amazonaws.com",
APNortheast1 = "s3-ap-northeast-1.amazonaws.com",
SAEast1 = "s3-sa-east-1.amazonaws.com"
}
// MARK: - AmazonS3RequestManager
/**
`AmazonS3RequestManager` is a subclass of `Alamofire.Manager` that encodes requests to the Amazon S3 service.
*/
public class AmazonS3RequestManager {
// MARK: Instance Properties
/**
The Amazon S3 Bucket for the client
*/
public var bucket: String?
/**
The Amazon S3 region for the client. `AmazonS3Region.USStandard` by default.
:note: Must not be `nil`.
:see: `AmazonS3Region` for defined regions.
*/
public var region: AmazonS3Region = .USStandard
/**
The Amazon S3 Access Key ID used to generate authorization headers and pre-signed queries
:dicussion: This can be found on the AWS control panel: http://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key
*/
public var accessKey: String
/**
The Amazon S3 Secret used to generate authorization headers and pre-signed queries
:dicussion: This can be found on the AWS control panel: http://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key
*/
public var secret: String
/**
The AWS STS session token. `nil` by default.
*/
public var sessionToken: String?
/**
Whether to connect over HTTPS. `true` by default.
*/
public var useSSL: Bool = true
/**
The `Alamofire.Manager` instance to use for network requests.
:note: This defaults to the shared instance of `Manager` used by top-level Alamofire requests.
*/
public var requestManager: Alamofire.Manager = Alamofire.Manager.sharedInstance
/**
A readonly endpoint URL created for the specified bucket, region, and SSL use preference. `AmazonS3RequestManager` uses this as the baseURL for all requests.
*/
public var endpointURL: NSURL {
var URLString = ""
let scheme = self.useSSL ? "https" : "http"
if bucket != nil {
URLString = "\(scheme)://\(region.rawValue)/\(bucket!)"
} else {
URLString = "\(scheme)://\(region.rawValue)"
}
return NSURL(string: URLString)!
}
// MARK: Initialization
/**
Initalizes an `AmazonS3RequestManager` with the given Amazon S3 credentials.
- parameter bucket: The Amazon S3 bucket for the client
- parameter region: The Amazon S3 region for the client
- parameter accessKey: The Amazon S3 access key ID for the client
- parameter secret: The Amazon S3 secret for the client
- returns: An `AmazonS3RequestManager` with the given Amazon S3 credentials and a default configuration.
*/
required public init(bucket: String?, region: AmazonS3Region, accessKey: String, secret: String) {
self.bucket = bucket
self.region = region
self.accessKey = accessKey
self.secret = secret
}
// MARK: - GET Object Requests
/**
Gets and object from the Amazon S3 service and returns it as the response object without saving to file.
:note: This method performs a standard GET request and does not allow use of progress blocks.
- parameter path: The object path
- returns: A GET request for the object
*/
public func getObject(path: String) -> Request {
return requestManager.request(amazonURLRequest(.GET, path: path))
}
/**
Gets an object from the Amazon S3 service and saves it to file.
:note: The user for the manager's Amazon S3 credentials must have read access to the object
:dicussion: This method performs a download request that allows for a progress block to be implemented. For more information on using progress blocks, see `Alamofire`.
- parameter path: The object path
- parameter destinationURL: The `NSURL` to save the object to
- returns: A download request for the object
*/
public func downloadObject(path: String, saveToURL destinationURL: NSURL) -> Request {
return requestManager.download(amazonURLRequest(.GET, path: path), destination: { (_, _) -> (NSURL) in
return destinationURL
})
}
// MARK: PUT Object Requests
/**
Uploads an object to the Amazon S3 service with a given local file URL.
:note: The user for the manager's Amazon S3 credentials must have read access to the bucket
- parameter fileURL: The local `NSURL` of the file to upload
- parameter destinationPath: The desired destination path, including the file name and extension, in the Amazon S3 bucket
- parameter acl: The optional access control list to set the acl headers for the request. For more information see `AmazonS3ACL`.
- returns: An upload request for the object
*/
public func putObject(fileURL: NSURL, destinationPath: String, acl: AmazonS3ACL? = nil) -> Request {
let putRequest = amazonURLRequest(.PUT, path: destinationPath, acl: acl)
return requestManager.upload(putRequest, file: fileURL)
}
/**
Uploads an object to the Amazon S3 service with the given data.
:note: The user for the manager's Amazon S3 credentials must have read access to the bucket
- parameter data: The `NSData` for the object to upload
- parameter destinationPath: The desired destination path, including the file name and extension, in the Amazon S3 bucket
- parameter acl: The optional access control list to set the acl headers for the request. For more information see `AmazonS3ACL`.
- returns: An upload request for the object
*/
public func putObject(data: NSData, destinationPath: String, acl: AmazonS3ACL? = nil) -> Request {
let putRequest = amazonURLRequest(.PUT, path: destinationPath, acl: acl)
return requestManager.upload(putRequest, data: data)
}
// MARK: DELETE Object Request
/**
Deletes an object from the Amazon S3 service.
:warning: Once an object has been deleted, there is no way to restore or undelete it.
- parameter path: The object path
- returns: The delete request
*/
public func deleteObject(path: String) -> Request {
let deleteRequest = amazonURLRequest(.DELETE, path: path)
return requestManager.request(deleteRequest)
}
// MARK: ACL Requests
/**
Gets the access control list (ACL) for the current `bucket`
:note: To use this operation, you must have the `AmazonS3ACLPermission.ReadACL` for the bucket.
:see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETacl.html"
- returns: A GET request for the bucket's ACL
*/
public func getBucketACL() -> Request {
return requestManager.request(amazonURLRequest(.GET, path: "", subresource: "acl", acl: nil))
}
/**
Sets the access control list (ACL) for the current `bucket`
:note: To use this operation, you must have the `AmazonS3ACLPermission.WriteACL` for the bucket.
:see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html"
- returns: A PUT request to set the bucket's ACL
*/
public func setBucketACL(acl: AmazonS3ACL) -> Request {
return requestManager.request(amazonURLRequest(.PUT, path: "", subresource: "acl", acl: acl))
}
/**
Gets the access control list (ACL) for the object at the given path.
:note: To use this operation, you must have the `AmazonS3ACLPermission.ReadACL` for the object.
:see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETacl.html"
- parameter path: The object path
- returns: A GET request for the object's ACL
*/
public func getACL(forObjectAtPath path:String) -> Request {
return requestManager.request(amazonURLRequest(.GET, path: path, subresource: "acl"))
}
/**
Sets the access control list (ACL) for the object at the given path.
:note: To use this operation, you must have the `AmazonS3ACLPermission.WriteACL` for the object.
:see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUTacl.html"
- returns: A PUT request to set the objects's ACL
*/
public func setACL(forObjectAtPath path: String, acl: AmazonS3ACL) -> Request {
return requestManager.request(amazonURLRequest(.PUT, path: path, subresource: "acl", acl: acl))
}
// MARK: Amazon S3 Request Serialization
/**
:discussion: These methods serialize requests for use with the Amazon S3 service. The `NSURLRequest`s returned from these methods may be used with `Alamofire`, `NSURLSession` or any other network request manager.
*/
/**
This method serializes a request for the Amazon S3 service with the given method and path.
- parameter method: The HTTP method for the request. For more information see `Alamofire.Method`.
- parameter path: The desired path, including the file name and extension, in the Amazon S3 Bucket.
- parameter acl: The optional access control list to set the acl headers for the request. For more information see `AmazonS3ACL`.
- returns: An `NSURLRequest`, serialized for use with the Amazon S3 service.
*/
public func amazonURLRequest(method: Alamofire.Method, path: String, subresource: String? = nil, acl: AmazonS3ACL? = nil) -> NSURLRequest {
let url = endpointURL.URLByAppendingPathComponent(path).URLByAppendingS3Subresource(subresource)
var mutableURLRequest = NSMutableURLRequest(URL: url)
mutableURLRequest.HTTPMethod = method.rawValue
setContentType(forRequest: &mutableURLRequest)
acl?.setACLHeaders(forRequest: &mutableURLRequest)
setAuthorizationHeaders(forRequest: &mutableURLRequest)
return mutableURLRequest
}
private func setContentType(inout forRequest request: NSMutableURLRequest) {
let contentTypeString = MIMEType(request) ?? "application/octet-stream"
request.setValue(contentTypeString, forHTTPHeaderField: "Content-Type")
}
private func MIMEType(request: NSURLRequest) -> String? {
if let fileExtension = request.URL?.pathExtension {
if !fileExtension.isEmpty {
let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, nil)
let UTI = UTIRef?.takeUnretainedValue()
UTIRef?.release()
if let UTI = UTI {
let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType)
if let MIMETypeRef = MIMETypeRef {
let MIMEType = MIMETypeRef.takeUnretainedValue()
MIMETypeRef.release()
return MIMEType as String
}
}
}
}
return nil
}
private func setAuthorizationHeaders(inout forRequest request: NSMutableURLRequest) {
request.cachePolicy = .ReloadIgnoringLocalCacheData
if sessionToken != nil {
request.setValue(sessionToken!, forHTTPHeaderField: "x-amz-security-token")
}
let timestamp = currentTimeStamp()
let signature = AmazonS3SignatureHelpers.AWSSignatureForRequest(request,
timeStamp: timestamp,
secret: secret)
request.setValue(timestamp ?? "", forHTTPHeaderField: "Date")
request.setValue("AWS \(accessKey):\(signature)", forHTTPHeaderField: "Authorization")
}
private func currentTimeStamp() -> String {
return requestDateFormatter.stringFromDate(NSDate())
}
private lazy var requestDateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "GMT")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return dateFormatter
}()
}
private extension NSURL {
private func URLByAppendingS3Subresource(subresource: String?) -> NSURL {
if subresource != nil && !subresource!.isEmpty {
let URLString = self.absoluteString.stringByAppendingString("?\(subresource!)")
return NSURL(string: URLString)!
}
return self
}
}
|
mit
|
bddb928386005df8b1a0f7bdcc057dd2
| 34.86618 | 214 | 0.713026 | 4.375186 | false | false | false | false |
megavolt605/CNLFoundationTools
|
CNLFoundationTools/CNLAssociated.swift
|
1
|
1415
|
//
// CNLAssociated.swift
// CNLFoundationTools
//
// Created by Igor Smirnov on 11/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import Foundation
/// Generic helper class for assotiating stored variables within extensions
///
/// Typical usage:
/// ```swift
/// var variableKey = "variableKey"
/// extension "some" {
/// var "variable": "type" {
/// get {
/// if let value = (objc_getAssociatedObject(self, &variableKey) as? CNLAssociated<"type">)?.closure {
/// return value
/// } else {
/// return "defaultValue"
/// }
/// }
/// set {
/// objc_setAssociatedObject(self, &variableKey, CNLAssociated<"type">(closure: newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
/// }
/// }
/// }
/// ```
open class CNLAssociated<T>: NSObject, NSCopying {
open var closure: T?
/// Default initializer with closure
///
/// - Parameter value: Value
public convenience init(closure: T?) {
self.init()
self.closure = closure
}
/// Default copy function
///
/// - Parameter zone: Zone
/// - Returns: Copied instance
@objc open func copy(with zone: NSZone?) -> Any {
let wrapper: CNLAssociated<T> = CNLAssociated<T>()
wrapper.closure = closure
return wrapper
}
}
|
mit
|
c6ca84c044f890a24ea4807feb4914f2
| 25.679245 | 150 | 0.5686 | 4.220896 | false | false | false | false |
oskarpearson/rileylink_ios
|
MinimedKit/Messages/ReadTempBasalCarelinkMessageBody.swift
|
1
|
1512
|
//
// ReadTempBasalCarelinkMessageBody.swift
// Naterade
//
// Created by Nathan Racklyeft on 3/7/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
public class ReadTempBasalCarelinkMessageBody: CarelinkLongMessageBody {
// MMX12 and above
private static let strokesPerUnit = 40
public enum RateType {
case absolute
case percent
}
public let timeRemaining: TimeInterval
public let rate: Double
public let rateType: RateType
public required init?(rxData: Data) {
guard rxData.count == type(of: self).length else {
return nil
}
let rawRateType: UInt8 = rxData[1]
switch rawRateType {
case 0:
rateType = .absolute
let strokes = Int(bigEndianBytes: rxData.subdata(in: 3..<5))
rate = Double(strokes) / Double(type(of: self).strokesPerUnit)
case 1:
rateType = .percent
let rawRate: UInt8 = rxData[2]
rate = Double(rawRate)
default:
timeRemaining = 0
rate = 0
rateType = .absolute
super.init(rxData: rxData)
return nil
}
let minutesRemaining = Int(bigEndianBytes: rxData.subdata(in: 5..<7))
timeRemaining = TimeInterval(minutesRemaining * 60)
super.init(rxData: rxData)
}
public required init?(rxData: NSData) {
fatalError("init(rxData:) has not been implemented")
}
}
|
mit
|
6f02af0e65e0edfebd591f5bfdfc71a0
| 25.051724 | 77 | 0.604236 | 4.392442 | false | false | false | false |
allenngn/firefox-ios
|
Client/Frontend/Reader/ReaderModeHandlers.swift
|
10
|
4615
|
/* 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
struct ReaderModeHandlers {
static func register(webServer: WebServer, profile: Profile) {
// Register our fonts and css, which we want to expose to web content that we present in the WebView
webServer.registerMainBundleResourcesOfType("ttf", module: "reader-mode/fonts")
webServer.registerMainBundleResource("Reader.css", module: "reader-mode/styles")
// Register a handler that simply lets us know if a document is in the cache or not. This is called from the
// reader view interstitial page to find out when it can stop showing the 'Loading...' page and instead load
// the readerized content.
webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page-exists") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in
if let url = request.query["url"] as? String {
if let url = NSURL(string: url) {
if ReaderModeCache.sharedInstance.contains(url, error: nil) {
return GCDWebServerResponse(statusCode: 200)
} else {
return GCDWebServerResponse(statusCode: 404)
}
}
}
return GCDWebServerResponse(statusCode: 500)
}
// Register the handler that accepts /reader-mode/page?url=http://www.example.com requests.
webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in
if let url = request.query["url"] as? String {
if let url = NSURL(string: url) {
if let readabilityResult = ReaderModeCache.sharedInstance.get(url, error: nil) {
// We have this page in our cache, so we can display it. Just grab the correct style from the
// profile and then generate HTML from the Readability results.
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict) {
readerModeStyle = style
}
}
if let html = ReaderModeUtils.generateReaderContent(readabilityResult, initialStyle: readerModeStyle) {
let response = GCDWebServerDataResponse(HTML: html)
// Apply a Content Security Policy that disallows everything except images from anywhere and fonts and css from our internal server
response.setValue("default-src 'none'; img-src *; style-src http://localhost:*; font-src http://localhost:*", forAdditionalHeader: "Content-Security-Policy")
return response
}
} else {
// This page has not been converted to reader mode yet. This happens when you for example add an
// item via the app extension and the application has not yet had a change to readerize that
// page in the background.
//
// What we do is simply queue the page in the ReadabilityService and then show our loading
// screen, which will periodically call page-exists to see if the readerized content has
// become available.
ReadabilityService.sharedInstance.process(url)
if let readerViewLoadingPath = NSBundle.mainBundle().pathForResource("ReaderViewLoading", ofType: "html") {
if let readerViewLoading = NSMutableString(contentsOfFile: readerViewLoadingPath, encoding: NSUTF8StringEncoding, error: nil) {
return GCDWebServerDataResponse(HTML: readerViewLoading as String)
}
}
}
}
}
let errorString = NSLocalizedString("There was an error converting the page", comment: "Error displayed when reader mode cannot be enabled")
return GCDWebServerDataResponse(HTML: errorString) // TODO Needs a proper error page
}
}
}
|
mpl-2.0
|
44e91a8f2d021425e53a07dd62b14039
| 64.942857 | 185 | 0.591333 | 5.82702 | false | false | false | false |
gaurav1981/Nuke
|
Sources/CancellationToken.swift
|
1
|
2775
|
// The MIT License (MIT)
//
// Copyright (c) 2017 Alexander Grebenyuk (github.com/kean).
import Foundation
/// Manages cancellation tokens and signals them when cancellation is requested.
///
/// All `CancellationTokenSource` methods are thread safe.
public final class CancellationTokenSource {
public private(set) var isCancelling = false
private var observers = [(Void) -> Void]()
private let lock: Lock
/// Creates a new token associated with the source.
public var token: CancellationToken {
return CancellationToken(source: self)
}
/// Initializes the `CancellationTokenSource` instance.
public init() {
self.lock = Lock()
}
/// Allows to create cts with a shared lock to avoid excessive allocations.
/// This is tricky to use thus `internal` access modifier.
internal init(lock: Lock) {
self.lock = lock
}
internal static let lock = Lock()
fileprivate func register(_ closure: @escaping (Void) -> Void) {
if isCancelling { closure(); return } // fast pre-lock check
lock.sync {
if isCancelling {
closure()
} else {
observers.append(closure)
}
}
}
/// Communicates a request for cancellation to the managed token.
public func cancel() {
if isCancelling { return } // fast pre-lock check
lock.sync {
if !isCancelling {
isCancelling = true
observers.forEach { $0() }
observers.removeAll()
}
}
}
}
/// Enables cooperative cancellation of operations.
///
/// You create a cancellation token by instantiating a `CancellationTokenSource`
/// object and calling its `token` property. You then pass the token to any
/// number of threads, tasks, or operations that should receive notice of
/// cancellation. When the owning object calls `cancel()`, the `isCancelling`
/// property on every copy of the cancellation token is set to `true`.
/// The registered objects can respond in whatever manner is appropriate.
///
/// All `CancellationToken` methods are thread safe.
public struct CancellationToken {
fileprivate let source: CancellationTokenSource
/// Returns `true` if cancellation has been requested for this token.
public var isCancelling: Bool { return source.isCancelling }
/// Registers the closure that will be called when the token is canceled.
/// If this token is already cancelled, the closure will be run immediately
/// and synchronously.
/// - warning: Make sure that you don't capture token inside a closure to
/// avoid retain cycles.
public func register(closure: @escaping (Void) -> Void) { source.register(closure) }
}
|
mit
|
d266e19ec2e66efc6e0bd2bf848b81c9
| 34.576923 | 88 | 0.658378 | 4.768041 | false | false | false | false |
manuelCarlos/Swift-Playgrounds
|
SafeCollection.playground/Contents.swift
|
1
|
3175
|
/// A collection containing the same elements as a `Base` collection,
/// but on which subscripts arguments return an optional instead of
/// a "Index out of range" runtime error.
public struct SafeColection <Base : Collection > : Collection {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Base.Index
/// Creates an instance with `base` as its underlying Collection
/// instance.
internal init(_base: Base) {
self._base = _base
}
internal var _base: Base
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Base.Index {
return _base.startIndex
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// `endIndex` is always reachable from `startIndex` by zero or more
/// applications of `index(after:)`.
public var endIndex: Base.Index {
return _base.endIndex
}
// TODO: swift-3-indexing-model - add docs
public var indices: Base.Indices {
return _base.indices
}
// TODO: swift-3-indexing-model - add docs
public func index(after i: Base.Index) -> Base.Index {
return _base.index(after: i)
}
/// Accesses the element at `position`.
///
/// Returns `Optional(element)` if an element was found;
/// `nil` otherwise.
///
public subscript(position: Base.Index) -> Base.Iterator.Element? {
if startIndex <= position && position < endIndex {
return _base[position]
}
return nil
}
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// - Parameter bounds: A range of the collection's indices.
///
/// - Returns: A collection representing a contiguous sub-range of
/// `self`'s elements if the bounds of the range represent valid indices of the collection; otherwise, returns an empty ArraySlice.
public subscript(bounds: Range<Index>) -> Base.SubSequence {
if startIndex <= bounds.lowerBound && bounds.upperBound <= endIndex{
return _base[bounds]
}
return _base[Range(uncheckedBounds: (lower: endIndex, upper: endIndex) ) ]
}
}
public extension Collection {
var safe: SafeColection<Self> {
return SafeColection(_base: self)
}
}
// testing
let numbers: [Int] = [1,2,2,34,4]
let first: Int? = numbers.safe[0]
let last: Int? = numbers.safe[3]
let none: Int? = numbers.safe[4]
let all = numbers.safe[1...3]
|
mit
|
d4a9ab03b3ccd8269c9b2192f46bc6d8
| 24.604839 | 135 | 0.613858 | 4.434358 | false | false | false | false |
GreenCom-Networks/ios-charts
|
Charts/Classes/Data/Implementations/Standard/BarChartDataSet.swift
|
1
|
6152
|
//
// BarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBarChartDataSet
{
private func initialize()
{
self.highlightColor = NSUIColor.blackColor()
self.calcStackSize(yVals as! [BarChartDataEntry])
self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry])
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Data functions and accessors
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
private var _stackSize = 1
/// the overall entry count, including counting each stack-value individually
private var _entryCountStacks = 0
/// Calculates the total number of entries this DataSet represents, including
/// stacks. All values belonging to a stack are calculated separately.
private func calcEntryCountIncludingStacks(yVals: [BarChartDataEntry]!)
{
_entryCountStacks = 0
for i in 0 ..< yVals.count
{
let vals = yVals[i].values
if (vals == nil)
{
_entryCountStacks += 1
}
else
{
_entryCountStacks += vals!.count
}
}
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(yVals: [BarChartDataEntry]!)
{
for i in 0 ..< yVals.count
{
if let vals = yVals[i].values
{
if vals.count > _stackSize
{
_stackSize = vals.count
}
}
}
}
public override func calcMinMax(start start : Int, end: Int)
{
let yValCount = _yVals.count
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for i in start ... endValue
{
if let e = _yVals[i] as? BarChartDataEntry
{
if !e.value.isNaN
{
if e.values == nil
{
if e.value < _yMin
{
_yMin = e.value
}
if e.value > _yMax
{
_yMax = e.value
}
}
else
{
if -e.negativeSum < _yMin
{
_yMin = -e.negativeSum
}
if e.positiveSum > _yMax
{
_yMax = e.positiveSum
}
}
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
/// - returns: the maximum number of bars that can be stacked upon another in this DataSet.
public var stackSize: Int
{
return _stackSize
}
/// - returns: true if this DataSet is stacked (stacksize > 1) or not.
public var isStacked: Bool
{
return _stackSize > 1 ? true : false
}
/// - returns: the overall entry count, including counting each stack-value individually
public var entryCountStacks: Int
{
return _entryCountStacks
}
/// array of labels used to describe the different values of the stacked bars
public var stackLabels: [String] = ["Stack"]
// MARK: - Styling functions and accessors
/// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width)
public var barSpace: CGFloat = 0.15
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
public var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
public var highlightAlpha = CGFloat(120.0 / 255.0)
/// the default bar border color
public var barStrokeColor = NSUIColor.clearColor()
/// the default bar border width
public var barStrokeWidth = CGFloat(1.0)
/// indicate if bar stroke are enable or not
public var barStrokeEnabled = false
// the default bar width
public var barWidth = CGFloat(0.5)
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! BarChartDataSet
copy._stackSize = _stackSize
copy._entryCountStacks = _entryCountStacks
copy.stackLabels = stackLabels
copy.barSpace = barSpace
copy.barShadowColor = barShadowColor
copy.highlightAlpha = highlightAlpha
copy.barStrokeColor = barStrokeColor
copy.barStrokeWidth = barStrokeWidth
copy.barStrokeEnabled = barStrokeEnabled
copy.barWidth = barWidth
return copy
}
}
|
apache-2.0
|
bef4756995bb789cc968b0eb1abbd2c1
| 27.752336 | 148 | 0.524382 | 5.289768 | false | false | false | false |
jhurray/Ladybug
|
Source/JSONTransformer.swift
|
1
|
7578
|
//
// JSONTransformer.swift
// Ladybug iOS
//
// Created by Jeff Hurray on 7/31/17.
// Copyright © 2017 jhurray. All rights reserved.
//
import Foundation
/// A protocol that facilitates transforming of JSON objects. Used by objects conforming to JSONCodable
public protocol JSONTransformer {
/// Key path that points to the JSON value that is being mapped.
/// If `nil` the keypath is assumed to be the `propertyKey` passed to the `transform` method.
var keyPath: JSONKeyPath? { get }
// Alters a JSON object to prepare for decoding
func transform(_ json: inout [String: Any], mappingTo propertyKey: PropertyKey)
// Alters a JSON object to prepare for encoding
func reverseTransform(_ json: inout [String: Any], mappingFrom propertyKey: PropertyKey)
}
/// Maps a JSON value at this key path to a `Codable` property of an object conforming to `JSONCodable`
extension JSONKeyPath: JSONTransformer {
public var keyPath: JSONKeyPath? {
return self
}
public func transform(_ json: inout [String: Any], mappingTo propertyKey: PropertyKey) {
if let value = json[jsonKeyPath: self] {
json[propertyKey] = value
}
}
}
/// `String` can act as a `JSONKeyPath`
extension String: JSONTransformer {
public var keyPath: JSONKeyPath? {
return JSONKeyPath(self)
}
public func transform(_ json: inout [String : Any], mappingTo propertyKey: PropertyKey) {
keyPath?.transform(&json, mappingTo: propertyKey)
}
public func reverseTransform(_ json: inout [String: Any], mappingFrom propertyKey: PropertyKey) {
keyPath?.reverseTransform(&json, mappingFrom: propertyKey)
}
}
/// Supplies a default value for a given property. Can be used for Migrations and API changes.
public struct Default: JSONTransformer {
public var keyPath: JSONKeyPath? { return nil }
private let value: Any
private let override: Bool
/**
Supplies a default value for a given property
- Parameter value: The default value that will be assigned to the property
- Parameter override: If a value exists at the mapped-to `propertyKey` and override == true, the existing value will be replaced with value supplied
*/
init(value: Any, override: Bool = false) {
self.value = value
self.override = override
}
public func transform(_ json: inout [String: Any], mappingTo propertyKey: PropertyKey) {
guard json[propertyKey] == nil || override else {
return
}
json[propertyKey] = value
}
}
/// Used to map JSON values to a Codable property of type `MappedToType`
public struct Map<MappedToType: Codable>: JSONTransformer {
public let keyPath: JSONKeyPath?
private let map: (Any?) -> MappedToType?
/**
Used to map JSON values to a Codable property of type `MappedToType`
- Parameter map: A closure that transforms the JSON value to a value of type `MappedToType`
*/
public init(map: @escaping (Any?) -> MappedToType?) {
self.keyPath = nil
self.map = map
}
/**
Used to map JSON values to a Codable property of type `MappedToType`
- Parameter keyPath: Key path that points to the JSON value that is being mapped
- Parameter map: A closure that transforms the JSON value to a value of type `MappedToType`
*/
public init(keyPath: JSONKeyPath, map: @escaping (Any?) -> MappedToType?) {
self.keyPath = keyPath
self.map = map
}
public func transform(_ json: inout [String: Any], mappingTo propertyKey: PropertyKey) {
let keyPath = resolvedKeyPath(propertyKey)
if let mappedValue = map(json[jsonKeyPath: keyPath]) {
json[propertyKey] = mappedValue
}
}
}
/// Maps a JSON object to a type conforming to JSONCodable
internal struct NestedObjectTransformer<Type: JSONCodable>: JSONTransformer {
public let keyPath: JSONKeyPath?
/**
Maps the JSON value at the given key path to the given property of type `Type`
- Parameter keyPath: Key path that points to the JSON value that is being mapped
*/
public init(keyPath: JSONKeyPath? = nil) {
self.keyPath = keyPath
}
private func alterNestedJSON(_ json: inout [String: Any], propertyKey: PropertyKey, alteration: (inout [String: Any]) -> ()) {
let keyPath = resolvedKeyPath(propertyKey)
guard var nestedJSON = json[jsonKeyPath: keyPath] as? [String: Any] else {
return
}
alteration(&nestedJSON)
json[propertyKey] = nestedJSON
}
public func transform(_ json: inout [String: Any], mappingTo propertyKey: PropertyKey) {
alterNestedJSON(&json, propertyKey: propertyKey, alteration: Type.alterForDecoding)
}
public func reverseTransform(_ json: inout [String : Any], mappingFrom propertyKey: PropertyKey) {
alterNestedJSON(&json, propertyKey: propertyKey, alteration: Type.alterForEncoding)
}
}
/// Maps a JSON array to an array of a type conforming to JSONCodable
internal struct NestedListTransformer<Type: JSONCodable>: JSONTransformer {
public let keyPath: JSONKeyPath?
/**
Maps the JSON value at the given key path to the given property of type `[Type]`
- Parameter keyPath: Key path that points to the JSON array that is being mapped
*/
public init(keyPath: JSONKeyPath? = nil) {
self.keyPath = keyPath
}
private func alterNestedJSON(_ json: inout [String: Any], propertyKey: PropertyKey, alteration: (inout [String: Any]) -> ()) {
let keyPath = resolvedKeyPath(propertyKey)
guard let nestedJSONList = json[jsonKeyPath: keyPath] as? [[String: Any]] else {
return
}
var alteredJSONList: [[String: Any]] = []
for var nestedJSON in nestedJSONList {
alteration(&nestedJSON)
alteredJSONList.append(nestedJSON)
}
json[propertyKey] = alteredJSONList
}
public func transform(_ json: inout [String: Any], mappingTo propertyKey: PropertyKey) {
alterNestedJSON(&json, propertyKey: propertyKey, alteration: Type.alterForDecoding)
}
public func reverseTransform(_ json: inout [String : Any], mappingFrom propertyKey: PropertyKey) {
alterNestedJSON(&json, propertyKey: propertyKey, alteration: Type.alterForEncoding)
}
}
internal struct CompositeTransformer: JSONTransformer {
let transformers: [JSONTransformer]
init(transformers: JSONTransformer...) {
self.transformers = transformers
}
public var keyPath: JSONKeyPath? {
return nil
}
func transform(_ json: inout [String : Any], mappingTo propertyKey: PropertyKey) {
transformers.forEach {
$0.transform(&json, mappingTo: propertyKey)
}
}
func reverseTransform(_ json: inout [String : Any], mappingFrom propertyKey: PropertyKey) {
transformers.forEach {
$0.reverseTransform(&json, mappingFrom: propertyKey)
}
}
}
internal extension JSONTransformer {
internal func resolvedKeyPath(_ propertyKey: PropertyKey) -> JSONKeyPath {
return keyPath ?? JSONKeyPath(propertyKey)
}
}
public extension JSONTransformer {
func reverseTransform(_ json: inout [String: Any], mappingFrom propertyKey: PropertyKey) {
// Default Implementation - Override point
}
}
|
mit
|
e2a840bd6caa6f1c3f8d9dc892ae8400
| 33.285068 | 153 | 0.660948 | 4.637087 | false | false | false | false |
svanimpe/around-the-table
|
Sources/AroundTheTable/ViewModels/EditActivityDateTimeViewModel.swift
|
1
|
996
|
import Foundation
/**
View model for **edit-activity-datetime.stencil**.
*/
struct EditActivityDateTimeViewModel: Codable {
let base: BaseViewModel
let id: Int
struct DateViewModel: Codable {
let day: Int
let month: Int
let year: Int
let hour: Int
let minute: Int
init(_ components: DateComponents) {
day = components.day!
month = components.month!
year = components.year!
hour = components.hour!
minute = components.minute!
}
}
let date: DateViewModel
init(base: BaseViewModel, activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
self.base = base
self.id = id
let components = Settings.calendar.dateComponents(in: Settings.timeZone, from: activity.date)
self.date = DateViewModel(components)
}
}
|
bsd-2-clause
|
7ec72da59d1fc423e52e0eb5769b9e89
| 24.538462 | 101 | 0.578313 | 4.811594 | false | false | false | false |
aestesis/Aether
|
Sources/Aether/Foundation/Texture2D.swift
|
1
|
16820
|
//
// Texture2D.swift
// Aether
//
// Created by renan jegouzo on 01/03/2016.
// Copyright © 2016 aestesis. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
#if os(OSX)
import Metal
import CoreGraphics
import AppKit
#elseif os(iOS) || os(tvOS)
import Metal
import CoreGraphics
import UIKit
#else
import Uridium
#endif
// camera: http://stackoverflow.com/questions/37445052/how-to-create-a-mtltexture-backed-by-a-cvpixelbuffer
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
open class Texture2D : NodeUI {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum Format {
case alphaOnly
case rgba
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#if os(macOS) || os(iOS) || os(tvOS)
public private(set) var texture:MTLTexture?
#else
public private(set) var texture:Tin.Texture?
#endif
public private(set) var pixels:Size=Size.zero
public private(set) var pixel:Size=Size.unity
public private(set) var border:Size=Size.zero
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var ready:Bool {
return texture != nil
}
public var display:Size {
return Size((pixels.width-border.width*2)*pixel.width,(pixels.height-border.height)*pixel.height)
}
public var scale:Size {
get { return Size.unity/pixel }
set(s) { pixel=Size.unity/s }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#if os(macOS) || os(iOS) || os(tvOS)
internal func initialize(from cg:CGImage) {
do {
try self.texture=viewport!.gpu.loader!.newTexture(cgImage:cg,options:nil)
pixels.width=Double(texture!.width)
pixels.height=Double(texture!.height)
} catch {
Debug.error("can't create texture from CGImage",#file,#line)
}
}
#else
internal func initialize(from rb:RawBitmap) {
texture = Tin.Texture(engine:viewport!.gpu.engine!,width:rb.size.width,height:rb.size.height,pixels:rb.pixels)
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
internal func load(_ filename:String) {
#if os(iOS) || os(tvOS)
if let ui = UIImage(contentsOfFile: Application.resourcePath(filename)), let cg=ui.cgImage {
if viewport != nil && ui.size.width != 0 && ui.size.height != 0 {
initialize(from: cg)
} else if viewport == nil {
Debug.error("can't load texture: \(filename), Texture already detached (no viewport)",#file,#line)
} else {
Debug.error("can't load texture: \(filename), bad file format)",#file,#line)
}
} else {
Debug.error("can't load texture: \(filename), file not found)",#file,#line)
}
#elseif os(macOS)
if let ns=NSImage(contentsOfFile: Application.resourcePath(filename)), let cg=ns.cgImage(forProposedRect: nil,context:nil,hints:nil) {
if viewport != nil && ns.size.width != 0 && ns.size.height != 0 {
initialize(from: cg)
} else if viewport == nil {
Debug.error("can't load texture: \(filename), Texture detached (no viewport)",#file,#line)
} else {
Debug.error("can't load texture: \(filename), bad file format)",#file,#line)
}
} else {
Debug.error("can't load texture: \(filename), file not found)",#file,#line)
}
#else
if let rb = RawBitmap(path:Application.resourcePath(filename)) {
if viewport != nil && rb.size.width != 0 && rb.size.height != 0 {
initialize(from: rb)
} else if viewport == nil {
Debug.error("can't load texture: \(filename), Texture detached (no viewport)",#file,#line)
} else {
Debug.error("can't load texture: \(filename), bad file format)",#file,#line)
}
} else {
Debug.error("can't load texture: \(filename), file not found)",#file,#line)
}
#endif
// decode displaysize&scale from filename eg: filename.134x68.png -> display=Size(134,68)
let m=filename.split(".")
var n = 2
while m.count > n {
let s=m[m.count-n]
//Debug.info(s)
let ss=s.split("x")
if ss.count == 2 {
if let w=Int(ss[0]), let h=Int(ss[1]) {
pixel.width=Double(w)/pixels.width
pixel.height=Double(h)/pixels.height
}
}
n += 1
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
internal func load(_ data:Foundation.Data) {
// https://developer.apple.com/reference/coregraphics/cgimage/1455149-init load image without premutiplied alpha
#if os(iOS) || os(tvOS)
if let ui = UIImage(data:data), let cg=ui.cgImage {
if viewport != nil {
initialize(from: cg)
} else {
Debug.error("can't load texture: Texture detached (no viewport)",#file,#line)
}
}
#elseif os(macOS)
if let ns=NSImage(data:data), let cg=ns.cgImage(forProposedRect: nil,context:nil,hints:nil) {
if viewport != nil {
initialize(from: cg)
} else {
Debug.error("can't load texture: Texture detached (no viewport)",#file,#line)
}
}
#else
Debug.notImplemented()
#endif
}
#if os(macOS) || os(iOS) || os(tvOS)
static var memoCG=[[UInt32]]()
public var cg : CGImage? {
var data = self.get()
for i in 0..<data!.count {
var c = Color(abgr:data![i])
c.r *= c.a
c.g *= c.a
c.b *= c.a
data![i] = c.rgba
}
Texture2D.memoCG.append(data!)
let cs = CGColorSpaceCreateDeviceRGB()
let bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue:CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue)
let selftureSize = self.pixels.width * self.pixels.height * 4
let rowBytes = self.pixels.width * 4
let provider = CGDataProvider(dataInfo: nil, data: UnsafeMutablePointer(mutating:Texture2D.memoCG.last!)!, size: Int(selftureSize), releaseData: { u,d,c in
for i in 0..<Texture2D.memoCG.count {
if &Texture2D.memoCG[i] == d {
Texture2D.memoCG.remove(at: i)
break
}
}
})
return CGImage(width: Int(self.pixels.width), height: Int(self.pixels.height), bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: Int(rowBytes), space: cs, bitmapInfo: bitmapInfo, provider: provider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
}
#endif
#if os(iOS) || os(tvOS)
public var system : UIImage? {
get {
if let cg = self.cg {
return UIImage(cgImage: cg)
}
return nil
}
}
#elseif os(OSX)
public var system : NSImage? {
get {
if let cg = self.cg {
return NSImage(cgImage: cg, size: NSSize(width: CGFloat(cg.width), height: CGFloat(cg.height)))
}
return nil
}
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#if DEBUG
let dbgInfo:String
override public var debugDescription: String {
return dbgInfo
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public init(parent:NodeUI,texture:Texture2D,file:String=#file,line:Int=#line) {
#if DEBUG
self.dbgInfo = "Texture.init(file:'\(file)',line:\(line))"
#endif
self.pixels = texture.pixels
if texture.texture == nil {
Debug.error("Texture2D from texture, nil value")
}
self.texture = texture.texture
super.init(parent:parent)
self.scale = texture.scale
}
#if os(macOS) || os(iOS) || os(tvOS)
public init(parent:NodeUI,size:Size,scale:Size=Size(1,1),texture:MTLTexture,file:String=#file,line:Int=#line) {
#if DEBUG
self.dbgInfo = "Texture.init(file:'\(file)',line:\(line))"
#endif
self.pixels = size * scale
self.texture = texture
super.init(parent:parent)
self.scale = scale
}
public init(parent:NodeUI,size:Size,scale:Size=Size(1,1),border:Size=Size.zero,format:Format = .rgba,file:String=#file,line:Int=#line) {
#if DEBUG
self.dbgInfo = "Texture.init(file:'\(file)',line:\(line))"
#endif
let pixfmt = (format == .rgba) ? MTLPixelFormat.bgra8Unorm : MTLPixelFormat.a8Unorm
self.pixels=size*scale
super.init(parent: parent)
self.scale=scale
let d=MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixfmt, width: Int(self.pixels.width), height: Int(self.pixels.height), mipmapped: false)
//d.textureType = .Type2DMultisample // TODO: implement multisampled texture http://stackoverflow.com/questions/36227209/multi-sampling-jagged-edges-in-metalios
d.usage = [.shaderRead, .renderTarget]
self.texture=viewport!.gpu.device?.makeTexture(descriptor:d)
}
public init(parent:NodeUI,cg:CGImage,file:String=#file,line:Int=#line) {
#if DEBUG
self.dbgInfo = "Texture.init(file:'\(file)',line:\(line))"
#endif
super.init(parent:parent)
do {
try self.texture=viewport!.gpu.loader!.newTexture(cgImage:cg,options:nil)
pixels.width=Double(texture!.width)
pixels.height=Double(texture!.height)
} catch {
Debug.error("can't create texture from CGImage",#file,#line)
}
}
#else
public init(parent:NodeUI,size:Size,scale:Size=Size(1,1),border:Size=Size.zero,format:Format = .rgba,pixels:[UInt32]? = nil,file:String=#file,line:Int=#line) {
#if DEBUG
self.dbgInfo = "Texture.init(file:'\(file)',line:\(line))"
#endif
self.pixels=size*scale
super.init(parent: parent)
self.scale=scale
texture = Tin.Texture(engine:viewport!.gpu.engine!,width:Int(self.pixels.width),height:Int(self.pixel.height),pixels:pixels)
}
#endif
public init(parent:NodeUI,path:String,border:Size=Size.zero,file:String=#file,line:Int=#line) {
#if DEBUG
self.dbgInfo = "Texture.init(file:'\(file)',line:\(line))"
#endif
self.border=border
super.init(parent: parent)
load(path)
}
public init(parent:NodeUI,data:[UInt8],file:String=#file,line:Int=#line) {
#if DEBUG
self.dbgInfo = "Texture.init(file:'\(file)',line:\(line))"
#endif
super.init(parent:parent)
let d = Data(bytesNoCopy: UnsafeMutablePointer(mutating:data), count: data.count, deallocator: Data.Deallocator.none)
load(d)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
override open func detach() {
texture = nil
super.detach()
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#if os(macOS) || os(iOS) || os(tvOS)
public func get() -> [UInt32]? {
if let t=texture {
let data=[UInt32](repeating: 0,count: t.width*t.height)
t.getBytes(UnsafeMutablePointer(mutating:data), bytesPerRow: t.width*4, from: MTLRegion(origin:MTLOrigin(x:0,y:0,z:0),size:MTLSize(width:t.width,height:t.height,depth:1)), mipmapLevel: 0)
return data
} else {
Debug.error(Error("no texture",#file,#line))
}
return nil
}
public func get(pixel p:Point) -> Color {
if let t=texture {
let data=[UInt32](repeating: 0,count: 1)
t.getBytes(UnsafeMutablePointer(mutating:data), bytesPerRow: t.width*4, from: MTLRegion(origin:MTLOrigin(x:Int(p.x),y:Int(p.y),z:0),size:MTLSize(width:1,height:1,depth:1)), mipmapLevel: 0)
return Color(abgr:data[0])
} else {
Debug.error(Error("no texture",#file,#line))
}
return Color.transparent
}
public func set(pixels data:[UInt32]) {
if let t=texture {
t.replace(region: MTLRegion(origin:MTLOrigin(x:0,y:0,z:0),size:MTLSize(width:t.width,height:t.height,depth:1)), mipmapLevel: 0, withBytes: UnsafePointer(data), bytesPerRow: t.width*4)
} else {
Debug.error(Error("no texture",#file,#line))
}
}
public func set(raw data:UnsafeRawPointer) {
if let t=texture {
if t.pixelFormat == .rgba8Unorm {
t.replace(region: MTLRegion(origin:MTLOrigin(x:0,y:0,z:0),size:MTLSize(width:t.width,height:t.height,depth:1)), mipmapLevel: 0, withBytes: data, bytesPerRow: t.width*4)
} else { // MTLPixelFormat.a8Unorm
t.replace(region: MTLRegion(origin:MTLOrigin(x:0,y:0,z:0),size:MTLSize(width:t.width,height:t.height,depth:1)), mipmapLevel: 0, withBytes: data, bytesPerRow: t.width)
}
} else {
Debug.error(Error("no texture",#file,#line))
}
}
#else
public func set(pixels data:[UInt32]) {
Debug.notImplemented()
// TODO:
}
public func set(raw data:UnsafeRawPointer) {
Debug.notImplemented()
// TODO:
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
|
apache-2.0
|
8976def0fed51cc1f06c738ca9666150
| 46.377465 | 275 | 0.469112 | 4.673243 | false | false | false | false |
ParsePlatform/Parse-SDK-iOS-OSX
|
ParseUI/ParseUIDemo/Swift/CustomViewControllers/QueryTableViewController/DeletionTableViewController.swift
|
1
|
3592
|
//
// DeletionTableViewController.swift
// ParseUIDemo
//
// Created by Richard Ross III on 5/13/15.
// Copyright (c) 2015 Parse Inc. All rights reserved.
//
import UIKit
import Parse
import ParseUI
import Bolts.BFTask
class DeletionTableViewController: PFQueryTableViewController, UIAlertViewDelegate {
// MARK: Init
convenience init(className: String?) {
self.init(style: .plain, className: className)
title = "Deletion Table"
pullToRefreshEnabled = true
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.allowsMultipleSelectionDuringEditing = true
navigationItem.rightBarButtonItems = [
editButtonItem,
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTodo))
]
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if (editing) {
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .trash,
target: self,
action: #selector(deleteSelectedItems)
)
} else {
navigationItem.leftBarButtonItem = navigationItem.backBarButtonItem
}
}
override func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCellEditingStyle,
forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
removeObject(at: indexPath)
}
}
@objc
func addTodo() {
if #available(iOS 8.0, *) {
let alertDialog = UIAlertController(title: "Add Todo", message: nil, preferredStyle: .alert)
var titleTextField : UITextField! = nil
alertDialog.addTextField(configurationHandler: {
titleTextField = $0
})
alertDialog.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertDialog.addAction(UIAlertAction(title: "Save", style: .default) { _ in
if let title = titleTextField.text {
let object = PFObject(className: self.parseClassName!, dictionary: [ "title": title ])
object.saveInBackground().continueOnSuccessWith { _ -> AnyObject! in
return self.loadObjects()
}
}
})
present(alertDialog, animated: true, completion: nil)
} else {
let alertView = UIAlertView(
title: "Add Todo",
message: "",
delegate: self,
cancelButtonTitle: "Cancel",
otherButtonTitles: "Save"
)
alertView.alertViewStyle = .plainTextInput
alertView.textField(at: 0)?.placeholder = "Name"
alertView.show()
}
}
@objc
func deleteSelectedItems() {
removeObjects(at: tableView.indexPathsForSelectedRows)
}
// MARK - UIAlertViewDelegate
@objc
func alertView(_ alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
if (buttonIndex == alertView.cancelButtonIndex) {
return
}
if let title = alertView.textField(at: 0)?.text {
let object = PFObject(className: self.parseClassName!, dictionary: [ "title": title ])
object.saveEventually().continueOnSuccessWith { _ -> AnyObject! in
return self.loadObjects()
}
}
}
}
|
bsd-3-clause
|
56aa0e170d2b0604267d8ef0dab482d9
| 29.440678 | 106 | 0.58157 | 5.425982 | false | false | false | false |
RoRoche/iOSSwiftStarter
|
iOSSwiftStarter/Pods/Nimble/Sources/Nimble/Matchers/BeCloseTo.swift
|
30
|
4861
|
#if os(Linux)
import Glibc
#endif
import Foundation
internal let DefaultDelta = 0.0001
internal func isCloseTo(actualValue: NMBDoubleConvertible?, expectedValue: NMBDoubleConvertible, delta: Double, failureMessage: FailureMessage) -> Bool {
failureMessage.postfixMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))"
failureMessage.actualValue = "<\(stringify(actualValue))>"
return actualValue != nil && abs(actualValue!.doubleValue - expectedValue.doubleValue) < delta
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(expectedValue: Double, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<Double> {
return NonNilMatcherFunc { actualExpression, failureMessage in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage)
}
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<NMBDoubleConvertible> {
return NonNilMatcherFunc { actualExpression, failureMessage in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage)
}
}
#if _runtime(_ObjC)
public class NMBObjCBeCloseToMatcher : NSObject, NMBMatcher {
var _expected: NSNumber
var _delta: CDouble
init(expected: NSNumber, within: CDouble) {
_expected = expected
_delta = within
}
public func matches(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = beCloseTo(self._expected, within: self._delta)
return try! matcher.matches(expr, failureMessage: failureMessage)
}
public func doesNotMatch(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let matcher = beCloseTo(self._expected, within: self._delta)
return try! matcher.doesNotMatch(expr, failureMessage: failureMessage)
}
public var within: (CDouble) -> NMBObjCBeCloseToMatcher {
return ({ delta in
return NMBObjCBeCloseToMatcher(expected: self._expected, within: delta)
})
}
}
extension NMBObjCMatcher {
public class func beCloseToMatcher(expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToMatcher {
return NMBObjCBeCloseToMatcher(expected: expected, within: within)
}
}
#endif
public func beCloseTo(expectedValues: [Double], within delta: Double = DefaultDelta) -> NonNilMatcherFunc <[Double]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))"
if let actual = try actualExpression.evaluate() {
failureMessage.actualValue = "<\(stringify(actual))>"
if actual.count != expectedValues.count {
return false
} else {
for (index, actualItem) in actual.enumerate() {
if fabs(actualItem - expectedValues[index]) > delta {
return false
}
}
return true
}
}
return false
}
}
// MARK: - Operators
infix operator ≈ {
associativity none
precedence 130
}
public func ≈(lhs: Expectation<[Double]>, rhs: [Double]) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation<Double>, rhs: Double) {
lhs.to(beCloseTo(rhs))
}
public func ≈(lhs: Expectation<Double>, rhs: (expected: Double, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
public func ==(lhs: Expectation<Double>, rhs: (expected: Double, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
// make this higher precedence than exponents so the Doubles either end aren't pulled in
// unexpectantly
infix operator ± { precedence 170 }
public func ±(lhs: Double, rhs: Double) -> (expected: Double, delta: Double) {
return (expected: lhs, delta: rhs)
}
|
apache-2.0
|
b870d789ca742b24395f3365f9d48a30
| 38.120968 | 153 | 0.688106 | 4.841317 | false | false | false | false |
HabitRPG/habitrpg-ios
|
Habitica Database/Habitica Database/Models/User/RealmTag.swift
|
1
|
767
|
//
// RealmTag.swift
// Habitica Database
//
// Created by Phillip Thelen on 06.03.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmTag: Object, TagProtocol {
@objc dynamic var id: String?
@objc dynamic var userID: String?
@objc dynamic var text: String?
@objc dynamic var order: Int = 0
override static func primaryKey() -> String {
return "id"
}
var isValid: Bool {
return !isInvalidated
}
convenience init(userID: String?, tagProtocol: TagProtocol) {
self.init()
id = tagProtocol.id
self.userID = userID
text = tagProtocol.text
order = tagProtocol.order
}
}
|
gpl-3.0
|
78aaec69571e3f04e901373d08813cd1
| 20.885714 | 65 | 0.626632 | 4.163043 | false | false | false | false |
february29/Learning
|
swift/Fch_Contact/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift
|
15
|
2931
|
//
// RxPickerViewAdapter.swift
// RxCocoa
//
// Created by Sergey Shulga on 12/07/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
#if os(iOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
class RxPickerViewArrayDataSource<T>: NSObject, UIPickerViewDataSource, SectionedViewDataSourceType {
fileprivate var items: [T] = []
func model(at indexPath: IndexPath) throws -> Any {
guard items.indices ~= indexPath.row else {
throw RxCocoaError.itemsNotYetBound(object: self)
}
return items[indexPath.row]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return items.count
}
}
class RxPickerViewSequenceDataSource<S: Sequence>
: RxPickerViewArrayDataSource<S.Iterator.Element>
, RxPickerViewDataSourceType {
typealias Element = S
func pickerView(_ pickerView: UIPickerView, observedEvent: Event<S>) {
Binder(self) { dataSource, items in
dataSource.items = items
pickerView.reloadAllComponents()
}
.on(observedEvent.map(Array.init))
}
}
final class RxStringPickerViewAdapter<S: Sequence>
: RxPickerViewSequenceDataSource<S>
, UIPickerViewDelegate {
typealias TitleForRow = (Int, S.Iterator.Element) -> String?
private let titleForRow: TitleForRow
init(titleForRow: @escaping TitleForRow) {
self.titleForRow = titleForRow
super.init()
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return titleForRow(row, items[row])
}
}
final class RxAttributedStringPickerViewAdapter<S: Sequence>: RxPickerViewSequenceDataSource<S>, UIPickerViewDelegate {
typealias AttributedTitleForRow = (Int, S.Iterator.Element) -> NSAttributedString?
private let attributedTitleForRow: AttributedTitleForRow
init(attributedTitleForRow: @escaping AttributedTitleForRow) {
self.attributedTitleForRow = attributedTitleForRow
super.init()
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
return attributedTitleForRow(row, items[row])
}
}
final class RxPickerViewAdapter<S: Sequence>: RxPickerViewSequenceDataSource<S>, UIPickerViewDelegate {
typealias ViewForRow = (Int, S.Iterator.Element, UIView?) -> UIView
private let viewForRow: ViewForRow
init(viewForRow: @escaping ViewForRow) {
self.viewForRow = viewForRow
super.init()
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
return viewForRow(row, items[row], view)
}
}
#endif
|
mit
|
4433fe9d1f481b7eb203c7f64d799801
| 30.505376 | 133 | 0.693515 | 4.819079 | false | false | false | false |
epv44/TwitchAPIWrapper
|
Sources/TwitchAPIWrapper/Requests/ExtensionAnalyticsRequest.swift
|
1
|
917
|
//
// ExtensionAnalyticsRequest.swift
// TwitchAPIWrapper
//
// Created by Eric Vennaro on 5/2/21.
//
import Foundation
///Get extension analytics request, see https://dev.twitch.tv/docs/api/reference/#get-extension-analytics for details
public struct ExtensionAnalyticsRequest: JSONConstructableRequest {
public let url: URL?
public init(
after: String? = nil,
endedAt: String? = nil,
extensionID: String? = nil,
first: String? = nil,
startedAt: String? = nil,
type: String? = nil
) {
self.url = TwitchEndpoints.analyticsExtension.construct()?.appending(
queryItems: [
"after": after,
"ended_at": endedAt,
"extension_id": extensionID,
"first": first,
"started_at": startedAt,
"type": type
].buildQueryItems())
}
}
|
mit
|
6740af8ef516ac9789f4469410b58cf8
| 27.65625 | 117 | 0.575791 | 4.305164 | false | false | false | false |
vulgur/WeeklyFoodPlan
|
WeeklyFoodPlan/WeeklyFoodPlan/Models/Food.swift
|
1
|
2147
|
//
// HomeCook.swift
// WeeklyFoodPlan
//
// Created by vulgur on 2017/1/21.
// Copyright © 2017年 MAD. All rights reserved.
//
import Foundation
import RealmSwift
class WhenObject: Object {
dynamic var value = Food.When.lunch.rawValue
override static func primaryKey() -> String? {
return "value"
}
}
class Food: Object {
enum When: String {
case breakfast = "Breakfast"
case brunch = "Brunch"
case lunch = "Lunch"
case dinner = "Dinner"
}
enum FoodType: String {
case homeCook = "HomeCook"
case eatingOut = "EatingOut"
case takeOut = "TakeOut"
}
dynamic var id = UUID().uuidString
dynamic var name: String = ""
dynamic var isFavored: Bool = false
dynamic var imagePath: String?
var whenObjects = List<WhenObject>()
var tags = List<Tag>()
var ingredients = List<Ingredient>()
var tips = List<Tip>()
dynamic var cookCount:Int = 0
dynamic var typeRawValue = FoodType.homeCook.rawValue
override static func primaryKey() -> String? {
return "id"
}
func addNeedIngredientCount() {
for i in self.ingredients {
i.neededCount += 1
}
}
func reduceNeedIngredientCount() {
for i in self.ingredients {
i.neededCount -= 1
}
}
func consumeIngredients() {
for i in self.ingredients {
i.remainedCount -= 1
i.neededCount -= 1
}
}
func restoreIngredients() {
for i in self.ingredients {
i.remainedCount += 1
i.neededCount += 1
}
}
}
extension Food{
var type: FoodType {
get {
if let result = FoodType(rawValue: typeRawValue) {
return result
} else {
return FoodType.homeCook
}
}
}
var whenList: [String] {
get {
var result = [String]()
for obj in whenObjects {
result.append(obj.value)
}
return result
}
}
}
|
mit
|
356eee7d32ba0cf27da26ed6de3fae28
| 21.103093 | 62 | 0.534981 | 4.357724 | false | false | false | false |
pksprojects/ElasticSwift
|
Sources/ElasticSwiftNetworkingNIO/ElasticSwiftNetworkingNIO.swift
|
1
|
1862
|
//
// ElasticSwiftNetworkingNIO.swift
// ElasticSwiftNetworkingNIO
//
// Created by Prafull Kumar Soni on 9/27/19.
//
import AsyncHTTPClient
import ElasticSwiftCore
import Foundation
import Logging
import NIO
// MARK: - Timeouts
public struct Timeouts {
public static let DEFAULT_TIMEOUTS = Timeouts(read: TimeAmount.milliseconds(5000), connect: TimeAmount.milliseconds(5000))
public let read: TimeAmount?
public let connect: TimeAmount?
public init(read: TimeAmount? = nil, connect: TimeAmount? = nil) {
self.read = read
self.connect = connect
}
}
extension Timeouts: Equatable {}
// MARK: - HTTPAdaptorConfiguration
/// Class holding HTTPAdaptor Config
public class AsyncHTTPClientAdaptorConfiguration: HTTPAdaptorConfiguration {
public let adaptor: ManagedHTTPClientAdaptor.Type
public let clientConfig: HTTPClient.Configuration
public let eventLoopProvider: HTTPClient.EventLoopGroupProvider
public init(adaptor: ManagedHTTPClientAdaptor.Type = AsyncHTTPClientAdaptor.self, eventLoopProvider: HTTPClient.EventLoopGroupProvider = .createNew, asyncClientConfig: HTTPClient.Configuration) {
self.eventLoopProvider = eventLoopProvider
self.adaptor = adaptor
clientConfig = asyncClientConfig
}
public convenience init(adaptor: ManagedHTTPClientAdaptor.Type = AsyncHTTPClientAdaptor.self, eventLoopProvider: HTTPClient.EventLoopGroupProvider = .createNew, timeouts: Timeouts? = Timeouts.DEFAULT_TIMEOUTS) {
var config = HTTPClient.Configuration()
config.timeout = .init(connect: timeouts?.connect, read: timeouts?.read)
self.init(adaptor: adaptor, eventLoopProvider: eventLoopProvider, asyncClientConfig: config)
}
public static var `default`: HTTPAdaptorConfiguration {
return AsyncHTTPClientAdaptorConfiguration()
}
}
|
mit
|
ce5f4a4603539dde08e11a2a28c5f6f4
| 32.854545 | 215 | 0.758324 | 4.823834 | false | true | false | false |
mrahmiao/Velociraptor
|
VelociraptorTests/NSURLSessionStubs/SimpleRequestsWithEphemeralSessionConfigurationTests.swift
|
1
|
3920
|
//
// SimpleRequestsWithEphemeralSessionConfigurationTests.swift
// Velociraptor
//
// Created by mrahmiao on 5/7/15.
// Copyright (c) 2015 Code4Blues. All rights reserved.
//
import Foundation
import XCTest
import Velociraptor
class SimpleRequestsWithEphemeralSessionConfigurationTests: NSURLSessionStubsTestCase {
override func setUp() {
config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
}
func testStubURLStringAndReceiveDefaultResponse() {
let expectation = expectationWithDescription("URLString")
Velociraptor.request(URLString)
let url = NSURL(string: URLString)!
let task = session.dataTaskWithURL(url) { (data, res, error) in
expectation.fulfill()
XCTAssertEqual(data.length, 0, "The length of data should equal to 0, got \(data.length)")
XCTAssertNotNil(res, "Default response should not be nil")
XCTAssertNil(error, "Should not receive an error")
let response = res as! NSHTTPURLResponse
XCTAssertEqual(response.statusCode, 200, "Default status code should equal to 200, got \(response.statusCode)")
}
task.resume()
self.waitForExpectationsWithTimeout(1) { error in
if let error = error {
XCTFail(error.localizedDescription)
}
}
}
func testStubNSURLAndReceiveDefaultResponse() {
let expectation = expectationWithDescription("NSURL")
Velociraptor.request(URL)
let task = session.dataTaskWithURL(URL) { (data, res, error) in
expectation.fulfill()
XCTAssertEqual(data.length, 0, "The length of data should equal to 0, got \(data.length)")
XCTAssertNotNil(res, "Default response should not be nil")
XCTAssertNil(error, "Should not receive an error")
let response = res as! NSHTTPURLResponse
XCTAssertEqual(response.statusCode, 200, "Default status code should equal to 200, got \(response.statusCode)")
}
task.resume()
self.waitForExpectationsWithTimeout(1) { error in
if let error = error {
XCTFail(error.localizedDescription)
}
}
}
func testStubNSURLRequestAndReceiveDefaultResponse() {
let expectation = expectationWithDescription("NSURLRequest")
Velociraptor.request(request)
let task = session.dataTaskWithRequest(request) { (data, res, error) in
expectation.fulfill()
XCTAssertEqual(data.length, 0, "The length of data should equal to 0, got \(data.length)")
XCTAssertNotNil(res, "Default response should not be nil")
XCTAssertNil(error, "Should not receive an error")
let response = res as! NSHTTPURLResponse
XCTAssertEqual(response.statusCode, 200, "Default status code should equal to 200, got \(response.statusCode)")
}
task.resume()
self.waitForExpectationsWithTimeout(1) { error in
if let error = error {
XCTFail(error.localizedDescription)
}
}
}
func testStubStubbedRequestObjectAndReceiveDefaultResponse() {
let expectation = expectationWithDescription("VLRStubbedRequest")
let stubbedRequest = VLRStubbedRequest(URL: URL)
Velociraptor.request(stubbedRequest)
let task = session.dataTaskWithRequest(request) { (data, res, error) in
expectation.fulfill()
XCTAssertEqual(data.length, 0, "The length of data should equal to 0, got \(data.length)")
XCTAssertNotNil(res, "Default response should not be nil")
XCTAssertNil(error, "Should not receive an error")
let response = res as! NSHTTPURLResponse
XCTAssertEqual(response.statusCode, 200, "Default status code should equal to 200, got \(response.statusCode)")
}
task.resume()
self.waitForExpectationsWithTimeout(1) { error in
if let error = error {
XCTFail(error.localizedDescription)
}
}
}
}
|
mit
|
cee4dbbb9076bf5e4f185f08205888af
| 31.139344 | 117 | 0.684184 | 4.786325 | false | true | false | false |
vector-im/vector-ios
|
RiotSwiftUI/Modules/Common/Util/MultilineTextField.swift
|
1
|
6498
|
//
// Copyright 2021 New Vector Ltd
//
// 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 SwiftUI
@available(iOS 14.0, *)
struct MultilineTextField: View {
@Environment(\.theme) private var theme: ThemeSwiftUI
@Binding private var text: String
@State private var dynamicHeight: CGFloat = 100
@State private var isEditing = false
private var placeholder: String = ""
private var showingPlaceholder: Bool {
text.isEmpty
}
init(_ placeholder: String, text: Binding<String>) {
self.placeholder = placeholder
self._text = text
}
private var textColor: Color {
if (theme.identifier == ThemeIdentifier.dark) {
return theme.colors.primaryContent
} else {
return theme.colors.primaryContent
}
}
private var backgroundColor: Color {
return theme.colors.background
}
private var placeholderColor: Color {
return theme.colors.tertiaryContent
}
private var borderColor: Color {
if isEditing {
return theme.colors.accent
}
return theme.colors.quarterlyContent
}
private var borderWidth: CGFloat {
return isEditing ? 2.0 : 1.5
}
var body: some View {
let rect = RoundedRectangle(cornerRadius: 8.0)
return UITextViewWrapper(text: $text, calculatedHeight: $dynamicHeight, isEditing: $isEditing)
.frame(minHeight: dynamicHeight, maxHeight: dynamicHeight)
.padding(4.0)
.background(placeholderView, alignment: .topLeading)
.animation(.none)
.background(backgroundColor)
.clipShape(rect)
.overlay(rect.stroke(borderColor, lineWidth: borderWidth))
.introspectTextView { textView in
textView.textColor = UIColor(textColor)
textView.font = theme.fonts.uiFonts.callout
}
}
@ViewBuilder
private var placeholderView: some View {
if showingPlaceholder {
Text(placeholder)
.foregroundColor(placeholderColor)
.font(theme.fonts.callout)
.padding(.leading, 8.0)
.padding(.top, 12.0)
}
}
}
@available(iOS 14.0, *)
fileprivate struct UITextViewWrapper: UIViewRepresentable {
typealias UIViewType = UITextView
@Binding var text: String
@Binding var calculatedHeight: CGFloat
@Binding var isEditing: Bool
func makeUIView(context: UIViewRepresentableContext<UITextViewWrapper>) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
textView.isEditable = true
textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.isScrollEnabled = false
textView.backgroundColor = UIColor.clear
textView.returnKeyType = .done
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return textView
}
func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<UITextViewWrapper>) {
if uiView.text != self.text {
uiView.text = self.text
}
UITextViewWrapper.recalculateHeight(view: uiView, result: $calculatedHeight)
}
fileprivate static func recalculateHeight(view: UIView, result: Binding<CGFloat>) {
let newSize = view.sizeThatFits(CGSize(width: view.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
if result.wrappedValue != newSize.height {
DispatchQueue.main.async {
result.wrappedValue = newSize.height // !! must be called asynchronously
}
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text, height: $calculatedHeight, isEditing: $isEditing)
}
final class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<String>
var calculatedHeight: Binding<CGFloat>
var isEditing: Binding<Bool>
init(text: Binding<String>, height: Binding<CGFloat>, isEditing: Binding<Bool>) {
self.text = text
self.calculatedHeight = height
self.isEditing = isEditing
}
func textViewDidChange(_ uiView: UITextView) {
text.wrappedValue = uiView.text
UITextViewWrapper.recalculateHeight(view: uiView, result: calculatedHeight)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
textView.resignFirstResponder()
return false
}
return true
}
func textViewDidBeginEditing(_ textView: UITextView) {
isEditing.wrappedValue = true
}
func textViewDidEndEditing(_ textView: UITextView) {
isEditing.wrappedValue = false
}
}
}
@available(iOS 14.0, *)
struct MultilineTextField_Previews: PreviewProvider {
static var previews: some View {
return Group {
VStack {
PreviewWrapper()
PlaceholderPreviewWrapper()
PreviewWrapper()
.theme(ThemeIdentifier.dark)
PlaceholderPreviewWrapper()
.theme(ThemeIdentifier.dark)
}
}
.padding()
}
struct PreviewWrapper: View {
@State(initialValue: "123") var text: String
var body: some View {
MultilineTextField("Placeholder", text: $text)
}
}
struct PlaceholderPreviewWrapper: View {
@State(initialValue: "") var text: String
var body: some View {
MultilineTextField("Placeholder", text: $text)
}
}
}
|
apache-2.0
|
c62549b33754a8038e3567cd8634180c
| 30.391304 | 120 | 0.620037 | 5.173567 | false | false | false | false |
tjw/swift
|
tools/SwiftSyntax/SwiftSyntax.swift
|
2
|
3302
|
//===--------------- SwiftLanguage.swift - Swift Syntax Library -----------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This file provides main entry point into the Syntax library.
//===----------------------------------------------------------------------===//
import Foundation
#if os(macOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
/// A list of possible errors that could be encountered while parsing a
/// Syntax tree.
public enum ParserError: Error {
case swiftcFailed(Int, String)
case invalidFile
}
extension Syntax {
fileprivate static func encodeSourceFileSyntaxInternal(_ url: URL) throws -> Data {
let swiftcRunner = try SwiftcRunner(sourceFile: url)
let result = try swiftcRunner.invoke()
guard result.wasSuccessful else {
throw ParserError.swiftcFailed(result.exitCode, result.stderr)
}
return result.stdoutData
}
/// Parses the Swift file at the provided URL into a `Syntax` tree in Json
/// serialization format.
/// - Parameter url: The URL you wish to parse.
/// - Returns: The syntax tree in Json format string.
public static func encodeSourceFileSyntax(_ url: URL) throws -> String {
return String(data: try encodeSourceFileSyntaxInternal(url), encoding: .utf8)!
}
/// Parses the Swift file at the provided URL into a full-fidelity `Syntax`
/// tree.
/// - Parameter url: The URL you wish to parse.
/// - Returns: A top-level Syntax node representing the contents of the tree,
/// if the parse was successful.
/// - Throws: `ParseError.couldNotFindSwiftc` if `swiftc` could not be
/// located, `ParseError.invalidFile` if the file is invalid.
/// FIXME: Fill this out with all error cases.
public static func parse(_ url: URL) throws -> SourceFileSyntax {
return try decodeSourceFileSyntax(encodeSourceFileSyntaxInternal(url))
}
/// Decode a serialized form of SourceFileSyntax to a syntax node.
/// - Parameter content: The data of the serialized SourceFileSyntax.
/// - Returns: A top-level Syntax node representing the contents of the tree,
/// if the parse was successful.
fileprivate static func decodeSourceFileSyntax(_ content: Data) throws -> SourceFileSyntax {
let decoder = JSONDecoder()
let raw = try decoder.decode(RawSyntax.self, from: content)
guard let file = makeSyntax(raw) as? SourceFileSyntax else {
throw ParserError.invalidFile
}
return file
}
/// Decode a serialized form of SourceFileSyntax to a syntax node.
/// - Parameter content: The string content of the serialized SourceFileSyntax.
/// - Returns: A top-level Syntax node representing the contents of the tree,
/// if the parse was successful.
public static func decodeSourceFileSyntax(_ content: String) throws -> SourceFileSyntax {
return try decodeSourceFileSyntax(content.data(using: .utf8)!)
}
}
|
apache-2.0
|
c78d047e06836d05f9277e4a2bd59767
| 40.275 | 94 | 0.673834 | 4.63764 | false | false | false | false |
SergeMaslyakov/audio-player
|
app/src/controllers/music/popover/MusicPickerAnimator.swift
|
1
|
2255
|
//
// MusicPickerAnimator.swift
// AudioPlayer
//
// Created by Serge Maslyakov on 07/07/2017.
// Copyright © 2017 Maslyakov. All rights reserved.
//
import UIKit
class MusicPickerAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var presenting: Bool = false
private var dimmingView: UIView? = nil
private let animationDuration = 0.25
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return animationDuration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView;
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
let concreteView = self.presenting ? toView : fromView
let screen = UIScreen.main.bounds
let originalFrame = CGRect(x: 0, y: 20, width: screen.size.width, height: 44.0)
let finalFrame = self.presenting ? concreteView!.frame : originalFrame
if presenting {
dimmingView = UIView(frame: screen)
dimmingView?.alpha = 0
dimmingView?.backgroundColor = UIColor.black
containerView.addSubview(dimmingView!)
containerView.bringSubview(toFront: dimmingView!)
concreteView?.center = CGPoint(x: originalFrame.midX, y: originalFrame.midY)
concreteView?.clipsToBounds = true;
}
containerView.addSubview(concreteView!)
containerView.bringSubview(toFront: concreteView!)
UIView.animate(withDuration: animationDuration, animations: {
self.dimmingView?.alpha = self.presenting ? 0.5 : 0.0
concreteView?.center = CGPoint(x: finalFrame.midX, y: finalFrame.midY)
}, completion: { finished in
if finished {
transitionContext.completeTransition(true)
}
})
}
public func animationEnded(_ transitionCompleted: Bool) {
if self.presenting == false && transitionCompleted {
dimmingView?.removeFromSuperview()
dimmingView = nil
}
}
}
|
apache-2.0
|
6cb70f51a2b0cbcb6843fef685617590
| 34.21875 | 116 | 0.675244 | 5.457627 | false | false | false | false |
wyp767363905/GiftSay
|
GiftSay/GiftSay/classes/giftSay/adDetail/view/DetailView.swift
|
1
|
4832
|
//
// DetailView.swift
// GiftSay
//
// Created by qianfeng on 16/8/28.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class DetailView: UIView {
var clickClosure: ADCellClosure?
private var tbView: UITableView?
weak var delegate: PostWebCellDelegate?
var type: String?
var h: CGFloat = 0
var postModel: ADPostModel?{
didSet {
tbView?.reloadData()
}
}
var collectionModel: ADCollectionModel?{
didSet {
tbView?.reloadData()
}
}
var postLikeModel: ADPostLikeModel?{
didSet {
tbView?.reloadData()
}
}
init() {
super.init(frame: CGRectZero)
tbView = UITableView(frame: CGRectZero, style: .Plain)
tbView?.delegate = self
tbView?.dataSource = self
//分界线
tbView?.separatorStyle = .None
addSubview(tbView!)
tbView?.snp_makeConstraints(closure: {
[weak self]
(make) in
make.edges.equalTo(self!)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DetailView : UITableViewDelegate,UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowNum = 0
if type == "post" {
if postModel?.data != nil {
rowNum = 3
}
}else if type == "collection" {
if collectionModel?.data?.posts?.count > 0 {
rowNum += (collectionModel?.data?.posts?.count)!
}
}
return rowNum
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if type == "post" {
if postModel?.data != nil {
if indexPath.row == 0 {
let dataModel = postModel?.data
cell = PostCell.createPostCellFor(tableView, atIndexPath: indexPath, withDataModel: dataModel!)
}else if indexPath.row == 1 {
let dataModel = postModel?.data
cell = PostWebCell.createPostWebCellFor(tableView, atIndexPath: indexPath, withDataModel: dataModel!, delegate: delegate)
}else if indexPath.row == 2 {
let dataModel = postLikeModel?.data
cell = PostScrollViewCell.createPostScrollViewCellFor(tableView, atIndexPath: indexPath, withDataModel: dataModel!)
}
}
}else if type == "collection" {
if collectionModel?.data?.posts?.count > 0 {
let dataModel = collectionModel?.data
cell = CollectionCell.createCollectionCellFor(tableView, atIndexPath: indexPath, withDataModel: dataModel!, clickClosure: clickClosure)
}
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height: CGFloat = 0
if type == "post" {
if postModel?.data != nil {
if indexPath.row == 0 {
height = 140
}else if indexPath.row == 1 {
self.delegate = self
height = h+40
}else if indexPath.row == 2 {
height = 170
}
}
}else if type == "collection" {
if collectionModel?.data?.posts?.count > 0 {
height = 230
}
}
return height
}
}
extension DetailView : PostWebCellDelegate {
func heightForRow(height: CGFloat){
h = height
tbView?.reloadData()
}
}
|
mit
|
47bc0865ce411c4b8b8522f9239cc16a
| 21.85782 | 151 | 0.433962 | 6.37963 | false | false | false | false |
PANDA-Guide/PandaGuideApp
|
PandaGuide/HelpRequestCreationViewController.swift
|
1
|
19199
|
//
// HelpRequestCreationViewController.swift
// panda-guide
//
// Created by Arnaud Lenglet on 21/04/2017.
// Copyright © 2017 ESTHESIX. All rights reserved.
//
import UIKit
import Speech
import os.log
import Cartography
import PKHUD
protocol HelpRequestCreationViewControllerDelegate: class {
func didCreate(helpRequest: HelpRequest)
}
class HelpRequestCreationViewController: UIViewController {
// MARK: - Properties
var scrollView: UIScrollView!
var containerView: UIView!
var closeButton: UIButton!
var textView: UITextView!
var placeholderLabel: UILabel!
var imageView: UIImageView!
var microButton: MicrophoneButton!
var saveButton: UIButton!
private var speechRecognizer: SFSpeechRecognizer?
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private var recognitionTask: SFSpeechRecognitionTask?
private let audioEngine = AVAudioEngine()
var photoTaken: UIImage?
var helpRequest: HelpRequest?
// NB: import to store a delegate as `weak` to avoid dependency cycles
weak var delegate: HelpRequestCreationViewControllerDelegate?
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Demande", comment: "Nav Bar Title")
setupViewHierachy()
// ready for auto layout
view.setNeedsUpdateConstraints()
// add a gesture to exit the text view
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTapGesture))
view.addGestureRecognizer(tapGesture)
// configure speach recognozition
setupSpeechRecognizer()
}
private func setupViewHierachy() {
scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.contentSize = view.bounds.size
view.addSubview(scrollView)
containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.backgroundColor = UIColor.white
scrollView.addSubview(containerView)
imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.image = photoTaken
containerView.addSubview(imageView)
textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.textContainerInset = .zero
textView.backgroundColor = UIColor.white
textView.font = UIFont.brandFont(weight: .Regular, forSize: 1.2 * UIFont.systemFontSize)
textView.delegate = self
containerView.addSubview(textView)
placeholderLabel = UILabel()
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
placeholderLabel.isUserInteractionEnabled = false
placeholderLabel.numberOfLines = 0
placeholderLabel.font = textView.font
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.text = NSLocalizedString("Quelle est votre demande ? \nQue souhaitez-vous savoir ?", comment: "")
containerView.addSubview(placeholderLabel)
microButton = MicrophoneButton()
microButton.accessibilityTraits = UIAccessibilityTraitStartsMediaSession
microButton.accessibilityLabel = NSLocalizedString("Micro", comment: "")
microButton.accessibilityHint = NSLocalizedString("Appuyez deux fois pour activer la dictée", comment: "")
microButton.translatesAutoresizingMaskIntoConstraints = false
microButton.addTarget(self, action: #selector(self.handleMicroButtonTapped), for: .touchUpInside)
containerView.addSubview(microButton)
// TODO remove or reactivate the speech recognition
microButton.isHidden = true
saveButton = UIButton()
saveButton.translatesAutoresizingMaskIntoConstraints = false
saveButton.isEnabled = false
saveButton.alpha = 0.5
saveButton.setTitle(NSLocalizedString("Envoyer la demande", comment: ""), for: .normal)
saveButton.backgroundColor = UIColor.brandBlue
saveButton.setTitleColor(UIColor.white, for: .normal)
saveButton.titleLabel?.font = UIFont.brandFont(weight: .Bold, forSize: UIFont.buttonFontSize)
saveButton.addTarget(self, action: #selector(self.saveButtonTapped), for: .touchUpInside)
containerView.addSubview(saveButton)
closeButton = UIButton()
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.backgroundColor = UIColor.white
closeButton.layer.masksToBounds = true
let closeButtonRect = CGRect(x: 0, y: 0, width: 30, height: 30)
closeButton.setImage(UIImage.imageWithBezier(UIBezierPath.backArrow(closeButtonRect), color: UIColor.black, inRect: closeButtonRect), for: .normal)
closeButton.imageView?.contentMode = .scaleAspectFit
closeButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
closeButton.addTarget(self, action: #selector(self.cancelTapped(_:)), for: .touchUpInside)
view.addSubview(closeButton)
}
private func setupSpeechRecognizer() {
let userLocale = Locale.autoupdatingCurrent
speechRecognizer = SFSpeechRecognizer(locale: userLocale)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = containerView.bounds.size
closeButton.layer.cornerRadius = min(closeButton.bounds.height, closeButton.bounds.width) / 2
}
private var didSetupViewConstraints: Bool = false
override func updateViewConstraints() {
if !didSetupViewConstraints {
didSetupViewConstraints = true
setupViewConstraints()
}
super.updateViewConstraints()
}
private func setupViewConstraints() {
constrain(scrollView, containerView) { scroll, container in
scroll.edges == scroll.superview!.edges
container.top == container.superview!.top
container.left == container.superview!.left
container.width == scroll.width
container.height == scroll.height
}
constrain(imageView, textView, placeholderLabel, microButton, saveButton) { image, text, placeholder, micro, save in
image.top == image.superview!.top
image.left == image.superview!.left
image.right == image.superview!.right
image.width == image.superview!.width
image.bottom == image.superview!.centerY
micro.center == image.center
micro.width == 100
micro.height == 100
text.top == image.bottom + 20
text.left == text.superview!.left + 30
text.right == text.superview!.right - 30
text.bottom == text.superview!.bottom
placeholder.top == text.top
placeholder.left == text.left + 5 // 5pts more for pixel perfection
placeholder.right == text.right - 5 // 5pts less for pixel perfection
save.left == save.superview!.left
save.right == save.superview!.right
save.bottom == save.superview!.bottom
save.width == save.superview!.width
save.height == 70
}
constrain(closeButton) { close in
close.top == close.superview!.top + 30 // 20 for the status bar, 10 for padding
close.left == close.superview!.left + 10
close.width == 50
close.height == 50
}
}
// MARK: - Actions
@objc fileprivate func cancelTapped(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
@objc fileprivate func saveButtonTapped() {
// stop ongoing tasks, and resign responder (to hide the keyboard if necessary)
stopCurrentSpeechRecognition()
textView.resignFirstResponder()
guard let question = textView.text else {
os_log("🔴 We need a question description, should not happen", type: .error)
HUD.flash(.labeledError(title: "Incomplète", subtitle: "Veuillez décrire votre demande"))
return
}
guard let picture = imageView.image else {
os_log("🔴 We need an image, should not happen", type: .error)
HUD.flash(.labeledError(title: "Incomplète", subtitle: "Veuillez ajouter une photo"))
return
}
HUD.show(.labeledProgress(title: "Uploading", subtitle: "Demande en cours..."))
HelpRequestService(callerViewController: self).create(
question: question,
picture: picture,
success: { helpRequest in
os_log("HelpRequestViewController: updating view following success", log: .default, type: .debug)
HUD.hide(animated: true)
self.delegate?.didCreate(helpRequest: helpRequest)
},
failure: { error in
os_log("HelpRequestViewController: updating view following failure", log: .default, type: .error)
NSLog("Failed to upload request with error: \(error)")
HUD.flash(.labeledError(title: "Failed", subtitle: error.localizedDescription))
}
)
}
@objc fileprivate func handleTapGesture(gesture: UITapGestureRecognizer) {
if gesture.state == .ended {
let loc = gesture.location(in: view)
let relativeLoc = textView.convert(loc, from: view)
if !textView.frame.contains(relativeLoc) {
// exist the text view if the tap gesture is outside of it
textView.resignFirstResponder()
}
}
}
@objc fileprivate func handleMicroButtonTapped() {
guard let speechRecognizer = speechRecognizer else {
HUD.flash(.labeledSuccess(title: NSLocalizedString("Not available", comment: ""), subtitle: NSLocalizedString("Speech recognition is not yet available for your language", comment: "")),
delay: 3.0)
return
}
guard speechRecognizer.isAvailable else {
HUD.flash(.labeledSuccess(title: NSLocalizedString("Offline", comment: ""), subtitle: NSLocalizedString("Speech recognition needs internet connection", comment: "")),
delay: 3.0)
return
}
speechRecognizer.delegate = self
// check autorization
let status = SFSpeechRecognizer.authorizationStatus()
switch status {
case .denied:
HUD.flash(.labeledSuccess(title: NSLocalizedString("Denied", comment: ""), subtitle: NSLocalizedString("Please, authorize speech recognition in your General Settings", comment: "")),
delay: 3.0)
return
case .restricted:
HUD.flash(.labeledSuccess(title: NSLocalizedString("Restricted", comment: ""), subtitle: NSLocalizedString("Sorry, you are restricted", comment: "")),
delay: 3.0)
return
case .notDetermined:
SFSpeechRecognizer.requestAuthorization { authStatus in
switch authStatus {
case .authorized:
DispatchQueue.main.async {
// back to the main thread
self.toggleSpeechRecognition()
}
case .denied, .restricted, .notDetermined:
NSLog("Not authorized :( to access speech reco")
}
}
case .authorized:
toggleSpeechRecognition()
}
}
fileprivate func toggleSpeechRecognition() {
if audioEngine.isRunning {
microButton.recordingState = .waiting
stopCurrentSpeechRecognition()
} else {
microButton.recordingState = .connecting
performSpeechRecognition()
}
}
fileprivate func stopCurrentSpeechRecognition() {
if recognitionRequest != nil {
recognitionRequest?.endAudio()
}
if recognitionTask != nil {
recognitionTask?.cancel()
}
if audioEngine.isRunning {
audioEngine.stop()
}
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(false, with: .notifyOthersOnDeactivation)
} catch {
print("audioSession can't be set to active = false")
}
// announce it's ready on Voice Over
microButton.accessibilityLabel = NSLocalizedString("Dictée terminée", comment: "")
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
// reset label to micro
self.microButton.accessibilityLabel = NSLocalizedString("Micro", comment: "")
}
}
fileprivate func performSpeechRecognition() {
guard let speechRecognizer = speechRecognizer else {
print("No available speech recognizer, should not happen")
return
}
if let task = recognitionTask {
task.cancel()
recognitionTask = nil
}
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
// announce it's ready on Voice Over
microButton.accessibilityLabel = NSLocalizedString("Allez-y", comment: "")
// start audio session to stop any other sounds
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
} catch {
print("audioSession properties weren't set because of an error.")
HUD.flash(.labeledError(title: "Failed audio", subtitle: "Error during audio acquisition, please retry"))
return
}
guard let inputNode = audioEngine.inputNode else {
HUD.flash(.labeledError(title: "Failed audio", subtitle: "Error during audio access, please retry"))
return
}
guard let recognitionRequest = recognitionRequest else {
HUD.flash(.labeledError(title: "Failed audio", subtitle: "Error during audio setup, please retry"))
return
}
// we accept only partial results
recognitionRequest.shouldReportPartialResults = true
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
var isFinal = false
if let result = result {
self.textView.text = result.bestTranscription.formattedString
self.textViewHasBeenUpdated()
isFinal = result.isFinal
}
if error != nil || isFinal {
self.audioEngine.stop()
inputNode.removeTap(onBus: 0)
self.recognitionRequest = nil
self.recognitionTask = nil
}
})
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
self.recognitionRequest?.append(buffer)
}
audioEngine.prepare()
do {
try audioEngine.start()
} catch {
print("audioEngine couldn't start because of an error.")
}
// connection completed, show it in UI
microButton.recordingState = .recording
placeholderLabel.text = NSLocalizedString("Say something, I'm listening!", comment: "Placeholder during speech recognition start")
}
// MARK: - Keyboard
func keyboardWillShow(notification: NSNotification) {
scrollView.isScrollEnabled = true
if let userInfo = notification.userInfo, let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: endFrame.height, right: 0)
scrollView.scrollIndicatorInsets = scrollView.contentInset
UIView.animate(withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: {
self.scrollView.contentOffset = CGPoint(x: 0, y: endFrame.height)
}, completion: nil)
// ensure the text view is entirely visible
let availableHeight = scrollView.bounds.height - endFrame.height
if availableHeight < textView.bounds.height {
// TODO adjust the top constraint for the text view
}
}
}
func keyboardWillHide(notification: NSNotification) {
scrollView.contentInset = .zero
scrollView.scrollIndicatorInsets = .zero
//scrollView.setContentOffset(.zero, animated: true)
scrollView.isScrollEnabled = false
}
// MARK: - Private methods
fileprivate func textViewHasBeenUpdated() {
if textView.text.isEmpty {
placeholderLabel.alpha = 1.0
saveButton.isEnabled = false
saveButton.alpha = 0.5
} else {
placeholderLabel.alpha = 0.0
saveButton.isEnabled = true
saveButton.alpha = 1.0
}
}
}
extension HelpRequestCreationViewController: ApiVCProtocol {
func updateViewOnSuccess() {
}
func updateViewOnFailure(error: FormattedError) {
}
}
extension HelpRequestCreationViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
textViewHasBeenUpdated()
}
func textViewDidEndEditing(_ textView: UITextView) {
}
func textViewDidBeginEditing(_ textView: UITextView) {
stopCurrentSpeechRecognition()
microButton.recordingState = .waiting
}
}
extension HelpRequestCreationViewController: SFSpeechRecognizerDelegate {
}
|
gpl-3.0
|
8e72a1e211e4e4247b8b4fbaf5b3d858
| 36.472656 | 197 | 0.647399 | 5.527514 | false | false | false | false |
jegumhon/URWeatherView
|
URWeatherView/SpriteAssets/URBurningCometEmitterNode.swift
|
1
|
1960
|
//
// URBurningCometEmitterNode.swift
// URWeatherView
//
// Created by DongSoo Lee on 2017. 6. 15..
// Copyright © 2017년 zigbang. All rights reserved.
//
import SpriteKit
open class URBurningCometEmitterNode: SKEmitterNode {
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init() {
super.init()
let bundle = Bundle(for: URBurningCometEmitterNode.self)
let particleImage = UIImage(named: "spark", in: bundle, compatibleWith: nil)!
self.particleTexture = SKTexture(image: particleImage)
self.particleBirthRate = 300.0
// self.particleBirthRateMax?
self.particleLifetime = 1.5
self.particleLifetimeRange = 0.0
self.particlePositionRange = CGVector(dx: 5.0, dy: 5.0)
self.zPosition = 0.0
self.emissionAngle = CGFloat(150.0 * .pi / 180.0)
self.emissionAngleRange = CGFloat(20.054 * .pi / 180.0)
self.particleSpeed = 100.0
self.particleSpeedRange = 50.0
self.xAcceleration = 0.0
self.yAcceleration = 100.0
self.particleAlpha = 1.0
self.particleAlphaRange = 0.2
self.particleAlphaSpeed = -0.45
self.particleScale = 0.5
self.particleScaleRange = 0.4
self.particleScaleSpeed = -0.5
self.particleRotation = 0.0
self.particleRotationRange = 0.0
self.particleRotationSpeed = 0.0
self.particleColorBlendFactor = 1.0
self.particleColorBlendFactorRange = 0.0
self.particleColorBlendFactorSpeed = 0.0
self.particleColorSequence = SKKeyframeSequence(keyframeValues: [UIColor(red: 78.0/255.0, green: 33.0/255.0, blue: 6.0/255.0, alpha: 1.0), UIColor(red: 249.0/255.0, green: 108.0/255.0, blue: 21.0/255.0, alpha: 1.0), UIColor(red: 249.0/255.0, green: 108.0/255.0, blue: 21.0/255.0, alpha: 1.0)], times: [0.0, 0.35, 1.0])
self.particleBlendMode = .add
}
}
|
mit
|
d16b7f2106d2a057cfd5bb25985d5944
| 38.938776 | 326 | 0.649463 | 3.488414 | false | false | false | false |
hyperoslo/Catalog
|
Demos/CampaignReady/CampaignReady/ViewController.swift
|
1
|
655
|
import UIKit
import Wall
import Catalog
class ViewController: CatalogController {
let generator = ContentGenerator()
override func viewDidLoad() {
super.viewDidLoad()
title = "Campaign Ready"
config.wall.thumbnailForAttachment = {
(attachment: Attachment, size: CGSize) -> URLStringConvertible? in
return String(format: attachment.thumbnail!.string,
Int(size.width), Int(size.height))
}
config.wall.post.title.textAttributes[NSFontAttributeName] = UIFont.boldSystemFontOfSize(18)
catalogConfig.catalog.contentSection.statusIcon.rounded = true
listing = generator.listing()
reloadPosts()
}
}
|
mit
|
047d5ab80d9798d1fa03c2e2c27fb1eb
| 25.2 | 96 | 0.726718 | 4.612676 | false | true | false | false |
zxpLearnios/MyProject
|
test_projectDemo1/GuideVC/QrCode/MyQrCodeScanVC.swift
|
1
|
7334
|
//
// MyQrCodeScanVC.swift
// test_projectDemo1
//
// Created by Jingnan Zhang on 16/6/29.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
// 二维码扫描ViewController
// 1. UIAlertController, 2. 从图片中读取二维码, 3. 判断是否可以获取硬件信息等是为了防止在模拟器上出错
// 4. 从相册的图片中读取二维码 >=8.2模拟器就可以了
import UIKit
import AVFoundation
import Photos
import AssetsLibrary
// 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
}
}
class MyQrCodeScanVC: UIViewController, MyQrCodeScanViewDelegate, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
@IBOutlet weak var scanQrCodeView: MyQrCodeScanView!
var alert:UIAlertController!
convenience init(){
self.init(nibName:"MyQrCodeScanVC", bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
scanQrCodeView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func beginScanAction(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
scanQrCodeView.start()
}else{
scanQrCodeView.stop()
}
}
// MARK: 相册
@IBAction func albumAction(_ sender: UIButton) {
if !isGetPhotoAccess() {
print("没有相册权限,请到设置->隐私中开启本程序相册权限")
}else{ // 进入相册
let picker = UIImagePickerController() //MyImagePickerController.getSelf(nil) // UIImagePickerController
picker.delegate = self
//指定图片控制器类型
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
// let vc = MyAlbumViewController()
// let nav = MyCustomNav.init(rootViewController: vc)
// nav.pushViewController(picker, animated: false)
// self.presentViewController(nav, animated: true, completion: nil)
}
}
// MARK: 开灯
@IBAction func openLightAction(_ sender: UIButton) {
if !isGetCameraAccess() {
print("没有相机权限,请到设置->隐私中开启本程序相机权限")
}else{
sender.isSelected = !sender.isSelected
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
if device == nil {
print("可能是模拟器,故无法获取硬件信息!")
return
}
if (device?.hasTorch)! {
try! device?.lockForConfiguration()
if (sender.isSelected) {
device?.torchMode = .on
}else {
device?.torchMode = .off
}
device?.unlockForConfiguration()
}
}
}
//MARK: ---相机权限
fileprivate func isGetCameraAccess()-> Bool{
let authStaus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if authStaus != AVAuthorizationStatus.denied{
return true
}else{
return false
}
}
//MARK: ----获取相册权限
fileprivate func isGetPhotoAccess()->Bool{
var result = false
if Float(UIDevice.current.systemVersion) < 8.0{
if( ALAssetsLibrary.authorizationStatus() != ALAuthorizationStatus.denied ){
result = true
}
}else{
if ( PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.denied ){
result = true
}
}
return result
}
// MARK: ----- private ------
// 展示扫描结果
fileprivate func showScanResultInViewController(_ result:String, InViewController:UIViewController){
if result.hasPrefix("http") {
// 1. alert
alert = UIAlertController.init(title: "", message: "此为一个链接,确定打开吗", preferredStyle: .alert)
let confirm = UIAlertAction.init(title: "确定", style: .destructive, handler: { (action) in
let url = URL.init(string: result)
if url != nil {
UIApplication.shared.openURL(url!)
}
})
let cancle = UIAlertAction.init(title: "取消", style: .cancel, handler: { (action) in
})
alert.addAction(confirm)
alert.addAction(cancle)
InViewController.present(alert, animated: true, completion: nil)
}else{
if result == "" {
alert = UIAlertController.init(title: "", message: "没有读取到二维码!", preferredStyle: .alert)
let confirm = UIAlertAction.init(title: "确定", style: .cancel, handler: nil)
alert.addAction(confirm)
InViewController.present(alert, animated: true, completion: nil)
}
}
}
// MARK: -- MyQrCodeScanViewDelegate
func finishScanQrCodeWithOutPutString(_ result: String) {
print("获取到的二维码内容是---->\(result)")
showScanResultInViewController(result, InViewController: self)
}
// MARK: ------ UIImagePickerControllerDelegate -----
// 使用真机调试没问题, 模拟器选iphone5s及以上设备也是可以检测到的。
// MARK: 从UIImagePickerController选择完图片后就调用(拍照完毕或者选择相册图片完毕)
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//获取选择的原图
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
// 从所选中的图片中读取二维码
let ciImage = CIImage(image:image)!
// 探测器
let context = CIContext.init(options: nil)
let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])
let features = detector?.features(in: ciImage)
//遍历所有的二维码 && 取出探测到的数据
for feature in features! {
let qrCodeFeature = feature as! CIQRCodeFeature
debugPrint(qrCodeFeature.messageString)
}
// let resultVC = MyQrCodeScanResultVC()
// resultVC.image = image
// picker.presentViewController(resultVC, animated: true, completion: nil)
}
}
|
mit
|
999e00d1b34a29e278c8250dad55c7c5
| 30.474419 | 135 | 0.573371 | 4.861351 | false | false | false | false |
pjk1129/SONetwork
|
Demo/SwiftOne/Classes/BaseController/SOBaseViewController.swift
|
1
|
4388
|
//
// SOBaseViewController.swift
// SwiftOne
//
// Created by JK.PENG on 2017/3/20.
// Copyright © 2017年 XXXXX. All rights reserved.
//
import UIKit
class SOBaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
self.extendedLayoutIncludesOpaqueBars = false
self.automaticallyAdjustsScrollViewInsets = false
navigationController?.interactivePopGestureRecognizer?.isEnabled = true
navigationController?.interactivePopGestureRecognizer?.delegate = self
if(self.navigationController?.isNavigationBarHidden)!{
self.view.addSubview(navBarView)
navBarView.addSubview(navTitleLabel)
}
self.view.addSubview(containerView)
setUIConstraints()
}
func navLeftBtnDidClicked() {
self.navigationController!.popViewController(animated: true)
}
private func setUIConstraints(){
// align _collectionView from the left and right
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[containerView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["containerView" : containerView]))
// align _collectionView from the top and bottom
var format = "V:|-0-[containerView]-0-|"
if(self.navigationController?.isNavigationBarHidden)!{
format = "V:|-64-[containerView]-0-|"
}
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["containerView" : containerView]))
}
//MARK:- setter方法 赋值操作
var navTitle:NSString? {
//替代OC中重写setter方法,didSet没有代码提示
didSet {
if (self.navigationController?.isNavigationBarHidden)! {
navTitleLabel.text = navTitle as String?
}else{
self.navigationItem.title = navTitle as String?
}
}
}
var backBtnShown: Bool? {
didSet {
if backBtnShown! {
backButton.addTarget(self, action: #selector(navLeftBtnDidClicked), for: UIControlEvents.touchUpInside)
if (self.navigationController?.isNavigationBarHidden)! {
navBarView.addSubview(backButton)
backButton.frame = CGRect(x: 5, y: 27.5, width: 49, height: 29)
} else {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}
}
}
}
//MARK:- 懒加载属性
lazy var backButton:UIButton = {
let button = UIButton(type: .custom)
button.isExclusiveTouch = true
button.frame = CGRect(x: 0, y: 0, width: 49, height: 29)
button.setImage(UIImage(named: "back"), for: .normal)
button.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10)
return button
}()
lazy var containerView:UIView = {
let v = UIView()
v.backgroundColor = UIColor.clear
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
fileprivate lazy var navBarView:UIImageView = {
let imgView = UIImageView()
imgView.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 64)
imgView.isUserInteractionEnabled = true
imgView.backgroundColor = UIColor.so_withHex(hexString: "ff4800")
return imgView
}()
private lazy var navTitleLabel:UILabel = {
let label = UILabel()
label.frame = CGRect(x: 60, y: 27, width: kScreenW-120, height: 30)
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.center
label.textColor = UIColor.white
label.font = UIFont.systemFont(ofSize: 18)
return label
}()
}
extension SOBaseViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if (navigationController!.viewControllers.count) >= 2 {
return true
}
return false
}
}
|
mit
|
d05183376311cfe22fd89cc52b22982b
| 35.428571 | 212 | 0.631142 | 5.154578 | false | false | false | false |
MLSDev/TRON
|
Source/Tests/CodableTestCase.swift
|
1
|
1797
|
//
// CodableTestCase.swift
// TRON
//
// Created by Denys Telezhkin on 30.06.17.
// Copyright © 2017 Denys Telezhkin. All rights reserved.
//
import TRON
import Foundation
import XCTest
private struct CodableResponse: Codable {
let title: String
}
class CodableTestCase: ProtocolStubbedTestCase {
func testCodableParsing() {
let request: APIRequest<CodableResponse, APIError> = tron.codable.request("test").stubSuccess(["title": "Foo"].asData)
let expectation = self.expectation(description: "Parsing headers response")
request.perform(withSuccess: { response in
XCTAssertEqual(response.title, "Foo")
expectation.fulfill()
}, failure: { error in
print(error)
})
waitForExpectations(timeout: 1, handler: nil)
}
func testCodableErrorParsing() {
let request: APIRequest<Int, APIError> = tron.codable.request("status/418").stubStatusCode(418)
let expectation = self.expectation(description: "Teapot")
request.perform(withSuccess: { _ in
XCTFail("Failure expected but success was received")
}) { error in
XCTAssertEqual(error.response?.statusCode, 418)
expectation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testEmptyResponseStillCallsSuccessBlock() {
let request: APIRequest<Empty, APIError> = tron.codable.request("headers").stubSuccess(.init())
let expectation = self.expectation(description: "Empty response")
request.perform(withSuccess: { _ in
expectation.fulfill()
}, failure: { error in
XCTFail("unexpected network error: \(error)")
})
waitForExpectations(timeout: 1, handler: nil)
}
}
|
mit
|
9d2c83c812a832ee02ea22ae23320f6d
| 31.654545 | 126 | 0.64922 | 4.65285 | false | true | false | false |
vhesener/Closures
|
Xcode/Closures/Source/KVO.swift
|
2
|
4317
|
/**
The MIT License (MIT)
Copyright (c) 2017 Vincent Hesener
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
extension NSObject {
public var selfDeinits: (_KeyValueCodingAndObserving) -> Bool {
return { [weak self] _ in
return self == nil
}
}
}
extension _KeyValueCodingAndObserving {
/**
This convenience method puts only a tiny bit of polish on
Swift's latest closure-based KVO implementation. Although
there aren't many obvious differences between this
method and the one in `Foundation`, there are a few helpers, which
are describe below.
First, it passes a remove condition, `until`, which is simpy a closure
that gets called to determine whether to remove the observation
closure. Returning true will remove the observer, otherwise, the
observing will continue. `Foundation`'s method
automatically removes observation when the `NSKeyValueObservation`
is released, but this requires you to save it somewhere in your
view controller as a property, thereby cluttering up your view
controller with plumbing-only members.
Second, this method attempts to slightly improve the clutter. You
do not have to save the observer. `@discardableResult` allows you
to disregard the returned object entirely.
Finally, a typical pattern is to remove observers when deinit is
called on the object that owns the observed object.
For instance, if you are observing a model object property on your
view controller, you will probably want to stop observing when the
view controller gets released from memory. Because this is a
common pattern, there's a convenient var available on all subclasses
of NSObject named `selfDeinits`. Simply pass this as a parameter
into the `until` paramaeter, and the observation will be removed
when `self` is deallocated.
* * * *
#### An example of calling this method:
```swift
<#someObject#>.observe(\.<#some.key.path#>, until: selfDeinits) { obj,change in
<#do something#>
}
```
* parameter keyPath: The keyPath you wish to observe on this object
* parameter options: The observing options
* parameter until: The closure called when this handler should stop
observing. Return true if you want to forcefully stop observing.
* parameter changeHandler: The callback that will be called when
the keyPath change has occurred.
* returns: The observer object needed to remove observation
*/
@discardableResult
public func observe<Value>(
_ keyPath: KeyPath<Self, Value>,
options: NSKeyValueObservingOptions = [],
until removeCondition: @escaping (Self) -> Bool,
changeHandler: @escaping (Self, NSKeyValueObservedChange<Value>) -> Void)
-> NSKeyValueObservation {
var observer: NSKeyValueObservation?
observer = self.observe(keyPath, options: options) { obj, change in
guard !removeCondition(obj) else {
observer?.invalidate()
observer = nil
return
}
changeHandler(obj, change)
}
return observer!
}
}
|
mit
|
f1f8bcbe72a4072edc03870503283505
| 43.505155 | 98 | 0.697475 | 5.139286 | false | false | false | false |
scodx/LionsAndTigers
|
Lions and Tigers/ViewController.swift
|
1
|
2763
|
//
// ViewController.swift
// Lions and Tigers
//
// Created by Oscar on 17/10/14.
// Copyright (c) 2014 uinik. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var breedLabel: UILabel!
/**
* Array de tigers, nótese que se pone como propiedad a la clase
*/
var tigres:[Tiger] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var tiger = Tiger()
tiger.age = 3
tiger.name = "tigrito!"
tiger.breed = "bengal"
tiger.image = UIImage(named: "BengalTiger.jpg")
imageView.image = tiger.image
nameLabel.text = tiger.name
ageLabel.text = "\(tiger.age)"
breedLabel.text = tiger.breed
var tiger2 = Tiger()
tiger2.age = 3
tiger2.name = "tegro!"
tiger2.breed = "indochainis"
tiger2.image = UIImage(named: "IndochineseTiger.jpg")
var tiger3 = Tiger()
tiger3.age = 3
tiger3.name = "tugro!"
tiger3.breed = "malayan"
tiger3.image = UIImage(named: "MalayanTiger.jpg")
var tiger4 = Tiger()
tiger4.age = 3
tiger4.name = "tagro!"
tiger4.breed = "siberian"
tiger4.image = UIImage(named: "SiberianTiger.jpg")
tigres.append(tiger)
tigres += [tiger2, tiger3, tiger4]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func nextButtonPressed(sender: UIBarButtonItem) {
var randomNumber = Int(arc4random_uniform(UInt32(tigres.count)))
var tiger = tigres[randomNumber]
//
// imageView.image = tiger.image
// nameLabel.text = tiger.name
// ageLabel.text = "\(tiger.age)"
// breedLabel.text = tiger.breed
UIView.transitionWithView(self.view, duration: 2, options: UIViewAnimationOptions.TransitionCurlDown,
animations: {
self.imageView.image = tiger.image
self.nameLabel.text = tiger.name
self.ageLabel.text = "\(tiger.age)"
self.breedLabel.text = tiger.breed
}, completion: {
(finished: Bool) -> () in
}
)
}
}
|
mit
|
8e37d7e79ef064491ceca87e4cc07a96
| 21.455285 | 109 | 0.538378 | 3.991329 | false | false | false | false |
Shivol/Swift-CS333
|
playgrounds/uiKit/uiKitCatalog/UIKitCatalog/ButtonViewController.swift
|
3
|
4113
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to use UIButton. The buttons are created using storyboards, but each of the system buttons can be created in code by using the UIButton.buttonWithType() initializer. See the UIButton interface for a comprehensive list of the various UIButtonType values.
*/
import UIKit
class ButtonViewController: UITableViewController {
// MARK: - Properties
@IBOutlet weak var systemTextButton: UIButton!
@IBOutlet weak var systemContactAddButton: UIButton!
@IBOutlet weak var systemDetailDisclosureButton: UIButton!
@IBOutlet weak var imageButton: UIButton!
@IBOutlet weak var attributedTextButton: UIButton!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// All of the buttons are created in the storyboard, but configured below.
configureSystemTextButton()
configureSystemContactAddButton()
configureSystemDetailDisclosureButton()
configureImageButton()
configureAttributedTextSystemButton()
}
// MARK: - Configuration
func configureSystemTextButton() {
let buttonTitle = NSLocalizedString("Button", comment: "")
systemTextButton.setTitle(buttonTitle, for: UIControlState())
systemTextButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
func configureSystemContactAddButton() {
systemContactAddButton.backgroundColor = UIColor.clear
systemContactAddButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
func configureSystemDetailDisclosureButton() {
systemDetailDisclosureButton.backgroundColor = UIColor.clear
systemDetailDisclosureButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
func configureImageButton() {
// To create this button in code you can use UIButton.buttonWithType() with a parameter value of .Custom.
// Remove the title text.
imageButton.setTitle("", for: UIControlState())
imageButton.tintColor = UIColor.applicationPurpleColor
let imageButtonNormalImage = UIImage(named: "x_icon")
imageButton.setImage(imageButtonNormalImage, for: UIControlState())
// Add an accessibility label to the image.
imageButton.accessibilityLabel = NSLocalizedString("X Button", comment: "")
imageButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
func configureAttributedTextSystemButton() {
let buttonTitle = NSLocalizedString("Button", comment: "")
// Set the button's title for normal state.
let normalTitleAttributes = [
NSForegroundColorAttributeName: UIColor.applicationBlueColor,
NSStrikethroughStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue
] as [String : Any]
let normalAttributedTitle = NSAttributedString(string: buttonTitle, attributes: normalTitleAttributes)
attributedTextButton.setAttributedTitle(normalAttributedTitle, for: UIControlState())
// Set the button's title for highlighted state.
let highlightedTitleAttributes = [
NSForegroundColorAttributeName: UIColor.green,
NSStrikethroughStyleAttributeName: NSUnderlineStyle.styleThick.rawValue
] as [String : Any]
let highlightedAttributedTitle = NSAttributedString(string: buttonTitle, attributes: highlightedTitleAttributes)
attributedTextButton.setAttributedTitle(highlightedAttributedTitle, for: .highlighted)
attributedTextButton.addTarget(self, action: #selector(ButtonViewController.buttonClicked(_:)), for: .touchUpInside)
}
// MARK: - Actions
func buttonClicked(_ sender: UIButton) {
NSLog("A button was clicked: \(sender).")
}
}
|
mit
|
f16364c764ab830cdacc5dfe9f21de07
| 38.912621 | 297 | 0.719533 | 5.709722 | false | true | false | false |
Mogendas/ChickenFight
|
ChickenFight/AppDelegate.swift
|
1
|
4616
|
//
// AppDelegate.swift
// ChickenFight
//
// Created by Johan Wejdenstolpe on 2017-08-07.
// Copyright © 2017 Johan Wejdenstolpe. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ChickenFight")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
gpl-3.0
|
5af6eb949071af625561669c4fa1b2fc
| 48.623656 | 285 | 0.687324 | 5.805031 | false | false | false | false |
jayesh15111988/JKWayfairPriceGame
|
JKWayfairPriceGameTests/FinalScoreIndicatorViewModelSpec.swift
|
1
|
4257
|
//
// FinalScoreIndicatorViewModelSpec.swift
// JKWayfairPriceGame
//
// Created by Jayesh Kawli on 10/11/16.
// Copyright © 2016 Jayesh Kawli Backup. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import JKWayfairPriceGame
class FinalScoreIndicatorViewModelSpec: QuickSpec {
override func spec() {
describe("Verifying the final score indicator view model") {
var finalScoreIndicatorViewModel: FinalScoreIndicatorViewModel? = nil
var gameViewModel: GameViewModel? = nil
beforeEach({
let product1 = try? Product(dictionary: ["availability": "Available", "imageURL": "", "listPrice": 100, "manufacturerIdentifier": 200, "manufacturerName": "Random Manufacturer", "name": "A very good product", "salePrice": 50, "sku": "SK243"])
let product2 = try? Product(dictionary: ["availability": "Unavailable", "imageURL": "", "listPrice": 200, "manufacturerIdentifier": 9393, "manufacturerName": "Random Manufacturer 1", "name": "A very great product", "salePrice": 100, "sku": "SK343"])
let product3 = try? Product(dictionary: ["availability": "Available", "imageURL": "", "listPrice": 10000, "manufacturerIdentifier": 200, "manufacturerName": "Random Manufacturer 2", "name": "A very amazing product", "salePrice": 5000, "sku": "SK24453"])
gameViewModel = GameViewModel(products: [product1!, product2!, product3!])
// Mocking these values since we are not really testing the GameViewModel.
gameViewModel?.totalScore = 20
gameViewModel?.questionIndex = 3
gameViewModel?.skipCount = 0
finalScoreIndicatorViewModel = FinalScoreIndicatorViewModel(gameViewModel: gameViewModel!)
})
describe("Verifying the initial parameter values for FinalScoreIndicatorViewModel", {
it("Initial values of model should match the expected value", closure: {
expect(finalScoreIndicatorViewModel?.finalScoreScreenOption).to(equal(ScoreOption.FinalScoreScreenOption.GoBack))
expect(finalScoreIndicatorViewModel?.gameViewModel).toNot(beNil())
expect(gameViewModel).to(beIdenticalTo(finalScoreIndicatorViewModel?.gameViewModel))
})
})
describe("Verifying the game statistics", {
it("Game statistics should match the expected string corresponding to the game parameters based on the user performance", closure: {
expect(finalScoreIndicatorViewModel?.totalStats).to(equal("Total Questions: 3 Skipped: 0\n\nCorrect: 2 / 66%\n\nTotal Score: 20"))
})
})
describe("Verifying the back button press action", {
it("Pressing back button should update the finalScoreScreenOption to corresponding value", closure: {
finalScoreIndicatorViewModel?.goBackButtonActionCommand?.execute(nil)
expect(finalScoreIndicatorViewModel?.finalScoreScreenOption).to(equal(ScoreOption.FinalScoreScreenOption.GoBack))
})
})
describe("Verifying the new game button press action", {
it("Pressing new game button should update the finalScoreScreenOption to corresponding value", closure: {
finalScoreIndicatorViewModel?.newGameButtonActionCommand?.execute(nil)
expect(finalScoreIndicatorViewModel?.finalScoreScreenOption).to(equal(ScoreOption.FinalScoreScreenOption.NewGame))
})
})
describe("Verifying the view statistics button press action", {
it("Pressing view statistics button should update the finalScoreScreenOption to corresponding value", closure: {
finalScoreIndicatorViewModel?.viewStatisticsButtonActionCommand?.execute(nil)
expect(finalScoreIndicatorViewModel?.finalScoreScreenOption).to(equal(ScoreOption.FinalScoreScreenOption.ViewStatistics))
})
})
}
}
}
|
mit
|
10672468ae2567b8d92155a79bca59c9
| 58.111111 | 269 | 0.642622 | 5.254321 | false | false | false | false |
Yonward/RAReorderableLayout
|
RAReorderableLayout-Demo/RAReorderableLayout-Demo/HorizontalViewController.swift
|
2
|
8717
|
//
// HorizontalViewController.swift
// RAReorderableLayout-Demo
//
// Created by Ryo Aoyama on 11/17/14.
// Copyright (c) 2014 Ryo Aoyama. All rights reserved.
//
import UIKit
class HorizontalViewController: UIViewController, RAReorderableLayoutDelegate, RAReorderableLayoutDataSource {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var gradientView: UIView!
private var gradientLayer: CAGradientLayer?
private var books: [Book] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "RAReorderableLayout"
collectionView.register(BookCell.self, forCellWithReuseIdentifier: "horizontalCell")
collectionView.delegate = self
collectionView.dataSource = self
(collectionView.collectionViewLayout as! RAReorderableLayout).scrollDirection = .horizontal
applyGradation()
let aScalars = "A".unicodeScalars
let zScalars = "Z".unicodeScalars
let aAsciiCode = aScalars[aScalars.startIndex].value
let zAsciiCode = zScalars[zScalars.startIndex].value
books = (aAsciiCode...zAsciiCode)
.flatMap(UnicodeScalar.init)
.map(Character.init)
.enumerated()
.map {
let title = "Book \(String($1))"
let color = UIColor(hue: 255.0 / 26.0 * CGFloat($0) / 255.0, saturation: 1.0, brightness: 0.9, alpha: 1.0)
return .init(title: title, color: color)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
gradientLayer?.frame = gradientView.bounds
}
private func applyGradation() {
gradientLayer = CAGradientLayer()
gradientLayer!.frame = gradientView.bounds
let mainColor = UIColor(white: 0, alpha: 0.3).cgColor
let subColor = UIColor.clear.cgColor
gradientLayer!.colors = [subColor, mainColor]
gradientLayer!.locations = [0, 1]
gradientView.layer.insertSublayer(gradientLayer!, at: 0)
}
// collectionView delegate datasource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return books.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 130.0, height: 170.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 20.0, 0, 20.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 20.0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell: BookCell
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "horizontalCell", for: indexPath) as! BookCell
cell.book = books[(indexPath as NSIndexPath).item]
return cell
}
func collectionView(_ collectionView: UICollectionView, at: IndexPath, willMoveTo toIndexPath: IndexPath) {
}
func collectionView(_ collectionView: UICollectionView, at: IndexPath, didMoveTo toIndexPath: IndexPath) {
let book = books.remove(at: (toIndexPath as NSIndexPath).item)
books.insert(book, at: (toIndexPath as NSIndexPath).item)
}
func scrollTrigerEdgeInsetsInCollectionView(_ collectionView: UICollectionView) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 50, 0, 50)
}
func scrollSpeedValueInCollectionView(_ collectionView: UICollectionView) -> CGFloat {
return 15.0
}
}
class BookCell: UICollectionViewCell {
private var backCoverView: UIView!
private var pagesView: UIView!
private var frontCoverView: UIView!
private var bindingView: UIView!
private var titleLabel: UILabel!
var book: Book? {
didSet {
titleLabel.text = book?.title
color = book?.color
}
}
var color: UIColor? {
didSet {
backCoverView.backgroundColor = getDarkColor(color, minusValue: 20.0)
frontCoverView.backgroundColor = color
bindingView.backgroundColor = getDarkColor(color, minusValue: 50.0)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
override func prepareForReuse() {
super.prepareForReuse()
titleLabel.text = nil
}
private func configure() {
backCoverView = UIView(frame: bounds)
backCoverView.backgroundColor = getDarkColor(UIColor.red, minusValue: 20.0)
backCoverView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
pagesView = UIView(frame: CGRect(x: 15.0, y: 0, width: bounds.width - 25.0, height: bounds.height - 5.0))
pagesView.backgroundColor = UIColor.white
pagesView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
frontCoverView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height - 10.0))
frontCoverView.backgroundColor = UIColor.red
frontCoverView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
bindingView = UIView(frame: CGRect(x: 0, y: 0, width: 15.0, height: bounds.height))
bindingView.backgroundColor = getDarkColor(backCoverView?.backgroundColor, minusValue: 50.0)
bindingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
bindingView.layer.borderWidth = 1.0
bindingView.layer.borderColor = UIColor.black.cgColor
titleLabel = UILabel(frame: CGRect(x: 15.0, y: 30.0, width: bounds.width - 16.0, height: 30.0))
titleLabel.backgroundColor = UIColor(white: 1.0, alpha: 0.8)
titleLabel.textColor = UIColor.black
titleLabel.textAlignment = .center
titleLabel.font = UIFont.boldSystemFont(ofSize: 20.0)
contentView.addSubview(backCoverView)
contentView.addSubview(pagesView)
contentView.addSubview(frontCoverView)
contentView.addSubview(bindingView)
contentView.addSubview(titleLabel)
let backPath = UIBezierPath(roundedRect: backCoverView!.bounds, byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
let backMask = CAShapeLayer()
backMask.frame = backCoverView!.bounds
backMask.path = backPath.cgPath
let backLineLayer = CAShapeLayer()
backLineLayer.frame = backCoverView!.bounds
backLineLayer.path = backPath.cgPath
backLineLayer.strokeColor = UIColor.black.cgColor
backLineLayer.fillColor = UIColor.clear.cgColor
backLineLayer.lineWidth = 2.0
backCoverView!.layer.mask = backMask
backCoverView!.layer.insertSublayer(backLineLayer, at: 0)
let frontPath = UIBezierPath(roundedRect: frontCoverView!.bounds, byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
let frontMask = CAShapeLayer()
frontMask.frame = frontCoverView!.bounds
frontMask.path = frontPath.cgPath
let frontLineLayer = CAShapeLayer()
frontLineLayer.path = frontPath.cgPath
frontLineLayer.strokeColor = UIColor.black.cgColor
frontLineLayer.fillColor = UIColor.clear.cgColor
frontLineLayer.lineWidth = 2.0
frontCoverView!.layer.mask = frontMask
frontCoverView!.layer.insertSublayer(frontLineLayer, at: 0)
}
private func getDarkColor(_ color: UIColor?, minusValue: CGFloat) -> UIColor? {
if color == nil {
return nil
}
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
color!.getRed(&r, green: &g, blue: &b, alpha: &a)
r -= max(minusValue / 255.0, 0)
g -= max(minusValue / 255.0, 0)
b -= max(minusValue / 255.0, 0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
class Book: NSObject {
var title: String?
var color: UIColor?
init(title: String?, color: UIColor) {
super.init()
self.title = title
self.color = color
}
}
|
mit
|
d660b7e4675fe682383b33cc68896466
| 38.622727 | 170 | 0.659172 | 4.752999 | false | false | false | false |
groovelab/SwiftBBS
|
SwiftBBS/SwiftBBS Server/GoogleOAuthClient.swift
|
1
|
2304
|
//
// GoogleOAuthClient.swift
// SwiftBBS
//
// Created by Takeo Namba on 2016/02/17.
// Copyright GrooveLab
//
final class GoogleOAuthClient : OAuthClient {
let clientId: String
let clientSecret: String
let state: String = String.randomString(10)
required init(clientId: String, clientSecret: String) {
self.clientId = clientId
self.clientSecret = clientSecret
}
func authUrl(redirectUri: String) -> String {
return "https://accounts.google.com/o/oauth2/v2/auth?client_id=\(clientId)&response_type=code&scope=profile&redirect_uri=\(redirectUri)&state=\(state)"
}
func getAccessToken(code: String, extraData: String) throws -> String {
let url = "https://www.googleapis.com/oauth2/v4/token"
/*
response example
success : {"access_token": "hoge","token_type": "bearer", "expires_in": 1234, "id_token": "hoge"}
error : {"error": "error_message", "error_description": "Bad Request"}
*/
guard let jsonObject = try request(url, headers: nil, postParams: [
"code": code,
"client_id": clientId,
"client_secret": clientSecret,
"redirect_uri": extraData,
"grant_type": "authorization_code"
]) else { throw OAuthClientError.Fail("jsonObject") }
guard let jsonMap = jsonObject as? [String: Any] else { throw OAuthClientError.Fail("jsonMap") }
guard let accessToken = jsonMap["access_token"] as? String else { throw OAuthClientError.Fail("accessToken") }
return accessToken
}
func getSocialUser(accessToken: String) throws -> OAuthSocialUser {
let url = "https://www.googleapis.com/plus/v1/people/me?access_token=\(accessToken)"
/*
response example
{"displayName":"user name", "id":"1"}
*/
guard let jsonObject = try request(url) else { throw OAuthClientError.Fail("jsonObject") }
guard let jsonMap = jsonObject as? [String: Any] else { throw OAuthClientError.Fail("jsonMap") }
guard let id = jsonMap["id"] as? String else { throw OAuthClientError.Fail("id") }
guard let name = jsonMap["displayName"] as? String else { throw OAuthClientError.Fail("name") }
return (id: id, name: name)
}
}
|
mit
|
a051115c2fbec2789b253a40c29f6d50
| 41.666667 | 159 | 0.629774 | 4.106952 | false | false | false | false |
rwash8347/desktop-apod
|
DesktopAPOD/DesktopAPOD/APOD.swift
|
1
|
2092
|
//
// APOD.swift
// DesktopAPOD
//
// Created by Richard Ash on 4/29/17.
// Copyright © 2017 Richard. All rights reserved.
//
import Foundation
import Cocoa
class APOD: NSObject {
// MARK: - Static Properties
fileprivate static let Keys = (
title: "apodTitle",
apodImage: "apodImage",
lastRefresh: "lastRefresh"
)
private static let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
private static let archiveURL = documentDirectory.appendingPathComponent("apod")
// MARK: - Properties
let title: String
let image: NSImage
let lastRefresh: Date
lazy var formattedDate: String = {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
return dateFormatter.string(from: self.lastRefresh)
}()
// MARK: - Initialization
init(title: String, image: NSImage, date: Date) {
self.title = title
self.image = image
self.lastRefresh = date
}
required convenience init?(coder aDecoder: NSCoder) {
guard let title = aDecoder.decodeObject(forKey: APOD.Keys.title) as? String else { return nil }
guard let image = aDecoder.decodeObject(forKey: APOD.Keys.apodImage) as? NSImage else { return nil }
guard let lastRefresh = aDecoder.decodeObject(forKey: APOD.Keys.lastRefresh) as? Date else { return nil }
self.init(title: title, image: image, date: lastRefresh)
}
// MARK: - Static Methods
static func save(_ apod: APOD) {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(apod, toFile: archiveURL.path)
print("Attempt to save was\(isSuccessfulSave ? "" : " not") successful")
}
static func loadAPOD() -> APOD? {
return NSKeyedUnarchiver.unarchiveObject(withFile: archiveURL.path) as? APOD
}
}
// MARK: - NSCoding
extension APOD: NSCoding {
func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: APOD.Keys.title)
aCoder.encode(image, forKey: APOD.Keys.apodImage)
aCoder.encode(lastRefresh, forKey: APOD.Keys.lastRefresh)
}
}
|
mit
|
704ec39eb1b263b9687aa043a266df09
| 27.256757 | 118 | 0.697274 | 3.952741 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.