repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Rehsco/StyledOverlay | StyledOverlay/CGRectHelper.swift | 1 | 2640 | //
// CGRectHelper.swift
// StyledOverlay
//
// Created by Martin Rehder on 09.08.16.
/*
* Copyright 2016-present Martin Jacob Rehder.
* http://www.rehsco.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 UIKit
// Adopted from lanephillips/CGRectAspectFit.m (GitHub / Gist)
class CGRectHelper {
class func ScaleToAspectFitRectInRect(_ rfit: CGRect, rtarget: CGRect) -> CGFloat {
// first try to match width
let s = rtarget.width / rfit.width
// if we scale the height to make the widths equal, does it still fit?
if rfit.height * s <= rtarget.height {
return s
}
// no, match height instead
return rtarget.height / rfit.height
}
class func AspectFitRectInRect(_ rfit: CGRect, rtarget: CGRect) -> CGRect {
let s = ScaleToAspectFitRectInRect(rfit, rtarget: rtarget)
let w = rfit.width * s
let h = rfit.height * s
let x = rtarget.midX - w / 2
let y = rtarget.midY - h / 2
return CGRect(x: x, y: y, width: w, height: h)
}
class func ScaleToAspectFitRectAroundRect(_ rfit: CGRect, rtarget: CGRect) -> CGFloat {
return 1.0 / ScaleToAspectFitRectInRect(rtarget, rtarget: rfit)
}
class func AspectFitRectAroundRect(_ rfit: CGRect, rtarget: CGRect) -> CGRect {
let s = ScaleToAspectFitRectAroundRect(rfit, rtarget: rtarget)
let w = rfit.width * s
let h = rfit.height * s
let x = rtarget.midX - w / 2
let y = rtarget.midY - h / 2
return CGRect(x: x, y: y, width: w, height: h)
}
}
| mit | 778e71227c8237c68d7f4d0ddeabdeba | 39 | 91 | 0.675 | 3.893805 | false | false | false | false |
material-components/material-components-ios | catalog/MDCCatalog/MDCCatalogWindow.swift | 2 | 4320 | // Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import MaterialComponents.MaterialDialogs
import MaterialComponents.MaterialOverlayWindow
/// A custom UIWindow that displays the user's touches for recording video or demos.
///
/// Triple tapping anywhere will toggle the visible touches.
class MDCCatalogWindow: MDCOverlayWindow {
var showTouches = false
fileprivate let fadeDuration: TimeInterval = 0.2
fileprivate var touchViews = [Int: UIView]()
fileprivate var edgeView = MDCDebugSafeAreaInsetsView()
var showSafeAreaEdgeInsets: Bool {
set {
if newValue {
edgeView.frame = bounds
edgeView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(edgeView)
} else {
edgeView.removeFromSuperview()
}
}
get {
return edgeView.superview == self
}
}
override func sendEvent(_ event: UIEvent) {
if let touches = event.allTouches {
for touch in touches {
switch touch.phase {
case .began:
if showTouches {
beginDisplayingTouch(touch)
}
continue
case .moved:
updateTouch(touch)
continue
case .stationary:
continue
case .cancelled, .ended:
endDisplayingTouch(touch)
continue
default:
// TODO(b/152350850): Add support for new UITouchPhases
// New UITouchPhases added in iOS 13.4:
// regionEntered = 5
// regionMoved = 6
// regionExited = 7
continue
}
}
}
super.sendEvent(event)
}
func showDebugSettings() {
let touches = MDCCatalogDebugSetting(title: "Show touches")
touches.getter = { self.showTouches }
touches.setter = { newValue in self.showTouches = newValue }
let safeAreaInsets = MDCCatalogDebugSetting(title: "Show safeAreaInsets")
safeAreaInsets.getter = { self.showSafeAreaEdgeInsets }
safeAreaInsets.setter = { newValue in self.showSafeAreaEdgeInsets = newValue }
let debugUI = MDCCatalogDebugAlert(settings: [touches, safeAreaInsets])
rootViewController?.present(debugUI, animated: true, completion: nil)
}
fileprivate func beginDisplayingTouch(_ touch: UITouch) {
let view = MDCTouchView()
view.center = touch.location(in: self)
touchViews[touch.hash] = view
addSubview(view)
}
fileprivate func updateTouch(_ touch: UITouch) {
touchViews[touch.hash]?.center = touch.location(in: self)
}
fileprivate func endDisplayingTouch(_ touch: UITouch) {
let view = touchViews[touch.hash]
touchViews[touch.hash] = nil
UIView.animate(
withDuration: fadeDuration,
animations: { view?.alpha = 0 },
completion: { _ in view?.removeFromSuperview() })
}
}
/// A circular view that represents a user's touch.
class MDCTouchView: UIView {
fileprivate let touchCircleSize: CGFloat = 80
fileprivate let touchCircleAlpha: CGFloat = 0.25
fileprivate let touchCircleColor = UIColor.red
fileprivate let touchCircleBorderColor = UIColor.black
fileprivate let touchCircleBorderWidth: CGFloat = 1
override init(frame: CGRect) {
super.init(frame: frame)
commonMDCTouchViewInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonMDCTouchViewInit()
}
fileprivate func commonMDCTouchViewInit() {
backgroundColor = touchCircleColor
alpha = touchCircleAlpha
frame.size = CGSize(width: touchCircleSize, height: touchCircleSize)
layer.cornerRadius = touchCircleSize / 2
layer.borderColor = touchCircleBorderColor.cgColor
layer.borderWidth = touchCircleBorderWidth
isUserInteractionEnabled = false
}
}
| apache-2.0 | 81a95baf498c6c9f93d4f868f981929c | 30.532847 | 87 | 0.692593 | 4.55216 | false | false | false | false |
amomchilov/ZipNsequence | Zip10Sequence.swift | 1 | 9621 |
/// Creates a sequence of tuples built out of 10 underlying sequences.
///
/// In the `Zip10Sequence` instance returned by this function, the elements of
/// the *i*th tuple are the *i*th elements of each underlying sequence. The
/// following example uses the `zip(_:_:)` function to iterate over an array
/// of strings and a countable range at the same time:
///
/// let words = ["one", "two", "three", "four"]
/// let numbers = 1...4
///
/// for (word, number) in zip(words, numbers) {
/// print("\(word): \(number)")
/// }
/// // Prints "one: 1"
/// // Prints "two: 2
/// // Prints "three: 3"
/// // Prints "four: 4"
///
/// If the 10 sequences passed to `zip(_:_:_:_:_:_:_:_:_:_:)` are different lengths, the
/// resulting sequence is the same length as the shortest sequence. In this
/// example, the resulting array is the same length as `words`:
///
/// let naturalNumbers = 1...Int.max
/// let zipped = Array(zip(words, naturalNumbers))
/// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
///
/// - Parameters:
/// - sequence1: The sequence or collection in position 1 of each tuple.
/// - sequence2: The sequence or collection in position 2 of each tuple.
/// - sequence3: The sequence or collection in position 3 of each tuple.
/// - sequence4: The sequence or collection in position 4 of each tuple.
/// - sequence5: The sequence or collection in position 5 of each tuple.
/// - sequence6: The sequence or collection in position 6 of each tuple.
/// - sequence7: The sequence or collection in position 7 of each tuple.
/// - sequence8: The sequence or collection in position 8 of each tuple.
/// - sequence9: The sequence or collection in position 9 of each tuple.
/// - sequence10: The sequence or collection in position 10 of each tuple.
/// - Returns: A sequence of tuple pairs, where the elements of each pair are
/// corresponding elements of `sequence1` and `sequence2`.
public func zip<
Sequence1 : Sequence,
Sequence2 : Sequence,
Sequence3 : Sequence,
Sequence4 : Sequence,
Sequence5 : Sequence,
Sequence6 : Sequence,
Sequence7 : Sequence,
Sequence8 : Sequence,
Sequence9 : Sequence,
Sequence10 : Sequence
>(
_ sequence1: Sequence1,
_ sequence2: Sequence2,
_ sequence3: Sequence3,
_ sequence4: Sequence4,
_ sequence5: Sequence5,
_ sequence6: Sequence6,
_ sequence7: Sequence7,
_ sequence8: Sequence8,
_ sequence9: Sequence9,
_ sequence10: Sequence10
) -> Zip10Sequence<
Sequence1,
Sequence2,
Sequence3,
Sequence4,
Sequence5,
Sequence6,
Sequence7,
Sequence8,
Sequence9,
Sequence10
> {
return Zip10Sequence(
_sequence1: sequence1,
_sequence2: sequence2,
_sequence3: sequence3,
_sequence4: sequence4,
_sequence5: sequence5,
_sequence6: sequence6,
_sequence7: sequence7,
_sequence8: sequence8,
_sequence9: sequence9,
_sequence10: sequence10
)
}
/// An iterator for `Zip10Sequence`.
public struct Zip10Iterator<
Iterator1 : IteratorProtocol,
Iterator2 : IteratorProtocol,
Iterator3 : IteratorProtocol,
Iterator4 : IteratorProtocol,
Iterator5 : IteratorProtocol,
Iterator6 : IteratorProtocol,
Iterator7 : IteratorProtocol,
Iterator8 : IteratorProtocol,
Iterator9 : IteratorProtocol,
Iterator10 : IteratorProtocol
> : IteratorProtocol {
/// The type of element returned by `next()`.
public typealias Element = (
Iterator1.Element,
Iterator2.Element,
Iterator3.Element,
Iterator4.Element,
Iterator5.Element,
Iterator6.Element,
Iterator7.Element,
Iterator8.Element,
Iterator9.Element,
Iterator10.Element
)
/// Creates an instance around the underlying iterators.
internal init(
_ iterator1: Iterator1,
_ iterator2: Iterator2,
_ iterator3: Iterator3,
_ iterator4: Iterator4,
_ iterator5: Iterator5,
_ iterator6: Iterator6,
_ iterator7: Iterator7,
_ iterator8: Iterator8,
_ iterator9: Iterator9,
_ iterator10: Iterator10
) {
_baseStream1 = iterator1
_baseStream2 = iterator2
_baseStream3 = iterator3
_baseStream4 = iterator4
_baseStream5 = iterator5
_baseStream6 = iterator6
_baseStream7 = iterator7
_baseStream8 = iterator8
_baseStream9 = iterator9
_baseStream10 = iterator10
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
public mutating func next() -> Element? {
// The next() function needs to track if it has reached the end. If we
// didn't, and the first sequence is longer than the second, then when we
// have already exhausted the second sequence, on every subsequent call to
// next() we would consume and discard one additional element from the
// first sequence, even though next() had already returned nil.
if _reachedEnd {
return nil
}
guard
let element1 = _baseStream1.next(),
let element2 = _baseStream2.next(),
let element3 = _baseStream3.next(),
let element4 = _baseStream4.next(),
let element5 = _baseStream5.next(),
let element6 = _baseStream6.next(),
let element7 = _baseStream7.next(),
let element8 = _baseStream8.next(),
let element9 = _baseStream9.next(),
let element10 = _baseStream10.next()
else {
_reachedEnd = true
return nil
}
return (
element1,
element2,
element3,
element4,
element5,
element6,
element7,
element8,
element9,
element10
)
}
internal var _baseStream1: Iterator1
internal var _baseStream2: Iterator2
internal var _baseStream3: Iterator3
internal var _baseStream4: Iterator4
internal var _baseStream5: Iterator5
internal var _baseStream6: Iterator6
internal var _baseStream7: Iterator7
internal var _baseStream8: Iterator8
internal var _baseStream9: Iterator9
internal var _baseStream10: Iterator10
internal var _reachedEnd: Bool = false
}
/// A sequence of pairs built out of two underlying sequences.
///
/// In a `Zip10Sequence` instance, the elements of the *i*th pair are the *i*th
/// elements of each underlying sequence. To create a `Zip10Sequence` instance,
/// use the `zip(_:_:_:_:_:_:_:_:_:_:)` function.
///
/// The following example uses the `zip(_:_:)` function to iterate over an
/// array of strings and a countable range at the same time:
///
/// let words = ["one", "two", "three", "four"]
/// let numbers = 1...4
///
/// for (word, number) in zip(words, numbers) {
/// print("\(word): \(number)")
/// }
/// // Prints "one: 1"
/// // Prints "two: 2
/// // Prints "three: 3"
/// // Prints "four: 4"
///
/// - SeeAlso: `zip(_:_:_:_:_:_:_:_:_:_:)`
public struct Zip10Sequence<
Sequence1 : Sequence,
Sequence2 : Sequence,
Sequence3 : Sequence,
Sequence4 : Sequence,
Sequence5 : Sequence,
Sequence6 : Sequence,
Sequence7 : Sequence,
Sequence8 : Sequence,
Sequence9 : Sequence,
Sequence10 : Sequence
>
: Sequence {
public typealias Stream1 = Sequence1.Iterator
public typealias Stream2 = Sequence2.Iterator
public typealias Stream3 = Sequence3.Iterator
public typealias Stream4 = Sequence4.Iterator
public typealias Stream5 = Sequence5.Iterator
public typealias Stream6 = Sequence6.Iterator
public typealias Stream7 = Sequence7.Iterator
public typealias Stream8 = Sequence8.Iterator
public typealias Stream9 = Sequence9.Iterator
public typealias Stream10 = Sequence10.Iterator
/// A type whose instances can produce the elements of this
/// sequence, in order.
public typealias Iterator = Zip10Iterator<
Stream1,
Stream2,
Stream3,
Stream4,
Stream5,
Stream6,
Stream7,
Stream8,
Stream9,
Stream10
>
@available(*, unavailable, renamed: "Iterator")
public typealias Generator = Iterator
/// Creates an instance that makes pairs of elements from `sequence1` and
/// `sequence2`.
public // @testable
init(
_sequence1 sequence1: Sequence1,
_sequence2 sequence2: Sequence2,
_sequence3 sequence3: Sequence3,
_sequence4 sequence4: Sequence4,
_sequence5 sequence5: Sequence5,
_sequence6 sequence6: Sequence6,
_sequence7 sequence7: Sequence7,
_sequence8 sequence8: Sequence8,
_sequence9 sequence9: Sequence9,
_sequence10 sequence10: Sequence10
) {
_sequence1 = sequence1
_sequence2 = sequence2
_sequence3 = sequence3
_sequence4 = sequence4
_sequence5 = sequence5
_sequence6 = sequence6
_sequence7 = sequence7
_sequence8 = sequence8
_sequence9 = sequence9
_sequence10 = sequence10
}
/// Returns an iterator over the elements of this sequence.
public func makeIterator() -> Iterator {
return Iterator(
_sequence1.makeIterator(),
_sequence2.makeIterator(),
_sequence3.makeIterator(),
_sequence4.makeIterator(),
_sequence5.makeIterator(),
_sequence6.makeIterator(),
_sequence7.makeIterator(),
_sequence8.makeIterator(),
_sequence9.makeIterator(),
_sequence10.makeIterator()
)
}
internal let _sequence1: Sequence1
internal let _sequence2: Sequence2
internal let _sequence3: Sequence3
internal let _sequence4: Sequence4
internal let _sequence5: Sequence5
internal let _sequence6: Sequence6
internal let _sequence7: Sequence7
internal let _sequence8: Sequence8
internal let _sequence9: Sequence9
internal let _sequence10: Sequence10
} | apache-2.0 | d34e4d165305b263f8a4bbac966673f6 | 29.353312 | 88 | 0.670616 | 3.972337 | false | false | false | false |
RicardoAnjos/CringleApp | CringleApp/Models/Classes/Acount.swift | 1 | 922 | //
// Acount.swift
// CringleApp
//
// Created by Ricardo Jorge Lemos dos Anjos on 24/10/2016.
// Copyright © 2016 Ricardo Jorge Lemos dos Anjos. All rights reserved.
//
import Foundation
/// Class Account
/// It inherits DataObject. It's used for the data implementation of the rows
/// - variables:
/// - String: text
/// - String: image
/// - String: ownerName
/// - String: number
/// - Bool: isSelected
class Account : DataObject {
var ownerName : String?
var number : String?
var isSelected : Bool?
init(text:String, ownerName:String, number:String, isSelected:Bool){
let image : String
if (isSelected){
image = "CircleCheckedIcon"
}else{
image = "CircleUncheckedIcon"
}
super.init(text: text, image: image)
self.ownerName = ownerName
self.number = number
self.isSelected = isSelected
}
}
| mit | 0d9ce735d8991ea54890ed852dc61a1e | 25.314286 | 77 | 0.619978 | 3.919149 | false | false | false | false |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/Utils/TaskStatusImage.swift | 1 | 2023 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import SwiftUI
struct TaskStatusImage: View {
@ObservedObject var task: ModelData.Task
var body: some View {
let isDelivery = task.taskInfo.taskType == .DELIVERY
let taskLetter = task.sequenceString.lowercased()
let foregroundColor =
isDelivery ? .red : Color(.sRGB, red: 1.0, green: 0.7, blue: 0.7, opacity: 1)
Image(systemName: "\(taskLetter).circle.fill")
.foregroundColor(foregroundColor)
.frame(width: 30, height: 30)
}
}
struct TaskStatusImage_Previews: PreviewProvider {
static var previews: some View {
let _ = LMFSDriverSampleApp.googleMapsInited
let modelData = ModelData(filename: "test_manifest")
TaskStatusImage(task: modelData.tasks(stop: modelData.stops[0])[0])
.previewLayout(.fixed(width: 70, height: 70))
TaskStatusImage(task: modelData.tasks(stop: modelData.stops[0])[1])
.previewLayout(.fixed(width: 70, height: 70))
TaskStatusImage(task: modelData.tasks(stop: modelData.stops[0])[2])
.previewLayout(.fixed(width: 70, height: 70))
TaskStatusImage(task: modelData.tasks(stop: modelData.stops[1])[0])
.previewLayout(.fixed(width: 70, height: 70))
TaskStatusImage(task: modelData.tasks(stop: modelData.stops[1])[1])
.previewLayout(.fixed(width: 70, height: 70))
TaskStatusImage(task: modelData.tasks(stop: modelData.stops[1])[2])
.previewLayout(.fixed(width: 70, height: 70))
}
}
| apache-2.0 | 7179f0d327410fae6c152b3543100272 | 41.145833 | 91 | 0.71132 | 3.831439 | false | false | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Classes/PresentationLayer/Wallet/Receive/Module/ReceiveModule.swift | 1 | 730 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import UIKit
class ReceiveModule {
class func create(app: Application) -> ReceiveModuleInput {
let router = ReceiveRouter()
let presenter = ReceivePresenter()
let interactor = ReceiveInteractor()
let viewController = R.storyboard.receive.receiveViewController()!
interactor.output = presenter
viewController.output = presenter
presenter.view = viewController
presenter.router = router
presenter.interactor = interactor
router.app = app
// Injections
interactor.qrService = QRService()
interactor.walletRepsitory = app.walletRepository
return presenter
}
}
| gpl-3.0 | 48ca7c5af92219e0487e9042e7e8cc5f | 21.78125 | 70 | 0.706447 | 5.027586 | false | false | false | false |
jeffreybergier/WaterMe2 | WaterMe/WaterMe/Settings/SettingsInfoTableViewCell.swift | 1 | 2912 | //
// SettingsInfoTableViewCell.swift
// WaterMe
//
// Created by Jeffrey Bergier on 15/1/18.
// Copyright © 2017 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe 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.
//
// WaterMe 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 WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Datum
import UIKit
class SettingsInfoTableViewCell: UITableViewCell {
class var reuseID: String { return "SettingsInfoTableViewCell" }
class var nib: UINib { return UINib(nibName: self.reuseID, bundle: Bundle(for: self.self)) }
@IBOutlet private weak var leadingConstraint: NSLayoutConstraint?
@IBOutlet private weak var trailingConstraint: NSLayoutConstraint?
@IBOutlet private weak var topConstraint: NSLayoutConstraint?
@IBOutlet private weak var bottomConstraint: NSLayoutConstraint?
@IBOutlet private weak var emojiImageView: EmojiImageView?
@IBOutlet private weak var label: UILabel?
override func awakeFromNib() {
super.awakeFromNib()
self.leadingConstraint?.constant = UITableViewCell.style_labelCellLeadingPadding
self.trailingConstraint?.constant = UITableViewCell.style_labelCellTrailingPadding
self.topConstraint?.constant = UITableViewCell.style_labelCellTopPadding
self.bottomConstraint?.constant = UITableViewCell.style_labelCellBottomPadding
self.emojiImageView?.size = .small
self.emojiImageView?.ring = true
self.prepareForReuse()
}
func configure(with icon: ReminderVesselIcon?, and text: String) {
self.label?.attributedText = NSAttributedString(string: text, font: .selectableTableViewCell)
guard let icon = icon else { return }
self.emojiImageView?.setIcon(icon)
}
private func updateLayout() {
self.emojiImageView?.isHidden = self.traitCollection.preferredContentSizeCategory.isAccessibilityCategory
}
override func didMoveToWindow() {
super.didMoveToWindow()
self.updateLayout()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.updateLayout()
}
override func prepareForReuse() {
super.prepareForReuse()
self.label?.attributedText = nil
self.emojiImageView?.setIcon(nil)
}
}
| gpl-3.0 | bffd178d71cc4cd6b5b97484f0676419 | 36.320513 | 113 | 0.729303 | 4.976068 | false | false | false | false |
kumabook/MusicFav | MusicFav/YouTubeActivityTableViewController.swift | 1 | 2176 | //
// YouTubeActivityTableViewController.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 9/5/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import UIKit
import ReactiveSwift
import SoundCloudKit
import MusicFeeder
import YouTubeKit
class YouTubeActivityTableViewController: TimelineTableViewController {
let activityLoader: YouTubeActivityLoader!
var playlist: YouTubeKit.Playlist!
override func getPlaylistQueue() -> PlaylistQueue {
return activityLoader.playlistQueue
}
init(activityLoader: YouTubeActivityLoader, playlist: YouTubeKit.Playlist) {
self.activityLoader = activityLoader
self.playlist = playlist
super.init()
}
override init(style: UITableViewStyle) {
activityLoader = YouTubeActivityLoader()
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
activityLoader = YouTubeActivityLoader()
super.init(coder:aDecoder)
}
override var timelineTitle: String {
return playlist.title.localize()
}
override func getItems() -> [TimelineItem] {
var items: [TimelineItem] = []
if let vals = activityLoader.itemsOfPlaylist[playlist] {
for i in 0..<vals.count {
items.append(TimelineItem.youTubePlaylist(vals[i], activityLoader.playlistsOfYouTubePlaylist[playlist]?[i]))
}
}
return items
}
override func fetchNext() {
activityLoader.fetchPlaylistItems(playlist)
}
override func fetchLatest() {
activityLoader.clearPlaylist(playlist)
activityLoader.fetchPlaylistItems(playlist)
}
override func observeTimelineLoader() -> Disposable? {
return activityLoader.signal.observeResult({ result in
guard let event = result.value else { return }
switch event {
case .startLoading:
self.showIndicator()
case .completeLoading:
self.hideIndicator()
self.tableView.reloadData()
case .failToLoad:
self.showReloadButton()
}
})
}
}
| mit | b1edee5bea4ba461bd1d590a25a96c61 | 28.013333 | 124 | 0.64614 | 4.911964 | false | false | false | false |
lorentey/swift | stdlib/public/core/ReflectionMirror.swift | 6 | 5324 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_silgen_name("swift_reflectionMirror_normalizedType")
internal func _getNormalizedType<T>(_: T, type: Any.Type) -> Any.Type
@_silgen_name("swift_reflectionMirror_count")
internal func _getChildCount<T>(_: T, type: Any.Type) -> Int
internal typealias NameFreeFunc = @convention(c) (UnsafePointer<CChar>?) -> Void
@_silgen_name("swift_reflectionMirror_subscript")
internal func _getChild<T>(
of: T,
type: Any.Type,
index: Int,
outName: UnsafeMutablePointer<UnsafePointer<CChar>?>,
outFreeFunc: UnsafeMutablePointer<NameFreeFunc?>
) -> Any
// Returns 'c' (class), 'e' (enum), 's' (struct), 't' (tuple), or '\0' (none)
@_silgen_name("swift_reflectionMirror_displayStyle")
internal func _getDisplayStyle<T>(_: T) -> CChar
internal func getChild<T>(of value: T, type: Any.Type, index: Int) -> (label: String?, value: Any) {
var nameC: UnsafePointer<CChar>? = nil
var freeFunc: NameFreeFunc? = nil
let value = _getChild(of: value, type: type, index: index, outName: &nameC, outFreeFunc: &freeFunc)
let name = nameC.flatMap({ String(validatingUTF8: $0) })
freeFunc?(nameC)
return (name, value)
}
#if _runtime(_ObjC)
@_silgen_name("swift_reflectionMirror_quickLookObject")
internal func _getQuickLookObject<T>(_: T) -> AnyObject?
@_silgen_name("_swift_stdlib_NSObject_isKindOfClass")
internal func _isImpl(_ object: AnyObject, kindOf: UnsafePointer<CChar>) -> Bool
internal func _is(_ object: AnyObject, kindOf `class`: String) -> Bool {
return `class`.withCString {
return _isImpl(object, kindOf: $0)
}
}
internal func _getClassPlaygroundQuickLook(
_ object: AnyObject
) -> _PlaygroundQuickLook? {
if _is(object, kindOf: "NSNumber") {
let number: _NSNumber = unsafeBitCast(object, to: _NSNumber.self)
switch UInt8(number.objCType[0]) {
case UInt8(ascii: "d"):
return .double(number.doubleValue)
case UInt8(ascii: "f"):
return .float(number.floatValue)
case UInt8(ascii: "Q"):
return .uInt(number.unsignedLongLongValue)
default:
return .int(number.longLongValue)
}
}
if _is(object, kindOf: "NSAttributedString") {
return .attributedString(object)
}
if _is(object, kindOf: "NSImage") ||
_is(object, kindOf: "UIImage") ||
_is(object, kindOf: "NSImageView") ||
_is(object, kindOf: "UIImageView") ||
_is(object, kindOf: "CIImage") ||
_is(object, kindOf: "NSBitmapImageRep") {
return .image(object)
}
if _is(object, kindOf: "NSColor") ||
_is(object, kindOf: "UIColor") {
return .color(object)
}
if _is(object, kindOf: "NSBezierPath") ||
_is(object, kindOf: "UIBezierPath") {
return .bezierPath(object)
}
if _is(object, kindOf: "NSString") {
return .text(_forceBridgeFromObjectiveC(object, String.self))
}
return .none
}
#endif
extension Mirror {
internal init(internalReflecting subject: Any,
subjectType: Any.Type? = nil,
customAncestor: Mirror? = nil)
{
let subjectType = subjectType ?? _getNormalizedType(subject, type: type(of: subject))
let childCount = _getChildCount(subject, type: subjectType)
let children = (0 ..< childCount).lazy.map({
getChild(of: subject, type: subjectType, index: $0)
})
self.children = Children(children)
self._makeSuperclassMirror = {
guard let subjectClass = subjectType as? AnyClass,
let superclass = _getSuperclass(subjectClass) else {
return nil
}
// Handle custom ancestors. If we've hit the custom ancestor's subject type,
// or descendants are suppressed, return it. Otherwise continue reflecting.
if let customAncestor = customAncestor {
if superclass == customAncestor.subjectType {
return customAncestor
}
if customAncestor._defaultDescendantRepresentation == .suppressed {
return customAncestor
}
}
return Mirror(internalReflecting: subject,
subjectType: superclass,
customAncestor: customAncestor)
}
let rawDisplayStyle = _getDisplayStyle(subject)
switch UnicodeScalar(Int(rawDisplayStyle)) {
case "c": self.displayStyle = .class
case "e": self.displayStyle = .enum
case "s": self.displayStyle = .struct
case "t": self.displayStyle = .tuple
case "\0": self.displayStyle = nil
default: preconditionFailure("Unknown raw display style '\(rawDisplayStyle)'")
}
self.subjectType = subjectType
self._defaultDescendantRepresentation = .generated
}
internal static func quickLookObject(_ subject: Any) -> _PlaygroundQuickLook? {
#if _runtime(_ObjC)
let object = _getQuickLookObject(subject)
return object.flatMap(_getClassPlaygroundQuickLook)
#else
return nil
#endif
}
}
| apache-2.0 | 95d9aab17a1f78e20e21a7848ff90d29 | 31.864198 | 101 | 0.648948 | 4.195429 | false | false | false | false |
ewhitley/CDAKit | CDAKit/health-data-standards/lib/import/c32/c32_insurance_provider_importer.swift | 1 | 3149 | //
// immunization_importer.swift
// CDAKit
//
// Created by Eric Whitley on 1/21/16.
// Copyright © 2016 Eric Whitley. All rights reserved.
//
import Foundation
import Fuzi
class CDAKImport_C32_InsuranceProviderImporter: CDAKImport_CDA_SectionImporter {
override init(entry_finder: CDAKImport_CDA_EntryFinder = CDAKImport_CDA_EntryFinder(entry_xpath: "//cda:act[cda:templateId/@root='2.16.840.1.113883.10.20.1.26']")) {
super.init(entry_finder: entry_finder)
check_for_usable = false //# needs to be this way becase CDAKInsuranceProvider does not respond to usable?
entry_class = CDAKInsuranceProvider.self
}
override func create_entry(payer_element: XMLElement, nrh: CDAKImport_CDA_NarrativeReferenceHandler = CDAKImport_CDA_NarrativeReferenceHandler()) -> CDAKInsuranceProvider? {
let ip = CDAKInsuranceProvider()
if let type = CDAKImport_CDA_SectionImporter.extract_code(payer_element, code_xpath: "./cda:code") {
ip.type = type.code
}
if let payer = payer_element.xpath("./cda:performer/cda:assignedEntity[cda:code[@code='PAYOR']]").first {
ip.payer = import_organization(payer)
}
ip.guarantors = extract_guarantors(payer_element.xpath("./cda:performer[cda:assignedEntity[cda:code[@code='GUAR']]]"))
if let subscriber = payer_element.xpath("./cda:participant[@typeCode='HLD']/cda:participantRole").first {
ip.subscriber = import_person(subscriber)
}
if let member_info_element = payer_element.xpath("cda:participant[@typeCode='COV']").first {
extract_dates(member_info_element, entry: ip, element_name: "time")
if let patient_element = member_info_element.xpath("./cda:participantRole[@classCode='PAT']").first {
ip.member_id = patient_element.xpath("./cda:id").first?.stringValue //not sure this is right
ip.relationship.addCodes(CDAKImport_CDA_SectionImporter.extract_code(patient_element, code_xpath: "./cda:code"))
}
}
if let name = payer_element.xpath("./cda:entryRelationship[@typeCode='REFR']/cda:act[@classCode='ACT' and @moodCode='DEF']/cda:text").first {
ip.name = name.stringValue
}
ip.financial_responsibility_type.addCodes(CDAKImport_CDA_SectionImporter.extract_code(payer_element, code_xpath: "./cda:performer/cda:assignedEntity/cda:code"))
return ip
}
func extract_guarantors(guarantor_elements: XPathNodeSet) -> [CDAKGuarantor] {
var guarantors: [CDAKGuarantor] = []
for guarantor_element in guarantor_elements {
let guarantor = CDAKGuarantor()
extract_dates(guarantor_element, entry: guarantor, element_name: "time")
if let guarantor_entity = guarantor_element.xpath("./cda:assignedEntity").first {
if let person_element = guarantor_entity.xpath("./cda:assignedPerson").first {
guarantor.person = import_person(person_element)
}
if let org_element = guarantor_entity.xpath("./cda:representedOrganization").first {
guarantor.organization = import_organization(org_element)
}
}
guarantors.append(guarantor)
}
return guarantors
}
} | mit | 068e1b925d4978bb6b4aa39f94760c52 | 41.554054 | 175 | 0.695362 | 3.783654 | false | false | false | false |
hemantasapkota/SwiftStore | Example/SwiftStoreExample/SwiftStoreExample/Extensions.swift | 1 | 2341 | //
// Extensions.swift
// SwiftStoreExample
//
// Created by Hemanta Sapkota on 31/05/2015.
// Copyright (c) 2015 Hemanta Sapkota. All rights reserved.
//
import Foundation
import UIKit
//From https://github.com/yeahdongcn/UIColor-Hex-Swift
extension UIColor {
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.index(rgba.startIndex, offsetBy: 1)
let hex = rgba.substring(from: index)
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hex.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "")
}
} else {
print("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix", terminator: "")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
| mit | 9d0cbb8cc510b5f3ff1cabb01a78e7db | 40.803571 | 125 | 0.476292 | 4.022337 | false | false | false | false |
marcoconti83/targone | Sources/ParsingStatus.swift | 1 | 5295 | //
// ParsingStatus.swift
// Targone
//
// Created by Marco Conti on 28/12/15.
// Copyright © 2015 Marco. All rights reserved.
//
import Foundation
extension Array where Element : CommandLineArgument {
/// Filter arguments by type
fileprivate func filterByType(_ type: ArgumentStyle) -> [CommandLineArgument] {
return self.filter { $0.style == type }
}
}
/// Status of the parsing of arguments
/// e.g. what was parsed so far, what is still missing, ...
struct ParsingStatus {
/// look up for optionals labels ("--foo")
fileprivate let argumentLookupByOptionalLabel : [String : CommandLineArgument]
/// arguments still to parse, by type of flag
fileprivate var nonPositionalArgumentsStillToParse = [ArgumentStyle : Set<CommandLineArgument>]()
/// positional arguments still to parse
fileprivate var positionalArgumentsStillToParse : [CommandLineArgument]
/// arguments parsed so far
var parsedArguments = [String : Any]()
/// next token generator
fileprivate var generator : IndexingIterator<[String]>
init(expectedArguments: [CommandLineArgument], tokensToParse: [String]) throws {
var lookupByOptionalLabel : [String : CommandLineArgument] = [:]
expectedArguments.filter { $0.style.hasFlagLikeName()}.forEach { arg in arg.allLabels.forEach {lookupByOptionalLabel[$0] = arg} }
self.argumentLookupByOptionalLabel = lookupByOptionalLabel
for argumentType in [ArgumentStyle.flag, ArgumentStyle.optional] {
nonPositionalArgumentsStillToParse[argumentType] = Set(expectedArguments.filterByType(argumentType))
}
self.positionalArgumentsStillToParse = expectedArguments.filterByType(.positional)
self.generator = tokensToParse.makeIterator()
try self.startParsing()
}
/// Parse the tokens
fileprivate mutating func startParsing() throws {
var nextToken = self.generator.next()
while (nextToken != nil) {
guard let token = nextToken else { break }
defer { nextToken = self.generator.next() }
try self.parseToken(token)
}
// are there still some argument? then it's an error
if self.positionalArgumentsStillToParse.count > 0 {
throw ArgumentParsingError.tooFewArguments
}
// are there still some flag arguments? then they are false
self.nonPositionalArgumentsStillToParse[.flag]!.forEach { self.setParsedValue(false, argument: $0) }
// are there still some optional arguments? then take the default, if any
if let remainingArgumentsWithPossibleDefaultValue = self.nonPositionalArgumentsStillToParse[.optional] {
remainingArgumentsWithPossibleDefaultValue.forEach {
if let defaultValue = $0.defaultValue, let value = defaultValue {
self.setParsedValue(value, argument: $0)
}
}
}
}
/// Set the parsed value for the argument
fileprivate mutating func setParsedValue(_ value: Any, argument: CommandLineArgument) {
argument.allLabels.forEach {
self.parsedArguments[$0] = value
}
}
/// parse a specific token
fileprivate mutating func parseToken(_ token: String) throws {
// what kind of argument?
if let argument = self.argumentLookupByOptionalLabel[token] {
switch(argument.style) {
case .optional:
self.nonPositionalArgumentsStillToParse[argument.style]!.remove(argument)
case .flag:
self.nonPositionalArgumentsStillToParse[argument.style]!.remove(argument)
default:
ErrorReporting.die("Was not expecting this type of argument: \(argument.style)")
}
if let parsed = try self.parseFlagStyleArgument(argument) {
parsedArguments[argument.label] = parsed
}
}
else {
// positional
guard let positional = self.positionalArgumentsStillToParse.first else { throw ArgumentParsingError.unexpectedPositionalArgument(token: token) }
self.positionalArgumentsStillToParse.removeFirst()
if let parsedValue = try self.parsePositionalArgument(positional, token: token) {
positional.allLabels.forEach { parsedArguments[$0] = parsedValue }
}
}
}
/// Attempts to parse a flag style argument and returns the value
fileprivate mutating func parseFlagStyleArgument(_ argument: CommandLineArgument) throws -> Any? {
if argument.style.requiresAdditionalValue() {
// optional
guard let followingToken = self.generator.next() , !followingToken.isFlagStyle()
else { throw ArgumentParsingError.parameterExpectedAfterToken(previousToken: argument.label) }
return try argument.parseValue(followingToken)
} else {
// flag
return true
}
}
fileprivate mutating func parsePositionalArgument(_ argument: CommandLineArgument, token: String) throws -> Any? {
return try argument.parseValue(token)
}
}
| mit | 91aa73d5982da28b0d311d3b4d4e94a1 | 39.723077 | 156 | 0.65017 | 5.061185 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/Integration/ConversationTests+ReceiptMode.swift | 1 | 3485 | ////
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
class ConversationTests_ReceiptMode: IntegrationTest {
override func setUp() {
super.setUp()
createSelfUserAndConversation()
createExtraUsersAndConversations()
createTeamAndConversations()
}
func testThatItUpdatesTheReadReceiptsSetting() {
// given
XCTAssert(login())
let sut = conversation(for: groupConversation)!
XCTAssertFalse(sut.hasReadReceiptsEnabled)
// when
sut.setEnableReadReceipts(true, in: userSession!) { (result) in
switch result {
case .failure:
XCTFail()
case .success:
break
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
// then
XCTAssertTrue(sut.hasReadReceiptsEnabled)
}
func testThatItUpdatesTheReadReceiptsSettingWhenOutOfSyncWithBackend() {
// given
XCTAssert(login())
let sut = conversation(for: groupConversation)!
XCTAssertFalse(sut.hasReadReceiptsEnabled)
mockTransportSession.performRemoteChanges { _ in
self.groupConversation.receiptMode = 1
}
// when
sut.setEnableReadReceipts(true, in: userSession!) { (result) in
switch result {
case .failure:
XCTFail()
case .success:
break
}
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
// then
XCTAssertTrue(sut.hasReadReceiptsEnabled)
}
func testThatItUpdatesTheReadReceiptsSettingWhenChangedRemotely() {
// given
XCTAssert(login())
let sut = conversation(for: groupConversation)!
XCTAssertFalse(sut.hasReadReceiptsEnabled)
// when
mockTransportSession.performRemoteChanges { (_) in
self.groupConversation.changeReceiptMode(by: self.user1, receiptMode: 1)
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
// then
XCTAssertTrue(sut.hasReadReceiptsEnabled)
}
func testThatItWeCantChangeTheReadReceiptsSettingInAOneToOneConversation() {
// given
XCTAssert(login())
let sut = conversation(for: selfToUser1Conversation)!
XCTAssertFalse(sut.hasReadReceiptsEnabled)
let expectation = self.expectation(description: "Invalid Operation")
// when
sut.setEnableReadReceipts(true, in: userSession!) { (result) in
switch result {
case .failure(ReadReceiptModeError.invalidOperation):
expectation.fulfill()
default:
XCTFail()
}
}
XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.1))
}
}
| gpl-3.0 | c4c482e1cc91b6e46c4e61f6204a8ecd | 30.396396 | 84 | 0.641033 | 5.217066 | false | true | false | false |
RichardAtDP/jbsignup | Sources/App/Routes.swift | 1 | 20508 | import Vapor
import Sessions
var lang = "en"
extension Droplet {
func setupRoutes() throws {
get("inscription") { req in
setLang(req.data["lang"])
var error:String?
if req.data["error"] != nil {
error = self.config["labels",lang,req.data["error"]!.string!]!.string
}
logIt("Inscription")
return try self.view.make("inscription",["label":self.config["labels",lang] as Any, "errors":error as Any, "lang":lang])
}
post("inscription") { req in
let emailProvided = req.data["email"]?.string
if (emailProvided?.range(of:"@")==nil || emailProvided?.range(of:".")==nil) {
return Response(redirect: "/inscription?error=INVALID_EMAIL")}
let Fam = try family.makeQuery().filter("email", .equals, emailProvided)
if try Fam.count() > 0 {
try sendEmail(familyId: (try Fam.first()!.id?.string!)!, Template: "EMAIL_EXISTS", drop: self, lang:lang, host:req.uri.hostname)
return Response(redirect: "/inscription?error=EMAIL_EXISTS")
}
let status = validate().verify(data: req.data, contentType: "inscription")
if status["status"] == "ok" {
let Family = try family(email: emailProvided!, CASL:req.data["CASL"]?.string,street: (req.data["street"]?.string)!, appartment: req.data["appartment"]?.string, city: (req.data["city"]?.string)!, postcode: (req.data["postcode"]?.string)!, homephone: req.data["homephone"]?.string, cellphone: req.data["cellphone"]?.string, emergencyContact: (req.data["emergencyContact"]?.string)!,how_hear:req.data["how_hear"]?.string,photos:req.data["photos"]?.string,lang:lang)
try Family.save()
let session = try req.assertSession()
try session.data.set("email", emailProvided)
logIt("Validated Family \(String(describing: emailProvided))")
return Response(redirect: "/family/\(String(describing: Family.id!.int!))/dancer")
} else {
logIt("Non-validated family \(String(describing: emailProvided))")
return try self.view.make("inscription", ["errors":status,"la!bel":self.config["labels",lang], "lang":lang])
}
}
get("family", ":id", "dancer") {req in
guard let familyid = req.parameters["id"]?.int else {
throw Abort.badRequest
}
let session = try req.assertSession()
if try family.makeQuery().filter("email",.equals,session.data["email"]!.string!).first()!.id!.int! != familyid {
throw Abort.badRequest
}
// Set default gender value
var setGender = JSON()
try setGender.set("female", "on")
return try self.view.make("dancer",["label":self.config["labels",lang],"Dancer":setGender, "lang":lang])
}
post("family", ":id", "dancer") { req in
guard let familyid = req.parameters["id"]?.string else {
throw Abort.badRequest
}
let session = try req.assertSession()
if try family.makeQuery().filter("email",.equals,session.data["email"]!.string!).first()!.id!.string! != familyid {
throw Abort.badRequest
}
let status = validate().verify(data: req.data, contentType: "dancer")
if status["status"] == "ok" {
let Dancer = try dancer(
FirstName:(req.data["FirstName"]?.string!)!
, LastName:(req.data["LastName"]?.string!)!
, Family:familyid
, DateOfBirth:(req.data["DateOfBirth"]?.string?.toDate())!
, Gender:(req.data["gender"]?.string!)!
, Allergies:req.data["Allergies"]?.string
)
try Dancer.save()
logIt("Dancer Saved for family \(familyid)")
return Response(redirect: "/family/\(String(describing: familyid))")
} else {
logIt("Dancer Errors for faimly \(familyid)")
return try self.view.make("dancer", ["errors":status,"label":self.config["labels",lang], "lang":lang])
}
}
get("family", ":id", "dancer", ":dancerId") {req in
guard let familyid = req.parameters["id"]?.int else {
throw Abort.badRequest
}
let session = try req.assertSession()
if try family.makeQuery().filter("email",.equals,session.data["email"]!.string!).first()!.id!.int! != familyid {
throw Abort.badRequest
}
guard let dancerid = req.parameters["dancerId"]?.int! else {
throw Abort.badRequest
}
guard var Dancer = try dancer.find(dancerid)?.makeJSON() else {
throw Abort.notFound
}
if try Dancer.get("Gender") == "male" {
try Dancer.set("male", true)
} else {
try Dancer.set("female", true)
}
return try self.view.make("dancer", ["Dancer": Dancer,"label":self.config["labels",lang], "lang":lang])
}
post("family", ":id", "dancer", ":dancerId") {req in
guard let familyid = req.parameters["id"]?.int else {
throw Abort.badRequest
}
let session = try req.assertSession()
if try family.makeQuery().filter("email",.equals,session.data["email"]!.string!).first()!.id!.int! != familyid {
throw Abort.badRequest
}
guard let dancerid = req.parameters["dancerId"]?.int! else {
throw Abort.badRequest
}
let status = validate().verify(data: req.data, contentType: "dancer")
if status["status"] == "ok" {
guard let Dancer = try dancer.find(dancerid) else {
throw Abort.notFound
}
Dancer.FirstName = (req.data["FirstName"]?.string!)!
Dancer.LastName = (req.data["LastName"]?.string!)!
Dancer.Gender = (req.data["gender"]?.string!)!
Dancer.DateOfBirth = (req.data["DateOfBirth"]?.string?.toDate())!
Dancer.Allergies = req.data["Allergies"]?.string
try Dancer.save()
logIt("Dancer Updated for family \(familyid)")
return Response(redirect: "/family/\(String(describing: familyid))")
} else {
return try self.view.make("dancer", ["errors":status,"label":self.config["labels",lang], "lang":lang])
}
}
get("family",":id","dancer", ":dancerId", "delete") { req in
guard let familyid = req.parameters["id"]?.int else {
throw Abort.badRequest
}
let session = try req.assertSession()
if try family.makeQuery().filter("email",.equals,session.data["email"]!.string!).first()!.id!.int! != familyid {
throw Abort.badRequest
}
guard let dancerid = req.parameters["dancerId"]?.int! else {
throw Abort.badRequest
}
guard let Dancer = try dancer.find(dancerid) else {
throw Abort.notFound
}
try Dancer.delete()
return Response(redirect: "/family/\(String(describing: familyid))")
}
get("family", ":id") { req in
guard let familyid = req.parameters["id"]?.int else {
throw Abort.badRequest
}
let session = try req.assertSession()
if (try family.makeQuery().filter("email",.equals,session.data["email"]?.string).first()?.id?.int ?? 0)! != familyid {
throw Abort.badRequest
}
let familyMembers = try dancer.makeQuery().filter("Family", .equals ,familyid).all().makeJSON()
logIt("Family Overview for familyId \(familyid)")
return try self.view.make("family", ["family":familyMembers, "familyid":familyid, "label":self.config["labels",lang], "lang":lang])
}
get("family",":id","lessons") { req in
guard let familyid = req.parameters["id"]?.int else {
throw Abort.badRequest
}
let session = try req.assertSession()
if (try family.makeQuery().filter("email",.equals,session.data["email"]?.string).first()?.id?.int ?? 0)! != familyid {
throw Abort.badRequest
}
let dancers = try formatLessonList(familyid:familyid, info:self)
return try self.view.make("lessons", ["familyid":familyid,"dancers":dancers,"selectLesson":lessonList(self), "label":self.config["labels",lang], "lang":lang])
}
post("family",":id","lessons") { req in
guard let familyid = req.parameters["id"]?.string else {
throw Abort.badRequest
}
let session = try req.assertSession()
if (try family.makeQuery().filter("email",.equals,session.data["email"]?.string).first()?.id?.string ?? "0")! != familyid {
throw Abort.badRequest
}
try saveLesson(proData:req.data, familyid:familyid)
try sendEmail(familyId: familyid, Template: "PRINT", drop: self, lang: lang, host:req.uri.hostname)
let dancers = try dancer.makeQuery().filter("Family", .equals, familyid).all().makeJSON()
return try self.view.make("confirm", ["familyid":familyid,"label":self.config["labels",lang],"dancers":dancers, "lang":lang, "host":req.uri.hostname])
}
get("family",":id", "lesson",":lessonId","delete") { req in
guard let familyid = req.parameters["id"]?.string else {
throw Abort.badRequest
}
let session = try req.assertSession()
if (try family.makeQuery().filter("email",.equals,session.data["email"]?.string).first()?.id?.string ?? "0")! != familyid {
throw Abort.badRequest
}
guard let lessonid = req.parameters["lessonId"]?.int else {
throw Abort.badRequest
}
try lesson.find(lessonid)?.delete()
return Response(redirect: "/family/\(String(describing: familyid))/lessons")
}
get("print",":printKey") { req in
guard let printKey = req.parameters["printKey"]?.string else {
throw Abort.badRequest
}
guard let dancer = try dancer.makeQuery().filter("printKey",.equals,printKey).first() else {
throw Abort.badRequest
}
let Family = try family.makeQuery().filter("id",.equals,dancer.Family.string).first()
lang = Family!.lang!
let lessons = try addLessonName(drop: self, familyId: (Family?.id?.string!)!, lang:lang)
logIt("Printed for dancer \(String(describing: dancer.id?.string!))")
return try self.view.make("print",["family":Family!.makeJSON(), "dancers":dancer.makeJSON(), "lessons":lessons, "config":self.config["lessons"]!.makeNode(in:nil), "label":self.config["labels",lang]!])
}
get("restart",":printKey") { req in
guard let printKey = req.parameters["printKey"]?.string else {
throw Abort.badRequest
}
guard let Family = try family.makeQuery().filter("printKey",.equals,printKey).first() else {
throw Abort.badRequest
}
let session = try req.assertSession()
try session.data.set("email", Family.email)
lang = Family.lang!
return Response(redirect: "/family/\(String(describing: Family.id!.string!))")
}
get("summary",":printKey") { req in
guard let printKey = req.parameters["printKey"]?.string else {
throw Abort.badRequest
}
guard let Family = try family.makeQuery().filter("printKey",.equals,printKey).first() else {
throw Abort.badRequest
}
let session = try req.assertSession()
try session.data.set("email", Family.email)
lang = Family.lang!
let dancers = try dancer.makeQuery().filter("Family", .equals, Family.id!.string).all().makeJSON()
logIt("Confirmation screen from email for family \(String(describing: Family.id?.string!))")
return try self.view.make("confirm", ["familyid":Family.id!.string,"label":self.config["labels",lang],"dancers":dancers, "lang":lang, "host":req.uri.hostname])
}
get("family",":id","summary") {req in
guard let familyid = req.parameters["id"]?.string else {
throw Abort.badRequest
}
let session = try req.assertSession()
if (try family.makeQuery().filter("email",.equals,session.data["email"]?.string).first()?.id?.string ?? "0")! != familyid {
throw Abort.badRequest
}
try sendEmail(familyId: familyid, Template: "PRINT", drop: self, lang: lang, host:req.uri.hostname)
let dancers = try dancer.makeQuery().filter("Family", .equals, familyid).all().makeJSON()
logIt("Confirmation screen for family \(String(describing: familyid))")
return try self.view.make("confirm", ["familyid":familyid,"label":self.config["labels",lang],"dancers":dancers, "lang":lang, "host":req.uri.hostname])
}
get("administration","identify") { req in
setLang(req.data["lang"])
return try self.view.make("administration/identify", ["lang":lang,"label":self.config["labels",lang]])
}
post("administration","identify") { req in
guard let suppliedEmail = req.data["email"]?.string else {
throw Abort.badRequest
}
for useremail in (self.config["administration","useremails"]?.array)! {
print(useremail)
if useremail.string == suppliedEmail {
let warning = self.config["labels",lang,"identify_email"]
try sendAdminEmail(Template: "ADMINLINK", drop: self, lang: lang, host: req.uri.hostname, email: suppliedEmail)
return try self.view.make("administration/identify", ["lang":lang,"label":self.config["labels",lang],"warning":warning])
}
}
return "Unable to process"
}
get("administration",":securityKey") {req in
guard let securityKey = req.parameters["securityKey"]?.string else {
throw Abort.badRequest
}
var status = "UNAUTHORIZED"
for useremail in (self.config["administration","useremails"]?.array)! {
if try self.hash.check(useremail.string!.makeBytes(), matchesHash: securityKey.makeBytes()) {
status = "OK"
}
}
if status == "UNAUTHORIZED" {return "Bad access"}
var adminList = [JSON]()
var sortType = "email"
if req.data["sort"]?.string == "created" {
sortType = "created_At"
}
if req.data["sort"]?.string == "updated" {
sortType = "updated_At"
}
if req.data["sort"]?.string == "email" {
sortType = "email"
}
let families = try family.makeQuery()
.sort(sortType, .ascending)
.all().array
for Family in families {
var FamilyInfo = JSON()
let dancers = try dancer.makeQuery().filter("Family", .equals, Family.id?.string).all().array
FamilyInfo = try Family.makeJSON()
try FamilyInfo.set("dancers", dancers)
let reminderCounter = try counter.makeQuery().filter("objectId", .equals, Family.id?.string).first()?.counter
try FamilyInfo.set("reminderCounter",reminderCounter)
adminList.append(FamilyInfo)
}
return try self.view.make("administration/administration", ["adminList":adminList, "lang":lang,"label":self.config["labels",lang],"securityKey":securityKey])
}
get("administration","reminder",":securityKey",":familyid") {req in
guard let securityKey = req.parameters["securityKey"]?.string else {
throw Abort.badRequest
}
guard let familyid = req.parameters["familyid"]?.string else {
throw Abort.badRequest
}
var status = "UNAUTHORIZED"
for useremail in (self.config["administration","useremails"]?.array)! {
if try self.hash.check(useremail.string!.makeBytes(), matchesHash: securityKey.makeBytes()) {
status = "OK"
}
}
if status == "UNAUTHORIZED" {return "Bad access"}
var Template = ""
if try dancer.makeQuery().filter("Family", .equals, familyid).count() == 0 { Template = "ADDDANCERS"} else { Template = "REMINDER"}
let familyLang = try family.find(familyid)?.lang
try sendEmail(familyId: familyid, Template: Template, drop: self, lang: familyLang!, host:req.uri.hostname)
let existingCounter = try counter.makeQuery().filter("objectId", .equals, familyid).first()
let count = 1
if existingCounter == nil {
let _ = try counter(objectId: familyid, counter: 1).save()
} else {
existingCounter?.counter += 1
try existingCounter?.save()
}
return String(describing: existingCounter?.counter ?? count)
}
try resource("posts", PostController.self)
}
}
func setLang(_ content:Node?) {
if content?.string != nil {
if ["en","fr"].contains(content!.string!) {
lang = (content!.string!)
print(lang)
}
}
}
| mit | 05067c1ee0bf8bb6c2c96b57f4d6cf99 | 38.287356 | 478 | 0.489711 | 5.030169 | false | false | false | false |
ximximik/DPTableView | DPTableView/Classes/DPTableView.swift | 1 | 9818 | //
// Created by Danil Pestov on 06.12.16.
// Copyright (c) 2016 HOKMT. All rights reserved.
//
import RxSwift
import RxCocoa
import DZNEmptyDataSet
import RxDataSources
public protocol DPTableViewElementCellProtocol {
associatedtype ViewModel
static var estimatedHeight: CGFloat { get }
func set(viewModel: ViewModel)
}
//MARK: -
open class DPTableView: UITableView {
private var disposeBag = DisposeBag()
///CellType saved from setup method
open var cellType: AnyClass?
///HeaderType saved from setup method
open var headerType: DPSectionHeader.Type?
///Text, that showed when row count == 0
open var noItemsText: String = ""
///If true then when selected cell will be auto deselected
open var isAutoDeselect: Bool = true
//MARK: Initialization
override open func awakeFromNib() {
super.awakeFromNib()
setupTableView()
}
private func setupTableView() {
self.emptyDataSetSource = self
self.emptyDataSetDelegate = self
self.rowHeight = UITableView.automaticDimension
self.tableFooterView = UIView()
self.delegate = self
}
//MARK: Sizing
///Compress and correct sizing header of tableView
open func sizeHeaderToFit() {
DispatchQueue.main.async {
if let headerView = self.tableHeaderView {
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
self.tableHeaderView = headerView
}
}
}
//MARK: Setups
///Basic setup for RxTableView, that same for non-sectioned and sectioned tables.
private func basicSetup<CellType: UITableViewCell>(cellType: CellType.Type, isLoadFromNib: Bool = false)
where CellType: DPTableViewElementCellProtocol {
dataSource = nil
estimatedRowHeight = CellType.estimatedHeight
self.cellType = cellType
if isLoadFromNib {
register(cellType.nib, forCellReuseIdentifier: cellType.describing)
}
layoutIfNeeded()
}
/**
Setup table view with RxDataSource
- parameter cellType: Type of cell, that will be used for present data in table. Must conform **SBTableViewElementCellProtocol**.
- parameter viewModels: Observable of array of viewModels, that will be used for cell configuration.
- parameter isLoadFromNib: If **true**, view for cell will be loaded from *xib*, that named same as cell type. See: `UIView.nib`.
- parameter customCellSetup: Custom configuration block, called for each cell on reload data for cell.
*/
open func setup<CellType: UITableViewCell, ViewModel>(cellType: CellType.Type,
viewModels: Observable<[ViewModel]>,
isLoadFromNib: Bool = false,
customCellSetup: ((CellType, IndexPath) -> Void)? = nil)
where CellType: DPTableViewElementCellProtocol, CellType.ViewModel == ViewModel {
basicSetup(cellType: cellType, isLoadFromNib: isLoadFromNib)
//Cell configuration
viewModels
.bind(to: self.rx.items(cellIdentifier: cellType.describing, cellType: cellType))
{ row, viewModel, cell in
cell.set(viewModel: viewModel)
if let customCellSetup = customCellSetup {
customCellSetup(cell, IndexPath(row: row, section: 0))
}
}
.disposed(by: disposeBag)
}
/**
Setup table view with RxTableViewSectionedReloadDataSource.
- parameter cellType: Type of cell, that will be used for present data in table. Must conform **SBTableViewElementCellProtocol**.
- parameter items: Observable of array of section items, that will be used for cell configuration and header titles. Section items must conform **SBSectionItemProtocol**.
- parameter isLoadFromNib: If **true**, view for cell will be loaded from *xib*, that named same as cell type. See: `UIView.nib`.
- parameter headerType: If not nil, view loaded from xib with that type will be used for section header.
- parameter customCellSetup: Custom configuration block, called for each cell on reload data for cell.
*/
open func setup<CellType: UITableViewCell, SectionItem:DPSectionItemProtocol, HeaderType:DPSectionHeader>(cellType: CellType.Type,
items: Observable<[SectionItem]>,
isLoadFromNib: Bool = false,
headerType: HeaderType.Type? = nil,
dataSourceSetup: ((RxTableViewSectionedAnimatedDataSource<SectionItem>) -> ())? = nil,
customCellSetup: ((CellType, IndexPath) -> Void)? = nil)
where CellType: DPTableViewElementCellProtocol, CellType.ViewModel == SectionItem.Item, SectionItem: AnimatableSectionModelType {
basicSetup(cellType: cellType, isLoadFromNib: isLoadFromNib)
//Register header
if let headerType = headerType {
self.headerType = headerType
register(headerType.nib, forHeaderFooterViewReuseIdentifier: headerType.describing)
}
//Cell configurations
let dataSource = RxTableViewSectionedAnimatedDataSource<SectionItem>(configureCell: { dataSource, tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier:cellType.describing, for: indexPath)
if let cell = cell as? CellType {
cell.set(viewModel: item)
if let customCellSetup = customCellSetup {
customCellSetup(cell, indexPath)
}
}
return cell
})
//Section titles
dataSource.titleForHeaderInSection = { dateSource, section in
return dataSource[section].header
}
dataSourceSetup?(dataSource)
items
.bind(to: self.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
open func setupWithDiff<CellType: UITableViewCell, ViewModel>(cellType: CellType.Type,
viewModels: Observable<[ViewModel]>,
isLoadFromNib: Bool = false,
dataSourceSetup: ((RxTableViewSectionedAnimatedDataSource<DPSectionModel<Int, ViewModel>>) -> ())? = nil,
customCellSetup: ((CellType, IndexPath) -> Void)? = nil)
where CellType: DPTableViewElementCellProtocol, CellType.ViewModel == ViewModel, ViewModel: Equatable & IdentifiableType {
let items = viewModels.map { [DPSectionModel(identity: 0, header: nil, items: $0)] }
setup(cellType: cellType, items: items, isLoadFromNib: isLoadFromNib, headerType: nil, dataSourceSetup: dataSourceSetup, customCellSetup: customCellSetup)
}
}
//MARK: - UITableViewDelegate
extension DPTableView: UITableViewDelegate {
open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let title = dataSource?.tableView?(self, titleForHeaderInSection: section)
if let _ = title {
return UITableView.automaticDimension
}
return 0
}
open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let headerType = headerType, let dataSource = dataSource {
let header = dequeueReusableHeaderFooterView(withIdentifier: headerType.describing) as? DPSectionHeader
let title = dataSource.tableView?(self, titleForHeaderInSection: section)
header?.set(title: title)
return header
}
return nil
}
open func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
let title = dataSource?.tableView?(self, titleForHeaderInSection: section)
if let _ = title {
return 40
}
return 0
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if isAutoDeselect {
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
//MARK: - DZNEmptyDataSet
extension DPTableView: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
open func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)]
return NSAttributedString(string: noItemsText, attributes: attributes)
}
}
| mit | 55e070ab6b8cca099ec72ad7f8860eff | 45.311321 | 196 | 0.586066 | 6.128589 | false | false | false | false |
macressler/Swifter-Reverse-Auth | Swifter-Reverse-Auth.swift | 1 | 3808 | // Swifter-Reverse-Auth.swift
//
// Copyright (c) 2015 Gurpartap Singh (http://github.com/Gurpartap)
//
// 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
#if os(iOS)
import SwifteriOS
#else
import SwifterOSX
#endif
let swifterApiURL = NSURL(string: "https://api.twitter.com")!
public extension Swifter {
public func postReverseOAuthTokenRequest(success: (authenticationHeader: String) -> Void, failure: FailureHandler?) {
let path = "/oauth/request_token"
var parameters = Dictionary<String, AnyObject>()
parameters["x_auth_mode"] = "reverse_auth"
self.client.post(path, baseURL: swifterApiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { data, response in
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!
success(authenticationHeader: responseString)
}, failure: failure)
}
public func postReverseAuthAccessTokenWithAuthenticationHeader(authenticationHeader: String, success: TokenSuccessHandler, failure: FailureHandler?) {
let path = "/oauth/access_token"
let shortHeader = authenticationHeader.stringByReplacingOccurrencesOfString("OAuth ", withString: "")
let authenticationHeaderDictionary = shortHeader.parametersDictionaryFromCommaSeparatedParametersString()
let consumerKey = authenticationHeaderDictionary["oauth_consumer_key"]!
var parameters = Dictionary<String, AnyObject>()
parameters["x_reverse_auth_target"] = consumerKey
parameters["x_reverse_auth_parameters"] = authenticationHeader
self.client.post(path, baseURL: swifterApiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { data, response in
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
let accessToken = SwifterCredential.OAuthAccessToken(queryString: responseString!)
success(accessToken: accessToken, response: response)
}, failure: failure)
}
}
extension String {
func parametersDictionaryFromCommaSeparatedParametersString() -> Dictionary<String, String> {
var dict = Dictionary<String, String>()
for parameter in self.componentsSeparatedByString(", ") {
// transform k="v" into {'k':'v'}
let keyValue = parameter.componentsSeparatedByString("=")
if keyValue.count != 2 {
continue
}
let value = keyValue[1].stringByReplacingOccurrencesOfString("\"", withString:"")
dict.updateValue(value, forKey: keyValue[0])
}
return dict
}
}
| mit | ca3679437f587a2032732a871a4aaffd | 40.391304 | 154 | 0.695641 | 5.017128 | false | false | false | false |
KrishMunot/swift | stdlib/public/core/ArrayCast.swift | 1 | 7036 | //===--- ArrayCast.swift - Casts and conversions for Array ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Because NSArray is effectively an [AnyObject], casting [T] -> [U]
// is an integral part of the bridging process and these two issues
// are handled together.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
// FIXME: These need to be implemented even for non-objc:
// rdar://problem/18881196
internal enum _ValueOrReference {
case reference, value
internal init<T>(_: T.Type) {
self = _isClassOrObjCExistential(T.self) ? .reference : .value
}
}
internal enum _BridgeStyle {
case verbatim, explicit
internal init<T>(_: T.Type) {
self = _isBridgedVerbatimToObjectiveC(T.self) ? .verbatim : .explicit
}
}
//===--- Forced casts: [T] as! [U] ----------------------------------------===//
/// Implements `source as! [TargetElement]`.
///
/// - Precondition: At least one of `SourceElement` and `TargetElement` is a
/// class type or ObjC existential. May trap for other "valid" inputs when
/// `TargetElement` is not bridged verbatim, if an element can't be converted.
public func _arrayForceCast<SourceElement, TargetElement>(
_ source: Array<SourceElement>
) -> Array<TargetElement> {
switch (
_ValueOrReference(SourceElement.self), _BridgeStyle(TargetElement.self)
) {
case (.reference, .verbatim):
let native = source._buffer.requestNativeBuffer()
if _fastPath(native != nil) {
if _fastPath(native!.storesOnlyElementsOfType(TargetElement.self)) {
// A native buffer that is known to store only elements of the
// TargetElement can be used directly
return Array(source._buffer.cast(toBufferOf: TargetElement.self))
}
// Other native buffers must use deferred element type checking
return Array(
source._buffer.downcast(
toBufferWithDeferredTypeCheckOf: TargetElement.self))
}
// All non-native buffers use deferred element typechecking
return Array(_immutableCocoaArray: source._buffer._asCocoaArray())
case (.reference, .explicit):
let result: [TargetElement]? = _arrayConditionalBridgeElements(source)
_precondition(result != nil, "array cannot be bridged from Objective-C")
return result!
case (.value, .verbatim):
var buf = _ContiguousArrayBuffer<TargetElement>(
uninitializedCount: source.count, minimumCapacity: 0)
let _: Void = buf.withUnsafeMutableBufferPointer {
var p = $0.baseAddress
for value in source {
let bridged: AnyObject? = _bridgeToObjectiveC(value)
_precondition(
bridged != nil, "array element cannot be bridged to Objective-C")
// FIXME: should be an unsafeDowncast.
p.initialize(with: unsafeBitCast(bridged!, to: TargetElement.self))
p += 1
}
}
return Array(_ArrayBuffer(buf, shiftedToStartIndex: 0))
case (.value, .explicit):
_sanityCheckFailure(
"Force-casting between Arrays of value types not prevented at compile-time"
)
}
}
//===--- Conditional casts: [T] as? [U] -----------------------------------===//
/// Implements the semantics of `x as? [TargetElement]` where `x` has type
/// `[SourceElement]` and `TargetElement` is a verbatim-bridged trivial subtype of
/// `SourceElement`.
///
/// Returns an Array<TargetElement> containing the same elements as a
///
/// O(1) if a's buffer elements are dynamically known to have type
/// TargetElement or a type derived from TargetElement. O(N)
/// otherwise.
internal func _arrayConditionalDownCastElements<SourceElement, TargetElement>(
_ a: Array<SourceElement>
) -> [TargetElement]? {
_sanityCheck(_isBridgedVerbatimToObjectiveC(SourceElement.self))
_sanityCheck(_isBridgedVerbatimToObjectiveC(TargetElement.self))
if _fastPath(!a.isEmpty) {
let native = a._buffer.requestNativeBuffer()
if _fastPath(native != nil) {
if native!.storesOnlyElementsOfType(TargetElement.self) {
return Array(a._buffer.cast(toBufferOf: TargetElement.self))
}
return nil
}
// slow path: we store an NSArray
// We can skip the check if TargetElement happens to be AnyObject
if !(AnyObject.self is TargetElement.Type) {
for element in a {
if !(element is TargetElement) {
return nil
}
}
}
return Array(a._buffer.cast(toBufferOf: TargetElement.self))
}
return []
}
/// Try to convert the source array of objects to an array of values
/// produced by bridging the objects from Objective-C to `TargetElement`.
///
/// - Precondition: SourceElement is a class type.
/// - Precondition: TargetElement is bridged non-verbatim to Objective-C.
/// O(n), because each element must be bridged separately.
internal func _arrayConditionalBridgeElements<SourceElement, TargetElement>(
_ source: Array<SourceElement>
) -> Array<TargetElement>? {
_sanityCheck(_isBridgedVerbatimToObjectiveC(SourceElement.self))
_sanityCheck(!_isBridgedVerbatimToObjectiveC(TargetElement.self))
let buf = _ContiguousArrayBuffer<TargetElement>(
uninitializedCount: source.count, minimumCapacity: 0)
var p = buf.firstElementAddress
ElementwiseBridging:
repeat {
for object: SourceElement in source {
let value = Swift._conditionallyBridgeFromObjectiveC(
unsafeBitCast(object, to: AnyObject.self), TargetElement.self)
if _slowPath(value == nil) {
break ElementwiseBridging
}
p.initialize(with: value!)
p += 1
}
return Array(_ArrayBuffer(buf, shiftedToStartIndex: 0))
}
while false
// Don't destroy anything we never created.
buf.count = p - buf.firstElementAddress
// Report failure
return nil
}
/// Implements `source as? [TargetElement]`: convert each element of
/// `source` to a `TargetElement` and return the resulting array, or
/// return `nil` if any element fails to convert.
///
/// - Precondition: `SourceElement` is a class or ObjC existential type.
/// O(n), because each element must be checked.
public func _arrayConditionalCast<SourceElement, TargetElement>(
_ source: [SourceElement]
) -> [TargetElement]? {
switch (_ValueOrReference(SourceElement.self), _BridgeStyle(TargetElement.self)) {
case (.value, _):
_sanityCheckFailure(
"Conditional cast from array of value types not prevented at compile-time")
case (.reference, .verbatim):
return _arrayConditionalDownCastElements(source)
case (.reference, .explicit):
return _arrayConditionalBridgeElements(source)
}
}
#endif
| apache-2.0 | 6855d408c80ebed49d3618c15b1fd525 | 34.535354 | 84 | 0.668562 | 4.419598 | false | false | false | false |
adrfer/swift | validation-test/compiler_crashers_fixed/01651-getselftypeforcontainer.swift | 2 | 433 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
<T, i : BooleanType, x }
func c] = B
}
}
}
protocol P {
typealias C = A(2, c]
extension NSSet {
class b()
case s: T, V, ().B == B
convenience init(t.h: ("cd"foo"
protocol A : C {
t.g == B<h = f, 3)
class func a<d(b[se
| apache-2.0 | 3cbfd487b9a24bb51915fa74126dba17 | 20.65 | 87 | 0.658199 | 2.886667 | false | true | false | false |
scarlett2003/MRTSwift | MRT/AppDelegate.swift | 1 | 2858 | //
// AppDelegate.swift
// MRT
//
// Created by evan3rd on 2015/5/13.
// Copyright (c) 2015年 evan3rd. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
DepartureManager.sharedInstance.syncStationData(completionBlock: { () -> Void in
DepartureManager.sharedInstance.syncMRTDepartureTime(completionBlock: { () -> Void in
println("==========")
for var i = 0; i < DepartureManager.sharedInstance.stations.count; ++i {
var st = DepartureManager.sharedInstance.stations[i]
println("\(st.cname) \(st.code)")
for p:Platform in st.redLine {
println("\(p.destination) \(p.arrivalTime) \(p.nextArrivalTime)")
}
for p:Platform in st.orangeLine {
println("\(p.destination) \(p.arrivalTime) \(p.nextArrivalTime)")
}
println("==========")
}
}, errorBlock: nil)
}, errorBlock: nil)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | adb8e3e1e3d1d36852d708af8f6bf61d | 42.272727 | 281 | 0.715686 | 5.054867 | false | false | false | false |
ngageoint/fog-machine | FogMachine/FogMachine/PeerPack/Session.swift | 1 | 5957 | //
// Session.swift
//
// Created by JP Simard on 11/3/14.
// Copyright (c) 2014 JP Simard. All rights reserved.
//
import Foundation
import MultipeerConnectivity
/**
Part of PeerPack used by FogMachine. Developers using FogMachine will not need to use this.
*/
public protocol SessionDelegate {
func connecting(myPeerID: MCPeerID, toPeer peer: MCPeerID)
func connected(myPeerID: MCPeerID, toPeer peer: MCPeerID)
func disconnected(myPeerID: MCPeerID, fromPeer peer: MCPeerID)
func receivedData(myPeerID: MCPeerID, data: NSData, fromPeer peer: MCPeerID)
func finishReceivingResource(myPeerID: MCPeerID, resourceName: String, fromPeer peer: MCPeerID, atURL localURL: NSURL)
}
/**
Part of PeerPack. Developers using FogMachine will not need to use this.
*/
public class Session: NSObject, MCSessionDelegate {
var delegate: SessionDelegate?
var myPeerSessions = [String: MCSession]()
public let myPeerId = MCPeerID(displayName: PeerPack.myName)
public init(displayName: String, delegate: SessionDelegate? = nil) {
self.delegate = delegate
super.init()
myPeerSessions[String(myPeerSessions.count)] = self.availableSession(displayName, peerName: displayName)
}
public func disconnect(displayName: String) {
//self.delegate = nil
//mcSession.delegate = nil
//mcSession.disconnect()
//myPeerSessions[displayName]?.delegate = nil
//myPeerSessions[displayName]?.disconnect()
if let session = self.getSession(displayName) {
session.delegate = nil
session.disconnect()
myPeerSessions.removeValueForKey(displayName)
}
}
func getSession(displayName: String) -> MCSession? {
guard myPeerSessions.indexForKey(displayName) != nil else {
return nil
}
return myPeerSessions[displayName]!
}
func getPeerId() -> MCPeerID {
return myPeerId
}
// Some functions below adopted from:
// http://stackoverflow.com/questions/23014523/multipeer-connectivity-framework-lost-peer-stays-in-session/23017463#23017463
public func allConnectedPeers() -> [MCPeerID] {
var allPeers: [MCPeerID] = []
for (_, session) in myPeerSessions {
for peer in session.connectedPeers {
allPeers.append(peer)
}
}
return allPeers
}
public func allConnectedSessions() -> [MCSession] {
var allSessions: [MCSession] = []
for (_, session) in myPeerSessions {
allSessions.append(session)
}
return allSessions
}
func availableSession(displayName: String, peerName: String) -> MCSession {
var notFound = true
var availableSession: MCSession? = nil
//Try and use an existing session (_sessions is a mutable array)
for (_, session) in myPeerSessions {
if (session.connectedPeers.count < kMCSessionMaximumNumberOfPeers) {
notFound = false
availableSession = session
break
}
}
if notFound {
availableSession = self.newSession(displayName, peerName: peerName)
}
return availableSession!
}
func newSession(displayName: String, peerName: String) -> MCSession {
let newSession = MCSession(peer: myPeerId, securityIdentity: nil, encryptionPreference: MCEncryptionPreference.Required)
newSession.delegate = self
myPeerSessions[String(myPeerSessions.count)] = newSession
return newSession
}
func sendData(data: NSData, toPeers peerIDs: [MCPeerID], withMode: MCSessionSendDataMode) {
guard peerIDs.count != 0 else {
return
}
// Match up peers to their session
for session: MCSession in allConnectedSessions() {
do {
try session.sendData(data, toPeers: peerIDs, withMode: withMode)
} catch let errors as NSError{
NSLog("Session error in sendData: \(errors.localizedDescription)")
}
}
}
// MARK: MCSessionDelegate
public func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) {
switch state {
case .Connecting:
delegate?.connecting(session.myPeerID, toPeer: peerID)
case .Connected:
//myPeerSessions[session.myPeerID.displayName] = session
delegate?.connected(session.myPeerID, toPeer: peerID)
case .NotConnected:
//self.disconnect(peerID.displayName)
delegate?.disconnected(session.myPeerID, fromPeer: peerID)
}
}
public func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) {
self.delegate?.receivedData(session.myPeerID, data: data, fromPeer: peerID)
}
public func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
// unused
}
public func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) {
// unused
}
public func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) {
// unused
if error != nil {
debugPrint("Error didFinishReceivingResourceWithName: \(error)")
}
if (error == nil) {
delegate?.finishReceivingResource(session.myPeerID, resourceName: resourceName, fromPeer: peerID, atURL: localURL)
}
}
public func session(session: MCSession, didReceiveCertificate certificate: [AnyObject]?, fromPeer peerID: MCPeerID, certificateHandler: (Bool) -> Void) {
certificateHandler(true)
}
}
| mit | 67f4881901b4ac0bb16586e4de76a4ab | 33.235632 | 179 | 0.656371 | 4.955907 | false | false | false | false |
LeLuckyVint/MessageKit | Sources/Protocols/MessagesDisplayDelegate.swift | 1 | 4887 | /*
MIT License
Copyright (c) 2017 MessageKit
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 TextMessageDisplayDelegate: class {
func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor
func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType]
}
public extension TextMessageDisplayDelegate {
func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
guard let dataSource = messagesCollectionView.messagesDataSource else { return .darkText }
return dataSource.isFromCurrentSender(message: message) ? .white : .darkText
}
func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType] {
return [.url, .address, .phoneNumber, .date]
}
}
public protocol MessagesDisplayDelegate: class {
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle
func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor
func messageHeaderView(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageHeaderView
func shouldDisplayHeader(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> Bool
func messageFooterView(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageFooterView
}
public extension MessagesDisplayDelegate {
func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
return .bubble
}
func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
switch message.data {
case .emoji:
return .clear
default:
guard let dataSource = messagesCollectionView.messagesDataSource else { return .white }
return dataSource.isFromCurrentSender(message: message) ? .outgoingGreen : .incomingGray
}
}
func messageHeaderView(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageHeaderView {
let header = messagesCollectionView.dequeueReusableHeaderView(MessageDateHeaderView.self, for: indexPath)
header.dateLabel.text = MessageKitDateFormatter.shared.string(from: message.sentDate)
return header
}
func shouldDisplayHeader(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> Bool {
guard let dataSource = messagesCollectionView.messagesDataSource else { return false }
if indexPath.section == 0 { return false }
let previousSection = indexPath.section - 1
let previousIndexPath = IndexPath(item: 0, section: previousSection)
let previousMessage = dataSource.messageForItem(at: previousIndexPath, in: messagesCollectionView)
let timeIntervalSinceLastMessage = message.sentDate.timeIntervalSince(previousMessage.sentDate)
return timeIntervalSinceLastMessage >= messagesCollectionView.showsDateHeaderAfterTimeInterval
}
func messageFooterView(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageFooterView {
return messagesCollectionView.dequeueReusableFooterView(MessageFooterView.self, for: indexPath)
}
}
| mit | 4fa0eef225edc810f293105b6e5835b9 | 48.363636 | 151 | 0.770821 | 5.41196 | false | false | false | false |
DragonCherry/CameraPreviewController | CameraPreviewController/Classes/CameraPreviewController.swift | 1 | 11692 | //
// CameraPreviewController.swift
// Pods
//
// Created by DragonCherry on 1/5/17.
//
//
import UIKit
import CoreMotion
import TinyLog
import PureLayout
import GPUImage
// MARK: - Declaration for CameraPreviewControllerDelegate
public protocol CameraPreviewControllerDelegate: class {
func cameraPreview(_ controller: CameraPreviewController, didSaveVideoAt url: URL)
func cameraPreview(_ controller: CameraPreviewController, didFailSaveVideoWithError error: Error)
func cameraPreview(_ controller: CameraPreviewController, willOutput sampleBuffer: CMSampleBuffer, with sequence: UInt64)
func cameraPreview(_ controller: CameraPreviewController, willFocusInto tappedLocationInView: CGPoint, tappedLocationInImage: CGPoint)
}
// MARK: - Declaration for CameraPreviewControllerLayoutSource
public protocol CameraPreviewControllerLayoutSource: class {
func cameraPreviewNeedsLayout(_ controller: CameraPreviewController, preview: GPUImageView)
}
// MARK: - Declaration for CameraPreviewControllerFaceDetectionDelegate
public protocol CameraPreviewControllerFaceDetectionDelegate: class {
func cameraPreview(_ controller: CameraPreviewController, detected faceFeatures: [CIFaceFeature]?, aperture: CGRect, orientation: UIDeviceOrientation)
}
// MARK: - Declaration for CameraPreviewController
open class CameraPreviewController: UIViewController {
// MARK: Delegates
open weak var delegate: CameraPreviewControllerDelegate?
open weak var layoutSource: CameraPreviewControllerLayoutSource?
open weak var faceDetectionDelegate: CameraPreviewControllerFaceDetectionDelegate?
// MARK: Layout
fileprivate var didSetupConstraints = false
fileprivate var customConstraints = false
// MARK: Basic
open var cameraPosition: AVCaptureDevicePosition = .front
open var capturePreset: String = AVCaptureSessionPresetHigh
open var captureSequence: UInt64 = 0
open var fillMode: GPUImageFillModeType = kGPUImageFillModePreserveAspectRatioAndFill
open var resolution: CGSize = .zero
let preview: GPUImageView = { return GPUImageView.newAutoLayout() }()
var camera: GPUImageStillCamera!
// MARK: Face
var faceDetector: CIDetector?
var faceViews = [UIView]()
/** Setting this true invokes cameraPreviewDetectedFaces one per faceDetectFrequency frame. Default frequency is 10, if you want to detect face more frequent, set faceDetectFrequency as smaller number. */
open var isFaceDetectorEnabled: Bool = false {
willSet(isEnabled) {
if isEnabled {
if faceDetector == nil {
let detectorOptions = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: detectorOptions)
}
} else {
removeFaceViews()
}
}
}
/** Setting smaller number makes it detect face more frequent. Regards zero as default value 30. */
open var faceDetectFrequency: UInt = 30
// MARK: Filter
/** Default filter for capturing still image, and this is recommeded by BradLarson in https://github.com/BradLarson/GPUImage/issues/1874 */
var defaultFilter = GPUImageFilter()
var filters = [GPUImageFilter]()
var lastFilter: GPUImageOutput { return filters.last ?? defaultFilter }
// MARK: Focus
open var isTapFocusingEnabled: Bool = true {
didSet {
if isTapFocusingEnabled {
setupTapFocusing()
} else {
clearTapFocusing()
}
}
}
var tapFocusingRecognizer: UITapGestureRecognizer?
// MARK: Video
var motionManager = CMMotionManager()
var videoWriter: GPUImageMovieWriter?
var videoUrl: URL?
open var isRecordingVideo: Bool {
if let videoWriter = self.videoWriter, let _ = self.videoUrl, !videoWriter.isPaused {
return true
} else {
return false
}
}
// MARK: Pinch to Zoom
open var isPinchZoomingEnabled: Bool = true {
didSet {
if isPinchZoomingEnabled {
setupPinchZooming()
} else {
clearPinchZooming()
}
}
}
var pinchToZoomGesture: UIPinchGestureRecognizer?
var pivotPinchScale: CGFloat = 1
// MARK: - Lifecycle for UIViewController
override open func loadView() {
super.loadView()
view = UIView()
view.backgroundColor = .white
}
override open func viewDidLoad() {
super.viewDidLoad()
setupPreview()
setupCamera()
setupNotification()
startCapture()
view.setNeedsUpdateConstraints()
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override open func updateViewConstraints() {
if !didSetupConstraints {
if !customConstraints {
preview.autoPinEdgesToSuperviewEdges()
}
didSetupConstraints = true
}
super.updateViewConstraints()
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
deinit {
logd("Released \(type(of: self)).")
clearTapFocusing()
clearCamera()
clearNotification()
}
}
// MARK: - Lifecycle
extension CameraPreviewController: UIGestureRecognizerDelegate {
func setupPreview() {
// layout
layoutSource?.cameraPreviewNeedsLayout(self, preview: preview)
if let _ = preview.superview {
customConstraints = true
} else {
view.addSubview(preview)
}
// config fill mode
preview.fillMode = fillMode
// transform preview by camera position
switch cameraPosition {
case .back:
preview.transform = CGAffineTransform.identity
default:
preview.transform = preview.transform.scaledBy(x: -1, y: 1)
}
// tap to focus
if isTapFocusingEnabled {
setupTapFocusing()
}
// pinch to zoom
if isPinchZoomingEnabled {
setupPinchZooming()
}
}
func setupCamera() {
clearCamera()
camera = GPUImageStillCamera(sessionPreset: capturePreset, cameraPosition: cameraPosition)
switch cameraPosition {
case .back:
camera.outputImageOrientation = .portrait
default:
camera.outputImageOrientation = .portrait
}
camera.delegate = self
camera.addTarget(defaultFilter)
defaultFilter.addTarget(preview)
}
func setupNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: Notification.Name.UIApplicationWillResignActive, object: nil)
}
open func flipCamera() {
switch cameraPosition {
case .back:
cameraPosition = .front
default:
cameraPosition = .back
}
camera.rotateCamera()
setupPreview()
}
open func pauseCapture() {
camera.pauseCapture()
}
open func resumeCapture() {
camera.resumeCameraCapture()
}
open func startCapture() {
if !camera.captureSession.isRunning {
camera.startCapture()
}
}
open func stopCapture() {
if camera.captureSession.isRunning {
camera.stopCapture()
}
}
open func clearCamera() {
if let camera = self.camera {
if camera.captureSession.isRunning {
camera.stopCapture()
}
camera.removeAllTargets()
camera.removeInputsAndOutputs()
camera.removeAudioInputsAndOutputs()
camera.removeFramebuffer()
}
captureSequence = 0
}
open func clearNotification() {
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil)
}
}
// MARK: - Internal Methods
extension CameraPreviewController {
func applicationWillResignActive(notification: Notification) {
if isRecordingVideo {
finishRecordingVideo()
clearRecordingVideo()
}
}
func fetchMetaInfo(_ sampleBuffer: CMSampleBuffer) {
if captureSequence == 0 {
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
loge("Failed to get image buffer from CMSampleBuffer object.")
return
}
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
resolution = CGSize(width: width, height: height)
logi("Successfully fetched meta info from sample buffer.")
}
}
open func findOrientation(completion: @escaping ((UIDeviceOrientation) -> ())) {
guard motionManager.isAccelerometerAvailable else { return }
let queue = OperationQueue()
var isFound: Bool = false
motionManager.startAccelerometerUpdates(to: queue) { (data, error) in
guard let data = data, !isFound else { return }
let angle = (atan2(data.acceleration.y,data.acceleration.x)) * 180 / Double.pi;
self.motionManager.stopAccelerometerUpdates()
isFound = true
if fabs(angle) <= 45 {
completion(.landscapeLeft)
print("landscapeLeft")
} else if fabs(angle) > 45 && fabs(angle) < 135 {
if angle > 0 {
completion(.portraitUpsideDown)
print("portraitUpsideDown")
} else {
completion(.portrait)
print("portrait")
}
} else {
completion(.landscapeRight)
print("landscapeRight")
}
}
}
}
// MARK: - Implementation for GPUImageVideoCameraDelegate
extension CameraPreviewController: GPUImageVideoCameraDelegate {
open func willOutputSampleBuffer(_ sampleBuffer: CMSampleBuffer!) {
fetchMetaInfo(sampleBuffer)
delegate?.cameraPreview(self, willOutput: sampleBuffer, with: captureSequence)
captureSequence += 1
guard isFaceDetectorEnabled && captureSequence % UInt64(faceDetectFrequency) == 0 else { return }
faceFeatures(from: sampleBuffer, completion: { features, aperture, orientation in
guard let features = features else { return }
var faceFeatures = [CIFaceFeature]()
for feature in features {
if let faceFeature = feature as? CIFaceFeature {
faceFeatures.append(faceFeature)
} else {
logw("CIFeature object is not a kind of CIFaceFeature.")
}
}
if faceFeatures.count > 0 {
self.faceDetectionDelegate?.cameraPreview(self, detected: faceFeatures, aperture: aperture, orientation: orientation)
} else {
self.faceDetectionDelegate?.cameraPreview(self, detected: nil, aperture: aperture, orientation: orientation)
}
})
}
}
| mit | 54fdfc535455025133457b6342a72115 | 32.405714 | 208 | 0.623931 | 5.476347 | false | false | false | false |
CodeMozart/MHzSinaWeibo-Swift- | SinaWeibo(stroyboard)/SinaWeibo/Classes/Profile/ProfileViewController.swift | 1 | 3136 | //
// PorfileViewController.swift
// SinaWeibo
//
// Created by Minghe on 11/6/15.
// Copyright © 2015 Stanford swift. All rights reserved.
//
import UIKit
class ProfileViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if !login
{
visitorView?.setupVisitorInfo("visitordiscover_image_profile", title: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
return
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 57d6e48e1c014e74d8e3332fcae3a6cf | 31.410526 | 157 | 0.674894 | 5.439929 | false | false | false | false |
ProcedureKit/ProcedureKit | Tests/ProcedureKitTests/RepeatProcedureTests.swift | 2 | 11381 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
import XCTest
import TestingProcedureKit
@testable import ProcedureKit
class RepeatProcedureTests: RepeatTestCase {
func test__init_with_max_and_custom_iterator() {
repeatProcedure = RepeatProcedure(max: 2, iterator: createIterator())
wait(for: repeatProcedure)
PKAssertProcedureFinished(repeatProcedure)
XCTAssertEqual(repeatProcedure.count, 2)
}
func test__init_with_max_and_delay_iterator() {
repeatProcedure = RepeatProcedure(max: 2, delay: Delay.Iterator.immediate, iterator: AnyIterator { TestProcedure() })
wait(for: repeatProcedure)
PKAssertProcedureFinished(repeatProcedure)
XCTAssertEqual(repeatProcedure.count, 2)
}
func test__init_with_max_and_wait_strategy() {
repeatProcedure = RepeatProcedure(max: 2, wait: .constant(0.001), iterator: AnyIterator { TestProcedure() })
wait(for: repeatProcedure)
PKAssertProcedureFinished(repeatProcedure)
XCTAssertEqual(repeatProcedure.count, 2)
}
func test__init_with_max_and_body() {
let procedureExecutedCount = Protector<Int>(0)
let repeatProcedure = RepeatProcedure(max: 2) { BlockProcedure(block: { procedureExecutedCount.advance(by: 1) }) }
wait(for: repeatProcedure)
PKAssertProcedureFinished(repeatProcedure)
XCTAssertEqual(repeatProcedure.count, 2)
XCTAssertEqual(procedureExecutedCount.access, 2)
}
func test__init_with_no_max_and_delay_iterator() {
repeatProcedure = RepeatProcedure(delay: Delay.Iterator.immediate, iterator: createIterator(succeedsAfterCount: 2))
wait(for: repeatProcedure)
XCTAssertEqual(repeatProcedure.count, 2)
PKAssertProcedureFinishedWithError(repeatProcedure, expectedError)
}
func test__init_with_no_max_and_wait_strategy() {
repeatProcedure = RepeatProcedure(wait: .constant(0.001), iterator: createIterator(succeedsAfterCount: 2))
wait(for: repeatProcedure)
XCTAssertEqual(repeatProcedure.count, 2)
PKAssertProcedureFinishedWithError(repeatProcedure, expectedError)
}
func test__append_configure_block() {
repeatProcedure = RepeatProcedure() { TestProcedure() }
var didRunConfigureBlock1 = false
repeatProcedure.appendConfigureBlock { _ in
didRunConfigureBlock1 = true
}
var didRunConfigureBlock2 = false
repeatProcedure.appendConfigureBlock { _ in
didRunConfigureBlock2 = true
}
repeatProcedure.configure(TestProcedure())
XCTAssertTrue(didRunConfigureBlock1)
XCTAssertTrue(didRunConfigureBlock2)
}
func test__replace_configure_block() {
repeatProcedure = RepeatProcedure() { TestProcedure() }
repeatProcedure.appendConfigureBlock { _ in
XCTFail("Configure block should have been replaced.")
}
var didRunConfigureBlock = false
repeatProcedure.replaceConfigureBlock { _ in
didRunConfigureBlock = true
}
repeatProcedure.configure(TestProcedure())
XCTAssertTrue(didRunConfigureBlock)
}
func test__payload_with_configure_block_replaces_configure() {
var didExecuteConfigureBlock = 0
repeatProcedure = RepeatProcedure(max: 3, iterator: AnyIterator { RepeatProcedurePayload(operation: TestProcedure()) { _ in
didExecuteConfigureBlock = didExecuteConfigureBlock + 1
}
})
wait(for: repeatProcedure)
PKAssertProcedureFinished(repeatProcedure)
XCTAssertEqual(repeatProcedure.count, 3)
XCTAssertEqual(didExecuteConfigureBlock, 2)
}
func test__with_input_procedure_payload() {
let outputProcedure = TestProcedure()
outputProcedure.output = .ready(.success("ProcedureKit"))
repeatProcedure = RepeatProcedure(max: 3, iterator: createIterator())
var textOutput: [String] = []
repeatProcedure.addWillAddOperationBlockObserver { (_, operation) in
if let procedure = operation as? TestProcedure {
procedure.addDidFinishBlockObserver { (testProcedure, _) in
if let output = testProcedure.output.value?.value {
textOutput.append(output)
}
}
}
}
repeatProcedure.injectResult(from: outputProcedure)
wait(for: repeatProcedure, outputProcedure)
PKAssertProcedureFinished(repeatProcedure)
XCTAssertEqual(textOutput, ["Hello ProcedureKit", "Hello ProcedureKit", "Hello ProcedureKit"])
}
}
@available(*, deprecated, message: "Protocol is now deprecated")
class RepeatableTestProcedure: TestProcedure, Repeatable {
let limit: Int
init(limit: Int = 5) {
self.limit = limit
super.init()
}
func shouldRepeat(count: Int) -> Bool {
return count < limit
}
}
@available(*, deprecated, message: "Protocol is now deprecated")
class RepeatableRepeatProcedureTests: ProcedureKitTestCase {
func test__init_with_repeatable_procedure() {
let repeatProcedure = RepeatProcedure { RepeatableTestProcedure() }
wait(for: repeatProcedure)
PKAssertProcedureFinished(repeatProcedure)
XCTAssertEqual(repeatProcedure.count, 5)
}
func test__init_with_max_repeatable_procedure() {
let repeatProcedure = RepeatProcedure(max: 4) { RepeatableTestProcedure() }
wait(for: repeatProcedure)
PKAssertProcedureFinished(repeatProcedure)
XCTAssertEqual(repeatProcedure.count, 4)
}
}
class IteratorTests: XCTestCase {
func test__finite__limits_are_not_exceeeded() {
var iterator = FiniteIterator(AnyIterator(stride(from: 0, to: 10, by: 1).makeIterator()), limit: 2)
guard let _ = iterator.next(), let _ = iterator.next() else {
XCTFail("Should return values up to a limit."); return
}
if let _ = iterator.next() {
XCTFail("Should not return a value once the limit is reached.")
}
}
}
class WaitStrategyTestCase: XCTestCase {
var strategy: WaitStrategy!
var iterator: AnyIterator<TimeInterval>!
func test__constant() {
strategy = .constant(1.0)
iterator = strategy.iterator
XCTAssertEqual(iterator.next(), 1.0)
XCTAssertEqual(iterator.next(), 1.0)
XCTAssertEqual(iterator.next(), 1.0)
XCTAssertEqual(iterator.next(), 1.0)
XCTAssertEqual(iterator.next(), 1.0)
}
func test__incrementing() {
strategy = .incrementing(initial: 0, increment: 3)
iterator = strategy.iterator
XCTAssertEqual(iterator.next(), 0)
XCTAssertEqual(iterator.next(), 3)
XCTAssertEqual(iterator.next(), 6)
XCTAssertEqual(iterator.next(), 9)
XCTAssertEqual(iterator.next(), 12)
XCTAssertEqual(iterator.next(), 15)
}
func test__fibonacci() {
strategy = .fibonacci(period: 1, maximum: 30.0)
iterator = strategy.iterator
XCTAssertEqual(iterator.next(), 0)
XCTAssertEqual(iterator.next(), 1)
XCTAssertEqual(iterator.next(), 1)
XCTAssertEqual(iterator.next(), 2)
XCTAssertEqual(iterator.next(), 3)
XCTAssertEqual(iterator.next(), 5)
XCTAssertEqual(iterator.next(), 8)
XCTAssertEqual(iterator.next(), 13)
XCTAssertEqual(iterator.next(), 21)
XCTAssertEqual(iterator.next(), 30)
}
func test__exponential() {
strategy = .exponential(power: 2.0, period: 1.0, maximum: 20.0)
iterator = strategy.iterator
XCTAssertEqual(iterator.next(), 1)
XCTAssertEqual(iterator.next(), 2)
XCTAssertEqual(iterator.next(), 4)
XCTAssertEqual(iterator.next(), 8)
XCTAssertEqual(iterator.next(), 16)
XCTAssertEqual(iterator.next(), 20)
}
}
class DelayIteratorTests: XCTestCase {
var iterator: AnyIterator<Delay>!
func test__constant() {
iterator = Delay.Iterator.constant(1.0)
XCTAssertEqual(iterator.next(), .by(1.0))
XCTAssertEqual(iterator.next(), .by(1.0))
XCTAssertEqual(iterator.next(), .by(1.0))
XCTAssertEqual(iterator.next(), .by(1.0))
XCTAssertEqual(iterator.next(), .by(1.0))
}
func test__incrementing() {
iterator = Delay.Iterator.incrementing(from: 0, by: 3)
XCTAssertEqual(iterator.next(), .by(0))
XCTAssertEqual(iterator.next(), .by(3))
XCTAssertEqual(iterator.next(), .by(6))
XCTAssertEqual(iterator.next(), .by(9))
XCTAssertEqual(iterator.next(), .by(12))
XCTAssertEqual(iterator.next(), .by(15))
}
func test__fibonacci() {
iterator = Delay.Iterator.fibonacci(withPeriod: 1, andMaximum: 30.0)
XCTAssertEqual(iterator.next(), .by(0))
XCTAssertEqual(iterator.next(), .by(1))
XCTAssertEqual(iterator.next(), .by(1))
XCTAssertEqual(iterator.next(), .by(2))
XCTAssertEqual(iterator.next(), .by(3))
XCTAssertEqual(iterator.next(), .by(5))
XCTAssertEqual(iterator.next(), .by(8))
XCTAssertEqual(iterator.next(), .by(13))
XCTAssertEqual(iterator.next(), .by(21))
XCTAssertEqual(iterator.next(), .by(30))
}
func test__exponential() {
iterator = Delay.Iterator.exponential(power: 2.0, withPeriod: 1, andMaximum: 20.0)
XCTAssertEqual(iterator.next(), .by(1))
XCTAssertEqual(iterator.next(), .by(2))
XCTAssertEqual(iterator.next(), .by(4))
XCTAssertEqual(iterator.next(), .by(8))
XCTAssertEqual(iterator.next(), .by(16))
XCTAssertEqual(iterator.next(), .by(20))
}
}
class RandomnessTests: StressTestCase {
func test__random_wait_strategy() {
let wait: WaitStrategy = .random(minimum: 1.0, maximum: 2.0)
let iterator = wait.iterator
stress(level: .custom(1, 100_000)) { batch, iteration in
guard let interval = iterator.next() else { XCTFail("randomness never stops."); return }
XCTAssertGreaterThanOrEqual(interval, 1.0)
XCTAssertLessThanOrEqual(interval, 2.0)
}
}
func test__random_delay_iterator() {
let iterator = Delay.Iterator.random(withMinimum: 1.0, andMaximum: 2.0)
stress(level: .custom(1, 100_000)) { batch, iteration in
guard let delay = iterator.next() else { XCTFail("randomness never stops."); return }
XCTAssertGreaterThanOrEqual(delay, .by(1.0))
XCTAssertLessThanOrEqual(delay, .by(2.0))
}
}
func test__random_fail_iterator() {
var iterator = RandomFailIterator(AnyIterator { true }, probability: 0.2)
var numberOfSuccess = 0
stress(level: .custom(1, 100_000)) { batch, iteration in
if let _ = iterator.next() {
numberOfSuccess = numberOfSuccess + 1
}
}
let probabilityFailure = Double(100_000 - numberOfSuccess) / 100_000.0
#if swift(>=3.2)
XCTAssertEqual(probabilityFailure, iterator.probability, accuracy: 0.10)
#else
XCTAssertEqualWithAccuracy(probabilityFailure, iterator.probability, accuracy: 0.10)
#endif
}
}
| mit | deaac7bad6e6fa74a6e114ebb485a383 | 34.899054 | 131 | 0.646749 | 4.548361 | false | true | false | false |
ResearchSuite/ResearchSuiteAppFramework-iOS | Source/Lab/Classes/RSLOnboardingViewController.swift | 1 | 2565 | //
// RSLOnboardingViewController.swift
// Pods
//
// Created by James Kizer on 3/22/17.
//
//
import UIKit
import ResearchSuiteTaskBuilder
import ReSwift
open class RSLOnboardingViewController: RSAFRootViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var titleImageView: UIImageView!
private var state: RSAFCombinedState?
private var showingVC = false
override open func viewDidLoad() {
super.viewDidLoad()
}
override open func newState(state: RSAFCombinedState) {
super.newState(state: state)
self.state = state
if !showingVC,
let delegate = UIApplication.shared.delegate as? RSLApplicationDelegate,
delegate.isSignedIn(state: state),
let labState = state.middlewareState as? RSLLabState,
RSLLabSelectors.isResearcherDemographicsCompleted(labState) {
showingVC = true
delegate.showViewController(state: state)
}
guard let coreState = state.coreState as? RSAFCoreState else {
return
}
self.titleLabel.text = RSAFCoreSelectors.getTitleLabelText(coreState)
self.titleImageView.image = RSAFCoreSelectors.getTitleImage(coreState)
}
@IBAction func signInTapped(_ sender: Any) {
guard let delegate = UIApplication.shared.delegate as? RSLApplicationDelegate,
let store = delegate.reduxStore,
let state = self.state else {
return
}
if !delegate.isSignedIn(state: state),
let item = delegate.signInItem(),
let taskBuilder = self.taskBuilder {
// let activityRun = RSAFActivityRun.create(from: item)
// let action = QueueActivityAction(uuid: UUID(), activityRun: activityRun)
let action = RSAFActionCreators.queueActivity(fromScheduleItem: item, taskBuilder: taskBuilder)
store.dispatch(action)
}
else if !delegate.isResearcherDemographicsCompleted(state: state),
let item = delegate.researcherDemographics(),
let taskBuilder = self.taskBuilder {
// let activityRun = RSAFActivityRun.create(from: item)
// let action = QueueActivityAction(uuid: UUID(), activityRun: activityRun)
let action = RSAFActionCreators.queueActivity(fromScheduleItem: item, taskBuilder: taskBuilder)
store.dispatch(action)
}
}
}
| apache-2.0 | db6dfcb36691d43e103af2624a4d69e5 | 31.884615 | 107 | 0.631969 | 4.923225 | false | false | false | false |
kazuhidet/fastlane | fastlane/swift/main.swift | 4 | 1403 | // main.swift
// Copyright (c) 2020 FastlaneTools
//
// ** 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
let argumentProcessor = ArgumentProcessor(args: CommandLine.arguments)
let timeout = argumentProcessor.commandTimeout
class MainProcess {
var doneRunningLane = false
var thread: Thread!
@objc func connectToFastlaneAndRunLane() {
runner.startSocketThread(port: argumentProcessor.port)
let completedRun = Fastfile.runLane(from: nil, named: argumentProcessor.currentLane, with: argumentProcessor.laneParameters())
if completedRun {
runner.disconnectFromFastlaneProcess()
}
doneRunningLane = true
}
func startFastlaneThread() {
thread = Thread(target: self, selector: #selector(connectToFastlaneAndRunLane), object: nil)
thread.name = "worker thread"
thread.start()
}
}
let process = MainProcess()
process.startFastlaneThread()
while !process.doneRunningLane, RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 2)) {
// no op
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
| mit | ab4ac497a0efc026080a782b4e2153bc | 28.851064 | 134 | 0.71846 | 4.200599 | false | false | false | false |
hackersatcambridge/hac-website | Sources/HaCTML/Attributes.swift | 2 | 1759 | private func stringAttribute(_ key: String) -> AttributeKey<String> {
return AttributeKey(key, apply: { .text($0) })
}
private func numberAttribute(_ key: String) -> AttributeKey<Int> {
return AttributeKey(key, apply: { .text(String($0)) })
}
private func CSSAttribute(_ key: String) -> AttributeKey<[String: String?]> {
return AttributeKey(key, apply: { dict in
.text(
// filter out the nil values
dict.flatMap {
$0 as? (String, String)
}.map {
"\($0): \($1);"
}.joined(separator: " ")
)
})
}
public enum Attributes {
// We are filling this list in incrementally,
// implementing attributes as we need them so that we can type them correctly
static public let alt = stringAttribute("alt")
static public let charset = stringAttribute("charset")
static public let className = stringAttribute("class")
static public let content = stringAttribute("content")
static public let height = numberAttribute("height")
static public let href = stringAttribute("href")
static public let id = stringAttribute("id")
static public let lang = stringAttribute("lang")
static public let name = stringAttribute("name")
static public let rel = stringAttribute("rel")
static public let src = stringAttribute("src")
static public let srcset = stringAttribute("srcset")
static public let style = CSSAttribute("style")
static public let target = stringAttribute("target")
static public let type = stringAttribute("type")
static public let placeholder = stringAttribute("placeholder")
static public let tabIndex = numberAttribute("tab-index")
static public let width = numberAttribute("width")
}
// Creating a more concise namespace for expressivity
public let Attr = Attributes.self
| mit | aa67b2555159517a3f3106c12e483743 | 37.23913 | 79 | 0.707789 | 4.290244 | false | false | false | false |
AlexIzh/SearchQueryParser | SearchiOSExample/SearchTest/ViewController.swift | 1 | 2207 | //
// ViewController.swift
// SearchTest
//
// Created by Alex Severyanov on 07/07/2017.
// Copyright © 2017 alexizh. All rights reserved.
//
import UIKit
import SearchQueryParser
class ViewController: UIViewController {
var array: [Item] = []
var filteredItems: [Item] = [] {
didSet {
tableView?.reloadData()
}
}
@IBOutlet var tableView: UITableView!
let builder = DefaultFilterBlockBuilder<Item>(options: .caseInsensitive, valuePredicate: { str in
return { $0.searchString.lowercased().contains(str.lowercased()) }
})
override func viewDidLoad() {
super.viewDidLoad()
array = [
Item(color: "red", fruit: "apple"),
Item(color: "green", fruit: "apple"),
Item(color: "blue", fruit: "apple"),
Item(color: "red", fruit: "orange"),
Item(color: "green", fruit: "orange"),
Item(color: "blue", fruit: "orange"),
Item(color: "red", fruit: "banana"),
Item(color: "green", fruit: "banana"),
Item(color: "blue", fruit: "banana")
]
filteredItems = array
}
class Item: NSObject {
let color: String
let fruit: String
dynamic var searchString: String
init(color: String, fruit: String) {
self.color = color; self.fruit = fruit
searchString = color + " " + fruit
}
}
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let filterBlock = builder.build(from: searchText)
filteredItems = array.filter(filterBlock ?? {_ in true})
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = filteredItems[indexPath.row].searchString
return cell
}
}
| mit | d781fd412724afdf481916e9451c71e6 | 27.649351 | 101 | 0.614687 | 4.595833 | false | false | false | false |
hemincong/iOSCNWindow | Launchy/Launchy/DetailViewController.swift | 1 | 2394 | //
// DetailViewController.swift
// Launchy
//
// Created by Manchung.Ho on 2/26/15.
// Copyright (c) 2015 net.mincong. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var titleTF: UITextField!
@IBOutlet weak var serverAddressTF: UITextField!
@IBOutlet weak var sharedSecretTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var accountNameTF: UITextField!
internal var detailItem: VPNProfile? = nil
private var magicPassword: String? = "9FAs&&^%$#@#vv!czsg"
override func viewDidLoad() {
super.viewDidLoad()
var rightButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("done"))
self.navigationItem.rightBarButtonItem = rightButton
}
override func viewWillAppear(animated: Bool) {
if let item = detailItem {
titleTF.text = item.title
serverAddressTF.text = item.serverAddress
accountNameTF.text = item.accountName
passwordTF.text = magicPassword
sharedSecretTF.text = magicPassword
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func done() {
if let vp = VPNProfileManager.sharedManager.createVPNProfileAndSave(titleTF.text, serverAddress: serverAddressTF.text, accountName: accountNameTF.text) {
if let password = passwordTF.text {
if password != magicPassword {
KeychainWrapper.setPassword(password, forVPNProfileID: vp.ID)
}
}
if let sercet = sharedSecretTF.text {
if sercet != magicPassword {
KeychainWrapper.setSharedSecret(sercet, forVPNProfileID: vp.ID)
}
}
}
self.navigationController?.popViewControllerAnimated(false)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-2.0 | 95757a69f1242796fa965836581a968a | 30.92 | 161 | 0.652464 | 4.925926 | false | false | false | false |
hulinSun/MyRx | MyRx/MyRx/Classes/Main/View/TopicBottomView.swift | 1 | 1580 |
//
// TopicBottomView.swift
// MyRx
//
// Created by Hony on 2017/1/4.
// Copyright © 2017年 Hony. All rights reserved.
//
import UIKit
class TopicBottomView: UIView {
@IBOutlet weak var zanBtn: UIButton!
@IBOutlet weak var commentBtn: UIButton!
@IBOutlet weak var forwardBtn: UIButton!
@IBOutlet weak var timeLabel: UILabel!
override func layoutSubviews() {
super.layoutSubviews()
lay.position = CGPoint(x: 0, y: 49.3)
self.layer.addSublayer(lay)
}
fileprivate lazy var lay: CALayer = {
let i = CALayer()
i.backgroundColor = UIColor("#e3e3e5").cgColor
i.anchorPoint = CGPoint.zero
i.bounds = CGRect(x: 0, y: 0, width: UIConst.screenWidth, height: 0.6)
return i
}()
var topic: Topic?{
didSet{
timeLabel.text = topic?.info?.created?.subString(from: 11).subString(to: 5)
if let heart = topic?.info?.heart, Int(heart)! > 0{
zanBtn.setTitle(heart, for: .normal)
}else{
zanBtn.setTitle("", for: .normal)
}
if let comment = topic?.info?.comment, Int(comment)! > 0{
commentBtn.setTitle(comment, for: .normal)
}else{
commentBtn.setTitle("", for: .normal)
}
if let forward = topic?.info?.forward, Int(forward)! > 0{
forwardBtn.setTitle(forward, for: .normal)
}else{
forwardBtn.setTitle("", for: .normal)
}
}
}
}
| mit | 7984d3639512b5e1ef13af1877294276 | 28.203704 | 87 | 0.544705 | 4.074935 | false | false | false | false |
tlax/looper | looper/Data/DManager.swift | 1 | 4563 | import Foundation
import CoreData
class DManager
{
static let sharedInstance:DManager = DManager()
private let managedObjectContext:NSManagedObjectContext
private let kModelName:String = "DLooper"
private let kModelExtension:String = "momd"
private let kSQLiteExtension:String = ".sqlite"
private init()
{
let sqliteFile:String = "\(kModelName)\(kSQLiteExtension)"
let storeCoordinatorURL:URL = FileManager.appDirectory.appendingPathComponent(
sqliteFile)
guard
let modelURL:URL = Bundle.main.url(
forResource:kModelName,
withExtension:kModelExtension),
let managedObjectModel:NSManagedObjectModel = NSManagedObjectModel(
contentsOf:modelURL)
else
{
fatalError()
}
let persistentStoreCoordinator:NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(
managedObjectModel:managedObjectModel)
do
{
try persistentStoreCoordinator.addPersistentStore(
ofType:NSSQLiteStoreType,
configurationName:nil,
at:storeCoordinatorURL,
options:nil)
}
catch let error
{
#if DEBUG
print("coredata: \(error.localizedDescription)")
#endif
}
managedObjectContext = NSManagedObjectContext(
concurrencyType:
NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
}
//MARK: public
func save()
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{
if self.managedObjectContext.hasChanges
{
self.managedObjectContext.perform
{
do
{
try self.managedObjectContext.save()
}
catch let error
{
#if DEBUG
print("coredata: \(error.localizedDescription)")
#endif
}
}
}
}
}
func createManagedObject(
entityName:String,
completion:@escaping((NSManagedObject?) -> ()))
{
managedObjectContext.perform
{
if let entityDescription:NSEntityDescription = NSEntityDescription.entity(
forEntityName:entityName,
in:self.managedObjectContext)
{
let managedObject:NSManagedObject = NSManagedObject(
entity:entityDescription,
insertInto:self.managedObjectContext)
completion(managedObject)
}
else
{
completion(nil)
}
}
}
func fetchManagedObjects(
entityName:String,
limit:Int = 0,
predicate:NSPredicate? = nil,
sorters:[NSSortDescriptor]? = nil,
completion:@escaping(([NSManagedObject]?) -> ()))
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{
let fetchRequest:NSFetchRequest<NSManagedObject> = NSFetchRequest(
entityName:entityName)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sorters
fetchRequest.fetchLimit = limit
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.includesPropertyValues = true
fetchRequest.includesSubentities = true
self.managedObjectContext.perform
{
let results:[NSManagedObject]?
do
{
results = try self.managedObjectContext.fetch(fetchRequest)
}
catch
{
results = nil
}
completion(results)
}
}
}
func delete(object:NSManagedObject, completion:(() -> ())? = nil)
{
managedObjectContext.perform
{
self.managedObjectContext.delete(object)
completion?()
}
}
}
| mit | 4c0267d56ce292218339a9e20c92c14b | 29.218543 | 99 | 0.519176 | 7.041667 | false | false | false | false |
NobodyNada/chatbot | Sources/FireAlarmCore/Redunda.swift | 3 | 5427 | //
// Redunda.swift
// FireAlarm
//
// Created by NobodyNada on 3/23/17.
//
//
import Foundation
import SwiftChatSE
import Dispatch
import CryptoSwift
open class Redunda {
public enum RedundaError: Error {
case invalidJSON(json: Any)
case downloadFailed(status: Int)
case uploadFailed(status: Int)
}
public struct Event {
public let name: String
public let headers: [String:String]
public let content: String
public func contentAsJSON() throws -> Any {
return try JSONSerialization.jsonObject(with: content.data(using: .utf8)!)
}
public init(json: [String:Any]) throws {
guard let name = json["name"] as? String,
let headers = json["headers"] as? [String:String],
let content = json["content"] as? String
else { throw RedundaError.invalidJSON(json: json) }
self.name = name
self.headers = headers
self.content = content
}
}
public let key: String
public let client: Client
public let filesToSync: [String] //An array of regexes.
open func downloadFile(named name: String) throws {
print("Downloading \(name).")
let (data, response) = try client.get("https://redunda.sobotics.org/bots/data/\(name)?key=\(key)")
guard response.statusCode == 200 else {
throw RedundaError.downloadFailed(status: response.statusCode)
}
try data.write(to:
URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent(name)
)
}
open func uploadFile(named name: String) throws {
print("Uploading \(name).")
let data = try Data(contentsOf:
URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent(name)
)
let (_, response) = try client.post(
"https://redunda.sobotics.org/bots/data/\(name)?key=\(key)",
data: data, contentType: "application/octet-stream"
)
guard response.statusCode < 400 else {
throw RedundaError.uploadFailed(status: response.statusCode)
}
}
open func hash(of file: String) throws -> String {
return try Data(contentsOf: URL(fileURLWithPath: file)).sha256().toHexString()
}
///Downloads modified files from Redunda.
///- Warning:
///Do not post non-`RedundaError`s to chat; they may contain the instance key!
open func downloadFiles() throws {
let response = try client.parseJSON(client.get("https://redunda.sobotics.org/bots/data.json?key=\(key)"))
guard let json = response as? [[String:Any]] else {
throw RedundaError.invalidJSON(json: response)
}
let manager = FileManager.default
for item in json {
guard let filename = item["key"] as? String else {
throw RedundaError.invalidJSON(json: response)
}
if manager.fileExists(atPath: filename) {
if try hash(of: filename) != item["sha256"] as? String {
try downloadFile(named: filename)
}
} else {
try downloadFile(named: filename)
}
}
}
///Downloads modified files from Redunda.
///- Warning:
///Do not post non-`RedundaError`s to chat; they may contain the instance key!
open func uploadFiles() throws {
let response = try client.parseJSON(client.get("https://redunda.sobotics.org/bots/data.json?key=\(key)"))
guard let json = response as? [[String:Any]] else {
throw RedundaError.invalidJSON(json: response)
}
let manager = FileManager.default
for filename in try manager.contentsOfDirectory(atPath: ".") {
for regex in filesToSync {
guard filename.range(of: regex, options: [.regularExpression]) != nil else {
continue
}
if let index = json.firstIndex(where: { filename == $0["key"] as? String }) {
if try hash(of: filename) != json[index]["sha256"] as? String {
try uploadFile(named: filename)
}
} else {
try uploadFile(named: filename)
}
}
}
}
public init(key: String, client: Client, filesToSync: [String] = []) {
self.key = key
self.client = client
self.filesToSync = filesToSync
}
open var shouldStandby: Bool = false
open var locationName: String?
//The number of unread events.
open var eventCount: Int = 0
open func fetchEvents() throws -> [Event] {
let json = try client.parseJSON(
try client.post(
"https://redunda.sobotics.org/events.json",
["key":key]
)
)
guard let events = try (json as? [[String:Any]])?.map(Event.init) else {
throw RedundaError.invalidJSON(json: json)
}
eventCount = 0
return events
}
open func sendStatusPing(version: String? = nil) throws {
let data = version == nil ? ["key":key] : ["key":key, "version":version!]
let response = try client.parseJSON(try client.post("https://redunda.sobotics.org/status.json", data))
guard let json = response as? [String:Any] else {
throw RedundaError.invalidJSON(json: response)
}
guard let standby = json["should_standby"] as? Bool else {
throw RedundaError.invalidJSON(json: response)
}
guard let eventCount = json["event_count"] as? Int else {
throw RedundaError.invalidJSON(json: response)
}
shouldStandby = standby
locationName = json["location"] as? String
self.eventCount = eventCount
}
}
| mit | 3c64111a30eb47b4ff2d933e853a319a | 28.177419 | 107 | 0.637553 | 3.745342 | false | false | false | false |
Yoloabdo/REST-Udemy | REST apple/REST apple/SettingsTableViewController.swift | 1 | 4899 | //
// SettingsTableViewController.swift
// REST apple
//
// Created by Abdulrhman eaita on 4/14/16.
// Copyright © 2016 Abdulrhman eaita. All rights reserved.
// it lacks the High image Quality option plus security, but it's doable later anytime.
// most of the app functionality now is done. about page is left blank as nothing much to say about this app apperantly
import UIKit
import MessageUI
class SettingsTableViewController: UIViewController, MFMailComposeViewControllerDelegate {
let defaults = NSUserDefaults.standardUserDefaults()
@IBOutlet weak var aboutButton: UIButton!
@IBOutlet weak var feedbackLabel: UILabel!
@IBOutlet weak var securityLabel: UILabel!
@IBOutlet weak var bestImageQuality: UILabel!
@IBOutlet weak var APICnt: UILabel!
@IBOutlet weak var numberOfvideosLabel: UILabel!
@IBOutlet weak var feedbackBtnLabel: UIButton!
@IBOutlet weak var dragSliderLabel: UILabel!
@IBOutlet weak var sliderCnt: UISlider!
@IBOutlet weak var touchID: UISwitch!
@IBAction func sliderAPICnt(sender: UISlider) {
let value = Int(sender.value)
defaults.setObject(value, forKey: StoryBoard.APICount)
APICnt.text = "\(value) "
}
private struct StoryBoard {
static let SecurityKey = "SecSettings"
static let APICount = "APICNT"
static let DefaultDownloadedAPIValue = 10
}
@IBAction func touchIdSec(sender: UISwitch) {
if touchID.on {
defaults.setBool(true, forKey: StoryBoard.SecurityKey)
}else {
defaults.setBool(false, forKey: StoryBoard.SecurityKey)
}
}
// MARK:- MAIL functions
@IBAction func feedBackBtn(sender: UIButton) {
let mailCompVC = configureMail()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailCompVC, animated: true, completion: nil)
}else{
mailAlert()
}
}
func configureMail() -> MFMailComposeViewController {
let mailComposeVC = MFMailComposeViewController()
mailComposeVC.mailComposeDelegate = self
mailComposeVC.setToRecipients(["[email protected]"])
mailComposeVC.setSubject("Music app feedBack")
mailComposeVC.setMessageBody("Hello Abdo, \n\nI would like to share the following feedback ...\n", isHTML: false)
return mailComposeVC
}
func mailAlert() -> Void {
let alertCV = UIAlertController(title: "Mail Error", message: "No Email Account setup on iPhone", preferredStyle: .Alert)
let alert = UIAlertAction(title: "ok", style: .Default, handler: nil)
alertCV.addAction(alert)
self.presentViewController(alertCV, animated: true, completion: nil)
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
switch result.rawValue {
case MFMailComposeResultCancelled.rawValue:
print("mail Canceled")
case MFMailComposeResultSent.rawValue:
print("mail send")
default:
print("Unknown issue")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateFonts), name: UIContentSizeCategoryDidChangeNotification, object: nil)
title = "settings"
touchID.on = defaults.boolForKey(StoryBoard.SecurityKey)
guard let value = defaults.objectForKey(StoryBoard.APICount) else {
APICnt.text = "\(StoryBoard.DefaultDownloadedAPIValue)"
sliderCnt.value = Float(StoryBoard.DefaultDownloadedAPIValue)
return
}
APICnt.text = "\(value)"
sliderCnt.value = Float(value as! NSNumber)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
func updateFonts() -> Void {
aboutButton.titleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
feedbackBtnLabel.titleLabel!.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
securityLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
bestImageQuality.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
APICnt.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
numberOfvideosLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
dragSliderLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote)
}
}
| mit | 107e901914fadb2f97cb675ebb03bb5f | 36.106061 | 159 | 0.680073 | 5.205101 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Service/LinkedBanks/LinkedBankActivationService.swift | 1 | 2314 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import RxSwift
import RxToolKit
import ToolKit
public enum BankActivationState {
case active(LinkedBankData)
case pending
case inactive(LinkedBankData?)
var isPending: Bool {
switch self {
case .pending:
return true
case .active, .inactive:
return false
}
}
init(_ response: LinkedBankResponse) {
guard let bankData = LinkedBankData(response: response) else {
self = .inactive(nil)
return
}
switch response.state {
case .active:
self = .active(bankData)
case .pending:
self = .pending
case .blocked:
self = .inactive(bankData)
}
}
}
public protocol LinkedBankActivationServiceAPI {
/// Cancel polling
var cancel: Completable { get }
/// Poll for activation
func waitForActivation(
of bankId: String,
paymentAccountId: String,
accountId: String
) -> Single<PollResult<BankActivationState>>
}
final class LinkedBankActivationService: LinkedBankActivationServiceAPI {
// MARK: - Properties
var cancel: Completable {
pollService.cancel
}
// MARK: - Injected
private let pollService: PollService<BankActivationState>
private let client: LinkedBanksClientAPI
// MARK: - Setup
init(client: LinkedBanksClientAPI = resolve()) {
self.client = client
pollService = PollService(matcher: { !$0.isPending })
}
func waitForActivation(
of bankId: String,
paymentAccountId: String,
accountId: String
) -> Single<PollResult<BankActivationState>> {
pollService.setFetch(weak: self) { (self) -> Single<BankActivationState> in
self.client.updateBankLinkage(
for: bankId,
providerAccountId: paymentAccountId,
accountId: accountId
)
.map { payload in
guard payload.state != .pending else {
return .pending
}
return BankActivationState(payload)
}
.asSingle()
}
return pollService.poll(timeoutAfter: 60)
}
}
| lgpl-3.0 | 21d475c46fcf33ba9d263dd2664f13fb | 24.417582 | 83 | 0.591872 | 4.869474 | false | false | false | false |
prolificinteractive/simcoe | Simcoe/EnumerationListable.swift | 1 | 1449 | //
// EnumerationListable.swift
// Simcoe
//
// Created by Michael Campbell on 10/26/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
/// The enumeration listable protocol.
protocol EnumerationListable {
/// Defines all keys in an enumeration.
static var allKeys: [Self] { get }
}
extension EnumerationListable where Self: RawRepresentable {
/// The unfound keys in the provided Properties.
///
/// - Parameter properties: The properties.
/// - Returns: The unfound keys.
fileprivate static func unfoundKeys(_ properties: Properties) -> [String] {
let allKeyRawValues: [String] = Self.allKeys.compactMap { $0.rawValue as? String }
let allKeyRawValuesSet = Set(allKeyRawValues)
let allPropertiesKeysSet = Set(properties.keys)
let results: Set<String> = allPropertiesKeysSet.subtracting(allKeyRawValuesSet)
return results.map { $0 }
}
/// The remaining properties.
///
/// - Parameter properties: The properties.
/// - Returns: The remaining properties.
static func remaining(properties: Properties) -> Properties {
let unfoundKeys = Self.unfoundKeys(properties)
var additionalProperties = Properties()
if unfoundKeys.count > 0 {
for key in unfoundKeys {
additionalProperties[key] = properties[key]
}
}
return additionalProperties
}
}
| mit | edf41c7703df1b7990b352404863a32a | 28.55102 | 90 | 0.656768 | 4.469136 | false | false | false | false |
abertelrud/swift-package-manager | Tests/PackageRegistryTests/RegistryDownloadsManagerTests.swift | 2 | 19376 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import PackageModel
import PackageLoading
@testable import PackageRegistry
import SPMTestSupport
import TSCBasic
import XCTest
class RegistryDownloadsManagerTests: XCTestCase {
func testNoCache() throws {
let observability = ObservabilitySystem.makeForTesting()
let fs = InMemoryFileSystem()
let registry = MockRegistry(
filesystem: fs,
identityResolver: DefaultIdentityResolver(),
checksumAlgorithm: MockHashAlgorithm(),
fingerprintStorage: MockPackageFingerprintStorage()
)
let package: PackageIdentity = .plain("test.\(UUID().uuidString)")
let packageVersion: Version = "1.0.0"
let packageSource = InMemoryRegistryPackageSource(fileSystem: fs, path: .root.appending(components: "registry", "server", package.description))
try packageSource.writePackageContent()
registry.addPackage(
identity: package,
versions: [packageVersion],
source: packageSource
)
let delegate = MockRegistryDownloadsManagerDelegate()
let downloadsPath = AbsolutePath.root.appending(components: "registry", "downloads")
let manager = RegistryDownloadsManager(
fileSystem: fs,
path: downloadsPath,
cachePath: .none, // cache disabled
registryClient: registry.registryClient,
checksumAlgorithm: MockHashAlgorithm(),
delegate: delegate
)
// try to get a package
do {
delegate.prepare(fetchExpected: true)
let path = try manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))
XCTAssertTrue(fs.isDirectory(path))
try delegate.wait(timeout: .now() + 2)
XCTAssertEqual(delegate.willFetch.count, 1)
XCTAssertEqual(delegate.willFetch.first?.packageVersion, .init(package: package, version: packageVersion))
XCTAssertEqual(delegate.willFetch.first?.fetchDetails, .init(fromCache: false, updatedCache: false))
XCTAssertEqual(delegate.didFetch.count, 1)
XCTAssertEqual(delegate.didFetch.first?.packageVersion, .init(package: package, version: packageVersion))
XCTAssertEqual(try! delegate.didFetch.first?.result.get(), .init(fromCache: false, updatedCache: false))
}
// try to get a package that does not exist
let unknownPackage: PackageIdentity = .plain("unknown.\(UUID().uuidString)")
let unknownPackageVersion: Version = "1.0.0"
do {
delegate.prepare(fetchExpected: true)
XCTAssertThrowsError(try manager.lookup(package: unknownPackage, version: unknownPackageVersion, observabilityScope: observability.topScope)) { error in
XCTAssertNotNil(error as? RegistryError)
}
try delegate.wait(timeout: .now() + 2)
XCTAssertEqual(delegate.willFetch.map { ($0.packageVersion) },
[
(PackageVersion(package: package, version: packageVersion)),
(PackageVersion(package: unknownPackage, version: unknownPackageVersion))
]
)
XCTAssertEqual(delegate.didFetch.map { ($0.packageVersion) },
[
(PackageVersion(package: package, version: packageVersion)),
(PackageVersion(package: unknownPackage, version: unknownPackageVersion))
]
)
}
// try to get the existing package again, no fetching expected this time
do {
delegate.prepare(fetchExpected: false)
let path = try manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))
XCTAssertTrue(fs.isDirectory(path))
try delegate.wait(timeout: .now() + 2)
XCTAssertEqual(delegate.willFetch.map { ($0.packageVersion) },
[
(PackageVersion(package: package, version: packageVersion)),
(PackageVersion(package: unknownPackage, version: unknownPackageVersion))
]
)
XCTAssertEqual(delegate.didFetch.map { ($0.packageVersion) },
[
(PackageVersion(package: package, version: packageVersion)),
(PackageVersion(package: unknownPackage, version: unknownPackageVersion))
]
)
}
// remove the package
do {
try manager.remove(package: package)
delegate.prepare(fetchExpected: true)
let path = try manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))
XCTAssertTrue(fs.isDirectory(path))
try delegate.wait(timeout: .now() + 2)
XCTAssertEqual(delegate.willFetch.map { ($0.packageVersion) },
[
(PackageVersion(package: package, version: packageVersion)),
(PackageVersion(package: unknownPackage, version: unknownPackageVersion)),
(PackageVersion(package: package, version: packageVersion))
]
)
XCTAssertEqual(delegate.didFetch.map { ($0.packageVersion) },
[
(PackageVersion(package: package, version: packageVersion)),
(PackageVersion(package: unknownPackage, version: unknownPackageVersion)),
(PackageVersion(package: package, version: packageVersion))
]
)
}
}
func testCache() throws {
let observability = ObservabilitySystem.makeForTesting()
let fs = InMemoryFileSystem()
let registry = MockRegistry(
filesystem: fs,
identityResolver: DefaultIdentityResolver(),
checksumAlgorithm: MockHashAlgorithm(),
fingerprintStorage: MockPackageFingerprintStorage()
)
let package: PackageIdentity = .plain("test.\(UUID().uuidString)")
let packageVersion: Version = "1.0.0"
let packageSource = InMemoryRegistryPackageSource(fileSystem: fs, path: .root.appending(components: "registry", "server", package.description))
try packageSource.writePackageContent()
registry.addPackage(
identity: package,
versions: [packageVersion],
source: packageSource
)
let delegate = MockRegistryDownloadsManagerDelegate()
let downloadsPath = AbsolutePath.root.appending(components: "registry", "downloads")
let cachePath = AbsolutePath.root.appending(components: "registry", "cache")
let manager = RegistryDownloadsManager(
fileSystem: fs,
path: downloadsPath,
cachePath: cachePath, // cache enabled
registryClient: registry.registryClient,
checksumAlgorithm: MockHashAlgorithm(),
delegate: delegate
)
// try to get a package
do {
delegate.prepare(fetchExpected: true)
let path = try manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))
XCTAssertTrue(fs.isDirectory(path))
XCTAssertTrue(fs.isDirectory(cachePath.appending(components: package.scopeAndName!.scope.description, package.scopeAndName!.name.description, packageVersion.description)))
try delegate.wait(timeout: .now() + 2)
XCTAssertEqual(delegate.willFetch.count, 1)
XCTAssertEqual(delegate.willFetch.first?.packageVersion, .init(package: package, version: packageVersion))
XCTAssertEqual(delegate.willFetch.first?.fetchDetails, .init(fromCache: false, updatedCache: false))
XCTAssertEqual(delegate.didFetch.count, 1)
XCTAssertEqual(delegate.didFetch.first?.packageVersion, .init(package: package, version: packageVersion))
XCTAssertEqual(try! delegate.didFetch.first?.result.get(), .init(fromCache: true, updatedCache: true))
}
// remove the "local" package, should come from cache
do {
try manager.remove(package: package)
delegate.prepare(fetchExpected: true)
let path = try manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))
XCTAssertTrue(fs.isDirectory(path))
try delegate.wait(timeout: .now() + 2)
XCTAssertEqual(delegate.willFetch.count, 2)
XCTAssertEqual(delegate.willFetch.last?.packageVersion, .init(package: package, version: packageVersion))
XCTAssertEqual(delegate.willFetch.last?.fetchDetails, .init(fromCache: true, updatedCache: false))
XCTAssertEqual(delegate.didFetch.count, 2)
XCTAssertEqual(delegate.didFetch.last?.packageVersion, .init(package: package, version: packageVersion))
XCTAssertEqual(try! delegate.didFetch.last?.result.get(), .init(fromCache: true, updatedCache: false))
}
// remove the "local" package, and purge cache
do {
try manager.remove(package: package)
try manager.purgeCache()
delegate.prepare(fetchExpected: true)
let path = try manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))
XCTAssertTrue(fs.isDirectory(path))
try delegate.wait(timeout: .now() + 2)
XCTAssertEqual(delegate.willFetch.count, 3)
XCTAssertEqual(delegate.willFetch.last?.packageVersion, .init(package: package, version: packageVersion))
XCTAssertEqual(delegate.willFetch.last?.fetchDetails, .init(fromCache: false, updatedCache: false))
XCTAssertEqual(delegate.didFetch.count, 3)
XCTAssertEqual(delegate.didFetch.last?.packageVersion, .init(package: package, version: packageVersion))
XCTAssertEqual(try! delegate.didFetch.last?.result.get(), .init(fromCache: true, updatedCache: true))
}
}
func testConcurrency() throws {
let observability = ObservabilitySystem.makeForTesting()
let fs = InMemoryFileSystem()
let registry = MockRegistry(
filesystem: fs,
identityResolver: DefaultIdentityResolver(),
checksumAlgorithm: MockHashAlgorithm(),
fingerprintStorage: MockPackageFingerprintStorage()
)
let downloadsPath = AbsolutePath.root.appending(components: "registry", "downloads")
let delegate = MockRegistryDownloadsManagerDelegate()
let manager = RegistryDownloadsManager(
fileSystem: fs,
path: downloadsPath,
cachePath: .none, // cache disabled
registryClient: registry.registryClient,
checksumAlgorithm: MockHashAlgorithm(),
delegate: delegate
)
// many different versions
do {
let concurrency = 100
let package: PackageIdentity = .plain("test.\(UUID().uuidString)")
let packageVersions = (0 ..< concurrency).map { Version($0, 0 , 0) }
let packageSource = InMemoryRegistryPackageSource(fileSystem: fs, path: .root.appending(components: "registry", "server", package.description))
try packageSource.writePackageContent()
registry.addPackage(
identity: package,
versions: packageVersions,
source: packageSource
)
let group = DispatchGroup()
let results = ThreadSafeKeyValueStore<Version, Result<AbsolutePath, Error>>()
for packageVersion in packageVersions {
group.enter()
delegate.prepare(fetchExpected: true)
manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope, delegateQueue: .sharedConcurrent, callbackQueue: .sharedConcurrent) { result in
results[packageVersion] = result
group.leave()
}
}
if case .timedOut = group.wait(timeout: .now() + 60) {
return XCTFail("timeout")
}
try delegate.wait(timeout: .now() + 2)
XCTAssertEqual(delegate.willFetch.count, concurrency)
XCTAssertEqual(delegate.didFetch.count, concurrency)
XCTAssertEqual(results.count, concurrency)
for packageVersion in packageVersions {
let expectedPath = try downloadsPath.appending(package.downloadPath(version: packageVersion))
XCTAssertEqual(try results[packageVersion]?.get(), expectedPath)
}
}
// same versions
do {
let concurrency = 1000
let repeatRatio = 10
let package: PackageIdentity = .plain("test.\(UUID().uuidString)")
let packageVersions = (0 ..< concurrency / 10).map { Version($0, 0 , 0) }
let packageSource = InMemoryRegistryPackageSource(fileSystem: fs, path: .root.appending(components: "registry", "server", package.description))
try packageSource.writePackageContent()
registry.addPackage(
identity: package,
versions: packageVersions,
source: packageSource
)
delegate.reset()
let group = DispatchGroup()
let results = ThreadSafeKeyValueStore<Version, Result<AbsolutePath, Error>>()
for index in 0 ..< concurrency {
group.enter()
delegate.prepare(fetchExpected: index < concurrency / repeatRatio)
let packageVersion = Version(index % (concurrency / repeatRatio), 0 , 0)
manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope, delegateQueue: .sharedConcurrent, callbackQueue: .sharedConcurrent) { result in
results[packageVersion] = result
group.leave()
}
}
if case .timedOut = group.wait(timeout: .now() + 60) {
return XCTFail("timeout")
}
try delegate.wait(timeout: .now() + 2)
XCTAssertEqual(delegate.willFetch.count, concurrency / repeatRatio)
XCTAssertEqual(delegate.didFetch.count, concurrency / repeatRatio)
XCTAssertEqual(results.count, concurrency / repeatRatio)
for packageVersion in packageVersions {
let expectedPath = try downloadsPath.appending(package.downloadPath(version: packageVersion))
XCTAssertEqual(try results[packageVersion]?.get(), expectedPath)
}
}
}
}
private class MockRegistryDownloadsManagerDelegate: RegistryDownloadsManagerDelegate {
private var _willFetch = [(packageVersion: PackageVersion, fetchDetails: RegistryDownloadsManager.FetchDetails)]()
private var _didFetch = [(packageVersion: PackageVersion, result: Result<RegistryDownloadsManager.FetchDetails, Error>)]()
private let lock = NSLock()
private var group = DispatchGroup()
public func prepare(fetchExpected: Bool) {
if fetchExpected {
group.enter() // will fetch
group.enter() // did fetch
}
}
public func reset() {
self.group = DispatchGroup()
self._willFetch = []
self._didFetch = []
}
public func wait(timeout: DispatchTime) throws {
switch group.wait(timeout: timeout) {
case .success:
return
case .timedOut:
throw StringError("timeout")
}
}
var willFetch: [(packageVersion: PackageVersion, fetchDetails: RegistryDownloadsManager.FetchDetails)] {
return self.lock.withLock { _willFetch }
}
var didFetch: [(packageVersion: PackageVersion, result: Result<RegistryDownloadsManager.FetchDetails, Error>)] {
return self.lock.withLock { _didFetch }
}
func willFetch(package: PackageIdentity, version: Version, fetchDetails: RegistryDownloadsManager.FetchDetails) {
self.lock.withLock {
_willFetch += [(PackageVersion(package: package, version: version), fetchDetails: fetchDetails)]
}
self.group.leave()
}
func didFetch(package: PackageIdentity, version: Version, result: Result<RegistryDownloadsManager.FetchDetails, Error>, duration: DispatchTimeInterval) {
self.lock.withLock {
_didFetch += [(PackageVersion(package: package, version: version), result: result)]
}
self.group.leave()
}
func fetching(package: PackageIdentity, version: Version, bytesDownloaded downloaded: Int64, totalBytesToDownload total: Int64?) {
}
}
extension RegistryDownloadsManager {
fileprivate func lookup(package: PackageIdentity, version: Version, observabilityScope: ObservabilityScope) throws -> AbsolutePath {
return try tsc_await {
self.lookup(
package: package,
version: version,
observabilityScope: observabilityScope,
delegateQueue: .sharedConcurrent,
callbackQueue: .sharedConcurrent, completion: $0
)
}
}
}
fileprivate struct PackageVersion: Hashable, Equatable {
let package: PackageIdentity
let version: Version
}
| apache-2.0 | 42e90019240272b69cb54a1a1f826491 | 43.542529 | 197 | 0.626703 | 5.523375 | false | false | false | false |
coinbase/coinbase-ios-sdk | Source/Resources/Transactions/Models/TransactionParty.swift | 1 | 2333 | //
// TransactionParty.swift
// Coinbase
//
// Copyright © 2018 Coinbase, Inc. All rights reserved.
//
import Foundation
/// List of available transaction parties.
///
/// - email: An email address (e.g. not a registered Coinbase user).
/// - user: Registered Coinbase user.
/// - cryptoAddress: Direct address of Bitcoin, Bitcoin Cash, Litecoin or Ethereum network.
/// - account: An account (e.g. bitcoin, bitcoin cash, litecoin and ethereum wallets, fiat currency accounts, and vaults).
///
public enum TransactionParty: Decodable {
/// An email address (e.g. not a registered Coinbase user).
case email(EmailModel)
/// Registered Coinbase user.
case user(User)
/// Direct address of Bitcoin, Bitcoin Cash, Litecoin or Ethereum network.
case cryptoAddress(CryptoAddress)
/// An account (e.g. bitcoin, bitcoin cash, litecoin and ethereum wallets, fiat currency accounts, and vaults).
case account(Account)
public init(from decoder: Decoder) throws {
let resourceObject = try decoder.singleValueContainer().decode(ResourceObject.self)
switch resourceObject.resource {
case ResourceKeys.user:
let user = try decoder.singleValueContainer().decode(User.self)
self = .user(user)
case ResourceKeys.email:
let email = try decoder.singleValueContainer().decode(EmailModel.self)
self = .email(email)
case ResourceKeys.account:
let account = try decoder.singleValueContainer().decode(Account.self)
self = .account(account)
case let field where field.hasSuffix(ResourceKeys.address) || field.hasSuffix(ResourceKeys.network):
let cryptoAddress = try decoder.singleValueContainer().decode(CryptoAddress.self)
self = .cryptoAddress(cryptoAddress)
default:
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: [],
debugDescription: "Undefined resource type. Failed to decode.")
)
}
}
/// List of supported resource keys.
private struct ResourceKeys {
static let user = "user"
static let email = "email"
static let account = "account"
static let address = "address"
static let network = "network"
}
}
| apache-2.0 | d8853d91beaa31de54cc629fd1b46e07 | 37.866667 | 122 | 0.659949 | 4.692153 | false | false | false | false |
zehrer/SOGraphDB | Sources/SOGraphDB_old/Model/Classes/Common/PropertyAccessElement.swift | 1 | 9562 | //
// PropertyAccessElement.swift
// SOGraphDB
//
// Created by Stephan Zehrer on 16.06.14.
// Copyright (c) 2014 Stephan Zehrer. All rights reserved.
//
import Foundation
public class PropertyAccessElement : GraphElement {
// MARK: Init
// is required in the coding if the subclassess
required public init() {
}
// MARK: Subclass
// subclasses have to override this
var propertyID : UID {
get {
return 0
}
set {
// override
}
}
// override
func update() {
}
// MARK: General
var _propertiesArray:[Property]? = nil
var _propertiesDictionary:[UID: Property]? = nil // The key is the UID of the keyNode
public var propertiesArray: [Property] {
get {
assert(context != nil, "No GraphContext available")
if (_propertiesArray == nil) {
initPropertyData()
readPropertyData()
}
return _propertiesArray!
}
}
public var propertiesDictionary:[UID: Property] {
get {
assert(context != nil, "No GraphContext available")
if (_propertiesDictionary == nil) {
initPropertyData()
readPropertyData()
}
return _propertiesDictionary!
}
}
func initPropertyData() {
_propertiesArray = [Property]()
_propertiesDictionary = Dictionary<UID, Property>()
}
// DONE : more generic version
func readPropertyData() {
// read data
var property:Property? = nil;
var nextPropertyID = propertyID;
while (nextPropertyID > 0) {
property = context!.readProperty(nextPropertyID)
if (property != nil) {
addToPropertyCollections(property!)
nextPropertyID = property!.nextPropertyID
} else {
// TODO: REPORT ERROR
}
}
}
func addToPropertyCollections(property:Property) {
//assert(_propertiesDictionary != nil, "PropertyData was not loaded or added")
//assert(_propertiesArray != nil, "PropertyData was not loaded or added")
_propertiesArray!.append(property)
_propertiesDictionary![property.keyNodeID] = property
}
func removedFromPropertyCollections(property:Property) {
//assert(_propertiesDictionary != nil, "PropertyData was not loaded or added")
//assert(_propertiesArray != nil, "PropertyData was not loaded or added")
_propertiesDictionary!.removeValueForKey(property.keyNodeID)
//let index = find(_propertiesArray!, property) // init propertiesArray in worst case
let index = _propertiesArray!.indexOf(property)
if let index = index {
_propertiesArray!.removeAtIndex(index)
}
}
public func deletePropertyForKey(keyNode:Node) {
if (context != nil) {
let property = propertyForKey(keyNode)
if (property != nil) {
//var data = property.data
deleteProperty(property!)
// return data
}
}
//return nil
}
//MARK: PropertyAccess Support
public func propertyForKey(keyNode:Node) -> Property? {
assert(keyNode.uid != nil, "KeyNode without a uid")
return propertiesDictionary[keyNode.uid!]
}
public func containsProperty(keyNode:Node) -> Bool {
let property = propertyForKey(keyNode)
if property == nil {
return false
}
return true
}
// PreConditions: Element is in a context
func ensurePropertyforKey(keyNode:Node) -> Property {
var property = propertyForKey(keyNode)
if (property == nil) {
property = createPropertyForKeyNode(keyNode)
}
return property!
}
// Create a new property and add it to this element
// This methode update
// - the new property (twice, 1. create 2. update)
// - (optional) the lastProperty -> the property was appended directly
// - (optional) the element -> the property was appended
// PreConditions: Element is in a context
// DONE
func createPropertyForKeyNode(keyNode:Node) -> Property {
assert(context != nil, "No GraphContext available")
let property = Property(graphElement: self, keyNode: keyNode)
context!.registerProperty(property)
addProperty (property)
return property
}
// DONE
func addProperty( property : Property) {
//assert(context != nil, "No GraphContext available")
//assert(property.uid != nil, "KeyNode without a uid") // test does not match to comment
let lastProperty = propertiesArray.last
if (lastProperty != nil) {
// it seems this element has already one or more properties
// add property to the last one
property.previousPropertyID = lastProperty!.uid!;
lastProperty!.nextPropertyID = property.uid!;
// CONTEXT WRITE
// updated of the LAST relationship is only required if
// the is was extended
context!.updateProperty(lastProperty!)
} else {
// It seems this is the frist property
// add property to the element (e.g. Node -> Property)
self.propertyID = property.uid!
// CONTEXT WRITE
// update of self is only required if the id was set
self.update()
}
// CONTEXT WRTIE
context!.updateProperty(property)
// add property to internal array
addToPropertyCollections(property)
}
// DONE
func deleteProperty(property:Property) {
assert(context != nil, "No GraphContext available")
var previousProperty:Property? = nil
var nextProperty:Property? = nil
let nextPropertyID:UID = property.nextPropertyID
let previousPropertyID = property.previousPropertyID
if (nextPropertyID > 0) {
nextProperty = context!.readProperty(nextPropertyID)
if (nextProperty != nil) {
nextProperty!.previousPropertyID = previousPropertyID
// CONTEXT WRITE
context!.updateProperty(nextProperty!)
} else {
// TODO: ERROR
}
}
if (previousPropertyID > 0) {
previousProperty = context!.readProperty(previousPropertyID)
if (nextProperty != nil) {
previousProperty!.nextPropertyID = nextPropertyID
// CONTEXT WRITE
context!.updateProperty(previousProperty!)
} else {
// TODO: ERROR
}
} else {
// seems this is the first property in the chain
self.propertyID = nextPropertyID
// CONTEXT WRITE
// update of self is only required if the id was set
self.update()
}
// update property to internal array and maps
removedFromPropertyCollections(property)
// last step delete the property itself
property.delete()
}
func raiseError() {
//#warning writing exception key
//[NSException raise:NSInvalidArchiveOperationException format:@"Property for key not found"];
}
//MARK: PropertyAccess Protocol
// DONE
public subscript(keyNode: Node) -> Property {
get {
assert(context != nil, "No GraphContext available")
return ensurePropertyforKey(keyNode)
}
/**
set a nil valie would lead to an optional return value
set {
if newValue == nil {
var property = propertyForKey(keyNode)
if property != nil {
deleteProperty(property!)
}
// property == nil -> do nothing :)
} else {
assertionFailure("ERROR: this interface does not allow setting values")
}
}
*/
}
/**
// Exampled how to use
var a = Node() // <- auto default context (not implemented yet !!!)
var b = Node() // <- auto default context
var keyNode = Node()
a[keyNode].value = 1
b[keyNode].value = "Test"
var result = a[keyNode].value
a[keyNode].valueInt = 1
b[keyNode].valueString = "Test"
*/
/**
subscript(keyNode: Node) -> Double {
get {
var property = propertyForKey(keyNode)
if (property != nil) {
//return property.value
}
raiseError()
return 0
}
set {
assert(context != nil, "No GraphContext available")
var property = ensurePropertyforKey(keyNode)
//property.value = newValue
context.updateProperty(property)
}
}
*/
} | mit | 40f64f11e5df22685940df8d7b475b8e | 27.631737 | 102 | 0.536812 | 5.253846 | false | false | false | false |
nielubowicz/Particle-SDK | Source/ParticleDevice.swift | 1 | 8489 | //
// ParticleDevice.swift
// Particle-SDK
//
// Created by Chris Nielubowicz on 11/17/15.
// Copyright © 2015 Mobiquity, Inc. All rights reserved.
//
import Foundation
import Alamofire
enum DeviceParameterNames : String {
case id
case name
case last_app
case connected
case last_ip_address
case last_heard
}
public class ParticleDevice : NSObject {
public var id : String = ""
public var deviceName : String = ""
public var last_app: String = ""
public var connected: Bool = false
public var last_ip_address: String = ""
public var last_heard: String = ""
init(deviceJSON: Dictionary<String,AnyObject>) {
if let id = deviceJSON[DeviceParameterNames.id.rawValue] as? String {
self.id = id
}
if let deviceName = deviceJSON[DeviceParameterNames.name.rawValue] as? String {
self.deviceName = deviceName
}
if let last_app = deviceJSON[DeviceParameterNames.last_app.rawValue] as? String {
self.last_app = last_app
}
if let connected = deviceJSON[DeviceParameterNames.connected.rawValue] as? NSNumber {
self.connected = connected.boolValue
}
if let last_ip_address = deviceJSON[DeviceParameterNames.last_ip_address.rawValue] as? String {
self.last_ip_address = last_ip_address
}
if let last_heard = deviceJSON[DeviceParameterNames.last_heard.rawValue] as? String {
self.last_heard = last_heard
}
}
override public var description : String {
return "(\(id)): \(deviceName)"
}
}
// MARK: Variable / Function Access
extension ParticleDevice {
public func getVariable(withName: String, completion:( (AnyObject?, NSError?) -> Void)) {
guard Particle.sharedInstance.OAuthToken != nil else { return }
let variableURL = url(ParticleEndpoints.Variable(deviceName: deviceName, authToken: Particle.sharedInstance.OAuthToken!, variableName: withName))
Alamofire.request(.GET, variableURL)
.responseJSON { response in
if (response.result.error != nil) {
completion(nil, response.result.error)
return;
}
if let JSON = response.result.value as? Dictionary<String, AnyObject> {
completion(JSON[ResponseParameterNames.result.rawValue], nil)
} else {
let particleError = ParticleErrors.VariableResponse(deviceName: self.deviceName, variableName: withName)
completion(nil, particleError.error)
}
}
}
func callFunction(named: String, arguments: Array<AnyObject>?, completion:( (NSNumber?, NSError?) -> Void)) {
guard Particle.sharedInstance.OAuthToken != nil else { return }
var arguments: Dictionary<String,AnyObject>?
if let args = arguments {
let argsValue = args.map({ "\($0)"}).joinWithSeparator(",")
if argsValue.characters.count > 63 {
let particleError = ParticleErrors.MaximumArgLengthExceeded()
completion(nil, particleError.error)
return
}
arguments = ["args": argsValue]
}
let variableURL = url(ParticleEndpoints.Function(deviceName: deviceName, authToken: Particle.sharedInstance.OAuthToken!, functionName: named))
Alamofire.request(.POST, variableURL, parameters: arguments)
.authenticate(user: Particle.sharedInstance.OAuthToken!, password: "")
.responseJSON { response in
if (response.result.error != nil) {
completion(nil, response.result.error)
return
}
if let JSON = response.result.value as? Dictionary<String, AnyObject> {
if let connected = JSON[ResponseParameterNames.connected.rawValue] as? NSNumber {
if (connected == false) {
let particleError = ParticleErrors.DeviceNotConnected(deviceName: self.deviceName)
completion(nil, particleError.error)
return
}
}
completion(JSON[ResponseParameterNames.return_value.rawValue] as? NSNumber, nil)
} else {
let particleError = ParticleErrors.FunctionResponse(deviceName: self.deviceName, functionName: named)
completion(nil, particleError.error)
}
}
}
}
// MARK: Housekeeping
extension ParticleDevice {
func refresh(completion:( (NSError?) -> Void)) {
Particle.sharedInstance.getDevice(self.id) { (device, error) -> Void in
if let error = error {
completion(error)
}
guard let device = device else {
completion(ParticleErrors.DeviceFailedToRefresh(deviceName: self.deviceName).error)
return
}
var propertyNames = Set<NSString>()
var outCount: UInt32 = 0
let properties = class_copyPropertyList(NSClassFromString("Particle-SDK.ParticleDevice"), &outCount)
for i in 0...Int(outCount) {
let property = properties[i]
if let propertyName = NSString(CString: property_getName(property), encoding:NSStringEncodingConversionOptions.AllowLossy.rawValue) {
propertyNames.insert(propertyName)
}
}
free(properties)
for property in propertyNames {
let p = String(property)
let value = device.valueForKey(p)
self.setValue(value, forKey: p)
}
}
}
//
// /**
// * Remove device from current logged in user account
// *
// * @param completion Completion block called when function completes with NSError object in case of an error or nil if success.
// */
// -(void)unclaim:(void(^)(NSError* error))completion;
//
//
// /**
// * Rename device
// *
// * @param newName New device name
// * @param completion Completion block called when function completes with NSError object in case of an error or nil if success.
// */
// -(void)rename:(NSString *)newName completion:(void(^)(NSError* error))completion;
//
}
// MARK: Event Handling
// /*
// -(void)addEventHandler:(NSString *)eventName handler:(void(^)(void))handler;
// -(void)removeEventHandler:(NSString *)eventName;
// */
//
//
// MARK: Compilation / Flashing
// /**
// * Flash files to device
// *
// * @param filesDict files dictionary in the following format: @{@"filename.bin" : <NSData>, ...} - that is a NSString filename as key and NSData blob as value. More than one file can be flashed. Data is alway binary.
// * @param completion Completion block called when function completes with NSError object in case of an error or nil if success. NSError.localized descripion will contain a detailed error report in case of a
// */
// -(void)flashFiles:(NSDictionary *)filesDict completion:(void(^)(NSError* error))completion; //@{@"<filename>" : NSData, ...}
// /*
// -(void)compileAndFlash:(NSString *)sourceCode completion:(void(^)(NSError* error))completion;
// -(void)flash:(NSData *)binary completion:(void(^)(NSError* error))completion;
// */
//
// /**
// * Flash known firmware images to device
// *
// * @param knownAppName NSString of known app name. Currently @"tinker" is supported.
// * @param completion Completion block called when function completes with NSError object in case of an error or nil if success. NSError.localized descripion will contain a detailed error report in case of a
// */
// -(void)flashKnownApp:(NSString *)knownAppName completion:(void (^)(NSError *))completion; // knownAppName = @"tinker", @"blinky", ... see http://docs.
//
// //-(void)compileAndFlashFiles:(NSDictionary *)filesDict completion:(void(^)(NSError* error))completion; //@{@"<filename>" : @"<file contents>"}
// //-(void)complileFiles:(NSDictionary *)filesDict completion:(void(^)(NSData *resultBinary, NSError* error))completion; //@{@"<filename>" : @"<file contents>"}
// | mit | 69d91fb9491d115de9b9e2138baad2f6 | 40.612745 | 225 | 0.60344 | 4.605534 | false | false | false | false |
asm-products/kanshu-ios | kanshu/kanshu/ArticleListViewController.swift | 1 | 2846 | //
// ArticleListViewController.swift
// kanshu
//
// Created by Christopher Wood on 3/25/15.
// Copyright (c) 2015 Fluid Pixel Ltd. All rights reserved.
//
import UIKit
class ArticleListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
articleListTableView.delegate = self
articleListTableView.dataSource = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Alert View Setup
func showAlertView(title: String) {
let alertView = UIAlertController(title: title, message: "\(title)", preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: .Cancel) { action -> Void in
//Just dismiss the action sheet
}
alertView.addAction(cancelAction)
self.presentViewController(alertView, animated: true, completion: nil)
}
// MARK: - TableViewController
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return sampleEntryList.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return sampleEntryList[section].count
}
private struct Storyboard {
static let CellReuseIdentifier = "ArticleCell"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.CellReuseIdentifier, forIndexPath: indexPath) as ArticleListTableViewCell
cell.entry = sampleEntryList[indexPath.section][indexPath.row]
return cell
}
// MARK: - Instantiate Properties
@IBOutlet weak var articleListTableView: UITableView!
@IBAction func menuButton(sender: UIBarButtonItem) {
showAlertView("Menu Button Pressed")
}
@IBAction func searchTextField(sender: UITextField) {
showAlertView("Search Successful")
}
@IBOutlet weak var searchTextField: SearchTextField!
private var articleListView: ArticleListView! { return view as ArticleListView }
// MARK: - TextField Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| agpl-3.0 | 51b58e48f3081afa0ecf4d2e7ba120b5 | 32.093023 | 147 | 0.675685 | 5.737903 | false | false | false | false |
pikciu/RxCells | RxCells/Example/SimpleBindingViewController.swift | 1 | 1154 | //
// SimpleBindingViewController.swift
// RxCells
//
// Created by Tomasz Pikć on 03/01/2020.
//
import UIKit
import RxSwift
import RxCocoa
final class SimpleBindingViewController: UIViewController {
let tableView = UITableView()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.register(cellType: SampleCell.self)
Observable.just(Array(0..<100))
.bind(to: tableView.rx.cells(SampleCell.self, withDelegate: self))
.disposed(by: disposeBag)
}
}
extension SimpleBindingViewController: SampleCellDelegate {
func someDelegateMethod() {
}
}
| mit | a8f043e94eb9b22ac332ca19d8518b45 | 28.564103 | 89 | 0.689506 | 5.013043 | false | false | false | false |
Incipia/Goalie | Goalie/UIColor+Extensions.swift | 1 | 8199 | //
// UIColor+Extensions.swift
// Goalie
//
// Created by Gregory Klein on 12/16/15.
// Copyright © 2015 Incipia. All rights reserved.
//
import UIKit
enum GoalieHeadComponent {
case background, cheek, chin, stripe
}
/*
Empty:
- background: (106, 104, 181)
- cheeks: (249, 205, 223, 0.2)
- chin: (30, 94, 99, .2)
AGES:
- background: (8, 207, 152)
- cheeks: (249, 205, 223, 0.4)
- chin: (29, 153, 118, 0.2)
LATER:
- background: (14, 127, 204)
- cheeks: (249, 205, 223, 0.4)
- chin: (28, 77, 109, 0.2)
SOON:
- background: (106, 104, 181)
- cheeks: (249, 205, 223, 0.4)
- chin: (198, 133, 16, 0.3)
ASAP:
- background: (211, 57, 87)
- cheeks: (249, 205, 223, 0.3)
- chin: (153, 29, 59, 0.2)
*/
private func _rgb(_ priority: TaskPriority, component: GoalieHeadComponent) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)
{
var values: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) = (0, 0, 0, 0)
switch component
{
case .background:
values = _headBackgroundRGBA(priority)
case .cheek:
values = _headCheeksRGBA(priority)
case .chin:
values = _headChinRGBA(priority)
case .stripe:
values = _headStripeRGBA(priority)
}
return values
}
private func _headBackgroundRGBA(_ priority: TaskPriority) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)
{
var values: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) = (0, 0, 0, 0)
switch priority
{
case .ages:
values = (4, 191, 133, 1)
break
case .later:
values = (14, 127, 204, 1)
break
case .soon:
values = (229, 161, 23, 1)
break
case .asap:
values = (211, 57, 87, 1)
break
case .unknown:
values = (106, 104, 181, 1)
break
}
values = (values.r/255.0, values.g/255.0, values.b/255.0, values.a)
return values
}
private func _headCheeksRGBA(_ priority: TaskPriority) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)
{
var values: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) = (0, 0, 0, 0)
switch priority
{
case .ages:
values = (249, 205, 223, 0.4)
break
case .later:
values = (249, 205, 223, 0.4)
break
case .soon:
values = (249, 205, 223, 0.4)
break
case .asap:
values = (249, 205, 223, 0.3)
break
case .unknown:
values = (249, 205, 223, 0.2)
break
}
values = (values.r/255.0, values.g/255.0, values.b/255.0, values.a)
return values
}
private func _headChinRGBA(_ priority: TaskPriority) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)
{
var values: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) = (0, 0, 0, 0)
switch priority
{
case .ages:
values = (29, 153, 118, 0.2)
break
case .later:
values = (28, 77, 109, 0.2)
break
case .soon:
values = (198, 133, 16, 0.3)
break
case .asap:
values = (153, 29, 59, 0.2)
break
case .unknown:
values = (30, 94, 99, 0.2)
break
}
values = (values.r/255.0, values.g/255.0, values.b/255.0, values.a)
return values
}
private func _headStripeRGBA(_ priority: TaskPriority) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)
{
var values: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) = (0, 0, 0, 0)
switch priority
{
case .ages:
values = (29, 100, 79, 1)
break
case .later:
values = (28, 77, 109, 1)
break
case .soon:
values = (198, 133, 16, 1)
break
case .asap:
values = (153, 29, 59, 1)
break
case .unknown:
values = (74, 74, 147, 1)
break
}
values = (values.r/255.0, values.g/255.0, values.b/255.0, values.a)
return values
}
private func _rgbValuesForPriority(_ priority: TaskPriority) -> (r: CGFloat, g: CGFloat, b: CGFloat)
{
var values: (r: CGFloat, g: CGFloat, b: CGFloat) = (0, 0, 0)
switch priority
{
case .ages:
values = (18, 225, 168)
break
case .later:
values = (18, 164, 255)
break
case .soon:
values = (255, 200, 31)
break
case .asap:
values = (255, 80, 100)
break
case .unknown:
values = (228, 229, 231)
break
}
values = (values.r/255.0, values.g/255.0, values.b/255.0)
return values
}
private func _headerBackgroundRGBValuesForPriority(_ priority: TaskPriority) -> (r: CGFloat, g: CGFloat, b: CGFloat)
{
var values: (r: CGFloat, g: CGFloat, b: CGFloat) = (0, 0, 0)
switch priority
{
case .ages:
values = (18, 225, 168)
break
case .later:
values = (18, 164, 255)
break
case .soon:
values = (255, 200, 31)
break
case .asap:
values = (255, 80, 100)
break
case .unknown:
values = (130, 122, 209)
break
}
values = (values.r/255.0, values.g/255.0, values.b/255.0)
return values
}
extension UIColor
{
convenience init(priority: TaskPriority, headComponent: GoalieHeadComponent)
{
let values = _rgb(priority, component: headComponent)
let color = UIColor(colorLiteralRed: Float(values.r), green: Float(values.g), blue: Float(values.b), alpha: Float(values.a))
self.init(cgColor: color.cgColor)
}
convenience init(priority: TaskPriority)
{
let values = _rgbValuesForPriority(priority)
let color = UIColor(colorLiteralRed: Float(values.r), green: Float(values.g), blue: Float(values.b), alpha: 1)
self.init(cgColor: color.cgColor)
}
static func goalieHeaderBackgroundColor(_ averagePriority: TaskPriority) -> UIColor
{
let values = _headerBackgroundRGBValuesForPriority(averagePriority)
return UIColor(colorLiteralRed: Float(values.r), green: Float(values.g), blue: Float(values.b), alpha: 1)
}
fileprivate convenience init(r: CGFloat, g: CGFloat, b: CGFloat)
{
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
}
convenience init(rgbValues: (r: Float, g: Float, b: Float))
{
self.init(colorLiteralRed: rgbValues.r/255.0, green: rgbValues.g/255.0, blue: rgbValues.b/255.0, alpha: 1)
}
static func goalieEmptyTasksColor() -> UIColor
{
return UIColor(colorLiteralRed: 130/255.0, green: 122/255.0, blue: 209/255.0, alpha: 1)
}
static func goalieGrayColor() -> UIColor
{
return UIColor(colorLiteralRed: 228/255.0, green: 229/255.0, blue: 231/255.0, alpha: 1)
}
static func lightGoalieGrayColor() -> UIColor
{
return UIColor(colorLiteralRed: 228/255.0, green: 229/255.0, blue: 231/255.0, alpha: 0.6)
}
static func eyeColorForPriority(_ priority: TaskPriority) -> UIColor
{
switch priority
{
case .ages: return UIColor(red: 0.098, green: 0.324, blue: 0.243, alpha: 1.000)
case .later: return UIColor(red: 0.090, green: 0.233, blue: 0.352, alpha: 1.000)
case .soon: return UIColor(red: 0.611, green: 0.356, blue: 0.044, alpha: 1.000)
case .asap: return UIColor(red: 0.522, green: 0.053, blue: 0.177, alpha: 1.000)
case .unknown: return UIColor(red: 0.225, green: 0.211, blue: 0.504, alpha: 1.000)
}
}
static func bizeeBeeCheeckColor(_ priority: TaskPriority) -> UIColor
{
switch priority
{
case .ages: return UIColor(red: 0.945, green: 0.890, blue: 0.914, alpha: 0.400)
case .later: return UIColor(red: 0.965, green: 0.752, blue: 0.845, alpha: 0.300)
case .soon: return UIColor(red: 0.965, green: 0.752, blue: 0.845, alpha: 0.300)
case .asap: return UIColor(red: 0.965, green: 0.752, blue: 0.845, alpha: 0.300)
case .unknown: return UIColor(red: 0.965, green: 0.752, blue: 0.845, alpha: 0.300)
}
}
static func bizeeBeeStripeColor(_ priority: TaskPriority) -> UIColor
{
switch priority
{
case .ages: return UIColor(red: 0.098, green: 0.325, blue: 0.243, alpha: 0.400)
case .later: return UIColor(red: 0.090, green: 0.233, blue: 0.352, alpha: 0.400)
case .soon: return UIColor(red: 0.722, green: 0.448, blue: 0.061, alpha: 1.000)
case .asap: return UIColor(red: 0.522, green: 0.053, blue: 0.177, alpha: 0.400)
case .unknown: return UIColor(red: 0.225, green: 0.211, blue: 0.504, alpha: 0.400)
}
}
}
| apache-2.0 | 415cd18360cfc5ccd96f57cfcaefcd82 | 27.075342 | 130 | 0.601 | 3.043059 | false | false | false | false |
pablogsIO/MadridShops | MadridShopsTests/Model/CityDataInformationTests.swift | 1 | 1285 | //
// ShopsTests.swift
// MadridShopsTests
//
// Created by Pablo García on 07/09/2017.
// Copyright © 2017 KC. All rights reserved.
//
import XCTest
@testable import MadridShops
class CityDataInformationTests: XCTestCase {
var cdiList: CityDataInformationList?
override func setUp() {
super.setUp()
let expectationTest = expectation(description: "Expectations")
let downloadCDI = DownloadCityDataInformationInteractorNSURLSessionImpl()
downloadCDI.execute(urlString: Constants.urlMadridShops) { (cityDataInformationList: CityDataInformationList) in
self.cdiList = cityDataInformationList
expectationTest.fulfill()
}
waitForExpectations(timeout: 20.0, handler:nil)
}
func testGivenEmptyShopsNumberShopsIsZero() {
//sut: system under testing
let sut = CityDataInformationList()
XCTAssertEqual(0, sut.count())
}
func testGivenShopsWithOneElementNumberShopsIsOne() {
let sut = CityDataInformationList()
sut.add(cityDataInformation: CityDataInformation(name: "Shop"))
XCTAssertEqual(1, sut.count())
}
func testImagesURLs(){
if let cdiList = self.cdiList, let imagesURLs = self.cdiList?.getImagesURL(){
XCTAssert(imagesURLs.count == 3*cdiList.count())
}
}
}
| mit | b02d0f34e92585387431653c666f27e8 | 23.207547 | 114 | 0.717069 | 3.697406 | false | true | false | false |
con-beo-vang/Spendy | Spendy/Helpers/UIColor+Extension.swift | 1 | 667 | //
// UIColor+Extension.swift
// Spendy
//
// Created by Dave Vo on 11/14/15.
// Copyright © 2015 Cheetah. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
| mit | f66f218281de15e703c86dc7e2a59f22 | 27.956522 | 112 | 0.62012 | 3.186603 | false | false | false | false |
xiaomudegithub/iosstar | iOSStar/General/Base/BaseWebVC.swift | 3 | 935 | //
// BaseWebVC.swift
// iOSStar
//
// Created by sum on 2017/6/1.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import WebKit
class BaseWebVC: UIViewController {
var loadRequest = "" {
didSet {
webView?.loadRequest(URLRequest.init(url: NSURL.fileURL(withPath: loadRequest)))
}
}
var navtitle = ""
var webView : UIWebView?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
title = navtitle
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: view.width, height: view.height-64))
let url = URL(string: loadRequest)
let request = URLRequest(url: url!)
webView.load(request)
view.addSubview(webView)
}
}
| gpl-3.0 | bceb60de400c2a74465890ba016525d1 | 24.888889 | 101 | 0.627682 | 4.236364 | false | false | false | false |
andr3a88/TryNetworkLayer | TryNetworkLayer/Controllers/UserDetail/UserDetailViewModel.swift | 1 | 814 | //
// UserDetailViewModel.swift
// TryNetworkLayer
//
// Created by Andrea Stevanato on 03/09/2017.
// Copyright © 2019 Andrea Stevanato All rights reserved.
//
import Foundation
final class UserDetailViewModel {
// MARK: Observables
@Published var username: String = ""
// MARK: Properties
private(set) var user: GHUserDetail?
let usersRepo: UsersRepoProtocol
// MARK: Methods
init(usersRepo: UsersRepoProtocol = UsersRepo(), userLogin: String) {
self.usersRepo = usersRepo
self.username = userLogin
}
func fecthUser() {
usersRepo.fetchDetail(username: username) { [weak self] (user) in
if let user = user {
self?.user = user
self?.username = user.login!
}
}
}
}
| mit | a2f666e541629241966c4128743d6057 | 20.972973 | 73 | 0.606396 | 4.278947 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | bluefruitconnect/Platform/OSX/Controllers/NeopixelViewControllerOSX.swift | 1 | 7413 | //
// NeopixelViewController.swift
// Bluefruit Connect
//
// Created by Antonio García on 10/01/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import Cocoa
class NeopixelViewControllerOSX: NSViewController {
// Config
private static let kShouldAutoconnectToNeopixel = true
// Constants
private static let kUartTimeout = 5.0 // seconds
// UI
@IBOutlet weak var statusImageView: NSImageView!
@IBOutlet weak var statusLabel: NSTextField!
@IBOutlet weak var sendButton: NSButton!
// Bluetooth Uart
private let uartData = UartManager.sharedInstance
private var uartResponseDelegate : ((NSData?)->Void)?
private var uartResponseTimer : NSTimer?
// Neopixel
private var isNeopixelSketchAvailable : Bool?
private var isSendingData = false
override func viewDidLoad() {
super.viewDidLoad()
}
deinit {
cancelUartResponseTimer()
}
func start() {
DLog("neopixel start");
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(NeopixelViewControllerOSX.didReceiveData(_:)), name: UartManager.UartNotifications.DidReceiveData.rawValue, object: nil)
}
func stop() {
DLog("neopixel stop");
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: UartManager.UartNotifications.DidReceiveData.rawValue, object: nil)
cancelUartResponseTimer()
}
func connectNeopixel() {
start()
if NeopixelViewControllerOSX.kShouldAutoconnectToNeopixel {
self.checkNeopixelSketch()
}
}
// MARK: Notifications
func uartIsReady(notification: NSNotification) {
DLog("Uart is ready")
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: UartManager.UartNotifications.DidBecomeReady.rawValue, object: nil)
dispatch_async(dispatch_get_main_queue(),{ [unowned self] in
self.connectNeopixel()
})
}
// MARK: - Neopixel Commands
private func checkNeopixelSketch() {
// Send version command and check if returns a valid response
DLog("Ask Version...")
let text = "V"
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
sendDataToUart(data) { [unowned self] responseData in
var isNeopixelSketchAvailable = false
if let data = responseData, result = NSString(data:data, encoding: NSUTF8StringEncoding) as? String {
isNeopixelSketchAvailable = result.hasPrefix("Neopixel")
}
DLog("isNeopixelAvailable: \(isNeopixelSketchAvailable)")
self.isNeopixelSketchAvailable = isNeopixelSketchAvailable
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.updateUI()
});
}
}
}
private func updateUI() {
var statusText = "Connecting..."
statusImageView.image = NSImage(named: "NSStatusNone")
if let isNeopixelSketchAvailable = isNeopixelSketchAvailable {
statusText = isNeopixelSketchAvailable ? "Neopixel: Ready" : "Neopixel: Not available"
statusImageView.image = NSImage(named: isNeopixelSketchAvailable ?"NSStatusAvailable":"NSImageNameStatusUnavailable")
}
statusLabel.stringValue = statusText
sendButton.enabled = isNeopixelSketchAvailable == true && !isSendingData
}
// MARK: - Uart
private func sendDataToUart(data: NSData, completionHandler: (response: NSData?)->Void) {
guard uartResponseDelegate == nil && uartResponseTimer == nil else {
DLog("sendDataToUart error: waiting for a previous response")
return
}
uartResponseTimer = NSTimer.scheduledTimerWithTimeInterval(NeopixelViewControllerOSX.kUartTimeout, target: self, selector: #selector(NeopixelViewControllerOSX.uartResponseTimeout), userInfo: nil, repeats: false)
uartResponseDelegate = completionHandler
uartData.sendData(data)
}
func didReceiveData(notification: NSNotification) {
if let dataChunk = notification.userInfo?["dataChunk"] as? UartDataChunk {
if let uartResponseDelegate = uartResponseDelegate {
self.uartResponseDelegate = nil
cancelUartResponseTimer()
uartResponseDelegate(dataChunk.data)
}
}
}
func uartResponseTimeout() {
DLog("uartResponseTimeout")
if let uartResponseDelegate = uartResponseDelegate {
self.uartResponseDelegate = nil
cancelUartResponseTimer()
uartResponseDelegate(nil)
}
}
private func cancelUartResponseTimer() {
uartResponseTimer?.invalidate()
uartResponseTimer = nil
}
// MARK: - Actions
@IBAction func onClickSend(sender: AnyObject) {
let data = NSMutableData()
let width : UInt8 = 8
let height : UInt8 = 4
let command : [UInt8] = [0x44, width, height ] // Command: 'D', Width: 8, Height: 8
data.appendBytes(command, length: command.count)
let redPixel : [UInt8] = [32, 1, 1 ]
let blackPixel : [UInt8] = [0, 0, 0 ]
var imageData : [UInt8] = []
let imageLength = width * height
for i in 0..<imageLength {
imageData.appendContentsOf(i%2==0 ? redPixel : blackPixel)
}
data.appendBytes(imageData, length: imageData.count)
//DLog("Send data: \(hexString(data))")
/*
if let message = NSString(data: data, encoding: NSUTF8StringEncoding) {
DLog("Send data: \(message)")
}
*/
isSendingData = true
sendDataToUart(data) { [unowned self] responseData in
var success = false
if let data = responseData, result = NSString(data:data, encoding: NSUTF8StringEncoding) as? String {
success = result.hasPrefix("OK")
}
DLog("configured: \(success)")
self.isSendingData = false
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
self.updateUI()
});
}
}
}
// MARK: - DetailTab
extension NeopixelViewControllerOSX : DetailTab {
func tabWillAppear() {
uartData.blePeripheral = BleManager.sharedInstance.blePeripheralConnected // Note: this will start the service discovery
if (uartData.isReady()) {
connectNeopixel()
}
else {
DLog("Wait for uart to be ready to start PinIO setup")
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(NeopixelViewControllerOSX.uartIsReady(_:)), name: UartManager.UartNotifications.DidBecomeReady.rawValue, object: nil)
}
updateUI()
}
func tabWillDissapear() {
stop()
}
func tabReset() {
}
}
| mit | afcafc1470b0a49538c87b6b16034150 | 33.310185 | 219 | 0.617191 | 4.828013 | false | false | false | false |
cpageler93/ConsulSwift | Sources/ConsulSwift/ConsulAgentCheck.swift | 1 | 2844 | //
// ConsulAgentCheck.swift
// ConsulSwift
//
// Created by Christoph on 26.05.17.
//
//
import Foundation
import Quack
public extension Consul {
public enum AgentCheckStatus: String {
case passing
case warning
case critical
}
public class AgentCheckOutput: Quack.Model {
public var node: String
public var checkID: String
public var name: String
public var status: AgentCheckStatus?
public var notes: String?
public var output: String?
public var serviceID: String?
public var serviceName: String?
required public init?(json: JSON) {
guard let node = json["Node"].string,
let checkID = json["CheckID"].string,
let name = json["Name"].string,
let status = json["Status"].string
else {
return nil
}
self.node = node
self.checkID = checkID
self.name = name
self.status = AgentCheckStatus(rawValue: status)
self.notes = json["Notes"].string
self.output = json["Output"].string
self.serviceID = json["ServiceID"].string
self.serviceName = json["ServiceName"].string
}
}
public class AgentCheckInput {
public var name: String
public var id: String?
public var notes: String?
public var deregisterCriticalServiceAfter: String? // 90m
public var script: String?
public var dockerContainerID: String?
public var serviceID: String?
public var http: String?
public var tcp: String?
public var interval: String? // 10s
public var ttl: String? // 15s
public var tlsSkipVerify: Bool = false
public var status: AgentCheckStatus?
public init(name: String, ttl: String) {
self.name = name
self.ttl = ttl
}
public init(name: String, script: String, interval: String) {
self.name = name
self.script = script
self.interval = interval
}
public init(name: String, dockerContainerID: String, interval: String) {
self.name = name
self.dockerContainerID = dockerContainerID
self.interval = interval
}
public init(name: String, http: String, interval: String) {
self.name = name
self.http = http
self.interval = interval
}
public init(name: String, tcp: String, interval: String) {
self.name = name
self.tcp = tcp
self.interval = interval
}
}
}
| mit | b0347320464c4219b05959541d6509fd | 26.882353 | 80 | 0.53692 | 4.895009 | false | false | false | false |
PlutoMa/EmployeeCard | EmployeeCard/EmployeeCard/Core/LiftVC/LiftVC.swift | 1 | 5765 | //
// LeftVC.swift
// EmployeeCard
//
// Created by PlutoMa on 2017/4/6.
// Copyright © 2017年 PlutoMa. All rights reserved.
//
import UIKit
class LiftVC: UIViewController {
let bannerImageArr: [String] = ["life_banner1.png", "life_banner2.png", "life_banner3.png"]
fileprivate lazy var configArr: [ConfigModel] = {
var configArr = [ConfigModel]()
var configModel: ConfigModel?
configModel = ConfigModel(text: "通讯录", segue: "liftToAddressBook", icon: "txl.png")
configArr.append(configModel!)
configModel = ConfigModel(text: "航班", segue: "liftToBus", icon: "bc.png")
configArr.append(configModel!)
configModel = ConfigModel(text: "地图", segue: "liftToMap", icon: "dldt.png")
configArr.append(configModel!)
configModel = ConfigModel(text: "婚讯", segue: "liftToWedding", icon: "hytz.png")
configArr.append(configModel!)
configModel = ConfigModel(text: "记录", segue: "liftToRecord", icon: "jcjl.png")
configArr.append(configModel!)
configModel = ConfigModel(text: "菜谱", segue: "liftToFoods", icon: "cp.png")
configArr.append(configModel!)
return configArr
}()
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension LiftVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 1
} else if section == 1{
return configArr.count
} else {
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LiftCell1", for: indexPath)
var carouselView = cell.contentView.viewWithTag(11111) as? CarouselView
if carouselView == nil {
carouselView = CarouselView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width / 1080.0 * 452.0), imageArr: bannerImageArr)
carouselView?.tag = 11111
cell.contentView.addSubview(carouselView!)
}
return cell
} else if indexPath.section == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LiftCell2", for: indexPath)
var imageView = cell.contentView.viewWithTag(11111) as? UIImageView
var textLabel = cell.contentView.viewWithTag(11112) as? UILabel
let configModel = configArr[indexPath.item]
let cellSize = CGSize(width: (UIScreen.main.bounds.width - 2) / 3.0, height: (UIScreen.main.bounds.width - 2) / 3.0 / 250.0 * 270.0)
if imageView == nil {
imageView = UIImageView(frame: CGRect(x: cellSize.width / 4.0, y: cellSize.height / 2.0 - cellSize.width / 2.0 / 151.0 * 124.0 + 10, width: cellSize.width / 2.0, height: cellSize.width / 2.0 / 151.0 * 124.0))
imageView?.tag = 11111
cell.contentView.addSubview(imageView!)
}
if textLabel == nil {
textLabel = UILabel(frame: CGRect(x: 0, y: 0, width: cellSize.width, height: cellSize.height / 3.0))
textLabel?.center = CGPoint(x: cellSize.width / 2.0, y: cellSize.height / 4.0 * 3.0)
textLabel?.textAlignment = .center
textLabel?.textColor = UIColor.black
textLabel?.font = UIFont.systemFont(ofSize: 13)
textLabel?.tag = 11112
cell.contentView.addSubview(textLabel!)
}
imageView?.image = UIImage(named: configModel.icon)
textLabel?.text = configModel.text
return cell
} else {
let cell = UICollectionViewCell()
return cell
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 0 {
return CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width / 1080.0 * 452.0)
} else if indexPath.section == 1 {
return CGSize(width: (UIScreen.main.bounds.width - 2) / 3.0, height: (UIScreen.main.bounds.width - 2) / 3.0 / 250.0 * 270.0)
} else {
return CGSize.zero
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let configModel = configArr[indexPath.item]
performSegue(withIdentifier: configModel.segue, sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let viewC = segue.destination
viewC.hidesBottomBarWhenPushed = true
}
}
| mit | 321f21ea1cb56dd7000f5b771dd5d07e | 43.465116 | 224 | 0.634937 | 4.58147 | false | true | false | false |
cpoutfitters/cpoutfitters | CPOutfitters/SocialTypeCell.swift | 1 | 4020 | //
// SocialTypeCell.swift
// CPOutfitters
//
// Created by Cory Thompson on 4/4/16.
// Copyright © 2016 SnazzyLLama. All rights reserved.
//
import UIKit
import Parse
import ParseUI
import ChameleonFramework
class SocialTypeCell: UITableViewCell {
@IBOutlet weak var captionLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var topImageView: PFImageView!
@IBOutlet weak var bottomImageView: PFImageView!
@IBOutlet weak var footwearImageView: PFImageView!
@IBOutlet weak var profileImageView: PFImageView!
@IBOutlet weak var topImageAverageColorView: UIView!
@IBOutlet weak var bottomImageAverageColorView: UIView!
var post: PFObject! {
didSet {
let author = post["author"] as? PFUser
self.authorLabel.text = author?["fullname"] as? String
self.captionLabel.text = post["caption"] as? String
//profileImageView.image = author?["profilePicture"] as? PFFile
if let profileImageFile = author?["profilePicture"] as? PFFile {
profileImageFile.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) in
if error == nil {
if let imageData = imageData {
self.profileImageView.image = UIImage(data: imageData)
}
}
})
}
if let topImageFile = post["topImage"] as? PFFile {
topImageFile.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) in
if error == nil {
if let imageData = imageData {
self.topImageView.image = UIImage(data: imageData)
self.topImageAverageColorView.backgroundColor = UIColor(averageColorFromImage: self.topImageView.image)
}
}
})
}
if let bottomImageFile = post?["bottomImage"] as? PFFile {
bottomImageFile.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) in
if error == nil {
if let imageData = imageData {
self.bottomImageView.image = UIImage(data: imageData)
self.bottomImageAverageColorView.backgroundColor = UIColor(averageColorFromImage: self.bottomImageView.image)
}
}
})
}
if let footwearImageFile = post?["footwearImage"] as? PFFile {
footwearImageFile.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) in
if error == nil {
if let imageData = imageData {
self.footwearImageView.image = UIImage(data: imageData)
}
}
})
}
//topImageView.image
//topImageView = post["topImage"] as? PFImageView
// topImageView.imageView?.image =
// if let imageFile = post["image"] as? PFFile {
// imageFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) in
// if error == nil {
// if let imageData = imageData {
// self.pictureImageView.image = UIImage(data: imageData)
// }
// }
// }
// }
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 | e4ddc3b2d4eed145a35199601f0382a9 | 35.87156 | 137 | 0.520279 | 5.716927 | false | false | false | false |
katfang/swift-overview | 12-generics-in-protocols.playground/section-1.swift | 1 | 1938 | // -- Generics in Protocols and Classes
/*
// Cannot do:
protocol Container<ItemType> {
func push(item: ItemType)
func pop() -> ItemType
}
class Stack<T> : Container<T> { ... }
class Stack<T> {
var store = T[]();
func push(item:T) { store.append(item) }
func pop() -> T { return store.removeLast() }
}
*/
protocol Container {
typealias ItemType
func push(item:ItemType)
func pop() -> ItemType
}
class Stack<T> : Container {
typealias ItemType = T
var store = [T]();
func push(item:T) { store.append(item) }
func pop() -> T { return store.removeLast() }
}
var stack = Stack<Int>()
stack.push(3)
stack.pop()
stack.push(4)
// var container: Container = stack // Error Protocol 'Container' can only be used as a generic constraitn because it has Self or associated type requirements
// You still lose associated type information, but you can use funcs which don't have generics on input
func popContainer<T:Container>(container: T) {
// container.push(30) // ERROR T.ItemType does not conform to protocol IntegerLiteralConvertible
println(container.pop())
}
popContainer(stack)
/* // This errors because Container does not have pop / push.
class ContainerWrapper<T> : Container {
typealias ItemType = T
var c: Container
init<C: Container where C.ItemType == T>(var c: C) {
self.c = c
}
func pop() -> T {
return c.pop()
}
func push(item:T) {
return c.push(item)
}
}
c.pop()
self.c.pop()
*/
class ContainerWrapper<T> : Container {
typealias ItemType = T
let _pop: () -> T
let _push: (T) -> ()
init<C: Container where C.ItemType == T>(var c: C) {
_pop = { c.pop() }
_push = { c.push($0) }
}
func pop() -> T {
return _pop()
}
func push(item:T) {
return _push(item)
}
}
// Good discussions:
// http://schani.wordpress.com/2014/06/03/playing-with-swift/
// https://devforums.apple.com/thread/230611?tstart=0
| mit | 798e1a492aa3b0814ea39a056a4631d7 | 20.296703 | 158 | 0.636739 | 3.301533 | false | false | false | false |
DanielAsher/Few.swift | Few-Mac/Label.swift | 5 | 2577 | //
// Label.swift
// Few
//
// Created by Josh Abernathy on 8/5/14.
// Copyright (c) 2014 Josh Abernathy. All rights reserved.
//
import Foundation
import AppKit
private let DefaultLabelFont = NSFont.labelFontOfSize(NSFont.systemFontSizeForControlSize(.RegularControlSize))
private let StringFudge = CGSize(width: 4, height: 0)
private let ABigDimension: CGFloat = 10000
internal func estimateStringSize(string: NSAttributedString, maxSize: CGSize = CGSize(width: ABigDimension, height: ABigDimension)) -> CGSize {
let rect = string.boundingRectWithSize(maxSize, options: .UsesLineFragmentOrigin | .UsesFontLeading)
let width = ceil(rect.size.width) + StringFudge.width
let height = ceil(rect.size.height) + StringFudge.height
return CGSize(width: width, height: height)
}
public class Label: Element {
private var attributedString: NSAttributedString
public var text: String { return attributedString.string }
public convenience init(_ text: String, textColor: NSColor = .controlTextColor(), font: NSFont = DefaultLabelFont) {
let attributes = [
NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor,
]
self.init(attributedString: NSAttributedString(string: text, attributes: attributes))
}
public init(attributedString: NSAttributedString) {
self.attributedString = attributedString
}
// MARK: Element
public override func applyDiff(old: Element, realizedSelf: RealizedElement?) {
super.applyDiff(old, realizedSelf: realizedSelf)
if let textField = realizedSelf?.view as? NSTextField {
if attributedString != textField.attributedStringValue {
textField.attributedStringValue = attributedString
realizedSelf?.markNeedsLayout()
}
}
}
public override func createView() -> ViewType {
let field = NSTextField(frame: CGRectZero)
field.editable = false
field.drawsBackground = false
field.bordered = false
field.font = DefaultLabelFont
field.attributedStringValue = attributedString
field.alphaValue = alpha
field.hidden = hidden
return field
}
public override func assembleLayoutNode() -> Node {
let childNodes = children.map { $0.assembleLayoutNode() }
return Node(size: frame.size, children: childNodes, direction: direction, margin: marginWithPlatformSpecificAdjustments, padding: paddingWithPlatformSpecificAdjustments, wrap: wrap, justification: justification, selfAlignment: selfAlignment, childAlignment: childAlignment, flex: flex) { w in
estimateStringSize(self.attributedString, maxSize: CGSize(width: w.isNaN ? ABigDimension : w, height: ABigDimension))
}
}
}
| mit | d851ac4885fccf4b92ceb6e3c7b2633f | 34.791667 | 294 | 0.770664 | 4.129808 | false | false | false | false |
natecook1000/swift | stdlib/public/SDK/Foundation/JSONEncoder.swift | 1 | 114052 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary`
/// containing `Encodable` values (in which case it should be exempt from key conversion strategies).
///
/// NOTE: The architecture and environment check is due to a bug in the current (2018-08-08) Swift 4.2
/// runtime when running on i386 simulator. The issue is tracked in https://bugs.swift.org/browse/SR-8276
/// Making the protocol `internal` instead of `fileprivate` works around this issue.
/// Once SR-8276 is fixed, this check can be removed and the protocol always be made fileprivate.
#if arch(i386) || arch(arm)
internal protocol _JSONStringDictionaryEncodableMarker { }
#else
fileprivate protocol _JSONStringDictionaryEncodableMarker { }
#endif
extension Dictionary : _JSONStringDictionaryEncodableMarker where Key == String, Value: Encodable { }
/// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary`
/// containing `Decodable` values (in which case it should be exempt from key conversion strategies).
///
/// The marker protocol also provides access to the type of the `Decodable` values,
/// which is needed for the implementation of the key conversion strategy exemption.
///
/// NOTE: Please see comment above regarding SR-8276
#if arch(i386) || arch(arm)
internal protocol _JSONStringDictionaryDecodableMarker {
static var elementType: Decodable.Type { get }
}
#else
fileprivate protocol _JSONStringDictionaryDecodableMarker {
static var elementType: Decodable.Type { get }
}
#endif
extension Dictionary : _JSONStringDictionaryDecodableMarker where Key == String, Value: Decodable {
static var elementType: Decodable.Type { return Value.self }
}
//===----------------------------------------------------------------------===//
// JSON Encoder
//===----------------------------------------------------------------------===//
/// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON.
open class JSONEncoder {
// MARK: Options
/// The formatting of the output JSON data.
public struct OutputFormatting : OptionSet {
/// The format's default value.
public let rawValue: UInt
/// Creates an OutputFormatting value with the given raw value.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
/// Produce human-readable JSON with indented output.
public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0)
/// Produce JSON with dictionary keys sorted in lexicographic order.
@available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
public static let sortedKeys = OutputFormatting(rawValue: 1 << 1)
}
/// The strategy to use for encoding `Date` values.
public enum DateEncodingStrategy {
/// Defer to `Date` for choosing an encoding. This is the default strategy.
case deferredToDate
/// Encode the `Date` as a UNIX timestamp (as a JSON number).
case secondsSince1970
/// Encode the `Date` as UNIX millisecond timestamp (as a JSON number).
case millisecondsSince1970
/// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Encode the `Date` as a string formatted by the given formatter.
case formatted(DateFormatter)
/// Encode the `Date` as a custom value encoded by the given closure.
///
/// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place.
case custom((Date, Encoder) throws -> Void)
}
/// The strategy to use for encoding `Data` values.
public enum DataEncodingStrategy {
/// Defer to `Data` for choosing an encoding.
case deferredToData
/// Encoded the `Data` as a Base64-encoded string. This is the default strategy.
case base64
/// Encode the `Data` as a custom value encoded by the given closure.
///
/// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place.
case custom((Data, Encoder) throws -> Void)
}
/// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN).
public enum NonConformingFloatEncodingStrategy {
/// Throw upon encountering non-conforming values. This is the default strategy.
case `throw`
/// Encode the values using the given representation strings.
case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String)
}
/// The strategy to use for automatically changing the value of keys before encoding.
public enum KeyEncodingStrategy {
/// Use the keys specified by each type. This is the default strategy.
case useDefaultKeys
/// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to JSON payload.
///
/// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt).
/// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences.
///
/// Converting from camel case to snake case:
/// 1. Splits words at the boundary of lower-case to upper-case
/// 2. Inserts `_` between words
/// 3. Lowercases the entire string
/// 4. Preserves starting and ending `_`.
///
/// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`.
///
/// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted.
case convertToSnakeCase
/// Provide a custom conversion to the key in the encoded JSON from the keys specified by the encoded types.
/// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding.
/// If the result of the conversion is a duplicate key, then only one value will be present in the result.
case custom((_ codingPath: [CodingKey]) -> CodingKey)
fileprivate static func _convertToSnakeCase(_ stringKey: String) -> String {
guard !stringKey.isEmpty else { return stringKey }
var words : [Range<String.Index>] = []
// The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase
//
// myProperty -> my_property
// myURLProperty -> my_url_property
//
// We assume, per Swift naming conventions, that the first character of the key is lowercase.
var wordStart = stringKey.startIndex
var searchRange = stringKey.index(after: wordStart)..<stringKey.endIndex
// Find next uppercase character
while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) {
let untilUpperCase = wordStart..<upperCaseRange.lowerBound
words.append(untilUpperCase)
// Find next lowercase character
searchRange = upperCaseRange.lowerBound..<searchRange.upperBound
guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else {
// There are no more lower case letters. Just end here.
wordStart = searchRange.lowerBound
break
}
// Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word
let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound)
if lowerCaseRange.lowerBound == nextCharacterAfterCapital {
// The next character after capital is a lower case character and therefore not a word boundary.
// Continue searching for the next upper case for the boundary.
wordStart = upperCaseRange.lowerBound
} else {
// There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character.
let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound)
words.append(upperCaseRange.lowerBound..<beforeLowerIndex)
// Next word starts at the capital before the lowercase we just found
wordStart = beforeLowerIndex
}
searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
}
words.append(wordStart..<searchRange.upperBound)
let result = words.map({ (range) in
return stringKey[range].lowercased()
}).joined(separator: "_")
return result
}
}
/// The output format to produce. Defaults to `[]`.
open var outputFormatting: OutputFormatting = []
/// The strategy to use in encoding dates. Defaults to `.deferredToDate`.
open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate
/// The strategy to use in encoding binary data. Defaults to `.base64`.
open var dataEncodingStrategy: DataEncodingStrategy = .base64
/// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`.
open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw
/// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`.
open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys
/// Contextual user-provided information for use during encoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the encoding hierarchy.
fileprivate struct _Options {
let dateEncodingStrategy: DateEncodingStrategy
let dataEncodingStrategy: DataEncodingStrategy
let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy
let keyEncodingStrategy: KeyEncodingStrategy
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level encoder.
fileprivate var options: _Options {
return _Options(dateEncodingStrategy: dateEncodingStrategy,
dataEncodingStrategy: dataEncodingStrategy,
nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy,
keyEncodingStrategy: keyEncodingStrategy,
userInfo: userInfo)
}
// MARK: - Constructing a JSON Encoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Encoding Values
/// Encodes the given top-level value and returns its JSON representation.
///
/// - parameter value: The value to encode.
/// - returns: A new `Data` value containing the encoded JSON data.
/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.
open func encode<T : Encodable>(_ value: T) throws -> Data {
let encoder = _JSONEncoder(options: self.options)
guard let topLevel = try encoder.box_(value) else {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values."))
}
if topLevel is NSNull {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as null JSON fragment."))
} else if topLevel is NSNumber {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as number JSON fragment."))
} else if topLevel is NSString {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as string JSON fragment."))
}
let writingOptions = JSONSerialization.WritingOptions(rawValue: self.outputFormatting.rawValue)
do {
return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions)
} catch {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [], debugDescription: "Unable to encode the given top-level value to JSON.", underlyingError: error))
}
}
}
// MARK: - _JSONEncoder
fileprivate class _JSONEncoder : Encoder {
// MARK: Properties
/// The encoder's storage.
fileprivate var storage: _JSONEncodingStorage
/// Options set on the top-level encoder.
fileprivate let options: JSONEncoder._Options
/// The path to the current point in encoding.
public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level encoder options.
fileprivate init(options: JSONEncoder._Options, codingPath: [CodingKey] = []) {
self.options = options
self.storage = _JSONEncodingStorage()
self.codingPath = codingPath
}
/// Returns whether a new element can be encoded at this coding path.
///
/// `true` if an element has not yet been encoded at this coding path; `false` otherwise.
fileprivate var canEncodeNewValue: Bool {
// Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container).
// At the same time, every time a container is requested, a new value gets pushed onto the storage stack.
// If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition.
//
// This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path.
// Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here).
return self.storage.count == self.codingPath.count
}
// MARK: - Encoder Methods
public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> {
// If an existing keyed container was already requested, return that one.
let topContainer: NSMutableDictionary
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushKeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableDictionary else {
preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
return KeyedEncodingContainer(container)
}
public func unkeyedContainer() -> UnkeyedEncodingContainer {
// If an existing unkeyed container was already requested, return that one.
let topContainer: NSMutableArray
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushUnkeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableArray else {
preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
}
public func singleValueContainer() -> SingleValueEncodingContainer {
return self
}
}
// MARK: - Encoding Storage and Containers
fileprivate struct _JSONEncodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the JSON types (NSNull, NSNumber, NSString, NSArray, NSDictionary).
private(set) fileprivate var containers: [NSObject] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary {
let dictionary = NSMutableDictionary()
self.containers.append(dictionary)
return dictionary
}
fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray {
let array = NSMutableArray()
self.containers.append(array)
return array
}
fileprivate mutating func push(container: NSObject) {
self.containers.append(container)
}
fileprivate mutating func popContainer() -> NSObject {
precondition(!self.containers.isEmpty, "Empty container stack.")
return self.containers.popLast()!
}
}
// MARK: - Encoding Containers
fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: _JSONEncoder
/// A reference to the container we're writing to.
private let container: NSMutableDictionary
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - Coding Path Operations
private func _converted(_ key: CodingKey) -> CodingKey {
switch encoder.options.keyEncodingStrategy {
case .useDefaultKeys:
return key
case .convertToSnakeCase:
let newKeyString = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue)
return _JSONKey(stringValue: newKeyString, intValue: key.intValue)
case .custom(let converter):
return converter(codingPath + [key])
}
}
// MARK: - KeyedEncodingContainerProtocol Methods
public mutating func encodeNil(forKey key: Key) throws {
self.container[_converted(key).stringValue] = NSNull()
}
public mutating func encode(_ value: Bool, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int8, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int16, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int32, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Int64, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt8, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt16, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt32, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: UInt64, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: String, forKey key: Key) throws {
self.container[_converted(key).stringValue] = self.encoder.box(value)
}
public mutating func encode(_ value: Float, forKey key: Key) throws {
// Since the float may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[_converted(key).stringValue] = try self.encoder.box(value)
}
public mutating func encode(_ value: Double, forKey key: Key) throws {
// Since the double may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[_converted(key).stringValue] = try self.encoder.box(value)
}
public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[_converted(key).stringValue] = try self.encoder.box(value)
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
let dictionary = NSMutableDictionary()
self.container[_converted(key).stringValue] = dictionary
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
let array = NSMutableArray()
self.container[_converted(key).stringValue] = array
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return _JSONReferencingEncoder(referencing: self.encoder, key: _JSONKey.super, convertedKey: _converted(_JSONKey.super), wrapping: self.container)
}
public mutating func superEncoder(forKey key: Key) -> Encoder {
return _JSONReferencingEncoder(referencing: self.encoder, key: key, convertedKey: _converted(key), wrapping: self.container)
}
}
fileprivate struct _JSONUnkeyedEncodingContainer : UnkeyedEncodingContainer {
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: _JSONEncoder
/// A reference to the container we're writing to.
private let container: NSMutableArray
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
/// The number of elements encoded into the container.
public var count: Int {
return self.container.count
}
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - UnkeyedEncodingContainer Methods
public mutating func encodeNil() throws { self.container.add(NSNull()) }
public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Float) throws {
// Since the float may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(_JSONKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func encode(_ value: Double) throws {
// Since the double may be invalid and throw, the coding path needs to contain this key.
self.encoder.codingPath.append(_JSONKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func encode<T : Encodable>(_ value: T) throws {
self.encoder.codingPath.append(_JSONKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {
self.codingPath.append(_JSONKey(index: self.count))
defer { self.codingPath.removeLast() }
let dictionary = NSMutableDictionary()
self.container.add(dictionary)
let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
self.codingPath.append(_JSONKey(index: self.count))
defer { self.codingPath.removeLast() }
let array = NSMutableArray()
self.container.add(array)
return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return _JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
}
}
extension _JSONEncoder : SingleValueEncodingContainer {
// MARK: - SingleValueEncodingContainer Methods
fileprivate func assertCanEncodeNewValue() {
precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.")
}
public func encodeNil() throws {
assertCanEncodeNewValue()
self.storage.push(container: NSNull())
}
public func encode(_ value: Bool) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int8) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int16) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int32) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Int64) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt8) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt16) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt32) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: UInt64) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: String) throws {
assertCanEncodeNewValue()
self.storage.push(container: self.box(value))
}
public func encode(_ value: Float) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
public func encode(_ value: Double) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
public func encode<T : Encodable>(_ value: T) throws {
assertCanEncodeNewValue()
try self.storage.push(container: self.box(value))
}
}
// MARK: - Concrete Value Representations
extension _JSONEncoder {
/// Returns the given value boxed in a container appropriate for pushing onto the container stack.
fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) }
fileprivate func box(_ float: Float) throws -> NSObject {
guard !float.isInfinite && !float.isNaN else {
guard case let .convertToString(positiveInfinity: posInfString,
negativeInfinity: negInfString,
nan: nanString) = self.options.nonConformingFloatEncodingStrategy else {
throw EncodingError._invalidFloatingPointValue(float, at: codingPath)
}
if float == Float.infinity {
return NSString(string: posInfString)
} else if float == -Float.infinity {
return NSString(string: negInfString)
} else {
return NSString(string: nanString)
}
}
return NSNumber(value: float)
}
fileprivate func box(_ double: Double) throws -> NSObject {
guard !double.isInfinite && !double.isNaN else {
guard case let .convertToString(positiveInfinity: posInfString,
negativeInfinity: negInfString,
nan: nanString) = self.options.nonConformingFloatEncodingStrategy else {
throw EncodingError._invalidFloatingPointValue(double, at: codingPath)
}
if double == Double.infinity {
return NSString(string: posInfString)
} else if double == -Double.infinity {
return NSString(string: negInfString)
} else {
return NSString(string: nanString)
}
}
return NSNumber(value: double)
}
fileprivate func box(_ date: Date) throws -> NSObject {
switch self.options.dateEncodingStrategy {
case .deferredToDate:
// Must be called with a surrounding with(pushedKey:) call.
// Dates encode as single-value objects; this can't both throw and push a container, so no need to catch the error.
try date.encode(to: self)
return self.storage.popContainer()
case .secondsSince1970:
return NSNumber(value: date.timeIntervalSince1970)
case .millisecondsSince1970:
return NSNumber(value: 1000.0 * date.timeIntervalSince1970)
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return NSString(string: _iso8601Formatter.string(from: date))
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
return NSString(string: formatter.string(from: date))
case .custom(let closure):
let depth = self.storage.count
do {
try closure(date, self)
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
guard self.storage.count > depth else {
// The closure didn't encode anything. Return the default keyed container.
return NSDictionary()
}
// We can pop because the closure encoded something.
return self.storage.popContainer()
}
}
fileprivate func box(_ data: Data) throws -> NSObject {
switch self.options.dataEncodingStrategy {
case .deferredToData:
// Must be called with a surrounding with(pushedKey:) call.
let depth = self.storage.count
do {
try data.encode(to: self)
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
// This shouldn't be possible for Data (which encodes as an array of bytes), but it can't hurt to catch a failure.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
return self.storage.popContainer()
case .base64:
return NSString(string: data.base64EncodedString())
case .custom(let closure):
let depth = self.storage.count
do {
try closure(data, self)
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
guard self.storage.count > depth else {
// The closure didn't encode anything. Return the default keyed container.
return NSDictionary()
}
// We can pop because the closure encoded something.
return self.storage.popContainer()
}
}
fileprivate func box(_ dict: [String : Encodable]) throws -> NSObject? {
let depth = self.storage.count
let result = self.storage.pushKeyedContainer()
do {
for (key, value) in dict {
self.codingPath.append(_JSONKey(stringValue: key, intValue: nil))
defer { self.codingPath.removeLast() }
result[key] = try box(value)
}
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
// The top container should be a new container.
guard self.storage.count > depth else {
return nil
}
return self.storage.popContainer()
}
fileprivate func box(_ value: Encodable) throws -> NSObject {
return try self.box_(value) ?? NSDictionary()
}
// This method is called "box_" instead of "box" to disambiguate it from the overloads. Because the return type here is different from all of the "box" overloads (and is more general), any "box" calls in here would call back into "box" recursively instead of calling the appropriate overload, which is not what we want.
fileprivate func box_(_ value: Encodable) throws -> NSObject? {
// Disambiguation between variable and function is required due to
// issue tracked at: https://bugs.swift.org/browse/SR-1846
let type = Swift.type(of: value)
if type == Date.self || type == NSDate.self {
// Respect Date encoding strategy
return try self.box((value as! Date))
} else if type == Data.self || type == NSData.self {
// Respect Data encoding strategy
return try self.box((value as! Data))
} else if type == URL.self || type == NSURL.self {
// Encode URLs as single strings.
return self.box((value as! URL).absoluteString)
} else if type == Decimal.self || type == NSDecimalNumber.self {
// JSONSerialization can natively handle NSDecimalNumber.
return (value as! NSDecimalNumber)
} else if value is _JSONStringDictionaryEncodableMarker {
return try self.box(value as! [String : Encodable])
}
// The value should request a container from the _JSONEncoder.
let depth = self.storage.count
do {
try value.encode(to: self)
} catch {
// If the value pushed a container before throwing, pop it back off to restore state.
if self.storage.count > depth {
let _ = self.storage.popContainer()
}
throw error
}
// The top container should be a new container.
guard self.storage.count > depth else {
return nil
}
return self.storage.popContainer()
}
}
// MARK: - _JSONReferencingEncoder
/// _JSONReferencingEncoder is a special subclass of _JSONEncoder which has its own storage, but references the contents of a different encoder.
/// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container).
fileprivate class _JSONReferencingEncoder : _JSONEncoder {
// MARK: Reference types.
/// The type of container we're referencing.
private enum Reference {
/// Referencing a specific index in an array container.
case array(NSMutableArray, Int)
/// Referencing a specific key in a dictionary container.
case dictionary(NSMutableDictionary, String)
}
// MARK: - Properties
/// The encoder we're referencing.
fileprivate let encoder: _JSONEncoder
/// The container reference itself.
private let reference: Reference
// MARK: - Initialization
/// Initializes `self` by referencing the given array container in the given encoder.
fileprivate init(referencing encoder: _JSONEncoder, at index: Int, wrapping array: NSMutableArray) {
self.encoder = encoder
self.reference = .array(array, index)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(_JSONKey(index: index))
}
/// Initializes `self` by referencing the given dictionary container in the given encoder.
fileprivate init(referencing encoder: _JSONEncoder,
key: CodingKey, convertedKey: CodingKey, wrapping dictionary: NSMutableDictionary) {
self.encoder = encoder
self.reference = .dictionary(dictionary, convertedKey.stringValue)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(key)
}
// MARK: - Coding Path Operations
fileprivate override var canEncodeNewValue: Bool {
// With a regular encoder, the storage and coding path grow together.
// A referencing encoder, however, inherits its parents coding path, as well as the key it was created for.
// We have to take this into account.
return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1
}
// MARK: - Deinitialization
// Finalizes `self` by writing the contents of our storage to the referenced encoder's storage.
deinit {
let value: Any
switch self.storage.count {
case 0: value = NSDictionary()
case 1: value = self.storage.popContainer()
default: fatalError("Referencing encoder deallocated with multiple containers on stack.")
}
switch self.reference {
case .array(let array, let index):
array.insert(value, at: index)
case .dictionary(let dictionary, let key):
dictionary[NSString(string: key)] = value
}
}
}
//===----------------------------------------------------------------------===//
// JSON Decoder
//===----------------------------------------------------------------------===//
/// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types.
open class JSONDecoder {
// MARK: Options
/// The strategy to use for decoding `Date` values.
public enum DateDecodingStrategy {
/// Defer to `Date` for decoding. This is the default strategy.
case deferredToDate
/// Decode the `Date` as a UNIX timestamp from a JSON number.
case secondsSince1970
/// Decode the `Date` as UNIX millisecond timestamp from a JSON number.
case millisecondsSince1970
/// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format).
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Decode the `Date` as a string parsed by the given formatter.
case formatted(DateFormatter)
/// Decode the `Date` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Date)
}
/// The strategy to use for decoding `Data` values.
public enum DataDecodingStrategy {
/// Defer to `Data` for decoding.
case deferredToData
/// Decode the `Data` from a Base64-encoded string. This is the default strategy.
case base64
/// Decode the `Data` as a custom value decoded by the given closure.
case custom((_ decoder: Decoder) throws -> Data)
}
/// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN).
public enum NonConformingFloatDecodingStrategy {
/// Throw upon encountering non-conforming values. This is the default strategy.
case `throw`
/// Decode the values from the given representation strings.
case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String)
}
/// The strategy to use for automatically changing the value of keys before decoding.
public enum KeyDecodingStrategy {
/// Use the keys specified by each type. This is the default strategy.
case useDefaultKeys
/// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type.
///
/// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences.
///
/// Converting from snake case to camel case:
/// 1. Capitalizes the word starting after each `_`
/// 2. Removes all `_`
/// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata).
/// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`.
///
/// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character.
case convertFromSnakeCase
/// Provide a custom conversion from the key in the encoded JSON to the keys specified by the decoded types.
/// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding.
/// If the result of the conversion is a duplicate key, then only one value will be present in the container for the type to decode from.
case custom((_ codingPath: [CodingKey]) -> CodingKey)
fileprivate static func _convertFromSnakeCase(_ stringKey: String) -> String {
guard !stringKey.isEmpty else { return stringKey }
// Find the first non-underscore character
guard let firstNonUnderscore = stringKey.index(where: { $0 != "_" }) else {
// Reached the end without finding an _
return stringKey
}
// Find the last non-underscore character
var lastNonUnderscore = stringKey.index(before: stringKey.endIndex)
while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" {
stringKey.formIndex(before: &lastNonUnderscore)
}
let keyRange = firstNonUnderscore...lastNonUnderscore
let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore
let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex
var components = stringKey[keyRange].split(separator: "_")
let joinedString : String
if components.count == 1 {
// No underscores in key, leave the word as is - maybe already camel cased
joinedString = String(stringKey[keyRange])
} else {
joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined()
}
// Do a cheap isEmpty check before creating and appending potentially empty strings
let result : String
if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) {
result = joinedString
} else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) {
// Both leading and trailing underscores
result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange])
} else if (!leadingUnderscoreRange.isEmpty) {
// Just leading
result = String(stringKey[leadingUnderscoreRange]) + joinedString
} else {
// Just trailing
result = joinedString + String(stringKey[trailingUnderscoreRange])
}
return result
}
}
/// The strategy to use in decoding dates. Defaults to `.deferredToDate`.
open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate
/// The strategy to use in decoding binary data. Defaults to `.base64`.
open var dataDecodingStrategy: DataDecodingStrategy = .base64
/// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`.
open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw
/// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`.
open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys
/// Contextual user-provided information for use during decoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the decoding hierarchy.
fileprivate struct _Options {
let dateDecodingStrategy: DateDecodingStrategy
let dataDecodingStrategy: DataDecodingStrategy
let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy
let keyDecodingStrategy: KeyDecodingStrategy
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level decoder.
fileprivate var options: _Options {
return _Options(dateDecodingStrategy: dateDecodingStrategy,
dataDecodingStrategy: dataDecodingStrategy,
nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy,
keyDecodingStrategy: keyDecodingStrategy,
userInfo: userInfo)
}
// MARK: - Constructing a JSON Decoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Decoding Values
/// Decodes a top-level value of the given type from the given JSON representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON.
/// - throws: An error if any value throws an error during decoding.
open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T {
let topLevel: Any
do {
topLevel = try JSONSerialization.jsonObject(with: data)
} catch {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error))
}
let decoder = _JSONDecoder(referencing: topLevel, options: self.options)
guard let value = try decoder.unbox(topLevel, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
}
return value
}
}
// MARK: - _JSONDecoder
fileprivate class _JSONDecoder : Decoder {
// MARK: Properties
/// The decoder's storage.
fileprivate var storage: _JSONDecodingStorage
/// Options set on the top-level decoder.
fileprivate let options: JSONDecoder._Options
/// The path to the current point in encoding.
fileprivate(set) public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level container and options.
fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: JSONDecoder._Options) {
self.storage = _JSONDecodingStorage()
self.storage.push(container: container)
self.codingPath = codingPath
self.options = options
}
// MARK: - Decoder Methods
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer)
}
let container = _JSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
return KeyedDecodingContainer(container)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get unkeyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer)
}
return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
// MARK: - Decoding Storage
fileprivate struct _JSONDecodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]).
private(set) fileprivate var containers: [Any] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate var topContainer: Any {
precondition(!self.containers.isEmpty, "Empty container stack.")
return self.containers.last!
}
fileprivate mutating func push(container: Any) {
self.containers.append(container)
}
fileprivate mutating func popContainer() {
precondition(!self.containers.isEmpty, "Empty container stack.")
self.containers.removeLast()
}
}
// MARK: Decoding Containers
fileprivate struct _JSONKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _JSONDecoder
/// A reference to the container we're reading from.
private let container: [String : Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [String : Any]) {
self.decoder = decoder
switch decoder.options.keyDecodingStrategy {
case .useDefaultKeys:
self.container = container
case .convertFromSnakeCase:
// Convert the snake case keys in the container to camel case.
// If we hit a duplicate key after conversion, then we'll use the first one we saw. Effectively an undefined behavior with JSON dictionaries.
self.container = Dictionary(container.map {
key, value in (JSONDecoder.KeyDecodingStrategy._convertFromSnakeCase(key), value)
}, uniquingKeysWith: { (first, _) in first })
case .custom(let converter):
self.container = Dictionary(container.map {
key, value in (converter(decoder.codingPath + [_JSONKey(stringValue: key, intValue: nil)]).stringValue, value)
}, uniquingKeysWith: { (first, _) in first })
}
self.codingPath = decoder.codingPath
}
// MARK: - KeyedDecodingContainerProtocol Methods
public var allKeys: [Key] {
return self.container.keys.compactMap { Key(stringValue: $0) }
}
public func contains(_ key: Key) -> Bool {
return self.container[key.stringValue] != nil
}
private func _errorDescription(of key: CodingKey) -> String {
switch decoder.options.keyDecodingStrategy {
case .convertFromSnakeCase:
// In this case we can attempt to recover the original value by reversing the transform
let original = key.stringValue
let converted = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(original)
if converted == original {
return "\(key) (\"\(original)\")"
} else {
return "\(key) (\"\(original)\"), converted to \(converted)"
}
default:
// Otherwise, just report the converted string
return "\(key) (\"\(key.stringValue)\")"
}
}
public func decodeNil(forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
return entry is NSNull
}
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key))."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \(_errorDescription(of: key))"))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \(_errorDescription(of: key))"))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
private func _superDecoder(forKey key: CodingKey) throws -> Decoder {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
let value: Any = self.container[key.stringValue] ?? NSNull()
return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
public func superDecoder() throws -> Decoder {
return try _superDecoder(forKey: _JSONKey.super)
}
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _superDecoder(forKey: key)
}
}
fileprivate struct _JSONUnkeyedDecodingContainer : UnkeyedDecodingContainer {
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _JSONDecoder
/// A reference to the container we're reading from.
private let container: [Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
/// The index of the element we're about to decode.
private(set) public var currentIndex: Int
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [Any]) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
self.currentIndex = 0
}
// MARK: - UnkeyedDecodingContainer Methods
public var count: Int? {
return self.container.count
}
public var isAtEnd: Bool {
return self.currentIndex >= self.count!
}
public mutating func decodeNil() throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
if self.container[self.currentIndex] is NSNull {
self.currentIndex += 1
return true
} else {
return false
}
}
public mutating func decode(_ type: Bool.Type) throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int.Type) throws -> Int {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int8.Type) throws -> Int8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int16.Type) throws -> Int16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int32.Type) throws -> Int32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int64.Type) throws -> Int64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt.Type) throws -> UInt {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Float.Type) throws -> Float {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Double.Type) throws -> Double {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: String.Type) throws -> String {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
self.currentIndex += 1
let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
self.currentIndex += 1
return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
public mutating func superDecoder() throws -> Decoder {
self.decoder.codingPath.append(_JSONKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Decoder.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get superDecoder() -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
self.currentIndex += 1
return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
}
extension _JSONDecoder : SingleValueDecodingContainer {
// MARK: SingleValueDecodingContainer Methods
private func expectNonNull<T>(_ type: T.Type) throws {
guard !self.decodeNil() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead."))
}
}
public func decodeNil() -> Bool {
return self.storage.topContainer is NSNull
}
public func decode(_ type: Bool.Type) throws -> Bool {
try expectNonNull(Bool.self)
return try self.unbox(self.storage.topContainer, as: Bool.self)!
}
public func decode(_ type: Int.Type) throws -> Int {
try expectNonNull(Int.self)
return try self.unbox(self.storage.topContainer, as: Int.self)!
}
public func decode(_ type: Int8.Type) throws -> Int8 {
try expectNonNull(Int8.self)
return try self.unbox(self.storage.topContainer, as: Int8.self)!
}
public func decode(_ type: Int16.Type) throws -> Int16 {
try expectNonNull(Int16.self)
return try self.unbox(self.storage.topContainer, as: Int16.self)!
}
public func decode(_ type: Int32.Type) throws -> Int32 {
try expectNonNull(Int32.self)
return try self.unbox(self.storage.topContainer, as: Int32.self)!
}
public func decode(_ type: Int64.Type) throws -> Int64 {
try expectNonNull(Int64.self)
return try self.unbox(self.storage.topContainer, as: Int64.self)!
}
public func decode(_ type: UInt.Type) throws -> UInt {
try expectNonNull(UInt.self)
return try self.unbox(self.storage.topContainer, as: UInt.self)!
}
public func decode(_ type: UInt8.Type) throws -> UInt8 {
try expectNonNull(UInt8.self)
return try self.unbox(self.storage.topContainer, as: UInt8.self)!
}
public func decode(_ type: UInt16.Type) throws -> UInt16 {
try expectNonNull(UInt16.self)
return try self.unbox(self.storage.topContainer, as: UInt16.self)!
}
public func decode(_ type: UInt32.Type) throws -> UInt32 {
try expectNonNull(UInt32.self)
return try self.unbox(self.storage.topContainer, as: UInt32.self)!
}
public func decode(_ type: UInt64.Type) throws -> UInt64 {
try expectNonNull(UInt64.self)
return try self.unbox(self.storage.topContainer, as: UInt64.self)!
}
public func decode(_ type: Float.Type) throws -> Float {
try expectNonNull(Float.self)
return try self.unbox(self.storage.topContainer, as: Float.self)!
}
public func decode(_ type: Double.Type) throws -> Double {
try expectNonNull(Double.self)
return try self.unbox(self.storage.topContainer, as: Double.self)!
}
public func decode(_ type: String.Type) throws -> String {
try expectNonNull(String.self)
return try self.unbox(self.storage.topContainer, as: String.self)!
}
public func decode<T : Decodable>(_ type: T.Type) throws -> T {
try expectNonNull(type)
return try self.unbox(self.storage.topContainer, as: type)!
}
}
// MARK: - Concrete Value Representations
extension _JSONDecoder {
/// Returns the given value unboxed from a container.
fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber {
// TODO: Add a flag to coerce non-boolean numbers into Bools?
if number === kCFBooleanTrue as NSNumber {
return true
} else if number === kCFBooleanFalse as NSNumber {
return false
}
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let bool = value as? Bool {
return bool
*/
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int = number.intValue
guard NSNumber(value: int) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int
}
fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int8 = number.int8Value
guard NSNumber(value: int8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int8
}
fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int16 = number.int16Value
guard NSNumber(value: int16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int16
}
fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int32 = number.int32Value
guard NSNumber(value: int32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int32
}
fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int64 = number.int64Value
guard NSNumber(value: int64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return int64
}
fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint = number.uintValue
guard NSNumber(value: uint) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint
}
fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint8 = number.uint8Value
guard NSNumber(value: uint8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint8
}
fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint16 = number.uint16Value
guard NSNumber(value: uint16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint16
}
fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint32 = number.uint32Value
guard NSNumber(value: uint32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint32
}
fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
guard !(value is NSNull) else { return nil }
guard let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint64 = number.uint64Value
guard NSNumber(value: uint64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type)."))
}
return uint64
}
fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
// We are willing to return a Float by losing precision:
// * If the original value was integral,
// * and the integral value was > Float.greatestFiniteMagnitude, we will fail
// * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24
// * If it was a Float, you will get back the precise value
// * If it was a Double or Decimal, you will get back the nearest approximation if it will fit
let double = number.doubleValue
guard abs(double) <= Double(Float.greatestFiniteMagnitude) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type)."))
}
return Float(double)
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let double = value as? Double {
if abs(double) <= Double(Float.max) {
return Float(double)
}
overflow = true
} else if let int = value as? Int {
if let float = Float(exactly: int) {
return float
}
overflow = true
*/
} else if let string = value as? String,
case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy {
if string == posInfString {
return Float.infinity
} else if string == negInfString {
return -Float.infinity
} else if string == nanString {
return Float.nan
}
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
guard !(value is NSNull) else { return nil }
if let number = value as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse {
// We are always willing to return the number as a Double:
// * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double
// * If it was a Float or Double, you will get back the precise value
// * If it was Decimal, you will get back the nearest approximation
return number.doubleValue
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let double = value as? Double {
return double
} else if let int = value as? Int {
if let double = Double(exactly: int) {
return double
}
overflow = true
*/
} else if let string = value as? String,
case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy {
if string == posInfString {
return Double.infinity
} else if string == negInfString {
return -Double.infinity
} else if string == nanString {
return Double.nan
}
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? {
guard !(value is NSNull) else { return nil }
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return string
}
fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? {
guard !(value is NSNull) else { return nil }
switch self.options.dateDecodingStrategy {
case .deferredToDate:
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try Date(from: self)
case .secondsSince1970:
let double = try self.unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double)
case .millisecondsSince1970:
let double = try self.unbox(value, as: Double.self)!
return Date(timeIntervalSince1970: double / 1000.0)
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
let string = try self.unbox(value, as: String.self)!
guard let date = _iso8601Formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted."))
}
return date
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
}
case .formatted(let formatter):
let string = try self.unbox(value, as: String.self)!
guard let date = formatter.date(from: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter."))
}
return date
case .custom(let closure):
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try closure(self)
}
}
fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
guard !(value is NSNull) else { return nil }
switch self.options.dataDecodingStrategy {
case .deferredToData:
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try Data(from: self)
case .base64:
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
guard let data = Data(base64Encoded: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64."))
}
return data
case .custom(let closure):
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try closure(self)
}
}
fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? {
guard !(value is NSNull) else { return nil }
// Attempt to bridge from NSDecimalNumber.
if let decimal = value as? Decimal {
return decimal
} else {
let doubleValue = try self.unbox(value, as: Double.self)!
return Decimal(doubleValue)
}
}
fileprivate func unbox<T>(_ value: Any, as type: _JSONStringDictionaryDecodableMarker.Type) throws -> T? {
guard !(value is NSNull) else { return nil }
var result = [String : Any]()
guard let dict = value as? NSDictionary else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let elementType = type.elementType
for (key, value) in dict {
let key = key as! String
self.codingPath.append(_JSONKey(stringValue: key, intValue: nil))
defer { self.codingPath.removeLast() }
result[key] = try unbox_(value, as: elementType)
}
return result as? T
}
fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? {
return try unbox_(value, as: type) as? T
}
fileprivate func unbox_(_ value: Any, as type: Decodable.Type) throws -> Any? {
if type == Date.self || type == NSDate.self {
return try self.unbox(value, as: Date.self)
} else if type == Data.self || type == NSData.self {
return try self.unbox(value, as: Data.self)
} else if type == URL.self || type == NSURL.self {
guard let urlString = try self.unbox(value, as: String.self) else {
return nil
}
guard let url = URL(string: urlString) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Invalid URL string."))
}
return url
} else if type == Decimal.self || type == NSDecimalNumber.self {
return try self.unbox(value, as: Decimal.self)
} else if let stringKeyedDictType = type as? _JSONStringDictionaryDecodableMarker.Type {
return try self.unbox(value, as: stringKeyedDictType)
} else {
self.storage.push(container: value)
defer { self.storage.popContainer() }
return try type.init(from: self)
}
}
}
//===----------------------------------------------------------------------===//
// Shared Key Types
//===----------------------------------------------------------------------===//
fileprivate struct _JSONKey : CodingKey {
public var stringValue: String
public var intValue: Int?
public init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
public init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
public init(stringValue: String, intValue: Int?) {
self.stringValue = stringValue
self.intValue = intValue
}
fileprivate init(index: Int) {
self.stringValue = "Index \(index)"
self.intValue = index
}
fileprivate static let `super` = _JSONKey(stringValue: "super")!
}
//===----------------------------------------------------------------------===//
// Shared ISO8601 Date Formatter
//===----------------------------------------------------------------------===//
// NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
fileprivate var _iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
}()
//===----------------------------------------------------------------------===//
// Error Utilities
//===----------------------------------------------------------------------===//
fileprivate extension EncodingError {
/// Returns a `.invalidValue` error describing the given invalid floating-point value.
///
///
/// - parameter value: The value that was invalid to encode.
/// - parameter path: The path of `CodingKey`s taken to encode this value.
/// - returns: An `EncodingError` with the appropriate path and debug description.
fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError {
let valueDescription: String
if value == T.infinity {
valueDescription = "\(T.self).infinity"
} else if value == -T.infinity {
valueDescription = "-\(T.self).infinity"
} else {
valueDescription = "\(T.self).nan"
}
let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded."
return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription))
}
}
| apache-2.0 | 6495c8472068c274eee462ea71e484a8 | 43.796544 | 323 | 0.6471 | 5.02897 | false | false | false | false |
LucianoPAlmeida/FlatPickerView | FlatPickerView/FlatPickerView.swift | 1 | 13519 | //
// FlatPickerView.swift
// CustomPickerView
//
// Created by Luciano Almeida on 25/12/16.
// Copyright © 2016 Luciano Almeida. All rights reserved.
//
import UIKit
public protocol FlatPickerViewDataSource: class {
func flatPickerNumberOfRows(pickerView: FlatPickerView) -> Int
}
public protocol FlatPickerViewDelegate: class {
func flatPicker(pickerView: FlatPickerView, titleForRow row: Int) -> String?
func flatPicker(pickerView: FlatPickerView, attributedTitleForRow row: Int) -> NSAttributedString?
func flatPicker(pickerView: FlatPickerView, viewForRow row: Int) -> UIView?
func flatPickerViewForSelectedItem(pickerView: FlatPickerView) -> UIView?
func flatPickerShouldShowSelectionView(pickerView: FlatPickerView) -> Bool
func flatPicker(pickerView: FlatPickerView, didSelectRow row: Int)
func flatPicker(pickerView: FlatPickerView, didPassOnSelection row: Int)
func flatPickerSpacingBetweenItems(pickerView: FlatPickerView) -> CGFloat?
}
open class FlatPickerView: UIView {
// MARK: Definitions
public enum Direction {
case horizontal
case vertical
}
// MARK: Properties
open var itemSize: CGFloat = 50 {
didSet {
highlitedViewFrameForDirection()
}
}
open weak var delegate: FlatPickerViewDelegate? {
didSet {
setupPickerSelectionView()
collectionView?.reloadData()
}
}
open weak var dataSource: FlatPickerViewDataSource? {
didSet {
collectionView?.reloadData()
}
}
fileprivate weak var collectionView: UICollectionView!
open fileprivate(set) weak var highlightedView: UIView!
open var isScroolEnabled: Bool = true {
didSet {
collectionView?.isScrollEnabled = isScroolEnabled
}
}
fileprivate var lastIdxPassedOnSelection: Int!
open var direction: Direction! {
didSet {
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = direction == Direction.horizontal ? UICollectionViewScrollDirection.horizontal : UICollectionViewScrollDirection.vertical
}
highlitedViewFrameForDirection()
}
}
open fileprivate(set) var currentSelectedRow: Int!
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func awakeFromNib() {
super.awakeFromNib()
initialize()
}
override open func layoutSubviews() {
super.layoutSubviews()
setupInsetForCollection()
collectionView?.frame = CGRect(origin: CGPoint.zero, size: frame.size)
collectionView?.performBatchUpdates(nil, completion: nil)
highlitedViewFrameForDirection()
let indexPath: IndexPath = currentSelectedRow == nil ? IndexPath(item: (self.dataSource?.flatPickerNumberOfRows(pickerView: self) ?? 0)/2, section: 0) : IndexPath(item: currentSelectedRow, section: 0)
selectItemAtIntexPath(indexPath: indexPath, animated: false, triggerDelegate: false)
}
private func initialize() {
setupCollectionView()
//Setting default direction
direction = .vertical
setupPickerSelectionView()
}
open func reload() {
self.collectionView?.reloadData()
}
private func highlitedViewFrameForDirection() {
if direction != nil {
if direction == .horizontal {
highlightedView?.frame = CGRect(x: frame.size.width/2 - (itemSize/2),
y: 0,
width: itemSize, height: frame.size.height)
} else {
highlightedView?.frame = CGRect(x: 0,
y: frame.size.height/2 - (itemSize/2),
width: frame.size.width, height: itemSize)
}
}
}
private func setupCollectionView() {
let collectionView: UICollectionView = UICollectionView(frame: CGRect.zero,
collectionViewLayout: UICollectionViewFlowLayout())
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = UIColor.clear
collectionView.allowsSelection = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "DefaultCell")
collectionView.register(TextCollectionViewCell.self, forCellWithReuseIdentifier: TextCollectionViewCell.reuseIdentifier)
addSubview(collectionView)
collectionView.frame = CGRect(origin: CGPoint.zero, size: frame.size)
self.collectionView = collectionView
}
private func setupPickerSelectionView() {
highlightedView?.removeFromSuperview()
let pickerSelectionView: UIView = self.delegate?.flatPickerViewForSelectedItem(pickerView: self) ?? PickerDefaultSelectedItemView(frame: CGRect.zero, direction : direction)
if pickerSelectionView is PickerDefaultSelectedItemView {
pickerSelectionView.isUserInteractionEnabled = false
}
addSubview(pickerSelectionView)
bringSubview(toFront: pickerSelectionView)
self.highlightedView = pickerSelectionView
highlitedViewFrameForDirection()
highlightedView.isHidden = !(self.delegate?.flatPickerShouldShowSelectionView(pickerView: self) ?? true)
}
private func setupInsetForCollection() {
if direction == .vertical {
collectionView.contentInset = UIEdgeInsets(top: (frame.size.height/2) - (itemSize/2),
left: 0,
bottom: (frame.size.height/2) - (itemSize/2) ,
right: 0)
} else {
collectionView.contentInset = UIEdgeInsets(top: 0,
left: (frame.size.width/2) - (itemSize/2),
bottom: 0,
right: (frame.size.width/2) - (itemSize/2))
}
}
// MARK: Public functions
open func selectRow(at row: Int, animated: Bool) {
selectItemAtIntexPath(indexPath: IndexPath(item: row, section: 0), animated: animated, triggerDelegate: true)
}
open func viewForRow(at row: Int) -> UIView? {
return collectionView.cellForItem(at: IndexPath(item: row, section: 0))?.contentView
}
}
extension FlatPickerView: UICollectionViewDelegate, UICollectionViewDataSource {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource?.flatPickerNumberOfRows(pickerView: self) ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let text = self.delegate?.flatPicker(pickerView: self, titleForRow: indexPath.item) {
return generateCellForText(collectionView, indexPath: indexPath, text: text)
} else if let attrText = self.delegate?.flatPicker(pickerView: self, attributedTitleForRow: indexPath.row) {
return generateCellForAttibutedText(collectionView, indexPath: indexPath, attributedText: attrText)
} else if let view = self.delegate?.flatPicker(pickerView: self, viewForRow: indexPath.item) {
return generateCustomViewCell(collectionView, indexPath: indexPath, view: view)
}
return UICollectionViewCell()
}
// MARK: Generate cells
private func generateCustomViewCell(_ collectionView: UICollectionView, indexPath: IndexPath, view: UIView) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DefaultCell", for: indexPath)
view.frame = cell.contentView.frame
cell.contentView.subviews.forEach({$0.removeFromSuperview()})
cell.contentView.addSubview(view)
return cell
}
private func generateCellForAttibutedText(_ collectionView: UICollectionView, indexPath: IndexPath, attributedText: NSAttributedString) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TextCollectionViewCell.reuseIdentifier, for: indexPath) as! TextCollectionViewCell
cell.textLabel.attributedText = attributedText
return cell
}
private func generateCellForText(_ collectionView: UICollectionView, indexPath: IndexPath, text: String) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TextCollectionViewCell.reuseIdentifier, for: indexPath) as! TextCollectionViewCell
cell.textLabel.text = text
return cell
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let indexPath = collectionView.indexPathForItem(at: CGPoint(x: highlightedView.center.x + collectionView.contentOffset.x, y: highlightedView.center.y + collectionView.contentOffset.y)) {
if lastIdxPassedOnSelection == nil || indexPath.row != lastIdxPassedOnSelection {
lastIdxPassedOnSelection = indexPath.row
self.delegate?.flatPicker(pickerView: self, didPassOnSelection: indexPath.row)
}
}
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
adjustSelectedItem()
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
adjustSelectedItem()
}
private func adjustSelectedItem() {
var incrementalSpacing: CGFloat = 0
var point: CGPoint = CGPoint(x: highlightedView.center.x + collectionView.contentOffset.x, y: highlightedView.center.y + collectionView.contentOffset.y)
//Searching for the nearst cell
repeat {
if let indexPath = collectionView.indexPathForItem(at: point) {
selectItemAtIntexPath(indexPath: indexPath, animated: true, triggerDelegate: true)
break
} else {
incrementalSpacing += 1.0
if direction == .vertical {
point = CGPoint(x: highlightedView.center.x + collectionView.contentOffset.x,
y: highlightedView.center.y + collectionView.contentOffset.y + incrementalSpacing)
} else {
point = CGPoint(x: highlightedView.center.x + collectionView.contentOffset.x + incrementalSpacing,
y: highlightedView.center.y + collectionView.contentOffset.y)
}
}
} while point.x < frame.size.width || point.y < frame.size.height
}
fileprivate func selectItemAtIntexPath(indexPath: IndexPath, animated: Bool, triggerDelegate: Bool) {
if indexPath.item >= 0 && indexPath.row < collectionView.numberOfItems(inSection: 0) {
if let layout = collectionView.layoutAttributesForItem(at: indexPath) {
var point: CGPoint = CGPoint.zero
if direction == .vertical {
point = CGPoint(x: collectionView.contentOffset.x, y: layout.frame.origin.y - collectionView.contentInset.top)
} else {
point = CGPoint(x: layout.frame.origin.x - collectionView.contentInset.left, y: collectionView.contentOffset.y)
}
collectionView.setContentOffset( point, animated: animated)
CATransaction.setCompletionBlock({
if self.currentSelectedRow == nil || self.currentSelectedRow != indexPath.item {
self.currentSelectedRow = indexPath.item
if triggerDelegate {
self.delegate?.flatPicker(pickerView: self, didSelectRow: indexPath.item)
}
}
})
}
}
}
}
extension FlatPickerView : UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if direction == .horizontal {
return CGSize(width: itemSize, height: self.frame.size.height )
}
return CGSize(width: self.frame.size.width, height: itemSize )
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return self.delegate?.flatPickerSpacingBetweenItems(pickerView: self) ?? 1
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return self.delegate?.flatPickerSpacingBetweenItems(pickerView: self) ?? 1
}
}
| mit | 717d54424064c01073318b6f4f491f7f | 43.467105 | 209 | 0.653499 | 5.560675 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Crypto/MXCryptoV2.swift | 1 | 26978 | //
// Copyright 2022 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
#if DEBUG
public extension MXLegacyCrypto {
/// Create a Rust-based work-in-progress implementation of `MXCrypto`
///
/// The experimental crypto module is created only if:
/// - using DEBUG build
/// - enabling `enableCryptoV2` feature flag
@objc static func createCryptoV2IfAvailable(session: MXSession!) -> MXCrypto? {
let log = MXNamedLog(name: "MXCryptoV2")
guard MXSDKOptions.sharedInstance().enableCryptoV2 else {
return nil
}
guard let session = session else {
log.failure("Cannot create crypto V2, missing session")
return nil
}
do {
return try MXCryptoV2(session: session)
} catch {
log.failure("Error creating crypto V2", context: error)
return nil
}
}
}
#endif
#if DEBUG
import MatrixSDKCrypto
/// An implementation of `MXCrypto` which uses [matrix-rust-sdk](https://github.com/matrix-org/matrix-rust-sdk/tree/main/crates/matrix-sdk-crypto)
/// under the hood.
private class MXCryptoV2: NSObject, MXCrypto {
enum Error: Swift.Error {
case missingCredentials
case missingRoom
case roomNotEncrypted
case cannotUnsetTrust
case backupNotEnabled
}
// MARK: - Private properties
private static let keyRotationPeriodMsgs: Int = 100
private static let keyRotationPeriodSec: Int = 7 * 24 * 3600
private weak var session: MXSession?
private let cryptoQueue: DispatchQueue
private let legacyStore: MXCryptoStore
private let machine: MXCryptoMachine
private let roomEventDecryptor: MXRoomEventDecrypting
private let deviceInfoSource: MXDeviceInfoSource
private let trustLevelSource: MXTrustLevelSource
private let backupEngine: MXCryptoKeyBackupEngine?
private let keyVerification: MXKeyVerificationManagerV2
private var startTask: Task<(), Never>?
private var roomEventObserver: Any?
private let log = MXNamedLog(name: "MXCryptoV2")
// MARK: - Public properties
var version: String {
guard let sdkVersion = Bundle(for: OlmMachine.self).infoDictionary?["CFBundleShortVersionString"] else {
return "Matrix SDK Crypto"
}
return "Matrix SDK Crypto \(sdkVersion)"
}
var deviceCurve25519Key: String? {
return machine.deviceCurve25519Key
}
var deviceEd25519Key: String? {
return machine.deviceEd25519Key
}
let backup: MXKeyBackup?
let keyVerificationManager: MXKeyVerificationManager
let crossSigning: MXCrossSigning
let recoveryService: MXRecoveryService
init(session: MXSession) throws {
guard
let restClient = session.matrixRestClient,
let credentials = session.credentials,
let userId = credentials.userId,
let deviceId = credentials.deviceId
else {
throw Error.missingCredentials
}
self.session = session
self.cryptoQueue = DispatchQueue(label: "MXCryptoV2-\(userId)")
// A few features (global untrusted users blacklist) are not yet implemented in `MatrixSDKCrypto`
// so they have to be stored locally. Will be moved to `MatrixSDKCrypto` eventually
if MXRealmCryptoStore.hasData(for: credentials) {
self.legacyStore = MXRealmCryptoStore(credentials: credentials)
} else {
self.legacyStore = MXRealmCryptoStore.createStore(with: credentials)
}
machine = try MXCryptoMachine(
userId: userId,
deviceId: deviceId,
restClient: restClient,
getRoomAction: { [weak session] roomId in
session?.room(withRoomId: roomId)
}
)
roomEventDecryptor = MXRoomEventDecryption(handler: machine)
deviceInfoSource = MXDeviceInfoSource(source: machine)
trustLevelSource = MXTrustLevelSource(
userIdentitySource: machine,
devicesSource: machine
)
keyVerification = MXKeyVerificationManagerV2(
session: session,
handler: machine
)
if MXSDKOptions.sharedInstance().enableKeyBackupWhenStartingMXCrypto {
let engine = MXCryptoKeyBackupEngine(backup: machine, roomEventDecryptor: roomEventDecryptor)
backupEngine = engine
backup = MXKeyBackup(
engine: engine,
restClient: restClient,
secretShareManager: MXSecretShareManager(),
queue: cryptoQueue
)
} else {
backupEngine = nil
backup = nil
}
keyVerificationManager = keyVerification
let crossSign = MXCrossSigningV2(
crossSigning: machine,
restClient: restClient
)
crossSigning = crossSign
recoveryService = MXRecoveryService(
dependencies: .init(
credentials: restClient.credentials,
backup: backup,
secretStorage: MXSecretStorage(
matrixSession: session,
processingQueue: cryptoQueue
),
secretStore: MXCryptoSecretStoreV2(
backup: backup,
backupEngine: backupEngine,
crossSigning: machine
),
crossSigning: crossSigning,
cryptoQueue: cryptoQueue
),
delegate: crossSign
)
log.debug("Initialized Crypto module")
}
// MARK: - Crypto start / close
func start(
_ onComplete: (() -> Void)?,
failure: ((Swift.Error) -> Void)?
) {
guard startTask == nil else {
log.error("Crypto module has already been started")
onComplete?()
return
}
log.debug("->")
startTask = Task {
do {
try await machine.start()
crossSigning.refreshState(success: nil)
backup?.checkAndStart()
log.debug("Crypto module started")
await MainActor.run {
listenToRoomEvents()
onComplete?()
}
} catch {
log.error("Failed starting crypto module", context: error)
await MainActor.run {
failure?(error)
}
}
}
}
public func close(_ deleteStore: Bool) {
log.debug("->")
startTask?.cancel()
startTask = nil
session?.removeListener(roomEventObserver)
Task {
await roomEventDecryptor.resetUndecryptedEvents()
}
if deleteStore {
if let credentials = session?.credentials {
MXRealmCryptoStore.delete(with: credentials)
} else {
log.failure("Missing credentials, cannot delete store")
}
do {
try machine.deleteAllData()
} catch {
log.failure("Cannot delete crypto store", context: error)
}
}
}
// MARK: - Event Encryption
public func isRoomEncrypted(_ roomId: String) -> Bool {
guard let summary = session?.room(withRoomId: roomId)?.summary else {
log.error("Missing room")
return false
}
// State of room encryption is not yet implemented in `MatrixSDKCrypto`
// Will be moved to `MatrixSDKCrypto` eventually
return summary.isEncrypted
}
func encryptEventContent(
_ eventContent: [AnyHashable: Any],
withType eventType: String,
in room: MXRoom,
success: (([AnyHashable: Any], String) -> Void)?,
failure: ((Swift.Error) -> Void)?
) -> MXHTTPOperation? {
log.debug("Encrypting content of type `\(eventType)`")
let startDate = Date()
let stopTracking = MXSDKOptions.sharedInstance().analyticsDelegate?
.startDurationTracking(forName: "MXCryptoV2", operation: "encryptEventContent")
guard let roomId = room.roomId else {
log.failure("Missing room id")
failure?(Error.missingRoom)
return nil
}
guard isRoomEncrypted(roomId) else {
log.failure("Attempting to encrypt event in room without encryption")
failure?(Error.roomNotEncrypted)
return nil
}
Task {
do {
let users = try await getRoomUserIds(for: room)
let settings = try encryptionSettings(for: room)
try await machine.shareRoomKeysIfNecessary(
roomId: roomId,
users: users,
settings: settings
)
let result = try machine.encryptRoomEvent(
content: eventContent,
roomId: roomId,
eventType: eventType
)
stopTracking?()
let duration = Date().timeIntervalSince(startDate) * 1000
log.debug("Encrypted in \(duration) ms")
await MainActor.run {
success?(result, kMXEventTypeStringRoomEncrypted)
}
} catch {
log.error("Error encrypting content", context: error)
await MainActor.run {
failure?(error)
}
}
}
return nil
}
func decryptEvents(
_ events: [MXEvent],
inTimeline timeline: String?,
onComplete: (([MXEventDecryptionResult]) -> Void)?
) {
guard session?.isEventStreamInitialised == true else {
log.debug("Ignoring \(events.count) encrypted event(s) during initial sync in timeline \(timeline ?? "") (we most likely do not have the keys yet)")
let results = events.map { _ in MXEventDecryptionResult() }
onComplete?(results)
return
}
Task {
log.debug("Decrypting \(events.count) event(s) in timeline \(timeline ?? "")")
let results = await roomEventDecryptor.decrypt(events: events)
await MainActor.run {
onComplete?(results)
}
}
}
func ensureEncryption(
inRoom roomId: String,
success: (() -> Void)?,
failure: ((Swift.Error) -> Void)?
) -> MXHTTPOperation? {
log.debug("->")
guard let room = session?.room(withRoomId: roomId) else {
log.failure("Missing room")
failure?(Error.missingRoom)
return nil
}
Task {
do {
let users = try await getRoomUserIds(for: room)
let settings = try encryptionSettings(for: room)
try await machine.shareRoomKeysIfNecessary(
roomId: roomId,
users: users,
settings: settings
)
log.debug("Room keys shared when necessary")
await MainActor.run {
success?()
}
} catch {
log.error("Error ensuring encryption", context: error)
await MainActor.run {
failure?(error)
}
}
}
return nil
}
public func eventDeviceInfo(_ event: MXEvent) -> MXDeviceInfo? {
guard
let userId = event.sender,
let deviceId = event.wireContent["device_id"] as? String
else {
log.error("Missing user id or device id")
return nil;
}
return device(withDeviceId: deviceId, ofUser: userId)
}
public func discardOutboundGroupSessionForRoom(
withRoomId roomId: String,
onComplete: (() -> Void)?
) {
log.debug("->")
machine.discardRoomKey(roomId: roomId)
onComplete?()
}
// MARK: - Sync
func handle(_ syncResponse: MXSyncResponse, onComplete: @escaping () -> Void) {
let toDeviceCount = syncResponse.toDevice?.events.count ?? 0
let devicesChanged = syncResponse.deviceLists?.changed?.count ?? 0
let devicesLeft = syncResponse.deviceLists?.left?.count ?? 0
MXLog.debug("[MXCryptoV2] --------------------------------")
log.debug("Handling new sync response with \(toDeviceCount) to-device event(s), \(devicesChanged) device(s) changed, \(devicesLeft) device(s) left")
Task {
do {
let toDevice = try machine.handleSyncResponse(
toDevice: syncResponse.toDevice,
deviceLists: syncResponse.deviceLists,
deviceOneTimeKeysCounts: syncResponse.deviceOneTimeKeysCount ?? [:],
unusedFallbackKeys: syncResponse.unusedFallbackKeys
)
await handle(toDeviceEvents: toDevice.events)
try await machine.processOutgoingRequests()
} catch {
log.error("Cannot handle sync", context: error)
}
log.debug("Completing sync response")
MXLog.debug("[MXCryptoV2] --------------------------------")
await MainActor.run {
onComplete()
}
}
}
private func handle(toDeviceEvents: [MXEvent]) async {
// Some of the to-device events processed by the machine require further updates
// on the client side, not currently exposed through any convenient api.
// These include new key verification events, or receiving backup key
// which allows downloading room keys from backup.
for event in toDeviceEvents {
await keyVerification.handleDeviceEvent(event)
restoreBackupIfPossible(event: event)
await roomEventDecryptor.handlePossibleRoomKeyEvent(event)
}
if backupEngine?.enabled == true && backupEngine?.hasKeysToBackup() == true {
backup?.maybeSend()
}
}
// MARK: - Cross-signing / Local trust
public func setDeviceVerification(
_ verificationStatus: MXDeviceVerification,
forDevice deviceId: String,
ofUser userId: String,
success: (() -> Void)?,
failure: ((Swift.Error) -> Void)?
) {
log.debug("Setting device verification status to \(verificationStatus)")
let localTrust = verificationStatus.localTrust
switch localTrust {
case .verified:
// If we want to set verified status, we will manually verify the device,
// including uploading relevant signatures
Task {
do {
try await machine.verifyDevice(userId: userId, deviceId: deviceId)
log.debug("Successfully marked device as verified")
await MainActor.run {
success?()
}
} catch {
log.error("Failed marking device as verified", context: error)
await MainActor.run {
failure?(error)
}
}
}
case .blackListed, .ignored, .unset:
// In other cases we will only set local trust level
do {
try machine.setLocalTrust(userId: userId, deviceId: deviceId, trust: localTrust)
log.debug("Successfully set local trust to \(localTrust)")
success?()
} catch {
log.error("Failed setting local trust", context: error)
failure?(error)
}
}
}
public func setUserVerification(
_ verificationStatus: Bool,
forUser userId: String,
success: (() -> Void)?,
failure: ((Swift.Error) -> Void)?
) {
guard verificationStatus else {
log.failure("Cannot unset user trust")
failure?(Error.cannotUnsetTrust)
return
}
log.debug("Signing user")
crossSigning.signUser(
withUserId: userId,
success: {
success?()
},
failure: {
failure?($0)
}
)
}
public func trustLevel(forUser userId: String) -> MXUserTrustLevel {
return trustLevelSource.userTrustLevel(userId: userId)
}
public func deviceTrustLevel(forDevice deviceId: String, ofUser userId: String) -> MXDeviceTrustLevel? {
return trustLevelSource.deviceTrustLevel(userId: userId, deviceId: deviceId)
}
public func trustLevelSummary(
forUserIds userIds: [String],
forceDownload: Bool,
success: ((MXUsersTrustLevelSummary?) -> Void)?,
failure: ((Swift.Error) -> Void)?
) {
_ = downloadKeys(userIds, forceDownload: forceDownload, success: { [weak self] _, _ in
success?(
self?.trustLevelSource.trustLevelSummary(userIds: userIds)
)
}, failure: failure)
}
// MARK: - Users keys
public func downloadKeys(
_ userIds: [String],
forceDownload: Bool,
success: ((MXUsersDevicesMap<MXDeviceInfo>?, [String: MXCrossSigningInfo]?) -> Void)?,
failure: ((Swift.Error) -> Void)?
) -> MXHTTPOperation? {
log.debug("->")
guard forceDownload else {
success?(
deviceInfoSource.devicesMap(userIds: userIds),
crossSigningInfo(userIds: userIds)
)
return nil
}
log.debug("Force-downloading keys")
Task {
do {
try await machine.downloadKeys(users: userIds)
log.debug("Downloaded keys")
await MainActor.run {
success?(
deviceInfoSource.devicesMap(userIds: userIds),
crossSigningInfo(userIds: userIds)
)
}
} catch {
log.error("Failed downloading keys", context: error)
await MainActor.run {
failure?(error)
}
}
}
return nil
}
public func devices(forUser userId: String) -> [String : MXDeviceInfo] {
return deviceInfoSource.devicesInfo(userId: userId)
}
public func device(withDeviceId deviceId: String, ofUser userId: String) -> MXDeviceInfo? {
return deviceInfoSource.deviceInfo(userId: userId, deviceId: deviceId)
}
// MARK: - Import / Export
public func exportRoomKeys(
withPassword password: String,
success: ((Data) -> Void)?,
failure: ((Swift.Error) -> Void)?
) {
log.debug("->")
guard let engine = backupEngine else {
log.failure("Cannot export keys when backup not enabled")
failure?(Error.backupNotEnabled)
return
}
Task {
do {
let data = try engine.exportRoomKeys(passphrase: password)
await MainActor.run {
log.debug("Exported room keys")
success?(data)
}
} catch {
await MainActor.run {
log.error("Failed exporting room keys", context: error)
failure?(error)
}
}
}
}
public func importRoomKeys(
_ keyFile: Data,
withPassword password: String,
success: ((UInt, UInt) -> Void)?,
failure: ((Swift.Error) -> Void)?
) {
log.debug("->")
guard let engine = backupEngine else {
log.failure("Cannot import keys when backup not enabled")
failure?(Error.backupNotEnabled)
return
}
Task {
do {
let result = try await engine.importRoomKeys(keyFile, passphrase: password)
await MainActor.run {
log.debug("Imported room keys")
success?(UInt(result.total), UInt(result.imported))
}
} catch {
await MainActor.run {
log.error("Failed importing room keys", context: error)
failure?(error)
}
}
}
}
// MARK: - Key sharing
public func reRequestRoomKey(for event: MXEvent) {
log.debug("->")
Task {
do {
try await machine.requestRoomKey(event: event)
log.debug("Sent room key request")
} catch {
log.error("Failed requesting room key", context: error)
}
}
}
// MARK: - Crypto settings
public var globalBlacklistUnverifiedDevices: Bool {
get {
return legacyStore.globalBlacklistUnverifiedDevices
}
set {
legacyStore.globalBlacklistUnverifiedDevices = newValue
}
}
public func isBlacklistUnverifiedDevices(inRoom roomId: String) -> Bool {
return legacyStore.blacklistUnverifiedDevices(inRoom: roomId)
}
public func setBlacklistUnverifiedDevicesInRoom(_ roomId: String, blacklist: Bool) {
legacyStore.storeBlacklistUnverifiedDevices(inRoom: roomId, blacklist: blacklist)
}
// MARK: - Private
private func listenToRoomEvents() {
guard let session = session else {
return
}
roomEventObserver = session.listenToEvents(Array(MXKeyVerificationManagerV2.dmEventTypes)) { [weak self] event, direction, _ in
guard let self = self else { return }
if direction == .forwards && event.sender != session.myUserId {
Task {
if let userId = await self.keyVerification.handleRoomEvent(event), !self.machine.isUserTracked(userId: userId) {
// If we recieved a verification event from a new user we do not yet track
// we need to download their keys to be able to proceed with the verification flow
try await self.machine.downloadKeys(users: [userId])
}
}
}
}
}
private func restoreBackupIfPossible(event: MXEvent) {
guard
event.type == kMXEventTypeStringSecretSend
&& event.content?["name"] as? NSString == MXSecretId.keyBackup.takeUnretainedValue(),
let secret = MXSecretShareSend(fromJSON: event.content)?.secret
else {
return
}
log.debug("Restoring backup after receiving backup key")
guard
let backupVersion = backup?.keyBackupVersion,
let version = backupVersion.version else
{
log.error("There is not backup version to restore")
return
}
let data = MXBase64Tools.data(fromBase64: secret)
backupEngine?.savePrivateKey(data, version: version)
log.debug("Restoring room keys")
backup?.restore(usingPrivateKeyKeyBackup: backupVersion, room: nil, session: nil) { [weak self] total, imported in
self?.log.debug("Restored \(imported) out of \(total) room keys")
}
}
private func getRoomUserIds(for room: MXRoom) async throws -> [String] {
return try await room.members()?.members
.compactMap(\.userId) ?? []
}
private func crossSigningInfo(userIds: [String]) -> [String: MXCrossSigningInfo] {
return userIds
.compactMap(crossSigning.crossSigningKeys(forUser:))
.reduce(into: [String: MXCrossSigningInfo] ()) { dict, info in
return dict[info.userId] = info
}
}
private func encryptionSettings(for room: MXRoom) throws -> EncryptionSettings {
guard let roomId = room.roomId else {
throw Error.missingRoom
}
let historyVisibility = try HistoryVisibility(identifier: room.summary.historyVisibility)
return .init(
algorithm: .megolmV1AesSha2,
rotationPeriod: UInt64(Self.keyRotationPeriodSec),
rotationPeriodMsgs: UInt64(Self.keyRotationPeriodMsgs),
historyVisibility: historyVisibility,
onlyAllowTrustedDevices: globalBlacklistUnverifiedDevices || isBlacklistUnverifiedDevices(inRoom: roomId)
)
}
}
private extension MXDeviceVerification {
var localTrust: LocalTrust {
switch self {
case .unverified:
return .unset
case .verified:
return .verified
case .blocked:
return .blackListed
case .unknown:
return .unset
@unknown default:
MXNamedLog(name: "MXDeviceVerification").failure("Unknown device verification", context: self)
return .unset
}
}
}
private extension HistoryVisibility {
enum Error: Swift.Error {
case invalidVisibility
}
init(identifier: String) throws {
guard let visibility = MXRoomHistoryVisibility(identifier: identifier) else {
throw Error.invalidVisibility
}
switch visibility {
case .worldReadable:
self = .worldReadable
case .shared:
self = .shared
case .invited:
self = .invited
case .joined:
self = .joined
}
}
}
#endif
| apache-2.0 | 47bcc0518a9505cdc326b0b23df98c02 | 32.7225 | 160 | 0.550486 | 5.280485 | false | false | false | false |
smoope/ios-sdk | Pod/Classes/SPConversation.swift | 1 | 1717 | /*
* Copyright 2016 smoope GmbH
*
* 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
public class SPConversation: SPCreated {
public var lastActivity: NSDate?
public var unreadMessages: Int?
public private(set) var states: [SPConversationState] = []
public required init(data: [String: AnyObject]) {
if let lastActivity = data["lastActivity"] {
self.lastActivity = NSDate.fromISO8601String(lastActivity as! String)
}
if let unreadMessages = data["unreadMessages"] {
self.unreadMessages = unreadMessages as? Int
}
if let states = data["status"] as? [String] {
self.states = states.map({ s in SPConversationState(rawValue: s)!})
}
super.init(data: data)
}
public override func unmap() -> Dictionary<String, AnyObject> {
var result: [String: AnyObject] = [:]
if let lastActivity = self.lastActivity {
result["lastActivity"] = lastActivity.toISO8601String()
}
if let unreadMessages = self.unreadMessages {
result["unreadMessages"] = unreadMessages
}
if !states.isEmpty {
result["states"] = states.map({ i in i.rawValue })
}
return result
.append(super.unmap())
}
} | apache-2.0 | 89ea06cb7a3cca727884989fddc5e8b8 | 29.678571 | 75 | 0.68841 | 4.157385 | false | false | false | false |
lucaslouca/swift-concurrency | app-ios/Fluxcapacitor/FXCViewControllerOrderListing.swift | 1 | 27367 | //
// FXCViewControllerOrderListing.swift
// Fluxcapacitor
//
// Created by Lucas Louca on 24/05/15.
// Copyright (c) 2015 Lucas Louca. All rights reserved.
//
import UIKit
class FXCViewControllerOrderListing: UIViewController, UITableViewDelegate, UITableViewDataSource, FXCOrderFetchDelegate, UISearchResultsUpdating {
@IBOutlet weak var orderListingTableView: UITableView!
@IBOutlet weak var numberOfResultsLabel: UILabel!
@IBOutlet weak var searchBarView: UIView!
@IBOutlet weak var barView: FXCBorderView!
@IBOutlet weak var orderListingTableViewConstTop: NSLayoutConstraint!
var searchController: UISearchController!
let tableViewCellIdentifier = "FXCTableViewCellOrderListing"
let segueToOrderDetails = "SegueToOrderDetails"
let tableViewCellNibName = "FXCTableViewCellOrderListing"
var orders = [FXCOrder]()
var filteredOrders = [FXCOrder]()
var selectedOrder: FXCOrder?
var refreshControl: UIRefreshControl!
var refreshLoadingView : UIView!
var refreshColorView : UIView!
var compass_background : UIImageView!
var compass_spinner : UIImageView!
var isRefreshIconsOverlap = false
var isRefreshAnimating = false
var sortDropDownView: UIView!
var sortDropDownViewConstHeight: NSLayoutConstraint!
var sortDropDownIsExpanded = false
var currentSorting: FXCSortAttribute = FXCSortAttribute.None
enum FXCSortOrder {
case Descending, Ascending
}
enum FXCSortAttribute {
case None, PriceDescending, PriceAscending
}
override func viewDidLoad() {
super.viewDidLoad()
// Setup search
setupSearch()
// Hide navigation bars shadow image and setup colors
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.backgroundColor = UIColor.whiteColor()
self.navigationController?.navigationBar.tintColor = UIColor.darkGrayColor()
// Register table cell nib
let tableViewCellNib = UINib(nibName: tableViewCellNibName, bundle: nil)
orderListingTableView.registerNib(tableViewCellNib, forCellReuseIdentifier: tableViewCellIdentifier)
// Setup pull and refresh
setupRefreshControl()
// Setup dropdown for sorting
setupSortDropDownView()
// Fetch Order meta information
FXCFluxcapacitorAPI.sharedInstance.fetchOrderDetails(self)
}
// MARK: - Sorting
func setupSortDropDownView() {
sortDropDownView = NSBundle.mainBundle().loadNibNamed("FXCViewOrderListingSort", owner: self, options: nil)[0] as? UIView
sortDropDownView.frame = CGRectMake(0, 0, self.view.frame.width, 200)
sortDropDownView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(sortDropDownView!)
let constTop = NSLayoutConstraint(item: sortDropDownView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: barView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
let constWidth = NSLayoutConstraint(item: sortDropDownView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)
sortDropDownViewConstHeight = NSLayoutConstraint(item: sortDropDownView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0)
self.view.addConstraint(constTop)
self.view.addConstraint(constWidth)
self.view.addConstraint(sortDropDownViewConstHeight)
sortDropDownView.alpha = 0.0
}
/**
Button action when the sort button is tapped. This action toggles the sort drop down menu view's visibility
*/
@IBAction func sortButtonTapped(sender: AnyObject) {
let sortDropDownViewExpandedHeight: CGFloat = 37.0
let sortDropDownViewHiddenHeight: CGFloat = 0.0
if (!sortDropDownIsExpanded) {
UIView.animateWithDuration(0.2, animations: {
self.sortDropDownView.frame = CGRectMake(self.sortDropDownView.frame.origin.x, self.sortDropDownView.frame.origin.y, self.view.frame.width, sortDropDownViewExpandedHeight)
self.orderListingTableView.frame = CGRectMake(self.orderListingTableView.frame.origin.x, self.orderListingTableView.frame.origin.y + sortDropDownViewExpandedHeight, self.orderListingTableView.frame.width, self.orderListingTableView.frame.height - sortDropDownViewExpandedHeight)
self.sortDropDownView.alpha = 1.0
}, completion: {
(complete: Bool) in
self.sortDropDownViewConstHeight.constant = sortDropDownViewExpandedHeight
self.orderListingTableViewConstTop.constant = sortDropDownViewExpandedHeight
self.sortDropDownIsExpanded = true
})
} else {
UIView.animateWithDuration(0.2, animations: {
self.sortDropDownView.frame = CGRectMake(self.sortDropDownView.frame.origin.x, self.sortDropDownView.frame.origin.y, self.view.frame.width, sortDropDownViewHiddenHeight)
self.orderListingTableView.frame = CGRectMake(self.orderListingTableView.frame.origin.x, self.orderListingTableView.frame.origin.y - sortDropDownViewExpandedHeight, self.orderListingTableView.frame.width, self.orderListingTableView.frame.height + sortDropDownViewExpandedHeight)
self.sortDropDownView.alpha = 0.0
}, completion: {
(complete: Bool) in
self.sortDropDownViewConstHeight.constant = sortDropDownViewHiddenHeight
self.orderListingTableViewConstTop.constant = sortDropDownViewHiddenHeight
self.sortDropDownIsExpanded = false
})
}
}
/**
Sorts orders in table view by price descending (15, 14, 9, ....) or ascending (9, 14, 15 ...)
- parameter FXCSortOrder: the sorting order to perform
*/
func sortByPriceUsingSortOrder(sortOrder: FXCSortOrder) {
// We need an unsorted copy of the array for the animation
let unsortedOrders = orders
// Sort the elements and replace the array used by the data source with the sorted ones
if (sortOrder == FXCSortOrder.Descending) {
orders.sortInPlace { $0.price > $1.price }
} else if (sortOrder == FXCSortOrder.Ascending) {
orders.sortInPlace { $0.price < $1.price }
}
updateTableWithSorting(unsortedOrders)
}
/**
Changes the order of the items in the table view based on the old and new order array
- parameter [FXCOrder]: array of unsorted orders
*/
func updateTableWithSorting(unsortedOrders:[FXCOrder]) {
// Prepare table for the animations batch
orderListingTableView.beginUpdates()
// Move the cells around
var sourceRow = 0;
for order in unsortedOrders {
let destRow = orders.indexOf(order)
if (destRow != sourceRow) {
// Move the rows within the table view
let sourceIndexPath = NSIndexPath(forItem: sourceRow, inSection: 0)
let destIndexPath = NSIndexPath(forItem: destRow!, inSection: 0)
orderListingTableView.moveRowAtIndexPath(sourceIndexPath, toIndexPath: destIndexPath)
// Alternate row colors
if destIndexPath.row % 2 == 1 {
orderListingTableView.cellForRowAtIndexPath(sourceIndexPath)?.backgroundColor = UIColor(red: 250.0/255.0, green: 250.0/255.0, blue: 250.0/255.0, alpha: 1.0)
} else {
orderListingTableView.cellForRowAtIndexPath(sourceIndexPath)?.backgroundColor = UIColor.whiteColor()
}
}
sourceRow++
}
orderListingTableView.endUpdates()
}
/**
Applies the sorting on the order array based on the currentSorting value
*/
func applySorting() {
// Do sorting when new orders finished parsing
switch currentSorting {
case .PriceAscending:
sortByPriceUsingSortOrder(FXCSortOrder.Ascending)
case .PriceDescending:
sortByPriceUsingSortOrder(FXCSortOrder.Descending)
default:
NSLog("no sorting")
}
}
@IBAction func buttonSortPriceAscendingTapped(sender: AnyObject) {
if let button = sender as? UIButton {
if (button.selected) {
sortByPriceUsingSortOrder(FXCSortOrder.Ascending)
currentSorting = FXCSortAttribute.PriceAscending
} else {
currentSorting = FXCSortAttribute.None
}
}
}
@IBAction func buttonSortPriceDescendingTapped(sender: AnyObject) {
if let button = sender as? UIButton {
if (button.selected) {
sortByPriceUsingSortOrder(FXCSortOrder.Descending)
currentSorting = FXCSortAttribute.PriceDescending
} else {
currentSorting = FXCSortAttribute.None
}
}
}
// MARK: - Operations
func startOperationsForOrder(orderDetails:FXCOrder, indexPath: NSIndexPath) {
switch (orderDetails.state) {
case .New:
FXCFluxcapacitorAPI.sharedInstance.startDownloadForOrder(orderDetails, indexPath: indexPath, delegate:self)
case .Downloaded:
FXCFluxcapacitorAPI.sharedInstance.startXMPParsingForOrder(orderDetails, indexPath: indexPath, delegate:self)
default:
NSLog("")
}
}
func suspendAllOperations() {
FXCFluxcapacitorAPI.sharedInstance.suspendAllOrderDownloads()
FXCFluxcapacitorAPI.sharedInstance.suspendAllOrderXMLParsingOperations()
}
func resumeAllOperations() {
FXCFluxcapacitorAPI.sharedInstance.resumeAllOrderDownloads()
FXCFluxcapacitorAPI.sharedInstance.resumeAllOrderXMLParsingOperations()
}
/**
Cancel processing of off-screen cells and prioritize the cells that are currently displayed.
*/
func loadOrdersForOnscreenCells () {
// Start with an array containing index paths of all the currently visible rows in the table view.
if let pathsArray = orderListingTableView.indexPathsForVisibleRows {
// Get a set of all pending operations by combining all the downloads in progress + all the XML parsers in progress.
let allPendingOperations = FXCFluxcapacitorAPI.sharedInstance.allPendingOrderOperations()
//Construct a set of all index paths with operations to be cancelled. Start with all operations, and then remove the index paths of the visible rows. This will leave the set of operations involving off-screen rows.
var toBeCancelled = allPendingOperations
let visiblePaths = Set(pathsArray as [NSIndexPath])
toBeCancelled.subtractInPlace(visiblePaths)
//Construct a set of index paths that need their operations started. Start with index paths all visible rows, and then remove the ones where operations are already pending.
var toBeStarted = visiblePaths
toBeStarted.subtractInPlace(allPendingOperations)
//Loop through those to be cancelled, cancel them, and remove their reference from PendingOperations.
for indexPath in toBeCancelled {
FXCFluxcapacitorAPI.sharedInstance.cancelDownloadOrderOperation(indexPath)
FXCFluxcapacitorAPI.sharedInstance.cancelXMLParsingOrderOperation(indexPath)
}
// Loop through those to be started, and call startOperationsForOrder for each.
for indexPath in toBeStarted {
let indexPath = indexPath as NSIndexPath
let orderToProcess = orders[indexPath.row]
startOperationsForOrder(orderToProcess, indexPath:indexPath)
}
}
}
// MARK: - Search
func setupSearch() {
searchController = UISearchController(searchResultsController: nil)
searchController.dimsBackgroundDuringPresentation = false
searchController.searchResultsUpdater = self
searchController.searchBar.frame = CGRectMake(0, 0, searchBarView.frame.width, searchBarView.frame.height)
searchController.searchBar.autoresizingMask = UIViewAutoresizing.FlexibleWidth
searchController.searchBar.placeholder = "Address"
searchController.searchBar.layer.borderColor = UIColor.whiteColor().CGColor
searchController.searchBar.layer.borderWidth = 1.0
searchController.searchBar.barTintColor = UIColor.whiteColor()
let searchField = searchController.searchBar.valueForKey("searchField") as! UITextField
searchField.backgroundColor = UIColor.whiteColor()
searchField.layer.borderColor = UIColor.lightGrayColor().CGColor
searchField.layer.borderWidth = 1.0
searchBarView.addSubview(searchController.searchBar)
}
func filterContentForSearchText(searchText: String) {
// Filter the array using the filter method
self.filteredOrders = self.orders.filter({( order: FXCOrder) -> Bool in
let stringMatch = order.address.rangeOfString(searchText)
return (stringMatch != nil)
})
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == segueToOrderDetails {
if let destination = segue.destinationViewController as? FXCViewControllerOrderDetails {
if selectedOrder != nil {
destination.order = selectedOrder
}
}
}
}
/**
Action performed when a detail button in the table view cell is tapped
*/
func detailButtonTapped(sender:UIButton!) {
let buttonPosition: CGPoint = sender.convertPoint(CGPointZero, toView: orderListingTableView)
if let orderIndex = orderListingTableView.indexPathForRowAtPoint(buttonPosition) {
if (searchController.active) {
selectedOrder = filteredOrders[orderIndex.row]
} else {
selectedOrder = orders[orderIndex.row]
}
performSegueWithIdentifier(segueToOrderDetails, sender: self)
}
}
// MARK: - Pull to Refresh
func setupRefreshControl() {
// Programmatically inserting a UIRefreshControl
self.refreshControl = UIRefreshControl()
orderListingTableView.addSubview(refreshControl)
// Setup the loading view, which will hold the moving graphics
self.refreshLoadingView = UIView(frame: self.refreshControl!.bounds)
self.refreshLoadingView.backgroundColor = UIColor.clearColor()
// Setup the color view, which will display the rainbowed background
self.refreshColorView = UIView(frame: self.refreshControl!.bounds)
self.refreshColorView.backgroundColor = UIColor.clearColor()
self.refreshColorView.alpha = 0.30
// Create the graphic image views
compass_background = UIImageView(image: UIImage(named: "compass_background.png"))
self.compass_spinner = UIImageView(image: UIImage(named: "compass_spinner.png"))
// Add the graphics to the loading view
self.refreshLoadingView.addSubview(self.compass_background)
self.refreshLoadingView.addSubview(self.compass_spinner)
// Clip so the graphics don't stick out
self.refreshLoadingView.clipsToBounds = true;
// Hide the original spinner icon
self.refreshControl!.tintColor = UIColor.clearColor()
// Add the loading and colors views to our refresh control
self.refreshControl!.addSubview(self.refreshColorView)
self.refreshControl!.addSubview(self.refreshLoadingView)
// Initalize flags
self.isRefreshIconsOverlap = false;
self.isRefreshAnimating = false;
// When activated, invoke our refresh function
self.refreshControl?.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
}
func refresh(){
FXCFluxcapacitorAPI.sharedInstance.fetchOrderDetails(self)
let delayInSeconds = 1.0;
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)));
dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
// When done requesting/reloading/processing invoke endRefreshing, to close the control
self.refreshControl!.endRefreshing()
}
}
func animateRefreshView() {
// Background color to loop through for our color view
var colorArray = [FXCDrawUtil.greenColor, FXCDrawUtil.orangeColor]
// In Swift, static variables must be members of a struct or class
struct ColorIndex {
static var colorIndex = 0
}
// Flag that we are animating
self.isRefreshAnimating = true;
UIView.animateWithDuration(
Double(0.2),
delay: Double(0.0),
options: UIViewAnimationOptions.CurveLinear,
animations: {
// Rotate the spinner by M_PI_2 = PI/2 = 90 degrees
self.compass_spinner.transform = CGAffineTransformRotate(self.compass_spinner.transform, CGFloat(M_PI_2))
// Change the background color
self.refreshColorView!.backgroundColor = colorArray[ColorIndex.colorIndex]
ColorIndex.colorIndex = (ColorIndex.colorIndex + 1) % colorArray.count
},
completion: { finished in
// If still refreshing, keep spinning, else reset
if (self.refreshControl!.refreshing) {
self.animateRefreshView()
}else {
self.resetAnimation()
}
}
)
}
func resetAnimation() {
// Reset our flags and }background color
self.isRefreshAnimating = false;
self.isRefreshIconsOverlap = false;
self.refreshColorView.backgroundColor = UIColor.clearColor()
}
}
// MARK: - UISearchResultsUpdating
extension FXCViewControllerOrderListing {
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
self.orderListingTableView.reloadData()
}
}
// MARK: - UITableViewDataSource
extension FXCViewControllerOrderListing {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.searchController.active) {
numberOfResultsLabel.text = "\(self.filteredOrders.count) orders"
return filteredOrders.count
} else {
numberOfResultsLabel.text = "\(self.orders.count) orders"
return orders.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: FXCTableViewCellOrderListing = self.orderListingTableView.dequeueReusableCellWithIdentifier(tableViewCellIdentifier) as! FXCTableViewCellOrderListing
// Alternate row colors
if indexPath.row % 2 == 1 {
cell.backgroundColor = UIColor(red: 250.0/255.0, green: 250.0/255.0, blue: 250.0/255.0, alpha: 1.0)
} else {
cell.backgroundColor = UIColor.whiteColor()
}
// Remove any accessoryView (e.g. DetailButton) because we are using a reusable cell
cell.accessoryView = nil
if cell.accessoryView == nil {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
cell.accessoryView = indicator
}
let indicator = cell.accessoryView as? UIActivityIndicatorView
cell.accessoryType = UITableViewCellAccessoryType.DetailDisclosureButton
var orderDetails: FXCOrder!
if (self.searchController.active) {
orderDetails = filteredOrders[indexPath.row]
} else {
orderDetails = orders[indexPath.row]
}
// Fill details
cell.priceLabel.text = "$\(orderDetails.price)"
cell.itemCountLabel.text = "\(orderDetails.itemCount)"
cell.dateLabel.text = "\(orderDetails.deliveryDate)"
cell.radiusLabel.text = "\(orderDetails.radius) \(orderDetails.radiusUnit)"
switch (orderDetails.state){
case .New, .Downloaded:
indicator?.startAnimating()
if (!orderListingTableView.dragging && !orderListingTableView.decelerating) {
startOperationsForOrder(orderDetails, indexPath:indexPath)
}
case .Parsed:
indicator?.stopAnimating()
let detailButton = FXCButtonDetail(frame: CGRectMake(0, 0, 30, 30))
detailButton.borderColor = FXCDrawUtil.iconColor
detailButton.borderWidth = 1.0
detailButton.cornerRadius = 15.0
detailButton.addTarget(self, action: "detailButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
cell.accessoryView = detailButton
case .Failed:
indicator?.stopAnimating()
}
return cell;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 90
}
}
// MARK: - UITableViewDelegate
extension FXCViewControllerOrderListing {
/**
As soon as the user starts scrolling, we want to suspend all operations and take a look at what the user wants to see.
*/
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
suspendAllOperations()
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//If the value of decelerate is false, that means the user stopped dragging the table view. Therefore you want to resume suspended operations, cancel operations for offscreen cells, and start operations for onscreen cells.
if !decelerate {
loadOrdersForOnscreenCells()
resumeAllOperations()
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
loadOrdersForOnscreenCells()
resumeAllOperations()
}
/**
Show pull to refresh image
*/
func scrollViewDidScroll(scrollView: UIScrollView) {
// Get the current size of the refresh controller
var refreshBounds = self.refreshControl!.bounds
// Distance the table has been pulled >= 0
let pullDistance = max(0.0, -self.refreshControl!.frame.origin.y)
// Half the width of the table
let midX = self.orderListingTableView.frame.size.width / 2.0
// Calculate the width and height of our graphics
let compassHeight = self.compass_background.bounds.size.height
let compassHeightHalf = compassHeight / 2.0
let compassWidth = self.compass_background.bounds.size.width
let compassWidthHalf = compassWidth / 2.0
let spinnerHeight = self.compass_spinner.bounds.size.height
let spinnerHeightHalf = spinnerHeight / 2.0
let spinnerWidth = self.compass_spinner.bounds.size.width
let spinnerWidthHalf = spinnerWidth / 2.0
// Calculate the pull ratio, between 0.0-1.0
let pullRatio = min( max(pullDistance, 0.0), 100.0) / 100.0
// Set the Y coord of the graphics, based on pull distance
let compassY = pullDistance / 2.0 - compassHeightHalf
let spinnerY = pullDistance / 2.0 - spinnerHeightHalf
// Calculate the X coord of the graphics, adjust based on pull ratio
var compassX = (midX + compassWidthHalf) - (compassWidth * pullRatio)
var spinnerX = (midX - spinnerWidth - spinnerWidthHalf) + (spinnerWidth * pullRatio)
// When the compass and spinner overlap, keep them together
if (fabsf(Float(compassX - spinnerX)) < 1.0) {
self.isRefreshIconsOverlap = true
}
// If the graphics have overlapped or we are refreshing, keep them together
if (self.isRefreshIconsOverlap || self.refreshControl!.refreshing) {
compassX = midX - compassWidthHalf
spinnerX = midX - spinnerWidthHalf
}
// Set the graphic's frames
var compassFrame = self.compass_background.frame;
compassFrame.origin.x = compassX
compassFrame.origin.y = compassY
var spinnerFrame = self.compass_spinner.frame;
spinnerFrame.origin.x = spinnerX
spinnerFrame.origin.y = spinnerY
self.compass_background.frame = compassFrame
self.compass_spinner.frame = spinnerFrame
// Set the encompassing view's frames
refreshBounds.size.height = pullDistance
self.refreshColorView.frame = refreshBounds
self.refreshLoadingView.frame = refreshBounds
// Set alpha
self.compass_background.alpha = pullRatio
self.compass_spinner.alpha = pullRatio
// If we're refreshing and the animation is not playing, then play the animation
if (self.refreshControl!.refreshing && !self.isRefreshAnimating) {
self.animateRefreshView()
}
}
}
// MARK: - FXCOrderFetchDelegate
extension FXCViewControllerOrderListing {
func orderDetailsFetchDidFinishWith(orderDetails:[FXCOrder]) {
self.filteredOrders.removeAll(keepCapacity: false)
self.orders = orderDetails
if (searchController.active) {
filterContentForSearchText(self.searchController.searchBar.text!)
}
self.orderListingTableView.reloadData()
}
func orderDownloadDidFinishForIndexPath(indexPath: NSIndexPath) {
self.orderListingTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
func orderXMParsingDidFinishForIndexPath(indexPath: NSIndexPath) {
if (currentSorting != FXCSortAttribute.None) {
applySorting()
// reload whole table, because moved cells that werent parsing (because they were not visible)
// have become visible now (after the sorting) and should start parsing.
self.orderListingTableView.reloadData()
} else {
self.orderListingTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
} | mit | 3746093788126925e8f9c4677be7ba90 | 42.929374 | 294 | 0.661198 | 5.209785 | false | false | false | false |
JensRavens/crumbstr | Crumbstr/Controllers/PostViewController.swift | 1 | 1187 | //
// PostViewController.swift
// Crumbstr
//
// Created by Jens Ravens on 20/05/15.
// Copyright (c) 2015 swift.berlin. All rights reserved.
//
import Foundation
import Foundation
import Interstellar
import CoreLocation
import Social
public class PostViewController: SLComposeServiceViewController {
let location = LocationService.sharedService.location.ensure(Thread.main)
let user = UserService.sharedService.user
public override func viewDidLoad() {
super.viewDidLoad()
location.subscribe { result in
self.validateContent()
}
}
public override func didSelectPost() {
let crumb = Crumb(location: location.peek()!, text: contentText, author: user.peek()!)
CrumbService.sharedService.createCrumb(crumb) { result in }
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
public override func didSelectCancel() {
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
public override func isContentValid() -> Bool {
return count(contentText)>3 && location.peek() != nil && user.peek() != nil
}
} | mit | 35b3f44ebee82f6a76a39e6fe22cf326 | 28.7 | 94 | 0.695872 | 4.748 | false | false | false | false |
PerfectlySoft/Perfect-Authentication | Sources/OAuth2/AuthProviders/Slack.swift | 1 | 4738 | //
// Slack.swift
// Perfect-Authentication
//
// Created by Jonathan Guthrie on 2017-01-31.
//
//
import Foundation
import PerfectHTTP
import PerfectSession
/// Slack configuration singleton
public struct SlackConfig {
/// AppID obtained from registering app with Slack (Also known as Client ID)
public static var appid = ""
/// Secret associated with AppID (also known as Client Secret)
public static var secret = ""
/// Where should Slack redirect to after Authorization
public static var endpointAfterAuth = ""
/// Where should the app redirect to after Authorization & Token Exchange
public static var redirectAfterAuth = ""
public init(){}
}
/**
Slack allows you to authenticate against Slack for login purposes.
*/
public class Slack: OAuth2 {
/**
Create a Slack object. Uses the Client ID and Client Secret from the
Slack Developers Console.
*/
public init(clientID: String, clientSecret: String) {
let tokenURL = "https://slack.com/api/oauth.access"
let authorizationURL = "https://slack.com/oauth/authorize"
super.init(clientID: clientID, clientSecret: clientSecret, authorizationURL: authorizationURL, tokenURL: tokenURL)
}
private var appAccessToken: String {
return clientID + "%7C" + clientSecret
}
/// After exchanging token, this function retrieves user information from Slack
public func getUserData(_ accessToken: String) -> [String: Any] {
let url = "https://slack.com/api/users.identity?token=\(accessToken)"
// let (_, data, _, _) = makeRequest(.get, url)
let data = makeRequest(.get, url)
var out = [String: Any]()
out["id"] = digIntoDictionary(mineFor: ["user", "id"], data: data) as! String
let fullName = digIntoDictionary(mineFor: ["user", "name"], data: data) as! String
let fullNameSplit = fullName.components(separatedBy: " ")
if fullNameSplit.count > 0 {
out["first_name"] = fullNameSplit.first
}
if fullNameSplit.count > 1 {
out["last_name"] = fullNameSplit.last
}
out["picture"] = digIntoDictionary(mineFor: ["user", "image_192"], data: data) as! String
return out
}
/// Slack-specific exchange function
public func exchange(request: HTTPRequest, state: String) throws -> OAuth2Token {
return try exchange(request: request, state: state, redirectURL: "\(SlackConfig.endpointAfterAuth)?session=\((request.session?.token)!)")
}
/// Slack-specific login link
public func getLoginLink(state: String, request: HTTPRequest, scopes: [String] = ["identity.basic", "identity.avatar"]) -> String {
return getLoginLink(redirectURL: "\(SlackConfig.endpointAfterAuth)?session=\((request.session?.token)!)", state: state, scopes: scopes)
}
/// Route handler for managing the response from the OAuth provider
/// Route definition would be in the form
/// ["method":"get", "uri":"/auth/response/slack", "handler":Slack.authResponse]
public static func authResponse(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let fb = Slack(clientID: SlackConfig.appid, clientSecret: SlackConfig.secret)
do {
guard let state = request.session?.data["csrf"] else {
// print("state issue: \(request.session?.data["state"])")
throw OAuth2Error(code: .unsupportedResponseType)
}
let t = try fb.exchange(request: request, state: state as! String)
request.session?.data["accessToken"] = t.accessToken
request.session?.data["refreshToken"] = t.refreshToken
let userdata = fb.getUserData(t.accessToken)
request.session?.data["loginType"] = "slack"
if let i = userdata["id"] {
request.session?.userid = i as! String
}
if let i = userdata["first_name"] {
request.session?.data["firstName"] = i as! String
}
if let i = userdata["last_name"] {
request.session?.data["lastName"] = i as! String
}
if let i = userdata["picture"] {
request.session?.data["picture"] = i as! String
}
} catch {
print(error)
}
response.redirect(path: SlackConfig.redirectAfterAuth, sessionid: (request.session?.token)!)
}
}
/// Route handler for managing the sending of the user to the OAuth provider for approval/login
/// Route definition would be in the form
/// ["method":"get", "uri":"/to/Slack", "handler":Slack.sendToProvider]
public static func sendToProvider(data: [String:Any]) throws -> RequestHandler {
// let rand = URandom()
return {
request, response in
// Add secure state token to session
// We expect to get this back from the auth
// request.session?.data["state"] = rand.secureToken
let fb = Slack(clientID: SlackConfig.appid, clientSecret: SlackConfig.secret)
response.redirect(path: fb.getLoginLink(state: request.session?.data["csrf"] as! String, request: request))
}
}
}
| apache-2.0 | 05d09d89265757790ddf57c3d1162b05 | 32.842857 | 139 | 0.69924 | 3.721917 | false | true | false | false |
marmelroy/PeekPop | PeekPop/PeekPopExtensions.swift | 1 | 1508 | //
// PeekPopExtensions.swift
// PeekPop
//
// Created by Roy Marmelstein on 11/03/2016.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import Foundation
extension UIView {
func screenshotView(_ inHierarchy: Bool = true, rect: CGRect? = nil) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.layer.frame.size, false, UIScreen.main.scale);
defer{
UIGraphicsEndImageContext()
}
if inHierarchy == true {
self.drawHierarchy(in: self.bounds, afterScreenUpdates: false)
}
else {
if let context = UIGraphicsGetCurrentContext() {
self.layer.render(in: context)
}
}
let image = UIGraphicsGetImageFromCurrentImageContext()
let rectTransform = CGAffineTransform(scaleX: (image?.scale)!, y: (image?.scale)!)
if let rect = rect, let croppedImageRef = image?.cgImage?.cropping(to: rect.applying(rectTransform)) {
return UIImage(cgImage: croppedImageRef)
}
else {
return image
}
}
}
extension PeekPop: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension PreviewingContext: Equatable {}
public func ==(lhs: PreviewingContext, rhs: PreviewingContext) -> Bool {
return lhs.sourceView == rhs.sourceView
}
| mit | 77e2d6f3abde855c77b81e8208d080c9 | 31.06383 | 164 | 0.656934 | 5.057047 | false | false | false | false |
hanhailong/practice-swift | Courses/stanford/stanford/cs193p/2015/Psychologist/Psychologist/PsychologistViewController.swift | 3 | 1208 | //
// ViewController.swift
// Psychologist
//
// Created by Domenico on 21.03.15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
class PsychologistViewController: UIViewController {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
// Check if the destination is a UIViewController
var destination = segue.destinationViewController as? UIViewController
// navCon should be a UINavigationController
if let navCon = destination as? UINavigationController{
destination = navCon.visibleViewController
}
if let hvc = destination as? HappinessViewController{
// Check if the identifier is set
if let identifier = segue.identifier{
switch identifier{
case "sad": hvc.happiness = 0
case "happy": hvc.happiness = 100
case "nothing": hvc.happiness = 25
default: hvc.happiness = 50
}
}
}
}
@IBAction func nothing(sender: UIButton) {
// Prepare the segue
performSegueWithIdentifier("nothing", sender: sender)
}
}
| mit | f2029aa2bed79bfabd8b0dbbc8f973f6 | 29.974359 | 80 | 0.616722 | 5.490909 | false | false | false | false |
davepatterson/DPValidatedTableViewController | Controllers/DPValidatedTableViewController.swift | 1 | 10051 | // Added tag 0.1.0
// DPValidatedViewController.swift
// DPValidateDemo
//
// Created by David Patterson on 8/24/15.
// Copyright (c) 2015 David Patterson. All rights reserved.
//
import UIKit
class DPValidatedTableViewController: UITableViewController, UITextFieldDelegate {
var validatedFields: [DPValidatedField] = []
private var validatedFieldsAndLabels: [AnyObject] = []
var errors: [DPValidatedLabel] = []
var rowHeight: CGFloat = 0.0
var errorColor: UIColor
var successColor: UIColor
var submitButton: DPValidatedSubmitButton
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(DPValidatedTableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
// center submit button in its super view (tableFooterView)
self.rowHeight = 50.0
self.tableView.rowHeight = self.rowHeight
self.tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.width, height: 45))
self.submitButton.addTarget(self, action: "submit", forControlEvents: UIControlEvents.TouchDown)
self.tableView.tableFooterView?.addSubview(submitButton)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
self.computeValidatedFieldsArray()
}
override init(style: UITableViewStyle) {
self.errorColor = UIColor(red: 0.88627450980392, green: 0.17254901960784, blue: 0.27058823529412, alpha: 1.0)
self.successColor = UIColor(red: 0.4, green: 0.690196, blue: 0.196078, alpha: 1.0)
self.submitButton = DPValidatedSubmitButton()
super.init(style: UITableViewStyle.Grouped)
}
required init!(coder aDecoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}
private override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
self.errorColor = UIColor(red: 0.88627450980392, green: 0.17254901960784, blue: 0.27058823529412, alpha: 1.0)
self.successColor = UIColor(red: 0.4, green: 0.690196, blue: 0.196078, alpha: 1.0)
self.submitButton = DPValidatedSubmitButton()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return validatedFields.count
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pressedSubmitButton() {
self.validateFields()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! DPValidatedTableViewCell
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins = UIEdgeInsetsZero
// get DPValidatedField from validatedFields array
let validatedField = validatedFields[indexPath.row]
cell.configureCellValidatedField(validatedField)
cell.accessoryType = UITableViewCellAccessoryType.None
return cell
}
func validateFields() {
var isValid: Bool
isValid = true
for field in validatedFields {
// if a field is invalid, change status to false
if !field.isValidated {
isValid = false
break
}
}
if isValid {
// since form has been validated, enable submit button
self.submitButton.alpha = 1.0
self.submitButton.enabled = true
} else {
// form is invalid, disable submit button
self.submitButton.alpha = 0.3
self.submitButton.enabled = false
}
}
func validateFieldIdentifiedByIndex(index: Int) {
}
func computeValidatedFieldsArray() {
// create an error label for each field that will be validated
var cnt: Int = 0
for field in self.validatedFields {
// add anged target to eachc textField
field.textField.addTarget(self, action: "textFieldChanged:", forControlEvents: UIControlEvents.EditingChanged)
field.textField.addTarget(self, action: "textFieldWasExited:", forControlEvents: UIControlEvents.EditingDidEnd)
field.textField.delegate = self
field.textField.tag = cnt
let result = field.rules.filter { $0 is ConfirmationRule }
if !result.isEmpty {
field.isConfirmField = true
self.validatedFields[cnt-1].isOriginalToCofirmField = true
}
cnt++
}
}
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// search from array of fields with errors
let field = validatedFields[indexPath.row]
if field.errors_.count > 0 {
return self.rowHeight + 30
} else {
return self.rowHeight
}
}
// MARK: - UITextField Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldChanged(textField: UITextField) {
let field = validatedFields[textField.tag]
// see if textField has started validating, if it hasn't, don't validate on keyup
if !field.startedValidating {
return
}
self.tableView.beginUpdates()
if field.isOriginalToCofirmField {
// prepare to retrieve field's DPValidatedTableViewCell
let indexPath = NSIndexPath(forRow: field.textField.tag, inSection: 0)
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! DPValidatedTableViewCell
// prepare to retrieve confirm fields DPValidatedTableViewCell
let confirmIndexPath = NSIndexPath(forRow: field.textField.tag+1, inSection: 0)
let confirmCell = self.tableView.cellForRowAtIndexPath(confirmIndexPath) as! DPValidatedTableViewCell
// since the field is original to a confirm field
// validate both fields with consideration of each other
let confirmField = validatedFields[textField.tag+1]
field.validateWithConfirmField(confirmField)
// if field is validated add checkmark
if field.isValidated {
// add checkmark to uitableviewcell
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
cell.tintColor = self.successColor
cell.textField?.tintColor = UITextField().tintColor
if field.textField.text == confirmField.textField.text {
confirmCell.accessoryType = UITableViewCellAccessoryType.Checkmark
confirmCell.tintColor = self.successColor
confirmCell.textField?.tintColor = UITextField().tintColor
}
} else {
cell.accessoryType = UITableViewCellAccessoryType.None
confirmField.isValidated = false
confirmCell.accessoryType = UITableViewCellAccessoryType.None
}
} else if field.isConfirmField {
// prepare to retrieve field's DPValidatedTableViewCell
let indexPath = NSIndexPath(forRow: field.textField.tag, inSection: 0)
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! DPValidatedTableViewCell
// since field is a confirm field
// validate it and its original field
let originalField = validatedFields[textField.tag-1]
field.validateWithConfirmField(originalField)
originalField.validateWithConfirmField(field)
// if field is validated add checkmark
if field.isValidated {
// add checkmark to uitableviewcell
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
cell.tintColor = self.successColor
cell.textField?.tintColor = UITextField().tintColor
} else {
cell.accessoryType = UITableViewCellAccessoryType.None
}
} else {
self.tableView.beginUpdates()
field.validateField()
self.tableView.endUpdates()
let indexPath = NSIndexPath(forRow: field.textField.tag, inSection: 0)
let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! DPValidatedTableViewCell
if field.isValidated {
// add checkmark to UITableViewCell
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
cell.tintColor = self.successColor
cell.textField?.tintColor = UITextField().tintColor
} else {
cell.accessoryType = UITableViewCellAccessoryType.None
}
}
self.tableView.endUpdates()
// check to see if form validation is complete
self.validateFields()
}
func textFieldWasExited(textField: UITextField) {
let field = validatedFields[textField.tag]
// skip validation if user has never typed in field
if !field.startedValidating && field.textField.text.isEmpty {
return
}
field.startedValidating = true
// begin field's initial validation
self.textFieldChanged(textField)
}
func submit() {
}
}
| mit | cc5ce160f44553e2069363163e353711 | 40.192623 | 135 | 0.64123 | 5.392167 | false | false | false | false |
danielsaidi/KeyboardKit | Sources/KeyboardKit/Keyboard/KeyboardHostingController.swift | 1 | 1284 | //
// KeyboardKeyboardHostingController.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2020-03-13.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import SwiftUI
/**
This controller can be used to add any `SwiftUI`-based view
to a `KeyboardInputViewController`.
You can either manually create a controller instance with a
`rootView` then add it to your `KeyboardInputViewController`
with `add(to:)` or use the input controller's `setup(with:)`
with a `SwiftUI` `View`, which does of all this for you.
*/
public class KeyboardHostingController<Content: View>: UIHostingController<Content> {
public func add(to controller: KeyboardInputViewController) {
controller.addChild(self)
controller.view.addSubview(view)
didMove(toParent: controller)
view.backgroundColor = .clear
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: controller.view.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: controller.view.trailingAnchor).isActive = true
view.topAnchor.constraint(equalTo: controller.view.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: controller.view.bottomAnchor).isActive = true
}
}
| mit | b097b766a2c25673ee938ddbf6181e00 | 37.878788 | 95 | 0.740452 | 4.699634 | false | false | false | false |
GiorgioNatili/pokedev | Pokedev/Pokedev/PokemonsCollection/Presenter/PokemonsCollectionPresenter.swift | 1 | 2698 | //
// Created by Benjamin Soung
// Copyright (c) 2016 Benjamin Soung. All rights reserved.
//
import Foundation
import UIKit
import SwiftyJSON
class PokemonsCollectionPresenter: PokemonsCollectionPresenterProtocol, PokemonsCollectionInteractorOutputProtocol
{
weak var view: PokemonsCollectionViewProtocol?
var interactor: PokemonsCollectionInteractorInputProtocol?
var wireFrame: PokemonsCollectionWireFrameProtocol?
private let DEFAULT_ERROR_MESSAGE = "Something went wrong, sorry!"
init() {
}
// MARK: - Data layer
func loadPokemons() {
// TODO: load the data from the net
interactor?.loadData()
}
// MARK: INTERACTOR -> PRESENTER
func showData(data: AnyObject) {
guard (view != nil) else {
return
}
let json = JSON(data)
let results = json["results"]
var pokemons = [Pokemon]()
for (_, content):(String, JSON) in results {
let pokemon = Pokemon()
if let name = content["name"].string {
pokemon.name = name
}
if let url = content["url"].string {
pokemon.detailsAPI = url
}
pokemons.append(pokemon)
}
view!.renderData(pokemons)
}
func showErrorMessage(error: NSError) {
guard (view != nil) else {
return
}
// TODO log the core error with crashlythics
if let message = error.localizedFailureReason {
view!.showErrorMessage(message)
} else {
view!.showErrorMessage(DEFAULT_ERROR_MESSAGE)
}
}
// MARK: - User Interactions
func openDetails(id: String) {
print("I am going to open the pokemon \(id)")
if let window = UIApplication.sharedApplication().delegate!.window! {
let wireFrame:PokemonDetailsWireFrame = PokemonDetailsWireFrame()
wireFrame.presentPokemonDetailsModule(fromView: window.rootViewController!)
}
}
func openFavorites() {
// Launch the favorites view
if let window = UIApplication.sharedApplication().delegate!.window! {
let wireFrame:FavoritePokemonsWireFrameProtocol = FavoritePokemonsWireFrame()
wireFrame.presentFavoritePokemonsModule(fromView: window.rootViewController!)
}
}
} | unlicense | 42ed9e5690f67bea1c135d9a48928228 | 23.990741 | 114 | 0.54596 | 5.777302 | false | false | false | false |
jiayoufang/LearnSwift | SwiftTips.playground/Pages/GCD和延迟调用.xcplaygroundpage/Contents.swift | 1 | 1229 | //: [Previous](@previous)
import Foundation
//创建目标队列
let workingQueue = DispatchQueue(label: "com.ivan.myqueue")
//派发到刚创建的队列中,GCD会负责线程调度
workingQueue.async {
//在workQueue中异步进行
print("Working....")
//模拟两秒的执行时间
Thread.sleep(forTimeInterval: 2)
print("Work finish")
DispatchQueue.main.async {
print("在主线程中更新UI")
}
}
typealias Task = (_ cancel: Bool) -> Void
func delay(_ time: TimeInterval,task: @escaping () -> ()) -> Task? {
//这个时候就体会到@escaping的含义了
func dispatch_later(block: @escaping () -> ()){
let t = DispatchTime.now() + time
DispatchQueue.main.asyncAfter(deadline: t, execute: block)
}
var closure: (() -> Void)? = task
var result: Task?
let delayedClosure: Task = {
cancel in
if let internalClosure = closure {
if cancel == false {
DispatchQueue.main.async(execute: internalClosure)
}
}
closure = nil
result = nil
}
result = delayedClosure
return result
}
delay(2){
print("aa")
}
//: [Next](@next)
| mit | 235fb3eefa8a15fe7e4db09c3008ebaa | 18.875 | 68 | 0.575921 | 3.824742 | false | false | false | false |
serp1412/LazyTransitions | LazyTransitions/ProtocolInterceptor.swift | 1 | 6357 | final class ProtocolInterceptor: NSObject {
var interceptedProtocols: [Protocol] { return _interceptedProtocols }
private var _interceptedProtocols: [Protocol] = []
weak var receiver: NSObjectProtocol?
weak var middleMan: NSObjectProtocol?
private func doesSelectorBelongToAnyInterceptedProtocol(aSelector: Selector) -> Bool {
for aProtocol in _interceptedProtocols where sel_belongsToProtocol(aSelector, aProtocol) {
return true
}
return false
}
override func forwardingTarget(for aSelector: Selector!) -> Any? {
if middleMan?.responds(to: aSelector) == true,
doesSelectorBelongToAnyInterceptedProtocol(aSelector: aSelector) {
return middleMan
}
if receiver?.responds(to: aSelector) == true {
return receiver
}
return super.forwardingTarget(for: aSelector)
}
override func responds(to aSelector: Selector!) -> Bool {
if middleMan?.responds(to: aSelector) == true &&
doesSelectorBelongToAnyInterceptedProtocol(aSelector: aSelector) {
return true
}
if receiver?.responds(to: aSelector) == true {
return true
}
return super.responds(to: aSelector)
}
class func forProtocol(aProtocol: Protocol) -> ProtocolInterceptor {
return forProtocols(protocols: [aProtocol])
}
class func forProtocols(protocols: Protocol ...) -> ProtocolInterceptor {
return forProtocols(protocols: protocols)
}
class func forProtocols(protocols: [Protocol]) -> ProtocolInterceptor {
let protocolNames = protocols.map { NSStringFromProtocol($0) }
let sortedProtocolNames = protocolNames.sorted()
let concatenatedName = sortedProtocolNames.joined(separator: ",")
let theConcreteClass = concreteClassWithProtocols(protocols: protocols,
concatenatedName: concatenatedName,
salt: nil)
let protocolInterceptor = theConcreteClass.init()
as! ProtocolInterceptor
protocolInterceptor._interceptedProtocols = protocols
return protocolInterceptor
}
/**
Return a subclass of `NSProtocolInterceptor` which conforms to specified
protocols.
- Parameter protocols: An array of Objective-C protocols. The
subclass returned from this function will conform to these protocols.
- Parameter concatenatedName: A string which came from concatenating
names of `protocols`.
- Parameter salt: A UInt number appended to the class name
which used for distinguishing the class name itself from the duplicated.
- Discussion: The return value type of this function can only be
`NSObject.Type`, because if you return with `NSProtocolInterceptor.Type`,
you can only init the returned class to be a `NSProtocolInterceptor` but not
its subclass.
*/
private class func concreteClassWithProtocols(
protocols: [Protocol],
concatenatedName: String,
salt: UInt?
) -> NSObject.Type {
let className: String = {
let basicClassName = "_" +
NSStringFromClass(ProtocolInterceptor.self) +
"_" + concatenatedName
if let salt = salt { return basicClassName + "_\(salt)" }
else { return basicClassName }
}()
let nextSalt = salt.map {$0 + 1}
if let theClass = NSClassFromString(className) {
switch theClass {
case let anInterceptorClass as ProtocolInterceptor.Type:
let isClassConformsToAllProtocols: Bool = {
// Check if the found class conforms to the protocols
for eachProtocol in protocols
where !class_conformsToProtocol(anInterceptorClass,
eachProtocol)
{
return false
}
return true
}()
if isClassConformsToAllProtocols {
return anInterceptorClass
} else {
return concreteClassWithProtocols(protocols: protocols,
concatenatedName: concatenatedName,
salt: nextSalt)
}
default:
return concreteClassWithProtocols(protocols: protocols,
concatenatedName: concatenatedName,
salt: nextSalt)
}
} else {
let subclass = objc_allocateClassPair(ProtocolInterceptor.self,
className,
0)
as! NSObject.Type
for eachProtocol in protocols {
class_addProtocol(subclass, eachProtocol)
}
objc_registerClassPair(subclass)
return subclass
}
}
}
/**
Returns true when the given selector belongs to the given protocol.
*/
func sel_belongsToProtocol(_ aSelector: Selector, _ aProtocol: Protocol) -> Bool {
for optionBits: UInt in 0..<(1 << 2) {
let isRequired = optionBits & 1 != 0
let isInstance = !(optionBits & (1 << 1) != 0)
var methodDescription = protocol_getMethodDescription(aProtocol, aSelector, isRequired, isInstance)
if !objc_method_description_isEmpty(methodDescription: &methodDescription) {
return true
}
}
return false
}
func objc_method_description_isEmpty(methodDescription: inout objc_method_description) -> Bool {
let ptr: UnsafePointer<Int8> = withUnsafePointer(to: &methodDescription) { pointer in
let copy = pointer as UnsafePointer<objc_method_description>
let opaque: OpaquePointer = OpaquePointer.init(copy)
return UnsafePointer<Int8>.init(opaque)
}
for offset in 0..<MemoryLayout.size(ofValue: methodDescription) {
if ptr[offset] != 0 { return false }
}
return true
}
| bsd-2-clause | b07696cfaca4618b51497b40c90883c8 | 35.534483 | 107 | 0.585182 | 5.595951 | false | false | false | false |
AndrewJByrne/GoodAsOldPhones-Swift | GoodAsOldPhones/Order.swift | 1 | 1570 | //
// Order.swift
// GoodAsOldPhones
//
// Created by Andrew Byrne on 3/5/16.
// Copyright © 2016 Andrew Byrne. All rights reserved.
//
import UIKit
class Order: NSObject, NSCoding {
let productName: String
let productPrice: Double
init(productName: String, productPrice: Double) {
self.productName = productName
self.productPrice = productPrice
super.init()
}
required init?(coder aDecoder: NSCoder) {
self.productName = aDecoder.decodeObjectForKey("name") as! String
self.productPrice = aDecoder.decodeObjectForKey("price") as! Double
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(productName, forKey: "name")
aCoder.encodeObject(productPrice, forKey: "price")
}
/*
Version of initializer that can throw based on invalid initial property values.
I am not using this, because the callee would have to by wrapped in a try. Not sure if
this is the right thing to do at the moment.
enum OrderErrorsList: ErrorType {
case InvalidNewPropValue
}
init(productName: String, productPrice: Double) throws {
self.productName = productName
self.productPrice = productPrice
super.init()
guard self.productName.characters.count > 0 else {
throw OrderErrorsList.InvalidNewPropValue
}
guard self.productPrice > 0.0 else {
throw OrderErrorsList.InvalidNewPropValue
}
}
*/
}
| mit | cf80cabb267cfcf825f1c7728778ce95 | 22.772727 | 90 | 0.639898 | 4.587719 | false | false | false | false |
nguyenantinhbk77/practice-swift | Views/TableViews/Enabling Swipe deletion of TableViewCells/Enabling Swipe deletion of TableViewCells/ViewController.swift | 2 | 2903 | //
// ViewController.swift
// Enabling Swipe deletion of TableViewCells
//
// Created by Domenico Solazzo on 10/05/15.
// License MIT
//
import UIKit
class ViewController: UIViewController,
UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView?
var allRows:[String] = [String]()
// ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Mock data
for index in 1..<10{
allRows.append("Row at index \(index)")
}
// Set the edit button
self.navigationItem.setLeftBarButtonItem(editButtonItem(), animated: true)
// Create the table view
tableView = UITableView(frame: view.bounds, style: UITableViewStyle.Plain)
if let theTableView = tableView{
// Register the TableViewCell
theTableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "identifier")
theTableView.dataSource = self
theTableView.delegate = self
theTableView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
// Add the table view as subview
view.addSubview(theTableView)
}
}
//- MARK: UITableViewDataSource
// Number of rows for section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allRows.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = "Row \(indexPath.row)"
return cell
}
//- MARK: UITableViewDelegate
// It indicates if it is possible to insert or delete rows
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
// Get notified if a deletion has occurred
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// Check if it is a delete
if editingStyle == .Delete{
// Remove the object from the source
allRows.removeAtIndex(indexPath.row)
// Remove the object from the table view using a Left animation
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
}
}
// Set editing
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView!.setEditing(editing, animated: animated)
}
}
| mit | c3c80de2ff15cb8f5755fe620468034d | 34.402439 | 148 | 0.658973 | 5.912424 | false | false | false | false |
macbaszii/CustomUI | OZGradientView/OZGradientView.swift | 1 | 1702 | //
// OZGradientView.swift
// CustomUI
//
// Created by Kiattisak Anoochitarom on 9/11/2557 BE.
// Copyright (c) 2557 Kiattisak Anoochitarom. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable class OZGradientView: UIView {
// MARK: - Inspectable properties
@IBInspectable var startColor: UIColor = UIColor.whiteColor() {
didSet {
setupView()
}
}
@IBInspectable var endColor: UIColor = UIColor.blackColor() {
didSet {
setupView()
}
}
@IBInspectable var isHorizontal: Bool = false {
didSet {
setupView()
}
}
@IBInspectable var roundness: CGFloat = 0.0 {
didSet {
setupView()
}
}
// MARK: - Main Layer
var gradientLayer: CAGradientLayer {
return layer as CAGradientLayer
}
// MARK: - Internal Function
private func setupView() {
let colors: Array<AnyObject> = [startColor.CGColor, endColor.CGColor]
gradientLayer.colors = colors
gradientLayer.cornerRadius = roundness
if (isHorizontal) {
gradientLayer.endPoint = CGPoint(x: 1, y: 0)
} else {
gradientLayer.endPoint = CGPoint(x: 0, y: 1)
}
self.setNeedsDisplay()
}
// MARK: - Overrided Functions
override class func layerClass() -> AnyClass {
return CAGradientLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
}
| mit | 17198f56afb6a07878e2a63a6adabf74 | 21.103896 | 77 | 0.56463 | 4.663014 | false | false | false | false |
gottesmm/swift | test/decl/protocol/req/recursion.swift | 4 | 3411 | // RUN: %target-typecheck-verify-swift
protocol SomeProtocol {
associatedtype T
}
extension SomeProtocol where T == Optional<T> { } // expected-error{{same-type constraint 'Self.T' == 'Optional<Self.T>' is recursive}}
// rdar://problem/19840527
class X<T> where T == X { // expected-error{{same-type constraint 'T' == 'X<T>' is recursive}}
// expected-error@-1{{same-type requirement makes generic parameter 'T' non-generic}}
// expected-error@-2{{same-type requirement makes generic parameter 'T' non-generic}}
var type: T { return type(of: self) }
}
// FIXME: The "associated type 'Foo' is not a member type of 'Self'" diagnostic
// should also become "associated type 'Foo' references itself"
protocol CircularAssocTypeDefault {
associatedtype Z = Z // expected-error{{associated type 'Z' references itself}}
// expected-note@-1{{type declared here}}
// expected-note@-2{{protocol requires nested type 'Z'; do you want to add it?}}
associatedtype Z2 = Z3 // expected-note{{type declared here}}
// expected-note@-1{{protocol requires nested type 'Z2'; do you want to add it?}}
associatedtype Z3 = Z2 // expected-error{{associated type 'Z2' references itself}}
// expected-note@-1{{protocol requires nested type 'Z3'; do you want to add it?}}
associatedtype Z4 = Self.Z4 // expected-error{{associated type 'Z4' is not a member type of 'Self'}}
// expected-note@-1{{protocol requires nested type 'Z4'; do you want to add it?}}
associatedtype Z5 = Self.Z6
// expected-note@-1{{protocol requires nested type 'Z5'; do you want to add it?}}
associatedtype Z6 = Self.Z5 // expected-error{{associated type 'Z5' is not a member type of 'Self'}}
// expected-note@-1{{protocol requires nested type 'Z6'; do you want to add it?}}
}
struct ConformsToCircularAssocTypeDefault : CircularAssocTypeDefault { }
// expected-error@-1 {{type 'ConformsToCircularAssocTypeDefault' does not conform to protocol 'CircularAssocTypeDefault'}}
// rdar://problem/20000145
public protocol P {
associatedtype T
}
public struct S<A: P> where A.T == S<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'S' references itself}}
func f(a: A.T) {
g(a: id(t: a))
// expected-error@-1 {{cannot convert value of type 'A.T' to expected argument type 'S<_>'}}
_ = A.T.self
}
func g(a: S<A>) {
f(a: id(t: a))
// expected-note@-1 {{expected an argument list of type '(a: A.T)'}}
// expected-error@-2 {{cannot invoke 'f' with an argument list of type '(a: S<A>)'}}
_ = S<A>.self
}
func id<T>(t: T) -> T {
return t
}
}
protocol I {
// FIXME: these are spurious
init() // expected-note {{protocol requires initializer 'init()' with type '()'}}
}
protocol PI {
associatedtype T : I
}
struct SI<A: PI> : I where A : I, A.T == SI<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'SI' references itself}}
func ggg<T : I>(t: T.Type) -> T {
return T()
}
func foo() {
_ = A()
_ = A.T()
_ = SI<A>()
_ = ggg(t: A.self)
_ = ggg(t: A.T.self)
_ = self.ggg(t: A.self)
_ = self.ggg(t: A.T.self)
}
}
// Used to hit infinite recursion
struct S4<A: PI> : I where A : I {
}
struct S5<A: PI> : I where A : I, A.T == S4<A> {
}
// Used to hit ArchetypeBuilder assertions
struct SU<A: P> where A.T == SU {
}
struct SIU<A: PI> : I where A : I, A.T == SIU {
}
| apache-2.0 | a265be54a47aa1991ba8772ed8f7e733 | 30.293578 | 135 | 0.646145 | 3.236243 | false | false | false | false |
gaoleegin/SwiftLianxi | SwiftLianxi/SwiftLianxi/Classes/Mudule/Main/MainViewController.swift | 1 | 2235 | //
// MainViewController.swift
// SwiftLianxi
//
// Created by 高李军 on 15/10/19.
// Copyright © 2015年 LJLianXi. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
@IBOutlet weak var mainTabar: MainTabBar!
override func viewDidLoad() {
super.viewDidLoad()
UITabBar.appearance().tintColor = UIColor.orangeColor()
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
addChildViewController("首页", image: "tabbar_home", storyName: "Home")
addChildViewController("发现", image: "tabbar_discover", storyName: "Discover")
addChildViewController("消息", image: "tabbar_message_center", storyName: "Message")
addChildViewController("我的", image: "tabbar_profile", storyName: "Profile")
// Do any additional setup after loading the view.
//可以直接打印,可以给撰写按钮添加监听事件
print(self.mainTabar.plusBtn)
mainTabar.plusBtn.addTarget(self, action: "plusBtnClicked", forControlEvents: UIControlEvents.TouchUpInside)
}
//
func plusBtnClicked(){
print("添加按钮的点击")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func addChildViewController(title:String,image:String,storyName:String) {
let sb = UIStoryboard(name: storyName, bundle: nil)
let nav = sb.instantiateInitialViewController() as!UINavigationController
nav.title = title
nav.topViewController?.title = title
nav.tabBarItem.image = UIImage(named: image)
nav.tabBarItem.selectedImage = UIImage(named: image + "_highlighted")
addChildViewController(nav)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | e76dd5e4de067acce9e3f00d59d6bb85 | 33.774194 | 116 | 0.672078 | 4.877828 | false | false | false | false |
prine/ROGenericTableViewController | Source/ROGenericTableViewController.swift | 1 | 3579 | //
// ROTableViewControllerGeneric.swift
// ROTableViewController
//
// Created by Robin Oster on 27/03/15.
// Copyright (c) 2015 Rascor International AG. All rights reserved.
//
import UIKit
class Box<T> {
let unbox: T
init(_ value: T) { self.unbox = value }
}
/**
Generic TableViewController
Inspired by the article of objc.io by Chris Eidhof
*/
open class ROGenericTableViewController : UITableViewController {
fileprivate var items:[Any] = []
fileprivate var cellForRow: (UITableView, Any) -> UITableViewCell? = { _ in return nil }
fileprivate var didSelect:(Any) -> () = { _ in }
open var swipeActions:[UITableViewRowAction] = Array<UITableViewRowAction>()
override open func viewDidLoad() {
// Custom initialization
}
override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = cellForRow(self.tableView, items[(indexPath as NSIndexPath).row]) {
return cell
} else {
return UITableViewCell(style: .default, reuseIdentifier: "CustomCell")
}
}
override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
didSelect(items[(indexPath as NSIndexPath).row])
}
override open func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return self.swipeActions
}
override open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
// Otherwise the table view actions are not working
}
}
public func createViewControllerGeneric<A>(_ items: [A], cellForRow: @escaping (UITableView, A) -> UITableViewCell?, select:@escaping (A) -> (), storyboardName:String, tableViewControllerIdentifier:String) -> UITableViewController {
// Load the Custom table view cell from a storyboard
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
let vc:ROGenericTableViewController = storyboard.instantiateViewController(withIdentifier: tableViewControllerIdentifier) as! ROGenericTableViewController
return unbox(vc, items: items, cellForRow: cellForRow, didSelect: select)
}
public func createViewControllerGeneric<A>(_ items: [A], cellForRow: @escaping (UITableView, A) -> UITableViewCell?, select:@escaping (A) -> ()) -> UITableViewController {
// There was no storyboard or tableviewcontroller identifier given so create the ROTableViewControllerGeneric
let vc:ROGenericTableViewController = ROGenericTableViewController(style: UITableViewStyle.plain)
return unbox(vc, items: items, cellForRow: cellForRow, didSelect: select)
}
func unbox<A>(_ vc:ROGenericTableViewController, items:[A], cellForRow: @escaping (UITableView, A) -> UITableViewCell?, didSelect:@escaping (A) -> ()) -> ROGenericTableViewController {
vc.items = items.map { Box($0) }
vc.cellForRow = {tableView, obj in
if let value = obj as? Box<A> {
return cellForRow(tableView, value.unbox)
}
return nil
}
vc.didSelect = { obj in
if let value = obj as? Box<A> {
didSelect(value.unbox)
}
}
return vc
}
public func updateItems<A>(_ vc:ROGenericTableViewController, items:[A]) {
vc.items = items.map({ Box($0)})
}
| mit | 97fb74200a8c6ac48ee5588e8ca3c1f6 | 35.896907 | 232 | 0.690975 | 4.862772 | false | false | false | false |
jokechat/swift3-novel | swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorShape.swift | 8 | 5589 | //
// NVActivityIndicatorShape.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/22/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
enum NVActivityIndicatorShape {
case circle
case circleSemi
case ring
case ringTwoHalfVertical
case ringTwoHalfHorizontal
case ringThirdFour
case rectangle
case triangle
case line
case pacman
func layerWith(size: CGSize, color: UIColor) -> CALayer {
let layer: CAShapeLayer = CAShapeLayer()
var path: UIBezierPath = UIBezierPath()
let lineWidth: CGFloat = 2
switch self {
case .circle:
path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 2,
startAngle: 0,
endAngle: CGFloat(2 * M_PI),
clockwise: false);
layer.fillColor = color.cgColor
case .circleSemi:
path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 2,
startAngle: CGFloat(-M_PI / 6),
endAngle: CGFloat(-5 * M_PI / 6),
clockwise: false)
path.close()
layer.fillColor = color.cgColor
case .ring:
path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 2,
startAngle: 0,
endAngle: CGFloat(2 * M_PI),
clockwise: false);
layer.fillColor = nil
layer.strokeColor = color.cgColor
layer.lineWidth = lineWidth
case .ringTwoHalfVertical:
path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
radius:size.width / 2,
startAngle:CGFloat(-3 * M_PI_4),
endAngle:CGFloat(-M_PI_4),
clockwise:true)
path.move(
to: CGPoint(x: size.width / 2 - size.width / 2 * CGFloat(cos(M_PI_4)),
y: size.height / 2 + size.height / 2 * CGFloat(sin(M_PI_4)))
)
path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
radius:size.width / 2,
startAngle:CGFloat(-5 * M_PI_4),
endAngle:CGFloat(-7 * M_PI_4),
clockwise:false)
layer.fillColor = nil
layer.strokeColor = color.cgColor
layer.lineWidth = lineWidth
case .ringTwoHalfHorizontal:
path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
radius:size.width / 2,
startAngle:CGFloat(3 * M_PI_4),
endAngle:CGFloat(5 * M_PI_4),
clockwise:true)
path.move(
to: CGPoint(x: size.width / 2 + size.width / 2 * CGFloat(cos(M_PI_4)),
y: size.height / 2 - size.height / 2 * CGFloat(sin(M_PI_4)))
)
path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
radius:size.width / 2,
startAngle:CGFloat(-M_PI_4),
endAngle:CGFloat(M_PI_4),
clockwise:true)
layer.fillColor = nil
layer.strokeColor = color.cgColor
layer.lineWidth = lineWidth
case .ringThirdFour:
path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 2,
startAngle: CGFloat(-3 * M_PI_4),
endAngle: CGFloat(-M_PI_4),
clockwise: false)
layer.fillColor = nil
layer.strokeColor = color.cgColor
layer.lineWidth = 2
case .rectangle:
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: size.width, y: 0))
path.addLine(to: CGPoint(x: size.width, y: size.height))
path.addLine(to: CGPoint(x: 0, y: size.height))
layer.fillColor = color.cgColor
case .triangle:
let offsetY = size.height / 4
path.move(to: CGPoint(x: 0, y: size.height - offsetY))
path.addLine(to: CGPoint(x: size.width / 2, y: size.height / 2 - offsetY))
path.addLine(to: CGPoint(x: size.width, y: size.height - offsetY))
path.close()
layer.fillColor = color.cgColor
case .line:
path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: size.width, height: size.height),
cornerRadius: size.width / 2)
layer.fillColor = color.cgColor
case .pacman:
path.addArc(withCenter: CGPoint(x: size.width / 2, y: size.height / 2),
radius: size.width / 4,
startAngle: 0,
endAngle: CGFloat(2 * M_PI),
clockwise: true);
layer.fillColor = nil
layer.strokeColor = color.cgColor
layer.lineWidth = size.width / 2
}
layer.backgroundColor = nil
layer.path = path.cgPath
layer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
return layer
}
}
| apache-2.0 | 5f10b40f568d16b51b8300c961fe1a73 | 41.022556 | 104 | 0.494543 | 4.432197 | false | false | false | false |
epv44/EVTopTabBar | Example/EVTopTabBar/AppDelegate.swift | 1 | 2844 | //
// AppDelegate.swift
// EVTopTabBar
//
// Created by Eric Vennaro on 02/29/2016.
// Copyright (c) 2016 Eric Vennaro. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let mainViewController = ViewController(nibName: "ViewController", bundle: nil)
let navigationController = UINavigationController(rootViewController: mainViewController)
navigationController.navigationBar.isTranslucent = false
navigationController.navigationBar.barTintColor = UIColor.init(red: 81/255.0, green: 153/255.0, blue: 206/255.0, alpha: 1.0)
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Light", size: 20)!]
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | a9ccb895e68b32530b523dead66d82ae | 51.666667 | 285 | 0.750352 | 5.490347 | false | false | false | false |
AlexSeverinov/Kingfisher | Kingfisher/UIImage+Decode.swift | 25 | 2181 | //
// UIImage+Decode.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/7.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension UIImage {
func kf_decodedImage() -> UIImage? {
return self.kf_decodedImage(scale: self.scale)
}
func kf_decodedImage(#scale: CGFloat) -> UIImage? {
let imageRef = self.CGImage
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(nil, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo)
if let context = context {
let rect = CGRectMake(0, 0, CGFloat(CGImageGetWidth(imageRef)), CGFloat(CGImageGetHeight(imageRef)))
CGContextDrawImage(context, rect, imageRef)
let decompressedImageRef = CGBitmapContextCreateImage(context)
return UIImage(CGImage: decompressedImageRef, scale: scale, orientation: self.imageOrientation)
} else {
return nil
}
}
} | mit | 718dc5b586162b6920a6a00cd40bc152 | 44.458333 | 133 | 0.715727 | 4.610994 | false | false | false | false |
csontosgabor/Twitter_Post | Twitter_Post/PhotoViewController.swift | 1 | 24303 | //
// PhotoViewController.swift
// Twitter_Post
//
// Created by Gabor Csontos on 12/23/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
import UIKit
import Photos
protocol PhotoViewControllerDelegate: class {
//header button delegates
func openCameraView()
func openPhotoView()
func openLocationView()
func handlePostButton()
func openPhotoOrVideoEditor(_ mediaType: CustomAVAsset.MediaType?, assetIdentifier: String?)
}
class PhotoViewController: UIViewController {
//delegates
weak var delegate: PhotoViewControllerDelegate?
weak var postViewController: PostViewController?
//avAsset
var avAssetIdentifiers = [String]()
//selectedMediaType -> Fetching Camera Roll,Favoutires, Selfies or Videos
var selectedMediaType: MediaTypes = MediaTypes.CameraRoll {
didSet {
//by selectedMediaType
switch selectedMediaType {
case .CameraRoll: grabPhotosAndVideos(.smartAlbumUserLibrary)
case .Favourites: grabPhotosAndVideos(.smartAlbumFavorites)
case .Selfies: grabPhotosAndVideos(.smartAlbumSelfPortraits)
case .Videos: grabPhotosAndVideos(.smartAlbumVideos)
}
}
}
//titleView
var titleView: UIView!
//fullView
var fullView: UIView!
//navbarMenu
var dropDownTitle: DropdownTitleView!
var navigationBarMenu: DropDownMenu!
//closeButton
var closeButton: UIButton!
//closedView
var closedView: UIView!
var locationButton: UIButton!
var photoButton: UIButton!
var cameraButton: UIButton!
var postButton: UIButton!
//separatorView
var titleViewSeparator: UIView!
//emptyDataSet Strings
var emptyPhotos: Bool = false
var emptyImgName: String = "ic_enable_photo"
var emptyTitle: String = "Please enable your photo access"
var emptyDescription: String = "In iPhone settings tap \(Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String)\n and turn on Photo access."
var emptyBtnTitle: String = "Open settings."
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// MARK: Views .collectionView //
// CollectionView is responsible to show the photos and videos in its cells.
// After fetching AVAssets from phones memory it create an AVASset which is used to help indentified the mediaType for editing and adding to the CreatePostViewController
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
lazy var collectionView: UICollectionView = {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = 1
layout.minimumInteritemSpacing = 1
layout.sectionInset = UIEdgeInsetsMake(1, 0, 0, 0)
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(AVAssetCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.backgroundColor = UIColor.white
collectionView.showsVerticalScrollIndicator = true
//setup emptyDataSource
collectionView.emptyDataSetSource = self
collectionView.emptyDataSetDelegate = self
collectionView.isScrollEnabled = false
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
if let nc = self.navigationController as? FeedNavigationController {
nc.si_delegate = self
nc.fullScreenSwipeUp = true
//setup the NavigationBar headers
titleView = UIView(frame: CGRect(x: 0, y: 0, width: nc.navigationBar.frame.width, height: nc.navigationBar.frame.height))
titleView.backgroundColor = .white
setupHeaders()
nc.navigationBar.addSubview(titleView)
view.center = nc.navigationBar.center
}
setupCollectionView()
//fast check and grabPhotos from CameraRoll(default value)
PHPhotoLibrary.requestAuthorization() { status in
switch status {
case .authorized: self.grabPhotosAndVideos(.smartAlbumUserLibrary)
default:
//set the PhotoViewController's view on the bottom of the Screen if the PhotoAccess check failed
DispatchQueue.main.async {
if let parentVC = self.navigationController?.parent?.childViewControllers.first as? PostViewController {
parentVC.reactOnScroll()
self.collectionView.reloadEmptyDataSet()
}
}
}
}
//setupDropDownMenuTitle -> Last view, because of the collectionView
setupDropDownMenuTitle()
}
fileprivate func setupButtons(_ withImage: String, selector: Selector) -> UIButton {
let button = UIButton(type: .system)
let imageView = UIImageView()
imageView.image = UIImage(named: withImage)!.withRenderingMode(.alwaysTemplate)
imageView.tintColor = UIColor.lightGray
button.setImage(imageView.image, for: .normal)
button.tintColor = UIColor.lightGray
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: selector, for: .touchUpInside)
return button
}
func setupHeaders() {
setupClosedHeader()
setupFullHeader()
}
func setupClosedHeader(){
locationButton = setupButtons("ic_location", selector: #selector(handleLocationBtn))
photoButton = setupButtons("ic_photos", selector: #selector(handlePhotoBtn))
cameraButton = setupButtons("ic_photo_camera", selector: #selector(handleCameraBtn))
postButton = UIButton(type: .system)
postButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
postButton.setTitle("POST", for: UIControlState())
postButton.setTitle("POST", for: .disabled)
postButton.setTitleColor(.white, for: UIControlState())
postButton.setTitleColor(UIColor.lightGray, for: .disabled)
postButton.isEnabled = false
postButton.layer.cornerRadius = 4
postButton.layer.borderWidth = 1
postButton.translatesAutoresizingMaskIntoConstraints = false
postButton.addTarget(self, action: #selector(handlePostBtn), for: .touchUpInside)
//closedView x,y,w,h
closedView = UIView()
closedView.translatesAutoresizingMaskIntoConstraints = false
if !closedView.isDescendant(of: titleView) { titleView.addSubview(closedView) }
closedView.leftAnchor.constraint(equalTo: titleView.leftAnchor).isActive = true
closedView.widthAnchor.constraint(equalTo: titleView.widthAnchor).isActive = true
closedView.heightAnchor.constraint(equalTo: titleView.heightAnchor).isActive = true
closedView.backgroundColor = .white
//location btn x,y,w,h
if !locationButton.isDescendant(of: closedView) { closedView.addSubview(locationButton) }
locationButton.leftAnchor.constraint(equalTo: closedView.leftAnchor,constant: 12).isActive = true
locationButton.centerYAnchor.constraint(equalTo: closedView.centerYAnchor).isActive = true
locationButton.widthAnchor.constraint(equalToConstant: 20).isActive = true
locationButton.heightAnchor.constraint(equalToConstant: 20).isActive = true
//photo btn x,y,w,h
if !photoButton.isDescendant(of: closedView) { closedView.addSubview(photoButton) }
photoButton.leftAnchor.constraint(equalTo: locationButton.rightAnchor,constant: 22).isActive = true
photoButton.centerYAnchor.constraint(equalTo: closedView.centerYAnchor).isActive = true
photoButton.widthAnchor.constraint(equalToConstant: 20).isActive = true
photoButton.heightAnchor.constraint(equalToConstant: 20).isActive = true
//camera btn x,y,w.h
if !cameraButton.isDescendant(of: closedView) { closedView.addSubview(cameraButton) }
cameraButton.leftAnchor.constraint(equalTo: photoButton.rightAnchor,constant: 22).isActive = true
cameraButton.centerYAnchor.constraint(equalTo: closedView.centerYAnchor).isActive = true
cameraButton.widthAnchor.constraint(equalToConstant: 20).isActive = true
cameraButton.heightAnchor.constraint(equalToConstant: 20).isActive = true
//post btn x,y,w,h
if !postButton.isDescendant(of: closedView) { closedView.addSubview(postButton) }
postButton.leftAnchor.constraint(equalTo: closedView.rightAnchor,constant: -72).isActive = true
postButton.centerYAnchor.constraint(equalTo: closedView.centerYAnchor).isActive = true
postButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
postButton.heightAnchor.constraint(equalToConstant: 26).isActive = true
enableDisablePostButton(enable: false)
//titleViewSeparator x,y,w,h
titleViewSeparator = UIView()
titleViewSeparator.translatesAutoresizingMaskIntoConstraints = false
closedView.addSubview(titleViewSeparator)
titleViewSeparator.leftAnchor.constraint(equalTo: closedView.leftAnchor).isActive = true
titleViewSeparator.centerXAnchor.constraint(equalTo: closedView.centerXAnchor).isActive = true
titleViewSeparator.widthAnchor.constraint(equalTo: closedView.widthAnchor).isActive = true
titleViewSeparator.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
titleViewSeparator.topAnchor.constraint(equalTo: closedView.topAnchor).isActive = true
titleViewSeparator.backgroundColor = UIColor(white: 0.7, alpha: 0.8)
}
func setupFullHeader(){
//fullView x,y,w,h
fullView = UIView()
fullView.translatesAutoresizingMaskIntoConstraints = false
if !fullView.isDescendant(of: titleView) { titleView.addSubview(fullView) }
fullView.leftAnchor.constraint(equalTo: titleView.leftAnchor).isActive = true
fullView.widthAnchor.constraint(equalTo: titleView.widthAnchor).isActive = true
fullView.heightAnchor.constraint(equalTo: titleView.heightAnchor).isActive = true
fullView.backgroundColor = .white
fullView.alpha = 0
//closeHeaderView Dismiss btn x,y,w,h
closeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: titleView.frame.height))
closeButton.addTarget(self, action: #selector(closeView), for: .touchUpInside)
closeButton.setTitle("Close", for: .normal)
closeButton.setTitleColor(.black, for: .normal)
fullView.addSubview(closeButton)
//closeHeaderView Title x,y,w,h
//dropDownTitle x,y,w,h
dropDownTitle = DropdownTitleView()
dropDownTitle.titleLabel.textAlignment = .center
dropDownTitle.addTarget(self,action: #selector(self.willToggleNavigationBarMenu),for: .touchUpInside)
dropDownTitle.title = MediaTypes.CameraRoll.rawValue //default title
dropDownTitle.translatesAutoresizingMaskIntoConstraints = false
if !dropDownTitle.isDescendant(of: fullView) { fullView.addSubview(dropDownTitle) }
dropDownTitle.centerXAnchor.constraint(equalTo: fullView.centerXAnchor).isActive = true
dropDownTitle.centerYAnchor.constraint(equalTo: fullView.centerYAnchor).isActive = true
dropDownTitle.widthAnchor.constraint(equalToConstant: 120).isActive = true
dropDownTitle.heightAnchor.constraint(equalToConstant: 20).isActive = true
}
func setupDropDownMenuTitle(){
//DropDownMenuBar setup
prepareNavigationBarMenu(MediaTypes.CameraRoll.rawValue)
updateMenuContentOffsets()
navigationBarMenu.container = view
}
func setupCollectionView() {
//collectionView x,y,w,h
if !collectionView.isDescendant(of: self.view) { self.view.addSubview(collectionView) }
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
self.self.collectionView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
self.collectionView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.collectionView.isScrollEnabled = false
}
//fetch photos or videos by PHAssetCollectionSubtype , setted by DropDownTitleView
func grabPhotosAndVideos(_ subType: PHAssetCollectionSubtype){
self.avAssetIdentifiers.removeAll()
let fetchOptions = PHFetchOptions()
let fetchResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: subType, options: fetchOptions)
fetchResult.enumerateObjects({ (collection, start, stop) in
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let assets = PHAsset.fetchAssets(in: collection, options: fetchOptions)
assets.enumerateObjects({ (object, count, stop) in
self.avAssetIdentifiers.append(object.localIdentifier)
DispatchQueue.main.async {
//reload collectionView
self.collectionView.reloadData()
if self.avAssetIdentifiers.count == 0 {
//if avAsset count is nil -> There is no Photos to load
//change emptyView for making selfies
self.emptyPhotos = true
self.emptyImgName = "ic_selfie_dribbble"
self.emptyTitle = "You don't have any photos"
self.emptyDescription = "Let's give a try, and make some selfies about you."
self.emptyBtnTitle = "Open camera."
//Here you can make more specific messages based on PHAssetCollectionSubtype
switch subType {
case .smartAlbumVideos:
self.emptyImgName = "ic_selfie_dribbble"
self.emptyTitle = "You don't have any videos"
self.emptyDescription = "Capture some moments to share."
case .smartAlbumFavorites:
self.emptyImgName = "ic_selfie_dribbble"
self.emptyTitle = "No favoutires:("
self.emptyDescription = "In Photos you can easily make your fav album."
case .smartAlbumSelfPortraits:
break //etc
case .smartAlbumUserLibrary:
break //etc
default: break
}
self.collectionView.reloadEmptyDataSet()
//set the view on the bottom
}
}
})
if self.avAssetIdentifiers.count == 0 {
DispatchQueue.main.async {
if let parentVC = self.navigationController?.parent?.childViewControllers.first as? PostViewController {
parentVC.reactOnScroll()
}
}
}
})
}
//Color indicator if the location is setted or not
func locationIsSetted(bool: Bool) {
if bool {
self.locationButton.tintColor = self.view.tintColor
} else {
self.locationButton.tintColor = UIColor.lightGray
}
}
func closeView(){
//set the dropDownTitle to false to avoid UI crash
if self.dropDownTitle.isUp {
self.dropDownTitle.toggleMenu()
self.navigationBarMenu.hide(withAnimation: false)
}
//set scrollView to default
self.collectionView.isScrollEnabled = false
self.collectionView.setContentOffset(self.collectionView.contentOffset, animated: false)
DispatchQueue.main.async {
self.parent?.navigationController?.si_dismissModalView(toViewController: self.parent!, completion: {
if let nc = self.navigationController as? FeedNavigationController {
nc.si_delegate?.navigationControllerDidClosed?(navigationController: nc)
}
})
}
}
}
extension PhotoViewController: FeedNavigationControllerDelegate {
// MARK: - FeedNavigationControllerDelegate
func navigationControllerDidSpreadToEntire(navigationController: UINavigationController) {
print("spread to the entire")
//set scrollView's scrolling
self.collectionView.isScrollEnabled = true
UIView.animate(withDuration: 0.2,
delay: 0.0,
options: .curveEaseIn,
animations: {
self.fullView.alpha = 1
}, completion: nil)
}
func navigationControllerDidClosed(navigationController: UINavigationController) {
print("decreased on the view")
//set the dropDownTitle to false to avoid UI crash
if self.dropDownTitle.isUp {
self.dropDownTitle.toggleMenu()
self.navigationBarMenu.hide(withAnimation: false)
}
//set scrollView to default
self.collectionView.isScrollEnabled = false
self.collectionView.setContentOffset(self.collectionView.contentOffset, animated: false)
UIView.animate(withDuration: 0.2,
delay: 0.0,
options: .curveEaseIn,
animations: {
self.fullView.alpha = 0
}, completion: nil)
}
}
//MARK: - UIBUTTON FUNCTIONS
extension PhotoViewController {
func handleLocationBtn(_ sender: UIButton){
delegate?.openLocationView()
}
func handlePhotoBtn(_ sender: UIButton){
delegate?.openPhotoView()
}
func handleCameraBtn(_ sender: UIButton){
delegate?.openCameraView()
}
func handlePostBtn(_ sender: UIButton){
delegate?.handlePostButton()
}
//setting the PostButton color if post contains text or content
func enableDisablePostButton(enable: Bool){
if enable {
postButton.isEnabled = true
postButton.layer.borderColor = self.view.tintColor.cgColor
postButton.backgroundColor = self.view.tintColor
} else {
postButton.isEnabled = false
postButton.layer.borderColor = UIColor.lightGray.cgColor
postButton.backgroundColor = .clear
}
}
}
extension PhotoViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return avAssetIdentifiers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AVAssetCollectionViewCell
cell.assetID = self.avAssetIdentifiers[indexPath.row]
cell.tag = (indexPath as NSIndexPath).row
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! AVAssetCollectionViewCell
// recognize the assetType and send the localidentifier to open the VideoTrimmer of PhotoEditor
delegate?.openPhotoOrVideoEditor(cell.asset?.type, assetIdentifier: cell.asset?.identifier)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width / 3 - 1
return CGSize(width: width, height: width)
}
}
extension PhotoViewController: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
return true
}
func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
return UIImage(named: emptyImgName)
}
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
let attribs = [
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18),
NSForegroundColorAttributeName: UIColor.darkGray
]
return NSAttributedString(string: emptyTitle, attributes: attribs)
}
func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
let para = NSMutableParagraphStyle()
para.lineBreakMode = NSLineBreakMode.byWordWrapping
para.alignment = NSTextAlignment.center
let attribs = [
NSFontAttributeName: UIFont.systemFont(ofSize: 14),
NSForegroundColorAttributeName: UIColor.lightGray,
NSParagraphStyleAttributeName: para
]
return NSAttributedString(string: emptyDescription, attributes: attribs)
}
func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControlState) -> NSAttributedString! {
let attribs = [
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16),
NSForegroundColorAttributeName: view.tintColor
]
return NSAttributedString(string: emptyBtnTitle, attributes: attribs)
}
func emptyDataSetDidTapButton(_ scrollView: UIScrollView!) {
if !emptyPhotos {
getAccessForSettings()
} else {
//shot some new pics
openCameraView()
}
}
func openCameraView(){
self.delegate?.openCameraView()
}
func getAccessForSettings(){
//Open App's settings
openApplicationSettings()
}
}
| mit | 49e8bc15bda4fe9a5b6b4f20a3973a41 | 36.794712 | 175 | 0.624434 | 5.881413 | false | false | false | false |
iOkay/MiaoWuWu | Pods/Material/Sources/iOS/Snackbar.swift | 1 | 3925 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(SnackbarStatus)
public enum SnackbarStatus: Int {
case visible
case hidden
}
open class Snackbar: Bar {
/// A convenience property to set the titleLabel text.
open var text: String? {
get {
return textLabel.text
}
set(value) {
textLabel.text = value
layoutSubviews()
}
}
/// Text label.
public internal(set) lazy var textLabel = UILabel()
open override var intrinsicContentSize: CGSize {
return CGSize(width: width, height: 49)
}
/// The status of the snackbar.
open internal(set) var status = SnackbarStatus.hidden
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
/**
Since the subviews will be outside the bounds of this view,
we need to look at the subviews to see if we have a hit.
*/
guard !isHidden else {
return nil
}
for v in subviews {
let p = v.convert(point, from: self)
if v.bounds.contains(p) {
return v.hitTest(p, with: event)
}
}
return super.hitTest(point, with: event)
}
/// Reloads the view.
open override func reload() {
super.reload()
centerViews = [textLabel]
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
depthPreset = .none
interimSpacePreset = .interimSpace8
contentEdgeInsets.left = interimSpace
contentEdgeInsets.right = interimSpace
backgroundColor = Color.grey.darken3
clipsToBounds = false
prepareTextLabel()
}
/// Prepares the textLabel.
private func prepareTextLabel() {
textLabel.contentScaleFactor = Device.scale
textLabel.font = RobotoFont.medium(with: 14)
textLabel.textAlignment = .left
textLabel.textColor = Color.white
textLabel.numberOfLines = 0
}
}
| gpl-3.0 | e0b835c463d3f4ad0f287d3b92a52a83 | 33.734513 | 87 | 0.665732 | 4.851669 | false | false | false | false |
banDedo/BDModules | HarnessModules/AccountUser/AccountUserProvider.swift | 1 | 2249 | //
// AccountUserProvider.swift
// BDModules
//
// Created by Patrick Hogan on 2/8/15.
// Copyright (c) 2015 bandedo. All rights reserved.
//
import Foundation
import FXKeychain
private let kAccountUserProviderKey = "kAccountUserProviderKey"
public class AccountUserProvider: NSObject, OAuth2SessionManagerDelegate {
// MARK:- Injectable
public lazy var keychain = FXKeychain()
public lazy var modelFactory = ModelFactory()
// MARK:- Properties
private(set) public lazy var accountUser: AccountUser = {
var accountUser: AccountUser = AccountUser()
if let savedAccountUser = self.keychain.objectForKey(kAccountUserProviderKey) as? AccountUser {
if savedAccountUser.oAuth2Credential == nil {
self.keychain.setObject(nil, forKey: kAccountUserProviderKey)
} else {
accountUser.user = self.modelFactory.object(savedAccountUser.user!.dictionary) as? User
accountUser.oAuth2Credential = savedAccountUser.oAuth2Credential
}
}
return accountUser
}()
public var user: User! {
return accountUser.user!
}
public var oAuth2Credential: OAuth2Credential! {
return accountUser.oAuth2Credential!
}
// MARK:- OAuth2
public func bearerHeader() -> String? {
if let accessToken = accountUser.oAuth2Credential?.accessToken {
return "Bearer \(accessToken)"
} else {
return nil
}
}
// MARK:- Persistence
public func userPersistenceHandler() -> (User -> Void) {
return { user in
self.accountUser.user = user
self.keychain.setObject(self.accountUser, forKey: kAccountUserProviderKey)
}
}
public func logout() {
keychain.setObject(nil, forKey: kAccountUserProviderKey)
accountUser = AccountUser()
}
// MARK:- OAuth2SessionManagerDelegate
public func oAuth2SessionManager(oAuth2SessionManager: OAuth2SessionManager, didUpdateCredential credential: OAuth2Credential) {
accountUser.oAuth2Credential = credential
keychain.setObject(accountUser, forKey: kAccountUserProviderKey)
}
}
| apache-2.0 | 56340bcd19e8fea62e7e8f7466471ac6 | 28.207792 | 132 | 0.656292 | 4.646694 | false | false | false | false |
nicolastinkl/swift | ListerAProductivityAppBuiltinSwift/Lister/NewListDocumentController.swift | 1 | 3323 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Allows users to create a new list document with a name and preferred color.
*/
import UIKit
import ListerKit
// Provides the ability to send a delegate a message about newly created list info objects.
@class_protocol protocol NewListDocumentControllerDelegate {
func newListDocumentController(newListDocumentController: NewListDocumentController, didCreateDocumentWithListInfo listInfo: ListInfo)
}
class NewListDocumentController: UIViewController, UITextFieldDelegate {
// MARK: Properties
@IBOutlet var grayButton: UIButton
@IBOutlet var blueButton: UIButton
@IBOutlet var greenButton: UIButton
@IBOutlet var yellowButton: UIButton
@IBOutlet var orangeButton: UIButton
@IBOutlet var redButton: UIButton
@IBOutlet var saveButton: UIBarButtonItem
@IBOutlet var toolbar: UIToolbar
@IBOutlet var titleLabel: UILabel
weak var selectedButton: UIButton?
// Lets the delegate know about new list info objects that are created.
var delegate: NewListDocumentControllerDelegate?
var selectedColor = List.Color.Gray
var selectedTitle: String?
var fileURL: NSURL? {
if selectedTitle {
return ListCoordinator.sharedListCoordinator.documentURLForName(selectedTitle!)
}
return nil
}
// MARK: UITextFieldDelegate
func textFieldDidEndEditing(textField: UITextField) {
if ListCoordinator.sharedListCoordinator.isValidDocumentName(textField.text) {
saveButton.enabled = true
selectedTitle = textField.text
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: IBActions
@IBAction func pickColor(sender: UIButton) {
// Use the button's tag to determine the color.
selectedColor = List.Color.fromRaw(sender.tag)!
// If a button was previously selected, we need to clear out its previous border.
if let oldButton = selectedButton {
oldButton.layer.borderWidth = 0.0
}
sender.layer.borderWidth = 5.0
sender.layer.borderColor = UIColor.lightGrayColor().CGColor
selectedButton = sender
titleLabel.textColor = selectedColor.colorValue
toolbar.tintColor = selectedColor.colorValue
}
@IBAction func save(sender: AnyObject) {
let listInfo = ListInfo(provider: fileURL!)
listInfo.color = selectedColor
listInfo.createAndSaveWithCompletionHandler { success in
if success {
self.delegate?.newListDocumentController(self, didCreateDocumentWithListInfo: listInfo)
}
else {
// In your app, you should handle this error gracefully.
NSLog("Unable to save document to URL: \(self.fileURL!.absoluteString).")
abort()
}
}
dismissModalViewControllerAnimated(true)
}
@IBAction func cancel(sender: AnyObject) {
dismissModalViewControllerAnimated(true)
}
}
| mit | 015a16d2ef7596017d4834056de3f432 | 31.881188 | 138 | 0.663957 | 5.716007 | false | false | false | false |
ennioma/arek | code/Classes/Core/Utilities/ArekPopupData.swift | 1 | 2036 | //
// ArekPopupData.swift
// Arek
//
// Copyright (c) 2016 Ennio Masi
//
// 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 enum ArekPopupType {
case codeido
case native
}
public struct ArekPopupData {
var title: String!
var message: String!
var image: String!
var allowButtonTitle: String!
var denyButtonTitle: String!
var type: ArekPopupType!
var styling: ArekPopupStyle?
public init(title: String = "",
message: String = "",
image: String = "",
allowButtonTitle: String = "",
denyButtonTitle: String = "",
type: ArekPopupType = .codeido,
styling: ArekPopupStyle? = nil) {
self.title = title
self.message = message
self.image = image
self.allowButtonTitle = allowButtonTitle
self.denyButtonTitle = denyButtonTitle
self.type = type
self.styling = styling
}
}
| mit | 4e6a8ba254ad73d39966b009f553810d | 34.103448 | 81 | 0.675344 | 4.494481 | false | false | false | false |
RobinFalko/Ubergang | Examples/TweenApp/Pods/Ubergang/Ubergang/Ease/Expo.swift | 1 | 1589 | //
// Expo.swift
// Ubergang
//
// Created by Robin Frielingsdorf on 07/01/16.
// Copyright © 2016 Robin Falko. All rights reserved.
//
import Foundation
open class Expo: Ease {
/**
Expo ease in.
- Parameter t: The value to be mapped going from 0 to `d`
- Parameter b: The mapped start value
- Parameter c: The mapped end value
- Parameter d: The end value
- Returns: The mapped result
*/
open class func easeIn(t: Double, b: Double, c: Double, d: Double) -> Double {
return (t==0) ? b : c * pow(2, 10 * (t/d - 1)) + b
}
/**
Circ ease out.
- Parameter t: The value to be mapped going from 0 to `d`
- Parameter b: The mapped start value
- Parameter c: The mapped end value
- Parameter d: The end value
- Returns: The mapped result
*/
open class func easeOut(t: Double, b: Double, c: Double, d: Double) -> Double {
return (t==d) ? b+c : c * (-pow(2, -10 * t/d) + 1) + b
}
/**
Circ ease in out.
- Parameter t: The value to be mapped going from 0 to `d`
- Parameter b: The mapped start value
- Parameter c: The mapped end value
- Parameter d: The end value
- Returns: The mapped result
*/
open class func easeInOut(t: Double, b: Double, c: Double, d: Double) -> Double {
var t = t
if (t==0) { return b }
if (t==d) { return b+c }
t/=d/2
if ((t) < 1) { return c/2 * pow(2, 10 * (t - 1)) + b }
t-=1
return c/2 * (-pow(2, -10 * t) + 2) + b
}
}
| apache-2.0 | f32225d3952cd59a975af9d0ee34e092 | 26.859649 | 85 | 0.537783 | 3.400428 | false | false | false | false |
auth0/Lock.iOS-OSX | LockTests/Interactors/EnterpriseDomainInteractorSpec.swift | 2 | 8480 | // EnterpriseDomainInteractorSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.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 Quick
import Nimble
import OHHTTPStubs
import Auth0
@testable import Lock
class EnterpriseDomainInteractorSpec: QuickSpec {
override func spec() {
let authentication = MockAuthentication(clientId: clientId, domain: domain)
var authInteractor: Auth0OAuth2Interactor!
var credentials: Credentials?
var connections: OfflineConnections!
var enterprise: EnterpriseDomainInteractor!
var user: User!
beforeEach {
user = User()
connections = OfflineConnections()
connections.enterprise(name: "TestAD", domains: ["test.com"])
connections.enterprise(name: "validAD", domains: ["valid.com"])
credentials = nil
var dispatcher = ObserverStore()
dispatcher.onAuth = {credentials = $0}
authInteractor = Auth0OAuth2Interactor(authentication: authentication, dispatcher: dispatcher, options: LockOptions(), nativeHandlers: [:])
enterprise = EnterpriseDomainInteractor(connections: connections, user: user, authentication: authInteractor)
}
afterEach {
Auth0Stubs.cleanAll()
Auth0Stubs.failUnknown()
}
describe("init") {
it("should have an entperise object") {
expect(enterprise).toNot(beNil())
}
it("connection should be nil") {
expect(enterprise.connection).to(beNil())
}
context("connection with single enterprise conection") {
beforeEach {
connections = OfflineConnections()
connections.enterprise(name: "TestAD", domains: [])
enterprise = EnterpriseDomainInteractor(connections: connections, user: user, authentication: authInteractor)
}
it("connection should not default to single connection") {
expect(enterprise.connection).toNot(beNil())
}
}
}
describe("updateEmail") {
context("connection with no domain") {
beforeEach {
connections = OfflineConnections()
connections.enterprise(name: "TestAD", domains: [])
enterprise = EnterpriseDomainInteractor(connections: connections, user: user, authentication: authInteractor)
}
it("should raise no error but no connection provided") {
expect{ try enterprise.updateEmail("[email protected]") }.toNot(throwError())
expect(enterprise.connection).to(beNil())
}
}
context("connection with one domain") {
beforeEach {
connections = OfflineConnections()
connections.enterprise(name: "TestAD", domains: ["test.com"])
enterprise = EnterpriseDomainInteractor(connections: connections, user: user, authentication: authInteractor)
}
it("should match email domain") {
expect{ try enterprise.updateEmail("[email protected]") }.toNot(throwError())
expect(enterprise.email) == "[email protected]"
expect(enterprise.domain) == "test.com"
}
it("should match email domain and provide enteprise connection") {
try! enterprise.updateEmail("[email protected]")
expect(enterprise.connection?.name) == "TestAD"
}
it("should case-insensitively match email domain and provide enteprise connection") {
try! enterprise.updateEmail("[email protected]")
expect(enterprise.connection?.name) == "TestAD"
}
it("should not match connection with unknown domain") {
try! enterprise.updateEmail("[email protected]")
expect(enterprise.connection).to(beNil())
expect(enterprise.domain) == "domainnotmatched.com"
}
it("should raise error if email is nil") {
expect{ try enterprise.updateEmail(nil)}.to(throwError())
}
it("should not match a connection with nil email") {
expect{ try enterprise.updateEmail(nil)}.to(throwError())
expect(enterprise.connection).to(beNil())
}
}
context("connection with multiple domains") {
beforeEach {
connections = OfflineConnections()
connections.enterprise(name: "TestAD", domains: ["test.com", "pepe.com"])
enterprise = EnterpriseDomainInteractor(connections: connections, user: user, authentication: authInteractor)
}
it("should match first email domain and provide enteprise connection") {
try! enterprise.updateEmail("[email protected]")
expect(enterprise.connection?.name) == "TestAD"
}
it("should match second email domain and provide enteprise connection") {
try! enterprise.updateEmail("[email protected]")
expect(enterprise.connection?.name) == "TestAD"
}
}
}
describe("login") {
var error: OAuth2AuthenticatableError?
beforeEach {
error = nil
connections = OfflineConnections()
connections.enterprise(name: "TestAD", domains: ["test.com"])
enterprise = EnterpriseDomainInteractor(connections: connections, user: user, authentication: authInteractor)
}
it("should fail to launch on no valid connection") {
try! enterprise.updateEmail("[email protected]")
enterprise.login() { error = $0 }
expect(error).toEventually(equal(OAuth2AuthenticatableError.noConnectionAvailable))
}
it("should not yield error on success") {
authentication.webAuthResult = { return .success(result: mockCredentials()) }
try! enterprise.updateEmail("[email protected]")
enterprise.login() { error = $0 }
expect(error).toEventually(beNil())
}
it("should add login_hint to parameters") {
authentication.webAuthResult = { return .success(result: mockCredentials()) }
try! enterprise.updateEmail("[email protected]")
enterprise.login() { error = $0 }
expect(error).toEventually(beNil())
expect(authentication.webAuth?.parameters["login_hint"]) == "[email protected]"
}
it("should call credentials callback") {
let expected = mockCredentials()
authentication.webAuthResult = { return .success(result: expected) }
try! enterprise.updateEmail("[email protected]")
enterprise.login() { error = $0 }
expect(credentials).toEventually(equal(expected))
}
}
}
}
| mit | 69c7c140699323b893d16812481e3cd8 | 39.574163 | 151 | 0.585024 | 5.350158 | false | true | false | false |
cpmpercussion/microjam | chirpey/MicrojamTutorialCloudLoginViewController.swift | 1 | 2572 | //
// MicrojamTutorialCloudLoginViewController.swift
// microjam
//
// Created by Charles Martin on 31/3/18.
// Copyright © 2018 Charles Martin. All rights reserved.
//
import UIKit
class MicrojamTutorialCloudLoginViewController: UIViewController {
/// Link to the users' profile data.
let profile: PerformerProfile = UserProfile.shared.profile
/// View shown if user is not logged into iCloud.
@IBOutlet weak var noAccountView: UIView!
/// View shown if the user is logged in
@IBOutlet weak var loggedInView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
updateUI()
}
override func viewDidAppear(_ animated: Bool) {
updateUI()
}
/// updates the profile screen's fields according to the present UserProfile data.
func updateUI() {
// Display appropriate views if user is not logged in.
if UserProfile.shared.loggedIn {
noAccountView.isHidden = true
loggedInView.isHidden = false
} else {
noAccountView.isHidden = false
loggedInView.isHidden = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func skipTutorial(_ sender: Any) {
self.dismiss(animated: false, completion: nil)
UserDefaults.standard.set(true, forKey: SettingsKeys.tutorialCompleted)
}
/// Used by login button, opens Settings app so that user can log into iCloud.
@IBAction func logIn(_ sender: Any) {
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
| mit | adbe69240d2e58a752093647027682ec | 35.211268 | 181 | 0.691949 | 5.041176 | false | false | false | false |
aijaz/icw1502 | playgrounds/Week03.playground/Pages/Chapter4-Collections.xcplaygroundpage/Contents.swift | 1 | 1641 | //: [Previous](@previous)
var str = "Hello, playground"
let numbers = [0, 1, 10, 44]
numbers[2]
numbers[0]
numbers[3]
let strs = ["Aijaz", "Ansari"]
typealias GreetingFunction = (String)->String
/**
This creates a greeting function
- parameter salutation: A string that will be used to greet the person
- returns: a GreetingFunction
*/
func createGreetingFunctionWithSalutation(salutation: String)->GreetingFunction {
func greetingFunction(name: String) -> String {
let greeting = "\(salutation), \(name)!"
return greeting
}
return greetingFunction
}
/// This is an array of greeting functions
let greetings = [
createGreetingFunctionWithSalutation("Hello")
, createGreetingFunctionWithSalutation("As-salaamu alaikum")
, createGreetingFunctionWithSalutation("Hey there")
, createGreetingFunctionWithSalutation("Yo")
]
let helloSwiftProgrammer = greetings[0]("Swift Programmer")
let salutations = ["Hello", "Hi", "Hey there"]
let simplerGreetings = salutations.map(createGreetingFunctionWithSalutation)
simplerGreetings[0]("Aijaz")
simplerGreetings[1]("Aijaz")
simplerGreetings[2]("Aijaz")
var drinkSizes = Array(count: 3, repeatedValue: "Big Gulp")
drinkSizes[0] = "Small"
drinkSizes[1] = "Medium"
drinkSizes[2] = "Large"
drinkSizes.append("XLarge")
drinkSizes
drinkSizes.count
for index in 0 ..< drinkSizes.count {
print (drinkSizes[index])
}
for index in 0 ..< drinkSizes.count {
print ("\(index) \(drinkSizes[index])")
}
for size in drinkSizes {
print (size)
}
for (index, size) in drinkSizes.enumerate() {
print ("\(index): \(size)")
}
//: [Next](@next)
| mit | 8b0c0e84da425e210a67b53bfa475f49 | 20.88 | 81 | 0.706886 | 3.440252 | false | false | false | false |
VladasZ/iOSTools | Sources/iOS/DatePicker.swift | 1 | 5713 | //
// DatePicker.swift
// SwiftTools
//
// Created by Vladas Zakrevskis on 2/8/17.
// Copyright © 2017 VladasZ All rights reserved.
//
#if os(iOS)
import UIKit
fileprivate var _backgroundColor = UIColor.gray
fileprivate var _doneButtonTextAligment: UIControl.ContentHorizontalAlignment = .center
fileprivate var _onFinishPicking: (() -> ())?
public protocol DatePickerDelegate : AnyObject {
func datePickerDidBeginPicking()
func datePickerDidEndPicking()
}
public extension DatePickerDelegate {
func datePickerDidBeginPicking() { }
func datePickerDidEndPicking() { }
}
public class DatePicker : UIView {
//MARK: - Properties
private static var height: CGFloat = 215.0
private static var doneButtonHeight: CGFloat = 50
private static var doneButtonMargin: CGFloat = 24
public static var locale: Locale?
public static var doneButtonTitle: String?
public static var doneButtonFont: UIFont?
public static var doneButtonColor: UIColor?
private static var pickerView: UIDatePicker!
private static var picker: DatePicker!
private static var completion: ((Date) -> ())!
public static func setBackgroundColor(_ color: UIColor) { _backgroundColor = color }
public static func setDoneButtonTextAligment(_ aligment: UIControl.ContentHorizontalAlignment)
{ _doneButtonTextAligment = aligment }
private static var hasDoneButton: Bool { return doneButtonTitle != nil }
private(set) public static var isHidden: Bool = true
public static var date: Date = Date()
public static weak var delegate: DatePickerDelegate?
public static func onFinishPicking(_ action: @escaping () -> ()) {
_onFinishPicking = action
}
//MARK: - Initialization
init(frame: CGRect, hasDoneButton: Bool, configuration: ((UIDatePicker) -> ())? = nil) {
super.init(frame: frame)
DatePicker.pickerView
= UIDatePicker(frame:
CGRect(x: 0,
y: (DatePicker.hasDoneButton ? DatePicker.doneButtonHeight : 0),
width: frame.size.width,
height: frame.size.height - (DatePicker.hasDoneButton ? DatePicker.doneButtonHeight : 0)))
if let locale = DatePicker.locale { DatePicker.pickerView.locale = locale }
DatePicker.pickerView.backgroundColor = _backgroundColor
DatePicker.pickerView.date = DatePicker.date
backgroundColor = _backgroundColor
DatePicker.pickerView.datePickerMode = .date
configuration?(DatePicker.pickerView)
addSubview(DatePicker.pickerView)
if hasDoneButton {
let button = UIButton(frame: CGRect(x: DatePicker.doneButtonMargin,
y: 0,
width: frame.size.width - DatePicker.doneButtonMargin * 2,
height: DatePicker.doneButtonHeight))
button.setTitleColor(DatePicker.doneButtonColor ?? UIColor.black, for: .normal)
button.setTitle(DatePicker.doneButtonTitle, for: .normal)
if let font = DatePicker.doneButtonFont { button.titleLabel?.font = font }
button.contentHorizontalAlignment = _doneButtonTextAligment
addSubview(button)
button.addTarget(self, action: #selector(didPressDoneButton), for: .touchUpInside)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Appearance
public static func pick(_ configuration: ((UIDatePicker) -> ())? = nil, _ completion: @escaping (Date) -> ()) {
if !isHidden { return }
picker = createPicker(configuration)
self.completion = completion
DatePicker.pickerView.date = DatePicker.date
keyWindow.addSubview(picker)
picker.hide(false, nil)
isHidden = false
delegate?.datePickerDidBeginPicking()
}
public static func finish() {
if isHidden { return }
isHidden = true
completion(pickerView.date)
picker.hide(true)
delegate?.datePickerDidEndPicking()
}
//MARK: - UI
private static func createPicker(_ configuration: ((UIDatePicker) -> ())?) -> DatePicker {
return DatePicker(frame:CGRect(x: 0,
y: keyWindow.frame.size.height,
width: keyWindow.frame.size.width,
height: height + (hasDoneButton ? doneButtonHeight : 0)),
hasDoneButton: hasDoneButton,
configuration: configuration)
}
//MARK: - Animation
private func hide(_ hide:Bool, _ completion:((Bool) -> Void)? = nil) {
let screenHeight = keyWindow.frame.size.height
let newPosition =
hide ?
screenHeight :
screenHeight - (DatePicker.height + (DatePicker.hasDoneButton ? DatePicker.doneButtonHeight : 0))
UIView.animate(withDuration: 0.211,
animations: { self.frame.origin.y = newPosition },
completion: completion)
}
//MARK: - Actions
@objc private func didPressDoneButton() {
_onFinishPicking?()
DatePicker.finish()
}
}
#endif
| mit | 38492e9174650b7c6aa993efa6a387da | 32.209302 | 115 | 0.588761 | 5.466029 | false | false | false | false |
remirobert/Camembert | sources/Camembert.swift | 1 | 7325 |
//
// Camembert.swift
// SwiftSQL
//
// Created by Remi Robert on 28/08/14.
// Copyright (c) 2014 remirobert. All rights reserved.
//
import Foundation
typealias INTEGER = Int
typealias REAL = Float
typealias TEXT = String
typealias DATE_TIME = NSDate
typealias BIT = Bool
enum Operator {
case LargerThan, LargerOrEqual, SmallerThan,SmallerOrEqual, EqualsTo, IsNull, NotNull
}
enum OrderOperator{
case Ascending, Descending
}
enum Select {
case SelectAll(OrderOperator, String)
case CustomRequest(String)
case Limit(Int, OrderOperator, String)
case Between(Int, Int, OrderOperator, String)
case Where(String, Operator, Any, OrderOperator, String)
}
class DataAccess {
var dataAccess :COpaquePointer = nil
var nameDataBase: String? = nil
private var _dbpath: String? = nil;
var DbPath: String? {
get{
return self._dbpath;
}
set (value){
var isDir = ObjCBool(true)
if !NSFileManager.defaultManager().fileExistsAtPath(value!, isDirectory: &isDir){
do {
try NSFileManager.defaultManager().createDirectoryAtPath(value!, withIntermediateDirectories: true, attributes: nil)
}
catch {
print("DataAccess function raised an exception")
}
}
self._dbpath = value;
}
}
class var access :DataAccess {
struct Static {
static let instance : DataAccess = DataAccess()
}
return Static.instance
}
}
class Camembert {
class var Date_Time_Format:String {
get
{
return "yyyy'-'MM'-'dd hh':'mm':'ss'";
}
}
class func initDataBase(nameDatabase :String) -> Bool {
let documentDirectory :String = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true)[0] as String
let pathDatabase = documentDirectory + "/" + nameDatabase
let ret = sqlite3_open(pathDatabase.cStringUsingEncoding(NSUTF8StringEncoding)!,
&DataAccess.access.dataAccess)
if ret != SQLITE_OK {
return createDataBase(nameDatabase)
}
DataAccess.access.nameDataBase = nameDatabase
return true
}
class func initDataBase(databaseFolder: String, nameDatabase :String) -> Bool{
DataAccess.access.DbPath = databaseFolder;
let ret = sqlite3_open(databaseFolder.cStringUsingEncoding(NSUTF8StringEncoding)!,
&DataAccess.access.dataAccess)
if ret != SQLITE_OK {
return createDataBase(databaseFolder, nameDatabase: nameDatabase)
}
DataAccess.access.nameDataBase = nameDatabase
return true;
}
class func createDataBase(nameDatabase: String) -> Bool {
let documentDirectory :String = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true)[0] as String
let pathDatabase = documentDirectory + "/" + nameDatabase
if sqlite3_open_v2(pathDatabase.cStringUsingEncoding(NSUTF8StringEncoding)!,
&DataAccess.access.dataAccess, (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE), nil) != SQLITE_OK {
DataAccess.access.dataAccess = nil
return false
}
DataAccess.access.nameDataBase = nameDatabase
return true
}
class func createDataBase(databaseFolder: String, nameDatabase: String) -> Bool {
if DataAccess.access.DbPath == nil {
DataAccess.access.DbPath = databaseFolder;
}
if sqlite3_open_v2((databaseFolder + "/" + nameDatabase).cStringUsingEncoding(NSUTF8StringEncoding)!,
&DataAccess.access.dataAccess, (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE), nil) != SQLITE_OK {
DataAccess.access.dataAccess = nil
return false
}
DataAccess.access.nameDataBase = nameDatabase
return true
}
class func closeDataBase() -> Bool {
if sqlite3_close(DataAccess.access.dataAccess) == SQLITE_OK {
DataAccess.access.dataAccess = nil
return true
}
DataAccess.access.dataAccess = nil
return false
}
func getObjectsWithQuery(query :String, table :String) -> [AnyObject]! {
var ptrRequest :COpaquePointer = nil
var objects :Array<AnyObject> = []
if sqlite3_prepare_v2(DataAccess.access.dataAccess,
query.cStringUsingEncoding(NSUTF8StringEncoding)!, -1, &ptrRequest, nil) != SQLITE_OK {
sqlite3_finalize(ptrRequest);
return nil
}
while (sqlite3_step(ptrRequest) == SQLITE_ROW) {
let currentObject :AnyObject! = camembertCreateObject(table) as AnyObject
(currentObject as! CamembertModel).setId(Int(sqlite3_column_int(ptrRequest, 0)))
for var index = 1; index < Int(sqlite3_column_count(ptrRequest)); index++ {
let columName :String = NSString(CString: sqlite3_column_name(ptrRequest,
CInt(index)), encoding: NSUTF8StringEncoding)! as String
switch sqlite3_column_type(ptrRequest, CInt(index)) {
case SQLITE_INTEGER:
currentObject.setValue((Int(sqlite3_column_int(ptrRequest,
CInt(index))) as AnyObject), forKey: columName)
case SQLITE_FLOAT:
currentObject.setValue((Float(sqlite3_column_double(ptrRequest,
CInt(index))) as AnyObject), forKey: columName)
case SQLITE_TEXT:
let stringValue = String.fromCString(UnsafePointer<CChar>(sqlite3_column_text(ptrRequest, CInt(index))))
currentObject.setValue(stringValue, forKey: columName)
default: Void()
}
}
objects.append(currentObject)
}
sqlite3_finalize(ptrRequest);
return objects
}
class func execQuery(query :String) -> COpaquePointer {
var ptrRequest :COpaquePointer = nil
if sqlite3_prepare_v2(DataAccess.access.dataAccess,
query.cStringUsingEncoding(NSUTF8StringEncoding)!, -1, &ptrRequest, nil) != SQLITE_OK {
sqlite3_finalize(ptrRequest);
return nil
}
sqlite3_finalize(ptrRequest);
return ptrRequest
}
class func getListTable() -> [String] {
var tables :[String] = []
var ptrRequest :COpaquePointer = nil
let requestListTables :String = "SELECT name FROM sqlite_master WHERE type='table';"
if sqlite3_prepare_v2(DataAccess.access.dataAccess,
requestListTables.cStringUsingEncoding(NSUTF8StringEncoding)!, -1, &ptrRequest, nil) != SQLITE_OK {
sqlite3_finalize(ptrRequest);
return tables
}
while sqlite3_step(ptrRequest) == SQLITE_ROW {
tables.append(String.fromCString(UnsafePointer<CChar>(sqlite3_column_text(ptrRequest, 0)))!)
}
sqlite3_finalize(ptrRequest);
return tables
}
}
| mit | 92e3160dce98995c5f8eb6e021c87cae | 34.558252 | 136 | 0.605734 | 4.750324 | false | false | false | false |
xwu/swift | test/Distributed/Runtime/distributed_actor_deinit.swift | 1 | 4717 | // RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-distributed -parse-as-library) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: distributed
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
// FIXME(distributed): Distributed actors currently have some issues on windows, isRemote always returns false. rdar://82593574
// UNSUPPORTED: windows
import _Distributed
@available(SwiftStdlib 5.5, *)
actor A {}
@available(SwiftStdlib 5.5, *)
distributed actor DA {
init(transport: ActorTransport) {}
}
@available(SwiftStdlib 5.5, *)
distributed actor DA_userDefined {
init(transport: ActorTransport) {}
deinit {}
}
@available(SwiftStdlib 5.5, *)
distributed actor DA_userDefined2 {
init(transport: ActorTransport) {}
deinit {
print("Deinitializing \(self.id)")
return
}
}
@available(SwiftStdlib 5.5, *)
distributed actor DA_state {
var name = "Hello"
var age = 42
init(transport: ActorTransport) {}
deinit {
print("Deinitializing \(self.id)")
return
}
}
// ==== Fake Transport ---------------------------------------------------------
@available(SwiftStdlib 5.5, *)
struct ActorAddress: ActorIdentity {
let address: String
init(parse address : String) {
self.address = address
}
}
@available(SwiftStdlib 5.5, *)
final class FakeTransport: @unchecked Sendable, ActorTransport {
var n = 0
func decodeIdentity(from decoder: Decoder) throws -> AnyActorIdentity {
print("decode identity from:\(decoder)")
fatalError("not implemented \(#function)")
}
func resolve<Act>(_ identity: AnyActorIdentity, as actorType: Act.Type) throws -> Act?
where Act: DistributedActor {
print("resolve type:\(actorType), address:\(identity)")
return nil
}
func assignIdentity<Act>(_ actorType: Act.Type) -> AnyActorIdentity
where Act: DistributedActor {
n += 1
let address = ActorAddress(parse: "addr-\(n)")
print("assign type:\(actorType), address:\(address)")
return .init(address)
}
public func actorReady<Act>(_ actor: Act) where Act: DistributedActor {
print("ready actor:\(actor), address:\(actor.id)")
}
func resignIdentity(_ identity: AnyActorIdentity) {
print("resign address:\(identity)")
}
}
// ==== Execute ----------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
func test() {
let transport = FakeTransport()
// no lifecycle things make sense for a normal actor, double check we didn't emit them
print("before A")
_ = A()
print("after A")
// CHECK: before A
// CHECK: after A
_ = { () -> DA in
DA(transport: transport)
}()
// CHECK: assign type:DA, address:[[ADDRESS:.*]]
// CHECK: ready actor:main.DA, address:AnyActorIdentity(ActorAddress(address: "[[ADDR1:addr-[0-9]]]"))
// CHECK: resign address:AnyActorIdentity(ActorAddress(address: "[[ADDR1]]"))
_ = { () -> DA_userDefined in
DA_userDefined(transport: transport)
}()
// CHECK: assign type:DA_userDefined, address:[[ADDRESS:.*]]
// CHECK: ready actor:main.DA_userDefined, address:AnyActorIdentity(ActorAddress(address: "[[ADDR2:addr-[0-9]]]"))
// CHECK: resign address:AnyActorIdentity(ActorAddress(address: "[[ADDR2]]"))
// resign must happen as the _last thing_ after user-deinit completed
_ = { () -> DA_userDefined2 in
DA_userDefined2(transport: transport)
}()
// CHECK: assign type:DA_userDefined2, address:[[ADDRESS:.*]]
// CHECK: ready actor:main.DA_userDefined2, address:AnyActorIdentity(ActorAddress(address: "[[ADDR3:addr-[0-9]]]"))
// CHECK: Deinitializing AnyActorIdentity(ActorAddress(address: "[[ADDR3]]"))
// CHECK-NEXT: resign address:AnyActorIdentity(ActorAddress(address: "[[ADDR3]]"))
// resign must happen as the _last thing_ after user-deinit completed
_ = { () -> DA_state in
DA_state(transport: transport)
}()
// CHECK: assign type:DA_state, address:[[ADDRESS:.*]]
// CHECK: ready actor:main.DA_state, address:AnyActorIdentity(ActorAddress(address: "[[ADDR4:addr-[0-9]]]"))
// CHECK: Deinitializing AnyActorIdentity(ActorAddress(address: "[[ADDR4]]"))
// CHECK-NEXT: resign address:AnyActorIdentity(ActorAddress(address: "[[ADDR4]]"))
// a remote actor should not resign it's address, it was never "assigned" it
let address = ActorAddress(parse: "remote-1")
_ = { () -> DA_userDefined2 in
try! DA_userDefined2.resolve(.init(address), using: transport)
}()
// CHECK-NEXT: resolve type:DA_userDefined2, address:AnyActorIdentity(ActorAddress(address: "[[ADDR5:remote-1]]"))
// CHECK-NEXT: Deinitializing
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
test()
}
}
| apache-2.0 | 16b7c6aa82a6468b693a2237f5d6c261 | 29.432258 | 127 | 0.665889 | 3.904801 | false | false | false | false |
AndreMuis/FiziksFunhouse | FiziksFunhouse/Views/FFHMainViewController.swift | 1 | 709 | //
// FFHMainViewController.swift
// FiziksFunhouse
//
// Created by Andre Muis on 5/4/16.
// Copyright © 2016 Andre Muis. All rights reserved.
//
import UIKit
class FFHMainViewController: UIViewController
{
let simulationEngine: FFHSimulationEngine = FFHSimulationEngine()
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if let viewController = segue.destination as? FFHControlsViewController
{
viewController.simulationEngine = self.simulationEngine
}
else if let viewController = segue.destination as? FFHSceneViewController
{
viewController.simulationEngine = self.simulationEngine
}
}
}
| mit | 4c3515deeaf336ba1863e41bf4d9b965 | 26.230769 | 81 | 0.693503 | 4.567742 | false | false | false | false |
HugoBoscDucros/HBAutocomplete | AutocompleteTestProject/AutocompleteDataSources/PlaceAutocompleteDataSource.swift | 1 | 1294 | //
// AddressAutocompleteDataSource.swift
// AutocompleteTestProject
//
// Created by Hugo Bosc-Ducros on 24/06/2019.
// Copyright © 2019 Hugo Bosc-Ducros. All rights reserved.
//
import Foundation
import HBAutocomplete
import MapKit
class PlaceAutocompleteDataSource: HBAutocompleteDataSource {
func getSuggestions(autocomplete: HBAutocomplete, input: String, completionHandler: @escaping ([String], [String : Any]?, [String : UIImage]?) -> Void) {
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = input
let search = MKLocalSearch(request: searchRequest)
search.start { response, error in
guard let response = response else {
print("Error: \(error?.localizedDescription ?? "Unknown error").")
completionHandler([String](),nil,nil)
return
}
var suggestions = [String]()
var mapItemDictionary = [String:MKMapItem]()
for item in response.mapItems {
if let name = item.name {
mapItemDictionary[name] = item
suggestions.append(name)
}
}
completionHandler(suggestions,mapItemDictionary,nil)
}
}
}
| mit | fd5e6046b07a2da21be051f311f31a67 | 33.026316 | 157 | 0.613302 | 4.935115 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Cells/MediaQuotaCell.swift | 2 | 1763 | import Foundation
import UIKit
import WordPressShared
// MARK: - View Model
@objc class MediaQuotaCell: WPTableViewCell {
@objc static let height: Float = 66.0
@objc static let defaultReuseIdentifier = "MediaQuotaCell"
@objc static let nib: UINib = {
let nib = UINib(nibName: "MediaQuotaCell", bundle: Bundle(for: MediaQuotaCell.self))
return nib
}()
// MARK: - Public interface
@objc var value: String? {
get {
return valueLabel.text
}
set {
valueLabel.text = newValue
}
}
@objc var title: String? {
get {
return titleLabel.text
}
set {
titleLabel.text = newValue
}
}
@objc var percentage: NSNumber? {
get {
return NSNumber(value: progressView.progress)
}
set {
if let nonNilValue = newValue {
progressView.progress = nonNilValue.floatValue
} else {
progressView.progress = 0
}
}
}
// MARK: - Private properties
@objc func customizeAppearance() {
titleLabel.font = WPStyleGuide.tableviewTextFont()
titleLabel.textColor = .neutral(.shade70)
valueLabel.font = WPStyleGuide.tableviewSubtitleFont()
valueLabel.textColor = .neutral(.shade30)
progressView.progressTintColor = .primary
progressView.trackTintColor = .neutral(.shade30)
}
// MARK: - UIKit bindings
override func awakeFromNib() {
super.awakeFromNib()
customizeAppearance()
}
@objc @IBOutlet var titleLabel: UILabel!
@objc @IBOutlet var valueLabel: UILabel!
@objc @IBOutlet var progressView: UIProgressView!
}
| gpl-2.0 | 4544c6205d1f276e806d904db2f42ce3 | 24.185714 | 92 | 0.591605 | 4.910864 | false | false | false | false |
Off-Piste/Trolley.io | Trolley/Core/Root/Parser.swift | 2 | 2395 | //
// Parser.swift
// Pods
//
// Created by Harry Wright on 24.05.17.
//
//
import Foundation
struct ParserError {
enum error: Error {
case dataIsNil
case pathCannotBeFound(forResource: String)
var localizedDescription: String {
switch self {
case .dataIsNil :
return "The data cannot be read by the file manager"
case .pathCannotBeFound(let resource) :
return "The path for the resource: \(resource) cannot be found"
}
}
}
}
typealias PError = ParserError.error
typealias PlistFormat = PropertyListSerialization.PropertyListFormat
class Parser {
var items = [String : Any]()
convenience init(forResouceName name: String, ofType type: String) throws {
try self.init(bundle: Bundle.main, name: name, type: type)
}
/* Testable */
init(bundle: Bundle, name: String, type: String) throws {
guard let bundle = bundle.path(forResource: name, ofType: type) else {
throw PError.pathCannotBeFound(forResource: name)
}
let plistParser = try PLISTParser(contentsOfURL: bundle)
self.items = plistParser.plist
}
}
class PLISTParser {
private(set) var plist = [String: AnyObject]() {
didSet {
self.headers = headers(fromXML: self.plist)
}
}
private(set) var headers: [String] = []
private init(xmlData: Data?, format: PlistFormat) throws {
if let data = xmlData {
var format = format
plist = try PropertyListSerialization
.propertyList(
from: data,
options: .mutableContainersAndLeaves,
format: &format) as! [String : AnyObject]
} else {
throw PError.dataIsNil
}
}
public convenience init(contentsOfURL url: String) throws {
let propertyListForamt: PlistFormat = .xml
let plistXML = FileManager.default.contents(atPath: url)
try self.init(xmlData: plistXML, format: propertyListForamt)
}
private func headers(fromXML xml: [String : AnyObject]) -> [String] {
var lines = [String]()
for (index, _) in self.plist {
lines.append(index)
}
return lines
}
}
| mit | 223e9d9443f82bbef4c01733ed7f7dfd | 25.910112 | 79 | 0.574948 | 4.623552 | false | false | false | false |
WeirdMath/SwiftyHaru | Sources/SwiftyHaru/Grid/Grid.Serifs.swift | 1 | 2321 | //
// Grid.Serifs.swift
// SwiftyHaru
//
// Created by Sergej Jaskiewicz on 04.11.16.
//
//
extension Grid {
/// Encapsulates the parameters of the top, bottom, left and right serifs of the grid.
public struct Serifs: Hashable {
/// Default set, where all the serif parameters are set to their `.default`.
public static let `default` = Serifs()
/// The serifs for vertical lines at the top of the grid.
public var top: SerifParameters?
/// The serifs for vertical lines at the bottom of the grid.
public var bottom: SerifParameters?
/// The serifs for horizontal lines on the left of the grid.
public var left: SerifParameters?
/// The serifs for horizontal lines on the right of the grid.
public var right: SerifParameters?
/// Creates a new set of the serif parameters for each kind of serifs.
///
/// Each parameter's default value is `SerifParameters.default`.
///
/// - parameter top: The parameters of the serifs for vertical
/// lines at the top of the grid. If specified `nil`, no such serifs
/// will be drawn.
/// - parameter bottom: The parameters of the serifs for vertical
/// lines at the bottom of the grid. If specified `nil`, no such serifs
/// will be drawn.
/// - parameter left: The parameters of the serifs for horizontal
/// lines on the left of the grid. If specified `nil`, no such serifs
/// will be drawn.
/// - parameter right: The parameters of the serifs for horizontal
/// lines on the right of the grid. If specified `nil`, no such serifs
/// will be drawn.
public init(top: SerifParameters? = .default,
bottom: SerifParameters? = .default,
left: SerifParameters? = .default,
right: SerifParameters? = .default) {
self.top = top
self.bottom = bottom
self.left = left
self.right = right
}
}
}
| mit | c28d60025da442a5e6e086838018b1db | 40.446429 | 100 | 0.538561 | 4.970021 | false | false | false | false |
Miridescen/M_365key | 365KEY_swift/365KEY_swift/tool/NSURLConnection+extension.swift | 1 | 35803 | //
// NSURLConnection+extension.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/10/31.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
extension NSURLConnection{
static let connection: NSURLConnection = {
let connectionShare = NSURLConnection()
return connectionShare
}()
// MARK: 个人中心我的留言提交评论按钮点击发送的请求
func usercenterMymessageClickSubmitRequest(messageStr: String, id: Int64, model: String, pid: Int64, completion: @escaping((_ isSuccess: Bool)->())) {
let userShard = SKUserShared.getUserSharedNeedPresentLoginView()
if userShard != nil {
let urlStr = "http://www.365key.com/Produce/addcommit_mobile"
var parames = [String: AnyObject]()
parames["uid"] = userShard?.uid as AnyObject
parames["model"] = model as AnyObject
parames["message"] = messageStr as AnyObject
parames["id"] = id as AnyObject
parames["pid"] = pid as AnyObject
connectionRequest(urlString: urlStr, paramers: parames, completion: { (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
guard let jsondata = jsonData,
let code = jsondata["code"],
let code1 = code else {
return
}
if code1 as! Int == 0 {
completion(true)
} else {
completion(false)
}
} else {
completion(false)
}
})
}
}
// MARK: 第三方登录发送的请求
func thirdPartLoginRequest(params: [String: AnyObject], completion: @escaping(_ isSuccess: Bool)->()) {
let urlStr = "http://www.365key.com/User/third_parth_login"
connectionRequest(urlString: urlStr, paramers: params) { (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject?]
print("jsonData == \(jsonData)")
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false)
return
}
if code2 as! Int == 0 {
let uid = jsonData?["uid"]
guard let uid1 = uid,
let uid2 = uid1 else {
completion(false)
return
}
var uidInt: Int
if (params["from"] as! String) == "qq" { // 如果不做判断QQ登录返回的数据类型不一样会崩溃
uidInt = Int(uid2 as! String)!
} else {
uidInt = uid2 as! Int
}
let userShared = SKUserShared()
userShared.uid = NSNumber(value: uidInt)
SKUserShared.saveUserShared(shared: userShared)
self.userInfoRequest(compeltion: { (bool) in
bool ? completion(true) : completion(false)
})
} else {
completion(false)
}
}
}
}
// MARK: 获取用户中心我的留言数据的请求
func userCenterMyMessageRequest(completion: @escaping(_ isSuccess: Bool, _ dataArray: [SKMyMessageModel]?)->()) {
let userShard = SKUserShared.getUserSharedNeedPresentLoginView()
if userShard != nil {
let urlStr = "http://www.365key.com/User/get_center_message"
var params = [String: AnyObject]()
params["uid"] = userShard?.uid as AnyObject
connectionRequest(urlString: urlStr, paramers: params, completion: { (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let dataArray = NSArray.yy_modelArray(with: SKMyMessageModel.self, json: jsonData?["list"] as Any)
if (dataArray?.count)! > 0 {
completion(true, dataArray as! [SKMyMessageModel]?)
} else {
completion(false, nil)
}
} else {
completion(false, nil)
}
})
}
}
// MARK: 用户中心我的关注产品取消关注按钮点击发送的请求
func userCenterMyFocusProductDfaultFocusRequest(params: [String: AnyObject], completion: @escaping(_ isSuccess: Bool)->()) {
let urlStr = "http://www.365key.com/Right/cancel_follow_modile"
connectionRequest(urlString: urlStr, paramers: params) { (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false)
return
}
if code2 as! Int == 0 {
completion(true)
} else {
completion(false)
}
} else {
completion(false)
}
}
}
// MARK: 用户中心我的关注数据请求
func userCenterMyFocusDataRqeuest(completion: @escaping(_ isSuccess: Bool, _ data: [SKProductListModel]?)->()) {
let userShard = SKUserShared.getUserSharedNeedPresentLoginView()
if userShard != nil {
let urlStr = "http://www.365key.com/User/personal_center"
var params = [String: AnyObject]()
params["id"] = userShard?.uid as AnyObject
params["type"] = "IOS" as AnyObject
connectionRequest(urlString: urlStr, paramers: params, completion: { (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let productDataArray = NSArray.yy_modelArray(with: SKProductListModel.self, json: jsonData?["pro_list"] as Any)
// let peopleDataArray = jsonData?["entre_list"]
if (productDataArray?.count)! > 0 {
completion(true, productDataArray as! [SKProductListModel]?)
} else {
completion(false, nil)
}
} else {
completion(false, nil)
}
})
}
}
// MARK: 产品详情页提交评论按钮点击发送的请求
func produceDetailClickSubmitRequest(messageStr: String, id: Int64, model: String, completion: @escaping((_ isSuccess: Bool)->())) {
let userShard = SKUserShared.getUserSharedNeedPresentLoginView()
if userShard != nil {
let urlStr = "http://www.365key.com/Produce/addcommit_mobile"
var parames = [String: AnyObject]()
parames["uid"] = userShard?.uid as AnyObject
parames["model"] = model as AnyObject
parames["message"] = messageStr as AnyObject
parames["id"] = id as AnyObject
connectionRequest(urlString: urlStr, paramers: parames, completion: { (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
guard let jsondata = jsonData,
let code = jsondata["code"],
let code1 = code else {
return
}
if code1 as! Int == 0 {
completion(true)
} else {
completion(false)
}
} else {
completion(false)
}
})
}
}
// MARK: 产品详情也点击相关评论按钮发送的请求
func productsCommentsRequest(params: [String: AnyObject], completion: @escaping(_ isSuccess: Bool, _ jsonData: [SKCommentsModel]?)->()) {
let urlStr = "http://www.365key.com/Produce/get_commit_by_id"
connectionRequest(urlString: urlStr, paramers: params) { (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [String: AnyObject?] ?? [:]
let commitlistArray = NSArray.yy_modelArray(with: SKCommentsModel.self, json: jsonData?["commitlist"] as Any) ?? []
if commitlistArray.count > 0 {
completion(true, commitlistArray as? [SKCommentsModel])
} else {
completion(false, nil)
}
} else {
completion(false, nil)
}
}
}
// MARK: 行业资讯页搜索按钮点击后发送的请求
func searchNewsRequest(params:[String: AnyObject]?,completion:@escaping (_ isSuccess: Bool, _ data: [[String: [SKNewsListModel]]]?)->()) {
let urlStr = "http://www.365key.com/Event/get_event_list_mobile"
connectionRequest(with: .POST, urlString: urlStr, paramers: params) { (bool, Data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: Data as! Data, options: []) as? [String: AnyObject?] ?? [:]
let newsListDataArray = NSArray.yy_modelArray(with: SKNewsListModel.self, json: jsonData?["eventlist"] as Any) ?? []
if newsListDataArray.count > 0 {
var dateArray = [String?]()
var dTime: String?
for i in 0..<newsListDataArray.count {
let newsModel = newsListDataArray[i] as? SKNewsListModel
if i == 0{
dTime = newsModel?.showTime
dateArray.append(dTime)
} else {
if dTime != newsModel?.showTime{
dTime = newsModel?.showTime
dateArray.append(dTime)
}
}
}
var allDataArray = [[String: [SKNewsListModel]]]()
for i in 0..<dateArray.count {
let showTime = dateArray[i]
var modelArray = [SKNewsListModel]()
for model in newsListDataArray {
if (model as! SKNewsListModel).showTime == showTime {
modelArray.append(model as! SKNewsListModel)
}
}
let modelDic: [String: [SKNewsListModel]] = [showTime!: modelArray]
allDataArray.append(modelDic)
}
completion(true, allDataArray)
} else{
completion(false, nil)
}
} else {
completion (false, nil)
}
}
}
// MARK: 产品页搜索按钮点击后发送的请求
func searchProdecdRequest(params:[String: AnyObject]?,completion:@escaping (_ isSuccess: Bool, _ data: [[String: [SKProductListModel]]]?)->()) {
let urlStr = "http://www.365key.com/Produce/get_product_list"
connectionRequest(with: .POST, urlString: urlStr, paramers: params) { (bool, Data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: Data as! Data, options: []) as? [String: AnyObject?] ?? [:]
let productListDataArray = NSArray.yy_modelArray(with: SKProductListModel.self, json: jsonData?["prolist"] as Any) ?? []
if productListDataArray.count > 0 {
var dateArray = [String?]()
var dTime: String?
for i in 0..<productListDataArray.count {
let ProductModel = productListDataArray[i] as? SKProductListModel
if i == 0{
dTime = ProductModel?.showTime
dateArray.append(dTime)
} else {
if dTime != ProductModel?.showTime{
dTime = ProductModel?.showTime
dateArray.append(dTime)
}
}
}
var allDataArray = [[String: [SKProductListModel]]]()
for i in 0..<dateArray.count {
let showTime = dateArray[i]
var modelArray = [SKProductListModel]()
for model in productListDataArray {
if (model as! SKProductListModel).showTime == showTime {
modelArray.append(model as! SKProductListModel)
}
}
let modelDic: [String: [SKProductListModel]] = [showTime!: modelArray]
allDataArray.append(modelDic)
}
completion(true, allDataArray)
} else{
completion(false, nil)
}
} else {
completion (false, nil)
}
}
}
// MARK: 邮箱注册的用户在进行添加新产品的时候要完善手机信息,这个时候发送的请求
func perfectUserInfoRequest(with phoneNumber: String, captcha: String, password: String, uid: NSNumber,completion:@escaping(_ isSuccess: Bool, _ codeNum: Int?)->()) {
let urlStr = "http://www.365key.com/User/reg"
var params = [String: AnyObject]()
params["phone"] = phoneNumber as AnyObject?
params["checkcode"] = captcha as AnyObject?
params["password"] = password as AnyObject?
params["uid"] = uid as AnyObject?
connectionRequest(urlString: urlStr, paramers: params){ (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false, nil)
return
}
completion(true, code2 as? Int)
} else {
completion(false, nil)
}
}
}
// MARK: 帮助界面用户信息反馈提交
func helpVCUploadUserFeedback(feedbackStr: String, completion:@escaping(_ isSuccess: Bool)->()) {
let userShared = SKUserShared.getUserSharedNeedPresentLoginView()
if userShared != nil {
let urlStr = "http://www.365key.com/Feedback/add_feedback"
var params = [String: AnyObject]()
params["message"] = feedbackStr as AnyObject
params["uid"] = userShared?.uid as AnyObject
connectionRequest(urlString: urlStr, paramers: params){ (bool, anyData) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: anyData as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false)
return
}
if code2 as! Int == 0 {
completion(true)
} else {
completion(false)
}
} else {
completion(false)
}
}
} else {
SKProgressHUD.setErrorString(with: "请登录后提交反馈")
}
}
// MARK: 用户信息页面修改用户信息请求
func chengeUserInfo(params: [String: AnyObject], completion:@escaping(_ isSuccess: Bool, _ codeNum: Int?)->()) {
let urlStr = "http://www.365key.com/User/modified"
connectionRequest(urlString: urlStr, paramers: params){ (bool, Data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: Data as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false, nil)
return
}
completion(true, code2 as? Int)
} else {
completion(false, nil)
}
}
}
// MARK: 新闻详情获取请求
func newsDetailDataRequest(newsID: Int64, completion: @escaping(_ isSuccess: Bool, _ newsDetailModel: SKNewsDetailModel?)->()) {
let urlStr = "http://www.365key.com/Event/get_event_detail_mobile"
var params = [String: AnyObject]()
params["id"] = newsID as AnyObject
if SKUserShared.getUserShared()?.uid != 0 {
params["uid"] = SKUserShared.getUserShared()?.uid as AnyObject?
}
connectionRequest(urlString: urlStr, paramers: params) { (bool, Data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: Data as! Data, options: [])
let detailModel = SKNewsDetailModel.yy_model(withJSON: jsonData!)
completion(true, detailModel!)
} else {
completion(false, nil)
}
}
}
// MARK: 新闻列表数据请求
func newsListDataRequest(with urlStr: String, params:[String: AnyObject]?,completion:@escaping (_ isSuccess: Bool, _ data: Any?)->()){
connectionRequest(with: .POST, urlString: urlStr, paramers: params) { (bool, Data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: Data as! Data, options: []) as? [String: AnyObject?] ?? [:]
let newsListDataArray = NSArray.yy_modelArray(with: SKNewsListModel.self, json: jsonData?["eventlist"] as Any) ?? []
if newsListDataArray.count > 0 {
var dateArray = [String?]()
var dTime: String?
for i in 0..<newsListDataArray.count {
let newsModel = newsListDataArray[i] as? SKNewsListModel
if i == 0{
dTime = newsModel?.showTime
dateArray.append(dTime)
} else {
if dTime != newsModel?.showTime{
dTime = newsModel?.showTime
dateArray.append(dTime)
}
}
}
var allDataArray = [[String: [SKNewsListModel]]]()
for i in 0..<dateArray.count {
let showTime = dateArray[i]
var modelArray = [SKNewsListModel]()
for model in newsListDataArray {
if (model as! SKNewsListModel).showTime == showTime {
modelArray.append(model as! SKNewsListModel)
}
}
let modelDic: [String: [SKNewsListModel]] = [showTime!: modelArray]
allDataArray.append(modelDic)
}
completion(true, allDataArray)
} else{
completion(false, nil)
}
} else {
completion (false, nil)
}
}
}
// mark: 取消产品详情页关注接口
func productCancleFocusRequest(params: [String: AnyObject], completion: @escaping(_ isSuccess: Bool)->()) {
let urlString = "http://www.365key.com/Right/cancel_follow_modile"
print(params)
connectionRequest(urlString: urlString, paramers: params){ (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false)
return
}
completion(code2 as! Int == 0 ? true : false)
} else {
completion(false)
}
}
}
// MARK: 产品详情页点赞或者关注接口(参数不同功能不同)
func productGoodBtnDidClick(with params: [String: AnyObject], completion: @escaping(_ isSuccess: Bool)-> ()) {
let urlString = "http://www.365key.com/Right/follow_for_modile"
print(params)
connectionRequest(urlString: urlString, paramers: params) { (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false)
return
}
completion(code2 as! Int == 0 ? true : false)
} else {
completion(false)
}
}
}
// MARK: 产品详情请求
func productDetailRequest(with productID:Int64, completion: @escaping(_ isSuccess: Bool, _ productDetailModel: SKProductDetailModel?)->()) {
let urlStr = "http://www.365key.com/Produce/get_pro_detail_mobile"
var params = [String: AnyObject]()
params["pid"] = productID as AnyObject?
if SKUserShared.getUserShared()?.uid != 0 {
params["uid"] = SKUserShared.getUserShared()?.uid as AnyObject?
}
print("params == \(params)")
connectionRequest(urlString: urlStr, paramers: params){ (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: [])
guard let jsondata: Any = jsonData else{
return
}
let productDetailModel = SKProductDetailModel.yy_model(withJSON: jsondata)
completion(bool, productDetailModel)
} else {
completion(false, nil)
}
}
}
// MARK: 找回密码请求
func findPasswordRequest(with phoneNumber: String, captcha: String, password: String, completion:@escaping(_ isSuccess: Bool, _ codeNum: Int?)->()) {
let urlStr = "http://www.365key.com/Feedback/retrieve_pwd"
var params = [String: AnyObject]()
params["phone"] = phoneNumber as AnyObject?
params["checkcode"] = captcha as AnyObject?
params["password"] = password as AnyObject?
connectionRequest(urlString: urlStr, paramers: params){ (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false, nil)
return
}
completion(true, code2 as? Int)
} else {
completion(false, nil)
}
}
}
// MARK: 新用户注册请求
func userRegisterRequest(with phoneNumber: String, captcha: String, password: String, completion:@escaping(_ isSuccess: Bool, _ codeNum: Int?)->()) {
let urlStr = "http://www.365key.com/User/reg"
var params = [String: AnyObject]()
params["phone"] = phoneNumber as AnyObject?
params["checkcode"] = captcha as AnyObject?
params["password"] = password as AnyObject?
connectionRequest(urlString: urlStr, paramers: params){ (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false, nil)
return
}
completion(true, code2 as? Int)
} else {
completion(false, nil)
}
}
}
// MARK: 注册界面获取验证码
func registerFatchCaptcha(with phoneNumber: String, completion:@escaping(_ isSuccess: Bool, _ codeNum: Int?)->()) {
let urlStr = "http://www.365key.com/User/check_code"
var params = [String: AnyObject]()
params["phone"] = phoneNumber as AnyObject?
params["type"] = "iOS" as AnyObject?
connectionRequest(urlString: urlStr, paramers: params){ (bool, data) in
if bool{
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false, nil)
return
}
completion(true, code2 as? Int)
} else {
completion(false, nil)
}
}
}
// MARK: 检查获取验证码时,手机号是否被用过
func checkPhoneNumIsUsed(with phoneNumber: String, completion:@escaping (_ isSuccess: Bool)->()) {
let urlStr = "http://www.365key.com/User/check_phone_mobile"
var params = [String: AnyObject]()
params["phone"] = phoneNumber as AnyObject?
var used = false
connectionRequest(urlString: urlStr, paramers: params){ (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
return
}
used = code2 as! Int == 0 ? true : false
completion(used)
} else {
used = false
completion(false)
}
}
}
// MARK: 个人中心信息请求
func userInfoRequest(compeltion:@escaping(_ isSuccess: Bool)->()) {
let userShared = SKUserShared.getUserShared()
let urlStr = "http://www.365key.com/User/personal_center"
var params = [String: AnyObject]()
params["id"] = userShared?.uid
params["type"] = "iOS" as AnyObject?
connectionRequest(urlString: urlStr, paramers: params){ (bool, data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [String: AnyObject?]
let userInfoData = jsonData?["userinfo"]
let userInfo = SKUserInfo.yy_model(withJSON: userInfoData as Any)
userShared?.userInfo = userInfo
SKUserShared.saveUserShared(shared: userShared!)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: SKUserLoginSuccessNotifiction), object: userShared, userInfo: nil)
compeltion(true)
} else {
compeltion(false)
}
}
}
// MARK: 登录请求
func userLoginRequset(with userName: String, password: String, completion:@escaping (_ isSuccess: Bool, _ data: AnyObject?)->()) {
var params = [String: AnyObject]()
params["phone"] = userName as AnyObject?
params["password"] = password as AnyObject?
params["type"] = "iOS" as AnyObject?
let urlStr = "http://www.365key.com/User/login"
print("\(params)")
connectionRequest(urlString: urlStr, paramers: params) { (bool, Data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: Data as! Data, options: []) as? [String: AnyObject?] ?? [:]
let code = jsonData!["code"]
guard let code1 = code,
let code2 = code1 else {
completion(false, nil)
return
}
if code2 as! Int == 0{
let userSared = SKUserShared.yy_model(withJSON: jsonData!)
userSared?.userName = userName
userSared?.passWord = password
SKUserShared.saveUserShared(shared: userSared!)
completion(bool, jsonData as AnyObject?)
} else {
completion(false, nil)
}
} else {
completion(false, nil)
}
}
}
// MARK: 产品列表信息请求
func productListDataRequest(with urlStr: String, params:[String: AnyObject]?,completion:@escaping (_ isSuccess: Bool, _ data: Any?)->()) {
connectionRequest(with: .POST, urlString: urlStr, paramers: params) { (bool, Data) in
if bool {
let jsonData = try? JSONSerialization.jsonObject(with: Data as! Data, options: []) as? [String: AnyObject?] ?? [:]
let productListDataArray = NSArray.yy_modelArray(with: SKProductListModel.self, json: jsonData?["prolist"] as Any) ?? []
if productListDataArray.count > 0 {
var dateArray = [String?]()
var dTime: String?
for i in 0..<productListDataArray.count {
let ProductModel = productListDataArray[i] as? SKProductListModel
if i == 0{
dTime = ProductModel?.showTime
dateArray.append(dTime)
} else {
if dTime != ProductModel?.showTime{
dTime = ProductModel?.showTime
dateArray.append(dTime)
}
}
}
var allDataArray = [[String: [SKProductListModel]]]()
for i in 0..<dateArray.count {
let showTime = dateArray[i]
var modelArray = [SKProductListModel]()
for model in productListDataArray {
if (model as! SKProductListModel).showTime == showTime {
modelArray.append(model as! SKProductListModel)
}
}
let modelDic: [String: [SKProductListModel]] = [showTime!: modelArray]
allDataArray.append(modelDic)
}
completion(true, allDataArray)
} else{
completion(false, nil)
}
} else {
completion (false, nil)
}
}
}
// MARK: connection请求
func connectionRequest(with requestMethod:requestMethod = .POST, urlString: String, paramers: [String: AnyObject]?, completion:@escaping (_ isSuccess: Bool, _ data: Any?)->()) {
let url = URL(string: urlString)
var request = URLRequest(url: url!)
if requestMethod == .POST {
request.httpMethod = "POST"
var paramersData: Data? = nil
paramersData = try? JSONSerialization.data(withJSONObject: paramers as Any, options: JSONSerialization.WritingOptions.prettyPrinted)
request.httpBody = paramersData
NSURLConnection.sendAsynchronousRequest(request, queue: .main, completionHandler: { (URLResponse, Data, Error) in
if Error != nil {
print(Error!)
completion(false, nil)
} else {
if Data != nil{
completion(true, Data)
} else{
completion(false, nil)
}
}
})
} else {
request.httpMethod = "GET"
print("GET方法还没写完")
}
}
}
| apache-2.0 | dc0e8d828fd256903884291bd5d51ee6 | 39.452134 | 181 | 0.46453 | 5.400678 | false | false | false | false |
Speicher210/wingu-sdk-ios-demoapp | Example/Pods/RSBarcodes_Swift/Source/RSUnifiedCodeValidator.swift | 1 | 2097 | //
// RSUnifiedCodeValidator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 10/3/16.
// Copyright (c) 2016 P.D.Q. All rights reserved.
//
import Foundation
import AVFoundation
open class RSUnifiedCodeValidator {
open class var shared: RSUnifiedCodeValidator {
return UnifiedCodeValidatorSharedInstance
}
open func isValid(_ contents:String, machineReadableCodeObjectType: String) -> Bool {
var codeGenerator: RSCodeGenerator?
switch machineReadableCodeObjectType {
case AVMetadataObjectTypeQRCode, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeAztecCode:
return false
case AVMetadataObjectTypeCode39Code:
codeGenerator = RSCode39Generator()
case AVMetadataObjectTypeCode39Mod43Code:
codeGenerator = RSCode39Mod43Generator()
case AVMetadataObjectTypeEAN8Code:
codeGenerator = RSEAN8Generator()
case AVMetadataObjectTypeEAN13Code:
codeGenerator = RSEAN13Generator()
case AVMetadataObjectTypeInterleaved2of5Code:
codeGenerator = RSITFGenerator()
case AVMetadataObjectTypeITF14Code:
codeGenerator = RSITF14Generator()
case AVMetadataObjectTypeUPCECode:
codeGenerator = RSUPCEGenerator()
case AVMetadataObjectTypeCode93Code:
codeGenerator = RSCode93Generator()
case AVMetadataObjectTypeCode128Code:
codeGenerator = RSCode128Generator()
case AVMetadataObjectTypeDataMatrixCode:
codeGenerator = RSCodeDataMatrixGenerator()
case RSBarcodesTypeISBN13Code:
codeGenerator = RSISBN13Generator()
case RSBarcodesTypeISSN13Code:
codeGenerator = RSISSN13Generator()
case RSBarcodesTypeExtendedCode39Code:
codeGenerator = RSExtendedCode39Generator()
default:
print("No code generator selected.")
return false
}
return codeGenerator!.isValid(contents)
}
}
let UnifiedCodeValidatorSharedInstance = RSUnifiedCodeValidator()
| apache-2.0 | 4b9a7b9a154107fc871934ae831005bf | 37.127273 | 103 | 0.699571 | 6.078261 | false | false | false | false |
pecuniabanking/pecunia-client | Plugins/Source/PluginWorker.swift | 1 | 19535 | /**
* Copyright (c) 2015, 2019, Pecunia Project. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; version 2 of the
* License.
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
// Contains the implementation needed to run JS code.
import Foundation
import WebKit
import AppKit
// 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
}
}
@objc protocol JSLogger : JSExport {
func logError(_ message: String) -> Void;
func logWarning(_ message: String) -> Void;
func logInfo(_ message: String) -> Void;
func logDebug(_ message: String) -> Void;
func logVerbose(_ message: String) -> Void;
}
internal class UserQueryEntry {
var bankCode: String;
var passwords: String;
var accountNumbers: [String];
var authRequest: AuthRequest;
init(bankCode bank: String, password pw: String, accountNumbers numbers: [String], auth: AuthRequest) {
bankCode = bank;
passwords = pw;
accountNumbers = numbers;
authRequest = auth;
}
};
class WebClient: WebView, WebViewJSExport {
fileprivate var redirecting: Bool = false;
fileprivate var pluginDescription: String = ""; // The plugin description for error messages.
var URL: String {
get {
return mainFrameURL;
}
set {
redirecting = false;
if let url = Foundation.URL(string: newValue) {
mainFrame.load(URLRequest(url: url));
}
}
}
var postURL: String {
get {
return mainFrameURL;
}
set {
redirecting = false;
if let url = Foundation.URL(string: newValue) {
var request = URLRequest(url: url);
request.httpMethod = "POST";
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type");
mainFrame.load(request);
}
}
}
var query: UserQueryEntry?;
var callback: JSValue = JSValue();
var completion: ([BankQueryResult]) -> Void = { (_: [BankQueryResult]) -> Void in }; // Block to call on results arrival.
func doTest() {
redirecting = false;
}
func reportError(_ account: String, _ message: String) {
query!.authRequest.errorOccured = true; // Flag the error in the auth request, so it doesn't store the PIN.
let alert = NSAlert();
alert.messageText = NSString.localizedStringWithFormat(NSLocalizedString("AP1800", comment: "") as NSString,
account, pluginDescription) as String;
alert.informativeText = message;
alert.alertStyle = .warning;
alert.runModal();
}
func resultsArrived(_ results: JSValue) -> Void {
query!.authRequest.finishPasswordEntry();
if let entries = results.toArray() as? [[String: AnyObject]] {
var queryResults: [BankQueryResult] = [];
// Unfortunately, the number format can change within a single set of values, which makes it
// impossible to just have the plugin specify it for us.
for entry in entries {
let queryResult = BankQueryResult();
if let type = entry["isCreditCard"] as? Bool {
queryResult.type = type ? .creditCard : .bankStatement;
}
if let lastSettleDate = entry["lastSettleDate"] as? Date {
queryResult.lastSettleDate = lastSettleDate;
}
if let account = entry["account"] as? String {
queryResult.account = BankAccount.findAccountWithNumber(account, bankCode: query!.bankCode);
if queryResult.type == .creditCard {
queryResult.ccNumber = account;
}
}
// Balance string might contain a currency code (3 letters).
if let value = entry["balance"] as? String, value.count > 0 {
if let number = NSDecimalNumber.fromString(value) { // Returns the value up to the currency code (if any).
queryResult.balance = number;
}
}
let statements = entry["statements"] as! [[String: AnyObject]];
for jsonStatement in statements {
let statement: BankStatement = BankStatement.createTemporary(); // Created in memory context.
if let final = jsonStatement["final"] as? Bool {
statement.isPreliminary = NSNumber(value: !final);
}
if let date = jsonStatement["valutaDate"] as? Date {
statement.valutaDate = date.addingTimeInterval(12 * 3600); // Add 12hrs so we start at noon.
} else {
statement.valutaDate = Date();
}
if let date = jsonStatement["date"] as? Date {
statement.date = date.addingTimeInterval(12 * 3600);
} else {
statement.date = statement.valutaDate;
}
if let purpose = jsonStatement["transactionText"] as? String {
statement.purpose = purpose;
}
if let value = jsonStatement["value"] as? String, value.count > 0 {
// Because there is a setValue function in NSObject we cannot write to the .value
// member in BankStatement. Using a custom setter would make this into a function
// call instead, but that crashes atm.
// Using dictionary access instead for the time being until this is resolved.
if let number = NSDecimalNumber.fromString(value) {
statement.setValue(number, forKey: "value");
} else {
statement.setValue(NSDecimalNumber(value: 0 as Int32), forKey: "value");
}
}
if let value = jsonStatement["originalValue"] as? String, value.count > 0 {
if let number = NSDecimalNumber.fromString(value) {
statement.origValue = number;
}
}
queryResult.statements.append(statement);
}
// Explicitly sort by date, as it might happen that statements have a different
// sorting (e.g. by valuta date).
queryResult.statements.sort(by: { $0.date < $1.date });
queryResults.append(queryResult);
}
completion(queryResults);
}
}
}
class PluginContext : NSObject, WebFrameLoadDelegate, WebUIDelegate {
fileprivate let webClient: WebClient;
fileprivate let workContext: JSContext; // The context on which we run the script.
// WebView's context is recreated on loading a new page,
// stopping so any running JS code.
fileprivate var jsLogger: JSLogger;
fileprivate var debugScript: String = "";
init?(pluginFile: String, logger: JSLogger, hostWindow: NSWindow?) {
jsLogger = logger;
webClient = WebClient();
workContext = JSContext();
super.init();
prepareContext();
do {
let script = try String(contentsOfFile: pluginFile, encoding: String.Encoding.utf8);
let parseResult = workContext.evaluateScript(script);
if parseResult?.toString() != "true" {
logger.logError("Script konnte geladen werden, wurde aber nicht erfolgreich ausgeführt");
return nil;
}
} catch {
logger.logError("Fehler beim Parsen des Scripts");
return nil;
}
setupWebClient(hostWindow);
}
init?(script: String, logger: JSLogger, hostWindow: NSWindow?) {
jsLogger = logger;
webClient = WebClient();
workContext = JSContext();
super.init();
prepareContext();
let parseResult = workContext.evaluateScript(script);
if parseResult?.toString() != "true" {
return nil;
}
setupWebClient(hostWindow);
}
// MARK: - Setup
fileprivate func prepareContext() {
workContext.setObject(false, forKeyedSubscript: "JSError" as (NSCopying & NSObjectProtocol)?);
workContext.exceptionHandler = { workContext, exception in
self.jsLogger.logError((exception?.toString())!);
workContext?.setObject(true, forKeyedSubscript: "JSError" as (NSCopying & NSObjectProtocol)?);
}
workContext.setObject(jsLogger.self, forKeyedSubscript: "logger" as NSCopying & NSObjectProtocol);
webClient.mainFrame.javaScriptContext.setObject(jsLogger.self, forKeyedSubscript: "logger" as NSCopying & NSObjectProtocol);
//webClient.mainFrame.javaScriptContext.setObject(webClient.self, forKeyedSubscript: "webClient" as NSCopying & NSObjectProtocol);
// Export Webkit to the work context, so that plugins can use it to work with data/the DOM
// from the web client.
workContext.setObject(DOMNodeList.self, forKeyedSubscript: "DOMNodeList" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMCSSStyleDeclaration.self, forKeyedSubscript: "DOMCSSStyleDeclaration" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMCSSRuleList.self, forKeyedSubscript: "DOMCSSRuleList" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMNamedNodeMap.self, forKeyedSubscript: "DOMNamedNodeMap" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMNode.self, forKeyedSubscript: "DOMNode" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMAttr.self, forKeyedSubscript: "DOMAttr" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMElement.self, forKeyedSubscript: "DOMElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLCollection.self, forKeyedSubscript: "DOMHTMLCollection" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLElement.self, forKeyedSubscript: "DOMHTMLElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMDocumentType.self, forKeyedSubscript: "DOMDocumentType" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLFormElement.self, forKeyedSubscript: "DOMHTMLFormElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLInputElement.self, forKeyedSubscript: "DOMHTMLInputElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLButtonElement.self, forKeyedSubscript: "DOMHTMLButtonElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLAnchorElement.self, forKeyedSubscript: "DOMHTMLAnchorElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLOptionElement.self, forKeyedSubscript: "DOMHTMLOptionElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLOptionsCollection.self, forKeyedSubscript: "DOMHTMLOptionsCollection" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLSelectElement.self, forKeyedSubscript: "DOMHTMLSelectElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMImplementation.self, forKeyedSubscript: "DOMImplementation" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMStyleSheetList.self, forKeyedSubscript: "DOMStyleSheetList" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMDocumentFragment.self, forKeyedSubscript: "DOMDocumentFragment" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMCharacterData.self, forKeyedSubscript: "DOMCharacterData" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMText.self, forKeyedSubscript: "DOMText" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMComment.self, forKeyedSubscript: "DOMComment" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMCDATASection.self, forKeyedSubscript: "DOMCDATASection" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMProcessingInstruction.self, forKeyedSubscript: "DOMProcessingInstruction" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMEntityReference.self, forKeyedSubscript: "DOMEntityReference" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMDocument.self, forKeyedSubscript: "DOMDocument" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(WebFrame.self, forKeyedSubscript: "WebFrame" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(webClient.self, forKeyedSubscript: "webClient" as NSCopying & NSObjectProtocol);
}
fileprivate func setupWebClient(_ hostWindow: NSWindow?) {
webClient.frameLoadDelegate = self;
webClient.uiDelegate = self;
webClient.preferences.javaScriptCanOpenWindowsAutomatically = true;
webClient.hostWindow = hostWindow;
if hostWindow != nil {
hostWindow!.contentView = webClient;
}
webClient.pluginDescription = workContext.objectForKeyedSubscript("description").toString();
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString");
webClient.applicationNameForUserAgent = "Pecunia/\(version ?? "1.3.3") (Safari)";
}
// MARK: - Plugin Logic
// Allows to add any additional script to the plugin context.
func addScript(_ script: String) {
workContext.evaluateScript(script);
}
// Like addScript but for both contexts. Applied on the webclient context each time
// it is recreated.
func addDebugScript(_ script: String) {
debugScript = script;
workContext.evaluateScript(script);
}
func pluginInfo() -> (name: String, author: String, description: String, homePage: String, license: String, version: String) {
return (
name: workContext.objectForKeyedSubscript("name").toString(),
author: workContext.objectForKeyedSubscript("author").toString(),
description: workContext.objectForKeyedSubscript("description").toString(),
homePage: workContext.objectForKeyedSubscript("homePage").toString(),
license: workContext.objectForKeyedSubscript("license").toString(),
version: workContext.objectForKeyedSubscript("version").toString()
);
}
// Calls the getStatements() plugin function and translates results from JSON to a BankQueryResult list.
func getStatements(_ userId: String, query: UserQueryEntry, fromDate: Date, toDate: Date,
completion: @escaping ([BankQueryResult]) -> Void) -> Void {
let scriptFunction: JSValue = workContext.objectForKeyedSubscript("getStatements");
let pluginId = workContext.objectForKeyedSubscript("name").toString();
if scriptFunction.isUndefined {
jsLogger.logError("Feler: getStatements() wurde in Plugin " + pluginId! + " nicht gefunden");
return;
}
webClient.completion = completion;
webClient.query = query;
if !(scriptFunction.call(withArguments: [userId, query.bankCode, query.passwords, fromDate,
toDate, query.accountNumbers]) != nil) {
jsLogger.logError("Fehler: getStatements() konnte für Plugin " + pluginId! + " nicht gestartet werden");
}
}
func getFunction(_ name: String) -> JSValue {
return workContext.objectForKeyedSubscript(name);
}
// Returns the outer body HTML text.
func getCurrentHTML() -> String {
return webClient.mainFrame.document.body.outerHTML;
}
func canHandle(_ account: String, bankCode: String) -> Bool {
let function = workContext.objectForKeyedSubscript("canHandle");
if (function?.isUndefined)! {
return false;
}
let result = function?.call(withArguments: [account, bankCode]);
if (result?.isBoolean)! {
return result!.toBool();
}
return false;
}
// MARK: - webView delegate methods.
internal func webView(_ sender: WebView!, didStartProvisionalLoadFor frame: WebFrame!) {
jsLogger.logVerbose("(*) Start loading");
webClient.redirecting = false; // Gets set when we get redirected while processing the provisional frame.
}
internal func webView(_ sender: WebView!, didReceiveServerRedirectForProvisionalLoadFor frame: WebFrame!) {
jsLogger.logVerbose("(*) Received server redirect for frame");
}
internal func webView(_ sender: WebView!, didCommitLoadFor frame: WebFrame!) {
jsLogger.logVerbose("(*) Committed load for frame");
}
internal func webView(_ sender: WebView!, willPerformClientRedirectTo URL: URL!,
delay seconds: TimeInterval, fire date: Date!, for frame: WebFrame!) {
jsLogger.logVerbose("(*) Performing client redirection...");
webClient.redirecting = true;
}
internal func webView(_ sender: WebView!, didCreateJavaScriptContext context: JSContext, for forFrame: WebFrame!) {
jsLogger.logVerbose("(*) JS create");
}
internal func webView(_ sender: WebView!, didFinishLoadFor frame: WebFrame!) {
jsLogger.logVerbose("(*) Finished loading frame from URL: " + frame.dataSource!.response.url!.absoluteString);
if webClient.redirecting {
webClient.redirecting = false;
return;
}
if !webClient.callback.isUndefined && !webClient.callback.isNull {
jsLogger.logVerbose("(*) Calling callback...");
webClient.callback.call(withArguments: [false]);
}
}
internal func webView(_ sender: WebView!, willClose frame: WebFrame!) {
jsLogger.logVerbose("(*) Closing frame...");
}
internal func webView(_ sender: WebView!, didFailLoadWithError error: Error!, for frame: WebFrame!) {
jsLogger.logError("(*) Navigation zur Seite schlug fehl. Ursache: \(error.localizedDescription)")
}
internal func webView(_ sender: WebView!, runJavaScriptAlertPanelWithMessage message: String, initiatedBy initiatedByFrame: WebFrame!) {
let alert = NSAlert();
alert.messageText = message;
alert.runModal();
}
}
| gpl-2.0 | d24a89d1c8c2a7a4316758e72cdfe7f9 | 44.852113 | 143 | 0.639175 | 4.97276 | false | false | false | false |
eBardX/XestiMonitors | Tests/UIKit/Other/KeyboardMonitorTests.swift | 1 | 18320 | //
// KeyboardMonitorTests.swift
// XestiMonitorsTests
//
// Created by J. G. Pusey on 2017-12-27.
//
// © 2017 J. G. Pusey (see LICENSE.md)
//
import UIKit
import XCTest
@testable import XestiMonitors
// swiftlint:disable type_body_length
internal class KeyboardMonitorTests: XCTestCase {
let notificationCenter = MockNotificationCenter()
override func setUp() {
super.setUp()
NotificationCenterInjector.inject = { self.notificationCenter }
}
func testMonitor_didChangeFrame() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeIn
let expectedAnimationDuration: TimeInterval = 0.15
let expectedFrameBegin = CGRect(x: 11, y: 21, width: 31, height: 41)
let expectedFrameEnd = CGRect(x: 51, y: 61, width: 71, height: 81)
let expectedIsLocal = true
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .didChangeFrame,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidChangeFrame(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didChangeFrame(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_didChangeFrame_badUserInfo() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeIn
let expectedAnimationDuration: TimeInterval = 0.15
let expectedFrameBegin = CGRect(x: 11, y: 21, width: 31, height: 41)
let expectedFrameEnd = CGRect(x: 51, y: 61, width: 71, height: 81)
let expectedIsLocal = false
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .didChangeFrame,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidChangeFrame(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal,
badUserInfo: true)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didChangeFrame(info) = event {
XCTAssertNotEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertNotEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertNotEqual(info.frameBegin, expectedFrameBegin)
XCTAssertNotEqual(info.frameEnd, expectedFrameEnd)
XCTAssertNotEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_didHide() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeOut
let expectedAnimationDuration: TimeInterval = 0.25
let expectedFrameBegin = CGRect(x: 12, y: 22, width: 32, height: 42)
let expectedFrameEnd = CGRect(x: 52, y: 62, width: 72, height: 82)
let expectedIsLocal = false
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .didHide,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidHide(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didHide(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_didShow() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeInOut
let expectedAnimationDuration: TimeInterval = 0.35
let expectedFrameBegin = CGRect(x: 13, y: 23, width: 33, height: 43)
let expectedFrameEnd = CGRect(x: 53, y: 63, width: 73, height: 83)
let expectedIsLocal = true
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .didShow,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateDidShow(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .didShow(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_willChangeFrame() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeIn
let expectedAnimationDuration: TimeInterval = 0.45
let expectedFrameBegin = CGRect(x: 14, y: 24, width: 34, height: 44)
let expectedFrameEnd = CGRect(x: 54, y: 64, width: 74, height: 84)
let expectedIsLocal = false
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .willChangeFrame,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateWillChangeFrame(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .willChangeFrame(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_willHide() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeOut
let expectedAnimationDuration: TimeInterval = 0.55
let expectedFrameBegin = CGRect(x: 15, y: 25, width: 35, height: 45)
let expectedFrameEnd = CGRect(x: 55, y: 65, width: 75, height: 85)
let expectedIsLocal = true
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .willHide,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateWillHide(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .willHide(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
func testMonitor_willShow() {
let expectation = self.expectation(description: "Handler called")
let expectedAnimationCurve: UIViewAnimationCurve = .easeInOut
let expectedAnimationDuration: TimeInterval = 0.65
let expectedFrameBegin = CGRect(x: 16, y: 26, width: 36, height: 46)
let expectedFrameEnd = CGRect(x: 56, y: 66, width: 76, height: 86)
let expectedIsLocal = false
var expectedEvent: KeyboardMonitor.Event?
let monitor = KeyboardMonitor(options: .willShow,
queue: .main) { event in
XCTAssertEqual(OperationQueue.current, .main)
expectedEvent = event
expectation.fulfill()
}
monitor.startMonitoring()
simulateWillShow(animationCurve: expectedAnimationCurve,
animationDuration: expectedAnimationDuration,
frameBegin: expectedFrameBegin,
frameEnd: expectedFrameEnd,
isLocal: expectedIsLocal)
waitForExpectations(timeout: 1)
monitor.stopMonitoring()
if let event = expectedEvent,
case let .willShow(info) = event {
XCTAssertEqual(info.animationCurve, expectedAnimationCurve)
XCTAssertEqual(info.animationDuration, expectedAnimationDuration)
XCTAssertEqual(info.frameBegin, expectedFrameBegin)
XCTAssertEqual(info.frameEnd, expectedFrameEnd)
XCTAssertEqual(info.isLocal, expectedIsLocal)
} else {
XCTFail("Unexpected event")
}
}
private func makeUserInfo(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) -> [AnyHashable: Any] {
return [UIKeyboardAnimationCurveUserInfoKey: NSNumber(value: animationCurve.rawValue),
UIKeyboardAnimationDurationUserInfoKey: NSNumber(value: animationDuration),
UIKeyboardFrameBeginUserInfoKey: NSValue(cgRect: frameBegin),
UIKeyboardFrameEndUserInfoKey: NSValue(cgRect: frameEnd),
UIKeyboardIsLocalUserInfoKey: NSNumber(value: isLocal)]
}
private func simulateDidChangeFrame(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool,
badUserInfo: Bool = false) {
let userInfo: [AnyHashable: Any]?
if badUserInfo {
userInfo = nil
} else {
userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
}
notificationCenter.post(name: .UIKeyboardDidChangeFrame,
object: nil,
userInfo: userInfo)
}
private func simulateDidHide(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardDidHide,
object: nil,
userInfo: userInfo)
}
private func simulateDidShow(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardDidShow,
object: nil,
userInfo: userInfo)
}
private func simulateWillChangeFrame(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardWillChangeFrame,
object: nil,
userInfo: userInfo)
}
private func simulateWillHide(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardWillHide,
object: nil,
userInfo: userInfo)
}
private func simulateWillShow(animationCurve: UIViewAnimationCurve,
animationDuration: TimeInterval,
frameBegin: CGRect,
frameEnd: CGRect,
isLocal: Bool) {
let userInfo = makeUserInfo(animationCurve: animationCurve,
animationDuration: animationDuration,
frameBegin: frameBegin,
frameEnd: frameEnd,
isLocal: isLocal)
notificationCenter.post(name: .UIKeyboardWillShow,
object: nil,
userInfo: userInfo)
}
}
// swiftlint:enable type_body_length
| mit | cf77e9af61a1c1d5e89c5b23ecaddd9e | 44.683292 | 94 | 0.549702 | 6.596687 | false | false | false | false |
hughbe/swift | stdlib/public/core/StringHashable.swift | 11 | 4020 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if _runtime(_ObjC)
@_silgen_name("swift_stdlib_NSStringHashValue")
func _stdlib_NSStringHashValue(_ str: AnyObject, _ isASCII: Bool) -> Int
@_silgen_name("swift_stdlib_NSStringHashValuePointer")
func _stdlib_NSStringHashValuePointer(_ str: OpaquePointer, _ isASCII: Bool) -> Int
@_silgen_name("swift_stdlib_CFStringHashCString")
func _stdlib_CFStringHashCString(_ str: OpaquePointer, _ len: Int) -> Int
#endif
extension Unicode {
internal static func hashASCII(
_ string: UnsafeBufferPointer<UInt8>
) -> Int {
let collationTable = _swift_stdlib_unicode_getASCIICollationTable()
var hasher = _SipHash13Context(key: _Hashing.secretKey)
for c in string {
_precondition(c <= 127)
let element = collationTable[Int(c)]
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if element != 0 {
hasher.append(element)
}
}
return hasher._finalizeAndReturnIntHash()
}
internal static func hashUTF16(
_ string: UnsafeBufferPointer<UInt16>
) -> Int {
let collationIterator = _swift_stdlib_unicodeCollationIterator_create(
string.baseAddress!,
UInt32(string.count))
defer { _swift_stdlib_unicodeCollationIterator_delete(collationIterator) }
var hasher = _SipHash13Context(key: _Hashing.secretKey)
while true {
var hitEnd = false
let element =
_swift_stdlib_unicodeCollationIterator_next(collationIterator, &hitEnd)
if hitEnd {
break
}
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if element != 0 {
hasher.append(element)
}
}
return hasher._finalizeAndReturnIntHash()
}
}
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _hashString(_ string: String) -> Int {
let core = string._core
#if _runtime(_ObjC)
// Mix random bits into NSString's hash so that clients don't rely on
// Swift.String.hashValue and NSString.hash being the same.
#if arch(i386) || arch(arm)
let hashOffset = Int(bitPattern: 0x88dd_cc21)
#else
let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21)
#endif
// If we have a contiguous string then we can use the stack optimization.
let isASCII = core.isASCII
if core.hasContiguousStorage {
if isASCII {
return hashOffset ^ _stdlib_CFStringHashCString(
OpaquePointer(core.startASCII), core.count)
} else {
let stackAllocated = _NSContiguousString(core)
return hashOffset ^ stackAllocated._unsafeWithNotEscapedSelfPointer {
return _stdlib_NSStringHashValuePointer($0, false)
}
}
} else {
let cocoaString = unsafeBitCast(
string._bridgeToObjectiveCImpl(), to: _NSStringCore.self)
return hashOffset ^ _stdlib_NSStringHashValue(cocoaString, isASCII)
}
#else
if let asciiBuffer = core.asciiBuffer {
return Unicode.hashASCII(UnsafeBufferPointer(
start: asciiBuffer.baseAddress!,
count: asciiBuffer.count))
} else {
return Unicode.hashUTF16(
UnsafeBufferPointer(start: core.startUTF16, count: core.count))
}
#endif
}
extension String : Hashable {
/// The string's hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
return _hashString(self)
}
}
| apache-2.0 | 908fae81d3ee5a98aad5654eddfd28ee | 32.5 | 83 | 0.666915 | 4.327234 | false | false | false | false |
milseman/swift | test/IRGen/enum_resilience.swift | 4 | 12502 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s
import resilient_enum
import resilient_struct
// CHECK: %swift.type = type { [[INT:i32|i64]] }
// CHECK: %T15enum_resilience5ClassC = type <{ %swift.refcounted }>
// CHECK: %T15enum_resilience9ReferenceV = type <{ %T15enum_resilience5ClassC* }>
// Public fixed layout struct contains a public resilient struct,
// cannot use spare bits
// CHECK: %T15enum_resilience6EitherO = type <{ [[REFERENCE_TYPE:\[(4|8) x i8\]]], [1 x i8] }>
// Public resilient struct contains a public resilient struct,
// can use spare bits
// CHECK: %T15enum_resilience15ResilientEitherO = type <{ [[REFERENCE_TYPE]] }>
// Internal fixed layout struct contains a public resilient struct,
// can use spare bits
// CHECK: %T15enum_resilience14InternalEitherO = type <{ [[REFERENCE_TYPE]] }>
// Public fixed layout struct contains a fixed layout struct,
// can use spare bits
// CHECK: %T15enum_resilience10EitherFastO = type <{ [[REFERENCE_TYPE]] }>
public class Class {}
public struct Reference {
public var n: Class
}
@_fixed_layout public enum Either {
case Left(Reference)
case Right(Reference)
}
public enum ResilientEither {
case Left(Reference)
case Right(Reference)
}
enum InternalEither {
case Left(Reference)
case Right(Reference)
}
@_fixed_layout public struct ReferenceFast {
public var n: Class
}
@_fixed_layout public enum EitherFast {
case Left(ReferenceFast)
case Right(ReferenceFast)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25functionWithResilientEnum010resilient_A06MediumOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
public func functionWithResilientEnum(_ m: Medium) -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return m
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience33functionWithIndirectResilientEnum010resilient_A00E8ApproachOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
public func functionWithIndirectResilientEnum(_ ia: IndirectApproach) -> IndirectApproach {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum16IndirectApproachOMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return ia
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience31constructResilientEnumNoPayload010resilient_A06MediumOyF
public func constructResilientEnumNoPayload() -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 19
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %0, i32 0, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return Medium.Paper
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience29constructResilientEnumPayload010resilient_A06MediumO0G7_struct4SizeVF
public func constructResilientEnumPayload(_ s: Size) -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: [[COPY:%.*]] = call %swift.opaque* %initializeWithCopy(%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: [[METADATA2:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
// CHECK-NEXT: [[METADATA_ADDR2:%.*]] = bitcast %swift.type* [[METADATA2]] to i8***
// CHECK-NEXT: [[VWT_ADDR2:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR2]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT2:%.*]] = load i8**, i8*** [[VWT_ADDR2]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 19
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %0, i32 -2, %swift.type* [[METADATA2]])
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 1
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return Medium.Postcard(s)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @_T015enum_resilience19resilientSwitchTestSi0c1_A06MediumOF(%swift.opaque* noalias nocapture)
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 11
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ENUM_STORAGE:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque*
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[ENUM_COPY:%.*]] = call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias [[ENUM_STORAGE]], %swift.opaque* noalias %0, %swift.type* [[METADATA]])
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 17
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[TAG:%.*]] = call i32 %getEnumTag(%swift.opaque* noalias [[ENUM_STORAGE]], %swift.type* [[METADATA]])
// CHECK: switch i32 [[TAG]], label %[[DEFAULT_CASE:.*]] [
// CHECK: i32 -1, label %[[PAMPHLET_CASE:.*]]
// CHECK: i32 0, label %[[PAPER_CASE:.*]]
// CHECK: i32 1, label %[[CANVAS_CASE:.*]]
// CHECK: ]
// CHECK: ; <label>:[[PAPER_CASE]]
// CHECK: br label %[[END:.*]]
// CHECK: ; <label>:[[CANVAS_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[PAMPHLET_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[DEFAULT_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[END]]
// CHECK: ret
public func resilientSwitchTest(_ m: Medium) -> Int {
switch m {
case .Paper:
return 1
case .Canvas:
return 2
case .Pamphlet(let m):
return resilientSwitchTest(m)
default:
return 3
}
}
public func reabstraction<T>(_ f: (Medium) -> T) {}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25resilientEnumPartialApplyySi0c1_A06MediumOcF(i8*, %swift.refcounted*)
public func resilientEnumPartialApply(_ f: (Medium) -> Int) {
// CHECK: [[CONTEXT:%.*]] = call noalias %swift.refcounted* @swift_rt_swift_allocObject
// CHECK: call swiftcc void @_T015enum_resilience13reabstractionyx010resilient_A06MediumOclF(i8* bitcast (void (%TSi*, %swift.opaque*, %swift.refcounted*)* @_T014resilient_enum6MediumOSiIxid_ACSiIxir_TRTA to i8*), %swift.refcounted* [[CONTEXT:%.*]], %swift.type* @_T0SiN)
reabstraction(f)
// CHECK: ret void
}
// CHECK-LABEL: define internal swiftcc void @_T014resilient_enum6MediumOSiIxid_ACSiIxir_TRTA(%TSi* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.refcounted* swiftself)
// Enums with resilient payloads from a different resilience domain
// require runtime metadata instantiation, just like generics.
public enum EnumWithResilientPayload {
case OneSize(Size)
case TwoSizes(Size, Size)
}
// Make sure we call a function to access metadata of enums with
// resilient layout.
// CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_T015enum_resilience20getResilientEnumTypeypXpyF()
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T015enum_resilience24EnumWithResilientPayloadOMa()
// CHECK-NEXT: ret %swift.type* [[METADATA]]
public func getResilientEnumType() -> Any.Type {
return EnumWithResilientPayload.self
}
// Public metadata accessor for our resilient enum
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_T015enum_resilience24EnumWithResilientPayloadOMa()
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T015enum_resilience24EnumWithResilientPayloadOML
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[METADATA]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: call void @swift_once([[INT]]* @_T015enum_resilience24EnumWithResilientPayloadOMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_EnumWithResilientPayload to i8*), i8* undef)
// CHECK-NEXT: [[METADATA2:%.*]] = load %swift.type*, %swift.type** @_T015enum_resilience24EnumWithResilientPayloadOML
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[METADATA]], %entry ], [ [[METADATA2]], %cacheIsNull ]
// CHECK-NEXT: ret %swift.type* [[RESULT]]
// Methods inside extensions of resilient enums fish out type parameters
// from metadata -- make sure we can do that
extension ResilientMultiPayloadGenericEnum {
// CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_T014resilient_enum32ResilientMultiPayloadGenericEnumO0B11_resilienceE16getTypeParameterxmyF(%swift.type* %"ResilientMultiPayloadGenericEnum<T>", %swift.opaque* noalias nocapture swiftself)
// CHECK: [[METADATA:%.*]] = bitcast %swift.type* %"ResilientMultiPayloadGenericEnum<T>" to %swift.type**
// CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[METADATA]], [[INT]] 3
// CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]]
public func getTypeParameter() -> T.Type {
return T.self
}
}
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_EnumWithResilientPayload(i8*)
| apache-2.0 | e69b5af74deb46354fc9408ae1d79bbc | 46.356061 | 275 | 0.665893 | 3.447876 | false | false | false | false |
meteochu/Alamofire | Tests/ResultTests.swift | 133 | 5086 | //
// ResultTests.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@testable import Alamofire
import Foundation
import XCTest
class ResultTestCase: BaseTestCase {
let error = Error.error(code: .StatusCodeValidationFailed, failureReason: "Status code validation failed")
// MARK: - Is Success Tests
func testThatIsSuccessPropertyReturnsTrueForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true for success case")
}
func testThatIsSuccessPropertyReturnsFalseForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertFalse(result.isSuccess, "result is success should be true for failure case")
}
// MARK: - Is Failure Tests
func testThatIsFailurePropertyReturnsFalseForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertFalse(result.isFailure, "result is failure should be false for success case")
}
func testThatIsFailurePropertyReturnsTrueForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true for failure case")
}
// MARK: - Value Tests
func testThatValuePropertyReturnsValueForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertEqual(result.value ?? "", "success", "result value should match expected value")
}
func testThatValuePropertyReturnsNilForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertNil(result.value, "result value should be nil for failure case")
}
// MARK: - Error Tests
func testThatErrorPropertyReturnsNilForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertTrue(result.error == nil, "result error should be nil for success case")
}
func testThatErrorPropertyReturnsErrorForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertTrue(result.error != nil, "result error should not be nil for failure case")
}
// MARK: - Description Tests
func testThatDescriptionStringMatchesExpectedValueForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertEqual(result.description, "SUCCESS", "result description should match expected value for success case")
}
func testThatDescriptionStringMatchesExpectedValueForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertEqual(result.description, "FAILURE", "result description should match expected value for failure case")
}
// MARK: - Debug Description Tests
func testThatDebugDescriptionStringMatchesExpectedValueForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success value")
// Then
XCTAssertEqual(
result.debugDescription,
"SUCCESS: success value",
"result debug description should match expected value for success case"
)
}
func testThatDebugDescriptionStringMatchesExpectedValueForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertEqual(
result.debugDescription,
"FAILURE: \(error)",
"result debug description should match expected value for failure case"
)
}
}
| mit | 04e587fcd0e132d047b1ab09a4783805 | 33.598639 | 120 | 0.679709 | 4.952288 | false | true | false | false |
iamjono/clingon | Sources/clingon/utilities/makeHandlers.swift | 1 | 2019 | //
// makeHandlers.swift
// clingon
//
// Created by Jonathan Guthrie on 2017-04-01.
//
//
import PerfectLib
func makeHandler(handler: String, responseType: handlerType, apicomment: String = "") throws {
let nl = "//"
let el = ""
var str: [String] = ["//"]
str.append("// \(handler).swift")
str.append("// \(fconfig.projectName)")
str.append(nl)
str.append("// Created by Jonathan Guthrie on 2017-02-20.")
str.append("// Copyright (C) 2017 PerfectlySoft, Inc.")
str.append(nl)
str.append("// Modified by Clingon: https://github.com/iamjono/clingon")
str.append(nl)
str.append("import PerfectHTTP")
if responseType == .html { str.append("import PerfectMustache") }
str.append(el)
str.append("extension Handlers {")
if !apicomment.isEmpty { str.append(" /// \(apicomment)") }
str.append(" static func \(handler)(data: [String:Any]) throws -> RequestHandler {")
str.append(" return {")
str.append(" request, response in")
// response type switch
if responseType == .json {
str.append(" let _ = try? response.setBody(json: [\"error\": \"Handler \(handler) not implemented\"])")
} else {
do {
try makeTemplate(handler: handler)
str.append(" let context: [String : Any] = [")
str.append(" \"property\": \"value\"")
str.append(" ]")
str.append(" response.render(template: \"templates/\(handler)\", context: context)")
} catch {
str.append(" response.setBody(string: \"<html><title>Not Implemented</title><body>This handler (\(handler)) is yet to be implemented</body></html>\")")
print("unable to create handler template for \(handler)")
}
}
str.append(" response.completed()")
str.append(" }")
str.append(" }")
str.append("}")
str.append("")
// Write file
do {
try writeFile("\(fconfig.destinationDir)/Sources/\(fconfig.projectName)/handlers/\(handler).swift", contents: str)
} catch {
throw scaffoldError.fileWriteError
}
}
| apache-2.0 | c7e6129690aac0a2bfb194f3214beecb | 28.26087 | 165 | 0.618623 | 3.410473 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.