repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/TrainingCard.swift | 1 | 1377 | //
// TrainingCard.swift
// AwesomeCore
//
// Created by Leonardo Vinicius Kaminski Ferreira on 05/09/17.
//
import Foundation
public struct TrainingCard: Codable {
public let id: Int
public let academyId: Int
public let courseId: Int
public let date: Date?
public let title: String
public let author: String
public let placeholder: String
public let imageUrl: String
public let categories: [String]
public let href: String
public let studentCount: Int
public let rating: Double
public let completionPercentage: Double
init(id: Int,
academyId: Int,
courseId: Int,
date: Date?,
title: String,
author: String,
placeholder: String,
imageUrl: String,
categories: [String],
href: String,
studentCount: Int,
rating: Double,
completionPercentage: Double) {
self.id = id
self.academyId = academyId
self.courseId = courseId
self.date = date
self.title = title
self.author = author
self.placeholder = placeholder
self.imageUrl = imageUrl
self.categories = categories
self.href = href
self.studentCount = studentCount
self.rating = rating
self.completionPercentage = completionPercentage
}
}
| mit | f6b31d661c6a16da729b1fd485eb2892 | 24.5 | 63 | 0.613653 | 4.797909 | false | false | false | false |
Eonil/Editor | Editor4/ShellNotification.swift | 1 | 1530 | ////
//// ShellNotification.swift
//// Editor4
////
//// Created by Hoon H. on 2016/05/25.
//// Copyright © 2016 Eonil. All rights reserved.
////
//
///// A global notification in shell.
///// Strictly main-thread only.
///// Use this only when you HAVE TO route view component event to
///// another view components **IMMEDIATELY** without any driver
///// loop latency.
/////
///// For now, the only usage is routing `NSMenuDelegate.menuNeedsUpdate`
///// message which must update views immediately.
//enum ShellNotification {
// case FileNavigatorContextMenuWillOpen
// case FileNavigatorContextMenuNeedsUpdate
// case FileNavigatorContextMenuDidClose
//
// func broadcast() {
// for (_, invoke) in ShellNotification.mapping {
// invoke(self)
// }
// }
//
// private static var mapping = Dictionary<ObjectIdentifier, ShellNotification->()>()
// static func register<T: AnyObject>(observer: T, _ handler: T -> ShellNotification -> ()) {
// assertMainThread()
// let invoke = { [weak observer] (n: ShellNotification) -> () in
// guard let observer = observer else {
// reportErrorToDevelopers("Pre-deallocation of an observer.")
// fatalError()
// }
// handler(observer)(n)
// }
// mapping[ObjectIdentifier(observer)] = invoke
// }
// static func deregister<T: AnyObject>(observer: T) {
// assertMainThread()
// mapping[ObjectIdentifier(observer)] = nil
// }
//} | mit | d31e0a33627fa7f51668d6338e74e645 | 33.772727 | 96 | 0.616743 | 4.27095 | false | false | false | false |
scoremedia/Fisticuffs | Tests/FisticuffsTests/WritableComputedSpec.swift | 1 | 6702 | // The MIT License (MIT)
//
// Copyright (c) 2015 theScore Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Quick
import Nimble
@testable import Fisticuffs
class WritableComputedSpec: QuickSpec {
override func spec() {
describe("WritableComputed") {
it("should call its setter when a value is set") {
let name = Observable("John")
let greeting = WritableComputed(
getter: { "Hello, " + name.value },
setter: { value in
if value.hasPrefix("Hello, ") {
let nameStartIndex = value.index(value.startIndex, offsetBy: "Hello, ".count)
name.value = String(value[nameStartIndex...])
} else {
name.value = ""
}
}
)
expect(greeting.value) == "Hello, John"
// update `name` by modifying `greeting`
greeting.value = "Hello, Bob"
expect(name.value) == "Bob"
}
it("should derive its value from the provided block, regardless of what it is set to") {
let a = Observable(11)
let b = Observable(42)
let sum = WritableComputed(
getter: { a.value + b.value },
setter: { _ in }
)
sum.value = 5
expect(sum.value) == 53
}
it("should update its value when any dependencies change") {
let a = Observable(11)
let b = Observable(42)
let sum = WritableComputed(
getter: { a.value + b.value },
setter: { _ in }
)
a.value = 42
expect(sum.value).toEventually(equal(84))
}
context("coalescing updates") {
it("should coalesce updates") {
var numberOfTimesComputed = 0
let a = Observable(11)
let b = Observable(42)
let sum: WritableComputed<Int> = WritableComputed(
getter: {
numberOfTimesComputed += 1
return a.value + b.value
},
setter: { _ in }
)
a.value = 2
b.value = 3
expect(sum.value).toEventually(equal(5))
// once for init() & once for updating a/b
expect(numberOfTimesComputed) == 2
}
it("should immediately recompute if `.value` is accessed & it is dirty") {
let a = Observable(5)
let result = WritableComputed(
getter: { a.value },
setter: { _ in }
)
a.value = 11
expect(result.value) == 11
}
it("should avoid sending multiple updates when recomputed early due to accessing `value`") {
let a = Observable(5)
let result = WritableComputed(
getter: { a.value },
setter: { _ in }
)
var notificationCount = 0
let opts = SubscriptionOptions(notifyOnSubscription: false, when: .afterChange)
_ = result.subscribe(opts) { notificationCount += 1 }
a.value = 11
expect(result.value) == 11
// let runloop finish so that coalesced update happens
RunLoop.main.run(until: Date())
expect(notificationCount) == 1
}
it("should not recurse infinitely if the value is accessed in the subscription block") {
let a = Observable(5)
let result = WritableComputed(
getter: { a.value },
setter: { _ in }
)
_ = result.subscribe { [weak result] in
_ = result?.value // trigger "side effects" in getter
}
a.value = 11
expect(result.value) == 11
// this test will blow the stack here if it fails
}
}
it("should not collect dependencies for any Subscribables read in its subscriptions") {
let shouldNotDependOn = Observable(false)
let a = Observable(11)
let computed = WritableComputed(getter: { a.value }, setter: { _ in })
// attempt to introduce a (false) dependency on `shouldNotDependOn`
_ = computed.subscribe { _, _ in
_ = shouldNotDependOn.value // trigger "side effects" in getter
}
a.value = 5 // trigger the subscription block
var fired = false
_ = computed.subscribe(SubscriptionOptions(notifyOnSubscription: false, when: .afterChange)) { _, _ in fired = true }
// if a dependency was added, this'll cause `fired` to be set to `true`
shouldNotDependOn.value = true
expect(fired) == false
}
}
}
}
| mit | 67f5c5ed084be1300499c7023b2e44e1 | 37.965116 | 133 | 0.48866 | 5.404839 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/ViewControllers/SupportCenterContainer.swift | 1 | 5005 | //
// SupportCenterContainer.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-05-02.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class SupportCenterContainer: UIViewController {
func navigate(to: String) {
webView.navigate(to: to)
}
init(walletAuthenticator: TransactionAuthenticator) {
let mountPoint = "/support"
webView = BRWebViewController(bundleName: C.webBundle,
mountPoint: mountPoint,
walletAuthenticator: walletAuthenticator)
super.init(nibName: nil, bundle: nil)
}
private var webView: BRWebViewController
let blur = UIVisualEffectView()
override func viewDidLoad() {
view.backgroundColor = .clear
addChildViewController(webView, layout: {
webView.view.constrain([
webView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
webView.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
webView.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ])
})
addTopCorners()
webView.webView?.scrollView.bounces = false
}
func preload() {
webView.stopServer()
webView.bundleName = C.webBundle // reset in case of developer override
webView.startServer()
webView.preload()
}
private func addTopCorners() {
let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 6.0, height: 6.0)).cgPath
let maskLayer = CAShapeLayer()
maskLayer.path = path
webView.view.layer.mask = maskLayer
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension SupportCenterContainer: UIViewControllerTransitioningDelegate {
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return DismissSupportCenterAnimator()
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PresentSupportCenterAnimator()
}
}
class PresentSupportCenterAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let duration = transitionDuration(using: transitionContext)
guard let toViewController = transitionContext.viewController(forKey: .to) as? SupportCenterContainer else { assert(false, "Missing to view controller"); return }
guard let toView = transitionContext.view(forKey: .to) else { assert(false, "Missing to view"); return }
let container = transitionContext.containerView
let blur = toViewController.blur
blur.frame = container.frame
container.addSubview(blur)
let finalToViewFrame = toView.frame
toView.frame = toView.frame.offsetBy(dx: 0, dy: toView.frame.height)
container.addSubview(toView)
UIView.spring(duration, animations: {
blur.effect = UIBlurEffect(style: .dark)
toView.frame = finalToViewFrame
}, completion: { _ in
transitionContext.completeTransition(true)
})
}
}
class DismissSupportCenterAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard transitionContext.isAnimated else { return }
let duration = transitionDuration(using: transitionContext)
guard let fromView = transitionContext.view(forKey: .from) else { assert(false, "Missing from view"); return }
guard let fromViewController = transitionContext.viewController(forKey: .from) as? SupportCenterContainer
else { assert(false, "Missing to view controller"); return }
let originalFrame = fromView.frame
UIView.animate(withDuration: duration, animations: {
fromViewController.blur.effect = nil
fromView.frame = fromView.frame.offsetBy(dx: 0, dy: fromView.frame.height)
}, completion: { _ in
fromView.frame = originalFrame //Because this view gets reused, it's frame needs to be reset everytime
transitionContext.completeTransition(true)
})
}
}
| mit | c48b2a053f87582601952330b283f0b6 | 39.354839 | 170 | 0.692246 | 5.597315 | false | false | false | false |
scoremedia/Fisticuffs | Sources/Fisticuffs/UIKit/DataSource.swift | 1 | 13970 | // The MIT License (MIT)
//
// Copyright (c) 2015 theScore Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public protocol DataSourceView: AnyObject {
associatedtype CellView
func reloadData()
func insertCells(indexPaths: [IndexPath])
func deleteCells(indexPaths: [IndexPath])
func batchUpdates(_ updates: @escaping () -> Void)
func indexPathsForSelections() -> [IndexPath]?
func select(indexPath: IndexPath)
func deselect(indexPath: IndexPath)
func dequeueCell(reuseIdentifier: String, indexPath: IndexPath) -> CellView
}
open class DataSource<Item: Equatable, View: DataSourceView> : NSObject {
fileprivate weak var view: View?
// Underlying data
fileprivate let subscribable: Subscribable<[Item]>
fileprivate let observable: Observable<[Item]>?
fileprivate var subscribableSubscription: Disposable?
fileprivate var suppressChangeUpdates = false
fileprivate var items: [Item] = []
fileprivate var hasDoneInitialDataLoad = false
fileprivate var ignoreSelectionChanges: Bool = false
fileprivate var selectionsSubscription: Disposable?
fileprivate var selectionSubscription: Disposable?
/// All selected items
open var selections: Observable<[Item]>? {
didSet {
selectionsSubscription?.dispose()
selectionsSubscription = selections?.subscribe { [weak self] _, newValue in
if self?.ignoreSelectionChanges == true {
return
}
if let selection = self?.selection {
self?.ignoreSelectionChanges = true
if let selectionValue = selection.value {
if newValue.contains(selectionValue) == false {
selection.value = newValue.first
}
} else {
selection.value = newValue.first
}
self?.ignoreSelectionChanges = false
}
self?.syncSelections()
}
}
}
/// The selected item. If multiple items are allowed/selected, it is undefined which one
/// will show up in here. Setting it will clear out `selections`
open var selection: Observable<Item?>? {
didSet {
selectionSubscription?.dispose()
selectionSubscription = selection?.subscribe { [weak self] _, newValue in
if self?.ignoreSelectionChanges == true {
return
}
if let selections = self?.selections {
self?.ignoreSelectionChanges = true
if let newValue = newValue {
if selections.value.contains(newValue) == false {
selections.value.append(newValue)
}
} else {
selections.value = []
}
self?.ignoreSelectionChanges = false
}
self?.syncSelections()
}
}
}
fileprivate var disabledItemsSubscription: Disposable?
fileprivate var disabledItemsValue: [Item] = []
/// If set, will prevent the user from selecting these rows/items in collection/table views
/// NOTE: Won't adjust `selection`/`selections` properties (TODO: Should it?)
open func disableSelectionFor(_ subscribable: Subscribable<[Item]>) {
disabledItemsSubscription?.dispose()
disabledItemsSubscription = subscribable.subscribe { [weak self] _, newValue in
self?.disabledItemsValue = Array(newValue)
}
}
open var deselectOnSelection = true
public let onSelect = Event<Item>()
public let onDeselect = Event<Item>()
open var editable: Bool { return observable != nil }
public init(subscribable: Subscribable<[Item]>, view: View) {
self.view = view
self.subscribable = subscribable
self.observable = subscribable as? Observable<[Item]>
super.init()
subscribableSubscription = subscribable.subscribe { [weak self] old, new in
self?.underlyingDataChanged(new)
}
}
deinit {
subscribableSubscription?.dispose()
selectionsSubscription?.dispose()
selectionSubscription?.dispose()
disabledItemsSubscription?.dispose()
}
fileprivate var reuseIdentifier: String?
fileprivate var cellSetup: ((Item, View.CellView) -> Void)?
open func useCell(reuseIdentifier: String, setup: @escaping (Item, View.CellView) -> Void) {
self.reuseIdentifier = reuseIdentifier
cellSetup = setup
}
open var allowsMoving = false
open var animateChanges = true
}
extension DataSource {
func underlyingDataChanged(_ new: [Item]) {
let change = items.calculateChange(new)
guard suppressChangeUpdates == false else {
items = new
syncSelections()
return
}
guard animateChanges else {
items = new
view?.reloadData()
syncSelections()
return
}
if case .set = change {
items = new
view?.reloadData()
syncSelections()
return
}
// Do all updates in batch updates (ie UITableView.beginUpdates()/.endUpdates()
// or UICollectionView.performUpdates(_:completion:)) to avoid getting in a
// situation where the collection view may have not have queried for section/item counts
// already.
//
// By using performUpdate(_:completion:) it will query for section/item counts
// right away if needed, do the updates, and query the section/item counts after to validate
// the correct number of items were inserted/removed.
//
// If we do the inserts before it's queried for section/item counts (and outside a performUpdate(_:completion:)
// block). It'll simply query before and after it does the inserts, and we don't have any way of returning the
// old counts the first time, and the new counts the second time, so it'll always cause a crash like:
//
// *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete
// item 3 from section 0 which only contains 1 items before the update'
//
view?.batchUpdates {
// NOTE: important this happens inside the block, see above comment
self.items = new
switch change {
case .set:
assertionFailure("the .set case is handled above")
return
case let .insert(index: index, newElements: newElements):
let indexPaths = (index ..< index + newElements.count).map { i in IndexPath(item: i, section: 0) }
self.view?.insertCells(indexPaths: indexPaths)
case let .remove(range: range, removedElements: _):
let indexPaths = range.map { i in IndexPath(item: i, section: 0) }
self.view?.deleteCells(indexPaths: indexPaths)
case let .replace(range: range, removedElements: _, newElements: new):
let deleted = range.map { i in IndexPath(item: i, section: 0) }
self.view?.deleteCells(indexPaths: deleted)
let addedRange = range.lowerBound ..< range.lowerBound + new.count
let added = addedRange.map { i in IndexPath(item: i, section: 0) }
self.view?.insertCells(indexPaths: added)
}
}
syncSelections()
}
func syncSelections() {
guard let view = view else { return }
var selectedItems: [Item] = []
if let selections = selections {
selectedItems = selections.value
} else if let selection = selection {
if let value = selection.value {
selectedItems = [value]
}
} else {
// no selection binding setup
return
}
let currentSelections = Set(view.indexPathsForSelections() ?? [])
let expectedSelections: Set<IndexPath> = {
let expected = selectedItems.map { item -> IndexPath? in
items.firstIndex(of: item).map { index in
IndexPath(item: index, section: 0)
}
}
return Set(expected.compactMap { $0 })
}()
let toDeselect = currentSelections.subtracting(expectedSelections)
toDeselect.forEach(view.deselect)
let toSelect = expectedSelections.subtracting(currentSelections)
toSelect.forEach(view.select)
}
}
extension DataSource {
public func numberOfSections() -> Int {
// Sadly this is the best place to hook into this... If we try to sync
// selections before the table/collection view has been loaded (ie, when
// setting up its bindings), it won't save those selections. This triggers a
// sync again after the table/collection view has loaded its data
if hasDoneInitialDataLoad == false {
hasDoneInitialDataLoad = true
DispatchQueue.main.async {
self.syncSelections()
}
}
return 1
}
public func numberOfItems(section: Int) -> Int {
items.count
}
public func itemAtIndexPath(_ indexPath: IndexPath) -> Item {
items[(indexPath as NSIndexPath).item]
}
public func cellAtIndexPath(_ indexPath: IndexPath) -> View.CellView {
guard let view = view else {
preconditionFailure("view not set")
}
guard let reuseIdentifier = reuseIdentifier, let cellSetup = cellSetup else {
preconditionFailure("Cell reuseidentifier/setup block not set")
}
let item = itemAtIndexPath(indexPath)
let cell = view.dequeueCell(reuseIdentifier: reuseIdentifier, indexPath: indexPath)
cellSetup(item, cell)
return cell
}
public func didSelect(indexPath: IndexPath) {
let item = itemAtIndexPath(indexPath)
self.ignoreSelectionChanges = true
do {
selections?.value.append(item)
if selection?.value != item {
selection?.value = item
}
}
self.ignoreSelectionChanges = false
onSelect.fire(item)
if deselectOnSelection {
view?.deselect(indexPath: indexPath)
didDeselect(indexPath: indexPath)
}
}
public func didDeselect(indexPath: IndexPath) {
let item = itemAtIndexPath(indexPath)
self.ignoreSelectionChanges = true
do {
if let index = selections?.value.firstIndex(of: item) {
selections?.value.remove(at: index)
}
if selection?.value == item {
// reset back to the first multiple selection (or none if there isn't one)
selection?.value = selections?.value.first
}
}
self.ignoreSelectionChanges = false
onDeselect.fire(item)
}
public func canSelect(indexPath: IndexPath) -> Bool {
let item = itemAtIndexPath(indexPath)
return disabledItemsValue.contains(item) == false
}
}
extension DataSource {
func modifyUnderlyingData(suppressChangeUpdates suppress: Bool, block: (_ data: Observable<[Item]>) -> Void) {
suppressChangeUpdates = suppress
defer { suppressChangeUpdates = false }
assert(editable, "Underlying data must be editable")
guard let observable = observable else {
assertionFailure("Must have an observable to modify")
return
}
block(observable)
}
public func move(source: IndexPath, destination: IndexPath) {
// No need to send updates to the view (suppressChangeUpdates: true) for the moving items,
// as that is handled internally by UITableView / UICollectionView
modifyUnderlyingData(suppressChangeUpdates: true) { data in
let sourceIndex = data.value.startIndex.advanced(by: source.item)
let item = data.value.remove(at: sourceIndex)
let destIndex = data.value.startIndex.advanced(by: destination.item)
data.value.insert(item, at: destIndex)
}
}
public func delete(indexPath: IndexPath) {
modifyUnderlyingData(suppressChangeUpdates: false) { data in
let index = data.value.startIndex.advanced(by: indexPath.item)
data.value.remove(at: index)
}
}
}
| mit | 0ee4b573910bd59e77d7fe93528d8152 | 35.380208 | 124 | 0.605082 | 5.309768 | false | false | false | false |
snailjj/iOSDemos | SnailSwiftDemos/SnailSwiftDemos/Foundations/ViewControllers/FileViewController.swift | 2 | 8660 | //
// FileViewController.swift
// SnailSwiftDemos
//
// Created by Jian Wu on 2016/11/15.
// Copyright © 2016年 Snail. All rights reserved.
//
/*
一、iOS中的沙盒机制
1、iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。
它一般存放着程序包文件(可执行文件)、图片、音频、视频、plist文件、sqlite数据库以及其他文件。
2、每个应用程序都有自己的独立的存储空间(沙盒)
3、一般来说应用程序之间是不可以互相访问
二、当我们创建应用程序时,在每个沙盒中含有三个文件,分别是Document、Library和temp。
Document:一般需要持久的数据都放在此目录中,可以在当中添加子文件夹,iTunes备份和恢复的时候,会包括此目录。
Library:设置程序的默认设置和其他状态信息
temp:创建临时文件的目录,当iOS设备重启时,文件会被自动清除
*/
import UIKit
class FileViewController: CustomViewController {
let fileManager = FileManager.default
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
writeDataToFile()
fileAttr()
}
//MARK; - 常识
func commonSence() {
//TODO:获取程序的根目录(Home)
let homePath = NSHomeDirectory()
print("根目录Home\(homePath)")
//TODO:获取Document目录
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
print(documentPath ?? "Document路径获取错误")
//TODO:获取Library目录
let libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first
print(libraryPath ?? "Library路径获取错误")
//TODO:获取Library中的Cache目录
let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
print(cachePath)
//TODO:获取temp路径
let tempPath = NSTemporaryDirectory()
print(tempPath)
}
//MARK: - String的路径处理方法
func strPathAction() {
let path = NSHomeDirectory() as NSString
//TODO:获取组成此路径的各个组成部分
let pathStrArr = path.pathComponents
print("路径的各个组成部分\(pathStrArr)")
//TODO:提取路径的最后一个组成部分
let lastPath = path.lastPathComponent
print("路径的最后一个组成部分\(lastPath)")
//TODO:删除路径的最后一个组成部分
let lastDeletedPath = path.deletingLastPathComponent
print("删除路径的最后一个组成部分后的路径\(lastDeletedPath)")
//TODO:在路径后面添加其他路径
let addedPath = path.appendingPathComponent("Snail.txt") as NSString
print("在路径后面添加其他路径Snail.txt后\(addedPath)")
//TODO:取路径最后部分的扩展名
let getExName = addedPath.pathExtension
print("取路径最后部分的扩展名\(getExName)")
//TODO:删除掉路径最后部分的扩展名
let deleExNamePath = addedPath.deletingPathExtension
print("删除掉路径最后部分的扩展名后\(deleExNamePath)")
//TODO:路径最后追加扩展名
let appendExPath = path.appendingPathExtension("ppt")
print("路径最后追加扩展名\(appendExPath)")
}
/*
MARK: - 创建目录
*/
func createwjj() {
let homePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
//TODO:创建文件夹/目录
let wjjPath = homePath! + "/Snail"
print(wjjPath)
var success = true
if !fileManager.fileExists(atPath: wjjPath) {
do{
try fileManager.createDirectory(atPath: wjjPath, withIntermediateDirectories: true, attributes: nil)
}catch {
success = false
print("出错了")
}
}else{
print("目录已存在")
}
}
/*
创建文件
*/
func createWJ() {
let fileManager = FileManager.default
let homePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let wjjPath = homePath! + "/Snail"
let filePath = (wjjPath as NSString).appendingPathComponent("Snail.txt")
if !fileManager.fileExists(atPath: filePath) {
let success = fileManager.createFile(atPath: filePath, contents: nil, attributes: nil)
if success {
print("创建文件成功")
}else{
print("创建文件失败")
}
}else{
print("文件已存在")
}
}
/*
写、读数据
*/
func writeDataToFile() {
let homePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let wjjPath = homePath! + "/Snail"
let filePath = (wjjPath as NSString).appendingPathComponent("Snail.txt")
let str = "My english name is Snail..."
do {
//会把原来的数据覆盖掉
try str.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
print("写入成功")
}catch {
print("写入失败")
}
//TODO:读数据
//方法一
// do{
// let str = try String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding)
// print(str)
// }catch{
// print("出错了")
// }
//
// //方法二
// let data = NSData(contentsOfFile: filePath)
// let str = String.init(data: data!, encoding: NSUTF8StringEncoding)
// print(str)
}
/*
文件的属性
*/
func fileAttr() {
let homePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let wjjPath = homePath! + "/Snail"
let filePath = (wjjPath as NSString).appendingPathComponent("Snail.txt")
do{
let fileDict = try fileManager.attributesOfItem(atPath: filePath)
fileDict.forEach({ (key,value) in
print("\(key):\(value)")
})
}catch{
}
}
/*
对于文件的操作,移动删除等
*/
func fileAction() {
let homePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let wjjPath = homePath! + "/Snail"
let filePath = (wjjPath as NSString).appendingPathComponent("Snail.txt")
// //========================删除文件=======================
// do {
// //TODO:根据文件路径删除文件
// let res = try fileManager.removeItemAtPath(filePath)
// print("删除文件成功")
// }catch{
// print("删除文件失败")
// }
// print("文件\(fileManager.isExecutableFileAtPath(filePath) ? "存在" : "不存在")")
//
// //========================复制文件=======================
// do {
// //TODO:如果文件存在 则复制失败
// try fileManager.copyItemAtPath(filePath, toPath: "/Users/snail/Desktop/Snail.txt")
// print("复制文件成功")
// }catch{
// print(error)
// }
//
// //========================移动文件=======================
// do {
// try fileManager.moveItemAtPath(filePath, toPath: "/Users/snail/Desktop/Snail12.txt")
// print("移动文件成功")
// }catch{
// print(error)
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func 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 | 7aae18c54c4fc766802a537f571661e2 | 29.845833 | 116 | 0.564771 | 4.481235 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/Pods/Kingfisher/Sources/ImagePrefetcher.swift | 129 | 11713 | //
// ImagePrefetcher.swift
// Kingfisher
//
// Created by Claire Knight <[email protected]> on 24/02/2016
//
// Copyright (c) 2016 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.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
/// Progress update block of prefetcher.
///
/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
/// - `completedResources`: An array of resources that are downloaded and cached successfully.
public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ())
/// Completion block of prefetcher.
///
/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
/// - `completedResources`: An array of resources that are downloaded and cached successfully.
public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ())
/// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
/// This is useful when you know a list of image resources and want to download them before showing.
public class ImagePrefetcher {
/// The maximum concurrent downloads to use when prefetching images. Default is 5.
public var maxConcurrentDownloads = 5
private let prefetchResources: [Resource]
private let optionsInfo: KingfisherOptionsInfo
private var progressBlock: PrefetcherProgressBlock?
private var completionHandler: PrefetcherCompletionHandler?
private var tasks = [URL: RetrieveImageDownloadTask]()
private var pendingResources: ArraySlice<Resource>
private var skippedResources = [Resource]()
private var completedResources = [Resource]()
private var failedResources = [Resource]()
private var stopped = false
// The created manager used for prefetch. We will use the helper method in manager.
private let manager: KingfisherManager
private var finished: Bool {
return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty
}
/**
Init an image prefetcher with an array of URLs.
The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
The images already cached will be skipped without downloading again.
- parameter urls: The URLs which should be prefetched.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
- parameter completionHandler: Called when the whole prefetching process finished.
- returns: An `ImagePrefetcher` object.
- Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
*/
public convenience init(urls: [URL],
options: KingfisherOptionsInfo? = nil,
progressBlock: PrefetcherProgressBlock? = nil,
completionHandler: PrefetcherCompletionHandler? = nil)
{
let resources: [Resource] = urls.map { $0 }
self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Init an image prefetcher with an array of resources.
The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable.
After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
The images already cached will be skipped without downloading again.
- parameter resources: The resources which should be prefetched. See `Resource` type for more.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
- parameter completionHandler: Called when the whole prefetching process finished.
- returns: An `ImagePrefetcher` object.
- Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
*/
public init(resources: [Resource],
options: KingfisherOptionsInfo? = nil,
progressBlock: PrefetcherProgressBlock? = nil,
completionHandler: PrefetcherCompletionHandler? = nil)
{
prefetchResources = resources
pendingResources = ArraySlice(resources)
// We want all callbacks from main queue, so we ignore the call back queue in options
let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil))
self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo
let cache = self.optionsInfo.targetCache
let downloader = self.optionsInfo.downloader
manager = KingfisherManager(downloader: downloader, cache: cache)
self.progressBlock = progressBlock
self.completionHandler = completionHandler
}
/**
Start to download the resources and cache them. This can be useful for background downloading
of assets that are required for later use in an app. This code will not try and update any UI
with the results of the process.
*/
public func start()
{
// Since we want to handle the resources cancellation in main thread only.
DispatchQueue.main.safeAsync {
guard !self.stopped else {
assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
self.handleComplete()
return
}
guard self.maxConcurrentDownloads > 0 else {
assertionFailure("There should be concurrent downloads value should be at least 1.")
self.handleComplete()
return
}
guard self.prefetchResources.count > 0 else {
self.handleComplete()
return
}
let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
for _ in 0 ..< initialConcurentDownloads {
if let resource = self.pendingResources.popFirst() {
self.startPrefetching(resource)
}
}
}
}
/**
Stop current downloading progress, and cancel any future prefetching activity that might be occuring.
*/
public func stop() {
DispatchQueue.main.safeAsync {
if self.finished { return }
self.stopped = true
self.tasks.forEach { (_, task) -> () in
task.cancel()
}
}
}
func downloadAndCache(_ resource: Resource) {
let downloadTaskCompletionHandler: CompletionHandler = { (image, error, _, _) -> () in
self.tasks.removeValue(forKey: resource.downloadURL)
if let _ = error {
self.failedResources.append(resource)
} else {
self.completedResources.append(resource)
}
self.reportProgress()
if self.stopped {
if self.tasks.isEmpty {
self.failedResources.append(contentsOf: self.pendingResources)
self.handleComplete()
}
} else {
self.reportCompletionOrStartNext()
}
}
let downloadTask = manager.downloadAndCacheImage(
with: resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: RetrieveImageTask(),
progressBlock: nil,
completionHandler: downloadTaskCompletionHandler,
options: optionsInfo)
if let downloadTask = downloadTask {
tasks[resource.downloadURL] = downloadTask
}
}
func append(cached resource: Resource) {
skippedResources.append(resource)
reportProgress()
reportCompletionOrStartNext()
}
func startPrefetching(_ resource: Resource)
{
if optionsInfo.forceRefresh {
downloadAndCache(resource)
} else {
let alreadyInCache = manager.cache.isImageCached(forKey: resource.cacheKey).cached
if alreadyInCache {
append(cached: resource)
} else {
downloadAndCache(resource)
}
}
}
func reportProgress() {
progressBlock?(skippedResources, failedResources, completedResources)
}
func reportCompletionOrStartNext() {
if let resource = pendingResources.popFirst() {
startPrefetching(resource)
} else {
guard tasks.isEmpty else { return }
handleComplete()
}
}
func handleComplete() {
completionHandler?(skippedResources, failedResources, completedResources)
completionHandler = nil
progressBlock = nil
}
}
| apache-2.0 | 7d8b1630ef41742df09d20d4638d278e | 42.868914 | 209 | 0.667037 | 5.702532 | false | false | false | false |
tardieu/swift | test/SILGen/constrained_extensions.swift | 3 | 7402 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir %s
// RUN: %target-swift-frontend -emit-ir -O %s
extension Array where Element == Int {
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlESayxGyt1x_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int>
public init(x: ()) {
self.init()
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifg : $@convention(method) (@guaranteed Array<Int>) -> Int
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifs : $@convention(method) (Int, @inout Array<Int>) -> ()
// CHECK-LABEL: sil [transparent] [fragile] @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Array<Int>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK-LABEL: sil [transparent] [fragile] @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifmytfU_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Array<Int>, @thick Array<Int>.Type) -> ()
public var instanceProperty: Element {
get {
return self[0]
}
set {
self[0] = newValue
}
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14instanceMethodxyF : $@convention(method) (@guaranteed Array<Int>) -> Int
public func instanceMethod() -> Element {
return instanceProperty
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14instanceMethodxx1e_tF : $@convention(method) (Int, @guaranteed Array<Int>) -> Int
public func instanceMethod(e: Element) -> Element {
return e
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14staticPropertySifgZ : $@convention(method) (@thin Array<Int>.Type) -> Int
public static var staticProperty: Element {
return Array(x: ()).instanceProperty
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodxyFZ : $@convention(method) (@thin Array<Int>.Type) -> Int
public static func staticMethod() -> Element {
return staticProperty
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodxxSg1e_tFZfA_ : $@convention(thin) () -> Optional<Int>
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodxxSg1e_tFZ : $@convention(method) (Optional<Int>, @thin Array<Int>.Type) -> Int
public static func staticMethod(e: Element? = nil) -> Element {
return e!
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE9subscriptSiycfg : $@convention(method) (@guaranteed Array<Int>) -> Int
public subscript(i: ()) -> Element {
return self[0]
}
// CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE21inoutAccessOfPropertyyyF : $@convention(method) (@inout Array<Int>) -> ()
public mutating func inoutAccessOfProperty() {
func increment(x: inout Element) {
x += 1
}
increment(x: &instanceProperty)
}
}
extension Dictionary where Key == Int {
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lEAByxq_Gyt1x_tcfC : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @owned Dictionary<Int, Value> {
public init(x: ()) {
self.init()
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fg : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fs : $@convention(method) <Key, Value where Key == Int> (@in Value, @inout Dictionary<Int, Value>) -> ()
// CHECK-LABEL: sil [transparent] [fragile] @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fm : $@convention(method) <Key, Value where Key == Int> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Int, Value>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK-LABEL: sil [transparent] [fragile] @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fmytfU_ : $@convention(thin) <Key, Value where Key == Int> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Int, Value>, @thick Dictionary<Int, Value>.Type) -> ()
public var instanceProperty: Value {
get {
return self[0]!
}
set {
self[0] = newValue
}
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE14instanceMethodq_yF : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value
public func instanceMethod() -> Value {
return instanceProperty
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE14instanceMethodq_q_1v_tF : $@convention(method) <Key, Value where Key == Int> (@in Value, @guaranteed Dictionary<Int, Value>) -> @out Value
public func instanceMethod(v: Value) -> Value {
return v
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodxyFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int
public static func staticMethod() -> Key {
return staticProperty
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE14staticPropertySifgZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int
public static var staticProperty: Key {
return 0
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodq_xSg1k_q_Sg1vtFZfA_ : $@convention(thin) <Key, Value where Key == Int> () -> Optional<Int>
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodq_xSg1k_q_Sg1vtFZfA0_ : $@convention(thin) <Key, Value where Key == Int> () -> @out Optional<Value>
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodq_xSg1k_q_Sg1vtFZ : $@convention(method) <Key, Value where Key == Int> (Optional<Int>, @in Optional<Value>, @thin Dictionary<Int, Value>.Type) -> @out Value
public static func staticMethod(k: Key? = nil, v: Value? = nil) -> Value {
return v!
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE17callsStaticMethodq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value
public static func callsStaticMethod() -> Value {
return staticMethod()
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16callsConstructorq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value
public static func callsConstructor() -> Value {
return Dictionary(x: ()).instanceMethod()
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE9subscriptq_ycfg : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value
public subscript(i: ()) -> Value {
return self[0]!
}
// CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE21inoutAccessOfPropertyyyF : $@convention(method) <Key, Value where Key == Int> (@inout Dictionary<Int, Value>) -> ()
public mutating func inoutAccessOfProperty() {
func increment(x: inout Value) { }
increment(x: &instanceProperty)
}
}
| apache-2.0 | 4e2c9dcb2a105b79d6b87107a2008827 | 55.075758 | 313 | 0.722778 | 3.811535 | false | false | false | false |
yanagiba/swift-lint | Tests/LintTests/RuleProtocolTests.swift | 2 | 3458 | /*
Copyright 2015-2017 Ryuichi Laboratories and the Yanagiba project contributors
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 XCTest
@testable import Lint
class RuleProtocolTests : XCTestCase {
func testDefaultImplementations() {
class DoNothingRule : Rule {
var name: String {
return "Do Nothing"
}
func emitIssue(_: Issue) {}
func inspect(_: ASTContext, configurations: [String: Any]?) {}
}
let doNothingRule = DoNothingRule()
XCTAssertEqual(doNothingRule.identifier, "do_nothing")
XCTAssertEqual(doNothingRule.fileName, "DoNothingRule.swift")
XCTAssertNil(doNothingRule.description)
XCTAssertNil(doNothingRule.examples)
XCTAssertNil(doNothingRule.thresholds)
XCTAssertNil(doNothingRule.additionalDocument)
XCTAssertEqual(doNothingRule.severity, .minor)
XCTAssertEqual(doNothingRule.category, .uncategorized)
}
func testWhiteSpaces() {
class TooManySpacesRule : Rule {
var name: String {
return "I Typed Too Many Spaces"
}
func emitIssue(_: Issue) {}
func inspect(_: ASTContext, configurations: [String: Any]?) {}
}
let tooManySpacesRule = TooManySpacesRule()
XCTAssertEqual(tooManySpacesRule.identifier, "i_typed_too_many_spaces")
XCTAssertEqual(tooManySpacesRule.fileName, "ITypedTooManySpacesRule.swift")
}
func testIdentifierImplementation() {
class WithCustomIdentifierRule : Rule {
var name: String {
return "Rule Name"
}
var identifier: String {
return "rule_identifier"
}
var fileName: String {
return "FileName.test"
}
func emitIssue(_: Issue) {}
func inspect(_: ASTContext, configurations: [String: Any]?) {}
}
let customIdentifierRule = WithCustomIdentifierRule()
XCTAssertEqual(customIdentifierRule.identifier, "rule_identifier")
XCTAssertEqual(customIdentifierRule.fileName, "FileName.test")
}
func testNameContainsPunctuations() {
class NameHasPunctuationsRule : Rule {
var name: String {
return "(I'am the one with the force) May the Force be with y'all, always!"
}
var description: String { return "" }
var additionalDocument: String { return "" }
func emitIssue(_: Issue) {}
func inspect(_: ASTContext, configurations: [String: Any]?) {}
}
let may4Rule = NameHasPunctuationsRule()
XCTAssertEqual(
may4Rule.identifier,
"iam_the_one_with_the_force_may_the_force_be_with_yall_always")
XCTAssertEqual(
may4Rule.fileName,
"IamtheonewiththeforceMaytheForcebewithyallalwaysRule.swift")
}
static var allTests = [
("testDefaultImplementations", testDefaultImplementations),
("testWhiteSpaces", testWhiteSpaces),
("testIdentifierImplementation", testIdentifierImplementation),
("testNameContainsPunctuations", testNameContainsPunctuations),
]
}
| apache-2.0 | 4731dd8085ff3ff70bcdccb46535c22f | 32.901961 | 83 | 0.697513 | 4.743484 | false | true | false | false |
february29/Learning | swift/Fch_Contact/Fch_Contact/AppClasses/View/RightMenuViewTableViewCell.swift | 1 | 1871 | //
// RightMenuViewTableViewCell.swift
// Fch_Contact
//
// Created by bai on 2017/12/22.
// Copyright © 2017年 北京仙指信息技术有限公司. All rights reserved.
//
import UIKit
import SnapKit
class RightMenuViewTableViewCell: BBaseTableViewCell {
var iconImageView:UIImageView?
var nameLable:UILabel?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.backgroundColor = UIColor.clear;
iconImageView = UIImageView();
self.contentView.addSubview(iconImageView!);
iconImageView?.snp.makeConstraints({ (make) in
make.left.equalTo(self.contentView).offset(10);
make.centerY.equalTo(self.contentView);
make.width.height.equalTo(17);
})
nameLable = UILabel();
nameLable?.setTextFontSize(type: .primary);
nameLable?.setTextColor(.primary);
// nameLable?.font = UIFont.systemFont(ofSize: 13);
self.contentView.addSubview(nameLable!);
// nameLable?.textAlignment = .center;
nameLable?.snp.makeConstraints({ (make) in
make.left.equalTo(iconImageView!.snp.right).offset(10);
make.right.equalTo(self.contentView).offset(-5);
make.top.bottom.equalTo(self.contentView);
make.height.greaterThanOrEqualTo(30);
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | c6b239d1588ae7afb8dc0a5ba6c7e8c9 | 29.229508 | 74 | 0.63449 | 4.764858 | false | false | false | false |
LimCrazy/SwiftProject3.0-Master | SwiftPreject-Master/SwiftPreject-Master/Class/Login&Register/ViewController/RegisterVC.swift | 1 | 1628 | //
// RegisterVC.swift
// SwiftPreject-Master
//
// Created by lim on 2016/12/11.
// Copyright © 2016年 Lim. All rights reserved.
//
import UIKit
class RegisterVC: UIViewController {
@IBOutlet weak var iphoneNum: UITextField!
@IBOutlet weak var verificationCode: UITextField!
@IBOutlet weak var backView: UIImageView!
@IBOutlet weak var isShow: UIButton!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var registerBtn: UIButton!
@IBOutlet weak var SendVerificationCodeBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() -> () {
self.navigationItem.title = "手机注册"
//设置标题颜色
let dict = [NSForegroundColorAttributeName:UIColor.black,NSFontAttributeName:UIFont.systemFont(ofSize: 20)]
//修改导航栏文字颜色
self.navigationController?.navigationBar.titleTextAttributes = dict
//34 225 164
backView.backgroundColor = UIColor.init(red: 26/255.0, green: 202/255.0, blue: 156/255.0, alpha: 1.0);
registerBtn.layer.cornerRadius = registerBtn.frame.size.height / 2
}
//FIXME:密码是否可见
@IBAction func isShowBtn(_ sender: UIButton) {
}
//FIXME:注册
@IBAction func registerBtn(_ sender: UIButton) {
}
//FIXME:发送验证码
@IBAction func sendVerificationCodeBtn(_ sender: UIButton) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | e7ef5542a62fa74b6061c47ead22fa5c | 28.45283 | 115 | 0.65663 | 4.485632 | false | false | false | false |
EugeneVegner/sws-copyleaks-sdk-test | Example/PlagiarismChecker/SupportedFileTypesViewController.swift | 1 | 4101 | /*
* The MIT License(MIT)
*
* Copyright(c) 2016 Copyleaks LTD (https://copyleaks.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
import PlagiarismChecker
class SupportedFileTypesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var tableView: UITableView!
var source : NSDictionary = NSDictionary()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Supported File Types"
getSupportedFileTypes()
}
func getSupportedFileTypes() {
if activityIndicator.isAnimating() {
return
}
activityIndicator.startAnimating()
let cloud = CopyleaksCloud(.Businesses)
cloud.supportedFileTypes { (result) in
self.activityIndicator.stopAnimating()
if result.isSuccess {
print(result.value)
if let dic = result.value as? NSDictionary {
self.source = dic
}
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
} else {
Alert("Error", message: result.error?.localizedFailureReason ?? "Unknown error")
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return source.allKeys.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let key = source.allKeys[section] as? String {
if let values = source[key] as? NSArray {
return values.count
}
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FileTypeCell", forIndexPath: indexPath)
if let key = source.allKeys[indexPath.section] as? String {
if let values = source[key] as? NSArray {
cell.textLabel?.text = values[indexPath.row] as? String
}
}
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return source.allKeys[section] as? String
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 5102547341bc34c607ebf3961c4bba31 | 34.353448 | 109 | 0.640819 | 5.367801 | false | false | false | false |
LeeShiYoung/LSYWeibo | LSYWeiBo/Emoji/EmoticonPackage.swift | 1 | 8178 | //
// Emoticons.swift
// LSYWeiBo
//
// Created by 李世洋 on 16/5/23.
// Copyright © 2016年 李世洋. All rights reserved.
//
import UIKit
import HYLabel
class EmoticonPackage: NSObject {
var id: String?
var group_name_cn : String?
var emoticons: [Emoticon]?
// 单例
static let emptionsPackageManger: [EmoticonPackage] = EmoticonPackage.loadEmoticonsPackage()
// 获取带表情的字符串
class func emoticonAttributedString(str: String) -> NSAttributedString?
{
do {
let attStr = NSMutableAttributedString(string: str)
let pattern = "\\[.*?\\]"
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
let result = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSRange(0..<str.characters.count))
var count = result.count
while count > 0 {
count -= 1
let checkingResult = result[count]
let tempStr = (str as NSString).substringWithRange(checkingResult.range)
if let emtion = searchEmotions(tempStr) {
let attributedStr = EmojiTextAttachment.emojiAttachment(emtion, font: UIFont.systemFontOfSize(17))
attStr.replaceCharactersInRange(checkingResult.range, withAttributedString: attributedStr)
}
}
return attStr
} catch {
return nil
}
}
// 根据表情chs 查找 Emoticon
class func searchEmotions(str: String) -> Emoticon? {
var emoti: Emoticon?
for packge in EmoticonPackage.emptionsPackageManger
{
emoti = packge.emoticons?.filter({ (element) -> Bool in
return element.chs == str
}).last
if emoti != nil{
break
}
}
return emoti
}
private class func loadEmoticonsPackage() -> [EmoticonPackage] {
let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")!
let dictionary = NSDictionary(contentsOfFile: path)!
let packages = dictionary["packages"] as! [[String: AnyObject]]
// 所有表情文件放进一个数组
var infos = [EmoticonPackage]()
// 创建最近组
let pk = EmoticonPackage(id: "")
pk.group_name_cn = "最近"
pk.emoticons = [Emoticon]()
pk.appendEmtyEmoticons()
infos.append(pk)
// 正常的组(默认 emoji 浪小花...)
for elem in packages {
// 保存 id
let package = EmoticonPackage(id: elem["id"] as! String)
// 加载emoticons
package.loadEmoticons()
package.appendEmtyEmoticons()
infos.append(package)
}
return infos
}
func loadEmoticons() {
emoticons = [Emoticon]()
let emtionDic = emoticonPath(id)
group_name_cn = emtionDic["group_name_cn"] as? String
let emtionsArr = emtionDic["emoticons"] as! [[String: String]]
var index = 0
for emticion in emtionsArr {
if index == 20
{
emoticons?.append(Emoticon(removeBtn: true))
index = 0
}
// 初始化 Emoticon
emoticons?.append(Emoticon(dict: emticion, id: id!))
index += 1
}
}
func appendEmtyEmoticons()
{
let count = emoticons!.count % 21
for _ in count..<20
{
emoticons?.append(Emoticon(removeBtn: false))
}
emoticons?.append(Emoticon(removeBtn: true))
}
// 最近使用表情
func latelyUse(emoticon: Emoticon) {
let contains = emoticons!.contains(emoticon)
if emoticon.removeBtn {
return
}
// 添加
if !contains {
// 移除删除按钮
emoticons?.removeLast()
emoticons?.append(emoticon)
}
// 排序
var sortEms = emoticons?.sort{ $0.times > $1.times }
if !contains {
sortEms?.removeLast()
// 添加删除
sortEms?.append(Emoticon(removeBtn: true))
}
emoticons = sortEms
}
// bundle 根文件路径
class func bundlePath() -> NSString {
return (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons.bundle")
}
// 表情文件夹路径
func emoticonPath(id: String!) -> [String: AnyObject] {
let path = ((EmoticonPackage.bundlePath() as NSString).stringByAppendingPathComponent(id) as NSString).stringByAppendingPathComponent("info.plist")
let emoticonDic = NSDictionary(contentsOfFile: path)!
return emoticonDic as! [String : AnyObject]
}
init(id: String) {
self.id = id
}
}
class Emoticon: NSObject {
// 记录使用频率
var times = 0
// 系统emoji
var code: String?{
didSet{
let sca = NSScanner(string: code!)
var pointer: UInt32 = 0
sca.scanHexInt(&pointer)
emojiStr = "\(Character(UnicodeScalar(pointer)))"
}
}
var type: String?
// emoji 字符串
var emojiStr: String?
// 表情文件夹id
var id: String?
// 文字
var chs: String?
var png: String? {
didSet{
pngPath = (EmoticonPackage.bundlePath().stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent(png!)
}
}
// png表情路径
var pngPath: String?
// 删除按钮
var removeBtn: Bool = false
init(removeBtn: Bool) {
super.init()
self.removeBtn = removeBtn
}
init(dict: [String: AnyObject], id: String) {
super.init()
self.id = id
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
extension HYLabel {
func hy_emoticonAttributedString(text: String, callBack:() -> ()) {
dispatch_async(queue) {
do {
let attStr = NSMutableAttributedString(string: text)
let pattern = "\\[.*?\\]"
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
let result = regex.matchesInString(text, options: NSMatchingOptions(rawValue: 0), range: NSRange(0..<text.characters.count))
var count = result.count
while count > 0 {
count -= 1
let checkingResult = result[count]
let tempStr = (text as NSString).substringWithRange(checkingResult.range)
if let emtion = EmoticonPackage.searchEmotions(tempStr) {
let attributedStr = EmojiTextAttachment.emojiAttachment(emtion, font: UIFont.systemFontOfSize(17))
attStr.replaceCharactersInRange(checkingResult.range, withAttributedString: attributedStr)
}
}
dispatch_async(dispatch_get_main_queue(), {
self.attributedText = attStr
callBack()
})
} catch {
dispatch_async(dispatch_get_main_queue(), {
self.attributedText = nil
callBack()
})
}
}
}
}
| artistic-2.0 | 30b133ab2f1fa3181bf22a24f67896c2 | 28.095238 | 155 | 0.527257 | 5.246367 | false | false | false | false |
ta2yak/FloatLabelFields | FloatLabelExample/FloatLabelExample/ViewController.swift | 1 | 917 | //
// ViewController.swift
// FloatLabelExample
//
// Created by Fahim Farook on 28/11/14.
// Copyright (c) 2014 RookSoft Ltd. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
@IBOutlet var vwAddress:FloatLabelTextView!
@IBOutlet var vwHolder:UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Set font for placeholder of a FloatLabelTextView
if let fnt = UIFont(name:"Zapfino", size:12) {
vwAddress.titleFont = fnt
}
// Set up a FloatLabelTextField via code
let fld = FloatLabelTextField(frame:vwHolder.bounds)
fld.placeholder = "Comments"
// Set font for place holder (only displays in title mode)
if let fnt = UIFont(name:"Zapfino", size:12) {
fld.titleFont = fnt
}
vwHolder.addSubview(fld)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | bf038efce09281b2f18d0cbc4bc7ea70 | 24.472222 | 60 | 0.7241 | 3.596078 | false | false | false | false |
simorgh3196/Twifter | Sources/Twifter/Networking/OAuthSigner.swift | 1 | 5133 | //
// OAuthSigner.swift
// Core
//
// Created by Tomoya Hayakawa on 2020/03/26.
// Copyright © 2020 simorgh3196. All rights reserved.
//
import Foundation
public struct OAuthSigner {
public let credential: Credential
public var accessToken: AccessToken?
var signatureKey: String {
"\(credential.consumerSecret.urlEncoded)&\(accessToken?.oauthTokenSecret.urlEncoded ?? "")"
}
private let timestampGenerator: (() -> TimeInterval)
private let nonceGenerator: (() -> String)
public init(credential: Credential, accessToken: AccessToken?) {
self.credential = credential
self.accessToken = accessToken
self.timestampGenerator = { Date().timeIntervalSince1970 }
self.nonceGenerator = { UUID().uuidString }
}
init(credential: Credential,
accessToken: AccessToken?,
timestampGenerator: @escaping (() -> TimeInterval),
nonceGenerator: @escaping (() -> String)) {
self.credential = credential
self.accessToken = accessToken
self.timestampGenerator = timestampGenerator
self.nonceGenerator = nonceGenerator
}
public func sign<R: Request>(to request: R) -> URLRequest {
var urlRequest = request.buildURLRequest()
var parameters = makeParameters(for: request)
parameters["oauth_signature"] = makeSignature(for: request, parameters: parameters)
let value = parameters
.filter { $0.key.contains("oauth_") }
.sorted(by: <)
.map { "\($0.key)=\"\($0.value.urlEncoded)\"" }
.joined(separator: ", ")
urlRequest.setValue("OAuth \(value)", forHTTPHeaderField: "Authorization")
return urlRequest
}
}
extension OAuthSigner {
func makeParameters<R: Request>(for request: R) -> [String: String] {
let bodyParams = request.bodyParameters?.mapValues { "\($0)" } ?? [:]
let queryParams = request.queryParameters ?? [:]
let oauthParams = [
"oauth_consumer_key": credential.consumerKey,
"oauth_nonce": nonceGenerator(),
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": "\(Int(timestampGenerator()))",
"oauth_version": "1.0"
]
let accessTokenParams = accessToken.map { ["oauth_token": $0.oauthToken] } ?? [:]
return bodyParams
.merging(queryParams, uniquingKeysWith: { _, new in new })
.merging(oauthParams, uniquingKeysWith: { _, new in new })
.merging(accessTokenParams, uniquingKeysWith: { _, new in new })
}
func makeSignature<R: Request>(for request: R, parameters: [String: String]) -> String {
let parameterString = collect(parameters: parameters)
let signatureBaseString = signatureBase(for: request, parameterString: parameterString)
let signature = calculateSignature(base: signatureBaseString, key: signatureKey)
return signature
}
func collect(parameters: [String: String]) -> String {
// These values need to be encoded into a single string, which will be used later on.
// The process to build the string is very specific:
// 1. Percent encode every key and value that will be signed.
// 2. Sort the list of parameters alphabetically [1] by encoded key [2].
// 3. For each key/value pair:
// 4. Append the encoded key to the output string.
// 5. Append the ‘=’ character to the output string.
// 6. Append the encoded value to the output string.
// 7. If there are more key/value pairs remaining, append a ‘&’ character to the output string.
let parameterString = parameters
.reduce(into: [:]) { $0[$1.key.urlEncoded] = $1.value.urlEncoded }
.sorted(by: <)
.map { "\($0.key)=\($0.value)" }
.joined(separator: "&")
return parameterString
}
func signatureBase<R: Request>(for request: R, parameterString: String) -> String {
// To encode the HTTP method, base URL, and parameter string into a single string:
// 1. Convert the HTTP Method to uppercase and set the output string equal to this value.
// 2. Append the ‘&’ character to the output string.
// 3. Percent encode the URL and append it to the output string.
// 4. Append the ‘&’ character to the output string.
// 5. Percent encode the parameter string and append it to the output string.
let methodString = request.method.value
let encodedURLString = request.requestURL.absoluteString.urlEncoded
let encodedParameterString = parameterString.urlEncoded
let signatureBaseString = "\(methodString)&\(encodedURLString)&\(encodedParameterString)"
return signatureBaseString
}
func calculateSignature(base: String, key: String) -> String {
let signatureData = HMAC(base).data(withKey: key, algorithm: .sha1)
let signatureBase64 = signatureData.base64EncodedString()
return signatureBase64
}
}
| mit | ce2bbce38cfe845f29d94927841e23df | 39.603175 | 107 | 0.632916 | 4.772388 | false | false | false | false |
Ajunboys/actor-platform | actor-apps/app-ios/Actor/AppDelegate.swift | 23 | 11417 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import Foundation
@objc class AppDelegate : UIResponder, UIApplicationDelegate {
// MARK: -
// MARK: Private vars
var window : UIWindow?
private var binder = Binder()
private var syncTask: UIBackgroundTaskIdentifier?
private var completionHandler: ((UIBackgroundFetchResult) -> Void)?
// MARK: -
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
var config = MSG.config
// Apply crash logging
if config.mint != nil {
Mint.sharedInstance().initAndStartSession(config.mint!)
}
// Register hockey app
if config.hockeyapp != nil {
BITHockeyManager.sharedHockeyManager().configureWithIdentifier(config.hockeyapp!)
BITHockeyManager.sharedHockeyManager().disableCrashManager = true
BITHockeyManager.sharedHockeyManager().updateManager.checkForUpdateOnLaunch = true
BITHockeyManager.sharedHockeyManager().startManager()
BITHockeyManager.sharedHockeyManager().authenticator.authenticateInstallation()
}
// Register notifications
// Register always even when not enabled in build for local notifications
if application.respondsToSelector("registerUserNotificationSettings:") {
let types: UIUserNotificationType = (.Alert | .Badge | .Sound)
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
}
// Apply styles
MainAppTheme.applyAppearance(application)
// Bind Messenger LifeCycle
binder.bind(MSG.getAppState().getIsSyncing(), closure: { (value: JavaLangBoolean?) -> () in
if value!.booleanValue() {
if self.syncTask == nil {
self.syncTask = application.beginBackgroundTaskWithName("Background Sync", expirationHandler: { () -> Void in
})
}
} else {
if self.syncTask != nil {
application.endBackgroundTask(self.syncTask!)
self.syncTask = nil
}
if self.completionHandler != nil {
self.completionHandler!(UIBackgroundFetchResult.NewData)
self.completionHandler = nil
}
}
})
// Bind badge counter
binder.bind(MSG.getAppState().getGlobalCounter(), closure: { (value: JavaLangInteger?) -> () in
application.applicationIconBadgeNumber = Int((value!).integerValue)
})
// Creating main window
window = UIWindow(frame: UIScreen.mainScreen().bounds);
window?.backgroundColor = UIColor.whiteColor()
if (MSG.isLoggedIn()) {
onLoggedIn(false)
} else {
// Create root layout for login
let phoneController = AuthPhoneViewController()
var loginNavigation = AANavigationController(rootViewController: phoneController)
loginNavigation.navigationBar.tintColor = Resources.BarTintColor
loginNavigation.makeBarTransparent()
window?.rootViewController = loginNavigation
window?.makeKeyAndVisible();
}
return true;
}
func onLoggedIn(isAfterLogin: Bool) {
// Create root layout for app
MSG.onAppVisible()
var rootController : UIViewController? = nil
if (isIPad) {
var splitController = MainSplitViewController()
splitController.viewControllers = [MainTabViewController(isAfterLogin: isAfterLogin), NoSelectionViewController()]
rootController = splitController
} else {
var tabController = MainTabViewController(isAfterLogin: isAfterLogin)
binder.bind(MSG.getAppState().getIsAppLoaded(), valueModel2: MSG.getAppState().getIsAppEmpty()) { (loaded: JavaLangBoolean?, empty: JavaLangBoolean?) -> () in
if (empty!.booleanValue()) {
if (loaded!.booleanValue()) {
tabController.showAppIsEmptyPlaceholder()
} else {
tabController.showAppIsSyncingPlaceholder()
}
} else {
tabController.hidePlaceholders()
}
}
rootController = tabController
}
window?.rootViewController = rootController!
window?.makeKeyAndVisible();
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
println("open url: \(url)")
if (url.scheme == "actor") {
if (url.host == "invite") {
if (MSG.isLoggedIn()) {
var token = url.query?.componentsSeparatedByString("=")[1]
if token != nil {
UIAlertView.showWithTitle(nil, message: localized("GroupJoinMessage"), cancelButtonTitle: localized("AlertNo"), otherButtonTitles: [localized("GroupJoinAction")], tapBlock: { (view, index) -> Void in
if (index == view.firstOtherButtonIndex) {
self.execute(MSG.joinGroupViaLinkCommandWithUrl(token), successBlock: { (val) -> Void in
var groupId = val as! JavaLangInteger
self.openChat(AMPeer.groupWithInt(groupId.intValue))
}, failureBlock: { (val) -> Void in
if let res = val as? AMRpcException {
if res.getTag() == "USER_ALREADY_INVITED" {
UIAlertView.showWithTitle(nil, message: localized("ErrorAlreadyJoined"), cancelButtonTitle: localized("AlertOk"), otherButtonTitles: nil, tapBlock: nil)
return
}
}
UIAlertView.showWithTitle(nil, message: localized("ErrorUnableToJoin"), cancelButtonTitle: localized("AlertOk"), otherButtonTitles: nil, tapBlock: nil)
})
}
})
}
}
return true
}
}
return false
}
func applicationWillEnterForeground(application: UIApplication) {
MSG.onAppVisible();
// Hack for resync phone book
MSG.onPhoneBookChanged()
}
func applicationDidEnterBackground(application: UIApplication) {
MSG.onAppHidden();
if MSG.isLoggedIn() {
var completitionTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
completitionTask = application.beginBackgroundTaskWithName("Completition", expirationHandler: { () -> Void in
application.endBackgroundTask(completitionTask)
completitionTask = UIBackgroundTaskInvalid
})
// Wait for 40 secs before app shutdown
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(40.0 * Double(NSEC_PER_SEC))), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
application.endBackgroundTask(completitionTask)
completitionTask = UIBackgroundTaskInvalid
}
}
}
// MARK: -
// MARK: Notifications
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenString = "\(deviceToken)".stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString("<", withString: "").stringByReplacingOccurrencesOfString(">", withString: "")
var config = MSG.config
if config.pushId != nil {
MSG.registerApplePushWithApnsId(jint(config.pushId!), withToken: tokenString)
}
if config.mixpanel != nil {
Mixpanel.sharedInstance().people.addPushDeviceToken(deviceToken)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if !MSG.isLoggedIn() {
completionHandler(UIBackgroundFetchResult.NoData)
return
}
self.completionHandler = completionHandler
}
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if !MSG.isLoggedIn() {
completionHandler(UIBackgroundFetchResult.NoData)
return
}
self.completionHandler = completionHandler
}
func execute(command: AMCommand) {
execute(command, successBlock: nil, failureBlock: nil)
}
func execute(command: AMCommand, successBlock: ((val: Any?) -> Void)?, failureBlock: ((val: Any?) -> Void)?) {
var window = UIApplication.sharedApplication().windows[1] as! UIWindow
var hud = MBProgressHUD(window: window)
hud.mode = MBProgressHUDMode.Indeterminate
hud.removeFromSuperViewOnHide = true
window.addSubview(hud)
window.bringSubviewToFront(hud)
hud.show(true)
command.startWithCallback(CocoaCallback(result: { (val:Any?) -> () in
dispatch_async(dispatch_get_main_queue(), {
hud.hide(true)
successBlock?(val: val)
})
}, error: { (val) -> () in
dispatch_async(dispatch_get_main_queue(), {
hud.hide(true)
failureBlock?(val: val)
})
}))
}
func openChat(peer: AMPeer) {
for i in UIApplication.sharedApplication().windows {
var root = (i as! UIWindow).rootViewController
if let tab = root as? MainTabViewController {
var controller = tab.viewControllers![tab.selectedIndex] as! AANavigationController
var destController = ConversationViewController(peer: peer)
destController.hidesBottomBarWhenPushed = true
controller.pushViewController(destController, animated: true)
return
} else if let split = root as? MainSplitViewController {
split.navigateDetail(ConversationViewController(peer: peer))
return
}
}
}
} | mit | cc4938c2a55a24b092e442459d57812c | 41.924812 | 223 | 0.577998 | 6.238798 | false | false | false | false |
devgabrielcoman/woodhouse | Pod/Classes/Services/Google/GoogleDetails.swift | 1 | 1416 | //
// GoogleDetails.swift
// Pods
//
// Created by Gabriel Coman on 10/04/2016.
//
//
import UIKit
public class GoogleDetails: NSObject, ServiceProtocol {
private var placeId: String = ""
private var dataService: DataService = DataService()
public override init() {
super.init()
dataService.serviceDelegate = self
dataService.authDelgate = GoogleAuth.sharedInstance
}
func apiurl() -> String {
return "https://maps.googleapis.com/maps/api/place/details/json"
}
func method() -> String {
return "GET"
}
func query() -> [String : AnyObject]? {
return [
"placeid":placeId
]
}
func header() -> [String : AnyObject]? {
return nil
}
func body() -> [String : AnyObject]? {
return nil
}
func process(JSON: AnyObject) -> AnyObject {
if let detail = JSON as? [String:AnyObject],
let final = detail["result"] as? [String:AnyObject] {
return final
}
return [:]
}
public func search(placeid p: String) {
placeId = p
dataService.execute() { result in
print(result)
if let result = result as? [String: AnyObject] {
print("###################")
print(mapGoogleToOMenu(result))
}
}
}
}
| gpl-3.0 | 65cd2c4b41e5163dfe8c20d6645e65f7 | 21.83871 | 72 | 0.524011 | 4.495238 | false | false | false | false |
kickstarter/ios-oss | KsApi/mutations/templates/query/FetchUserBackingsQueryTemplate.swift | 1 | 6541 | import Apollo
@testable import KsApi
public enum FetchUserBackingsQueryTemplate {
case valid
case errored
var data: GraphAPI.FetchUserBackingsQuery.Data {
switch self {
case .valid:
return GraphAPI.FetchUserBackingsQuery.Data(unsafeResultMap: self.validResultMap)
case .errored:
return GraphAPI.FetchUserBackingsQuery.Data(unsafeResultMap: self.erroredResultMap)
}
}
// MARK: Private Properties
private var validResultMap: [String: Any?] {
[
"data": [
"me": [
"__typename": "User",
"backings": [
"__typename": "UserBackingsConnection",
"nodes": [[
"__typename": "Backing",
"addOns": [
"__typename": "RewardTotalCountConnection",
"nodes": []
],
"errorReason": "Your card was declined.",
"amount": [
"__typename": "Money",
"amount": "1.0",
"currency": "USD",
"symbol": "$"
],
"backer": [
"__typename": "User",
"chosenCurrency": "USD",
"email": "[email protected]",
"hasPassword": true,
"id": "VXNlci0xNDcwOTUyNTQ1",
"imageUrl": "https://ksr-qa-ugc.imgix.net/missing_user_avatar.png?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=&auto=format&frame=1&q=92&s=e17a7b6f853aa6320cfe67ee783eb3d8",
"isAppleConnected": false,
"isCreator": false,
"isDeliverable": true,
"isEmailVerified": true,
"name": "Hari Singh",
"uid": "1470952545"
],
"backerCompleted": false,
"bonusAmount": [
"__typename": "Money",
"amount": "1.0",
"currency": "USD",
"symbol": "$"
],
"cancelable": false,
"creditCard": [
"__typename": "CreditCard",
"expirationDate": "2023-01-01",
"id": "69021312",
"lastFour": "0341",
"paymentType": "CREDIT_CARD",
"state": "ACTIVE",
"type": "VISA"
],
"id": "QmFja2luZy0xNDQ5NTI3NTQ=",
"location": nil,
"pledgedOn": 1_627_592_045,
"project": [
"__typename": "Project",
"backersCount": 4,
"category": [
"__typename": "Category",
"id": "Q2F0ZWdvcnktMjg1",
"name": "Plays",
"parentCategory": [
"__typename": "Category",
"id": "Q2F0ZWdvcnktMTc=",
"name": "Theater"
]
],
"canComment": false,
"country": [
"__typename": "Country",
"code": "US",
"name": "the United States"
],
"creator": [
"__typename": "User",
"chosenCurrency": nil,
"email": "[email protected]",
"hasPassword": nil,
"id": "VXNlci03NDAzNzgwNzc=",
"imageUrl": "https://ksr-qa-ugc.imgix.net/assets/033/406/310/0643a06ea18a1462cc8466af5718d9ef_original.jpeg?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=1620659730&auto=format&frame=1&q=92&s=86608b67fc0b349026722388df683a89",
"isAppleConnected": nil,
"isCreator": nil,
"isDeliverable": true,
"isEmailVerified": true,
"name": "Afees Lawal",
"uid": "740378077"
],
"currency": "USD",
"deadlineAt": 1_683_676_800,
"description": "test blurb",
"finalCollectionDate": nil,
"fxRate": 1.0,
"friends": [
"__typename": "ProjectBackerFriendsConnection",
"nodes": []
],
"goal": [
"__typename": "Money",
"amount": "19974.0",
"currency": "USD",
"symbol": "$"
],
"image": [
"__typename": "Photo",
"id": "UGhvdG8tMTEyNTczMzY=",
"url": "https://ksr-qa-ugc.imgix.net/assets/011/257/336/a371c892fb6e936dc1824774bea14a1b_original.jpg?ixlib=rb-4.0.2&crop=faces&w=1024&h=576&fit=crop&v=1463673674&auto=format&frame=1&q=92&s=87715e16f6e9b5a26afa42ea54a33fcc"
],
"isProjectWeLove": false,
"isWatched": false,
"launchedAt": 1_620_662_504,
"location": [
"__typename": "Location",
"country": "NG",
"countryName": "Nigeria",
"displayableName": "Nigeria",
"id": "TG9jYXRpb24tMjM0MjQ5MDg=",
"name": "Nigeria"
],
"name": "Mouth Trumpet Robot Cats",
"pid": 1_234_627_104,
"pledged": [
"__typename": "Money",
"amount": "65.0",
"currency": "USD",
"symbol": "$"
],
"slug": "afeestest/mouth-trumpet-robot-cats",
"state": "LIVE",
"stateChangedAt": 1_620_662_506,
"url": "https://staging.kickstarter.com/projects/afeestest/mouth-trumpet-robot-cats",
"usdExchangeRate": 1.0
],
"reward": nil,
"sequence": 5,
"shippingAmount": [
"__typename": "Money",
"amount": "0.0",
"currency": "USD",
"symbol": "$"
],
"status": "errored"
]],
"totalCount": 1
],
"id": "VXNlci0xNDcwOTUyNTQ1",
"imageUrl": "https://ksr-qa-ugc.imgix.net/missing_user_avatar.png?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=&auto=format&frame=1&q=92&s=e17a7b6f853aa6320cfe67ee783eb3d8",
"name": "Hari Singh",
"uid": "1470952545"
]
]
]
}
private var erroredResultMap: [String: Any?] {
return [:]
}
}
| apache-2.0 | 783ca416d1e409c6f3fe867957799a33 | 36.377143 | 249 | 0.434643 | 4.037654 | false | false | false | false |
whipsterCZ/WeatherTest | WeatherTest/Classes/Models/Weather.swift | 1 | 3299 | //
// Weather.swift
// WeatherTest
//
// Created by Daniel Kouba on 16/02/15.
// Copyright (c) 2015 Daniel Kouba. All rights reserved.
//
import Foundation
let WEATHER_NA = "?"
let WEATHER_NOT_AVAILABLE = "Not available"
class Weather : NSObject
{
var latLng: String
var type = WEATHER_NOT_AVAILABLE
var tempreatureC = WEATHER_NA
var tempreatureF = WEATHER_NA
var iconImageBig = UIImage()
var iconImage = UIImage()
var iconCode : Int {
set(code) {
iconImageBig = UIImage(named: DI.context.weatherService.iconNameByCode(code, big:true))!
iconImage = UIImage(named: DI.context.weatherService.iconNameByCode(code))!
}
get {
return 0
}
}
var rainPercentage = WEATHER_NA
var rainAmmountMm: Float?
var windDirection = WEATHER_NA
var windSpeedMetric = WEATHER_NA
var windSpeedImperial = WEATHER_NA
var forecastList = [Forecast]()
var lastUpdated:NSDate?
var isFetching = false
init(latLng:String) {
self.latLng = latLng
super.init()
fetchWeather()
}
func fetchWeather()
{
if ( isFetching) {
return
}
let updateInterval = (DI.context.getParameter("weather_update_interval", defaultValue: "1800")! as NSString).doubleValue - 1.0
var timeIntervalSinceNow: Double = 3600 // hodina default
if lastUpdated != nil {
timeIntervalSinceNow = -lastUpdated!.timeIntervalSinceNow
}
if ( timeIntervalSinceNow >= updateInterval || type==WEATHER_NOT_AVAILABLE) {
DI.context.weatherService.fetchWeather(self)
}
}
func weatherStartUpdate() {
isFetching = true
}
func weatherDidUpdate() {
isFetching = false
lastUpdated = NSDate()
NSNotificationCenter.defaultCenter().postNotificationName(RELOAD_NOTIFICATION, object: self)
}
func fahrenheit(celsius: Float) -> Float
{
return (celsius * 1.8) + 32.0
}
func inches(meters:Float) ->Float
{
return meters * 39.3701
}
func miles(km:Float) -> Float
{
return km * 0.621371
}
func tempreature(short:Bool) -> String
{
if ( DI.context.settings.tempreatureUnit == .Celsius ) {
return tempreatureC + ( short ? "°" :"°C" )
} else {
return tempreatureF + ( short ? "°" :"°F" )
}
}
func windSpeed() -> String
{
if ( DI.context.settings.lengthUnit == .Metric ) {
return windSpeedMetric + " m/s"
} else {
return windSpeedImperial + " ml/s"
}
}
func rainAmmount() ->String
{
if ( rainAmmountMm != nil) {
if ( DI.context.settings.lengthUnit == .Metric ) {
return "\(rainAmmountMm!) mm"
} else {
var rainAmmountInches = inches(rainAmmountMm!/1000)
return "\(rainAmmountInches) in"
}
}
return WEATHER_NA
}
func summary()->String
{
return tempreature(false) + " | " + type
}
} | apache-2.0 | f5ca655ba21eaeaa38f13a5de7b4d043 | 23.058394 | 134 | 0.54871 | 4.482993 | false | false | false | false |
mutualmobile/VIPER-SWIFT | VIPER-SWIFT/Classes/AppDependencies.swift | 1 | 1721 | //
// AppDependencies.swift
// VIPER TODO
//
// Created by Conrad Stoll on 6/4/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
import UIKit
class AppDependencies {
var listWireframe = ListWireframe()
init() {
configureDependencies()
}
func installRootViewControllerIntoWindow(_ window: UIWindow) {
listWireframe.presentListInterfaceFromWindow(window)
}
func configureDependencies() {
let coreDataStore = CoreDataStore()
let clock = DeviceClock()
let rootWireframe = RootWireframe()
let listPresenter = ListPresenter()
let listDataManager = ListDataManager()
let listInteractor = ListInteractor(dataManager: listDataManager, clock: clock)
let addWireframe = AddWireframe()
let addInteractor = AddInteractor()
let addPresenter = AddPresenter()
let addDataManager = AddDataManager()
listInteractor.output = listPresenter
listPresenter.listInteractor = listInteractor
listPresenter.listWireframe = listWireframe
listWireframe.addWireframe = addWireframe
listWireframe.listPresenter = listPresenter
listWireframe.rootWireframe = rootWireframe
listDataManager.coreDataStore = coreDataStore
addInteractor.addDataManager = addDataManager
addWireframe.addPresenter = addPresenter
addPresenter.addWireframe = addWireframe
addPresenter.addModuleDelegate = listPresenter
addPresenter.addInteractor = addInteractor
addDataManager.dataStore = coreDataStore
}
}
| mit | fb4b303697838e8fb8bee3dc6af5be3d | 28.672414 | 87 | 0.66473 | 6.518939 | false | false | false | false |
WhisperSystems/Signal-iOS | Signal/src/views/GroupTableViewCell.swift | 1 | 2707 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import UIKit
import SignalServiceKit
@objc class GroupTableViewCell: UITableViewCell {
// MARK: - Dependencies
private var contactsManager: OWSContactsManager {
return Environment.shared.contactsManager
}
// MARK: -
private let avatarView = AvatarImageView()
private let nameLabel = UILabel()
private let subtitleLabel = UILabel()
private let accessoryLabel = UILabel()
@objc var accessoryMessage: String?
init() {
super.init(style: .default, reuseIdentifier: GroupTableViewCell.logTag())
// Font config
nameLabel.font = .ows_dynamicTypeBody
nameLabel.textColor = Theme.primaryColor
subtitleLabel.font = UIFont.ows_regularFont(withSize: 11.0)
subtitleLabel.textColor = Theme.secondaryColor
// Layout
avatarView.autoSetDimension(.width, toSize: CGFloat(kStandardAvatarSize))
avatarView.autoPinToSquareAspectRatio()
let textRows = UIStackView(arrangedSubviews: [nameLabel, subtitleLabel])
textRows.axis = .vertical
textRows.alignment = .leading
let columns = UIStackView(arrangedSubviews: [avatarView, textRows, accessoryLabel])
columns.axis = .horizontal
columns.alignment = .center
columns.spacing = kContactCellAvatarTextMargin
self.contentView.addSubview(columns)
columns.autoPinEdgesToSuperviewMargins()
// Accessory Label
accessoryLabel.font = .ows_mediumFont(withSize: 13)
accessoryLabel.textColor = Theme.middleGrayColor
accessoryLabel.textAlignment = .right
accessoryLabel.isHidden = true
}
required init?(coder aDecoder: NSCoder) {
notImplemented()
}
@objc
public func configure(thread: TSGroupThread) {
OWSTableItem.configureCell(self)
if let groupName = thread.groupModel.groupName, !groupName.isEmpty {
self.nameLabel.text = groupName
} else {
self.nameLabel.text = MessageStrings.newGroupDefaultTitle
}
let groupMembers = thread.groupModel.groupMembers
let groupMemberNames = groupMembers.map { contactsManager.displayName(for: $0) }.joined(separator: ", ")
self.subtitleLabel.text = groupMemberNames
self.avatarView.image = OWSAvatarBuilder.buildImage(thread: thread, diameter: kStandardAvatarSize)
if let accessoryMessage = accessoryMessage, !accessoryMessage.isEmpty {
accessoryLabel.text = accessoryMessage
accessoryLabel.isHidden = false
} else {
accessoryLabel.isHidden = true
}
}
}
| gpl-3.0 | 7a5bc3abe66f91719d56d3a6e0975ba9 | 30.476744 | 112 | 0.679719 | 5.2158 | false | false | false | false |
riehs/on-the-map | On the Map/On the Map/MapViewController.swift | 1 | 2080 | //
// MapViewController.swift
// On the Map
//
// Created by Daniel Riehs on 3/22/15.
// Copyright (c) 2015 Daniel Riehs. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate, ReloadableTab {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
//Sets the map zoom.
mapView?.camera.altitude = 50000000;
//Sets the center of the map.
mapView?.centerCoordinate = CLLocationCoordinate2D(latitude: -3.831239, longitude: -78.183406)
//Adding a link to the annotation requires making the mapView a delegate of MKMapView.
mapView.delegate = self
//Draws the annotations on the map.
reloadViewController()
}
//Opens the mediaURL in Safari when the annotation info box is tapped.
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
UIApplication.shared.openURL(URL(string: view.annotation!.subtitle!!)!)
}
//Adds a "callout" to the annotation info box so that it can be tapped to access the mediaURL.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "MapAnnotation")
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
return view
}
//Required to conform to the ReloadableTab protocol.
func reloadViewController() {
for result in MapPoints.sharedInstance().mapPoints {
//Creates an annotation and coordinate.
let annotation = MKPointAnnotation()
let location = CLLocationCoordinate2D(latitude: result.latitude, longitude: result.longitude)
//Sets the coordinates of the annotation.
annotation.coordinate = location
//Adds a student name and URL to the annotation.
annotation.title = result.fullName
annotation.subtitle = result.mediaURL
//Adds the annotation to the map.
mapView.addAnnotation(annotation)
}
}
}
| mit | d56b279b0cc795db4127d650c67f1d0a | 28.714286 | 126 | 0.751923 | 4.176707 | false | false | false | false |
nathawes/swift | test/IDE/print_ast_tc_decls_errors.swift | 3 | 13498 | // Verify errors in this file to ensure that parse and type checker errors
// occur where we expect them.
// RUN: %target-typecheck-verify-swift -show-diagnostics-after-fatal
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -prefer-type-repr=false > %t.printed.txt
// RUN: %FileCheck %s -strict-whitespace < %t.printed.txt
// RUN: %FileCheck -check-prefix=NO-TYPEREPR %s -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -prefer-type-repr=true > %t.printed.txt
// RUN: %FileCheck %s -strict-whitespace < %t.printed.txt
// RUN: %FileCheck -check-prefix=TYPEREPR %s -strict-whitespace < %t.printed.txt
//===---
//===--- Helper types.
//===---
class FooClass {}
class BarClass {}
protocol FooProtocol {}
protocol BarProtocol {}
protocol BazProtocol { func baz() }
protocol QuxProtocol {
associatedtype Qux
}
class FooProtocolImpl : FooProtocol {}
class FooBarProtocolImpl : FooProtocol, BarProtocol {}
class BazProtocolImpl : BazProtocol { func baz() {} }
//===---
//===--- Import printing.
//===---
import not_existent_module_a // expected-error{{no such module 'not_existent_module_a'}}
// CHECK: {{^}}import not_existent_module_a{{$}}
import not_existent_module_a.submodule // expected-error{{no such module}}
// CHECK-NEXT: {{^}}import not_existent_module_a.submodule{{$}}
@_exported import not_existent_module_b // expected-error{{no such module 'not_existent_module_b'}}
// CHECK-NEXT: {{^}}@_exported import not_existent_module_b{{$}}
@_exported import not_existent_module_b.submodule // expected-error{{no such module}}
// CHECK-NEXT: {{^}}@_exported import not_existent_module_b.submodule{{$}}
import struct not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import struct not_existent_module_c.foo{{$}}
import class not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import class not_existent_module_c.foo{{$}}
import enum not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import enum not_existent_module_c.foo{{$}}
import protocol not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import protocol not_existent_module_c.foo{{$}}
import var not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import var not_existent_module_c.foo{{$}}
import func not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}}
// CHECK-NEXT: {{^}}import func not_existent_module_c.foo{{$}}
//===---
//===--- Inheritance list in structs.
//===---
struct StructWithInheritance1 : FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}}
// NO-TYPEREPR: {{^}}struct StructWithInheritance1 : <<error type>> {{{$}}
// TYPEREPR: {{^}}struct StructWithInheritance1 : FooNonExistentProtocol {{{$}}
struct StructWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}}
// NO-TYPEREPR: {{^}}struct StructWithInheritance2 : <<error type>>, <<error type>> {{{$}}
// TYPEREPR: {{^}}struct StructWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}}
//===---
//===--- Inheritance list in classes.
//===---
class ClassWithInheritance1 : FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}}
// NO-TYREPR: {{^}}class ClassWithInheritance1 : <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance1 : FooNonExistentProtocol {{{$}}
class ClassWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}}
// NO-TYREPR: {{^}}class ClassWithInheritance2 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}}
class ClassWithInheritance3 : FooClass, FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}}
// NO-TYREPR: {{^}}class ClassWithInheritance3 : FooClass, <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance3 : FooClass, FooNonExistentProtocol {{{$}}
class ClassWithInheritance4 : FooProtocol, FooClass {} // expected-error {{superclass 'FooClass' must appear first in the inheritance clause}} {{31-31=FooClass, }} {{42-52=}}
// CHECK: {{^}}class ClassWithInheritance4 : FooProtocol, FooClass {{{$}}
class ClassWithInheritance5 : FooProtocol, BarProtocol, FooClass {} // expected-error {{superclass 'FooClass' must appear first in the inheritance clause}} {{31-31=FooClass, }} {{55-65=}}
// CHECK: {{^}}class ClassWithInheritance5 : FooProtocol, BarProtocol, FooClass {{{$}}
class ClassWithInheritance6 : FooClass, BarClass {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}}
// NO-TYREPR: {{^}}class ClassWithInheritance6 : FooClass, <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance6 : FooClass, BarClass {{{$}}
class ClassWithInheritance7 : FooClass, BarClass, FooProtocol {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}}
// NO-TYREPR: {{^}}class ClassWithInheritance7 : FooClass, <<error type>>, FooProtocol {{{$}}
// TYREPR: {{^}}class ClassWithInheritance7 : FooClass, BarClass, FooProtocol {{{$}}
class ClassWithInheritance8 : FooClass, BarClass, FooProtocol, BarProtocol {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}}
// NO-TYREPR: {{^}}class ClassWithInheritance8 : FooClass, <<error type>>, FooProtocol, BarProtocol {{{$}}
// TYREPR: {{^}}class ClassWithInheritance8 : FooClass, BarClass, FooProtocol, BarProtocol {{{$}}
class ClassWithInheritance9 : FooClass, BarClass, FooProtocol, BarProtocol, FooNonExistentProtocol {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}} expected-error {{cannot find type 'FooNonExistentProtocol' in scope}}
// NO-TYREPR: {{^}}class ClassWithInheritance9 : FooClass, <<error type>>, FooProtocol, BarProtocol, <<error type>> {{{$}}
// TYREPR: {{^}}class ClassWithInheritance9 : FooClass, BarClass, FooProtocol, BarProtocol, FooNonExistentProtocol {{{$}}
//===---
//===--- Inheritance list in enums.
//===---
enum EnumWithInheritance1 : FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{an enum with no cases}}
// NO-TYREPR: {{^}}enum EnumWithInheritance1 : <<error type>> {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance1 : FooNonExistentProtocol {{{$}}
enum EnumWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}} expected-error {{an enum with no cases}}
// NO-TYREPR: {{^}}enum EnumWithInheritance2 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}}
enum EnumWithInheritance3 : FooClass { case X } // expected-error {{raw type 'FooClass' is not expressible by a string, integer, or floating-point literal}}
// expected-error@-1{{'EnumWithInheritance3' declares raw type 'FooClass', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-2{{RawRepresentable conformance cannot be synthesized because raw type 'FooClass' is not Equatable}}
// NO-TYREPR: {{^}}enum EnumWithInheritance3 : <<error type>> {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance3 : FooClass {{{$}}
enum EnumWithInheritance4 : FooClass, FooProtocol { case X } // expected-error {{raw type 'FooClass' is not expressible by a string, integer, or floating-point literal}}
// expected-error@-1{{'EnumWithInheritance4' declares raw type 'FooClass', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-2{{RawRepresentable conformance cannot be synthesized because raw type 'FooClass' is not Equatable}}
// NO-TYREPR: {{^}}enum EnumWithInheritance4 : <<error type>>, FooProtocol {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance4 : FooClass, FooProtocol {{{$}}
enum EnumWithInheritance5 : FooClass, BarClass { case X } // expected-error {{raw type 'FooClass' is not expressible by a string, integer, or floating-point literal}} expected-error {{multiple enum raw types 'FooClass' and 'BarClass'}}
// expected-error@-1{{'EnumWithInheritance5' declares raw type 'FooClass', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-2{{RawRepresentable conformance cannot be synthesized because raw type 'FooClass' is not Equatable}}
// NO-TYREPR: {{^}}enum EnumWithInheritance5 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}enum EnumWithInheritance5 : FooClass, BarClass {{{$}}
//===---
//===--- Inheritance list in protocols.
//===---
protocol ProtocolWithInheritance1 : FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance1 : <<error type>> {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance1 : FooNonExistentProtocol {{{$}}
protocol ProtocolWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance2 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}}
protocol ProtocolWithInheritance3 : FooClass {}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance3 : FooClass {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance3 : FooClass {{{$}}
protocol ProtocolWithInheritance4 : FooClass, FooProtocol {}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance4 : FooClass, FooProtocol {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance4 : FooClass, FooProtocol {{{$}}
protocol ProtocolWithInheritance5 : FooClass, BarClass {} // expected-error{{multiple inheritance from classes 'FooClass' and 'BarClass'}} expected-error{{protocol 'ProtocolWithInheritance5' cannot require 'Self' to be a subclass of both 'BarClass' and 'FooClass'}} // expected-note{{superclass constraint 'Self' : 'FooClass' written here}}
// NO-TYREPR: {{^}}protocol ProtocolWithInheritance5 : <<error type>>, <<error type>> {{{$}}
// TYREPR: {{^}}protocol ProtocolWithInheritance5 : FooClass, BarClass {{{$}}
//===---
//===--- Typealias printing.
//===---
// Normal typealiases.
typealias Typealias1 = FooNonExistentProtocol // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}}
// NO-TYREPR: {{^}}typealias Typealias1 = <<error type>>{{$}}
// TYREPR: {{^}}typealias Typealias1 = FooNonExistentProtocol{{$}}
// sr-197
func foo(bar: Typealias1<Int>) {} // Should not generate error "cannot specialize non-generic type '<<error type>>'"
// Associated types.
protocol AssociatedType1 {
// CHECK-LABEL: AssociatedType1 {
associatedtype AssociatedTypeDecl1 : FooProtocol = FooClass
// CHECK: {{^}} associatedtype AssociatedTypeDecl1 : FooProtocol = FooClass{{$}}
associatedtype AssociatedTypeDecl2 : BazProtocol = FooClass
// CHECK: {{^}} associatedtype AssociatedTypeDecl2 : BazProtocol = FooClass{{$}}
associatedtype AssociatedTypeDecl3 : FooNonExistentProtocol // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}}
// NO-TYREPR: {{^}} associatedtype AssociatedTypeDecl3 : <<error type>>{{$}}
// TYREPR: {{^}} associatedtype AssociatedTypeDecl3 : FooNonExistentProtocol{{$}}
associatedtype AssociatedTypeDecl4 : FooNonExistentProtocol, BarNonExistentProtocol // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}}
// NO-TYREPR: {{^}} associatedtype AssociatedTypeDecl4 : <<error type>>, <<error type>>{{$}}
// TYREPR: {{^}} associatedtype AssociatedTypeDecl4 : FooNonExistentProtocol, BarNonExistentProtocol{{$}}
associatedtype AssociatedTypeDecl5 : FooClass
// CHECK: {{^}} associatedtype AssociatedTypeDecl5{{$}}
}
//===---
//===--- Variable declaration printing.
//===---
var topLevelVar1 = 42
// CHECK: {{^}}var topLevelVar1: Int{{$}}
// CHECK-NOT: topLevelVar1
// CHECK: class C1
class C1 {
// CHECK: init(data: <<error type>>)
init(data:) // expected-error {{expected parameter type following ':'}}
}
protocol IllegalExtension {}
class OuterContext {
// CHECK: class OuterContext {
extension IllegalExtension { // expected-error {{declaration is only valid at file scope}}
// CHECK: extension IllegalExtension {
func protocolFunc() {}
// CHECK: func protocolFunc()
}
}
static func topLevelStaticFunc() {} // expected-error {{static methods may only be declared on a type}}
// NO-TYPEPR: {{^}}func topLevelStaticFunc() -> <<error type>>{{$}}
// TYPEPR: {{^}}func topLevelStaticFunc() {{$}}
static var topLevelStaticVar = 42 // expected-error {{static properties may only be declared on a type}}
// CHECK: {{^}}var topLevelStaticVar: Int{{$}}
| apache-2.0 | 756eeb609f427710b535c0525291b343 | 58.201754 | 340 | 0.720773 | 4.80185 | false | false | false | false |
EmmaXiYu/SE491 | DonateParkSpot/DonateParkSpot/MySpotDetail.swift | 1 | 1807 | //
// MySpotDetail.swift
// DonateParkSpot
//
// Created by Pravangsu Biswas on 10/29/15.
// Copyright © 2015 Apple. All rights reserved.
//
import UIKit
import CoreLocation
class MySpotDetail: UIViewController {
@IBOutlet weak var lblAddress: UILabel!
@IBOutlet weak var lblMinPrice: UILabel!
var DetailSpot : Spot = Spot()
override func viewDidLoad() {
super.viewDidLoad()
self.lblAddress.text = String(format:"%f", DetailSpot.location.latitude!) + " " + String(format:"%f", DetailSpot.location.longitude!)
self.lblMinPrice.text = String(DetailSpot.minDonation)
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: DetailSpot.location.latitude!, longitude: DetailSpot.location.longitude!)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
let placeArray = placemarks! as? [CLPlacemark]
// Place details
var placeMark: CLPlacemark!
placeMark = placeArray?[0]
if let locationName = placeMark.addressDictionary!["Name"] as? NSString {
self.lblAddress.text = String(locationName)
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func 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 | f9ae93d792a58e93a653ae4e0a1bd9c5 | 31.25 | 144 | 0.644518 | 4.881081 | false | false | false | false |
IngmarStein/swift | test/SILGen/dynamic.swift | 3 | 22981 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | %FileCheck %s
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify
// REQUIRES: objc_interop
import Foundation
import gizmo
class Foo: Proto {
// Not objc or dynamic, so only a vtable entry
init(native: Int) {}
func nativeMethod() {}
var nativeProp: Int = 0
subscript(native native: Int) -> Int {
get { return native }
set {}
}
// @objc, so it has an ObjC entry point but can also be dispatched
// by vtable
@objc init(objc: Int) {}
@objc func objcMethod() {}
@objc var objcProp: Int = 0
@objc subscript(objc objc: AnyObject) -> Int {
get { return 0 }
set {}
}
// dynamic, so it has only an ObjC entry point
dynamic init(dynamic: Int) {}
dynamic func dynamicMethod() {}
dynamic var dynamicProp: Int = 0
dynamic subscript(dynamic dynamic: Int) -> Int {
get { return dynamic }
set {}
}
func overriddenByDynamic() {}
@NSManaged var managedProp: Int
}
protocol Proto {
func nativeMethod()
var nativeProp: Int { get set }
subscript(native native: Int) -> Int { get set }
func objcMethod()
var objcProp: Int { get set }
subscript(objc objc: AnyObject) -> Int { get set }
func dynamicMethod()
var dynamicProp: Int { get set }
subscript(dynamic dynamic: Int) -> Int { get set }
}
// ObjC entry points for @objc and dynamic entry points
// normal and @objc initializing ctors can be statically dispatched
// CHECK-LABEL: sil hidden @_TFC7dynamic3FooC
// CHECK: function_ref @_TFC7dynamic3Fooc
// CHECK-LABEL: sil hidden @_TFC7dynamic3FooC
// CHECK: function_ref @_TFC7dynamic3Fooc
// CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc
// CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo10objcMethod
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog8objcPropSi
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos8objcPropSi
// CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si
// CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si
// TODO: dynamic initializing ctor must be objc dispatched
// CHECK-LABEL: sil hidden @_TFC7dynamic3FooC
// CHECK: function_ref @_TTDFC7dynamic3Fooc
// CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Fooc
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.init!initializer.1.foreign :
// CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc
// CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo13dynamicMethod
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog11dynamicPropSi
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos11dynamicPropSi
// CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT7dynamicSi_Si
// CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT7dynamicSi_Si
// Protocol witnesses use best appropriate dispatch
// Native witnesses use vtable dispatch:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_12nativeMethod
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g10nativePropSi
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s10nativePropSi
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT6nativeSi_Si
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT6nativeSi_Si
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
// @objc witnesses use vtable dispatch:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_10objcMethod
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g8objcPropSi
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s8objcPropSi
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT4objcPs9AnyObject__Si
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT4objcPs9AnyObject__Si
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
// Dynamic witnesses use objc dispatch:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_13dynamicMethod
// CHECK: function_ref @_TTDFC7dynamic3Foo13dynamicMethod
// CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foo13dynamicMethod
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g11dynamicPropSi
// CHECK: function_ref @_TTDFC7dynamic3Foog11dynamicPropSi
// CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foog11dynamicPropSi
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s11dynamicPropSi
// CHECK: function_ref @_TTDFC7dynamic3Foos11dynamicPropSi
// CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foos11dynamicPropSi
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT7dynamicSi_Si
// CHECK: function_ref @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si
// CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign :
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT7dynamicSi_Si
// CHECK: function_ref @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si
// CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign :
// Superclass dispatch
class Subclass: Foo {
// Native and objc methods can directly reference super members
override init(native: Int) {
super.init(native: native)
}
// CHECK-LABEL: sil hidden @_TFC7dynamic8SubclassC
// CHECK: function_ref @_TFC7dynamic8Subclassc
override func nativeMethod() {
super.nativeMethod()
}
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass12nativeMethod
// CHECK: function_ref @_TFC7dynamic3Foo12nativeMethodfT_T_ : $@convention(method) (@guaranteed Foo) -> ()
override var nativeProp: Int {
get { return super.nativeProp }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg10nativePropSi
// CHECK: function_ref @_TFC7dynamic3Foog10nativePropSi : $@convention(method) (@guaranteed Foo) -> Int
set { super.nativeProp = newValue }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss10nativePropSi
// CHECK: function_ref @_TFC7dynamic3Foos10nativePropSi : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(native native: Int) -> Int {
get { return super[native: native] }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT6nativeSi_Si
// CHECK: function_ref @_TFC7dynamic3Foog9subscriptFT6nativeSi_Si : $@convention(method) (Int, @guaranteed Foo) -> Int
set { super[native: native] = newValue }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT6nativeSi_Si
// CHECK: function_ref @_TFC7dynamic3Foos9subscriptFT6nativeSi_Si : $@convention(method) (Int, Int, @guaranteed Foo) -> ()
}
override init(objc: Int) {
super.init(objc: objc)
}
// CHECK-LABEL: sil hidden @_TFC7dynamic8SubclasscfT4objcSi_S0_
// CHECK: function_ref @_TFC7dynamic3FoocfT4objcSi_S0_ : $@convention(method) (Int, @owned Foo) -> @owned Foo
override func objcMethod() {
super.objcMethod()
}
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass10objcMethod
// CHECK: function_ref @_TFC7dynamic3Foo10objcMethodfT_T_ : $@convention(method) (@guaranteed Foo) -> ()
override var objcProp: Int {
get { return super.objcProp }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg8objcPropSi
// CHECK: function_ref @_TFC7dynamic3Foog8objcPropSi : $@convention(method) (@guaranteed Foo) -> Int
set { super.objcProp = newValue }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss8objcPropSi
// CHECK: function_ref @_TFC7dynamic3Foos8objcPropSi : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(objc objc: AnyObject) -> Int {
get { return super[objc: objc] }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT4objcPs9AnyObject__Si
// CHECK: function_ref @_TFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si : $@convention(method) (@owned AnyObject, @guaranteed Foo) -> Int
set { super[objc: objc] = newValue }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT4objcPs9AnyObject__Si
// CHECK: function_ref @_TFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> ()
}
// Dynamic methods are super-dispatched by objc_msgSend
override init(dynamic: Int) {
super.init(dynamic: dynamic)
}
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassc
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.init!initializer.1.foreign :
override func dynamicMethod() {
super.dynamicMethod()
}
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass13dynamicMethod
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicMethod!1.foreign :
override var dynamicProp: Int {
get { return super.dynamicProp }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg11dynamicPropSi
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!getter.1.foreign :
set { super.dynamicProp = newValue }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss11dynamicPropSi
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!setter.1.foreign :
}
override subscript(dynamic dynamic: Int) -> Int {
get { return super[dynamic: dynamic] }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT7dynamicSi_Si
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign :
set { super[dynamic: dynamic] = newValue }
// CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT7dynamicSi_Si
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign :
}
dynamic override func overriddenByDynamic() {}
}
// CHECK-LABEL: sil hidden @_TF7dynamic20nativeMethodDispatchFT_T_ : $@convention(thin) () -> ()
func nativeMethodDispatch() {
// CHECK: function_ref @_TFC7dynamic3FooC
let c = Foo(native: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
c[native: 0] = y
}
// CHECK-LABEL: sil hidden @_TF7dynamic18objcMethodDispatchFT_T_ : $@convention(thin) () -> ()
func objcMethodDispatch() {
// CHECK: function_ref @_TFC7dynamic3FooC
let c = Foo(objc: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 :
c.objcMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 :
c.objcProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
let y = c[objc: 0 as NSNumber]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
c[objc: 0 as NSNumber] = y
}
// CHECK-LABEL: sil hidden @_TF7dynamic21dynamicMethodDispatchFT_T_ : $@convention(thin) () -> ()
func dynamicMethodDispatch() {
// CHECK: function_ref @_TFC7dynamic3FooC
let c = Foo(dynamic: 0)
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign
c.dynamicMethod()
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign
let x = c.dynamicProp
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign
c.dynamicProp = x
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign
let y = c[dynamic: 0]
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden @_TF7dynamic15managedDispatchFCS_3FooT_
func managedDispatch(_ c: Foo) {
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign
let x = c.managedProp
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!setter.1.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden @_TF7dynamic21foreignMethodDispatchFT_T_
func foreignMethodDispatch() {
// CHECK: function_ref @_TFCSo9GuisemeauC
let g = Guisemeau()!
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.frob!1.foreign
g.frob()
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!getter.1.foreign
let x = g.count
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!setter.1.foreign
g.count = x
// CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.1.foreign
let y: Any! = g[0]
// CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.1.foreign
g[0] = y
// CHECK: class_method [volatile] {{%.*}} : $NSObject, #NSObject.description!getter.1.foreign
_ = g.description
}
extension Gizmo {
// CHECK-LABEL: sil hidden @_TFE7dynamicCSo5Gizmoc
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.init!initializer.1.foreign
convenience init(convenienceInExtension: Int) {
self.init(bellsOn: convenienceInExtension)
}
// CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC
// CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign
convenience init(foreignClassFactory x: Int) {
self.init(stuff: x)
}
// CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC
// CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign
convenience init(foreignClassExactFactory x: Int) {
self.init(exactlyStuff: x)
}
@objc func foreignObjCExtension() { }
dynamic func foreignDynamicExtension() { }
}
// CHECK-LABEL: sil hidden @_TF7dynamic24foreignExtensionDispatchFCSo5GizmoT_
func foreignExtensionDispatch(_ g: Gizmo) {
// CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignObjCExtension!1.foreign : (Gizmo)
g.foreignObjCExtension()
// CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignDynamicExtension!1.foreign
g.foreignDynamicExtension()
}
// CHECK-LABEL: sil hidden @_TF7dynamic33nativeMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> ()
func nativeMethodDispatchFromOtherFile() {
// CHECK: function_ref @_TFC7dynamic13FromOtherFileC
let c = FromOtherFile(native: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod!1 :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter.1 :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter.1 :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 :
c[native: 0] = y
}
// CHECK-LABEL: sil hidden @_TF7dynamic31objcMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> ()
func objcMethodDispatchFromOtherFile() {
// CHECK: function_ref @_TFC7dynamic13FromOtherFileC
let c = FromOtherFile(objc: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod!1 :
c.objcMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter.1 :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter.1 :
c.objcProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 :
let y = c[objc: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 :
c[objc: 0] = y
}
// CHECK-LABEL: sil hidden @_TF7dynamic34dynamicMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> ()
func dynamicMethodDispatchFromOtherFile() {
// CHECK: function_ref @_TFC7dynamic13FromOtherFileC
let c = FromOtherFile(dynamic: 0)
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!1.foreign
c.dynamicMethod()
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.1.foreign
let x = c.dynamicProp
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.1.foreign
c.dynamicProp = x
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1.foreign
let y = c[dynamic: 0]
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden @_TF7dynamic28managedDispatchFromOtherFileFCS_13FromOtherFileT_
func managedDispatchFromOtherFile(_ c: FromOtherFile) {
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign
let x = c.managedProp
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.1.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden @_TF7dynamic23dynamicExtensionMethodsFCS_13ObjCOtherFileT_
func dynamicExtensionMethods(_ obj: ObjCOtherFile) {
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign
obj.extensionMethod()
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.1.foreign
_ = obj.extensionProp
// CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.1.foreign
// CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
_ = type(of: obj).extensionClassProp
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!1.foreign
obj.dynExtensionMethod()
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.1.foreign
_ = obj.dynExtensionProp
// CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.1.foreign
// CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
_ = type(of: obj).dynExtensionClassProp
}
public class Base {
dynamic var x: Bool { return false }
}
public class Sub : Base {
// CHECK-LABEL: sil hidden @_TFC7dynamic3Subg1xSb : $@convention(method) (@guaranteed Sub) -> Bool {
// CHECK: [[AUTOCLOSURE:%.*]] = function_ref @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error Error)
// CHECK: = partial_apply [[AUTOCLOSURE]](%0)
// CHECK: return {{%.*}} : $Bool
// CHECK: }
// CHECK-LABEL: sil shared [transparent] @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error Error) {
// CHECK: [[SUPER:%.*]] = super_method [volatile] %0 : $Sub, #Base.x!getter.1.foreign : (Base) -> () -> Bool , $@convention(objc_method) (Base) -> ObjCBool
// CHECK: = apply [[SUPER]]({{%.*}})
// CHECK: return {{%.*}} : $Bool
// CHECK: }
override var x: Bool { return false || super.x }
}
// Vtable contains entries for native and @objc methods, but not dynamic ones
// CHECK-LABEL: sil_vtable Foo {
// CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc
// CHECK-LABEL: #Foo.nativeMethod!1: _TFC7dynamic3Foo12nativeMethod
// CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.getter : (native : Swift.Int) -> Swift.Int
// CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.setter : (native : Swift.Int) -> Swift.Int
// CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc
// CHECK-LABEL: #Foo.objcMethod!1: _TFC7dynamic3Foo10objcMethod
// CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.getter : (objc : Swift.AnyObject) -> Swift.Int
// CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.setter : (objc : Swift.AnyObject) -> Swift.Int
// CHECK-NOT: dynamic.Foo.init (dynamic.Foo.Type)(dynamic : Swift.Int) -> dynamic.Foo
// CHECK-NOT: dynamic.Foo.dynamicMethod
// CHECK-NOT: dynamic.Foo.subscript.getter (dynamic : Swift.Int) -> Swift.Int
// CHECK-NOT: dynamic.Foo.subscript.setter (dynamic : Swift.Int) -> Swift.Int
// CHECK-LABEL: #Foo.overriddenByDynamic!1: _TFC7dynamic3Foo19overriddenByDynamic
// CHECK-LABEL: #Foo.nativeProp!getter.1: _TFC7dynamic3Foog10nativePropSi // dynamic.Foo.nativeProp.getter : Swift.Int
// CHECK-LABEL: #Foo.nativeProp!setter.1: _TFC7dynamic3Foos10nativePropSi // dynamic.Foo.nativeProp.setter : Swift.Int
// CHECK-LABEL: #Foo.objcProp!getter.1: _TFC7dynamic3Foog8objcPropSi // dynamic.Foo.objcProp.getter : Swift.Int
// CHECK-LABEL: #Foo.objcProp!setter.1: _TFC7dynamic3Foos8objcPropSi // dynamic.Foo.objcProp.setter : Swift.Int
// CHECK-NOT: dynamic.Foo.dynamicProp.getter
// CHECK-NOT: dynamic.Foo.dynamicProp.setter
// Vtable uses a dynamic thunk for dynamic overrides
// CHECK-LABEL: sil_vtable Subclass {
// CHECK-LABEL: #Foo.overriddenByDynamic!1: _TTDFC7dynamic8Subclass19overriddenByDynamic
| apache-2.0 | 62c6d67090adcc47346d42e5be575ac6 | 48.20985 | 165 | 0.692442 | 3.611661 | false | false | false | false |
noremac/Textile | TextileTests/Source/TextileTests.swift | 1 | 8682 | /*
The MIT License (MIT)
Copyright (c) 2017 Cameron Pulsford
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import XCTest
@testable import Textile
class TextileTests: XCTestCase {
var style: TextStyle!
var defaultParagraphStyle = NSMutableParagraphStyle()
override func setUp() {
super.setUp()
style = TextStyle()
}
override func tearDown() {
style = nil
super.tearDown()
}
// MARK: - Test attributes
func tryAttributeKeyPath<T>(_ keyPath: WritableKeyPath<TextStyle, T?>, key: NSAttributedStringKey, value: T) where T: Equatable {
style[keyPath: keyPath] = value
XCTAssertEqual(style[keyPath: keyPath], value)
XCTAssertEqual(style.attributes[key] as? T, value)
}
func testCustomAttribute() {
style.color = .green
style.attributes[.attachment] = ""
XCTAssertEqual(style.attributes[.attachment] as? String, "")
XCTAssertEqual(style.attributes[.foregroundColor] as? UIColor, .green)
style.color = .red
XCTAssertEqual(style.attributes[.foregroundColor] as? UIColor, .red)
}
func testForegroundColor() {
tryAttributeKeyPath(\.color, key: .foregroundColor, value: .green)
}
func testBackgroundColor() {
tryAttributeKeyPath(\.backgroundColor, key: .backgroundColor, value: .green)
}
func testLigature() {
tryAttributeKeyPath(\.ligature, key: .ligature, value: 1)
}
func testKern() {
tryAttributeKeyPath(\.kern, key: .kern, value: 1)
}
func testStrikethroughStyle() {
tryAttributeKeyPath(\.strikethroughStyle, key: .strikethroughStyle, value: .styleSingle)
}
func testStrikethroughColor() {
tryAttributeKeyPath(\.strikethroughColor, key: .strikethroughColor, value: .green)
}
func testUnderlineStyle() {
tryAttributeKeyPath(\.underlineStyle, key: .underlineStyle, value: .styleSingle)
}
func testUnderlineColor() {
tryAttributeKeyPath(\.underlineColor, key: .underlineColor, value: .green)
}
func testStrokeWidth() {
tryAttributeKeyPath(\.strokeWidth, key: .strokeWidth, value: 1)
}
func testStrokeColor() {
tryAttributeKeyPath(\.strokeColor, key: .strokeColor, value: .green)
}
func testShadow() {
let shadow = NSShadow()
tryAttributeKeyPath(\.shadow, key: .shadow, value: shadow)
}
func testTextEffect() {
tryAttributeKeyPath(\.textEffect, key: .textEffect, value: .letterpressStyle)
}
func testBaselineoffset() {
tryAttributeKeyPath(\.baselineOffset, key: .baselineOffset, value: 1)
}
func testObliqueness() {
style.obliqueness = [1]
XCTAssertEqual(style.obliqueness ?? [], [1])
XCTAssertEqual(style.attributes[.obliqueness] as? [CGFloat] ?? [], [1])
}
func testExpansion() {
style.expansion = [1]
XCTAssertEqual(style.expansion ?? [], [1])
XCTAssertEqual(style.attributes[.expansion] as? [CGFloat] ?? [], [1])
}
func testWritingDirection() {
style.writingDirection = [.rightToLeft]
XCTAssertEqual(style.writingDirection ?? [], [.rightToLeft])
XCTAssertEqual(style.attributes[.writingDirection] as? [NSWritingDirection] ?? [], [.rightToLeft])
}
func testVerticalGlyphs() {
tryAttributeKeyPath(\.verticalGlyphForm, key: .verticalGlyphForm, value: 1)
}
// MARK: - Test paragraph style
func testParagraphForWritingDoesNotChange() {
let style1 = style._paragraphStyleForWriting()
style.lineSpacing = 1
let style2 = style._paragraphStyleForWriting()
style.paragraphSpacing = 1
let style3 = style._paragraphStyleForWriting()
XCTAssertTrue(style1 === style2)
XCTAssertTrue(style1 === style3)
}
func tryParagraphStyleKeyPath<T>(_ styleKeyPath: WritableKeyPath<TextStyle, T>, _ paragraphStyleKeyPath: WritableKeyPath<NSMutableParagraphStyle, T>, value: T) where T: Equatable {
XCTAssertEqual(style[keyPath: styleKeyPath], defaultParagraphStyle[keyPath: paragraphStyleKeyPath])
XCTAssertNil(style._mutableParagraphStyleStorage)
style[keyPath: styleKeyPath] = value
XCTAssertEqual(style[keyPath: styleKeyPath], value)
XCTAssertEqual(style._mutableParagraphStyleStorage?[keyPath: paragraphStyleKeyPath], style[keyPath: styleKeyPath])
}
func testLineSpacing() {
tryParagraphStyleKeyPath(\.lineSpacing, \.lineSpacing, value: 1)
}
func testParagraphSpacing() {
tryParagraphStyleKeyPath(\.paragraphSpacing, \.paragraphSpacing, value: 1)
}
func testAlignment() {
tryParagraphStyleKeyPath(\.alignment, \.alignment, value: .center)
}
func testFirstLineHeadIndent() {
tryParagraphStyleKeyPath(\.firstLineHeadIndent, \.firstLineHeadIndent, value: 1)
}
func testHeadIndent() {
tryParagraphStyleKeyPath(\.headIndent, \.headIndent, value: 1)
}
func testTailIndent() {
tryParagraphStyleKeyPath(\.tailIndent, \.tailIndent, value: 1)
}
func testLineBreakMode() {
tryParagraphStyleKeyPath(\.lineBreakMode, \.lineBreakMode, value: .byCharWrapping)
}
func testMinimumLineHeight() {
tryParagraphStyleKeyPath(\.minimumLineHeight, \.minimumLineHeight, value: 1)
}
func testMaximumLineHeight() {
tryParagraphStyleKeyPath(\.maximumLineHeight, \.maximumLineHeight, value: 1)
}
func testBaseWritingDirection() {
tryParagraphStyleKeyPath(\.baseWritingDirection, \.baseWritingDirection, value: .rightToLeft)
}
func testLineHeightMultiple() {
tryParagraphStyleKeyPath(\.lineHeightMultiple, \.lineHeightMultiple, value: 1)
}
func testParagraphSpacingBefore() {
tryParagraphStyleKeyPath(\.paragraphSpacingBefore, \.paragraphSpacingBefore, value: 1)
}
func testHyphenationFactor() {
tryParagraphStyleKeyPath(\.hyphenationFactor, \.hyphenationFactor, value: 1)
}
func testTabStops() {
let value = [NSTextTab(textAlignment: .center, location: 0, options: [:])]
XCTAssertEqual(style.tabStops, defaultParagraphStyle.tabStops)
XCTAssertNil(style._mutableParagraphStyleStorage)
style.tabStops = value
XCTAssertEqual(style.tabStops, value)
XCTAssertEqual(style._mutableParagraphStyleStorage!.tabStops, style.tabStops)
}
func testDefaultTabInterval() {
tryParagraphStyleKeyPath(\.defaultTabInterval, \.defaultTabInterval, value: 1)
}
func testAllowsDefaultTighteningForTruncation() {
tryParagraphStyleKeyPath(\.allowsDefaultTighteningForTruncation, \.allowsDefaultTighteningForTruncation, value: true)
}
/// MARK: - Test fonts
func testThatFontFeaturesAreApplied() {
style.setFont(.systemFont(ofSize: 10), withFeatures: [UppercaseType.small])
guard let font = style.font else {
return XCTFail("No font was created")
}
guard font.fontDescriptor.fontAttributes[fontFeatureSettingsAttribute] != nil else {
return XCTFail("No features were added")
}
}
/// MARK: - Test strings
func testStyledWith() {
let string = "Hello, world!"
let color = UIColor.red
let font = UIFont.systemFont(ofSize: 10)
let attributedString1 = NSAttributedString(string: string, attributes: [.foregroundColor: color, .font: font])
style.color = color
style.font = font
let attributedString2 = string.styledWith(style)
XCTAssertEqual(attributedString1, attributedString2)
}
}
| mit | 010ef2ed0a5d2113982446aed186556b | 33.86747 | 184 | 0.687054 | 5.217548 | false | true | false | false |
Hout/SwiftDate | Tests/SwiftDateTests/TestDateInRegion+Langs.swift | 1 | 2196 | //
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import SwiftDate
import XCTest
class TestDateInRegion_Langs: XCTestCase {
public func testLanguages() {
RelativeFormatter.allLanguages.forEach { lang in
XCTAssert((lang.identifier.isEmpty == false), "Language \(lang.identifier) has not a valid identifier")
lang.flavours.forEach({ (key, value) in
if RelativeFormatter.Flavour(rawValue: key) == nil {
XCTFail("Flavour '\(key)' is not supported by the library (lang '\(lang.identifier)')")
return
}
guard let flavourDict = value as? [String: Any] else {
XCTFail("Flavour dictionary '\(key)' is not a valid dictionary")
return
}
flavourDict.keys.forEach({ rawTimeUnit in
if RelativeFormatter.Unit(rawValue: rawTimeUnit) == nil {
XCTFail("Time unit '\(rawTimeUnit)' in lang \(key) is not a valid")
return
}
})
})
}
}
public func testValues() {
let ago5Mins = DateInRegion() - 5.minutes
let value1 = ago5Mins.toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.italian) // "5 minuti fa"
XCTAssert(value1 == "5 minuti fa", "Failed to get relative date in default style")
let justNow2 = DateInRegion() - 2.hours
let value2 = justNow2.toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.italian) // "2h fa"
XCTAssert(value2 == "2h fa", "Failed to get relative date in twitter style")
let justNow = DateInRegion() - 10.seconds
let value3 = justNow.toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.italian) // "ora"
XCTAssert(value3 == "ora", "Failed to get relative date in twitter style")
let value4 = justNow.toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.english) // "now"
XCTAssert(value4 == "now", "Failed to get relative date in twitter style")
}
}
| mit | fbd9dd09de908292594be1cea2eb4455 | 36.20339 | 123 | 0.676538 | 4.034926 | false | true | false | false |
iOSDevLog/iOSDevLog | 201. UI Test/Swift/Lister WatchKit Extension/ListsInterfaceController.swift | 1 | 5346 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ListInterfaceController` that presents a single list managed by a `ListPresenterType` instance.
*/
import WatchKit
import ListerKit
class ListsInterfaceController: WKInterfaceController, ListsControllerDelegate {
// MARK: Types
struct Storyboard {
struct RowTypes {
static let list = "ListsInterfaceControllerListRowType"
static let noLists = "ListsInterfaceControllerNoListsRowType"
}
struct Segues {
static let listSelection = "ListsInterfaceControllerListSelectionSegue"
}
}
// MARK: Properties
@IBOutlet weak var interfaceTable: WKInterfaceTable!
var listsController: ListsController!
// MARK: Initializers
override init() {
super.init()
listsController = AppConfiguration.sharedConfiguration.listsControllerForCurrentConfigurationWithPathExtension(AppConfiguration.listerFileExtension)
let noListsIndexSet = NSIndexSet(index: 0)
interfaceTable.insertRowsAtIndexes(noListsIndexSet, withRowType: Storyboard.RowTypes.noLists)
if AppConfiguration.sharedConfiguration.isFirstLaunch {
print("Lister does not currently support configuring a storage option before the iOS app is launched. Please launch the iOS app first. See the Release Notes section in README.md for more information.")
}
}
// MARK: ListsControllerDelegate
func listsController(listsController: ListsController, didInsertListInfo listInfo: ListInfo, atIndex index: Int) {
let indexSet = NSIndexSet(index: index)
// The lists controller was previously empty. Remove the "no lists" row.
if index == 0 && listsController.count == 1 {
interfaceTable.removeRowsAtIndexes(indexSet)
}
interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.list)
configureRowControllerAtIndex(index)
}
func listsController(listsController: ListsController, didRemoveListInfo listInfo: ListInfo, atIndex index: Int) {
let indexSet = NSIndexSet(index: index)
// The lists controller is now empty. Add the "no lists" row.
if index == 0 && listsController.count == 0 {
interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.noLists)
}
interfaceTable.removeRowsAtIndexes(indexSet)
}
func listsController(listsController: ListsController, didUpdateListInfo listInfo: ListInfo, atIndex index: Int) {
configureRowControllerAtIndex(index)
}
// MARK: Segues
override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? {
if segueIdentifier == Storyboard.Segues.listSelection {
let listInfo = listsController[rowIndex]
return listInfo
}
return nil
}
// MARK: Convenience
func configureRowControllerAtIndex(index: Int) {
let listRowController = interfaceTable.rowControllerAtIndex(index) as! ColoredTextRowController
let listInfo = listsController[index]
listRowController.setText(listInfo.name)
listInfo.fetchInfoWithCompletionHandler() {
/*
The fetchInfoWithCompletionHandler(_:) method calls its completion handler on a background
queue, dispatch back to the main queue to make UI updates.
*/
dispatch_async(dispatch_get_main_queue()) {
let listRowController = self.interfaceTable.rowControllerAtIndex(index) as! ColoredTextRowController
listRowController.setColor(listInfo.color!.colorValue)
}
}
}
// MARK: Interface Life Cycle
override func willActivate() {
// If the `ListsController` is activating, we should invalidate any pending user activities.
invalidateUserActivity()
listsController.delegate = self
listsController.startSearching()
}
override func didDeactivate() {
listsController.stopSearching()
listsController.delegate = nil
}
override func handleUserActivity(userInfo: [NSObject: AnyObject]?) {
/*
The Lister watch app only supports continuing activities where
`AppConfiguration.UserActivity.listURLPathUserInfoKey` is provided.
*/
let listInfoFilePath = userInfo?[AppConfiguration.UserActivity.listURLPathUserInfoKey] as? String
// If no `listInfoFilePath` is found, there is no activity of interest to handle.
if listInfoFilePath == nil {
return
}
let listInfoURL = NSURL(fileURLWithPath: listInfoFilePath!, isDirectory: false)
// Create a `ListInfo` that represents the list at `listInfoURL`.
let listInfo = ListInfo(URL: listInfoURL)
// Present a `ListInterfaceController`.
pushControllerWithName(ListInterfaceController.Storyboard.interfaceControllerName, context: listInfo)
}
}
| mit | ff70706e5cae13d79870c30c0cf43343 | 35.353741 | 213 | 0.671594 | 5.951002 | false | true | false | false |
wwu-pi/md2-framework | de.wwu.md2.framework/res/resources/ios/lib/model/datastore/MD2LocalStore.swift | 1 | 8561 | //
// MD2LocalStore.swift
// md2-ios-library
//
// Created by Christoph Rieger on 22.07.15.
// Copyright (c) 2015 Christoph Rieger. All rights reserved.
//
import UIKit
import CoreData
import Foundation
/// Local data store implementation.
class MD2LocalStore<T: MD2Entity>: MD2DataStore {
/// The managed object context that is used to persist the data.
let managedContext : NSManagedObjectContext
/// Default initializer
init() {
// Setup connection to data store managed context
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
managedContext = appDelegate.managedObjectContext!
}
/**
Query the data store.
:param: query The query to specify which entity to retrieve.
:returns: The entity (if exists).
*/
func query(query: MD2Query) -> MD2Entity? {
let results = getManagedObject(query)
if (results.count > 0) {
var data: NSManagedObject = results[0] as! NSManagedObject
// Convert attributes to their respective types
var result: T = T()
result.internalId = MD2Integer(MD2String(data.valueForKey("internalId") as! String))
for (attributeKey, attributeValue) in result.containedTypes {
if data.valueForKey(attributeKey) == nil {
continue
}
let stringValue = data.valueForKey(attributeKey) as! String
if attributeValue is MD2Enum {
(attributeValue as! MD2Enum).setValueFromString(MD2String(stringValue))
} else if attributeValue is MD2Entity {
println(attributeValue)
// TODO
//result.set(attributeKey, value: attributeValue)
} else if attributeValue is MD2DataType {
if attributeValue is MD2String {
result.set(attributeKey, value: MD2String(stringValue))
} else if attributeValue is MD2Boolean {
result.set(attributeKey, value: MD2Boolean(MD2String(stringValue)))
} else if attributeValue is MD2Date {
result.set(attributeKey, value: MD2Date(MD2String(stringValue)))
} else if attributeValue is MD2DateTime {
result.set(attributeKey, value: MD2DateTime(MD2String(stringValue)))
} else if attributeValue is MD2Time {
result.set(attributeKey, value: MD2Time(MD2String(stringValue)))
} else if attributeValue is MD2Float {
result.set(attributeKey, value: MD2Float(MD2String(stringValue)))
} else if attributeValue is MD2Integer {
result.set(attributeKey, value: MD2Integer(MD2String(stringValue)))
}
}
}
return result
}
println("No results returned")
return nil
}
/**
Create or update the entity in the data store.
:param: entity The entity to persist.
*/
func put(entity: MD2Entity) {
if let managedObject = getById(entity.internalId) {
// Exists -> update
updateData(managedObject, entity: entity)
} else {
// New -> insert
insertData(entity)
}
}
/**
Remove an entity from the data store by Id.
:param: internalId The Id of the entity to remove.
*/
func remove(internalId: MD2Integer) {
if let object = getById(internalId) {
managedContext.deleteObject(object)
}
saveManagedContext()
}
/**
Retrieve an object from the data store.
:param: query The query specifying which entity to retrieve.
:returns: A list of entities matching the query.
*/
private func getManagedObject(query: MD2Query) -> NSArray {
var request = NSFetchRequest(entityName: MD2Util.getClassName(T()))
request.returnsObjectsAsFaults = false
// Construct predicates
var requestPredicates: Array<NSPredicate> = []
for (attribute, value) in query.predicates {
println("add query predicate: " + attribute + "==" + value)
requestPredicates.append(NSPredicate(format: attribute + " == %@", value))
}
if(query.predicates.count == 1) {
request.predicate = requestPredicates[0]
} else if (query.predicates.count > 1) {
request.predicate = NSCompoundPredicate(type: NSCompoundPredicateType.OrPredicateType, subpredicates: requestPredicates)
}
var error: NSError?
var results: NSArray = managedContext.executeFetchRequest(request, error: &error)!
if error != nil {
println("Could not load \(error), \(error?.userInfo)")
}
return results
}
/**
Retrieve an object from the local store by Id.
:param: internalId The Id of the object to look up.
:returns: The managed object instance if found.
*/
private func getById(internalId: MD2Integer) -> NSManagedObject? {
if internalId.isSet() && !internalId.equals(MD2Integer(0)) {
let query = MD2Query()
query.addPredicate("internalId", value: internalId.toString())
let results: NSArray = self.getManagedObject(query)
if results.count > 0 {
return results[0] as? NSManagedObject
}
}
return nil
}
/**
Add a new entity to the local data store.
:param: entity The entity to persist.
*/
private func insertData(entity: MD2Entity) {
// Get new managed object
let entityClass = NSEntityDescription.entityForName(MD2Util.getClassName(entity), inManagedObjectContext: managedContext)
let newObject = NSManagedObject(entity: entityClass!, insertIntoManagedObjectContext:managedContext)
// Define unique id
var id = Int(arc4random_uniform(999999999))
while let managedObject = getById(id) {
// Exists -> generate new Id
id = Int(arc4random_uniform(999999999))
}
entity.internalId = MD2Integer(id)
newObject.setValue(entity.internalId.toString(), forKey: "internalId")
// Fill with data and save
setValues(newObject, entity: entity)
saveManagedContext()
}
/**
Update an existing entity in the local data store.
:param: managedObject The object that is updated.
:param: entity The MD2 entity to persist in the managed object.
*/
private func updateData(managedObject: NSManagedObject, entity: MD2Entity) {
// Fill with data and save
setValues(managedObject, entity: entity)
saveManagedContext()
}
/**
Helper function to copy the entity content into a managed object.
:param: managedObject The object that is filled.
:param: entity The MD2 entity to copy.
*/
private func setValues(object: NSManagedObject, entity: MD2Entity) {
for (attributeKey, attributeValue) in entity.containedTypes {
if attributeValue is MD2Enum && (attributeValue as! MD2Enum).value != nil {
object.setValue(attributeValue.toString(), forKey: attributeKey)
} else if attributeValue is MD2Entity {
// TODO not working yet
//object.setValue((attributeValue as! MD2Entity), forKey: attributeKey)
} else if attributeValue is MD2DataType {
if !(attributeValue as! MD2DataType).isSet() {
continue
}
object.setValue((attributeValue as! MD2DataType).toString(), forKey: attributeKey)
}
}
}
/**
Save the managed context (similar to a commit in relational databases).
*/
private func saveManagedContext() {
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
}
} | apache-2.0 | 3bc80afb3d2cc7399fdf10ec21fb6367 | 34.675 | 132 | 0.575984 | 5.2748 | false | false | false | false |
Motsai/neblina-motiondemo-swift | Recorder/Recorder/AppDelegate.swift | 2 | 4361 | //
// AppDelegate.swift
// Recorder
//
// Created by Hoan Hoang on 2018-08-17.
// Copyright © 2018 Motsai. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Recorder")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | cb2a49c401ff88a8de75c3c4df5090e8 | 45.88172 | 279 | 0.72133 | 5.349693 | false | false | false | false |
zpz1237/NirZhihuNews | Pods/Alamofire/Source/Request.swift | 2 | 18941 | // Request.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
*/
public class Request {
// MARK: - Properties
/// The delegate for the underlying task.
public let delegate: TaskDelegate
/// The underlying task.
public var task: NSURLSessionTask { return delegate.task }
/// The session belonging to the underlying task.
public let session: NSURLSession
/// The request sent or to be sent to the server.
public var request: NSURLRequest { return task.originalRequest! }
/// The response received from the server, if any.
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
/// The progress of the request lifecycle.
public var progress: NSProgress { return delegate.progress }
// MARK: - Lifecycle
init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
}
}
// MARK: - Authentication
/**
Associates an HTTP Basic credential with the request.
- parameter user: The user.
- parameter password: The password.
- parameter persistence: The URL credential persistence. `.ForSession` by default.
- returns: The request.
*/
public func authenticate(user user: String, password: String, persistence: NSURLCredentialPersistence = .ForSession) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/**
Associates a specified credential with the request.
- parameter credential: The credential.
- returns: The request.
*/
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
delegate.credential = credential
return self
}
// MARK: - Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
- For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes expected to read.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
- returns: The request.
*/
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataProgress = closure
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
/**
Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
This closure returns the bytes most recently received from the server, not including data from previous calls. If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is also important to note that the `response` closure will be called with nil `responseData`.
- parameter closure: The code to be executed periodically during the lifecycle of the request.
- returns: The request.
*/
public func stream(closure: (NSData -> Void)? = nil) -> Self {
if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataStream = closure
}
return self
}
// MARK: - State
/**
Suspends the request.
*/
public func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
public func resume() {
task.resume()
}
/**
Cancels the request.
*/
public func cancel() {
if let
downloadDelegate = delegate as? DownloadTaskDelegate,
downloadTask = downloadDelegate.downloadTask
{
downloadTask.cancelByProducingResumeData { data in
downloadDelegate.resumeData = data
}
} else {
task.cancel()
}
}
// MARK: - TaskDelegate
/**
The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
executing all operations attached to the serial operation queue upon task completion.
*/
public class TaskDelegate: NSObject {
/// The serial operation queue used to execute all operations after the task completes.
public let queue: NSOperationQueue
let task: NSURLSessionTask
let progress: NSProgress
var data: NSData? { return nil }
var error: NSError?
var credential: NSURLCredential?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
self.queue = {
let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.suspended = true
if operationQueue.respondsToSelector("qualityOfService") {
operationQueue.qualityOfService = NSQualityOfService.Utility
}
return operationQueue
}()
}
deinit {
queue.cancelAllOperations()
queue.suspended = true
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest?) -> Void)) {
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
if credential != nil {
disposition = .UseCredential
}
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) {
var bodyStream: NSInputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
self.error = error
if let
downloadDelegate = self as? DownloadTaskDelegate,
userInfo = error.userInfo as? [String: AnyObject],
resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData
{
downloadDelegate.resumeData = resumeData
}
}
queue.suspended = false
}
}
}
// MARK: - DataTaskDelegate
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask }
private var totalBytesReceived: Int64 = 0
private var mutableData: NSMutableData
override var data: NSData? {
if dataStream != nil {
return nil
} else {
return mutableData
}
}
private var expectedContentLength: Int64?
private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
private var dataStream: ((data: NSData) -> Void)?
override init(task: NSURLSessionTask) {
mutableData = NSMutableData()
super.init(task: task)
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
// MARK: Delegate Methods
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
var disposition: NSURLSessionResponseDisposition = .Allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data: data)
} else {
mutableData.appendData(data)
}
totalBytesReceived += data.length
let totalBytesExpectedToReceive = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpectedToReceive
progress.completedUnitCount = totalBytesReceived
dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: totalBytesReceived, totalBytesExpectedToReceive: totalBytesExpectedToReceive)
}
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse?) -> Void)) {
var cachedResponse: NSCachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
// MARK: - Printable
extension Request: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the HTTP method and URL, as well as the response status code if a response has been received.
public var description: String {
var components: [String] = []
if let HTTPMethod = request.HTTPMethod {
components.append(HTTPMethod)
}
components.append(request.URL!.absoluteString)
if let response = response {
components.append("(\(response.statusCode))")
}
return " ".join(components)
}
}
// MARK: - DebugPrintable
extension Request: CustomDebugStringConvertible {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = request.URL
if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" {
components.append("-X \(HTTPMethod)")
}
if let credentialStorage = session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(
host: URL!.host!,
port: URL!.port?.integerValue ?? 0,
`protocol`: URL!.scheme,
realm: URL!.host!,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
for credential: NSURLCredential in (credentials as! [NSURLCredential]) {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
// Temporarily disabled on OS X due to build failure for CocoaPods
// See https://github.com/CocoaPods/swift/issues/24
#if !os(OSX)
if session.configuration.HTTPShouldSetCookies {
if let
cookieStorage = session.configuration.HTTPCookieStorage,
cookies = cookieStorage.cookiesForURL(URL!) as? [NSHTTPCookie]! where !cookies.isEmpty
{
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
#endif
if let headerFields = request.allHTTPHeaderFields {
for (field, value) in headerFields {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
for (field, value) in additionalHeaders {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let
HTTPBody = request.HTTPBody,
escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
{
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(URL!.absoluteString)\"")
return " \\\n\t".join(components)
}
/// The textual representation used when written to an output stream, in the form of a cURL command.
public var debugDescription: String {
return cURLRepresentation()
}
}
| mit | 76c5212b6b1e626c37beb928b1b64834 | 38.049485 | 321 | 0.633772 | 6.262897 | false | false | false | false |
NicholasTD07/TDRedux.swift | Sources/Types.swift | 1 | 2320 | //
// Types.swift
// TDRedux
//
// Created by Nicholas Tian on 21/10/2016.
// Copyright © 2016 nicktd. All rights reserved.
//
// MARK: - Reducer
extension Store {
/// Returns a new *State* based on the given *State* and *Action*
///
/// - parameter state: the current State of a Store
/// - parameter action: an Action dispatched to the Store
///
/// - returns: A new State
public typealias Reducer = (_ state: State?, _ action: Action) -> State
}
// MARK: - Subscribers
extension Store {
/// Subscribes to changes of a *Store*'s *State*
///
/// It can subscribe to a *Store* by calling `store.subscribe`.
///
/// When a Store's State changes, the Store will notify the change to all of its *Subscribers*.
///
/// - parameter store: A Store
///
/// - returns: Void
public typealias Subscriber = (_ store: Store) -> Void
/// Subscribe to changes of a *Store*'s *State*
///
/// - parameter state: A State
///
/// - returns: Void
public typealias StateSubscriber = (_ state: State) -> Void
/// Gets called every time when the *State* of a *Store* changes
public typealias UpdateSubscriber = () -> Void
}
// MARK: - Dispatcher, Dispatch, Middleware and AsyncAction
extension Store {
/// Dispatches the given *Action* to the given *Store*
///
/// - parameter store: A Store
/// - parameter action: an Action dispatched to the Store
///
/// - returns: Void
public typealias Dispatcher = (_ store: Store, _ action: Action) -> Void
/// It provides a third-party extension point between dispatching an action,
/// and the moment it reaches the reducer.
///
/// - Requires: Middlewares **MUST** call the Dispatcher that's passed in.
public typealias Middleware = (@escaping Dispatcher) -> Dispatcher
/// Dispatches the given *Action* to the binded *Store*
///
/// - parameter action: An Action will be dispatched to the binded Store
///
/// - returns: Void
public typealias Dispatch = (_ action: Action) -> Void
/// Async actions can call the dispatch function
///
/// - parameter dispatch: a Dispatch function
///
/// - returns: Void
public typealias AsyncAction = (_ dispath: @escaping Store.Dispatch) -> Void
}
| mit | 5e674c49d6ca0d922d5ef8b7ba891529 | 29.513158 | 99 | 0.622251 | 4.326493 | false | false | false | false |
entotsu/TKSubmitTransition | SubmitTransition/Classes/CGRectEx.swift | 1 | 2391 | //
// CGRectEx.swift
// SubmitTransition
//
// Created by Takuya Okamoto on 2015/08/07.
// Copyright (c) 2015年 Uniface. All rights reserved.
//
import UIKit
extension CGRect {
var x: CGFloat {
get {
return self.origin.x
}
set {
self = CGRect(x: newValue, y: self.y, width: self.width, height: self.height)
}
}
var y: CGFloat {
get {
return self.origin.y
}
set {
self = CGRect(x: self.x, y: newValue, width: self.width, height: self.height)
}
}
var width: CGFloat {
get {
return self.size.width
}
set {
self = CGRect(x: self.x, y: self.y, width: newValue, height: self.height)
}
}
var height: CGFloat {
get {
return self.size.height
}
set {
self = CGRect(x: self.x, y: self.y, width: self.width, height: newValue)
}
}
var top: CGFloat {
get {
return self.origin.y
}
set {
y = newValue
}
}
var bottom: CGFloat {
get {
return self.origin.y + self.size.height
}
set {
self = CGRect(x: x, y: newValue - height, width: width, height: height)
}
}
var left: CGFloat {
get {
return self.origin.x
}
set {
self.x = newValue
}
}
var right: CGFloat {
get {
return x + width
}
set {
self = CGRect(x: newValue - width, y: y, width: width, height: height)
}
}
var midX: CGFloat {
get {
return self.x + self.width / 2
}
set {
self = CGRect(x: newValue - width / 2, y: y, width: width, height: height)
}
}
var midY: CGFloat {
get {
return self.y + self.height / 2
}
set {
self = CGRect(x: x, y: newValue - height / 2, width: width, height: height)
}
}
var center: CGPoint {
get {
return CGPoint(x: self.midX, y: self.midY)
}
set {
self = CGRect(x: newValue.x - width / 2, y: newValue.y - height / 2, width: width, height: height)
}
}
}
| mit | fd425a0851b73610d5d951569c62c035 | 20.141593 | 110 | 0.445793 | 3.968439 | false | false | false | false |
jinweizhao/swift-Imitation | swift-Imitation/CaptureVideoAndImage/CaptureController.swift | 1 | 3802 | //
// CaptureController.swift
// swift-Imitation
//
// Created by KDB on 2017/2/24.
// Copyright © 2017年 Will-Z. All rights reserved.
//
import UIKit
import WebKit
import JavaScriptCore
class CaptureController: UIViewController,WKNavigationDelegate,WKUIDelegate,UIGestureRecognizerDelegate {
var longPress = UILongPressGestureRecognizer()
var webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
setRightNav()
setWKWebView()
}
func setWKWebView() {
webView = WKWebView(frame: self.view.bounds)
webView.navigationDelegate = self
webView.uiDelegate = self
self.view.addSubview(webView)
// let paste = UIPasteboard.general
// let urlString = paste.string ?? "https://www.baidu.com"
let urlString = "http://www.miaopai.com/show/Qi3NR5twvM2e5k2lc-nXjw__.htm"
let request = NSURLRequest(url: URL(string: urlString)!)
webView.load(request as URLRequest)
longPress.addTarget(self, action: #selector(longPressAction(gesture:)))
longPress.delegate = self
webView.scrollView.addGestureRecognizer(longPress)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
let alert = UIAlertController(title: "error", message: error.localizedDescription, preferredStyle: .alert)
alert .show(self, sender: nil)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == longPress {
return true
}
return false
}
func longPressAction(gesture:UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.began {
let point = gesture.location(in: webView.scrollView)
//第一种方式
let getPointedElement = "document.elementFromPoint(\(point.x),\(point.y)).src"
// let getPointedElement = "document.body"
webView.evaluateJavaScript(getPointedElement, completionHandler: { (obj, error) in
let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
if obj != nil {
alert.title = "获取到了"
alert.message = obj as? String
let paste = UIPasteboard.general
paste.string = alert.message
}else
{
alert.title = "未获取到!"
}
self.present(alert, animated: true, completion: nil)
})
//第二种方式:通过注入 js ,从 js 的方法中回调给 VC 需要的内容
}
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
func setRightNav() {
let rightItem = UIBarButtonItem(title: "Dismiss", style: .plain, target: self, action: #selector(close))
self.navigationItem.rightBarButtonItem = rightItem
}
func close() {
self.navigationController?.dismiss(animated: true, completion: nil)
}
}
| mit | 3633dcec2ae15d0270c96410d36a8c78 | 29.483607 | 157 | 0.574886 | 5.312857 | false | false | false | false |
hamstergene/swift-input-scanner | ExampleLispCalc/main.swift | 1 | 1674 | //
// An example calculator for LISP expressions.
//
// >>> (- (^ 2 16) 1)
// 65535.0
//
// Created by Evgeny Khomyakov on 2015-06-15.
// Copyright © 2015 Evgeny Khomyakov. All rights reserved.
//
import Foundation
let scanner = Scanner()
enum Error : ErrorType {
case Error(String)
}
func readList() throws -> Double {
scanner.skipWhitespace()
guard "(" == scanner.readCharacter() else { throw Error.Error("expected '('") }
guard let op = scanner.readCharacter() else { throw Error.Error("unexpected eof after '('") }
guard var rv = try readEval() else { throw Error.Error("a list need arguments") }
while let arg = try readEval() {
switch op {
case "+": rv += arg
case "-": rv -= arg
case "*": rv *= arg
case "^": rv = pow(rv, arg)
case "/":
guard arg != 0 else { throw Error.Error("division by zero") }
rv /= arg
default: throw Error.Error("unknown operator '\(op)'")
}
}
guard ")" == scanner.readCharacter() else { throw Error.Error("expected ')'") }
return rv
}
func readEval() throws -> Double? {
scanner.skipWhitespace()
if "(" == scanner.peek() {
return try readList()
}
return scanner.readDouble()
}
while !scanner.eof {
do {
print(">>> ", appendNewline: false)
if let v = try readEval() {
print(v)
} else {
if !scanner.eof { throw Error.Error("unexpected token: \(scanner.readWord()!)") }
print("quit")
break
}
} catch Error.Error(let msg) {
print("error: \(msg)")
scanner.nextLine()
}
}
| mit | ab82f2e0b81b4847500cba025c3b4603 | 25.983871 | 97 | 0.54991 | 3.973872 | false | false | false | false |
sysatom/OSC | OSC/OAuthViewController.swift | 1 | 1875 | //
// OAuthViewController.swift
// OSC
//
// Created by yuan on 15/11/16.
// Copyright © 2015年 yuan. All rights reserved.
//
import UIKit
import SnapKit
class OAuthViewController: UIViewController, UIWebViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let webView = UIWebView()
webView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
webView.backgroundColor = .clearColor()
webView.opaque = false
webView.delegate = self
self.view.addSubview(webView)
webView.snp_makeConstraints(closure: {
(make) -> Void in
make.top.equalTo(self.view)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
make.bottom.equalTo(self.view)
})
let url = NSURL(string: "http://www.oschina.net/action/oauth2/authorize?client_id=JkdUHVdwyBbmJ4nEE3dU&response_type=code&redirect_uri=http%3A%2F%2Fwww.sysatom.com")
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func webViewDidStartLoad(webView: UIWebView) {
print(webView.request?.URL?.absoluteString)
}
func webViewDidFinishLoad(webView: UIWebView) {
print(webView.request?.URL?.absoluteString)
}
}
| mit | 098cc4465b31fda8e4aba421d078d2c9 | 30.2 | 173 | 0.663462 | 4.457143 | false | false | false | false |
brokenseal/iOS-exercises | Stack Skills Tutorials/Is It Prime/Is It Prime/ViewController.swift | 1 | 1033 | //
// ViewController.swift
// Is It Prime
//
// Created by Davide Callegari on 21/03/17.
// Copyright © 2017 Davide Callegari. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func isItPrime(_ sender: UIButton) {
if let valueAsString = textField.text,
let value = Int(valueAsString) {
if self.isItPrime(value) {
textField.backgroundColor = .green
} else {
textField.backgroundColor = .red
}
}
}
private func isItPrime(_ number: Int) -> Bool {
return number > 1 && !(2..<number).contains { number % $0 == 0 }
}
}
| mit | 4aa74d566de7d9c1c7c437cf5d7fa9c6 | 26.157895 | 80 | 0.602713 | 4.607143 | false | false | false | false |
mtransitapps/mtransit-for-ios | MonTransit/Source/UI/ViewController/StopViewController.swift | 1 | 16241 | //
// StopViewController.swift
// MonTransit
//
// Created by Thibault on 16-01-19.
// Copyright © 2016 Thibault. All rights reserved.
//
//
import UIKit
import MapKit
import GoogleMobileAds
let offset_HeaderStop:CGFloat = 67.0 // At this offset the Header stops its transformations
let offset_B_LabelHeader:CGFloat = 95.0 // At this offset the Black label reaches the Header
let distance_W_LabelHeader:CGFloat = 30.0 // The distance between the bottom of the Header and the top of the White Label
class StopViewController: UIViewController, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var scrollView:UIScrollView!
@IBOutlet var busImage:StopImageView!
@IBOutlet var header:UIView!
@IBOutlet var headerLabel:UILabel!
@IBOutlet var headerMapView:MKMapView!
@IBOutlet weak var stationCodeLabel: UILabel!
@IBOutlet weak var stationNameLabel: UILabel!
@IBOutlet var visualEffectView:UIVisualEffectView!
@IBOutlet var timeListView: UITableView!
@IBOutlet var heightConstraint:NSLayoutConstraint!
@IBOutlet var favoriteButton:UIBarButtonItem!
@IBOutlet weak var alertTextBlock: UITextView!
@IBOutlet weak var alertSize: NSLayoutConstraint!
@IBOutlet weak var alertButton: UIButton!
@IBOutlet weak var noData: UILabel!
var blurredHeaderImageView:UIImageView?
private var mCompleteStopsList:[GTFSTimeObject]!
private var mStopsList:[GTFSTimeObject]!
private var mFavoriteHelper:FavoritesDataProviderHelper!
private let mPreviousTimeToDisplay = 2
private let mNextTimeToDisplay = 15
private var blurView:UIView!
private var mMapLoaded:Bool = false
var mSelectedStation:StationObject!
var mSelectedBus:BusObject!
var mSelectedTrip:TripObject!
private let regionRadius: CLLocationDistance = 1000
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
timeListView.delegate = self
timeListView.dataSource = self
let wServiceDate = ServiceDateDataProvider()
let wStopProvider = StopDataProviderHelper()
if nil != mSelectedStation{
mCompleteStopsList = []
//First get previous date of the previsou day
let wPreviousDate = NSDate().substractDays(1).getDateToInt()
let wPreviousDateService = wServiceDate.retrieveCurrentServiceByDate(wPreviousDate, iId: AgencyManager.getAgency().getAgencyId())
let wPreviousDayStopList = wStopProvider.retrieveGtfsTime(wPreviousDateService, iStationCodeId: mSelectedStation.getStationId(), iTripId: mSelectedTrip.getTripId(), iId:AgencyManager.getAgency().getAgencyId(), iDate: wPreviousDate)
// Get current day stop
let wCurrentDate = NSDate().getDateToInt()
let wCurrentDateService = wServiceDate.retrieveCurrentServiceByDate(wCurrentDate, iId:AgencyManager.getAgency().getAgencyId())
let wCurrentDayStopList = wStopProvider.retrieveGtfsTime(wCurrentDateService, iStationCodeId: mSelectedStation.getStationId(), iTripId: mSelectedTrip.getTripId(), iId:AgencyManager.getAgency().getAgencyId())
mCompleteStopsList.appendContentsOf(wPreviousDayStopList)
mCompleteStopsList.appendContentsOf(wCurrentDayStopList)
self.stationNameLabel.text = mSelectedStation.getStationTitle()
self.stationCodeLabel.text = mSelectedStation.getStationCode()
self.headerLabel.text = mSelectedBus.getBusNumber() + " - " + mSelectedStation.getStationTitle()
mStopsList = wStopProvider.filterListByTime(mCompleteStopsList, iPreviousTime: mPreviousTimeToDisplay, iAfterTime: mNextTimeToDisplay)
//set nearest time
if mPreviousTimeToDisplay < mStopsList.count {
mStopsList[mPreviousTimeToDisplay].isNearest(true)
}
else if mNextTimeToDisplay < mStopsList.count{
mStopsList[mNextTimeToDisplay].isNearest(true)
}
}
if nil != mSelectedBus {
self.navigationController!.navigationBar.barTintColor = ColorUtils.hexStringToUIColor(mSelectedBus.getBusColor())
self.busImage.backgroundColor = ColorUtils.hexStringToUIColor(mSelectedBus.getBusColor())
self.busImage.addBusNumber(mSelectedBus.getBusNumber(), iDirection: mSelectedTrip.getTripDirection())
}
heightConstraint.constant = CGFloat(44 * (mStopsList.count + 1))
mFavoriteHelper = FavoritesDataProviderHelper()
if nil != mFavoriteHelper {
let wFav = FavoriteObject(iId: 1, iRouteId: mSelectedBus.getBusId(), iTripId: mSelectedTrip.getTripId(), iStopId: mSelectedStation.getStationId(), iFolderId: 1, iProviderType: AgencyManager.getAgency().mAgencyType, iAgencyId: AgencyManager.getAgency().getAgencyId())
if mFavoriteHelper.favoriteExist(wFav, iId: AgencyManager.getAgency().getAgencyId())
{
favoriteButton.image = UIImage(named: "favorite_remove")
}
else
{
favoriteButton.image = UIImage(named: "favorite_add")
}
}
if mStopsList.count > 0{
noData.hidden = true
timeListView.hidden = false
}
else {
noData.hidden = false
timeListView.hidden = true
}
mMapLoaded = false
}
override func viewDidAppear(animated: Bool) {
if !mMapLoaded {
self.headerMapView = MKMapView(frame: self.header.bounds)
self.headerMapView?.contentMode = UIViewContentMode.ScaleAspectFill
self.headerMapView.showsUserLocation = true
self.header.insertSubview(self.headerMapView, belowSubview: self.headerLabel)
self.centerMapOnLocation(CLLocation(latitude: self.mSelectedStation.getStationLatitude(), longitude: self.mSelectedStation.getStationLongitude()))
self.blurView = UIView(frame: self.headerMapView.bounds)
self.visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
self.visualEffectView.frame = self.headerMapView.bounds
self.blurView.insertSubview(self.visualEffectView, atIndex: 1)
self.blurView.alpha = 0.0
self.header.insertSubview(self.blurView, belowSubview: self.headerLabel)
self.header.clipsToBounds = true
self.addIAdBanner()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
processAlert()
}
var adRecieved:Bool = false
override func adViewDidReceiveAd(bannerView: GADBannerView!) {
super.adViewDidReceiveAd(bannerView)
if (!self.adRecieved)
{
heightConstraint.constant = CGFloat(44 * (mStopsList.count + 1)) + CGRectGetHeight(bannerView.frame)
self.adRecieved = true;
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
var avatarTransform = CATransform3DIdentity
var headerTransform = CATransform3DIdentity
// PULL DOWN -----------------
if offset < 0 {
let headerScaleFactor:CGFloat = -(offset) / header.bounds.height
let headerSizevariation = ((header.bounds.height * (1.0 + headerScaleFactor)) - header.bounds.height)/2.0
headerTransform = CATransform3DTranslate(headerTransform, 0, headerSizevariation, 0)
headerTransform = CATransform3DScale(headerTransform, 1.0 + headerScaleFactor, 1.0 + headerScaleFactor, 0)
header.layer.transform = headerTransform
}
// SCROLL UP/DOWN ------------
else {
// Header -----------
headerTransform = CATransform3DTranslate(headerTransform, 0, max(-offset_HeaderStop, -offset), 0)
// ------------ Label
let labelTransform = CATransform3DMakeTranslation(0, max(-distance_W_LabelHeader, offset_B_LabelHeader - offset), 0)
headerLabel.layer.transform = labelTransform
// ------------ Blur
blurView?.alpha = min (1.0, (offset - offset_B_LabelHeader)/distance_W_LabelHeader)
// Bus Image -----------
let busScaleFactor = (min(offset_HeaderStop, offset)) / busImage.bounds.height / 1.4 // Slow down the animation
let busSizeVariation = ((busImage.bounds.height * (1.0 + busScaleFactor)) - busImage.bounds.height) / 2.0
avatarTransform = CATransform3DTranslate(avatarTransform, 0, busSizeVariation, 0)
avatarTransform = CATransform3DScale(avatarTransform, 1.0 - busScaleFactor, 1.0 - busScaleFactor, 0)
if offset <= offset_HeaderStop {
if busImage.layer.zPosition < header.layer.zPosition{
header.layer.zPosition = 0
}
}else {
if busImage.layer.zPosition >= header.layer.zPosition{
header.layer.zPosition = 2
}
}
}
// Apply Transformations
header.layer.transform = headerTransform
busImage.layer.transform = avatarTransform
}
@IBAction func addFavorite() {
if nil != mFavoriteHelper {
let wFav = FavoriteObject(iId: 1, iRouteId: mSelectedBus.getBusId(), iTripId: mSelectedTrip.getTripId(), iStopId: mSelectedStation.getStationId(), iFolderId: 1, iProviderType: AgencyManager.getAgency().mAgencyType, iAgencyId: AgencyManager.getAgency().getAgencyId())
self.clearAllNotice()
if mFavoriteHelper.favoriteExist(wFav, iId: AgencyManager.getAgency().getAgencyId())
{
mFavoriteHelper.removeFavorites(wFav, iId: AgencyManager.getAgency().getAgencyId())
favoriteButton.image = UIImage(named: "favorite_add")
self.noticeError(NSLocalizedString("RemovedKey", comment: "Removed"), autoClear: true, autoClearTime: 1)
}
else
{
mFavoriteHelper.addFavorites(wFav, iId: AgencyManager.getAgency().getAgencyId())
favoriteButton.image = UIImage(named: "favorite_remove")
self.noticeSuccess(NSLocalizedString("AddedKey", comment: "Added"), autoClear: true, autoClearTime: 1)
}
}
}
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
headerMapView.setRegion(coordinateRegion, animated: false)
let stoplocation:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let anotation = MKPointAnnotation()
anotation.coordinate = stoplocation
headerMapView.addAnnotation(anotation)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return mStopsList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("StopCell", forIndexPath: indexPath) as! StopTableViewCell
// Configure the cell...
if mStopsList != nil && indexPath.row <= mStopsList.count
{
cell.mTimeBusLabel.text = mStopsList[indexPath.row].getNSDate().getTime()
cell.mDateBusLabel.text = mStopsList[indexPath.row].getNSDate().getDate()
cell.isNearest(mStopsList[indexPath.row].isNearest())
}
return cell
}
// 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.
if (segue.identifier == "MapSegue") {
mMapLoaded = true
let navVC = segue.destinationViewController as! UINavigationController
let tableVC = navVC.viewControllers.first as! MapStopViewController
tableVC.mSelectedStation = mSelectedStation
tableVC.navigationController!.navigationBar.barTintColor = ColorUtils.hexStringToUIColor(mSelectedBus.getBusColor())
}
else if (segue.identifier == "HourSegue") {
mMapLoaded = true
let navVC = segue.destinationViewController as! UINavigationController
let tableVC = navVC.viewControllers.first as! CompleteHourViewController
tableVC.navigationController!.navigationBar.barTintColor = ColorUtils.hexStringToUIColor(mSelectedBus.getBusColor())
tableVC.mStopsList = mCompleteStopsList
tableVC.mStationId = mSelectedStation.getStationId()
tableVC.mTripId = mSelectedTrip.getTripId()
}
}
func processAlert(){
let wAlerts = AppDelegate().sharedInstance().getJson().retrieveAlertById(mSelectedBus.getBusId(), iDirection: mSelectedTrip.getTripDirection(), iStationId: mSelectedStation.getStationCode())
var wAlertText = ""
if wAlerts.count > 0 && !wAlerts[0].alert.containsString(AgencyManager.getAgency().getDefaultAlertMessage())
{
for wAlert in wAlerts{
wAlertText += wAlert.alert + "\n\n"
}
wAlertText = String(wAlertText.characters.dropLast(2))
alertButton.enabled = true
alertButton.hidden = false
let wString = wAlertText as NSString
let wCode = String(mSelectedStation.getStationCode())
let attributedString = NSMutableAttributedString(string: wString as String)
let firstAttributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(14)]
let wCodeRange = wString.rangeOfString(wCode)
let wDotIndex = wString.rangeOfString(".")
if wCodeRange.length != 0 && wDotIndex.location > wCodeRange.location{
let wBoldSation = NSMakeRange(wCodeRange.location, wDotIndex.location - wCodeRange.location)
attributedString.addAttributes(firstAttributes, range: wBoldSation)
}
alertTextBlock.text = wAlertText
alertTextBlock.attributedText = attributedString
}
self.alertSize.constant = 0
}
@IBAction func displayAlert(){
if self.alertSize.constant == 0 {
self.alertTextBlock.sizeToFit()
self.alertSize.constant = self.alertTextBlock.frame.height
UIView.animateWithDuration(0.3, animations: {
self.view.layoutIfNeeded()
})
}
else {
self.alertSize.constant = 0
UIView.animateWithDuration(0.3, animations: {
self.view.layoutIfNeeded()
})
}
}
} | apache-2.0 | cd9fcc38ac352e1f418bb37ef01010e7 | 41.294271 | 278 | 0.635037 | 5.594213 | false | false | false | false |
gregomni/swift | SwiftCompilerSources/Sources/Optimizer/Utilities/OptUtils.swift | 2 | 1298 | //===--- OptUtils.swift - Utilities for optimzations ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 SIL
extension Value {
var nonDebugUses: LazyFilterSequence<UseList> {
uses.lazy.filter { !($0.instruction is DebugValueInst) }
}
}
extension Builder {
static func insert(after inst: Instruction, location: Location,
_ context: PassContext, insertFunc: (Builder) -> ()) {
if inst is TermInst {
for succ in inst.block.successors {
assert(succ.hasSinglePredecessor,
"the terminator instruction must not have critical successors")
let builder = Builder(at: succ.instructions.first!, location: location,
context)
insertFunc(builder)
}
} else {
let builder = Builder(at: inst.next!, location: location, context)
insertFunc(builder)
}
}
}
| apache-2.0 | 24cee77d690f0d6df28876ce36432fb6 | 34.081081 | 80 | 0.607858 | 4.635714 | false | false | false | false |
cjbeauchamp/tvOSDashboard | Charts/Classes/Renderers/RadarChartRenderer.swift | 1 | 13828 | //
// RadarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class RadarChartRenderer: LineRadarChartRenderer
{
public weak var chart: RadarChartView?
public init(chart: RadarChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
}
public override func drawData(context context: CGContext)
{
guard let chart = chart else { return }
let radarData = chart.data
if (radarData != nil)
{
var mostEntries = 0
for set in radarData!.dataSets
{
if set.entryCount > mostEntries
{
mostEntries = set.entryCount
}
}
for set in radarData!.dataSets as! [IRadarChartDataSet]
{
if set.isVisible && set.entryCount > 0
{
drawDataSet(context: context, dataSet: set, mostEntries: mostEntries)
}
}
}
}
/// Draws the RadarDataSet
///
/// - parameter context:
/// - parameter dataSet:
/// - parameter mostEntries: the entry count of the dataset with the most entries
internal func drawDataSet(context context: CGContext, dataSet: IRadarChartDataSet, mostEntries: Int)
{
guard let
chart = chart,
animator = animator
else { return }
CGContextSaveGState(context)
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let entryCount = dataSet.entryCount
let path = CGPathCreateMutable()
var hasMovedToPoint = false
for (var j = 0; j < entryCount; j++)
{
guard let e = dataSet.entryForIndex(j) else { continue }
let p = ChartUtils.getPosition(
center: center,
dist: CGFloat(e.value - chart.chartYMin) * factor * phaseY,
angle: sliceangle * CGFloat(j) * phaseX + chart.rotationAngle)
if p.x.isNaN
{
continue
}
if !hasMovedToPoint
{
CGPathMoveToPoint(path, nil, p.x, p.y)
hasMovedToPoint = true
}
else
{
CGPathAddLineToPoint(path, nil, p.x, p.y)
}
}
// if this is the largest set, close it
if dataSet.entryCount < mostEntries
{
// if this is not the largest set, draw a line to the center before closing
CGPathAddLineToPoint(path, nil, center.x, center.y)
}
CGPathCloseSubpath(path)
// draw filled
if dataSet.isDrawFilledEnabled
{
if dataSet.fill != nil
{
drawFilledPath(context: context, path: path, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: path, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
// draw the line (only if filled is disabled or alpha is below 255)
if !dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0
{
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor)
CGContextSetLineWidth(context, dataSet.lineWidth)
CGContextSetAlpha(context, 1.0)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextStrokePath(context)
}
CGContextRestoreGState(context)
}
public override func drawValues(context context: CGContext)
{
guard let
chart = chart,
data = chart.data,
animator = animator
else { return }
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let yoffset = CGFloat(5.0)
for (var i = 0, count = data.dataSetCount; i < count; i++)
{
let dataSet = data.getDataSetByIndex(i) as! IRadarChartDataSet
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
let entryCount = dataSet.entryCount
for (var j = 0; j < entryCount; j++)
{
guard let e = dataSet.entryForIndex(j) else { continue }
let p = ChartUtils.getPosition(
center: center,
dist: CGFloat(e.value) * factor * phaseY,
angle: sliceangle * CGFloat(j) * phaseX + chart.rotationAngle)
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
ChartUtils.drawText(
context: context,
text: formatter.stringFromNumber(e.value)!,
point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight),
align: .Center,
attributes: [NSFontAttributeName: valueFont,
NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
}
public override func drawExtras(context context: CGContext)
{
drawWeb(context: context)
}
private var _webLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public func drawWeb(context context: CGContext)
{
guard let
chart = chart,
data = chart.data
else { return }
let sliceangle = chart.sliceAngle
CGContextSaveGState(context)
// calculate the factor that is needed for transforming the value to
// pixels
let factor = chart.factor
let rotationangle = chart.rotationAngle
let center = chart.centerOffsets
// draw the web lines that come from the center
CGContextSetLineWidth(context, chart.webLineWidth)
CGContextSetStrokeColorWithColor(context, chart.webColor.CGColor)
CGContextSetAlpha(context, chart.webAlpha)
let xIncrements = 1 + chart.skipWebLineCount
for var i = 0, xValCount = data.xValCount; i < xValCount; i += xIncrements
{
let p = ChartUtils.getPosition(
center: center,
dist: CGFloat(chart.yRange) * factor,
angle: sliceangle * CGFloat(i) + rotationangle)
_webLineSegmentsBuffer[0].x = center.x
_webLineSegmentsBuffer[0].y = center.y
_webLineSegmentsBuffer[1].x = p.x
_webLineSegmentsBuffer[1].y = p.y
CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2)
}
// draw the inner-web
CGContextSetLineWidth(context, chart.innerWebLineWidth)
CGContextSetStrokeColorWithColor(context, chart.innerWebColor.CGColor)
CGContextSetAlpha(context, chart.webAlpha)
let labelCount = chart.yAxis.entryCount
for (var j = 0; j < labelCount; j++)
{
for (var i = 0, xValCount = data.xValCount; i < xValCount; i++)
{
let r = CGFloat(chart.yAxis.entries[j] - chart.chartYMin) * factor
let p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle)
let p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle)
_webLineSegmentsBuffer[0].x = p1.x
_webLineSegmentsBuffer[0].y = p1.y
_webLineSegmentsBuffer[1].x = p2.x
_webLineSegmentsBuffer[1].y = p2.y
CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
private var _highlightPointBuffer = CGPoint()
public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight])
{
guard let
chart = chart,
data = chart.data as? RadarChartData,
animator = animator
else { return }
CGContextSaveGState(context)
CGContextSetLineWidth(context, data.highlightLineWidth)
if (data.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, data.highlightLineDashPhase, data.highlightLineDashLengths!, data.highlightLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let sliceangle = chart.sliceAngle
let factor = chart.factor
let center = chart.centerOffsets
for (var i = 0; i < indices.count; i++)
{
guard let set = chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as? IRadarChartDataSet else { continue }
if !set.isHighlightEnabled
{
continue
}
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor)
// get the index to highlight
let xIndex = indices[i].xIndex
let e = set.entryForXIndex(xIndex)
if e?.xIndex != xIndex
{
continue
}
let j = set.entryIndex(entry: e!)
let y = (e!.value - chart.chartYMin)
if (y.isNaN)
{
continue
}
_highlightPointBuffer = ChartUtils.getPosition(
center: center,
dist: CGFloat(y) * factor * phaseY,
angle: sliceangle * CGFloat(j) * phaseX + chart.rotationAngle)
// draw the lines
drawHighlightLines(context: context, point: _highlightPointBuffer, set: set)
if (set.isDrawHighlightCircleEnabled)
{
if (!_highlightPointBuffer.x.isNaN && !_highlightPointBuffer.y.isNaN)
{
var strokeColor = set.highlightCircleStrokeColor
if strokeColor == nil
{
strokeColor = set.colorAt(0)
}
if set.highlightCircleStrokeAlpha < 1.0
{
strokeColor = strokeColor?.colorWithAlphaComponent(set.highlightCircleStrokeAlpha)
}
drawHighlightCircle(
context: context,
atPoint: _highlightPointBuffer,
innerRadius: set.highlightCircleInnerRadius,
outerRadius: set.highlightCircleOuterRadius,
fillColor: set.highlightCircleFillColor,
strokeColor: strokeColor,
strokeWidth: set.highlightCircleStrokeWidth)
}
}
}
CGContextRestoreGState(context)
}
internal func drawHighlightCircle(
context context: CGContext,
atPoint point: CGPoint,
innerRadius: CGFloat,
outerRadius: CGFloat,
fillColor: NSUIColor?,
strokeColor: NSUIColor?,
strokeWidth: CGFloat)
{
CGContextSaveGState(context)
if let fillColor = fillColor
{
CGContextBeginPath(context)
CGContextAddEllipseInRect(context, CGRectMake(point.x - outerRadius, point.y - outerRadius, outerRadius * 2.0, outerRadius * 2.0))
if innerRadius > 0.0
{
CGContextAddEllipseInRect(context, CGRectMake(point.x - innerRadius, point.y - innerRadius, innerRadius * 2.0, innerRadius * 2.0))
}
CGContextSetFillColorWithColor(context, fillColor.CGColor)
CGContextEOFillPath(context)
}
if let strokeColor = strokeColor
{
CGContextBeginPath(context)
CGContextAddEllipseInRect(context, CGRectMake(point.x - outerRadius, point.y - outerRadius, outerRadius * 2.0, outerRadius * 2.0))
CGContextSetStrokeColorWithColor(context, strokeColor.CGColor)
CGContextSetLineWidth(context, strokeWidth)
CGContextStrokePath(context)
}
CGContextRestoreGState(context)
}
} | apache-2.0 | f0dd852c7af568f7dd635dc72b5c3f96 | 32.729268 | 146 | 0.53869 | 5.812526 | false | false | false | false |
twostraws/HackingWithSwift | Classic/project17/Project17/GameScene.swift | 1 | 3013 | //
// GameScene.swift
// Project17
//
// Created by Paul Hudson on 03/04/2019.
// Copyright © 2019 Hacking with Swift. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var starfield: SKEmitterNode!
var player: SKSpriteNode!
var scoreLabel: SKLabelNode!
var possibleEnemies = ["ball", "hammer", "tv"]
var gameTimer: Timer?
var isGameOver = false
var score = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
override func didMove(to view: SKView) {
backgroundColor = .black
starfield = SKEmitterNode(fileNamed: "starfield")!
starfield.position = CGPoint(x: 1024, y: 384)
starfield.advanceSimulationTime(10)
addChild(starfield)
starfield.zPosition = -1
player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 100, y: 384)
player.physicsBody = SKPhysicsBody(texture: player.texture!, size: player.size)
player.physicsBody?.contactTestBitMask = 1
addChild(player)
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.position = CGPoint(x: 16, y: 16)
scoreLabel.horizontalAlignmentMode = .left
addChild(scoreLabel)
score = 0
physicsWorld.gravity = .zero
physicsWorld.contactDelegate = self
gameTimer = Timer.scheduledTimer(timeInterval: 0.35, target: self, selector: #selector(createEnemy), userInfo: nil, repeats: true)
}
@objc func createEnemy() {
guard let enemy = possibleEnemies.randomElement() else { return }
let sprite = SKSpriteNode(imageNamed: enemy)
sprite.position = CGPoint(x: 1200, y: Int.random(in: 50...736))
addChild(sprite)
sprite.physicsBody = SKPhysicsBody(texture: sprite.texture!, size: sprite.size)
sprite.physicsBody?.categoryBitMask = 1
sprite.physicsBody?.velocity = CGVector(dx: -500, dy: 0)
sprite.physicsBody?.angularVelocity = 5
sprite.physicsBody?.linearDamping = 0
sprite.physicsBody?.angularDamping = 0
}
override func update(_ currentTime: TimeInterval) {
for node in children {
if node.position.x < -300 {
node.removeFromParent()
}
}
if !isGameOver {
score += 1
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
var location = touch.location(in: self)
if location.y < 100 {
location.y = 100
} else if location.y > 668 {
location.y = 668
}
player.position = location
}
func didBegin(_ contact: SKPhysicsContact) {
let explosion = SKEmitterNode(fileNamed: "explosion")!
explosion.position = player.position
addChild(explosion)
player.removeFromParent()
isGameOver = true
}
}
| unlicense | b3ceb971d74b3eefa33ebd94dcb85778 | 28.529412 | 138 | 0.618526 | 4.684292 | false | false | false | false |
Masteryyz/CSYMicroBlockSina | CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/OAuth_2.0/LoginViewWithOAUTHViewController.swift | 1 | 5422 | //
// LoginViewWithOAUTHViewController.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/9.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
import SVProgressHUD
import AFNetworking
class LoginViewWithOAUTHViewController: UIViewController {
let webView : UIWebView = UIWebView()
override func loadView() {
view = webView
webView.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
loadWebRequest()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension LoginViewWithOAUTHViewController{
private func loadWebRequest(){
let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
let request = NSURLRequest(URL: NSURL(string: urlStr)!)
webView.loadRequest(request)
}
}
// MARK: - 界面的设置
extension LoginViewWithOAUTHViewController{
private func setUpUI () {
//print("setUpUI")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeWebView")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动获取", style: UIBarButtonItemStyle.Plain, target: self, action: "autoInput")
}
@objc private func autoInput(){
let js = "document.getElementById('userId').value = '18636706784';" + "document.getElementById('passwd').value = '15343577589Yyz';"
webView.stringByEvaluatingJavaScriptFromString(js)
}
func closeWebView (){
dismissViewControllerAnimated(true) { () -> Void in
//print("Complete")
}
}
}
// MARK: - 代理获得请求的URL
extension LoginViewWithOAUTHViewController : UIWebViewDelegate{
func webViewDidStartLoad(webView: UIWebView) {
//开始载入的时候调用
SVProgressHUD.showWithStatus("请求授权中", maskType: SVProgressHUDMaskType.Black)
}
func webViewDidFinishLoad(webView: UIWebView) {
//结束载入的时候调用
SVProgressHUD.dismiss()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//载入出错的时候调用
//print("----------->\(error)")
}
/*抓取到了网络请求
<NSMutableURLRequest: 0x7fde51e11180> { URL: https://api.weibo.com/oauth2/authorize?client_id=641602405&redirect_uri=http://neihanshequ.com }
LoadSuccess
<NSMutableURLRequest: 0x7fde540d1560> { URL: https://api.weibo.com/oauth2/authorize }
<NSMutableURLRequest: 0x7fde51e54660> { URL: https://api.weibo.com/oauth2/authorize# }
<NSMutableURLRequest: 0x7fde51e593e0> { URL: https://api.weibo.com/oauth2/authorize }
<NSMutableURLRequest: 0x7fde51e63580> { URL: http://neihanshequ.com/?code=6fdc3dfc4cf63982fec4812d55c82e38 }
<NSMutableURLRequest: 0x7fde51ea1ef0> { URL: http://m.neihanshequ.com/ }
<NSMutableURLRequest: 0x7fde540d3cd0> { URL: http://m.neihanshequ.com/?skip_guidence=1 }
*/
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//监听WebView的所有网络请求
//如果网页没有获取到有用的请求信息,则拦截一切活动
guard let urlStr = request.URL?.absoluteString else{
//print(request.URL)
print("WebView闲置")
return false
}
//如果授权请求正在执行 ---> 让他继续
if urlStr.hasPrefix("https://api.weibo.com/") {
//print(request.URL)
//print("[请求授权中...]")
return true
}
//如果得到了定义好的域名请求,则代表或取到了自己的code ---> 获得数据[拦住他,不要继续了]
if !urlStr.hasPrefix(redirect_uri) {
//print("[拦截到CODE_URL]\(urlStr)")
return false
}
//程序在获得了code之后被卡住了,执行后续的操作
guard let queryStr = request.URL?.query else {
return false
}
let str = "code="
code = queryStr.substringFromIndex(str.endIndex)
print("--->获得CODE<--- [\(code)]")
//封装好的数据获取
GetUserInfoModel().getTokenWithCode(code!) { (errorMessage) -> () in
self.dismissViewControllerAnimated(true, completion: { () -> Void in
SVProgressHUD.dismiss()
NSNotificationCenter.defaultCenter().postNotificationName(APPDELEGATESHOULDSWITCHROOTVIEWCONTROLLER, object: "welCome")
})
}
return true
}
}
| mit | 8f176d50118db601030fd7a2e16839f6 | 22.276498 | 149 | 0.578103 | 4.672525 | false | false | false | false |
brorbw/Helium | Helium/Helium/HeliumPanelController.swift | 1 | 10464 | //
// HeliumPanelController.swift
// Helium
//
// Created by Jaden Geller on 4/9/15.
// Copyright (c) 2015 Jaden Geller. All rights reserved.
//
import AppKit
let optionKeyCode: UInt16 = 58
class HeliumPanelController : NSWindowController {
fileprivate var webViewController: WebViewController {
get {
return self.window?.contentViewController as! WebViewController
}
}
fileprivate var mouseOver: Bool = false
fileprivate var alpha: CGFloat = 0.6 { //default
didSet {
updateTranslucency()
}
}
fileprivate var translucencyPreference: TranslucencyPreference = .always {
didSet {
updateTranslucency()
}
}
fileprivate var translucencyEnabled: Bool = false {
didSet {
updateTranslucency()
}
}
fileprivate enum TranslucencyPreference {
case always
case mouseOver
case mouseOutside
}
fileprivate var currentlyTranslucent: Bool = false {
didSet {
if !NSApplication.shared().isActive {
panel.ignoresMouseEvents = currentlyTranslucent
}
if currentlyTranslucent {
panel.animator().alphaValue = alpha
panel.isOpaque = false
}
else {
panel.isOpaque = true
panel.animator().alphaValue = 1
}
}
}
fileprivate var panel: NSPanel! {
get {
return (self.window as! NSPanel)
}
}
// MARK: Window lifecycle
override func windowDidLoad() {
panel.isFloatingPanel = true
NotificationCenter.default.addObserver(self, selector: #selector(HeliumPanelController.didBecomeActive), name: NSNotification.Name.NSApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(HeliumPanelController.willResignActive), name: NSNotification.Name.NSApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(HeliumPanelController.didUpdateTitle(_:)), name: NSNotification.Name(rawValue: "HeliumUpdateTitle"), object: nil)
setFloatOverFullScreenApps()
if let alpha = UserDefaults.standard.object(forKey: UserSetting.opacityPercentage.userDefaultsKey) {
didUpdateAlpha(CGFloat(alpha as! Int))
}
}
// MARK : Mouse events
override func mouseEntered(with theEvent: NSEvent) {
mouseOver = true
updateTranslucency()
}
override func mouseExited(with theEvent: NSEvent) {
mouseOver = false
updateTranslucency()
}
// MARK : Translucency
fileprivate func updateTranslucency() {
currentlyTranslucent = shouldBeTranslucent()
}
fileprivate func shouldBeTranslucent() -> Bool {
/* Implicit Arguments
* - mouseOver
* - translucencyPreference
* - tranlucencyEnalbed
*/
guard translucencyEnabled else { return false }
switch translucencyPreference {
case .always:
return true
case .mouseOver:
return mouseOver
case .mouseOutside:
return !mouseOver
}
}
fileprivate func setFloatOverFullScreenApps() {
if UserDefaults.standard.bool(forKey: UserSetting.disabledFullScreenFloat.userDefaultsKey) {
panel.collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary]
} else {
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
}
}
//MARK: IBActions
fileprivate func disabledAllMouseOverPreferences(_ allMenus: [NSMenuItem]) {
// GROSS HARD CODED
for x in allMenus.dropFirst(2) {
x.state = NSOffState
}
}
@IBAction fileprivate func alwaysPreferencePress(_ sender: NSMenuItem) {
disabledAllMouseOverPreferences(sender.menu!.items)
translucencyPreference = .always
sender.state = NSOnState
}
@IBAction fileprivate func overPreferencePress(_ sender: NSMenuItem) {
disabledAllMouseOverPreferences(sender.menu!.items)
translucencyPreference = .mouseOver
sender.state = NSOnState
}
@IBAction fileprivate func outsidePreferencePress(_ sender: NSMenuItem) {
disabledAllMouseOverPreferences(sender.menu!.items)
translucencyPreference = .mouseOutside
sender.state = NSOnState
}
@IBAction fileprivate func translucencyPress(_ sender: NSMenuItem) {
if sender.state == NSOnState {
sender.state = NSOffState
didDisableTranslucency()
}
else {
sender.state = NSOnState
didEnableTranslucency()
}
}
@IBAction fileprivate func percentagePress(_ sender: NSMenuItem) {
for button in sender.menu!.items{
(button ).state = NSOffState
}
sender.state = NSOnState
let value = sender.title.substring(to: sender.title.characters.index(sender.title.endIndex, offsetBy: -1))
if let alpha = Int(value) {
didUpdateAlpha(CGFloat(alpha))
UserDefaults.standard.set(alpha, forKey: UserSetting.opacityPercentage.userDefaultsKey)
}
}
@IBAction fileprivate func openLocationPress(_ sender: AnyObject) {
didRequestLocation()
}
@IBAction fileprivate func openFilePress(_ sender: AnyObject) {
didRequestFile()
}
@IBAction fileprivate func floatOverFullScreenAppsToggled(_ sender: NSMenuItem) {
sender.state = (sender.state == NSOnState) ? NSOffState : NSOnState
UserDefaults.standard.set((sender.state == NSOffState), forKey: UserSetting.disabledFullScreenFloat.userDefaultsKey)
setFloatOverFullScreenApps()
}
@IBAction fileprivate func hideTitle(_ sender: NSMenuItem) {
if sender.state == NSOnState {
sender.state = NSOffState
panel.styleMask = NSBorderlessWindowMask
}
else {
sender.state = NSOnState
panel.styleMask = NSWindowStyleMask(rawValue: 8345)
}
}
@IBAction func setHomePage(_ sender: AnyObject){
didRequestChangeHomepage()
}
//MARK: Actual functionality
@objc fileprivate func didUpdateTitle(_ notification: Notification) {
if let title = notification.object as? String {
panel.title = title
}
}
fileprivate func didRequestFile() {
let open = NSOpenPanel()
open.allowsMultipleSelection = false
open.canChooseFiles = true
open.canChooseDirectories = false
if open.runModal() == NSModalResponseOK {
if let url = open.url {
webViewController.loadURL(url)
}
}
}
fileprivate func didRequestLocation() {
let alert = NSAlert()
alert.alertStyle = NSAlertStyle.informational
alert.messageText = "Enter Destination URL"
let urlField = NSTextField()
urlField.frame = NSRect(x: 0, y: 0, width: 300, height: 20)
urlField.lineBreakMode = NSLineBreakMode.byTruncatingHead
urlField.usesSingleLineMode = true
alert.accessoryView = urlField
//alert.accessoryView!.becomeFirstResponder()
alert.addButton(withTitle: "Load")
alert.addButton(withTitle: "Cancel")
alert.beginSheetModal(for: self.window!, completionHandler: { response in
if response == NSAlertFirstButtonReturn {
// Load
let text = (alert.accessoryView as! NSTextField).stringValue
self.webViewController.loadAlmostURL(text)
}
})
urlField.becomeFirstResponder()
}
func didRequestChangeHomepage(){
let alert = NSAlert()
alert.alertStyle = NSAlertStyle.informational
alert.messageText = "Enter new Home Page URL"
let urlField = NSTextField()
urlField.frame = NSRect(x: 0, y: 0, width: 300, height: 20)
urlField.lineBreakMode = NSLineBreakMode.byTruncatingHead
urlField.usesSingleLineMode = true
alert.accessoryView = urlField
alert.addButton(withTitle: "Set")
alert.addButton(withTitle: "Cancel")
alert.beginSheetModal(for: self.window!, completionHandler: { response in
if response == NSAlertFirstButtonReturn {
var text = (alert.accessoryView as! NSTextField).stringValue
// Add prefix if necessary
if !(text.lowercased().hasPrefix("http://") || text.lowercased().hasPrefix("https://")) {
text = "http://" + text
}
// Save to defaults if valid. Else, use Helium default page
if self.validateURL(text) {
UserDefaults.standard.set(text, forKey: UserSetting.homePageURL.userDefaultsKey)
}
else{
UserDefaults.standard.set("https://cdn.rawgit.com/brorbw/Helium/master/helium_start.html", forKey: UserSetting.homePageURL.userDefaultsKey)
}
// Load new Home page
self.webViewController.loadAlmostURL(UserDefaults.standard.string(forKey: UserSetting.homePageURL.userDefaultsKey)!)
}
})
}
//
func validateURL (_ stringURL : String) -> Bool {
let urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx])
return predicate.evaluate(with: stringURL)
}
@objc fileprivate func didBecomeActive() {
panel.ignoresMouseEvents = false
}
@objc fileprivate func willResignActive() {
if currentlyTranslucent {
panel.ignoresMouseEvents = true
}
}
fileprivate func didEnableTranslucency() {
translucencyEnabled = true
}
fileprivate func didDisableTranslucency() {
translucencyEnabled = false
}
fileprivate func didUpdateAlpha(_ newAlpha: CGFloat) {
alpha = newAlpha / 100
}
}
| mit | ff205bf5303c03a7ff87cd6c4038bec2 | 31.396285 | 186 | 0.610856 | 5.530655 | false | false | false | false |
LoopKit/LoopKit | LoopKitUI/Views/ScheduleItemView.swift | 1 | 1886 | //
// ScheduleItemView.swift
// LoopKitUI
//
// Created by Michael Pangburn on 4/24/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import SwiftUI
struct ScheduleItemView<ValueContent: View, ExpandedContent: View>: View {
var time: TimeInterval
@Binding var isEditing: Bool
var valueContent: ValueContent
var expandedContent: ExpandedContent
private let fixedMidnight = Calendar.current.startOfDay(for: Date(timeIntervalSinceReferenceDate: 0))
init(
time: TimeInterval,
isEditing: Binding<Bool>,
@ViewBuilder valueContent: () -> ValueContent,
@ViewBuilder expandedContent: () -> ExpandedContent
) {
self.time = time
self._isEditing = isEditing
self.valueContent = valueContent()
self.expandedContent = expandedContent()
}
var body: some View {
ExpandableSetting(
isEditing: $isEditing,
leadingValueContent: { timeText },
trailingValueContent: { valueContent },
expandedContent: { self.expandedContent }
)
}
private var timeText: Text {
let dayAtTime = fixedMidnight.addingTimeInterval(time)
return Text(DateFormatter.localizedString(from: dayAtTime, dateStyle: .none, timeStyle: .short))
.foregroundColor(isEditing ? .accentColor : Color(.label))
}
}
extension AnyTransition {
static let fadeInFromTop = move(edge: .top).combined(with: .opacity)
.delayingInsertion(by: 0.1)
.speedingUpRemoval(by: 1.8)
func delayingInsertion(by delay: TimeInterval) -> AnyTransition {
.asymmetric(insertion: animation(Animation.default.delay(delay)), removal: self)
}
func speedingUpRemoval(by factor: Double) -> AnyTransition {
.asymmetric(insertion: self, removal: animation(Animation.default.speed(factor)))
}
}
| mit | c61f6eeb09420be3d323d26fc1985b2f | 30.416667 | 105 | 0.669496 | 4.520384 | false | false | false | false |
JackieQi/ReSwift-Router | ReSwiftRouter/NavigationActions.swift | 2 | 1266 | //
// NavigationAction.swift
// Meet
//
// Created by Benjamin Encz on 11/27/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import ReSwift
/// Exports the type map needed for using ReSwiftRouter with a Recording Store
public let typeMap: [String: StandardActionConvertible.Type] =
["RE_SWIFT_ROUTER_SET_ROUTE": SetRouteAction.self]
public struct SetRouteAction: StandardActionConvertible {
let route: Route
let animated: Bool
public static let type = "RE_SWIFT_ROUTER_SET_ROUTE"
public init (_ route: Route, animated: Bool = true) {
self.route = route
self.animated = animated
}
public init(_ action: StandardAction) {
self.route = action.payload!["route"] as! Route
self.animated = action.payload!["animated"] as! Bool
}
public func toStandardAction() -> StandardAction {
return StandardAction(
type: SetRouteAction.type,
payload: ["route": route as AnyObject, "animated": animated as AnyObject],
isTypedAction: true
)
}
}
public struct SetRouteSpecificData: Action {
let route: Route
let data: Any
public init(route: Route, data: Any) {
self.route = route
self.data = data
}
}
| mit | 268c5fc6158c59172ce705dfbda7e9e2 | 24.816327 | 86 | 0.647431 | 4.202658 | false | false | false | false |
RemyDCF/tpg-offline | tpg offline Siri/DeparturesIntentHandler.swift | 1 | 1483 | //
// DeparturesIntentHandler.swift
// tpg offline Siri
//
// Created by レミー on 13/07/2018.
// Copyright © 2018 Remy. All rights reserved.
//
import UIKit
import Intents
import Alamofire
class DeparturesIntentHandler: INExtension, DeparturesIntentHandling {
func handle(intent: DeparturesIntent,
completion: @escaping (DeparturesIntentResponse) -> Void) {
guard let stopCode = intent.stop?.identifier else {
completion(DeparturesIntentResponse(code: .failure, userActivity: nil))
return
}
Alamofire
.request(URL.departures(with: stopCode), method: .get)
.responseData { (response) in
if let data = response.result.value {
var options = DeparturesOptions()
options.networkStatus = .online
let jsonDecoder = JSONDecoder()
jsonDecoder.userInfo = [ DeparturesOptions.key: options ]
do {
let json = try jsonDecoder.decode(DeparturesGroup.self, from: data)
completion(json.intentResponse)
return
} catch {
completion(DeparturesIntentResponse(code: .failure, userActivity: nil))
}
} else {
completion(DeparturesIntentResponse(code: .failure, userActivity: nil))
}
}
}
func confirm(intent: DeparturesIntent,
completion: @escaping (DeparturesIntentResponse) -> Void) {
completion(DeparturesIntentResponse(code: .success, userActivity: nil))
}
}
| mit | f6f4c7096c8da56db0d1ad01ed115fc2 | 31.8 | 83 | 0.654472 | 4.792208 | false | false | false | false |
surfandneptune/CommandCougar | Sources/CommandCougar/Flag.swift | 1 | 2845 | //
// Flag.swift
// CommandCougar
//
// Copyright (c) 2017 Surf & Neptune LLC (http://surfandneptune.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Option {
/// A flag is used to represent a entry in a command line argument
///
/// - short: A short entry would be -v. However flag only needs the v and not the dash
/// - long: A long entry would be --verbose
/// - both: Both flags are allowed
public enum Flag: Equatable, CustomStringConvertible {
case short(String)
case long(String)
case both(short: String, long: String)
/// The shortname of this Flag
public var shortName: String? {
switch self {
case .short(let s):
return s
case .both(let s, _):
return s
default:
return nil
}
}
/// The longname of this flag
public var longName: String? {
switch self {
case .long(let l):
return l
case .both(_ , let l):
return l
default:
return nil
}
}
/// The description of this flag as viewed in the help menu
public var description: String {
switch self {
case .short(name: let s):
return "-\(s)"
case .long(name: let l):
return "--\(l)"
case .both(short: let s, long: let l):
return "-\(s), --\(l)"
}
}
/// Equatability
public static func ==(lhs: Flag, rhs: Flag) -> Bool {
if let ls = lhs.shortName, let rs = rhs.shortName,
let ll = lhs.longName, let rl = rhs.longName {
return (ls == rs) && (ll == rl)
}
if let ls = lhs.shortName, let rs = rhs.shortName {
return ls == rs
}
if let ll = lhs.longName, let rl = rhs.longName {
return ll == rl
}
return false
}
public static func ==(lhs: Flag, rhs: String) -> Bool {
return (lhs.shortName == rhs) || (lhs.longName == rhs)
}
}
}
| mit | d48ab9d2eda0b982cd79c3961b87d7f2 | 28.329897 | 88 | 0.660808 | 3.587642 | false | false | false | false |
Resoulte/DYZB | DYZB/DYZB/Classes/Main/Controller/DYCustomViewController.swift | 1 | 2151 | //
// DYCustomViewController.swift
// DYZB
//
// Created by 师飞 on 2017/3/4.
// Copyright © 2017年 shifei. All rights reserved.
//
import UIKit
class DYCustomViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// 系统pop->view->target/action
// 自定义pan->view->target/action
// 1.取出手势,获取系统的pop手势
guard let systeamGrsture = interactivePopGestureRecognizer else {
return
}
// 2.获取添加手势的view
guard let gestureView = systeamGrsture.view else {
return
}
// 3.获取target/action
// 3.1利用运行时机制获得所有的属性名称
var count : UInt32 = 0
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)
for i in 0..<count {
let ivar = ivars?[Int(i)]
let name = ivar_getName(ivar)
print(String(cString: name!))
}
let targets = systeamGrsture.value(forKey: "_targets") as? [NSObject]
guard let targetObject = targets?.first else {
return
}
print(targetObject)
// 3.2 取出target
guard let target = targetObject.value(forKey: "target") else {return}
// guard let action = targetObject.value(forKey: "action") as? Selector else {return}
let action = Selector(("handleNavigationTransition:"))
// 4.创建自己的新的pan手势
let panGesture = UIPanGestureRecognizer()
gestureView.addGestureRecognizer(panGesture)
panGesture.addTarget(target, action: action)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
viewController.hidesBottomBarWhenPushed = true
super.pushViewController(viewController, animated: animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | ee1865a830ae357a312fc34e65fcdb5f | 26.945205 | 92 | 0.595098 | 4.811321 | false | false | false | false |
therealbnut/swift | stdlib/public/SDK/Foundation/DateInterval.swift | 4 | 8910 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/// DateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. DateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct DateInterval : ReferenceConvertible, Comparable, Hashable {
public typealias ReferenceType = NSDateInterval
/// The start date.
public var start : Date
/// The end date.
///
/// - precondition: `end >= start`
public var end : Date {
get {
return start + duration
}
set {
precondition(newValue >= start, "Reverse intervals are not allowed")
duration = newValue.timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate
}
}
/// The duration.
///
/// - precondition: `duration >= 0`
public var duration : TimeInterval {
willSet {
precondition(newValue >= 0, "Negative durations are not allowed")
}
}
/// Initializes a `DateInterval` with start and end dates set to the current date and the duration set to `0`.
public init() {
let d = Date()
start = d
duration = 0
}
/// Initialize a `DateInterval` with the specified start and end date.
///
/// - precondition: `end >= start`
public init(start: Date, end: Date) {
if end < start {
fatalError("Reverse intervals are not allowed")
}
self.start = start
duration = end.timeIntervalSince(start)
}
/// Initialize a `DateInterval` with the specified start date and duration.
///
/// - precondition: `duration >= 0`
public init(start: Date, duration: TimeInterval) {
precondition(duration >= 0, "Negative durations are not allowed")
self.start = start
self.duration = duration
}
/**
Compare two DateIntervals.
This method prioritizes ordering by start date. If the start dates are equal, then it will order by duration.
e.g. Given intervals a and b
```
a. |-----|
b. |-----|
```
`a.compare(b)` would return `.OrderedAscending` because a's start date is earlier in time than b's start date.
In the event that the start dates are equal, the compare method will attempt to order by duration.
e.g. Given intervals c and d
```
c. |-----|
d. |---|
```
`c.compare(d)` would result in `.OrderedDescending` because c is longer than d.
If both the start dates and the durations are equal, then the intervals are considered equal and `.OrderedSame` is returned as the result.
*/
public func compare(_ dateInterval: DateInterval) -> ComparisonResult {
let result = start.compare(dateInterval.start)
if result == .orderedSame {
if self.duration < dateInterval.duration { return .orderedAscending }
if self.duration > dateInterval.duration { return .orderedDescending }
return .orderedSame
}
return result
}
/// Returns `true` if `self` intersects the `dateInterval`.
public func intersects(_ dateInterval: DateInterval) -> Bool {
return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(start) || dateInterval.contains(end)
}
/// Returns a DateInterval that represents the interval where the given date interval and the current instance intersect.
///
/// In the event that there is no intersection, the method returns nil.
public func intersection(with dateInterval: DateInterval) -> DateInterval? {
if !intersects(dateInterval) {
return nil
}
if self == dateInterval {
return self
}
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalForSelfEnd = end.timeIntervalSinceReferenceDate
let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate
let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate
let resultStartDate : Date
if timeIntervalForGivenStart >= timeIntervalForSelfStart {
resultStartDate = dateInterval.start
} else {
// self starts after given
resultStartDate = start
}
let resultEndDate : Date
if timeIntervalForGivenEnd >= timeIntervalForSelfEnd {
resultEndDate = end
} else {
// given ends before self
resultEndDate = dateInterval.end
}
return DateInterval(start: resultStartDate, end: resultEndDate)
}
/// Returns `true` if `self` contains `date`.
public func contains(_ date: Date) -> Bool {
let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalforSelfEnd = end.timeIntervalSinceReferenceDate
if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) {
return true
}
return false
}
public var hashValue: Int {
var buf: (UInt, UInt) = (UInt(start.timeIntervalSinceReferenceDate), UInt(end.timeIntervalSinceReferenceDate))
return withUnsafeMutablePointer(to: &buf) {
return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self), CFIndex(MemoryLayout<UInt>.size * 2)))
}
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static func ==(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.start == rhs.start && lhs.duration == rhs.duration
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static func <(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension DateInterval : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "\(start) to \(end)"
}
public var debugDescription: String {
return description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "start", value: start))
c.append((label: "end", value: end))
c.append((label: "duration", value: duration))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension DateInterval : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSDateInterval.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDateInterval {
return NSDateInterval(start: start, duration: duration)
}
public static func _forceBridgeFromObjectiveC(_ dateInterval: NSDateInterval, result: inout DateInterval?) {
if !_conditionallyBridgeFromObjectiveC(dateInterval, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ dateInterval : NSDateInterval, result: inout DateInterval?) -> Bool {
result = DateInterval(start: dateInterval.startDate, duration: dateInterval.duration)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDateInterval?) -> DateInterval {
var result: DateInterval?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension NSDateInterval : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as DateInterval)
}
}
| apache-2.0 | 604a2e0c605a0a4cb8afa92db69836a6 | 37.571429 | 327 | 0.638496 | 5.138408 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus/Util/Notifications.swift | 1 | 3545 | import Foundation
import UserNotifications
class Notifications {
static func badge(badge: InAppBadge) {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = badge.title
content.body = badge.summary
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "badge_notification"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let identifier = "badge"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
center.add(request) { error in
if let error = error {
Log.error("Problem adding notification: \(error.localizedDescription)")
} else {
Log.error("Successfully added notification")
}
}
}
static func trip(trip: CloudTrip) {
let content = UNMutableNotificationContent()
let originName = BusStopRealmHelper.getName(id: trip.origin)
let destinationName = BusStopRealmHelper.getName(id: trip.destination)
content.title = L10n.Notification.Trip.title
content.body = L10n.Notification.Trip.body(originName, destinationName)
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "trip_notification"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let identifier = "trip"
add(identifier: identifier, content: content, trigger: trigger)
}
static func survey(hash: String) {
let content = UNMutableNotificationContent()
content.title = L10n.Notification.Survey.title
content.body = L10n.Notification.Survey.body
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "survey_notification"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let identifier = "survey"
add(identifier: identifier, content: content, trigger: trigger)
}
static func news(title: String) {
let content = UNMutableNotificationContent()
content.title = title
content.body = L10n.Notification.News.clickForMore
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "news_notification"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let identifier = "news"
add(identifier: identifier, content: content, trigger: trigger)
}
// ==================================================== UTILS ======================================================
static func clearAll() {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
private static func add(identifier: String, content: UNMutableNotificationContent, trigger: UNNotificationTrigger) {
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request) { error in
if let error = error {
Log.error("Problem adding \(identifier) notification: \(error.localizedDescription)")
} else {
Log.error("Successfully added \(identifier) notification")
}
}
}
}
| gpl-3.0 | 1556dc498f04eb142e6235e9b6e00f27 | 36.712766 | 120 | 0.649647 | 5.573899 | false | false | false | false |
HcomCoolCode/hotelowy | AcceptanceTests/FITHotelDataSet.swift | 1 | 1893 | //
// FITHotelDataSet.swift
// ListOfHotels
//
// Created by Richard Moult on 19/04/2016.
// Copyright © 2016 Expedia. All rights reserved.
//
import Foundation
struct FITHotelData {
var title:NSString
var starRating:NSString
var imageUrl:NSString
var id:NSString
static func jsonArray(array : [FITHotelData]) -> String {
return "[" + array.map {$0.jsonRepresentation}.joinWithSeparator(",") + "]"
}
var jsonRepresentation : String {
let hotelId:Int = id.integerValue
let starRatingValue:Float = starRating.floatValue
if id.length > 0 {
return "{\"hotelName\":\"\(title)\",\"starRating\":\(starRatingValue),\"thumbnailUrl\":\"\(imageUrl)\",\"hotelId\":\(hotelId)}"
}
else {
return "{\"hotelName\":\"\(title)\",\"starRating\":\(starRatingValue),\"thumbnailUrl\":\"\(imageUrl)\"}"
}
}
}
var staticHotelDataSet = [NSString: [FITHotelData]]()
@objc(FITHotelDataSet)
class FITHotelDataSet: NSObject {
// Id to identify the hotelData in the hotelDataSet
var staticHotelDataKey:NSString
// Array of table rows
var hotelDataSet = [FITHotelData]()
// Properties
var title:String?
var starRating:NSString?
var imageUrl:NSString?
var id: NSString {
set {
let hotelData = FITHotelData(title: title!, starRating: starRating!, imageUrl: imageUrl!, id: newValue)
self.hotelDataSet.append(hotelData)
}
get {
return ""
}
}
init(string: NSString) {
self.staticHotelDataKey = string
super.init()
}
func endTable() {
staticHotelDataSet[self.staticHotelDataKey] = hotelDataSet
}
class func getStaticHotelDataSet(staticHotelDataKey: NSString) -> [FITHotelData]? {
return staticHotelDataSet[staticHotelDataKey]
}
}
| mit | 803bd4141339df973582b1921c2df71d | 23.25641 | 139 | 0.624207 | 4.504762 | false | false | false | false |
AppTown/OpenWeather | OpenWeather/OpenWeather/WeatherIconsFontMapper.swift | 1 | 20932 | //
// WeatherIconsFontMap.swift
// OpenWeather
//
// Created by Dario Banno on 29/05/2017.
// Copyright © 2017 AppTown. All rights reserved.
//
import Foundation
/// Font Map for Weather Icons
/// URL: https://erikflowers.github.io/weather-icons/
/// Original map: https://erikflowers.github.io/weather-icons/api-list.html
/// Official OWM api icons: http://openweathermap.org/weather-conditions
struct WeatherIconsFontMapper {
static let charactersMap: [String:Character] = [
"wi-owm-200": "\u{f01e}",
"wi-owm-201": "\u{f01e}",
"wi-owm-202": "\u{f01e}",
"wi-owm-210": "\u{f016}",
"wi-owm-211": "\u{f016}",
"wi-owm-212": "\u{f016}",
"wi-owm-221": "\u{f016}",
"wi-owm-230": "\u{f01e}",
"wi-owm-231": "\u{f01e}",
"wi-owm-232": "\u{f01e}",
"wi-owm-300": "\u{f01c}",
"wi-owm-301": "\u{f01c}",
"wi-owm-302": "\u{f019}",
"wi-owm-310": "\u{f017}",
"wi-owm-311": "\u{f019}",
"wi-owm-312": "\u{f019}",
"wi-owm-313": "\u{f01a}",
"wi-owm-314": "\u{f019}",
"wi-owm-321": "\u{f01c}",
"wi-owm-500": "\u{f01c}",
"wi-owm-501": "\u{f019}",
"wi-owm-502": "\u{f019}",
"wi-owm-503": "\u{f019}",
"wi-owm-504": "\u{f019}",
"wi-owm-511": "\u{f017}",
"wi-owm-520": "\u{f01a}",
"wi-owm-521": "\u{f01a}",
"wi-owm-522": "\u{f01a}",
"wi-owm-531": "\u{f01d}",
"wi-owm-600": "\u{f01b}",
"wi-owm-601": "\u{f01b}",
"wi-owm-602": "\u{f0b5}",
"wi-owm-611": "\u{f017}",
"wi-owm-612": "\u{f017}",
"wi-owm-615": "\u{f017}",
"wi-owm-616": "\u{f017}",
"wi-owm-620": "\u{f017}",
"wi-owm-621": "\u{f01b}",
"wi-owm-622": "\u{f01b}",
"wi-owm-701": "\u{f01a}",
"wi-owm-711": "\u{f062}",
"wi-owm-721": "\u{f0b6}",
"wi-owm-731": "\u{f063}",
"wi-owm-741": "\u{f014}",
"wi-owm-761": "\u{f063}",
"wi-owm-762": "\u{f063}",
"wi-owm-771": "\u{f011}",
"wi-owm-781": "\u{f056}",
"wi-owm-800": "\u{f00d}",
"wi-owm-801": "\u{f011}",
"wi-owm-802": "\u{f011}",
"wi-owm-803": "\u{f012}",
"wi-owm-804": "\u{f013}",
"wi-owm-900": "\u{f056}",
"wi-owm-901": "\u{f01d}",
"wi-owm-902": "\u{f073}",
"wi-owm-903": "\u{f076}",
"wi-owm-904": "\u{f072}",
"wi-owm-905": "\u{f021}",
"wi-owm-906": "\u{f015}",
"wi-owm-957": "\u{f050}",
"wi-owm-day-200": "\u{f010}",
"wi-owm-day-201": "\u{f010}",
"wi-owm-day-202": "\u{f010}",
"wi-owm-day-210": "\u{f005}",
"wi-owm-day-211": "\u{f005}",
"wi-owm-day-212": "\u{f005}",
"wi-owm-day-221": "\u{f005}",
"wi-owm-day-230": "\u{f010}",
"wi-owm-day-231": "\u{f010}",
"wi-owm-day-232": "\u{f010}",
"wi-owm-day-300": "\u{f00b}",
"wi-owm-day-301": "\u{f00b}",
"wi-owm-day-302": "\u{f008}",
"wi-owm-day-310": "\u{f008}",
"wi-owm-day-311": "\u{f008}",
"wi-owm-day-312": "\u{f008}",
"wi-owm-day-313": "\u{f008}",
"wi-owm-day-314": "\u{f008}",
"wi-owm-day-321": "\u{f00b}",
"wi-owm-day-500": "\u{f00b}",
"wi-owm-day-501": "\u{f008}",
"wi-owm-day-502": "\u{f008}",
"wi-owm-day-503": "\u{f008}",
"wi-owm-day-504": "\u{f008}",
"wi-owm-day-511": "\u{f006}",
"wi-owm-day-520": "\u{f009}",
"wi-owm-day-521": "\u{f009}",
"wi-owm-day-522": "\u{f009}",
"wi-owm-day-531": "\u{f00e}",
"wi-owm-day-600": "\u{f00a}",
"wi-owm-day-601": "\u{f0b2}",
"wi-owm-day-602": "\u{f00a}",
"wi-owm-day-611": "\u{f006}",
"wi-owm-day-612": "\u{f006}",
"wi-owm-day-615": "\u{f006}",
"wi-owm-day-616": "\u{f006}",
"wi-owm-day-620": "\u{f006}",
"wi-owm-day-621": "\u{f00a}",
"wi-owm-day-622": "\u{f00a}",
"wi-owm-day-701": "\u{f009}",
"wi-owm-day-711": "\u{f062}",
"wi-owm-day-721": "\u{f0b6}",
"wi-owm-day-731": "\u{f063}",
"wi-owm-day-741": "\u{f003}",
"wi-owm-day-761": "\u{f063}",
"wi-owm-day-762": "\u{f063}",
"wi-owm-day-781": "\u{f056}",
"wi-owm-day-800": "\u{f00d}",
"wi-owm-day-801": "\u{f000}",
"wi-owm-day-802": "\u{f000}",
"wi-owm-day-803": "\u{f000}",
"wi-owm-day-804": "\u{f00c}",
"wi-owm-day-900": "\u{f056}",
"wi-owm-day-902": "\u{f073}",
"wi-owm-day-903": "\u{f076}",
"wi-owm-day-904": "\u{f072}",
"wi-owm-day-906": "\u{f004}",
"wi-owm-day-957": "\u{f050}",
"wi-owm-night-200": "\u{f02d}",
"wi-owm-night-201": "\u{f02d}",
"wi-owm-night-202": "\u{f02d}",
"wi-owm-night-210": "\u{f025}",
"wi-owm-night-211": "\u{f025}",
"wi-owm-night-212": "\u{f025}",
"wi-owm-night-221": "\u{f025}",
"wi-owm-night-230": "\u{f02d}",
"wi-owm-night-231": "\u{f02d}",
"wi-owm-night-232": "\u{f02d}",
"wi-owm-night-300": "\u{f02b}",
"wi-owm-night-301": "\u{f02b}",
"wi-owm-night-302": "\u{f028}",
"wi-owm-night-310": "\u{f028}",
"wi-owm-night-311": "\u{f028}",
"wi-owm-night-312": "\u{f028}",
"wi-owm-night-313": "\u{f028}",
"wi-owm-night-314": "\u{f028}",
"wi-owm-night-321": "\u{f02b}",
"wi-owm-night-500": "\u{f02b}",
"wi-owm-night-501": "\u{f028}",
"wi-owm-night-502": "\u{f028}",
"wi-owm-night-503": "\u{f028}",
"wi-owm-night-504": "\u{f028}",
"wi-owm-night-511": "\u{f026}",
"wi-owm-night-520": "\u{f029}",
"wi-owm-night-521": "\u{f029}",
"wi-owm-night-522": "\u{f029}",
"wi-owm-night-531": "\u{f02c}",
"wi-owm-night-600": "\u{f02a}",
"wi-owm-night-601": "\u{f0b4}",
"wi-owm-night-602": "\u{f02a}",
"wi-owm-night-611": "\u{f026}",
"wi-owm-night-612": "\u{f026}",
"wi-owm-night-615": "\u{f026}",
"wi-owm-night-616": "\u{f026}",
"wi-owm-night-620": "\u{f026}",
"wi-owm-night-621": "\u{f02a}",
"wi-owm-night-622": "\u{f02a}",
"wi-owm-night-701": "\u{f029}",
"wi-owm-night-711": "\u{f062}",
"wi-owm-night-721": "\u{f0b6}",
"wi-owm-night-731": "\u{f063}",
"wi-owm-night-741": "\u{f04a}",
"wi-owm-night-761": "\u{f063}",
"wi-owm-night-762": "\u{f063}",
"wi-owm-night-781": "\u{f056}",
"wi-owm-night-800": "\u{f02e}",
"wi-owm-night-801": "\u{f022}",
"wi-owm-night-802": "\u{f022}",
"wi-owm-night-803": "\u{f022}",
"wi-owm-night-804": "\u{f086}",
"wi-owm-night-900": "\u{f056}",
"wi-owm-night-902": "\u{f073}",
"wi-owm-night-903": "\u{f076}",
"wi-owm-night-904": "\u{f072}",
"wi-owm-night-906": "\u{f024}",
"wi-owm-night-957": "\u{f050}"
]
static func iconString(id: String, nightTime: Bool = false) -> String? {
var idPrefix = "wi-owm"
if nightTime {
idPrefix += "-night"
}
guard let character = charactersMap["\(idPrefix)-\(id)"] else {
return nil
}
return String(describing: character)
}
}
/*
Open Weather Map ids meaning
wi-owm-200: thunderstorm
wi-owm-201: thunderstorm
wi-owm-202: thunderstorm
wi-owm-210: lightning
wi-owm-211: lightning
wi-owm-212: lightning
wi-owm-221: lightning
wi-owm-230: thunderstorm
wi-owm-231: thunderstorm
wi-owm-232: thunderstorm
wi-owm-300: sprinkle
wi-owm-301: sprinkle
wi-owm-302: rain
wi-owm-310: rain-mix
wi-owm-311: rain
wi-owm-312: rain
wi-owm-313: showers
wi-owm-314: rain
wi-owm-321: sprinkle
wi-owm-500: sprinkle
wi-owm-501: rain
wi-owm-502: rain
wi-owm-503: rain
wi-owm-504: rain
wi-owm-511: rain-mix
wi-owm-520: showers
wi-owm-521: showers
wi-owm-522: showers
wi-owm-531: storm-showers
wi-owm-600: snow
wi-owm-601: snow
wi-owm-602: sleet
wi-owm-611: rain-mix
wi-owm-612: rain-mix
wi-owm-615: rain-mix
wi-owm-616: rain-mix
wi-owm-620: rain-mix
wi-owm-621: snow
wi-owm-622: snow
wi-owm-701: showers
wi-owm-711: smoke
wi-owm-721: day-haze
wi-owm-731: dust
wi-owm-741: fog
wi-owm-761: dust
wi-owm-762: dust
wi-owm-771: cloudy-gusts
wi-owm-781: tornado
wi-owm-800: day-sunny
wi-owm-801: cloudy-gusts
wi-owm-802: cloudy-gusts
wi-owm-803: cloudy-gusts
wi-owm-804: cloudy
wi-owm-900: tornado
wi-owm-901: storm-showers
wi-owm-902: hurricane
wi-owm-903: snowflake-cold
wi-owm-904: hot
wi-owm-905: windy
wi-owm-906: hail
wi-owm-957: strong-wind
wi-owm-day-200: day-thunderstorm
wi-owm-day-201: day-thunderstorm
wi-owm-day-202: day-thunderstorm
wi-owm-day-210: day-lightning
wi-owm-day-211: day-lightning
wi-owm-day-212: day-lightning
wi-owm-day-221: day-lightning
wi-owm-day-230: day-thunderstorm
wi-owm-day-231: day-thunderstorm
wi-owm-day-232: day-thunderstorm
wi-owm-day-300: day-sprinkle
wi-owm-day-301: day-sprinkle
wi-owm-day-302: day-rain
wi-owm-day-310: day-rain
wi-owm-day-311: day-rain
wi-owm-day-312: day-rain
wi-owm-day-313: day-rain
wi-owm-day-314: day-rain
wi-owm-day-321: day-sprinkle
wi-owm-day-500: day-sprinkle
wi-owm-day-501: day-rain
wi-owm-day-502: day-rain
wi-owm-day-503: day-rain
wi-owm-day-504: day-rain
wi-owm-day-511: day-rain-mix
wi-owm-day-520: day-showers
wi-owm-day-521: day-showers
wi-owm-day-522: day-showers
wi-owm-day-531: day-storm-showers
wi-owm-day-600: day-snow
wi-owm-day-601: day-sleet
wi-owm-day-602: day-snow
wi-owm-day-611: day-rain-mix
wi-owm-day-612: day-rain-mix
wi-owm-day-615: day-rain-mix
wi-owm-day-616: day-rain-mix
wi-owm-day-620: day-rain-mix
wi-owm-day-621: day-snow
wi-owm-day-622: day-snow
wi-owm-day-701: day-showers
wi-owm-day-711: smoke
wi-owm-day-721: day-haze
wi-owm-day-731: dust
wi-owm-day-741: day-fog
wi-owm-day-761: dust
wi-owm-day-762: dust
wi-owm-day-781: tornado
wi-owm-day-800: day-sunny
wi-owm-day-801: day-cloudy-gusts
wi-owm-day-802: day-cloudy-gusts
wi-owm-day-803: day-cloudy-gusts
wi-owm-day-804: day-sunny-overcast
wi-owm-day-900: tornado
wi-owm-day-902: hurricane
wi-owm-day-903: snowflake-cold
wi-owm-day-904: hot
wi-owm-day-906: day-hail
wi-owm-day-957: strong-wind
wi-owm-night-200: night-alt-thunderstorm
wi-owm-night-201: night-alt-thunderstorm
wi-owm-night-202: night-alt-thunderstorm
wi-owm-night-210: night-alt-lightning
wi-owm-night-211: night-alt-lightning
wi-owm-night-212: night-alt-lightning
wi-owm-night-221: night-alt-lightning
wi-owm-night-230: night-alt-thunderstorm
wi-owm-night-231: night-alt-thunderstorm
wi-owm-night-232: night-alt-thunderstorm
wi-owm-night-300: night-alt-sprinkle
wi-owm-night-301: night-alt-sprinkle
wi-owm-night-302: night-alt-rain
wi-owm-night-310: night-alt-rain
wi-owm-night-311: night-alt-rain
wi-owm-night-312: night-alt-rain
wi-owm-night-313: night-alt-rain
wi-owm-night-314: night-alt-rain
wi-owm-night-321: night-alt-sprinkle
wi-owm-night-500: night-alt-sprinkle
wi-owm-night-501: night-alt-rain
wi-owm-night-502: night-alt-rain
wi-owm-night-503: night-alt-rain
wi-owm-night-504: night-alt-rain
wi-owm-night-511: night-alt-rain-mix
wi-owm-night-520: night-alt-showers
wi-owm-night-521: night-alt-showers
wi-owm-night-522: night-alt-showers
wi-owm-night-531: night-alt-storm-showers
wi-owm-night-600: night-alt-snow
wi-owm-night-601: night-alt-sleet
wi-owm-night-602: night-alt-snow
wi-owm-night-611: night-alt-rain-mix
wi-owm-night-612: night-alt-rain-mix
wi-owm-night-615: night-alt-rain-mix
wi-owm-night-616: night-alt-rain-mix
wi-owm-night-620: night-alt-rain-mix
wi-owm-night-621: night-alt-snow
wi-owm-night-622: night-alt-snow
wi-owm-night-701: night-alt-showers
wi-owm-night-711: smoke
wi-owm-night-721: day-haze
wi-owm-night-731: dust
wi-owm-night-741: night-fog
wi-owm-night-761: dust
wi-owm-night-762: dust
wi-owm-night-781: tornado
wi-owm-night-800: night-clear
wi-owm-night-801: night-alt-cloudy-gusts
wi-owm-night-802: night-alt-cloudy-gusts
wi-owm-night-803: night-alt-cloudy-gusts
wi-owm-night-804: night-alt-cloudy
wi-owm-night-900: tornado
wi-owm-night-902: hurricane
wi-owm-night-903: snowflake-cold
wi-owm-night-904: hot
wi-owm-night-906: night-alt-hail
wi-owm-night-957: strong-wind
--
From weather-icons.css
.wi-owm-200:before {
content: "\f01e";
}
.wi-owm-201:before {
content: "\f01e";
}
.wi-owm-202:before {
content: "\f01e";
}
.wi-owm-210:before {
content: "\f016";
}
.wi-owm-211:before {
content: "\f016";
}
.wi-owm-212:before {
content: "\f016";
}
.wi-owm-221:before {
content: "\f016";
}
.wi-owm-230:before {
content: "\f01e";
}
.wi-owm-231:before {
content: "\f01e";
}
.wi-owm-232:before {
content: "\f01e";
}
.wi-owm-300:before {
content: "\f01c";
}
.wi-owm-301:before {
content: "\f01c";
}
.wi-owm-302:before {
content: "\f019";
}
.wi-owm-310:before {
content: "\f017";
}
.wi-owm-311:before {
content: "\f019";
}
.wi-owm-312:before {
content: "\f019";
}
.wi-owm-313:before {
content: "\f01a";
}
.wi-owm-314:before {
content: "\f019";
}
.wi-owm-321:before {
content: "\f01c";
}
.wi-owm-500:before {
content: "\f01c";
}
.wi-owm-501:before {
content: "\f019";
}
.wi-owm-502:before {
content: "\f019";
}
.wi-owm-503:before {
content: "\f019";
}
.wi-owm-504:before {
content: "\f019";
}
.wi-owm-511:before {
content: "\f017";
}
.wi-owm-520:before {
content: "\f01a";
}
.wi-owm-521:before {
content: "\f01a";
}
.wi-owm-522:before {
content: "\f01a";
}
.wi-owm-531:before {
content: "\f01d";
}
.wi-owm-600:before {
content: "\f01b";
}
.wi-owm-601:before {
content: "\f01b";
}
.wi-owm-602:before {
content: "\f0b5";
}
.wi-owm-611:before {
content: "\f017";
}
.wi-owm-612:before {
content: "\f017";
}
.wi-owm-615:before {
content: "\f017";
}
.wi-owm-616:before {
content: "\f017";
}
.wi-owm-620:before {
content: "\f017";
}
.wi-owm-621:before {
content: "\f01b";
}
.wi-owm-622:before {
content: "\f01b";
}
.wi-owm-701:before {
content: "\f01a";
}
.wi-owm-711:before {
content: "\f062";
}
.wi-owm-721:before {
content: "\f0b6";
}
.wi-owm-731:before {
content: "\f063";
}
.wi-owm-741:before {
content: "\f014";
}
.wi-owm-761:before {
content: "\f063";
}
.wi-owm-762:before {
content: "\f063";
}
.wi-owm-771:before {
content: "\f011";
}
.wi-owm-781:before {
content: "\f056";
}
.wi-owm-800:before {
content: "\f00d";
}
.wi-owm-801:before {
content: "\f011";
}
.wi-owm-802:before {
content: "\f011";
}
.wi-owm-803:before {
content: "\f012";
}
.wi-owm-804:before {
content: "\f013";
}
.wi-owm-900:before {
content: "\f056";
}
.wi-owm-901:before {
content: "\f01d";
}
.wi-owm-902:before {
content: "\f073";
}
.wi-owm-903:before {
content: "\f076";
}
.wi-owm-904:before {
content: "\f072";
}
.wi-owm-905:before {
content: "\f021";
}
.wi-owm-906:before {
content: "\f015";
}
.wi-owm-957:before {
content: "\f050";
}
.wi-owm-day-200:before {
content: "\f010";
}
.wi-owm-day-201:before {
content: "\f010";
}
.wi-owm-day-202:before {
content: "\f010";
}
.wi-owm-day-210:before {
content: "\f005";
}
.wi-owm-day-211:before {
content: "\f005";
}
.wi-owm-day-212:before {
content: "\f005";
}
.wi-owm-day-221:before {
content: "\f005";
}
.wi-owm-day-230:before {
content: "\f010";
}
.wi-owm-day-231:before {
content: "\f010";
}
.wi-owm-day-232:before {
content: "\f010";
}
.wi-owm-day-300:before {
content: "\f00b";
}
.wi-owm-day-301:before {
content: "\f00b";
}
.wi-owm-day-302:before {
content: "\f008";
}
.wi-owm-day-310:before {
content: "\f008";
}
.wi-owm-day-311:before {
content: "\f008";
}
.wi-owm-day-312:before {
content: "\f008";
}
.wi-owm-day-313:before {
content: "\f008";
}
.wi-owm-day-314:before {
content: "\f008";
}
.wi-owm-day-321:before {
content: "\f00b";
}
.wi-owm-day-500:before {
content: "\f00b";
}
.wi-owm-day-501:before {
content: "\f008";
}
.wi-owm-day-502:before {
content: "\f008";
}
.wi-owm-day-503:before {
content: "\f008";
}
.wi-owm-day-504:before {
content: "\f008";
}
.wi-owm-day-511:before {
content: "\f006";
}
.wi-owm-day-520:before {
content: "\f009";
}
.wi-owm-day-521:before {
content: "\f009";
}
.wi-owm-day-522:before {
content: "\f009";
}
.wi-owm-day-531:before {
content: "\f00e";
}
.wi-owm-day-600:before {
content: "\f00a";
}
.wi-owm-day-601:before {
content: "\f0b2";
}
.wi-owm-day-602:before {
content: "\f00a";
}
.wi-owm-day-611:before {
content: "\f006";
}
.wi-owm-day-612:before {
content: "\f006";
}
.wi-owm-day-615:before {
content: "\f006";
}
.wi-owm-day-616:before {
content: "\f006";
}
.wi-owm-day-620:before {
content: "\f006";
}
.wi-owm-day-621:before {
content: "\f00a";
}
.wi-owm-day-622:before {
content: "\f00a";
}
.wi-owm-day-701:before {
content: "\f009";
}
.wi-owm-day-711:before {
content: "\f062";
}
.wi-owm-day-721:before {
content: "\f0b6";
}
.wi-owm-day-731:before {
content: "\f063";
}
.wi-owm-day-741:before {
content: "\f003";
}
.wi-owm-day-761:before {
content: "\f063";
}
.wi-owm-day-762:before {
content: "\f063";
}
.wi-owm-day-781:before {
content: "\f056";
}
.wi-owm-day-800:before {
content: "\f00d";
}
.wi-owm-day-801:before {
content: "\f000";
}
.wi-owm-day-802:before {
content: "\f000";
}
.wi-owm-day-803:before {
content: "\f000";
}
.wi-owm-day-804:before {
content: "\f00c";
}
.wi-owm-day-900:before {
content: "\f056";
}
.wi-owm-day-902:before {
content: "\f073";
}
.wi-owm-day-903:before {
content: "\f076";
}
.wi-owm-day-904:before {
content: "\f072";
}
.wi-owm-day-906:before {
content: "\f004";
}
.wi-owm-day-957:before {
content: "\f050";
}
.wi-owm-night-200:before {
content: "\f02d";
}
.wi-owm-night-201:before {
content: "\f02d";
}
.wi-owm-night-202:before {
content: "\f02d";
}
.wi-owm-night-210:before {
content: "\f025";
}
.wi-owm-night-211:before {
content: "\f025";
}
.wi-owm-night-212:before {
content: "\f025";
}
.wi-owm-night-221:before {
content: "\f025";
}
.wi-owm-night-230:before {
content: "\f02d";
}
.wi-owm-night-231:before {
content: "\f02d";
}
.wi-owm-night-232:before {
content: "\f02d";
}
.wi-owm-night-300:before {
content: "\f02b";
}
.wi-owm-night-301:before {
content: "\f02b";
}
.wi-owm-night-302:before {
content: "\f028";
}
.wi-owm-night-310:before {
content: "\f028";
}
.wi-owm-night-311:before {
content: "\f028";
}
.wi-owm-night-312:before {
content: "\f028";
}
.wi-owm-night-313:before {
content: "\f028";
}
.wi-owm-night-314:before {
content: "\f028";
}
.wi-owm-night-321:before {
content: "\f02b";
}
.wi-owm-night-500:before {
content: "\f02b";
}
.wi-owm-night-501:before {
content: "\f028";
}
.wi-owm-night-502:before {
content: "\f028";
}
.wi-owm-night-503:before {
content: "\f028";
}
.wi-owm-night-504:before {
content: "\f028";
}
.wi-owm-night-511:before {
content: "\f026";
}
.wi-owm-night-520:before {
content: "\f029";
}
.wi-owm-night-521:before {
content: "\f029";
}
.wi-owm-night-522:before {
content: "\f029";
}
.wi-owm-night-531:before {
content: "\f02c";
}
.wi-owm-night-600:before {
content: "\f02a";
}
.wi-owm-night-601:before {
content: "\f0b4";
}
.wi-owm-night-602:before {
content: "\f02a";
}
.wi-owm-night-611:before {
content: "\f026";
}
.wi-owm-night-612:before {
content: "\f026";
}
.wi-owm-night-615:before {
content: "\f026";
}
.wi-owm-night-616:before {
content: "\f026";
}
.wi-owm-night-620:before {
content: "\f026";
}
.wi-owm-night-621:before {
content: "\f02a";
}
.wi-owm-night-622:before {
content: "\f02a";
}
.wi-owm-night-701:before {
content: "\f029";
}
.wi-owm-night-711:before {
content: "\f062";
}
.wi-owm-night-721:before {
content: "\f0b6";
}
.wi-owm-night-731:before {
content: "\f063";
}
.wi-owm-night-741:before {
content: "\f04a";
}
.wi-owm-night-761:before {
content: "\f063";
}
.wi-owm-night-762:before {
content: "\f063";
}
.wi-owm-night-781:before {
content: "\f056";
}
.wi-owm-night-800:before {
content: "\f02e";
}
.wi-owm-night-801:before {
content: "\f022";
}
.wi-owm-night-802:before {
content: "\f022";
}
.wi-owm-night-803:before {
content: "\f022";
}
.wi-owm-night-804:before {
content: "\f086";
}
.wi-owm-night-900:before {
content: "\f056";
}
.wi-owm-night-902:before {
content: "\f073";
}
.wi-owm-night-903:before {
content: "\f076";
}
.wi-owm-night-904:before {
content: "\f072";
}
.wi-owm-night-906:before {
content: "\f024";
}
.wi-owm-night-957:before {
content: "\f050";
}
*/
| bsd-3-clause | 5023ec40ed78ef59a5a0cdeac1e98e08 | 21.410064 | 76 | 0.567914 | 2.410572 | false | false | false | false |
colemancda/Pedido | CorePedidoServer/CorePedidoServer/Authentication.swift | 1 | 2051 | //
// Authentication.swift
// CorePedidoServer
//
// Created by Alsey Coleman Miller on 12/6/14.
// Copyright (c) 2014 ColemanCDA. All rights reserved.
//
import Foundation
import CoreData
import NetworkObjects
import CorePedido
func AuthenticationSessionFromRequestHeaders(headers: [String: String], context: NSManagedObjectContext) -> (Session?, NSError?) {
// get token header
let token = headers["Authorization"]
if token == nil {
return (nil, nil)
}
let fetchRequest = NSFetchRequest(entityName: "Session")
fetchRequest.predicate = NSComparisonPredicate(leftExpression: NSExpression(forKeyPath: "token"),
rightExpression: NSExpression(forConstantValue: token!),
modifier: NSComparisonPredicateModifier.DirectPredicateModifier,
type: NSPredicateOperatorType.EqualToPredicateOperatorType,
options: NSComparisonPredicateOptions.NormalizedPredicateOption)
// execute fetch request
var error: NSError?
var session: Session?
context.performBlockAndWait { () -> Void in
session = context.executeFetchRequest(fetchRequest, error: &error)?.first as? Session
}
// return found session or error
return (session, error)
}
func SessionTokenWithLength(length: UInt) -> String {
/** Random string generator. http://stackoverflow.com/questions/26845307/generate-random-alphanumeric-string-in-swift */
func randomStringWithLength (len : Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString : NSMutableString = NSMutableString(capacity: len)
for (var i=0; i < len; i++){
var length = UInt32 (letters.length)
var rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
return randomString
}
return randomStringWithLength(Int(length))
} | mit | 32a253bf407042888b745865584b74e4 | 30.090909 | 130 | 0.676743 | 5.258974 | false | false | false | false |
yonaskolb/SwagGen | Sources/Swagger/Component/ComponentResolver.swift | 1 | 3871 | import Foundation
#if !swift(>=4.2)
public protocol CaseIterable {
static var allCases: [Self] { get }
}
#endif
class ComponentResolver {
let spec: SwaggerSpec
var components: Components {
return spec.components
}
init(spec: SwaggerSpec) {
self.spec = spec
}
func resolve() {
resolve(components.schemas, resolve)
resolve(components.parameters, resolve)
resolve(components.requestBodies, resolve)
resolve(components.headers, resolve)
resolve(components.requestBodies, resolve)
spec.paths.forEach { path in
path.parameters.forEach(resolve)
path.operations.forEach { operation in
operation.pathParameters.forEach(resolve)
operation.operationParameters.forEach(resolve)
operation.responses.forEach(resolve)
if let requestBody = operation.requestBody {
resolveReference(requestBody, objects: components.requestBodies)
resolve(requestBody.value.content)
}
}
}
}
private func resolveReference<T>(_ reference: Reference<T>, objects: [ComponentObject<T>]) {
if reference.referenceType == T.componentType.rawValue,
let name = reference.referenceName,
let object = objects.first(where: { $0.name == name }) {
reference.resolve(with: object.value)
}
}
private func resolveReference<T: Component>(_ reference: PossibleReference<T>, objects: [ComponentObject<T>]) {
if case let .reference(reference) = reference {
resolveReference(reference, objects: objects)
}
}
private func resolve(_ schema: SchemaType) {
switch schema {
case let .reference(reference): resolveReference(reference, objects: components.schemas)
case let .object(object):
object.properties.forEach { resolve($0.schema) }
if let additionalProperties = object.additionalProperties {
resolve(additionalProperties)
}
case let .group(schemaGroup): schemaGroup.schemas.forEach(resolve)
case let .array(array):
switch array.items {
case let .single(schema): resolve(schema)
case let .multiple(schemas): schemas.forEach(resolve)
}
default: break
}
}
private func resolve(_ mediaItem: MediaItem) {
resolve(mediaItem.schema)
}
private func resolve(_ content: Content) {
for mediaItem in content.mediaItems.values {
resolve(mediaItem)
}
}
private func resolve(_ header: Header) {
resolve(header.schema.schema)
}
private func resolve(_ requestBody: RequestBody) {
resolve(requestBody.content)
}
private func resolve(_ schema: Schema) {
resolve(schema.type)
}
private func resolve(_ reference: PossibleReference<Parameter>) {
resolveReference(reference, objects: components.parameters)
resolve(reference.value)
}
private func resolve(_ parameter: Parameter) {
switch parameter.type {
case let .schema(schema): resolve(schema.schema)
case let .content(content): resolve(content)
}
}
private func resolve(_ response: OperationResponse) {
resolveReference(response.response, objects: components.responses)
if let content = response.response.value.content {
resolve(content)
}
for reference in response.response.value.headers.values {
resolveReference(reference, objects: components.headers)
}
}
private func resolve<T>(_ components: [ComponentObject<T>], _ resolver: (T) -> Void) {
components.forEach { resolver($0.value) }
}
}
| mit | d7feb4f8620961a3e7d1efb9db051108 | 30.471545 | 115 | 0.619478 | 4.90621 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io | CricketNews/CricketNews/Model/CricbuzzStory.swift | 1 | 1250 | //
// CricbuzzStory.swift
// CricketNews
//
// Created by Anirudh Das on 7/5/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct CricbuzzStory {
public var headline: String
public var summary: String
public var contentsArray: [String] = []
public var imageLinksArray: [String] = []
public init?(_ json: JSON) {
guard let newsInfo = json["news_info"].dictionary, let headline = newsInfo["headline"]?.string, let summary = newsInfo["summary"]?.string else {
return nil
}
self.headline = headline
self.summary = summary
if let contents = json["content"].array {
for item in contents {
if let type = item["type"].string, type == "text", let content = item["content"].string {
self.contentsArray.append(content)
}
}
}
if let imageUrl = json["image_url"].string, let images = json["images"].array {
for item in images {
if let url = item["url"].string {
self.imageLinksArray.append(imageUrl + "\(url)")
}
}
}
}
}
| apache-2.0 | 297374ac240a0879f115e5dcf1b1791a | 29.463415 | 152 | 0.550841 | 4.413428 | false | false | false | false |
JeeLiu/Mirror | Mirror/Mirror.swift | 1 | 3109 | //
// File.swift
// Mirror
//
// Created by Kostiantyn Koval on 05/07/15.
//
//
import Foundation
public struct MirrorItem {
public let name: String
public let type: Any.Type
public let value: Any
init(_ tup: (String, MirrorType)) {
self.name = tup.0
self.type = tup.1.valueType
self.value = tup.1.value
}
}
extension MirrorItem : Printable {
public var description: String {
return "\(name): \(type) = \(value)"
}
}
//MARK: -
public struct Mirror<T> {
private let mirror: MirrorType
let instance: T
public init (_ x: T) {
instance = x
mirror = reflect(x)
}
//MARK: - Type Info
/// Instance type full name, include Module
public var name: String {
return "\(instance.dynamicType)"
}
/// Instance type short name, just a type name, without Module
public var shortName: String {
return "\(instance.dynamicType)".pathExtension
}
public var isClass: Bool {
return mirror.objectIdentifier != nil
}
public var isStruct: Bool {
return mirror.objectIdentifier == nil
}
/// Type properties count
public var childrenCount: Int {
return mirror.count
}
public var memorySize: Int {
return sizeofValue(instance)
}
//MARK: - Children Inpection
/// Properties Names
public var names: [String] {
return map(self) { $0.name }
}
/// Properties Values
public var values: [Any] {
return map(self) { $0.value }
}
/// Properties Types
public var types: [Any.Type] {
return map(self) { $0.type }
}
/// Short style for type names
public var typesShortName: [String] {
return map(self) { "\($0.type)".pathExtension }
}
/// Mirror types for every children property
public var children: [MirrorItem] {
return map(self) { $0 }
}
//MARK: - Quering
/// Returns a property value for a property name
public subscript (key: String) -> Any? {
let res = findFirst(self) { $0.name == key }
return res.map { $0.value }
}
/// Returns a property value for a property name with a Genereci type
/// No casting needed
public func get<U>(key: String) -> U? {
let res = findFirst(self) { $0.name == key }
return res.flatMap { $0.value as? U }
}
/// Convert to a dicitonary with [PropertyName : PropertyValue] notation
public var toDictionary: [String : Any] {
var result: [String : Any] = [ : ]
for item in self {
result[item.name] = item.value
}
return result
}
/// Convert to NSDictionary.
/// Useful for saving it to Plist
public var toNSDictionary: NSDictionary {
var result: [String : AnyObject] = [ : ]
for item in self {
result[item.name] = item.value as? AnyObject
}
return result
}
}
extension Mirror : CollectionType, SequenceType {
public func generate() -> IndexingGenerator<[MirrorItem]> {
return children.generate()
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return mirror.count
}
public subscript (i: Int) -> MirrorItem {
return MirrorItem(mirror[i])
}
}
| mit | f9c6fd110e769db0f9823f8950499684 | 19.320261 | 74 | 0.623673 | 3.871731 | false | false | false | false |
typelift/Basis | Basis/Arrow.swift | 2 | 6460 | //
// Arrow.swift
// Basis
//
// Created by Robert Widmann on 9/9/14.
// Copyright (c) 2014 TypeLift. All rights reserved.
// Released under the MIT license.
//
/// An Arrow is most famous for being a "Generalization of a Monad". They're probably better
/// described as a more general view of computation. Where a monad M<A> yields a value of type A
/// given some context, an Arrow A<B, C> is a function from B -> C in some context A. Functions are
/// the simplest kind of Arrow (pun intended). Their context parameter, A, is essentially empty.
/// From there, the B -> C part of the arrow gets alpha-reduced to the A -> B part of the function
/// type.
///
/// Arrows can be modelled with circuit-esque diagrams, and indeed that can often be a better way to
/// envision the various arrow operators.
///
/// - >>> a -> [ f ] -> b -> [ g ] -> c
/// - <<< a -> [ g ] -> b -> [ f ] -> c
///
/// - arr a -> [ f ] -> b
///
/// - first a -> [ f ] -> b
/// c - - - - - -> c
///
/// - second c - - - - - -> c
/// a -> [ f ] -> b
///
///
/// - *** a - [ f ] -> b - •
/// \
/// o - -> (b, d)
/// /
/// c - [ g ] -> d - •
///
///
/// • a - [ f ] -> b - •
/// | \
/// - &&& a - o o - -> (b, c)
/// | /
/// • a - [ g ] -> c - •
///
/// Arrows inherit from Category so we can get Composition For Free™.
public protocol Arrow : Category {
/// Some arbitrary target our arrow can compose with.
typealias D
/// Some arbitrary target our arrow can compose with.
typealias E
/// Type of the result of first().
typealias FIRST = K2<(A, D), (B, D)>
/// Type of the result of second().
typealias SECOND = K2<(D, A), (D, B)>
/// Some arrow with an arbitrary target and source. Used in split().
typealias ADE = K2<D, E>
/// Type of the result of ***.
typealias SPLIT = K2<(A, D), (B, E)>
/// Some arrow from our target to some other arbitrary target. Used in fanout().
typealias ABD = K2<A, D>
/// Type of the result of &&&.
typealias FANOUT = K2<B, (B, D)>
/// Lift a function to an arrow.
static func arr(A -> B) -> Self
/// Splits the arrow into two tuples that model a computation that applies our Arrow to an
/// argument on the "left side" and sends the "right side" through unchanged.
///
/// The mirror image of second().
func first() -> FIRST
/// Splits the arrow into two tuples that model a computation that applies our Arrow to an
/// argument on the "right side" and sends the "left side" through unchanged.
///
/// The mirror image of first().
func second() -> SECOND
/// Split | Splits two computations and combines the result into one Arrow yielding a tuple of
/// the result of each side.
func ***(Self, ADE) -> SPLIT
/// Fanout | Given two functions with the same source but different targets, this function
/// splits the computation and combines the result of each Arrow into a tuple of the result of
/// each side.
func &&&(Self, ABD) -> FANOUT
}
/// Arrows that can produce an identity arrow.
public protocol ArrowZero : Arrow {
/// An arrow from A -> B. Colloquially, the "zero arrow".
typealias ABC = K2<A, B>
/// The identity arrow.
static func zeroArrow() -> ABC
}
/// A monoid for Arrows.
public protocol ArrowPlus : ArrowZero {
/// A binary function that combines two arrows.
func <+>(ABC, ABC) -> ABC
}
/// Arrows that permit "choice" or selecting which side of the input to apply themselves to.
///
/// - left a - - [ f ] - - > b
/// |
/// a - [f] -> b - o------EITHER------
/// |
/// d - - - - - - - > d
///
/// - right d - - - - - - - > d
/// |
/// a - [f] -> b - o------EITHER------
/// |
/// a - - [ f ] - - > b
///
/// - +++ a - [ f ] -> b - • • a - [ f ] -> b
/// \ |
/// o - -> o-----EITHER-----
/// / |
/// d - [ g ] -> e - • • d - [ g ] -> e
///
/// - ||| a - [ f ] -> c - • • a - [ f ] -> c •
/// \ | \
/// o - -> o-----EITHER-------o - -> c
/// / | /
/// b - [ g ] -> c - • • b - [ g ] -> c •
///
public protocol ArrowChoice : Arrow {
/// The result of left
typealias LEFT = K2<Either<A, D>, Either<B, D>>
/// The result of right
typealias RIGHT = K2<Either<D, A>, Either<D, B>>
/// The result of +++
typealias SPLAT = K2<Either<A, D>, Either<B, E>>
/// Some arrow from a different source and target for fanin.
typealias ACD = K2<B, D>
/// The result of |||
typealias FANIN = K2<Either<A, B>, D>
/// Feed marked inputs through the argument arrow, passing the rest through unchanged to the
/// output.
static func left(Self) -> LEFT
/// The mirror image of left.
static func right(Self) -> RIGHT
/// Splat | Split the input between both argument arrows, then retag and merge their outputs
/// into Eithers.
func +++(Self, ADE) -> SPLAT
/// Fanin | Split the input between two argument arrows and merge their ouputs.
func |||(ABD, ACD) -> FANIN
}
/// Arrows that allow application of arrow inputs to other inputs. Such arrows are equivalent to
/// monads.
///
/// - app (f : a -> b) - •
/// \
/// o - a - [ f ] -> b
/// /
/// a ------------ •
///
public protocol ArrowApply : Arrow {
typealias APP = K2<(Self, A), B>
static func app() -> APP
}
/// Arrows that admit right-tightening recursion.
///
/// The 'loop' operator expresses computations in which an output value is fed back as input,
/// although the computation occurs only once.
///
/// •-------•
/// | |
/// - loop a - - [ f ] - -> b
/// | |
/// d-------•
///
public protocol ArrowLoop : Arrow {
typealias LOOP = K2<(A, D), (B, D)>
static func loop(LOOP) -> Self
}
| mit | 250d4eb57c321cef9bfd1fb18b526e43 | 32.416667 | 100 | 0.488778 | 3.628959 | false | false | false | false |
cuzv/Popover | PopoverSwift/Sources/PopoverView.swift | 1 | 10690 | //
// PopoverView.swift
// PopoverSwift
//
// Created by Roy Shaw on 3/18/16.
// Copyright © @2016 Red Rain (https://github.com/cuzv).
//
// 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
open class PopoverView: UIView {
fileprivate let items: [PopoverItem]
fileprivate let fromView: UIView
fileprivate let initialIndex: Int
fileprivate let direction: Direction
fileprivate let reverseHorizontalCoordinates: Bool
fileprivate let style: PopoverStyle
fileprivate let dismissHandler: (() -> Void)?
fileprivate weak var commonSuperView: UIView!
let arrawView: UIImageView = {
let view = UIImageView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let tableView: UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: .plain)
tableView.rowHeight = RowHeight
tableView.bounces = false
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
tableView.backgroundColor = UIColor.clear
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.layer.cornerRadius = CornerRadius
tableView.layer.masksToBounds = true
return tableView
}()
lazy var tableViewWidth: CGFloat = {
var maxLengthTitle: String = ""
self.items.forEach { (item: PopoverItem) -> Void in
if item.title.length > maxLengthTitle.length {
maxLengthTitle = item.title
}
}
var width: CGFloat = maxLengthTitle.size(font: CellLabelFont, preferredMaxLayoutWidth: CGFloat.greatestFiniteMagnitude).width
if width < 60 {
width = 60
}
width += Leading * 2
if self.style == .withImage {
width += ImageWidth + Spacing
}
return width
}()
lazy var tableViewHeight: CGFloat = {
let count = self.items.count > MaxRowCount ? MaxRowCount : self.items.count
return CGFloat(count) * RowHeight
}()
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(_ host: PopoverController, commonSuperView: UIView) {
if host.reverseHorizontalCoordinates {
self.items = host.items.reversed()
} else {
self.items = host.items
}
self.fromView = host.fromView
self.initialIndex = host.initialIndex
self.direction = host.direction
self.reverseHorizontalCoordinates = host.reverseHorizontalCoordinates
self.style = host.style
self.dismissHandler = host.dismissHandler
self.commonSuperView = commonSuperView
super.init(frame: CGRect.zero)
setup()
}
open override func layoutSubviews() {
super.layoutSubviews()
if nil != arrawView.layer.contents {
return
}
let color = items[0].coverColor ?? UIColor.white
let arrawCenterX: CGFloat = fromView.frame.midX - arrawView.frame.midX + arrawView.bounds.midX
let bounds = arrawView.bounds
DispatchQueue.global().async { () -> Void in
let image = drawArrawImage(
in: bounds,
strokeColor: color,
fillColor: color,
lineWidth: LineWidth,
arrawCenterX: arrawCenterX,
arrawWidth: 10,
arrawHeight: 10,
cornerRadius: CornerRadius,
handstand: self.reverseHorizontalCoordinates
)
DispatchQueue.main.async(execute: { () -> Void in
self.arrawView.image = image
})
}
tableView.scrollToRow(at: IndexPath(row: initialIndex, section: 0), at: .top, animated: false)
}
func setup() {
tableView.delegate = self
tableView.dataSource = self
addSubview(arrawView)
addSubview(tableView)
var clazz: AnyClass? = PopoverCell.self
var identifier: String = PopoverCell.identifier
if style == .withImage {
clazz = PopoverWihtImageCell.self
identifier = PopoverWihtImageCell.identifier
}
tableView.register(clazz, forCellReuseIdentifier: identifier)
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let location = touches.first?.location(in: self), !arrawView.frame.contains(location) {
dismiss()
}
}
func dismiss(completion: (() -> Void)? = nil) {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.tableView.alpha = 0
self.arrawView.alpha = 0
}, completion: {_ in
self.subviews.forEach { $0.removeFromSuperview() }
self.removeFromSuperview()
self.dismissHandler?()
completion?()
})
}
func addConstraints() {
let screenWidth: CGFloat = superview!.frame.width
var centerX: CGFloat = fromView.frame.origin.x + fromView.bounds.width / 2.0
let rightHand = centerX - screenWidth / 2.0 > 0
if rightHand {
centerX = screenWidth - centerX
}
var constant0: CGFloat = 0
let distance = centerX - (tableViewWidth / 2.0 + 6)
if distance <= 0 {
constant0 = rightHand ? distance : -distance
}
var attribute0: LayoutAttribute = .top
var attribute1: LayoutAttribute = .bottom
var constant1: CGFloat = 10
if direction == .up {
attribute0 = .bottom
attribute1 = .top
constant1 = -10
}
commonSuperView.addConstraints([
NSLayoutConstraint(
item: tableView,
attribute: .centerX,
relatedBy: .equal,
toItem: fromView,
attribute: .centerX,
multiplier: 1,
constant: constant0
),
NSLayoutConstraint(
item: tableView,
attribute: attribute0,
relatedBy: .equal,
toItem: fromView,
attribute: attribute1,
multiplier: 1,
constant: constant1
),
NSLayoutConstraint(
item: tableView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: tableViewWidth
),
NSLayoutConstraint(
item: tableView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: tableViewHeight
)
])
commonSuperView.addConstraints([
NSLayoutConstraint(
item: arrawView,
attribute: .width,
relatedBy: .equal,
toItem: tableView,
attribute: .width,
multiplier: 1,
constant: LineWidth * 2
),
NSLayoutConstraint(
item: arrawView,
attribute: .height,
relatedBy: .equal,
toItem: tableView,
attribute: .height,
multiplier: 1,
constant: abs(constant1) - 2
),
NSLayoutConstraint(
item: arrawView,
attribute: .centerX,
relatedBy: .equal,
toItem: tableView,
attribute: .centerX,
multiplier: 1,
constant: 0
),
NSLayoutConstraint(
item: arrawView,
attribute: .centerY,
relatedBy: .equal,
toItem: tableView,
attribute: .centerY,
multiplier: 1,
constant: -constant1 / 2.0
)
])
}
#if DEBUG
deinit {
debugPrint("\(#file):\(#line):\(type(of: self)):\(#function)")
}
#endif
}
extension PopoverView: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if style == .withImage {
guard let cell = tableView.dequeueReusableCell(withIdentifier: PopoverWihtImageCell.identifier) as? PopoverWihtImageCell else {
fatalError("Must register cell first")
}
cell.setupData(items[(indexPath as NSIndexPath).row])
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: PopoverCell.identifier) as? PopoverCell else {
fatalError("Must register cell first")
}
cell.setupData(items[(indexPath as NSIndexPath).row])
return cell
}
}
}
extension PopoverView: UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let popoverItem = items[(indexPath as NSIndexPath).row]
dismiss {
popoverItem.handler?(popoverItem)
}
}
}
| mit | 5746a11fd209651a4c3482e6066e898a | 33.259615 | 139 | 0.582468 | 5.265517 | false | false | false | false |
rnystrom/GitHawk | Classes/Issues/Comments/Reactions/Defaults+Reaction.swift | 1 | 1051 | //
// Defaults+Reaction.swift
// Freetime
//
// Created by Ehud Adler on 7/30/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
extension UserDefaults {
private static let defaultKey = "com.whoisryannystrom.freetime.default-reaction"
private static let disabledValue = "disabled"
// Stores ReactionContent in string form but
// accepts and returns in original form
func setDefault(reaction: ReactionContent) {
set(reaction.emoji, forKey: UserDefaults.defaultKey)
}
func disableReaction() {
set(UserDefaults.disabledValue, forKey: UserDefaults.defaultKey)
}
var defaultReaction: ReactionContent? {
// if value doesn't exist, first access, default to previous behavior of +1
guard let value = string(forKey: UserDefaults.defaultKey)
else { return ReactionContent.thumbsUp }
if value == UserDefaults.disabledValue {
return nil
} else {
let reaction = value.reaction
return reaction
}
}
}
| mit | 3e457c654fde01099196b482b39dcb6e | 29 | 84 | 0.66381 | 4.585153 | false | false | false | false |
luanlzsn/pos | pos/Carthage/Checkouts/IQKeyboardManager/IQKeyboardManagerSwift/IQKeyboardReturnKeyHandler.swift | 6 | 25186 | //
// IQKeyboardReturnKeyHandler.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// 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
/**
Manages the return key to work like next/done in a view hierarchy.
*/
open class IQKeyboardReturnKeyHandler: NSObject , UITextFieldDelegate, UITextViewDelegate {
///---------------
/// MARK: Settings
///---------------
/**
Delegate of textField/textView.
*/
open var delegate: (UITextFieldDelegate & UITextViewDelegate)?
/**
Set the last textfield return key type. Default is UIReturnKeyDefault.
*/
open var lastTextFieldReturnKeyType : UIReturnKeyType = UIReturnKeyType.default {
didSet {
for infoDict in textFieldInfoCache {
if let view = (infoDict as AnyObject).object(forKey: kIQTextField) as? UIView {
updateReturnKeyTypeOnTextField(view)
}
}
}
}
///--------------------------------------
/// MARK: Initialization/Deinitialization
///--------------------------------------
public override init() {
super.init()
}
/**
Add all the textFields available in UIViewController's view.
*/
public init(controller : UIViewController) {
super.init()
addResponderFromView(controller.view)
}
deinit {
for infoDict in textFieldInfoCache {
let view = (infoDict as AnyObject).object(forKey: kIQTextField) as? UIView
if let textField = view as? UITextField {
let returnKeyTypeValue = (infoDict as AnyObject).object(forKey: kIQTextFieldReturnKeyType) as! NSNumber
textField.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.intValue)!
textField.delegate = (infoDict as AnyObject).object(forKey: kIQTextFieldDelegate) as? UITextFieldDelegate
} else if let textView = view as? UITextView {
textView.returnKeyType = UIReturnKeyType(rawValue: ((infoDict as AnyObject).object(forKey: kIQTextFieldReturnKeyType) as! NSNumber).intValue)!
let returnKeyTypeValue = (infoDict as AnyObject).object(forKey: kIQTextFieldReturnKeyType) as! NSNumber
textView.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.intValue)!
textView.delegate = (infoDict as AnyObject).object(forKey: kIQTextFieldDelegate) as? UITextViewDelegate
}
}
textFieldInfoCache.removeAllObjects()
}
///------------------------
/// MARK: Private variables
///------------------------
fileprivate var textFieldInfoCache = NSMutableSet()
fileprivate let kIQTextField = "kIQTextField"
fileprivate let kIQTextFieldDelegate = "kIQTextFieldDelegate"
fileprivate let kIQTextFieldReturnKeyType = "kIQTextFieldReturnKeyType"
///------------------------
/// MARK: Private Functions
///------------------------
fileprivate func textFieldViewCachedInfo(_ textField : UIView) -> [String : AnyObject]? {
for infoDict in textFieldInfoCache {
if (infoDict as AnyObject).object(forKey: kIQTextField) as! NSObject == textField {
return infoDict as? [String : AnyObject]
}
}
return nil
}
fileprivate func updateReturnKeyTypeOnTextField(_ view : UIView)
{
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347)
for disabledClass in IQKeyboardManager.sharedManager().toolbarPreviousNextAllowedClasses {
superConsideredView = view.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
var textFields : [UIView]?
//If there is a tableView in view's hierarchy, then fetching all it's subview that responds.
if let unwrappedTableView = superConsideredView { // (Enhancement ID: #22)
textFields = unwrappedTableView.deepResponderViews()
} else { //Otherwise fetching all the siblings
textFields = view.responderSiblings()
//Sorting textFields according to behaviour
switch IQKeyboardManager.sharedManager().toolbarManageBehaviour {
//If needs to sort it by tag
case .byTag: textFields = textFields?.sortedArrayByTag()
//If needs to sort it by Position
case .byPosition: textFields = textFields?.sortedArrayByPosition()
default: break
}
}
if let lastView = textFields?.last {
if let textField = view as? UITextField {
//If it's the last textField in responder view, else next
textField.returnKeyType = (view == lastView) ? lastTextFieldReturnKeyType : UIReturnKeyType.next
} else if let textView = view as? UITextView {
//If it's the last textField in responder view, else next
textView.returnKeyType = (view == lastView) ? lastTextFieldReturnKeyType : UIReturnKeyType.next
}
}
}
///----------------------------------------------
/// MARK: Registering/Unregistering textFieldView
///----------------------------------------------
/**
Should pass UITextField/UITextView intance. Assign textFieldView delegate to self, change it's returnKeyType.
@param textFieldView UITextField/UITextView object to register.
*/
open func addTextFieldView(_ view : UIView) {
var dictInfo : [String : AnyObject] = [String : AnyObject]()
dictInfo[kIQTextField] = view
if let textField = view as? UITextField {
dictInfo[kIQTextFieldReturnKeyType] = textField.returnKeyType.rawValue as AnyObject?
if let textFieldDelegate = textField.delegate {
dictInfo[kIQTextFieldDelegate] = textFieldDelegate
}
textField.delegate = self
} else if let textView = view as? UITextView {
dictInfo[kIQTextFieldReturnKeyType] = textView.returnKeyType.rawValue as AnyObject?
if let textViewDelegate = textView.delegate {
dictInfo[kIQTextFieldDelegate] = textViewDelegate
}
textView.delegate = self
}
textFieldInfoCache.add(dictInfo)
}
/**
Should pass UITextField/UITextView intance. Restore it's textFieldView delegate and it's returnKeyType.
@param textFieldView UITextField/UITextView object to unregister.
*/
open func removeTextFieldView(_ view : UIView) {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(view) {
if let textField = view as? UITextField {
let returnKeyTypeValue = dict[kIQTextFieldReturnKeyType] as! NSNumber
textField.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.intValue)!
textField.delegate = dict[kIQTextFieldDelegate] as? UITextFieldDelegate
} else if let textView = view as? UITextView {
let returnKeyTypeValue = dict[kIQTextFieldReturnKeyType] as! NSNumber
textView.returnKeyType = UIReturnKeyType(rawValue: returnKeyTypeValue.intValue)!
textView.delegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
textFieldInfoCache.remove(dict)
}
}
/**
Add all the UITextField/UITextView responderView's.
@param UIView object to register all it's responder subviews.
*/
open func addResponderFromView(_ view : UIView) {
let textFields = view.deepResponderViews()
for textField in textFields {
addTextFieldView(textField)
}
}
/**
Remove all the UITextField/UITextView responderView's.
@param UIView object to unregister all it's responder subviews.
*/
open func removeResponderFromView(_ view : UIView) {
let textFields = view.deepResponderViews()
for textField in textFields {
removeTextFieldView(textField)
}
}
@discardableResult fileprivate func goToNextResponderOrResign(_ view : UIView) -> Bool {
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347)
for disabledClass in IQKeyboardManager.sharedManager().toolbarPreviousNextAllowedClasses {
superConsideredView = view.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
var textFields : [UIView]?
//If there is a tableView in view's hierarchy, then fetching all it's subview that responds.
if let unwrappedTableView = superConsideredView { // (Enhancement ID: #22)
textFields = unwrappedTableView.deepResponderViews()
} else { //Otherwise fetching all the siblings
textFields = view.responderSiblings()
//Sorting textFields according to behaviour
switch IQKeyboardManager.sharedManager().toolbarManageBehaviour {
//If needs to sort it by tag
case .byTag: textFields = textFields?.sortedArrayByTag()
//If needs to sort it by Position
case .byPosition: textFields = textFields?.sortedArrayByPosition()
default:
break
}
}
if let unwrappedTextFields = textFields {
//Getting index of current textField.
if let index = unwrappedTextFields.index(of: view) {
//If it is not last textField. then it's next object becomeFirstResponder.
if index < (unwrappedTextFields.count - 1) {
let nextTextField = unwrappedTextFields[index+1]
nextTextField.becomeFirstResponder()
return false;
} else {
view.resignFirstResponder()
return true;
}
} else {
return true;
}
} else {
return true;
}
}
///----------------------------------------------
/// MARK: UITextField/UITextView delegates
///----------------------------------------------
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
var aDelegate : UITextFieldDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textField) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextFieldDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textFieldShouldBeginEditing(_:))) {
return unwrapDelegate.textFieldShouldBeginEditing?(textField) == true
}
}
return true
}
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
var aDelegate : UITextFieldDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textField) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextFieldDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textFieldShouldEndEditing(_:))) {
return unwrapDelegate.textFieldShouldEndEditing?(textField) == true
}
}
return true
}
open func textFieldDidBeginEditing(_ textField: UITextField) {
updateReturnKeyTypeOnTextField(textField)
var aDelegate : UITextFieldDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textField) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextFieldDelegate
}
}
aDelegate?.textFieldDidBeginEditing?(textField)
}
open func textFieldDidEndEditing(_ textField: UITextField) {
var aDelegate : UITextFieldDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textField) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextFieldDelegate
}
}
aDelegate?.textFieldDidEndEditing?(textField)
}
@available(iOS 10.0, *)
open func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
var aDelegate : UITextFieldDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textField) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextFieldDelegate
}
}
aDelegate?.textFieldDidEndEditing?(textField, reason: reason)
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var aDelegate : UITextFieldDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textField) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextFieldDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textField(_:shouldChangeCharactersIn:replacementString:))) {
return unwrapDelegate.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) == true
}
}
return true
}
open func textFieldShouldClear(_ textField: UITextField) -> Bool {
var aDelegate : UITextFieldDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textField) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextFieldDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textFieldShouldClear(_:))) {
return unwrapDelegate.textFieldShouldClear?(textField) == true
}
}
return true
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
var aDelegate : UITextFieldDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textField) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextFieldDelegate
}
}
var shouldReturn = true;
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(UITextFieldDelegate.textFieldShouldReturn(_:))) {
shouldReturn = unwrapDelegate.textFieldShouldReturn?(textField) == true
}
}
if shouldReturn == true {
goToNextResponderOrResign(textField)
return true;
} else {
return goToNextResponderOrResign(textField)
}
}
open func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(UITextViewDelegate.textViewShouldBeginEditing(_:))) {
return unwrapDelegate.textViewShouldBeginEditing?(textView) == true
}
}
return true
}
open func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(UITextViewDelegate.textViewShouldEndEditing(_:))) {
return unwrapDelegate.textViewShouldEndEditing?(textView) == true
}
}
return true
}
open func textViewDidBeginEditing(_ textView: UITextView) {
updateReturnKeyTypeOnTextField(textView)
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
aDelegate?.textViewDidBeginEditing?(textView)
}
open func textViewDidEndEditing(_ textView: UITextView) {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
aDelegate?.textViewDidEndEditing?(textView)
}
open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
var shouldReturn = true
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(UITextViewDelegate.textView(_:shouldChangeTextIn:replacementText:))) {
shouldReturn = (unwrapDelegate.textView?(textView, shouldChangeTextIn: range, replacementText: text)) == true
}
}
if shouldReturn == true && text == "\n" {
shouldReturn = goToNextResponderOrResign(textView)
}
return shouldReturn
}
open func textViewDidChange(_ textView: UITextView) {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
aDelegate?.textViewDidChange?(textView)
}
open func textViewDidChangeSelection(_ textView: UITextView) {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(textView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
aDelegate?.textViewDidChangeSelection?(textView)
}
@available(iOS 10.0, *)
open func textView(_ aTextView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(aTextView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(textView as (UITextView, URL, NSRange, UITextItemInteraction) -> Bool)) {
return unwrapDelegate.textView?(aTextView, shouldInteractWith: URL, in: characterRange, interaction: interaction) == true
}
}
return true
}
@available(iOS 10.0, *)
open func textView(_ aTextView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(aTextView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(textView as (UITextView, NSTextAttachment, NSRange, UITextItemInteraction) -> Bool)) {
return unwrapDelegate.textView?(aTextView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) == true
}
}
return true
}
@available(iOS, deprecated: 10.0)
open func textView(_ aTextView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(aTextView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(textView as (UITextView, URL, NSRange) -> Bool)) {
return unwrapDelegate.textView?(aTextView, shouldInteractWith: URL, in: characterRange) == true
}
}
return true
}
@available(iOS, deprecated: 10.0)
open func textView(_ aTextView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool {
var aDelegate : UITextViewDelegate? = delegate;
if aDelegate == nil {
if let dict : [String : AnyObject] = textFieldViewCachedInfo(aTextView) {
aDelegate = dict[kIQTextFieldDelegate] as? UITextViewDelegate
}
}
if let unwrapDelegate = aDelegate {
if unwrapDelegate.responds(to: #selector(textView as (UITextView, NSTextAttachment, NSRange) -> Bool)) {
return unwrapDelegate.textView?(aTextView, shouldInteractWith: textAttachment, in: characterRange) == true
}
}
return true
}
}
| mit | 9cc3c684ea27a453f214cf4dc19f917d | 35.501449 | 174 | 0.580918 | 6.411914 | false | false | false | false |
lanit-tercom-school/grouplock | GroupLockiOS/GroupLock/Scenes/Home_Stack/ScanningScene/ScanningPresenter.swift | 1 | 1949 | //
// ScanningPresenter.swift
// GroupLock
//
// Created by Sergej Jaskiewicz on 09.08.16.
// Copyright (c) 2016 Lanit-Tercom School. All rights reserved.
//
import CoreGraphics
protocol ScanningPresenterInput {
func formatKeyScan(_ response: Scanning.Keys.Response)
func formatCameraError(_ response: Scanning.CameraError.Response)
}
protocol ScanningPresenterOutput: class {
func displayKeyScan(_ viewModel: Scanning.Keys.ViewModel)
func displayCameraErrorMessage(_ viewModel: Scanning.CameraError.ViewModel)
}
class ScanningPresenter: ScanningPresenterInput {
weak var output: ScanningPresenterOutput!
// MARK: - Presentation logic
func formatKeyScan(_ response: Scanning.Keys.Response) {
let numberOfDifferentKeys = response.keys.count
// swiftlint:disable:next force_unwrapping (corners (CFDictionaries) are guaranteed to represent points)
let qrCodeCGPath = CGPath.create(response.qrCodeCorners.map { CGPoint(dictionaryRepresentation: $0)! })
let viewModel = Scanning.Keys.ViewModel(numberOfDifferentKeys: numberOfDifferentKeys,
qrCodeCGPath: qrCodeCGPath,
isValidKey: response.isValidKey)
output.displayKeyScan(viewModel)
}
func formatCameraError(_ response: Scanning.CameraError.Response) {
let errorDescription = response.error.localizedDescription
// swiftlint:disable:next force_unwrapping (since description is never empty)
let formattedDescription = String(errorDescription.characters.first!).uppercased() +
String(errorDescription.characters.dropFirst()).lowercased() + "."
let viewModel = Scanning.CameraError.ViewModel(errorName: "Camera Error",
errorDescription: formattedDescription)
output.displayCameraErrorMessage(viewModel)
}
}
| apache-2.0 | 492edfc88d949bcee18248a110467226 | 37.98 | 112 | 0.693176 | 5.21123 | false | false | false | false |
SereivoanYong/Charts | Source/Charts/Charts/ChartView.swift | 1 | 29778 | //
// ChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import UIKit
public protocol ChartViewDelegate : class {
/// Called when a value has been selected inside the chart.
/// - parameter entry: The selected Entry.
/// - parameter highlight: The corresponding highlight object that contains information about the highlighted position such as dataSetIndex etc.
func chartValueSelected(_ chartView: ChartView, entry: Entry, highlight: Highlight)
// Called when nothing has been selected or an "un-select" has been made.
func chartValueNothingSelected(_ chartView: ChartView)
// Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
func chartScaled(_ chartView: ChartView, scaleX: CGFloat, scaleY: CGFloat)
// Callbacks when the chart is moved / translated via drag gesture.
func chartTranslated(_ chartView: ChartView, dX: CGFloat, dY: CGFloat)
}
open class ChartView: UIView, ChartDataProvider {
// MARK: - Properties
/// - returns: The object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
open var xAxis: XAxis {
return _xAxis
}
/// The default IValueFormatter that has been determined by the chart considering the provided minimum and maximum values.
internal var _defaultValueFormatter: IValueFormatter? = DefaultValueFormatter(decimals: 0)
/// If set to true, chart continues to scroll after touch up
/// **default**: true
open var isDragDecelerationEnabled: Bool = true
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
fileprivate var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// if true, units are drawn next to the values in the chart
internal var _drawUnitInChart = false
/// The object representing the labels on the x-axis
internal var _xAxis: XAxis!
/// The `Description` object of the chart.
/// This should have been called just "description", but
open var chartDescription: Description? = Description()
/// delegate to receive chart events
open weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
open var noDataText = "No chart data available."
/// Font to be used for the no data text.
open var noDataFont: UIFont! = .systemFont(ofSize: 12.0)
/// color of the no data text
open var noDataTextColor: UIColor = .black
internal var _legendRenderer: LegendRenderer!
/// object responsible for rendering the data
open var renderer: DataRenderer?
open var highlighter: IHighlighter?
/// flag that indicates if offsets calculation has already been done or not
fileprivate var _offsetsCalculated = false
/// array of Highlight objects that reference the highlighted slices in the chart
internal var _indicesToHighlight = [Highlight]()
/// `true` if drawing the marker is enabled when tapping on values
/// (use the `marker` property to specify a marker)
open var isDrawMarkersEnabled: Bool = true
/// The marker that is displayed when a value is clicked on the chart
open var marker: Marker?
fileprivate var _interceptTouchEvents: Bool = false
/// An extra offset to be appended to the viewport's top
open var extraTopOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's right
open var extraRightOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's bottom
open var extraBottomOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's left
open var extraLeftOffset: CGFloat = 0.0
open func setExtraOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) {
extraLeftOffset = left
extraTopOffset = top
extraRightOffset = right
extraBottomOffset = bottom
}
// MARK: - Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
deinit {
removeObserver(self, forKeyPath: "bounds")
removeObserver(self, forKeyPath: "frame")
}
internal func initialize() {
backgroundColor = .clear
animator.delegate = self
viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
_legendRenderer = LegendRenderer(viewPortHandler: viewPortHandler, legend: legend)
_xAxis = XAxis()
addObserver(self, forKeyPath: "bounds", options: .new, context: nil)
addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}
// MARK: - ChartView
/// The data for the chart
open var data: ChartData? {
didSet {
_offsetsCalculated = false
guard let data = data else {
return
}
// calculate how many digits are needed
setupDefaultFormatter(min: data.getYMin(), max: data.getYMax())
for set in data.dataSets {
if set.needsFormatter || set.valueFormatter === _defaultValueFormatter {
set.valueFormatter = _defaultValueFormatter
}
}
// let the chart know there is new data
notifyDataSetChanged()
}
}
/// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()).
open func clear() {
data = nil
_offsetsCalculated = false
_indicesToHighlight.removeAll()
lastHighlighted = nil
setNeedsDisplay()
}
/// Removes all DataSets (and thereby Entries) from the chart. Does not set the data object to nil. Also refreshes the chart by calling setNeedsDisplay().
open func clearValues() {
data?.clearValues()
setNeedsDisplay()
}
/// - returns: `true` if the chart is empty (meaning it's data object is either null or contains no entries).
open func isEmpty() -> Bool {
guard let data = data else {
return true
}
return data.entryCount <= 0
}
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
/// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour.
open func notifyDataSetChanged() {
fatalError("notifyDataSetChanged() cannot be called on ChartView")
}
/// Calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets() {
fatalError("calculateOffsets() cannot be called on ChartView")
}
/// calcualtes the y-min and y-max value and the y-delta and x-delta value
internal func calcMinMax() {
fatalError("calcMinMax() cannot be called on ChartView")
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func setupDefaultFormatter(min: CGFloat, max: CGFloat) {
// check if a custom formatter is set or not
var reference: CGFloat
if let data = data, data.entryCount >= 2 {
reference = fabs(max - min)
} else {
let absMin = fabs(min)
let absMax = fabs(max)
reference = absMin > absMax ? absMin : absMax
}
if _defaultValueFormatter is DefaultValueFormatter {
// setup the formatter with a new number of digits
let digits = ChartUtils.decimals(reference)
(_defaultValueFormatter as? DefaultValueFormatter)?.decimals = digits
}
}
open override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()!
if data == nil && noDataText.characters.count > 0 {
context.saveGState()
ChartUtils.drawMultilineText(
context: context,
text: noDataText,
point: CGPoint(x: bounds.width / 2, y: bounds.height / 2),
attributes: [NSFontAttributeName: noDataFont, NSForegroundColorAttributeName: noDataTextColor],
constrainedToSize: bounds.size,
anchor: CGPoint(x: 0.5, y: 0.5),
angleRadians: 0.0)
context.restoreGState()
return
}
if !_offsetsCalculated {
calculateOffsets()
_offsetsCalculated = true
}
}
/// Draws the description text in the bottom right corner of the chart (per default)
internal func drawDescription(context: CGContext) {
// check if description should be drawn
guard
let description = chartDescription,
description.isEnabled,
let descriptionText = description.text,
descriptionText.characters.count > 0
else { return }
var position = description.position
// if no position specified, draw on default position
if position == nil {
let frame = self.bounds
position = CGPoint(x: frame.width - viewPortHandler.offsetRight - description.xOffset, y: frame.height - viewPortHandler.offsetBottom - description.yOffset - description.font.lineHeight)
}
ChartUtils.drawText(
context: context,
text: descriptionText,
point: position!,
align: description.textAlign,
attributes: [NSFontAttributeName: description.font, NSForegroundColorAttributeName: description.textColor])
}
// MARK: - Highlighting
/// - returns: The array of currently highlighted values. This might an empty if nothing is highlighted.
open var highlighted: [Highlight] {
return _indicesToHighlight
}
/// Set this to false to prevent values from being highlighted by tap gesture.
/// Values can still be highlighted via drag or programmatically.
/// **default**: true
open var isHighLightPerTapEnabled: Bool = true
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
/// - returns: `true` if there are values to highlight, `false` ifthere are no values to highlight.
open func valuesToHighlight() -> Bool {
return _indicesToHighlight.count > 0
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This method *will not* call the delegate.
open func highlightValues(_ highs: [Highlight]?) {
// set the indices to highlight
_indicesToHighlight = highs ?? [Highlight]()
if _indicesToHighlight.isEmpty {
self.lastHighlighted = nil
} else {
self.lastHighlighted = _indicesToHighlight[0]
}
// redraw the chart
setNeedsDisplay()
}
/// Highlights any y-value at the given x-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
/// This method will call the delegate.
/// - parameter x: The x-value to highlight
/// - parameter dataSetIndex: The dataset index to search in
open func highlightValue(x: CGFloat, dataSetIndex: Int) {
highlightValue(x: x, dataSetIndex: dataSetIndex, callDelegate: true)
}
/// Highlights the value at the given x-value and y-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
/// This method will call the delegate.
/// - parameter x: The x-value to highlight
/// - parameter y: The y-value to highlight. Supply `NaN` for "any"
/// - parameter dataSetIndex: The dataset index to search in
open func highlightValue(x: CGFloat, y: CGFloat, dataSetIndex: Int) {
highlightValue(x: x, y: y, dataSetIndex: dataSetIndex, callDelegate: true)
}
/// Highlights any y-value at the given x-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
/// - parameter x: The x-value to highlight
/// - parameter dataSetIndex: The dataset index to search in
/// - parameter callDelegate: Should the delegate be called for this change
open func highlightValue(x: CGFloat, dataSetIndex: Int, callDelegate: Bool) {
highlightValue(x: x, y: .nan, dataSetIndex: dataSetIndex, callDelegate: callDelegate)
}
/// Highlights the value at the given x-value and y-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
/// - parameter x: The x-value to highlight
/// - parameter y: The y-value to highlight. Supply `NaN` for "any"
/// - parameter dataSetIndex: The dataset index to search in
/// - parameter callDelegate: Should the delegate be called for this change
open func highlightValue(x: CGFloat, y: CGFloat, dataSetIndex: Int, callDelegate: Bool) {
guard let data = data else {
print("Value not highlighted because data is nil")
return
}
if dataSetIndex < 0 || dataSetIndex >= data.dataSets.count {
highlightValue(nil, callDelegate: callDelegate)
} else {
highlightValue(Highlight(x: x, y: y, dataSetIndex: dataSetIndex), callDelegate: callDelegate)
}
}
/// Highlights the values represented by the provided Highlight object
/// This method *will not* call the delegate.
/// - parameter highlight: contains information about which entry should be highlighted
open func highlightValue(_ highlight: Highlight?) {
highlightValue(highlight, callDelegate: false)
}
/// Highlights the value selected by touch gesture.
open func highlightValue(_ highlight: Highlight?, callDelegate: Bool) {
var entry: Entry?
var h = highlight
if h == nil {
_indicesToHighlight.removeAll(keepingCapacity: false)
} else {
// set the indices to highlight
entry = data?.entryForHighlight(h!)
if entry == nil {
h = nil
_indicesToHighlight.removeAll(keepingCapacity: false)
} else {
_indicesToHighlight = [h!]
}
}
if callDelegate && delegate != nil {
if h == nil {
delegate!.chartValueNothingSelected(self)
} else {
// notify the listener
delegate!.chartValueSelected(self, entry: entry!, highlight: h!)
}
}
// redraw the chart
setNeedsDisplay()
}
/// - returns: The Highlight object (contains x-index and DataSet index) of the
/// selected value at the given touch point inside the Line-, Scatter-, or
/// CandleStick-Chart.
open func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? {
if data == nil {
print("Can't select by touch. No data set.")
return nil
}
return highlighter?.highlight(at: pt)
}
/// The last value that was highlighted via touch.
open var lastHighlighted: Highlight?
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
internal func drawMarkers(context: CGContext) {
// if there is no marker view or drawing marker is disabled
guard let marker = marker, isDrawMarkersEnabled && valuesToHighlight() else {
return
}
for i in 0 ..< _indicesToHighlight.count {
let highlight = _indicesToHighlight[i]
guard let set = data?.getDataSetByIndex(highlight.dataSetIndex), let e = data?.entryForHighlight(highlight) else {
continue
}
let entryIndex = set.entryIndex(entry: e)
if entryIndex > Int(CGFloat(set.entries.count) * animator.phaseX) {
continue
}
let pos = getMarkerPosition(highlight: highlight)
// check bounds
if !viewPortHandler.isInBounds(x: pos.x, y: pos.y) {
continue
}
// callbacks to update the content
marker.refreshContent(entry: e, highlight: highlight)
// draw the marker
marker.draw(context: context, point: pos)
}
}
/// - returns: The actual position in pixels of the MarkerView for the given Entry in the given DataSet.
open func getMarkerPosition(highlight: Highlight) -> CGPoint {
return highlight.drawPosition
}
// MARK: - Animation
/// - returns: The animator responsible for animating chart values.
open internal(set) var animator: Animator = Animator()
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingX: an easing function for the animation on the x axis
/// - parameter easingY: an easing function for the animation on the y axis
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?) {
animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOptionX: the easing function for the animation on the x axis
/// - parameter easingOptionY: the easing function for the animation on the y axis
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption) {
animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) {
animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOption: ChartEasingOption) {
animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval) {
animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easing: an easing function for the animation
open func animate(xAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) {
animator.animate(xAxisDuration: xAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easingOption: the easing function for the animation
open func animate(xAxisDuration: TimeInterval, easingOption: ChartEasingOption) {
animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
open func animate(xAxisDuration: TimeInterval) {
animator.animate(xAxisDuration: xAxisDuration)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
open func animate(yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) {
animator.animate(yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
open func animate(yAxisDuration: TimeInterval, easingOption: ChartEasingOption) {
animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
open func animate(yAxisDuration: TimeInterval) {
animator.animate(yAxisDuration: yAxisDuration)
}
// MARK: - Accessors
/// - returns: The current y-max value across all DataSets
open var chartYMax: CGFloat {
return data?.yMax ?? 0.0
}
/// - returns: The current y-min value across all DataSets
open var chartYMin: CGFloat {
return data?.yMin ?? 0.0
}
open var chartXMax: CGFloat {
return _xAxis._axisMaximum
}
open var chartXMin: CGFloat {
return _xAxis._axisMinimum
}
open var xRange: CGFloat {
return _xAxis.axisRange
}
/// *
/// - note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)*
/// - returns: The center point of the chart (the whole View) in pixels.
open var midPoint: CGPoint {
return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0)
}
/// - returns: The center of the chart taking offsets under consideration. (returns the center of the content rectangle)
open var centerOffsets: CGPoint {
return viewPortHandler.contentCenter
}
/// - returns: The Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend.
open let legend: Legend = Legend()
/// - returns: The renderer object responsible for rendering / drawing the Legend.
open var legendRenderer: LegendRenderer! {
return _legendRenderer
}
/// - returns: The rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
open var contentRect: CGRect {
return viewPortHandler.contentRect
}
/// - returns: The ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
open let viewPortHandler: ViewPortHandler = ViewPortHandler()
/// - returns: The bitmap that represents the chart.
open func getChartImage(transparent: Bool) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque || !transparent, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()!
let rect = CGRect(origin: .zero, size: bounds.size)
if isOpaque || !transparent {
// Background color may be partially transparent, we must fill with white if we want to output an opaque image
context.setFillColor(UIColor.white.cgColor)
context.fill(rect)
if let backgroundColor = backgroundColor {
context.setFillColor(backgroundColor.cgColor)
context.fill(rect)
}
}
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public enum ImageFormat {
case jpeg
case png
}
/// Saves the current chart state with the given name to the given path on
/// the sdcard leaving the path empty "" will put the saved file directly on
/// the SD card chart is saved as a PNG image, example:
/// saveToPath("myfilename", "foldername1/foldername2")
///
/// - parameter to: path to the image to save
/// - parameter format: the format to save
/// - parameter compressionQuality: compression quality for lossless formats (JPEG)
///
/// - returns: `true` if the image was saved successfully
@discardableResult
open func save(to path: String, format: ImageFormat, compressionQuality: CGFloat) -> Bool {
guard let image = getChartImage(transparent: format != .jpeg) else {
return false
}
var imageData: Data
switch format {
case .png: imageData = UIImagePNGRepresentation(image)!
case .jpeg: imageData = UIImageJPEGRepresentation(image, compressionQuality)!
}
do {
try imageData.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch {
return false
}
return true
}
internal var _viewportJobs: [ViewPortJob] = []
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "bounds" || keyPath == "frame" {
let bounds = self.bounds
if bounds.size.width != viewPortHandler.chartSize.width || bounds.size.height != viewPortHandler.chartSize.height {
viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
// This may cause the chart view to mutate properties affecting the view port -- lets do this
// before we try to run any pending jobs on the view port itself
notifyDataSetChanged()
// Finish any pending viewport changes
while !_viewportJobs.isEmpty {
let job = _viewportJobs.remove(at: 0)
job.doJob()
}
}
}
}
open func removeViewportJob(_ job: ViewPortJob) {
if let index = _viewportJobs.index(where: { $0 === job }) {
_viewportJobs.remove(at: index)
}
}
open func clearAllViewportJobs() {
_viewportJobs.removeAll(keepingCapacity: false)
}
open func addViewportJob(_ job: ViewPortJob) {
if viewPortHandler.hasChartDimens {
job.doJob()
} else {
_viewportJobs.append(job)
}
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
///
/// **default**: true
open var dragDecelerationFrictionCoef: CGFloat {
get {
return _dragDecelerationFrictionCoef
}
set {
var val = newValue
if val < 0.0 {
val = 0.0
}
if val >= 1.0 {
val = 0.999
}
_dragDecelerationFrictionCoef = val
}
}
/// The maximum distance in screen pixels away from an entry causing it to highlight.
/// **default**: 500.0
open var maxHighlightDistance: CGFloat = 500.0
/// the number of maximum visible drawn values on the chart only active when `drawValuesEnabled` is enabled
open var maxVisibleCount: Int {
return .max
}
// MARK: - Touches
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if !_interceptTouchEvents {
super.touchesBegan(touches, with: event)
}
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if !_interceptTouchEvents {
super.touchesMoved(touches, with: event)
}
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if !_interceptTouchEvents {
super.touchesEnded(touches, with: event)
}
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
if !_interceptTouchEvents {
super.touchesCancelled(touches, with: event)
}
}
}
// MARK: - AnimatorDelegate
extension ChartView : AnimatorDelegate {
open func animatorDidUpdate(_ chartAnimator: Animator) {
setNeedsDisplay()
}
open func animatorDidStop(_ chartAnimator: Animator) {
}
}
| apache-2.0 | fd059a3471e4ee3078368d301779e73a | 36.885496 | 197 | 0.69464 | 4.900115 | false | false | false | false |
jemmons/Gauntlet | Sources/Gauntlet/StateMachine.swift | 2 | 8187 | import Foundation
import Combine
/**
The “machine” part of our finite state machine.
Given a `Transitionable` type `State`, this class holds its current value in the property `state` and manages transitions to new states by consulting `state`’s `shouldTransition(to:)` method.
```
let stateMachine = StateMachine(initialState: MyState.ready)
stateMachine.transition(to: .working)
stateMachine.state // If `state.shouldTransition(to: .working)`
// returns `true`, this will be `.working`.
// Otherwise it will be `.ready`.
```
This class also publishes state changes to subscribers via `publisher`:
```
let stateMachine = StateMachine(initialState: MyState.ready)
stateMachine.publisher.sink { from, to in
// from == .ready, to == .working if
// ready -> working is a valid transition
}
stateMachine.transition(to: .working)
```
### Property Wrapper
`StateMachine` can also be used as a property wrapper, in which case the wrapped property’s type is the state type conforming to `Transitionable`, its default value is the initial state, its projected value is its `publisher`, and all assignment happens through `transition(to:)`. The above example could be written as:
```
@StateMachine var stateMachine: MyState = .ready
$stateMachine.sink { from, to in
// from == .ready, to == .working if
// ready -> working is a valid transition
}
stateMachine = .working
```
*/
@propertyWrapper
public class StateMachine<State> where State: Transitionable {
lazy private var _publisher = PassthroughSubject<(from: State, to: State), Never>()
/**
The current state of the state machine. Read-only.
To transition to another state, use `transition(to:)`
### Property Wrapper
When using `StateMachine` as a property wrapper, the wrapped property’s getter is equivalent to the `state` property:
```
let stateMachine = StateMachine(initialState: MyState.ready)
stateMachine.state //> .ready
// Is equivalent to:
@StateMachine var stateMachine: MyState = .ready
stateMachine //> .ready
```
- SeeAlso: `transition(to:)`
*/
public private(set) var state: State
/**
Publishes state changes after valid transitions.
Consumers can subscribe (in the `Combine` sense) to `publisher` to recieve a set of `State` values after ⃰ a valid transition:
```
let stateMachine = StateMachine(initialState: MyState.ready)
//...
let subscription = stateMachine.publisher.sink { from, to in
// stuff to do when `stateMachine` has transitioned
// to or from particular states...
}
```
- Attention:
“After”, in this case, means “on the *next* cycle of the run loop”. Subscribers will always be sent all the state changes in the order they were made. But if `state` is transitioned multiple times in *this* cycle of the run loop, `to:` may not represent the current value of `state` by the time it’s received.
See the documentation for `transition(to:)` for more details and examples.
### Property Wrapper
When using `StateMachine` as a property wrapper, `publisher` is the wrapped property’s “projected value” — meaning we can access it by usign the `$` prefix. The above could be written as:
```
@StateMachine var stateMachine: MyState = .ready
//...
let subscription = $stateMachine.sink { from, to in
// stuff to do when `machine` has transitioned
// to or from particular states...
}
```
- SeeAlso: `transition(to:)`
*/
public var publisher: AnyPublisher<(from: State, to: State), Never> {
return _publisher.eraseToAnyPublisher()
}
/**
The value of the wrapped property when `StateMachine` is used as a property wrapper. Getting the value is equivalent to `state`. Setting the value is equivalent to calling `transition(to:)` with the new value.
- SeeAlso: `state`, `transition(to:)`
*/
public var wrappedValue: State {
get { state }
set { transition(to: newValue) }
}
/**
The projected value of the property (that is, the value when the property is prepended with a `$`) when `StateMachine` is used as a property wrapper.
The projected value is equivalent to the `publisher` property:
```
let stateMachine = StateMachine(initialState: MyState.ready)
stateMachine.publisher.sink { ... }
// Is equivalent to:
@StateMachine var stateMachine: MyState = .ready
$stateMachine.sink { ... }
```
*/
public var projectedValue: AnyPublisher<(from: State, to: State), Never> {
publisher
}
/**
Initializes the state machine with the given initial state.
*/
public init(initialState: State) {
state = initialState // set the internal value so we don't need a special rule in `shouldTranistion(to:)`. Also avoids publishing the change to `publisher`.
}
/**
Initializer called when using `StateMachine` as a property wrapper.
The default value of the property wrapper is made the “initial state” of the state machine:
```
let stateMachine = StateMachine(initialState: MyState.ready)
// Is equivalent to:
@StateMachine var stateMachine: MyState = .ready
```
*/
convenience public init(wrappedValue: State) {
self.init(initialState: wrappedValue)
}
/**
Use this method to transition states.
When called, this method:
* First, determines the validity of the transition to the given `newState` via a call to `state.shouldTransition(to:)`.
* If it is valid, `newState` is *synchonously* assigned to the `state` property. Then the previous and new states are published *asynchronously* to subscribers of `publisher`.
* If the transition to `newState` is *not* valid, it is silently ignored and nothing is published.
- Attention:
This method publishes to subscribers of `publisher` *asynchronously*. This is so we can call `transition(to:)` from within a the subscriber without concern for growing the stack.
But this also means that, while subscribers of `publisher` will always be sent all state changes and always in the order they occured, if `state` (which is is transitioned *synchronously*) is set multiple times in a row, a subscriber’s parameters may not reflect the *current* state of the machine by the time it’s received:
```
let stateMachine = StateMachine(initialState: MyState.first)
let sub = stateMachine.publisher.sink { from, to in
// On the first call...
print(to) //> .second
print(stateMachine.state) //> but `state` is already .third
// Second call...
print(to) //> .third
print(stateMachine.state) //> also .third
}
stateMachine.transition(to: .second)
// `state` is immediately set to `.second`,
// but `(.first, .second)` won't be published
// until the next runloop.
stateMachine.trasition(to: .third)
// Still in the current runloop; `state` is
// is set to `.third`. We still won’t publish
// `(.first, .second)` until the next runloop
// and `(.second, .third)` right after that.
```
- Parameter newState: The `State` to transition to.
### Property Wrapper
When using `StateMachine` as a property wrapper, the wrapped property’s setter is equivalent to calling `transition(to:)`:
```
let stateMachine = StateMachine(initialState: MyState.ready)
stateMachine.transition(to: .working)
// Is equivalent to:
@StateMachine var stateMachine: MyState = .ready
stateMachine = .working
```
- SeeAlso: `publisher`
*/
public func transition(to newState: State) {
if state.shouldTransition(to: newState) {
let from = state
state = newState
OperationQueue.current?.addOperation { [weak self] () -> Void in
self?._publisher.send((from: from, to: newState))
}
}
}
}
| mit | f30dc062c0b4b51f725a1ecba95607fc | 35.361607 | 331 | 0.66016 | 4.614731 | false | false | false | false |
Jude309307972/JudeTest | 05-swift.playground/Contents.swift | 1 | 8262 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
// Initisalization
struct Fahrenheit {
var temperature: Double
init(){
temperature = 32.0
}
}
var f = Fahrenheit()
print("the defualt is \(f.temperature)")
struct Celsius {
var temperatureInCelsius: Double = 0.0
init (fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init (fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
}
let boil = Celsius(fromFahrenheit: 212.0)
let free = Celsius(fromKelvin: 273.15)
struct Color {
var red = 0.0, green = 0.0, blue = 0.0
init(red: Double,green: Double, blue: Double){
self.red = red
self.green = green
self.blue = blue
}
}
let magenta = Color(red: 1.0, green: 1.0, blue: 1.0)
class SurveQuestion {
var text: String
var respone: String?
init (text: String) {
self.text = text
}
func ask(){
print(text)
}
}
let cheeseQuestion = SurveQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
cheeseQuestion.respone = "yes, I do like cheese."
class ShoppingListItem {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()
struct Size {
var width = 0.0 ,height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
init () {}
init(origin: Point, size:Size){
self.origin = origin
self.size = size
}
init(center: Point, size:Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY),size:size)
}
}
let basicRect = Rect()
let originRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0))
class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unamed]")
}
}
var nameMeat = Food(name: "bacon")
nameMeat = Food()
print(nameMeat.name)
class RecipeIngredient: Food {
var quantity: Int
init (name: String,quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, quantity:1)
}
}
let oneMysteryItem = RecipeIngredient()
let oneBacon = RecipeIngredient(name: "Bacon")
let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)
class ShoppingList: RecipeIngredient {
var purchased = false
var description : String {
var output = "\(quantity) x \(name.lowercaseString) "
output += purchased ? "1" : "2"
return output
}
}
var breakfastList = [
ShoppingList(),
ShoppingList(name: "Bacon"),
ShoppingList(name: "Eggs", quantity: 6)
]
breakfastList[0].name = "orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
print(item.description)
}
// 可失败的构造器
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty {
return nil
}
self.species = species
}
}
let someCreature = Animal(species: "cifaffe")
if let giraffe = someCreature {
print("an animal was \(giraffe.species)")
}
let anonyCreature = Animal(species: "")
if anonyCreature == nil {
print("the anonrmous")
}
class Shape {
var numberOfSides = 0
let width = 50
func allWidth(number: Int) ->Int{
return number * numberOfSides
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
let shape = Shape()
print(shape.width)
print(shape.numberOfSides)
let all = shape.allWidth(4)
let strSim = shape.simpleDescription()
class NameShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides"
}
}
class Square: NameShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "a square with sides of legth \(sideLength)"
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()
class Circle: NameShape {
var radius: Double
init(radius: Double,name : String) {
self.radius = radius
super.init(name: name)
numberOfSides = 5
}
func area() ->Double{
return radius * radius
}
override func simpleDescription() -> String {
return " circle simple"
}
}
let circle = Circle(radius: 5, name: "cirecle")
circle.area()
circle.simpleDescription()
class EquilateralTriagnle: NameShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "an equilateral \(sideLength)"
}
}
var triangle = EquilateralTriagnle(sideLength: 3.1, name: "a triang")
triangle.perimeter
triangle.perimeter = 9.9
print(triangle.perimeter)
triangle.sideLength
class TriangleAndSquare {
var triangle: EquilateralTriagnle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square (sideLength: size, name: name)
triangle = EquilateralTriagnle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another shape")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.square = Square(sideLength: 50, name: "lager")
triangleAndSquare.triangle.sideLength
class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes times: Int) {
count += amount * times
}
}
var counter = Counter()
counter.incrementBy(2, numberOfTimes: 7)
let optionSquare: Square? = Square(sideLength: 2.5, name: "square")
let sideLength = optionSquare?.sideLength
// 枚举和结构体
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.Ace
let aceRawValue = ace.rawValue
ace.simpleDescription()
if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
}
enum Suit {
case Spades, Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
let hearts = Suit.Hearts
let heartsDescription = hearts.simpleDescription()
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeDes = threeOfSpades.simpleDescription()
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("out of cheese.")
| apache-2.0 | 8fe93b642644db62d309a32cbd1443b1 | 21.139785 | 89 | 0.619111 | 3.866667 | false | false | false | false |
ibm-bluemix-omnichannel-iclabs/ICLab-OmniChannelAppDev | iOS/Pods/BMSCore/Source/Network Requests/BMSURLSessionUtility.swift | 1 | 25924 | /*
* Copyright 2017 IBM Corp.
* 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 BMSAnalyticsAPI
// MARK: - Swift 3
#if swift(>=3.0)
// Contains helper methods for BMSURLSession and BMSURLSessionDelegate
// This is where the "Bluemix Mobile Services" magic happens
internal struct BMSURLSessionUtility {
// Inject BMSSecurity and BMSAnalytics into the request object by adding headers
internal static func addBMSHeaders(to request: URLRequest, onlyIf precondition: Bool) -> URLRequest {
var bmsRequest = request
// If the request is in the process of authentication with the MCA authorization server, do not attempt to add headers, since this is an intermediary request.
if precondition {
// Security
let authManager = BMSClient.sharedInstance.authorizationManager
if let authHeader: String = authManager.cachedAuthorizationHeader {
bmsRequest.setValue(authHeader, forHTTPHeaderField: "Authorization")
}
// Analytics
bmsRequest.setValue(UUID().uuidString, forHTTPHeaderField: "x-wl-analytics-tracking-id")
if let requestMetadata = BaseRequest.requestAnalyticsData {
bmsRequest.setValue(requestMetadata, forHTTPHeaderField: "x-mfp-analytics-metadata")
}
}
return bmsRequest
}
// Required to hook in challenge handling via AuthorizationManager, as well as handling auto-retries
internal static func generateBmsCompletionHandler(from completionHandler: @escaping BMSDataTaskCompletionHandler, bmsUrlSession: BMSURLSession, urlSession: URLSession, request: URLRequest, originalTask: BMSURLSessionTaskType, requestBody: Data?, numberOfRetries: Int) -> BMSDataTaskCompletionHandler {
let trackingId = UUID().uuidString
let startTime = Int64(Date.timeIntervalSinceReferenceDate * 1000) // milliseconds
var requestMetadata = RequestMetadata(url: request.url, startTime: startTime, trackingId: trackingId)
return { (data: Data?, response: URLResponse?, error: Error?) -> Void in
if shouldRetryRequest(response: response, error: error, numberOfRetries: numberOfRetries) {
retryRequest(originalRequest: request, originalTask: originalTask, bmsUrlSession: bmsUrlSession)
}
else if isAuthorizationManagerRequired(for: response) {
// If authentication is successful, resend the original request with the "Authorization" header added
handleAuthorizationChallenge(session: urlSession, request: request, requestMetadata: requestMetadata, originalTask: originalTask, handleFailure: {
completionHandler(data, response, error)
})
}
// Don't log the request metadata if the response is a redirect
else if let response = response as? HTTPURLResponse, response.statusCode >= 300 && response.statusCode < 400 {
completionHandler(data, response, error)
}
// Only log the request metadata if a response was received so that we have all of the required data for logging
else if response != nil {
if BMSURLSession.shouldRecordNetworkMetadata {
requestMetadata.response = response
requestMetadata.bytesReceived = Int64(data?.count ?? 0)
requestMetadata.bytesSent = Int64(requestBody?.count ?? 0)
requestMetadata.endTime = Int64(Date.timeIntervalSinceReferenceDate * 1000) // milliseconds
requestMetadata.recordMetadata()
}
completionHandler(data, response, error)
}
else {
completionHandler(data, response, error)
}
}
}
// Determines whether auto-retry is appropriate given the conditions of the request failure.
internal static func shouldRetryRequest(response: URLResponse?, error: Error?, numberOfRetries: Int) -> Bool {
// Make sure auto-retries are even allowed
guard numberOfRetries > 0 else {
return false
}
// Client-side issues eligible for retries
let errorCodesForRetries: [Int] = [NSURLErrorTimedOut, NSURLErrorCannotConnectToHost, NSURLErrorNetworkConnectionLost]
if let error = error as NSError?,
errorCodesForRetries.contains(error.code) {
// If the device is running iOS, we should make sure that it has a network connection before resending the request
#if os(iOS)
let networkDetector = NetworkMonitor()
if networkDetector?.currentNetworkConnection != NetworkConnection.noConnection {
return true
}
else {
BMSURLSession.logger.error(message: "Cannot retry the last BMSURLSession request because the device has no internet connection.")
}
#else
return true
#endif
}
// Server-side issues eligible for retries
if let response = response as? HTTPURLResponse,
response.statusCode == 504 {
return true
}
return false
}
// Send the request again
// For auto-retries
internal static func retryRequest(originalRequest: URLRequest, originalTask: BMSURLSessionTaskType, bmsUrlSession: BMSURLSession) {
// Duplicate the original BMSURLSession, but with 1 fewer retry available
let newBmsUrlSession = BMSURLSession(configuration: bmsUrlSession.configuration, delegate: bmsUrlSession.delegate, delegateQueue: bmsUrlSession.delegateQueue, autoRetries: bmsUrlSession.numberOfRetries - 1)
originalTask.prepareForResending(urlSession: newBmsUrlSession, request: originalRequest).resume()
}
// Determines if the response is an authentication challenge from an MCA-protected server
// If true, we must use BMSSecurity to authenticate
internal static func isAuthorizationManagerRequired(for response: URLResponse?) -> Bool {
let authManager = BMSClient.sharedInstance.authorizationManager
if let response = response as? HTTPURLResponse,
let wwwAuthHeader = response.allHeaderFields["Www-Authenticate"] as? String,
authManager.isAuthorizationRequired(for: response.statusCode, httpResponseAuthorizationHeader: wwwAuthHeader) {
return true
}
return false
}
// First, obtain authorization with AuthorizationManager from BMSSecurity.
// If authentication is successful, a new URLSessionTask is generated.
// This new task is the same as the original task, but now with the "Authorization" header needed to complete the request successfully.
internal static func handleAuthorizationChallenge(session urlSession: URLSession, request: URLRequest, requestMetadata: RequestMetadata, originalTask: BMSURLSessionTaskType, handleFailure: @escaping () -> Void) {
let authManager = BMSClient.sharedInstance.authorizationManager
let authCallback: BMSCompletionHandler = {(response: Response?, error:Error?) in
if error == nil && response?.statusCode != nil && (response?.statusCode)! >= 200 && (response?.statusCode)! < 300 {
var request = request
let authManager = BMSClient.sharedInstance.authorizationManager
if let authHeader: String = authManager.cachedAuthorizationHeader {
request.setValue(authHeader, forHTTPHeaderField: "Authorization")
}
originalTask.prepareForResending(urlSession: urlSession, request: request, requestMetadata: requestMetadata).resume()
}
else {
BMSURLSession.logger.error(message: "Authorization process failed. \nError: \(String(describing: error)). \nResponse: \(response?.responseText ?? "No response").")
handleFailure()
}
}
authManager.obtainAuthorization(completionHandler: authCallback)
}
internal static func recordMetadataCompletionHandler(request: URLRequest, requestMetadata: RequestMetadata, originalCompletionHandler: @escaping BMSDataTaskCompletionHandler) -> BMSDataTaskCompletionHandler {
var requestMetadata = requestMetadata
let newCompletionHandler = {(data: Data?, response: URLResponse?, error: Error?) -> Void in
if BMSURLSession.shouldRecordNetworkMetadata {
requestMetadata.bytesReceived = Int64(data?.count ?? 0)
requestMetadata.bytesSent = Int64(request.httpBody?.count ?? 0)
requestMetadata.endTime = Int64(Date.timeIntervalSinceReferenceDate * 1000) // milliseconds
requestMetadata.recordMetadata()
}
originalCompletionHandler(data, response, error)
}
return newCompletionHandler
}
}
// List of the supported types of URLSessionTask
// Stored in BMSURLSession to determine what type of task to use if the request needs to be resent
// Used for:
// AuthorizationManager - After successfully authenticating with MCA, the original request must be resent with the newly-obtained authorization header.
// Auto-retries - If the original request failed due to network issues, the request can be sent again for a number of attempts specified by the user
internal enum BMSURLSessionTaskType {
case dataTask
case dataTaskWithCompletionHandler(BMSDataTaskCompletionHandler)
case uploadTaskWithFile(URL)
case uploadTaskWithData(Data)
case uploadTaskWithFileAndCompletionHandler(URL, BMSDataTaskCompletionHandler)
case uploadTaskWithDataAndCompletionHandler(Data?, BMSDataTaskCompletionHandler)
// Recreate the URLSessionTask from the original request to later resend it
func prepareForResending(urlSession: NetworkSession, request: URLRequest, requestMetadata: RequestMetadata? = nil) -> URLSessionTask {
// If this request is considered a continuation of the original request, then we record metadata from the original request instead of creating a new set of metadata (i.e. for MCA authorization requests). Otherwise, return the original completion handler (i.e. for auto-retries).
// This is not required for delegates since this is already taken care of in BMSURLSessionDelegate
func createNewCompletionHandler(originalCompletionHandler: @escaping BMSDataTaskCompletionHandler) -> BMSDataTaskCompletionHandler {
var completionHandler = originalCompletionHandler
if let requestMetadata = requestMetadata {
completionHandler = BMSURLSessionUtility.recordMetadataCompletionHandler(request: request, requestMetadata: requestMetadata, originalCompletionHandler: completionHandler)
}
return completionHandler
}
switch self {
case .dataTask:
return urlSession.dataTask(with: request)
case .dataTaskWithCompletionHandler(let completionHandler):
let newCompletionHandler = createNewCompletionHandler(originalCompletionHandler: completionHandler)
return urlSession.dataTask(with: request, completionHandler: newCompletionHandler)
case .uploadTaskWithFile(let file):
return urlSession.uploadTask(with: request, fromFile: file)
case .uploadTaskWithData(let data):
return urlSession.uploadTask(with: request, from: data)
case .uploadTaskWithFileAndCompletionHandler(let file, let completionHandler):
let newCompletionHandler = createNewCompletionHandler(originalCompletionHandler: completionHandler)
return urlSession.uploadTask(with: request, fromFile: file, completionHandler: newCompletionHandler)
case .uploadTaskWithDataAndCompletionHandler(let data, let completionHandler):
let newCompletionHandler = createNewCompletionHandler(originalCompletionHandler: completionHandler)
return urlSession.uploadTask(with: request, from: data, completionHandler: newCompletionHandler)
}
}
}
/**************************************************************************************************/
// MARK: - Swift 2
#else
internal struct BMSURLSessionUtility {
// Inject BMSSecurity and BMSAnalytics into the request object by adding headers
internal static func addBMSHeaders(to request: NSURLRequest, onlyIf precondition: Bool) -> NSURLRequest {
let bmsRequest = request.mutableCopy() as! NSMutableURLRequest
// If the request is in the process of authentication with the MCA authorization server, do not attempt to add headers, since this is an intermediary request.
if precondition {
// Security
let authManager = BMSClient.sharedInstance.authorizationManager
if let authHeader: String = authManager.cachedAuthorizationHeader {
bmsRequest.setValue(authHeader, forHTTPHeaderField: "Authorization")
}
// Analytics
bmsRequest.setValue(NSUUID().UUIDString, forHTTPHeaderField: "x-wl-analytics-tracking-id")
if let requestMetadata = BaseRequest.requestAnalyticsData {
bmsRequest.setValue(requestMetadata, forHTTPHeaderField: "x-mfp-analytics-metadata")
}
}
return bmsRequest
}
// Needed to hook in challenge handling via AuthorizationManager, as well as handling auto-retries
internal static func generateBmsCompletionHandler(from completionHandler: BMSDataTaskCompletionHandler, bmsUrlSession: BMSURLSession, urlSession: NSURLSession, request: NSURLRequest, originalTask: BMSURLSessionTaskType, requestBody: NSData?, numberOfRetries: Int) -> BMSDataTaskCompletionHandler {
let trackingId = NSUUID().UUIDString
let startTime = Int64(NSDate.timeIntervalSinceReferenceDate() * 1000) // milliseconds
var requestMetadata = RequestMetadata(url: request.URL, startTime: startTime, trackingId: trackingId)
return { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if shouldRetryRequest(response: response, error: error, numberOfRetries: numberOfRetries) {
retryRequest(originalRequest: request, originalTask: originalTask, bmsUrlSession: bmsUrlSession)
}
else if isAuthorizationManagerRequired(response) {
// If authentication is successful, resend the original request with the "Authorization" header added
let originalRequest = request.mutableCopy() as! NSMutableURLRequest
handleAuthorizationChallenge(session: urlSession, request: originalRequest, requestMetadata: requestMetadata, originalTask: originalTask, handleFailure: {
completionHandler(data, response, error)
})
}
// Don't log the request metadata if the response is a redirect
else if let response = response as? NSHTTPURLResponse where response.statusCode >= 300 && response.statusCode < 400 {
completionHandler(data, response, error)
}
// Only log the request metadata if a response was received so that we have all of the required data for logging
else if response != nil {
if BMSURLSession.shouldRecordNetworkMetadata {
requestMetadata.response = response
requestMetadata.bytesReceived = Int64(data?.length ?? 0)
requestMetadata.bytesSent = Int64(requestBody?.length ?? 0)
requestMetadata.endTime = Int64(NSDate.timeIntervalSinceReferenceDate() * 1000) // milliseconds
requestMetadata.recordMetadata()
}
completionHandler(data, response, error)
}
else {
completionHandler(data, response, error)
}
}
}
// Determines whether auto-retry is appropriate given the conditions of the request failure.
internal static func shouldRetryRequest(response response: NSURLResponse?, error: NSError?, numberOfRetries: Int) -> Bool {
// Make sure auto-retries are even allowed
guard numberOfRetries > 0 else {
return false
}
// Client-side issues eligible for retries
let errorCodesForRetries: [Int] = [NSURLErrorTimedOut, NSURLErrorCannotConnectToHost, NSURLErrorNetworkConnectionLost]
if let error = error where
errorCodesForRetries.contains(error.code) {
// If the device is running iOS, we should make sure that it has a network connection before resending the request
#if os(iOS)
let networkDetector = NetworkMonitor()
if networkDetector?.currentNetworkConnection != NetworkConnection.noConnection {
return true
}
else {
BMSURLSession.logger.error(message: "Cannot retry the last BMSURLSession request because the device has no internet connection.")
}
#else
return true
#endif
}
// Server-side issues eligible for retries
if let response = response as? NSHTTPURLResponse where
response.statusCode == 504 {
return true
}
return false
}
// Send the request again
// For auto-retries
internal static func retryRequest(originalRequest originalRequest: NSURLRequest, originalTask: BMSURLSessionTaskType, bmsUrlSession: BMSURLSession) {
// Duplicate the original BMSURLSession, but with 1 fewer retry available
let newBmsUrlSession = BMSURLSession(configuration: bmsUrlSession.configuration, delegate: bmsUrlSession.delegate, delegateQueue: bmsUrlSession.delegateQueue, autoRetries: bmsUrlSession.numberOfRetries - 1)
originalTask.prepareForResending(urlSession: newBmsUrlSession, request: originalRequest).resume()
}
internal static func isAuthorizationManagerRequired(response: NSURLResponse?) -> Bool {
let authManager = BMSClient.sharedInstance.authorizationManager
if let response = response as? NSHTTPURLResponse,
let wwwAuthHeader = response.allHeaderFields["WWW-Authenticate"] as? String
where authManager.isAuthorizationRequired(for: response.statusCode, httpResponseAuthorizationHeader: wwwAuthHeader) {
return true
}
return false
}
// First, obtain authorization with AuthorizationManager from BMSSecurity.
// If authentication is successful, a new URLSessionTask is generated.
// This new task is the same as the original task, but now with the "Authorization" header needed to complete the request successfully.
internal static func handleAuthorizationChallenge(session urlSession: NSURLSession, request: NSMutableURLRequest, requestMetadata: RequestMetadata, originalTask: BMSURLSessionTaskType, handleFailure: () -> Void) {
let authManager = BMSClient.sharedInstance.authorizationManager
let authCallback: BMSCompletionHandler = {(response: Response?, error:NSError?) in
if error == nil && response?.statusCode != nil && (response?.statusCode)! >= 200 && (response?.statusCode)! < 300 {
let authManager = BMSClient.sharedInstance.authorizationManager
if let authHeader: String = authManager.cachedAuthorizationHeader {
request.setValue(authHeader, forHTTPHeaderField: "Authorization")
}
originalTask.prepareForResending(urlSession: urlSession, request: request, requestMetadata: requestMetadata).resume()
}
else {
BMSURLSession.logger.error(message: "Authorization process failed. \nError: \(error). \nResponse: \(response).")
handleFailure()
}
}
authManager.obtainAuthorization(completionHandler: authCallback)
}
internal static func recordMetadataCompletionHandler(request request: NSURLRequest, requestMetadata: RequestMetadata, originalCompletionHandler: BMSDataTaskCompletionHandler) -> BMSDataTaskCompletionHandler {
var requestMetadata = requestMetadata
let newCompletionHandler = {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if BMSURLSession.shouldRecordNetworkMetadata {
requestMetadata.bytesReceived = Int64(data?.length ?? 0)
requestMetadata.bytesSent = Int64(request.HTTPBody?.length ?? 0)
requestMetadata.endTime = Int64(NSDate.timeIntervalSinceReferenceDate() * 1000) // milliseconds
requestMetadata.recordMetadata()
}
originalCompletionHandler(data, response, error)
}
return newCompletionHandler
}
}
// List of the supported types of NSURLSessionTask
// Stored in BMSURLSession to determine what type of task to use when resending the request after authenticating with MCA
internal enum BMSURLSessionTaskType {
case dataTask
case dataTaskWithCompletionHandler(BMSDataTaskCompletionHandler)
case uploadTaskWithFile(NSURL)
case uploadTaskWithData(NSData)
case uploadTaskWithFileAndCompletionHandler(NSURL, BMSDataTaskCompletionHandler)
case uploadTaskWithDataAndCompletionHandler(NSData?, BMSDataTaskCompletionHandler)
// Recreate the URLSessionTask from the original request to later resend it
func prepareForResending(urlSession urlSession: NetworkSession, request: NSURLRequest, requestMetadata: RequestMetadata? = nil) -> NSURLSessionTask {
// If this request is considered a continuation of the original request, then we record metadata from the original request instead of creating a new set of metadata (i.e. for MCA authorization requests). Otherwise, return the original completion handler (i.e. for auto-retries).
// This is not required for delegates since this is already taken care of in BMSURLSessionDelegate
func createNewCompletionHandler(originalCompletionHandler originalCompletionHandler: BMSDataTaskCompletionHandler) -> BMSDataTaskCompletionHandler {
var completionHandler = originalCompletionHandler
if let requestMetadata = requestMetadata {
completionHandler = BMSURLSessionUtility.recordMetadataCompletionHandler(request: request, requestMetadata: requestMetadata, originalCompletionHandler: completionHandler)
}
return completionHandler
}
switch self {
case .dataTask:
return urlSession.dataTaskWithRequest(request)
case .dataTaskWithCompletionHandler(let completionHandler):
let newCompletionHandler = createNewCompletionHandler(originalCompletionHandler: completionHandler)
return urlSession.dataTaskWithRequest(request, completionHandler: newCompletionHandler)
case .uploadTaskWithFile(let file):
return urlSession.uploadTaskWithRequest(request, fromFile: file)
case .uploadTaskWithData(let data):
return urlSession.uploadTaskWithRequest(request, fromData: data)
case .uploadTaskWithFileAndCompletionHandler(let file, let completionHandler):
let newCompletionHandler = createNewCompletionHandler(originalCompletionHandler: completionHandler)
return urlSession.uploadTaskWithRequest(request, fromFile: file, completionHandler: newCompletionHandler)
case .uploadTaskWithDataAndCompletionHandler(let data, let completionHandler):
let newCompletionHandler = createNewCompletionHandler(originalCompletionHandler: completionHandler)
return urlSession.uploadTaskWithRequest(request, fromData: data, completionHandler: newCompletionHandler)
}
}
}
#endif
| apache-2.0 | c1769cfd0eb00484c12b090fd8ea0a49 | 47.219739 | 305 | 0.660269 | 6.57375 | false | false | false | false |
igerard/Genesis | Genesis/Board/BoardView.swift | 1 | 2464 | //
// BoardView.swift
// Genesis
//
// Created by Iglesias, Gérard (FircoSoft) on 28/09/2017.
// Copyright © 2017 Gerard Iglesias. All rights reserved.
//
import UIKit
/// Will organize the layout of the document pages
class BoardView: UIView {
var pages = [BoardPageView]()
var current = 0
let device = MTLCreateSystemDefaultDevice()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard device != nil else { return }
backgroundColor = UIColor(white: 0.666, alpha: 1.0)
let firstPage = BoardPageView(frame: CGRect(x: 0, y: 0, width: A4.width, height: A4.height), device: device)
let curveRecogniser = GeoCurveRecogniser(target: firstPage, action: nil)
curveRecogniser.isEnabled = true
curveRecogniser.delaysTouchesBegan = true
firstPage.addGestureRecognizer(curveRecogniser)
pages.append(firstPage)
addSubview(pages[0])
}
override func draw(_ rect: CGRect) {
board_log_debug("UIBezierPath supports Secure Coding: %{bool}d", UIBezierPath.supportsSecureCoding)
}
override func layoutSubviews() {
pages[0].frame = layoutPage(pos: 0, nbPages: 1)
}
/// For now just one page
///
/// - Parameters:
/// - pos: position of the pages in the book
/// - nbPages: number of pages in the book
func layoutPage(pos: Int, nbPages: Int) -> CGRect {
let pageFormat = pages[pos].pageFormat
let scale: CGFloat = 1.00
let safeframe = bounds.inset(by: safeAreaInsets)
func center(width: CGFloat, height: CGFloat) -> CGRect {
let left = safeframe.origin.x + (safeframe.width - width) / 2.0
let bottom = safeframe.origin.y + (safeframe.height - height) / 2.0
return CGRect(x: left, y: bottom, width: width, height: height)
}
if safeframe.width > safeframe.height {
let height = safeframe.height * scale
let width = (height * pageFormat.width) / pageFormat.height
return center(width: width, height: height)
}
else {
let height = safeframe.height * scale
let width = height * pageFormat.width / pageFormat.height
return center(width: width, height: height)
}
}
@IBAction func toggleGrid(_ sender: Any) {
pages[current].showGrid = !pages[current].showGrid
}
override var canBecomeFirstResponder: Bool {
return true
}
override func didMoveToWindow() {
let f = becomeFirstResponder()
board_log_debug("First Responder : %{bool}d", f)
}
}
| mit | 2e916595303ace2a4000e8ad4fa133ce | 29.395062 | 112 | 0.672218 | 3.9392 | false | false | false | false |
frankthamel/TalenePowerPack | TalenePowerPack/TaleneFancyButton.swift | 1 | 2799 | //
// TaleneFancyButton.swift
// TalenePowerPack
//
// Created by frank thamel on 5/28/17.
// Copyright © 2017 Talene. All rights reserved.
//
import UIKit
@IBDesignable
class TaleneFancyButton: UIButton {
// set corner radius property
@IBInspectable public var cornerRadius : CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
// set button border width
@IBInspectable public var borderWidth : CGFloat = 0.0 {
didSet {
layer.borderWidth = borderWidth
}
}
// set button border color
@IBInspectable public var borderColor : UIColor = .black {
didSet {
layer.borderColor = borderColor.cgColor
}
}
/*
* Set title padding
*/
// Set title left padding
@IBInspectable public var titleLeftPadding : CGFloat = 0.0 {
didSet {
titleEdgeInsets.left = titleLeftPadding
}
}
// Set title rigt padding
@IBInspectable public var titleRightPadding : CGFloat = 0.0 {
didSet {
titleEdgeInsets.right = titleRightPadding
}
}
// Set title top padding
@IBInspectable public var titleTopPadding : CGFloat = 0.0 {
didSet {
titleEdgeInsets.top = titleTopPadding
}
}
// Set title Bottom padding
@IBInspectable public var titleBottomPadding : CGFloat = 0.0 {
didSet {
titleEdgeInsets.bottom = titleBottomPadding
}
}
/*
* Set image padding
*/
// set image left padding
@IBInspectable public var imageLeftPadding : CGFloat = 0.0 {
didSet {
imageEdgeInsets.left = imageLeftPadding
}
}
// set image right padding
@IBInspectable public var imageRightPadding : CGFloat = 0.0 {
didSet {
imageEdgeInsets.right = imageRightPadding
}
}
// set image top padding
@IBInspectable public var imageTopPadding : CGFloat = 0.0 {
didSet {
imageEdgeInsets.top = imageTopPadding
}
}
// set image bottom padding
@IBInspectable public var imageBottomPadding : CGFloat = 0.0 {
didSet {
imageEdgeInsets.bottom = imageBottomPadding
}
}
// set image right alligned
@IBInspectable public var enableImageRightAligned : Bool = false
override func layoutSubviews() {
super.layoutSubviews()
if enableImageRightAligned {
if let imageView = imageView {
imageEdgeInsets.left = self.bounds.width - imageView.bounds.width - imageRightPadding
}
}
}
}
| mit | 0b43737749c6a3ad00bedc2bf893b41e | 23.54386 | 101 | 0.580772 | 5.200743 | false | false | false | false |
richa008/PitchPerfect | PitchPerfect/PitchPerfect/PlaySoundViewController+Audio.swift | 1 | 5994 | //
// PlaySoundsViewController+Audio.swift
// PitchPerfect
//
// Copyright © 2016 Udacity. All rights reserved.
//
import UIKit
import AVFoundation
extension PlaySoundViewController: AVAudioPlayerDelegate {
struct Alerts {
static let DismissAlert = "Dismiss"
static let RecordingDisabledTitle = "Recording Disabled"
static let RecordingDisabledMessage = "You've disabled this app from recording your microphone. Check Settings."
static let RecordingFailedTitle = "Recording Failed"
static let RecordingFailedMessage = "Something went wrong with your recording."
static let AudioRecorderError = "Audio Recorder Error"
static let AudioSessionError = "Audio Session Error"
static let AudioRecordingError = "Audio Recording Error"
static let AudioFileError = "Audio File Error"
static let AudioEngineError = "Audio Engine Error"
}
// raw values correspond to sender tags
enum PlayingState { case Playing, NotPlaying }
// MARK: Audio Functions
func setupAudio() {
// initialize (recording) audio file
do {
audioFile = try AVAudioFile(forReading: recordedAudioURL)
} catch {
showAlert(Alerts.AudioFileError, message: String(error))
}
print("Audio has been setup")
}
func playSound(rate rate: Float? = nil, pitch: Float? = nil, echo: Bool = false, reverb: Bool = false) {
// initialize audio engine components
audioEngine = AVAudioEngine()
// node for playing audio
audioPlayerNode = AVAudioPlayerNode()
audioEngine.attachNode(audioPlayerNode)
// node for adjusting rate/pitch
let changeRatePitchNode = AVAudioUnitTimePitch()
if let pitch = pitch {
changeRatePitchNode.pitch = pitch
}
if let rate = rate {
changeRatePitchNode.rate = rate
}
audioEngine.attachNode(changeRatePitchNode)
// node for echo
let echoNode = AVAudioUnitDistortion()
echoNode.loadFactoryPreset(.MultiEcho1)
audioEngine.attachNode(echoNode)
// node for reverb
let reverbNode = AVAudioUnitReverb()
reverbNode.loadFactoryPreset(.Cathedral)
reverbNode.wetDryMix = 50
audioEngine.attachNode(reverbNode)
// connect nodes
if echo == true && reverb == true {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, echoNode, reverbNode, audioEngine.outputNode)
} else if echo == true {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, echoNode, audioEngine.outputNode)
} else if reverb == true {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, reverbNode, audioEngine.outputNode)
} else {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, audioEngine.outputNode)
}
// schedule to play and start the engine!
audioPlayerNode.stop()
audioPlayerNode.scheduleFile(audioFile, atTime: nil) {
var delayInSeconds: Double = 0
if let lastRenderTime = self.audioPlayerNode.lastRenderTime, let playerTime = self.audioPlayerNode.playerTimeForNodeTime(lastRenderTime) {
if let rate = rate {
delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate) / Double(rate)
} else {
delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate)
}
}
// schedule a stop timer for when audio finishes playing
self.stopTimer = NSTimer(timeInterval: delayInSeconds, target: self, selector: "stopAudio", userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(self.stopTimer!, forMode: NSDefaultRunLoopMode)
}
do {
try audioEngine.start()
} catch {
showAlert(Alerts.AudioEngineError, message: String(error))
return
}
// play the recording!
audioPlayerNode.play()
}
// MARK: Connect List of Audio Nodes
func connectAudioNodes(nodes: AVAudioNode...) {
for x in 0..<nodes.count-1 {
audioEngine.connect(nodes[x], to: nodes[x+1], format: audioFile.processingFormat)
}
}
func stopAudio() {
if let stopTimer = stopTimer {
stopTimer.invalidate()
}
configureUI(.NotPlaying)
if let audioPlayerNode = audioPlayerNode {
audioPlayerNode.stop()
}
if let audioEngine = audioEngine {
audioEngine.stop()
audioEngine.reset()
}
}
// MARK: UI Functions
func configureUI(playState: PlayingState) {
switch(playState) {
case .Playing:
setPlayButtonsEnabled(false)
stopButton.enabled = true
case .NotPlaying:
setPlayButtonsEnabled(true)
stopButton.enabled = false
}
}
func setPlayButtonsEnabled(enabled: Bool) {
snailButton.enabled = enabled
chipmunkButton.enabled = enabled
rabbitButton.enabled = enabled
vaderButton.enabled = enabled
echoButton.enabled = enabled
reverbButton.enabled = enabled
}
func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: Alerts.DismissAlert, style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
| mit | 39231cf9ed8d866346accd8a0e38a504 | 32.480447 | 158 | 0.616052 | 5.513339 | false | false | false | false |
marketplacer/Scrollable | Scrollable/Scrollable.swift | 2 | 2662 | import UIKit
/**
Makes the content in the scroll view scrollable.
*/
open class Scrollable {
@discardableResult
open class func createContentView(_ scrollView: UIScrollView) -> UIView {
let contentView = UIView()
scrollView.addSubview(contentView)
Scrollable.embedSubviews(scrollView, inNewSuperview: contentView)
Scrollable.layoutContentViewInScrollView(contentView, scrollView: scrollView)
scrollView.layoutIfNeeded()
return contentView
}
class func layoutContentViewInScrollView(_ contentView: UIView, scrollView: UIView) {
// Make content view fill scroll view
ScrollableAutolayoutConstraints.fillParent(contentView, parentView: scrollView, margin: 0,
vertically: false)
ScrollableAutolayoutConstraints.fillParent(contentView, parentView: scrollView, margin: 0,
vertically: true)
// Content view width is equal to scroll view width
ScrollableAutolayoutConstraints.equalWidth(contentView, viewTwo: scrollView,
constraintContainer: scrollView)
}
class func embedSubviews(_ fromView: UIView, inNewSuperview newSuperview: UIView) {
newSuperview.translatesAutoresizingMaskIntoConstraints = false
// Move all subviews to newSuperview
for subview in fromView.subviews {
if subview == newSuperview { continue }
newSuperview.addSubview(subview)
}
// Move all scrollview constraints to contentView
moveConstraints(fromView, toView: newSuperview)
}
class func moveConstraints(_ fromView: UIView, toView: UIView) {
let constraints = fromView.constraints
for constraint in constraints {
moveConstraint(constraint, fromView: fromView, toView: toView)
}
}
fileprivate class func moveConstraint(_ constraint: NSLayoutConstraint,
fromView: UIView, toView: UIView) {
if let firstItem = constraint.firstItem as? NSObject {
let newFirstItem = firstItem == fromView ? toView : firstItem
if let secondItem = constraint.secondItem as? NSObject {
let newSecondItem = secondItem == fromView ? toView : secondItem
let newConstraint = NSLayoutConstraint(
item: newFirstItem,
attribute: constraint.firstAttribute,
relatedBy: constraint.relation,
toItem: newSecondItem,
attribute: constraint.secondAttribute,
multiplier: constraint.multiplier,
constant: constraint.constant
)
newConstraint.priority = constraint.priority
fromView.removeConstraint(constraint)
toView.addConstraint(newConstraint)
}
}
}
}
| mit | b8e82e8ded5e4dca79bd895437b240a9 | 31.463415 | 94 | 0.702855 | 5.712446 | false | false | false | false |
shiratsu/PullToRefreshSwift | Source/PullToRefreshView.swift | 1 | 8625 | //
// PullToRefreshConst.swift
// PullToRefreshSwift
//
// Created by Yuji Hato on 12/11/14.
//
import UIKit
public class PullToRefreshView: UIView {
enum PullToRefreshState {
case Normal
case Pulling
case Refreshing
}
// MARK: Variables
let contentOffsetKeyPath = "contentOffset"
var kvoContext = ""
private var options: PullToRefreshOption!
private var backgroundView: UIView!
private var arrow: UIImageView!
private var indicator: UIActivityIndicatorView!
private var scrollViewBounces: Bool = false
private var scrollViewInsets: UIEdgeInsets = UIEdgeInsetsZero
private var previousOffset: CGFloat = 0
private var refreshCompletion: (() -> ()) = {}
var state: PullToRefreshState = PullToRefreshState.Normal {
didSet {
if self.state == oldValue {
return
}
switch self.state {
case .Normal:
stopAnimating()
case .Refreshing:
startAnimating()
default:
break
}
}
}
// MARK: UIView
override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience init(options: PullToRefreshOption, frame: CGRect, refreshCompletion :(() -> ())) {
self.init(frame: frame)
self.options = options
self.refreshCompletion = refreshCompletion
self.backgroundView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
self.backgroundView.backgroundColor = self.options.backgroundColor
self.backgroundView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.addSubview(backgroundView)
self.arrow = UIImageView(frame: CGRectMake(0, 0, 30, 30))
self.arrow.autoresizingMask = [UIViewAutoresizing.FlexibleLeftMargin,UIViewAutoresizing.FlexibleRightMargin]
self.arrow.image = UIImage(named: PullToRefreshConst.imageName)
self.addSubview(arrow)
self.indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
self.indicator.bounds = self.arrow.bounds
self.indicator.autoresizingMask = self.arrow.autoresizingMask
self.indicator.hidesWhenStopped = true
self.indicator.color = options.indicatorColor
self.addSubview(indicator)
self.autoresizingMask = UIViewAutoresizing.FlexibleWidth
}
public override func layoutSubviews() {
super.layoutSubviews()
self.arrow.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
self.indicator.center = self.arrow.center
}
public override func willMoveToSuperview(superView: UIView!) {
superview?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &kvoContext)
if let scrollView = superView as? UIScrollView {
scrollView.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &kvoContext)
}
}
deinit {
if let scrollView = superview as? UIScrollView {
scrollView.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &kvoContext)
}
}
// MARK: KVO
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if (context == &kvoContext && keyPath == contentOffsetKeyPath) {
if let scrollView = object as? UIScrollView {
// Debug
//println(scrollView.contentOffset.y)
var offsetWithoutInsets = self.previousOffset + self.scrollViewInsets.top
// Update the content inset for fixed section headers
if self.options.fixedSectionHeader && self.state == .Refreshing {
if (scrollView.contentOffset.y > 0) {
scrollView.contentInset = UIEdgeInsetsZero;
}
return
}
// Alpha set
if PullToRefreshConst.alpha {
var alpha = fabs(offsetWithoutInsets) / (self.frame.size.height + 30)
if alpha > 0.8 {
alpha = 0.8
}
self.arrow.alpha = alpha
}
// Backgroundview frame set
if PullToRefreshConst.fixedTop {
if PullToRefreshConst.height < fabs(offsetWithoutInsets) {
self.backgroundView.frame.size.height = fabs(offsetWithoutInsets)
} else {
self.backgroundView.frame.size.height = PullToRefreshConst.height
}
} else {
self.backgroundView.frame.size.height = PullToRefreshConst.height + fabs(offsetWithoutInsets)
self.backgroundView.frame.origin.y = -fabs(offsetWithoutInsets)
}
// Pulling State Check
if (offsetWithoutInsets < -self.frame.size.height) {
// pulling or refreshing
if (scrollView.dragging == false && self.state != .Refreshing) {
self.state = .Refreshing
} else if (self.state != .Refreshing) {
self.arrowRotation()
self.state = .Pulling
}
} else if (self.state != .Refreshing && offsetWithoutInsets < 0) {
// normal
self.arrowRotationBack()
}
self.previousOffset = scrollView.contentOffset.y
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
// MARK: private
private func startAnimating() {
self.indicator.startAnimating()
self.arrow.hidden = true
if let scrollView = superview as? UIScrollView {
scrollViewBounces = scrollView.bounces
scrollViewInsets = scrollView.contentInset
var insets = scrollView.contentInset
insets.top += self.frame.size.height
scrollView.contentOffset.y = self.previousOffset
scrollView.bounces = false
let interval:NSTimeInterval = 0
UIView.animateWithDuration(PullToRefreshConst.animationDuration, delay: interval, options:UIViewAnimationOptions(), animations: {
scrollView.contentInset = insets
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -insets.top)
}, completion: {finished in
if self.options.autoStopTime != 0 {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(self.options.autoStopTime * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
self.state = .Normal
}
}
self.refreshCompletion()
})
}
}
private func stopAnimating() {
self.indicator.stopAnimating()
self.arrow.transform = CGAffineTransformIdentity
self.arrow.hidden = false
if let scrollView = superview as? UIScrollView {
scrollView.bounces = self.scrollViewBounces
UIView.animateWithDuration(PullToRefreshConst.animationDuration, animations: { () -> Void in
scrollView.contentInset = self.scrollViewInsets
}) { (Bool) -> Void in
}
}
}
private func arrowRotation() {
let tmp = M_PI-0.0000001
let rotation = CGFloat(tmp)
UIView.animateWithDuration(0.2, delay: 0, options:[], animations: {
// -0.0000001 for the rotation direction control
self.arrow.transform = CGAffineTransformMakeRotation(rotation)
}, completion:nil)
}
private func arrowRotationBack() {
UIView.animateWithDuration(0.2, delay: 0, options:[], animations: {
self.arrow.transform = CGAffineTransformIdentity
}, completion:nil)
}
}
| mit | 5b9e950575953728ca0490efa678acf0 | 38.027149 | 164 | 0.574841 | 5.811995 | false | false | false | false |
p581581/BLACK-JACK-IN-SWIFT | BLACK JACKTests/BLACK_JACKTests.swift | 1 | 8916 | //
// BLACK_JACKTests.swift
// BLACK JACKTests
//
// Created by 581 on 2014/7/8.
// Copyright (c) 2014年 581. All rights reserved.
//
import XCTest
import UIKit
class BLACK_JACKTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testBJCard() {
// This is an example of a functional test case.
var card : BJCard
card = BJCard(digit: 1, suit: .Spade)
XCTAssert(card.isAnAce(), "Digit Ace error")
card = BJCard(digit: 2, suit: .Club)
XCTAssert(!card.isAnAce(), "Digit not Ace error")
card = BJCard(digit: 10, suit: .Club)
XCTAssert(card.isFaceOrTenCard(), "Digit Ten error")
card = BJCard(digit: 13, suit: .Club)
XCTAssert(card.isFaceOrTenCard(), "Digit Face error")
card = BJCard(digit: 9, suit: .Club)
XCTAssert(!card.isFaceOrTenCard(), "Digit not Ten or Face error ")
XCTAssertEqualObjects(card.getCardImage(), UIImage(named: "club-9"), "Get wrong card image.")
var cards = card.generateAPackOfRandCards()
XCTAssertEqual(cards.count, 52, "generate the wrong number of cards")
}
func testBJGameModel() {
var gameModel = BJGameModel()
var cardNum = gameModel.cards.count
var card = gameModel.nextCard()
XCTAssertEqual(gameModel.cards.count, cardNum - 1, "the number of card is wrong")
XCTAssertNotNil(card, "the next card is nil")
var playerCardNum = gameModel.playerCards.count
card = gameModel.nextPlayerCard()
XCTAssertEqual(gameModel.playerCards.count, playerCardNum + 1, "the number of player's card is wrong")
XCTAssertNotNil(card, "the next player's card is nil")
var dealerCardNum = gameModel.dealerCards.count
card = gameModel.nextDealerCard()
XCTAssertEqual(gameModel.dealerCards.count, dealerCardNum + 1, "the number of dealer's card is wrong")
XCTAssertNotNil(card, "the next dealer's card is nil")
var suit = BJCard.BJCardSuit.Spade
var cards = [BJCard(digit: 1, suit: suit), BJCard(digit: 9, suit: suit), BJCard(digit: 1, suit: suit)]
XCTAssertFalse(gameModel.areCardsBust(cards), "the cards bust incorrectly")
XCTAssertEqual(gameModel.calculateBestScore(cards), 21, "calculate the wrong score")
cards = [BJCard(digit: 10, suit: suit), BJCard(digit: 10, suit: suit), BJCard(digit: 2, suit: suit)]
XCTAssert(gameModel.areCardsBust(cards), "the cards not bust incorrectly")
XCTAssertEqual(gameModel.calculateBestScore(cards), 0, "calculate the wrong score")
// tesing updating game stage
//player got 21 points
gameModel = BJGameModel()
gameModel.playerCards = [BJCard(digit: 10, suit: suit), BJCard(digit: 1, suit: suit)]
gameModel.updateGameStage()
XCTAssertEqual(gameModel.gameStage, .Dealer, "the stage is wrong (should be Dealer stage)")
//player got 5 cards (max)
gameModel = BJGameModel()
gameModel.playerCards = [BJCard(digit: 6, suit: suit), BJCard(digit: 1, suit: suit), BJCard(digit: 2, suit: suit), BJCard(digit: 3, suit: suit), BJCard(digit: 5, suit: suit)]
gameModel.updateGameStage()
XCTAssertEqual(gameModel.gameStage, .Dealer, "the stage is wrong (should be Dealer stage)")
//player lose
gameModel = BJGameModel()
//player' card are bust
gameModel.playerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 8, suit: suit), BJCard(digit: 11, suit: suit)]
gameModel.updateGameStage()
XCTAssertEqual(gameModel.gameStage, .GameOver, "the stage is wrong (GameOver. Dealer win)")
XCTAssert(gameModel.didDealerWin, "the stage is wrong (GameOver. Dealer win)")
//player lose
gameModel = BJGameModel()
gameModel.gameStage = .Dealer
// the same score
gameModel.playerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 8, suit: suit), BJCard(digit: 3, suit: suit)]
gameModel.dealerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 8, suit: suit), BJCard(digit: 3, suit: suit)]
gameModel.updateGameStage()
XCTAssertEqual(gameModel.gameStage, .GameOver, "the stage is wrong (GameOver. Dealer win)")
XCTAssert(gameModel.didDealerWin, "the stage is wrong (GameOver. Dealer win)")
//player lose
gameModel = BJGameModel()
gameModel.gameStage = .Dealer
// dealer score is greater than player's
gameModel.playerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 8, suit: suit), BJCard(digit: 1, suit: suit)]
gameModel.dealerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 8, suit: suit), BJCard(digit: 3, suit: suit)]
gameModel.updateGameStage()
XCTAssertEqual(gameModel.gameStage, .GameOver, "the stage is wrong (GameOver. Dealer win)")
XCTAssert(gameModel.didDealerWin, "the stage is wrong (GameOver. Dealer win)")
//player lose
gameModel = BJGameModel()
gameModel.gameStage = .Dealer
// dealer score is greater than player's
gameModel.playerCards = [BJCard(digit: 2, suit: suit), BJCard(digit: 6, suit: suit), BJCard(digit: 1, suit: suit), BJCard(digit: 3, suit: suit), BJCard(digit: 4, suit: suit)]
gameModel.dealerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 8, suit: suit), BJCard(digit: 3, suit: suit)]
gameModel.updateGameStage()
XCTAssertEqual(gameModel.gameStage, .GameOver, "the stage is wrong (GameOver. Dealer win)")
XCTAssert(gameModel.didDealerWin, "the stage is wrong (GameOver. Dealer win)")
//player lose
gameModel = BJGameModel()
gameModel.gameStage = .Dealer
// dealer score is greater than player's
gameModel.playerCards = [BJCard(digit: 2, suit: suit), BJCard(digit: 5, suit: suit), BJCard(digit: 1, suit: suit), BJCard(digit: 3, suit: suit), BJCard(digit: 4, suit: suit)]
gameModel.dealerCards = [BJCard(digit: 2, suit: suit), BJCard(digit: 6, suit: suit), BJCard(digit: 1, suit: suit), BJCard(digit: 3, suit: suit), BJCard(digit: 4, suit: suit)]
gameModel.updateGameStage()
XCTAssertEqual(gameModel.gameStage, .GameOver, "the stage is wrong (GameOver. Dealer win)")
XCTAssert(gameModel.didDealerWin, "the stage is wrong (GameOver. Dealer win)")
//dealer lose
gameModel = BJGameModel()
gameModel.gameStage = .Dealer
// dealer score is greater than player's
gameModel.playerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 8, suit: suit), BJCard(digit: 1, suit: suit)]
gameModel.dealerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 8, suit: suit), BJCard(digit: 10, suit: suit)]
gameModel.updateGameStage()
XCTAssertEqual(gameModel.gameStage, .GameOver, "the stage is wrong (GameOver. Player win)")
XCTAssertFalse(gameModel.didDealerWin, "the stage is wrong (GameOver. Player win)")
// game continue
gameModel = BJGameModel()
gameModel.gameStage = .Dealer
// dealer score is greater than player's
gameModel.playerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 8, suit: suit), BJCard(digit: 1, suit: suit)]
gameModel.dealerCards = [BJCard(digit: 9, suit: suit), BJCard(digit: 4, suit: suit), BJCard(digit: 3, suit: suit)]
gameModel.updateGameStage()
XCTAssertEqual(gameModel.gameStage, .Dealer, "the stage is wrong (Dealer")
}
func testGameViewController() {
// let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil);
// let gvc : GameViewController = storyboard.instantiateViewControllerWithIdentifier("game") as GameViewController
// let gvc = GameViewController(coder: nil)
// let vc : ViewController = storyboard.instantiateInitialViewController() as ViewController
XCTAssert(true, "testing")
// XCTAssertNotNil(gvc.hitBtn, "stand button shouldn't be enabled.")
// XCTAssert(gvc.hitBtn.enabled, "stand button shouldn't be enabled.")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 | 9c99d176b0d97be34a0feda5c07032d1 | 47.978022 | 182 | 0.633947 | 4.432621 | false | true | false | false |
yonasstephen/swift-of-airbnb | airbnb-occupant-filter/airbnb-occupant-filter/ViewController.swift | 1 | 945 | //
// ViewController.swift
// airbnb-occupant-filter
//
// Created by Yonas Stephen on 4/4/17.
// Copyright © 2017 Yonas Stephen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
lazy var occupantFilter: AirbnbOccupantFilter = {
let btn = AirbnbOccupantFilter()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.delegate = self
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(occupantFilter)
occupantFilter.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
occupantFilter.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
occupantFilter.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
occupantFilter.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
}
| mit | 56e966caea11c3a733e29a84f7c73d1e | 28.5 | 103 | 0.689619 | 4.968421 | false | false | false | false |
ivygulch/IVGRouter | IVGRouter/source/viewController/PlaceholderViewController.swift | 1 | 2338 | //
// PlaceholderViewController.swift
// IVGRouter
//
// Created by Douglas Sjoquist on 4/24/16.
// Copyright © 2016 Ivy Gulch LLC. All rights reserved.
//
import UIKit
open class PlaceholderViewController: UIViewController {
public init(childViewController: UIViewController? = nil) {
super.init(nibName: nil, bundle: nil)
self.childViewController = childViewController
}
public init(lazyLoader: @escaping (() -> UIViewController)) {
self.lazyLoader = lazyLoader
super.init(nibName: nil, bundle: nil)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open var childViewController: UIViewController? {
get {
return self.childViewControllers.first
}
set {
if newValue == self.childViewControllers.first {
return // nothing to do
}
for viewController in self.childViewControllers {
viewController.willMove(toParentViewController: nil)
viewController.view.removeFromSuperview()
viewController.removeFromParentViewController()
}
if let newValue = newValue {
addChildViewController(newValue)
newValue.view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
newValue.view.frame = self.view.bounds
self.view.addSubview(newValue.view)
newValue.didMove(toParentViewController: self)
}
}
}
open override func viewDidLoad() {
super.viewDidLoad()
if let lazyLoader = lazyLoader {
childViewController = lazyLoader()
}
}
override open var tabBarItem: UITabBarItem! {
get {
return childViewController?.tabBarItem ?? super.tabBarItem
}
set {
if let childViewController = childViewController {
childViewController.tabBarItem = newValue
} else {
super.tabBarItem = newValue
}
}
}
override open var navigationItem: UINavigationItem {
get {
return childViewController?.navigationItem ?? super.navigationItem
}
}
fileprivate var lazyLoader: (() -> UIViewController)?
}
| mit | 737feeb5f41214b7105c72b316d0d96b | 28.2125 | 81 | 0.602054 | 5.799007 | false | false | false | false |
LambertPark/MySecureNote | Pods/RealmSwift/RealmSwift/List.swift | 1 | 11415 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/// :nodoc:
/// Internal class. Do not use directly.
public class ListBase: RLMListBase {
// Printable requires a description property defined in Swift (and not obj-c),
// and it has to be defined as @objc override, which can't be done in a
// generic class.
/// Returns a human-readable description of the objects contained in the list.
@objc public override var description: String {
return descriptionWithMaxDepth(RLMDescriptionMaxDepth)
}
@objc private func descriptionWithMaxDepth(depth: UInt) -> String {
let type = "List<\(_rlmArray.objectClassName)>"
return gsub("RLMArray <0x[a-z0-9]+>", template: type, string: _rlmArray.descriptionWithMaxDepth(depth)) ?? type
}
/// Returns the number of objects in this list.
public var count: Int { return Int(_rlmArray.count) }
}
/**
`List<T>` is the container type in Realm used to define to-many relationships.
Lists hold a single `Object` subclass (`T`) which defines the "type" of the list.
Lists can be filtered and sorted with the same predicates as `Results<T>`.
When added as a property on `Object` models, the property must be declared as `let` and cannot be `dynamic`.
*/
public final class List<T: Object>: ListBase {
// MARK: Properties
/// The Realm the objects in this list belong to, or `nil` if the list's owning
/// object does not belong to a realm (the list is standalone).
public var realm: Realm? {
if let rlmRealm = _rlmArray.realm {
return Realm(rlmRealm)
} else {
return nil
}
}
/// Indicates if the list can no longer be accessed.
public var invalidated: Bool { return _rlmArray.invalidated }
// MARK: Initializers
/// Creates a `List` that holds objects of type `T`.
public override init() {
// FIXME: use T.className()
super.init(array: RLMArray(objectClassName: (T.self as Object.Type).className()))
}
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the list.
:param: object The object whose index is being queried.
:returns: The index of the given object, or `nil` if the object is not in the list.
*/
public func indexOf(object: T) -> Int? {
return notFoundToNil(_rlmArray.indexOfObject(unsafeBitCast(object, RLMObject.self)))
}
/**
Returns the index of the first object matching the given predicate,
or `nil` no objects match.
:param: predicate The `NSPredicate` used to filter the objects.
:returns: The index of the given object, or `nil` if no objects match.
*/
public func indexOf(predicate: NSPredicate) -> Int? {
return notFoundToNil(_rlmArray.indexOfObjectWithPredicate(predicate))
}
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
:param: predicateFormat The predicate format string, optionally followed by a variable number
of arguments.
:returns: The index of the given object, or `nil` if no objects match.
*/
public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? {
return indexOf(NSPredicate(format: predicateFormat, argumentArray: args))
}
// MARK: Object Retrieval
/**
Returns the object at the given `index` on get.
Replaces the object at the given `index` on set.
:warning: You can only set an object during a write transaction.
:param: index The index.
:returns: The object at the given `index`.
*/
public subscript(index: Int) -> T {
get {
throwForNegativeIndex(index)
return _rlmArray[UInt(index)] as! T
}
set {
throwForNegativeIndex(index)
return _rlmArray[UInt(index)] = newValue
}
}
/// Returns the first object in the list, or `nil` if empty.
public var first: T? { return _rlmArray.firstObject() as! T? }
/// Returns the last object in the list, or `nil` if empty.
public var last: T? { return _rlmArray.lastObject() as! T? }
// MARK: KVC
/**
Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects.
:param: key The name of the property.
:returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects.
*/
public override func valueForKey(key: String) -> AnyObject? {
return _rlmArray.valueForKey(key)
}
/**
Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key.
:warning: This method can only be called during a write transaction.
:param: value The object value.
:param: key The name of the property.
*/
public override func setValue(value: AnyObject?, forKey key: String) {
return _rlmArray.setValue(value, forKey: key)
}
// MARK: Filtering
/**
Returns `Results` containing list elements that match the given predicate.
:param: predicateFormat The predicate format string which can accept variable arguments.
:returns: `Results` containing list elements that match the given predicate.
*/
public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> {
return Results<T>(_rlmArray.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args)))
}
/**
Returns `Results` containing list elements that match the given predicate.
:param: predicate The predicate to filter the objects.
:returns: `Results` containing list elements that match the given predicate.
*/
public func filter(predicate: NSPredicate) -> Results<T> {
return Results<T>(_rlmArray.objectsWithPredicate(predicate))
}
// MARK: Sorting
/**
Returns `Results` containing list elements sorted by the given property.
:param: property The property name to sort by.
:param: ascending The direction to sort by.
:returns: `Results` containing list elements sorted by the given property.
*/
public func sorted(property: String, ascending: Bool = true) -> Results<T> {
return sorted([SortDescriptor(property: property, ascending: ascending)])
}
/**
Returns `Results` with elements sorted by the given sort descriptors.
:param: sortDescriptors `SortDescriptor`s to sort by.
:returns: `Results` with elements sorted by the given sort descriptors.
*/
public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> {
return Results<T>(_rlmArray.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue }))
}
// MARK: Mutation
/**
Appends the given object to the end of the list. If the object is from a
different Realm it is copied to the List's Realm.
:warning: This method can only be called during a write transaction.
:param: object An object.
*/
public func append(object: T) {
_rlmArray.addObject(unsafeBitCast(object, RLMObject.self))
}
/**
Appends the objects in the given sequence to the end of the list.
:warning: This method can only be called during a write transaction.
:param: objects A sequence of objects.
*/
public func extend<S: SequenceType where S.Generator.Element == T>(objects: S) {
for obj in objects {
_rlmArray.addObject(unsafeBitCast(obj, RLMObject.self))
}
}
/**
Inserts the given object at the given index.
:warning: This method can only be called during a write transaction.
:warning: Throws an exception when called with an index smaller than zero or greater than
or equal to the number of objects in the list.
:param: object An object.
:param: index The index at which to insert the object.
*/
public func insert(object: T, atIndex index: Int) {
throwForNegativeIndex(index)
_rlmArray.insertObject(unsafeBitCast(object, RLMObject.self), atIndex: UInt(index))
}
/**
Removes the object at the given index from the list. Does not remove the object from the Realm.
:warning: This method can only be called during a write transaction.
:warning: Throws an exception when called with an index smaller than zero or greater than
or equal to the number of objects in the list.
:param: index The index at which to remove the object.
*/
public func removeAtIndex(index: Int) {
throwForNegativeIndex(index)
_rlmArray.removeObjectAtIndex(UInt(index))
}
/**
Removes the last object in the list. Does not remove the object from the Realm.
:warning: This method can only be called during a write transaction.
*/
public func removeLast() {
_rlmArray.removeLastObject()
}
/**
Removes all objects from the List. Does not remove the objects from the Realm.
:warning: This method can only be called during a write transaction.
*/
public func removeAll() {
_rlmArray.removeAllObjects()
}
/**
Replaces an object at the given index with a new object.
:warning: This method can only be called during a write transaction.
:warning: Throws an exception when called with an index smaller than zero or greater than
or equal to the number of objects in the list.
:param: index The list index of the object to be replaced.
:param: object An object to replace at the specified index.
*/
public func replace(index: Int, object: T) {
throwForNegativeIndex(index)
_rlmArray.replaceObjectAtIndex(UInt(index), withObject: unsafeBitCast(object, RLMObject.self))
}
}
extension List: ExtensibleCollectionType {
// MARK: Sequence Support
/// Returns a `GeneratorOf<T>` that yields successive elements in the list.
public func generate() -> RLMGenerator<T> {
return RLMGenerator(collection: _rlmArray)
}
// MARK: ExtensibleCollection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor().
public var endIndex: Int { return count }
/// This method has no effect.
public func reserveCapacity(capacity: Int) { }
}
| mit | 93b52e0d36a148734da0957f5ed35e02 | 33.801829 | 139 | 0.668068 | 4.636474 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/Manage/ReaderTagsTableViewController.swift | 2 | 825 | class ReaderTagsTableViewController: UIViewController {
private let style: UITableView.Style
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: style)
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
private var viewModel: ReaderTagsTableViewModel?
init(style: UITableView.Style) {
self.style = style
super.init(nibName: nil, bundle: nil)
viewModel = ReaderTagsTableViewModel(tableView: tableView, presenting: self)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
view.pinSubviewToAllEdges(tableView)
}
}
| gpl-2.0 | c5d3ee768dce96211454d32c3e253bcc | 26.5 | 84 | 0.68 | 5.221519 | false | false | false | false |
mitchins/MCSwift | MCSwiftTests/DateTime_Tests.swift | 1 | 6163 | //
// DateTime_Tests.swift
// MitchellCurrie.Swift
//
// Created by Mitchell Currie on 8/10/2015.
//
//
import XCTest
import MCSwift
class DateTime_Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
/**
Test NSTimeInterval functions
**/
func testTimeIntervalMinutes() {
//The zero case
var timeInterval = NSTimeInterval(0)
var expected = Int64(0)
XCTAssert(timeInterval.minutes == expected)
//The "do not round up" case
timeInterval = NSTimeInterval(59)
expected = Int64(0)
XCTAssert(timeInterval.minutes == expected)
//The simple case of a few minutes and some change case
timeInterval = NSTimeInterval(181) //3 minutes, 1 second
expected = Int64(3)
XCTAssert(timeInterval.minutes == expected)
//Make sure it doesn't do anything funny if there are hours involved too
timeInterval = NSTimeInterval(3601) //1 hour, 1 second
expected = Int64(60)
XCTAssert(timeInterval.minutes == expected)
//Pick a largish kind of number in the negative to make sure that doesn't mess it up
timeInterval = NSTimeInterval(-3660) //negative 61 minutes
expected = Int64(-61)
XCTAssert(timeInterval.minutes == expected)
}
func testTimeIntervalHours() {
//The zero case
var timeInterval = NSTimeInterval(0)
var expected = Int64(0)
XCTAssert(timeInterval.hours == expected)
//The "do not round up" case
timeInterval = NSTimeInterval(3599)
expected = Int64(0)
XCTAssert(timeInterval.hours == expected)
//The simple case of a few hours and some change case
timeInterval = NSTimeInterval(10801) // 3 hours, 1 second
expected = Int64(3)
XCTAssert(timeInterval.hours == expected)
//Make sure it doesn't do anything funny if there are days involved too
timeInterval = NSTimeInterval(86401) //1 day, 1 second
expected = Int64(24)
XCTAssert(timeInterval.hours == expected)
//Pick a largish kind of number in the negative to make sure that doesn't mess it up
timeInterval = NSTimeInterval(-172801) //negative 2 days, 1 second
expected = Int64(-48)
XCTAssert(timeInterval.hours == expected)
}
func testTimeIntervalDays() {
//The zero case
var timeInterval = NSTimeInterval(0)
var expected = Int64(0)
XCTAssert(timeInterval.days == expected)
//The "do not round up" case
timeInterval = NSTimeInterval(86399)
expected = Int64(0)
XCTAssert(timeInterval.days == expected)
//A whole day, and a numbetr of seconds
timeInterval = NSTimeInterval(86401) //1 day, 1 second
expected = Int64(1)
XCTAssert(timeInterval.days == expected)
//Pick a largish kind of number in the negative to make sure that doesn't mess it up
timeInterval = NSTimeInterval(-1728001) //negative 20 days, 1 second
expected = Int64(-20)
XCTAssert(timeInterval.days == expected)
}
/**
Test DateTime functions
**/
func testAddDays() {
let dateFormatter = NSDateFormatter(dateFormat: "YYYY-MM-dd")
//Test the trvial case
var originalDate = NSDate()
var expectedDate = originalDate
var outputDate = originalDate.addDays(0)
XCTAssert(outputDate.isEqualToDate(expectedDate))
//Test the case of one day to the next, with roll over of month
originalDate = dateFormatter.dateFromString("2015-01-31")!
expectedDate = dateFormatter.dateFromString("2015-02-01")!
outputDate = originalDate.addDays(1)
XCTAssert(outputDate.isEqualToDate(expectedDate))
//Obligatory leap year test
originalDate = dateFormatter.dateFromString("2016-02-28")!
expectedDate = dateFormatter.dateFromString("2016-03-01")!
outputDate = originalDate.addDays(2)
XCTAssert(outputDate.isEqualToDate(expectedDate))
//Test the case of going backwards, from one year to the previous, over multiple months
originalDate = dateFormatter.dateFromString("2015-01-02")!
expectedDate = dateFormatter.dateFromString("2014-11-14")!
outputDate = originalDate.addDays(-49)
XCTAssert(outputDate.isEqualToDate(expectedDate))
}
func testDaysSinceEpoch() {
let secondsFromGMT = NSTimeInterval(NSTimeZone.systemTimeZone().secondsFromGMT)
//Test the trvial case
var date = NSDate(timeIntervalSince1970: secondsFromGMT)
var expected = Int64(0)
XCTAssert(date.daysSinceEpoch == expected )
//Test a day in the future
date = NSDate(timeIntervalSince1970: secondsFromGMT + (24 * 60 * 60) )
expected = Int64(1)
XCTAssert(date.daysSinceEpoch == expected )
//Test a day in the past
date = NSDate(timeIntervalSince1970: -secondsFromGMT + (-24 * 60 * 60) )
expected = Int64(-1)
XCTAssert(date.daysSinceEpoch == expected )
//Test a week in the past
date = NSDate(timeIntervalSince1970: -secondsFromGMT + (-7 * 24 * 60 * 60) )
expected = Int64(-7)
XCTAssert(date.daysSinceEpoch == expected )
}
/**
Test NSDateFormatter conveniences
**/
func testNSDateFormatterConveniences() {
// convenience init(dateFormat: String, isRelative: Bool = false) {
// convenience init(dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle, isRelative: Bool = false) {
XCTFail("Not Implemented")
}
}
| mit | f1c665c76afc52e6cf536810c0693131 | 35.040936 | 128 | 0.625669 | 4.938301 | false | true | false | false |
jingyu982887078/daily-of-programmer | WeiBo/WeiBo/Classes/View/VisitorView/WBVisitorView.swift | 1 | 4242 | //
// WBVisitorView.swift
// WeiBo
//
// Created by wangjingyu on 2017/5/5.
// Copyright © 2017年 wangjingyu. All rights reserved.
//
import UIKit
/// 访客视图
class WBVisitorView: UIView {
let margin:CGFloat = 16
/// 注册按钮
lazy var registerButton:UIButton = UIButton.cz_textButton(
"注册",
fontSize: 14,
normalColor: UIColor.orange,
highlightedColor: UIColor.black,
backgroundImageName: "common_button_white_disable")
/// 登录按钮
lazy var loginButton: UIButton = UIButton.cz_textButton(
"登录",
fontSize: 14,
normalColor: UIColor.darkGray,
highlightedColor: UIColor.black,
backgroundImageName: "common_button_white_disable")
//1.先写一个构造函数
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 设置访客视图信息
func visitorInfo(dict:[String:String]?) {
guard let imageName = dict?["imageName"],
let message = dict?["message"] else {
return
}
tipLabel.text = message
tipLabel.textAlignment = .center
if imageName == "" {
setupAnimation()
return
}
iconView.image = UIImage(named: imageName)
houseIconView.isHidden = true
maskIconView.isHidden = true
}
//动画
func setupAnimation() {
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.toValue = 2 * Double.pi
animation.repeatCount = MAXFLOAT
animation.duration = 15
animation.isRemovedOnCompletion = false
iconView.layer .add(animation, forKey: nil)
}
//创建私有的方法
/// 图标图像
fileprivate lazy var iconView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
/// 遮罩图像
fileprivate lazy var maskIconView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
/// 小房子
fileprivate lazy var houseIconView = UIImageView(image: UIImage(named:"visitordiscover_feed_image_house" ))
/// 提示标签
fileprivate lazy var tipLabel: UILabel = UILabel.cz_label(
withText: "关注一些人,回这里看看有什么惊喜关注一些人,回这里看看有什么惊喜",
fontSize: 14,
color: UIColor.darkGray)
}
// MARK: - 设置界面
extension WBVisitorView {
func setupUI() {
backgroundColor = UIColor.cz_color(withHex: 0xEDEDED)
//1.添加控件
addSubview(iconView)
addSubview(maskIconView)
addSubview(houseIconView)
addSubview(tipLabel)
addSubview(registerButton)
addSubview(loginButton)
//2.设置布局
iconView.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.centerY.equalTo(self).offset(-60)
}
houseIconView.snp.makeConstraints { (make) in
make.center.equalTo(self)
}
tipLabel.snp.makeConstraints { (make) in
make.top.equalTo(houseIconView.snp.bottom).offset(margin)
make.centerX.equalTo(self)
make.width.equalTo(236)
}
registerButton.snp.makeConstraints { (make) in
make.top.equalTo(tipLabel.snp.bottom).offset(margin)
make.left.equalTo(tipLabel)
make.width.equalTo(100)
make.height.equalTo(35)
}
loginButton.snp.makeConstraints { (make) in
make.top.equalTo(tipLabel.snp.bottom).offset(margin)
make.right.equalTo(tipLabel)
make.width.equalTo(100)
make.height.equalTo(35)
}
maskIconView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(self)
make.bottom.equalTo(registerButton.snp.top)
}
}
}
| mit | 46b6890a4ae6094d84e3cf9e7b79874c | 26.290541 | 113 | 0.578856 | 4.751765 | false | false | false | false |
FlyKite/DYJW-Swift | DYJW/Common/View/DrawerCell.swift | 1 | 982 | //
// DrawerCell.swift
// DYJW
//
// Created by 风筝 on 2017/12/4.
// Copyright © 2017年 Doge Studio. All rights reserved.
//
import UIKit
class DrawerCell: UITableViewCell {
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var iconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.createRippleView(UIColor.lightBlue50, alpha: 0.5)
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 46))
view.backgroundColor = UIColor.lightBlue100
self.selectedBackgroundView = view
}
func set(title: String, icon: UIImage) {
self.titleLabel.text = title
self.iconImageView.image = icon
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| gpl-3.0 | 2c32f18fde06c00e15a5bec507428a77 | 25.351351 | 76 | 0.646154 | 4.295154 | false | false | false | false |
Peekazoo/Peekazoo-iOS | Peekazoo/PeekazooTests/Test Doubles/StubHomepageInterfaceViewModel.swift | 1 | 819 | //
// StubHomepageInterfaceViewModel.swift
// Peekazoo
//
// Created by Thomas Sherwood on 15/05/2017.
// Copyright © 2017 Peekazoo. All rights reserved.
//
import Peekazoo
struct StubHomepageInterfaceViewModel: HomepageInterfaceViewModel {
init(items: [StubHomepageInterfaceItemViewModel]) {
self.items = items
}
var items: [StubHomepageInterfaceItemViewModel]
var numberOfItems: Int { return items.count }
func item(at index: Int) -> HomepageInterfaceItemViewModel {
return items[index]
}
}
struct StubHomepageInterfaceItemViewModel: HomepageInterfaceItemViewModel {
var title: String = ""
var creationDate: String = ""
init(title: String = "", creationDate: String = "") {
self.title = title
self.creationDate = creationDate
}
}
| apache-2.0 | 8f86057b5f832b1ddc913eecdf3ce0fb | 21.722222 | 75 | 0.694377 | 4.647727 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Filters.playground/Pages/Modal Resonance Filter Operation.xcplaygroundpage/Contents.swift | 2 | 652 | //: ## Modal Resonance Filter Operation
//:
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
let frequency = AKOperation.sineWave(frequency: 0.3).scale(minimum: 200, maximum: 1200)
let effect = AKOperationEffect(player) { player, _ in
return player.modalResonanceFilter(frequency: frequency,
qualityFactor: 50) * 0.2
}
AudioKit.output = effect
AudioKit.start()
player.play()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true | mit | 44687bc4176a4d6a3c118e638a30878e | 27.391304 | 87 | 0.699387 | 4.624113 | false | false | false | false |
garricn/GGNLocationPicker | Example/GGNLocationPicker/AppDelegate.swift | 1 | 1308 | //
// AppDelegate.swift
// GGNLocationPicker
//
// Created by Garric Nahapetian on 09/21/2016.
// Copyright (c) 2016 Garric Nahapetian. All rights reserved.
//
import UIKit
import MapKit
import GGNLocationPicker
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let coordinate = CLLocationCoordinate2D(latitude: 34.0, longitude: -118.24)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "Hello, World!"
let locationPicker = LocationPickerVC(with: annotation)
locationPicker.pickerDelegate = self
locationPicker.didPick = { annotation in
print(annotation)
}
let navigationController = UINavigationController(rootViewController: locationPicker)
let frame = UIScreen.main.bounds
window = UIWindow(frame: frame)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
return true
}
}
extension AppDelegate: LocationPickerDelegate {
func didPick(_ annotation: MKAnnotation) {
print(annotation)
}
}
| mit | 50a64bca462e0b6ebb4abd5104f0806d | 29.418605 | 144 | 0.707951 | 5.253012 | false | false | false | false |
necrowman/CRLAlamofireFuture | Examples/SimpleTvOSCarthage/Carthage/Checkouts/UV/UV/Loop.swift | 111 | 3875 | //===--- Loop.swift -------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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 CUV
import Boilerplate
public typealias uv_loop_p = UnsafeMutablePointer<uv_loop_t>
public class Loop {
private let exclusive:Bool
public let loop:uv_loop_p
public init(loop:uv_loop_p) {
self.loop = loop
exclusive = false
}
public init() throws {
loop = uv_loop_p(allocatingCapacity: 1)
exclusive = true
try Error.handle {
uv_loop_init(loop)
}
}
deinit {
if exclusive {
defer {
loop.deinitialize(count: 1)
loop.deallocateCapacity(1)
}
do {
try close()
} catch let e as Error {
print(e.description)
} catch {
print("Unknown error occured while destroying the loop")
}
}
}
public static func defaultLoop() -> Loop {
return Loop(loop: uv_default_loop())
}
/*public func configure(option:uv_loop_option, _ args: CVarArgType...) {
try Error.handle {
uv_loop_configure(loop, option, getVaList(args))
}
}*/
private func close() throws {
try Error.handle {
uv_loop_close(loop)
}
}
/// returns true if no more handles are there
public func run(mode:uv_run_mode = UV_RUN_DEFAULT) -> Bool {
return uv_run(loop, mode) == 0
}
public var alive:Bool {
get {
return uv_loop_alive(loop) != 0
}
}
public func stop() {
uv_stop(loop)
}
private static func size() -> UInt64 {
return UInt64(uv_loop_size())
}
public var backendFd:Int32 {
get {
return uv_backend_fd(loop)
}
}
//in millisec
//wierd thing, doc says it should return -1 on no timeout, in fact - 0. Leaving as is for now. Subject to investigate
public var backendTimeout:Int32? {
get {
let timeout = uv_backend_timeout(loop)
return timeout == -1 ? nil : timeout
}
}
public var now:UInt64 {
get {
return uv_now(loop)
}
}
public func updateTime() {
uv_update_time(loop)
}
public func walk(f:LoopWalkCallback) {
let container = AnyContainer(f)
let arg = UnsafeMutablePointer<Void>(OpaquePointer(bitPattern:Unmanaged.passUnretained(container)))
uv_walk(loop, loop_walker, arg)
}
public var handles:Array<HandleType> {
get {
return Array(enumerator: walk)
}
}
}
public typealias LoopWalkCallback = (HandleType)->Void
private func loop_walker(handle:uv_handle_p, arg:UnsafeMutablePointer<Void>) {
let container = Unmanaged<AnyContainer<LoopWalkCallback>>.fromOpaque(OpaquePointer(arg)).takeUnretainedValue()
let callback = container.content
let handle:Handle<uv_handle_p> = Handle.fromHandle(handle)
callback(handle)
}
extension Loop : Equatable {
}
public func ==(lhs: Loop, rhs: Loop) -> Bool {
return lhs.loop == rhs.loop
} | mit | 854b53d44b44bd70b3309e5180529387 | 26.295775 | 121 | 0.566452 | 4.353933 | false | false | false | false |
Tyrant2013/LeetCodePractice | LeetCodePractice/Easy/13_Roman_To_Int.swift | 1 | 1015 | //
// Roman_To_Int.swift
// LeetCodePractice
//
// Created by 庄晓伟 on 2018/2/8.
// Copyright © 2018年 Zhuang Xiaowei. All rights reserved.
//
import UIKit
class Roman_To_Int: Solution {
override func ExampleTest() -> Void {
}
func romanToInt(_ s: String) -> Int {
let roman = ["I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000]
var num = 0
var last = ""
s.forEach { ch in
let cur = String(ch)
num += roman[cur]!
if last != "" {
if last == "I" && (cur == "V" || cur == "X") {
num -= roman[last]! * 2
}
else if last == "X" && (cur == "L" || cur == "C") {
num -= roman[last]! * 2
}
else if last == "C" && (cur == "D" || cur == "M") {
num -= roman[last]! * 2
}
}
last = cur
}
return num
}
}
| mit | 761df7880233574b2ff8debacf0722d9 | 25.473684 | 92 | 0.373757 | 3.493056 | false | false | false | false |
GirAppe/Blackhole | Example/Tests/SendingTestCase.swift | 1 | 1988 | import UIKit
import XCTest
import Blackhole
class SendingTestCase: BlackholeTestCase {
// MARK: - Basic Tests
func testSimpleSendingSuccess() {
let identifier = "someIdentifier"
let message: BlackholeMessage = ["someKey":"stringValue"]
let expectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
self.session.emit(TestSession.EmitResult(success: true))
do {
XCTAssert(self.session === emitter.session)
try emitter.sendMessage(message, withIdentifier: identifier, success: {
expectation.fulfill()
}, failure: { error in
XCTAssert(false, "Error sending: \(error)")
})
}
catch {
XCTAssert(false, "Error sending: \(error)")
}
self.waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTAssert(false, "Error sending: \(error)")
}
}
}
func testSimpleSendingFailure() {
let identifier = "someIdentifier"
let message: BlackholeMessage = ["someKey":"stringValue"]
let expectation: XCTestExpectation = self.expectation(description: "Expect message to be delivered")
self.session.emit(TestSession.EmitResult(success: false))
do {
XCTAssert(self.session === emitter.session)
try emitter.sendMessage(message, withIdentifier: identifier, success: {
XCTAssert(false, "Should not be there")
}, failure: { error in
expectation.fulfill()
})
}
catch {
XCTAssert(false, "Error sending: \(error)")
}
self.waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTAssert(false, "Error sending: \(error)")
}
}
}
}
| mit | dae0ec35d31c7cf4b7285b670e58968e | 31.590164 | 108 | 0.554829 | 5.329759 | false | true | false | false |
lucaswoj/sugar.swift | units/SugarUnitType.swift | 1 | 2382 | //
// SugarUnitType.swift
// Sugar
//
// Created by Lucas Wojciechowski on 10/21/14.
// Copyright (c) 2014 Scree Apps. All rights reserved.
//
import Foundation
protocol SugarUnitType {
class var name:String { get }
class var units:[SugarUnit<Self>] { get }
}
let distanceUnits = [
SugarUnit<SugarDistance>(name: "meters", abbreviation: "m"),
SugarUnit<SugarDistance>(name: "feet", abbreviation: "ft", multiplier: 3.28084)
]
final class SugarDistance:SugarUnitType {
class var name:String { return "distance" }
class var units:[SugarUnit<SugarDistance>] { return distanceUnits }
}
let pressureUnits = [
SugarUnit<SugarPressure>(name: "mmHg", abbreviation: "mmHg", multiplier: 7.50061683),
SugarUnit<SugarPressure>(name: "kilopascals", abbreviation: "kPa"),
SugarUnit<SugarPressure>(name: "hectopascals", abbreviation: "hPa", multiplier: 10),
SugarUnit<SugarPressure>(name: "atmospheres", abbreviation: "atm", multiplier: 0.00986923267)
]
final class SugarPressure:SugarUnitType {
class var name:String { return "pressure" }
class var units:[SugarUnit<SugarPressure>] { return pressureUnits }
}
let temperatureUnits = [
SugarUnit<SugarTemperature>(name: "kelvin", abbreviation: "K", offset: 273.15),
SugarUnit<SugarTemperature>(name: "celcius", abbreviation: "C"),
SugarUnit<SugarTemperature>(name: "fahrenheit", abbreviation: "F", multiplier: 9.0/5.0, offset: 32)
]
final class SugarTemperature:SugarUnitType {
class var name:String { return "temperature" }
class var units:[SugarUnit<SugarTemperature>] { return temperatureUnits }
}
let timeUnits = [
SugarUnit<SugarTime>(name: "seconds", abbreviation: "s"),
SugarUnit<SugarTime>(name: "minutes", abbreviation: "m", multiplier: 1/60),
SugarUnit<SugarTime>(name: "hours", abbreviation: "h", multiplier: 1/60/60)
]
final class SugarTime:SugarUnitType {
class var name:String { return "time" }
class var units:[SugarUnit<SugarTime>] { return timeUnits }
}
let percentUnits = [
SugarUnit<SugarPercent>(name: "percent", abbreviation: "%", multiplier: 100),
SugarUnit<SugarPercent>(name: "decimal", abbreviation: "")
]
final class SugarPercent:SugarUnitType {
class var name:String { return "percent" }
class var units:[SugarUnit<SugarPercent>] { return percentUnits }
} | mit | 2213c61f0544ad3d30b935508e0a07b6 | 36.234375 | 107 | 0.697313 | 3.786963 | false | false | false | false |
huonw/swift | test/Constraints/protocols.swift | 12 | 11238 | // RUN: %target-typecheck-verify-swift
protocol Fooable { func foo() }
protocol Barable { func bar() }
extension Int : Fooable, Barable {
func foo() {}
func bar() {}
}
extension Float32 : Barable {
func bar() {}
}
func f0(_: Barable) {}
func f1(_ x: Fooable & Barable) {}
func f2(_: Float) {}
let nilFunc: Optional<(Barable) -> ()> = nil
func g(_: (Barable & Fooable) -> ()) {}
protocol Classable : AnyObject {}
class SomeArbitraryClass {}
func fc0(_: Classable) {}
func fc1(_: Fooable & Classable) {}
func fc2(_: AnyObject) {}
func fc3(_: SomeArbitraryClass) {}
func gc(_: (Classable & Fooable) -> ()) {}
var i : Int
var f : Float
var b : Barable
//===----------------------------------------------------------------------===//
// Conversion to and among existential types
//===----------------------------------------------------------------------===//
f0(i)
f0(f)
f0(b)
f1(i)
f1(f) // expected-error{{argument type 'Float' does not conform to expected type 'Barable & Fooable'}}
f1(b) // expected-error{{argument type 'Barable' does not conform to expected type 'Barable & Fooable'}}
//===----------------------------------------------------------------------===//
// Subtyping
//===----------------------------------------------------------------------===//
g(f0) // okay (subtype)
g(f1) // okay (exact match)
g(f2) // expected-error{{cannot convert value of type '(Float) -> ()' to expected argument type '(Barable & Fooable) -> ()'}}
// FIXME: Workaround for ?? not playing nice with function types.
infix operator ??*
func ??*<T>(lhs: T?, rhs: T) -> T { return lhs ?? rhs }
g(nilFunc ??* f0)
gc(fc0) // okay
gc(fc1) // okay
gc(fc2) // okay
gc(fc3) // expected-error{{cannot convert value of type '(SomeArbitraryClass) -> ()' to expected argument type '(Classable & Fooable) -> ()'}}
// rdar://problem/19600325
func getAnyObject() -> AnyObject? {
return SomeArbitraryClass()
}
func castToClass(_ object: Any) -> SomeArbitraryClass? {
return object as? SomeArbitraryClass
}
_ = getAnyObject().map(castToClass)
_ = { (_: Any) -> Void in
return
} as ((Int) -> Void)
let _: (Int) -> Void = {
(_: Any) -> Void in
return
}
let _: () -> Any = {
() -> Int in
return 0
}
let _: () -> Int = {
() -> String in // expected-error {{declared closure result 'String' is incompatible with contextual type 'Int'}}
return ""
}
//===----------------------------------------------------------------------===//
// Members of archetypes
//===----------------------------------------------------------------------===//
func id<T>(_ t: T) -> T { return t }
protocol Initable {
init()
}
protocol P : Initable {
func bar(_ x: Int)
mutating func mut(_ x: Int)
static func tum()
}
protocol ClassP : class {
func bas(_ x: Int)
func quux(_ x: Int)
}
class ClassC : ClassP {
func bas(_ x: Int) {}
}
extension ClassP {
func quux(_ x: Int) {}
func bing(_ x: Int) {}
}
func generic<T: P>(_ t: T) {
var t = t
// Instance member of archetype
let _: (Int) -> () = id(t.bar)
let _: () = id(t.bar(0))
// Static member of archetype metatype
let _: () -> () = id(T.tum)
// Instance member of archetype metatype
let _: (T) -> (Int) -> () = id(T.bar)
let _: (Int) -> () = id(T.bar(t))
_ = t.mut // expected-error{{partial application of 'mutating' method is not allowed}}
_ = t.tum // expected-error{{static member 'tum' cannot be used on instance of type 'T'}}
}
func genericClassP<T: ClassP>(_ t: T) {
// Instance member of archetype)
let _: (Int) -> () = id(t.bas)
let _: () = id(t.bas(0))
// Instance member of archetype metatype)
let _: (T) -> (Int) -> () = id(T.bas)
let _: (Int) -> () = id(T.bas(t))
let _: () = id(T.bas(t)(1))
}
func genericClassC<C : ClassC>(_ c: C) {
// Make sure that we can find members of protocol extensions
// on a class-bound archetype
let _ = c.bas(123)
let _ = c.quux(123)
let _ = c.bing(123)
}
//===----------------------------------------------------------------------===//
// Members of existentials
//===----------------------------------------------------------------------===//
func existential(_ p: P) {
var p = p
// Fully applied mutating method
p.mut(1)
_ = p.mut // expected-error{{partial application of 'mutating' method is not allowed}}
// Instance member of existential)
let _: (Int) -> () = id(p.bar)
let _: () = id(p.bar(0))
// Static member of existential metatype)
let _: () -> () = id(type(of: p).tum)
}
func staticExistential(_ p: P.Type, pp: P.Protocol) {
let _ = p() // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
let _ = p().bar // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
let _ = p().bar(1) // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
let ppp: P = p.init()
_ = pp() // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = pp().bar // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = pp().bar(2) // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = pp.init() // expected-error{{protocol type 'P' cannot be instantiated}}
_ = pp.init().bar // expected-error{{protocol type 'P' cannot be instantiated}}
_ = pp.init().bar(3) // expected-error{{protocol type 'P' cannot be instantiated}}
_ = P() // expected-error{{protocol type 'P' cannot be instantiated}}
_ = P().bar // expected-error{{protocol type 'P' cannot be instantiated}}
_ = P().bar(4) // expected-error{{protocol type 'P' cannot be instantiated}}
// Instance member of metatype
let _: (P) -> (Int) -> () = P.bar
let _: (Int) -> () = P.bar(ppp)
P.bar(ppp)(5)
// Instance member of metatype value
let _: (P) -> (Int) -> () = pp.bar
let _: (Int) -> () = pp.bar(ppp)
pp.bar(ppp)(5)
// Static member of existential metatype value
let _: () -> () = p.tum
// Instance member of existential metatype -- not allowed
_ = p.bar // expected-error{{instance member 'bar' cannot be used on type 'P'}}
_ = p.mut // expected-error{{instance member 'mut' cannot be used on type 'P'}}
// Static member of metatype -- not allowed
_ = pp.tum // expected-error{{static member 'tum' cannot be used on protocol metatype 'P.Protocol'}}
_ = P.tum // expected-error{{static member 'tum' cannot be used on protocol metatype 'P.Protocol'}}
}
protocol StaticP {
static func foo(a: Int)
}
extension StaticP {
func bar() {
_ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype 'StaticP.Protocol'}} {{9-16=Self}}
func nested() {
_ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype 'StaticP.Protocol'}} {{11-18=Self}}
}
}
}
func existentialClassP(_ p: ClassP) {
// Instance member of existential)
let _: (Int) -> () = id(p.bas)
let _: () = id(p.bas(0))
// Instance member of existential metatype)
let _: (ClassP) -> (Int) -> () = id(ClassP.bas)
let _: (Int) -> () = id(ClassP.bas(p))
let _: () = id(ClassP.bas(p)(1))
}
// Partial application of curried protocol methods
protocol Scalar {}
protocol Vector {
func scale(_ c: Scalar) -> Self
}
protocol Functional {
func apply(_ v: Vector) -> Scalar
}
protocol Coalgebra {
func coproduct(_ f: Functional) -> (_ v1: Vector, _ v2: Vector) -> Scalar
}
// Make sure existential is closed early when we partially apply
func wrap<T>(_ t: T) -> T {
return t
}
func exercise(_ c: Coalgebra, f: Functional, v: Vector) {
let _: (Vector, Vector) -> Scalar = wrap(c.coproduct(f))
let _: (Scalar) -> Vector = v.scale
}
// Make sure existential isn't closed too late
protocol Copyable {
func copy() -> Self
}
func copyTwice(_ c: Copyable) -> Copyable {
return c.copy().copy()
}
//===----------------------------------------------------------------------===//
// Dynamic self
//===----------------------------------------------------------------------===//
protocol Clonable {
func maybeClone() -> Self?
func doubleMaybeClone() -> Self??
func subdivideClone() -> (Self, Self)
func metatypeOfClone() -> Self.Type
func goodClonerFn() -> (() -> Self)
}
extension Clonable {
func badClonerFn() -> ((Self) -> Self) { }
func veryBadClonerFn() -> ((inout Self) -> ()) { }
func extClone() -> Self { }
func extMaybeClone(_ b: Bool) -> Self? { }
func extProbablyClone(_ b: Bool) -> Self! { }
static func returnSelfStatic() -> Self { }
static func returnSelfOptionalStatic(_ b: Bool) -> Self? { }
static func returnSelfIUOStatic(_ b: Bool) -> Self! { }
}
func testClonableArchetype<T : Clonable>(_ t: T) {
// Instance member of extension returning Self)
let _: (T) -> () -> T = id(T.extClone)
let _: () -> T = id(T.extClone(t))
let _: T = id(T.extClone(t)())
let _: () -> T = id(t.extClone)
let _: T = id(t.extClone())
let _: (T) -> (Bool) -> T? = id(T.extMaybeClone)
let _: (Bool) -> T? = id(T.extMaybeClone(t))
let _: T? = id(T.extMaybeClone(t)(false))
let _: (Bool) -> T? = id(t.extMaybeClone)
let _: T? = id(t.extMaybeClone(true))
let _: (T) -> (Bool) -> T? = id(T.extProbablyClone as (T) -> (Bool) -> T?)
let _: (Bool) -> T? = id(T.extProbablyClone(t) as (Bool) -> T?)
let _: T! = id(T.extProbablyClone(t)(true))
let _: (Bool) -> T? = id(t.extProbablyClone as (Bool) -> T?)
let _: T! = id(t.extProbablyClone(true))
// Static member of extension returning Self)
let _: () -> T = id(T.returnSelfStatic)
let _: T = id(T.returnSelfStatic())
let _: (Bool) -> T? = id(T.returnSelfOptionalStatic)
let _: T? = id(T.returnSelfOptionalStatic(false))
let _: (Bool) -> T? = id(T.returnSelfIUOStatic as (Bool) -> T?)
let _: T! = id(T.returnSelfIUOStatic(true))
}
func testClonableExistential(_ v: Clonable, _ vv: Clonable.Type) {
let _: Clonable? = v.maybeClone()
let _: Clonable?? = v.doubleMaybeClone()
// FIXME: Tuple-to-tuple conversions are not implemented
let _: (Clonable, Clonable) = v.subdivideClone()
// expected-error@-1{{cannot express tuple conversion '(Clonable, Clonable)' to '(Clonable, Clonable)'}}
let _: Clonable.Type = v.metatypeOfClone()
let _: () -> Clonable = v.goodClonerFn()
// Instance member of extension returning Self
let _: () -> Clonable = id(v.extClone)
let _: Clonable = id(v.extClone())
let _: Clonable? = id(v.extMaybeClone(true))
let _: Clonable! = id(v.extProbablyClone(true))
// Static member of extension returning Self)
let _: () -> Clonable = id(vv.returnSelfStatic)
let _: Clonable = id(vv.returnSelfStatic())
let _: (Bool) -> Clonable? = id(vv.returnSelfOptionalStatic)
let _: Clonable? = id(vv.returnSelfOptionalStatic(false))
let _: (Bool) -> Clonable? = id(vv.returnSelfIUOStatic as (Bool) -> Clonable?)
let _: Clonable! = id(vv.returnSelfIUOStatic(true))
let _ = v.badClonerFn() // expected-error {{member 'badClonerFn' cannot be used on value of protocol type 'Clonable'; use a generic constraint instead}}
let _ = v.veryBadClonerFn() // expected-error {{member 'veryBadClonerFn' cannot be used on value of protocol type 'Clonable'; use a generic constraint instead}}
}
| apache-2.0 | 8c5e664517753cc294f38a9535295184 | 29.621253 | 162 | 0.578751 | 3.610022 | false | false | false | false |
nnsnodnb/nowplaying-ios | NowPlaying/Sources/ViewControllers/Play/PlayViewController.swift | 1 | 4861 | //
// PlayViewController.swift
// NowPlaying
//
// Created by Yuya Oka on 2021/12/31.
//
import RxSwift
import ScrollFlowLabel
import UIKit
final class PlayViewController: UIViewController {
// MARK: - Dependency
typealias Dependency = PlayViewModelType
// MARK: - Properties
private let viewModel: PlayViewModelType
private let disposeBag = DisposeBag()
@IBOutlet private var coverImageView: UIImageView! {
didSet {
coverImageView.layer.shadowColor = Asset.Colors.shadowMain.color.cgColor
coverImageView.layer.shadowOffset = .zero
coverImageView.layer.shadowRadius = 20
coverImageView.layer.shadowOpacity = 0.5
}
}
@IBOutlet private var songNameLabel: ScrollFlowLabel! {
didSet {
songNameLabel.textColor = .label
songNameLabel.textAlignment = .center
songNameLabel.font = .boldSystemFont(ofSize: 20)
songNameLabel.pauseInterval = 2
songNameLabel.scrollDirection = .left
songNameLabel.observeApplicationState()
}
}
@IBOutlet private var artistNameLabel: ScrollFlowLabel! {
didSet {
artistNameLabel.textColor = .label
artistNameLabel.textAlignment = .center
artistNameLabel.textAlignment = .center
artistNameLabel.font = .systemFont(ofSize: 16)
artistNameLabel.pauseInterval = 2
artistNameLabel.scrollDirection = .left
artistNameLabel.observeApplicationState()
}
}
@IBOutlet private var backButton: UIButton!
@IBOutlet private var playButton: UIButton!
@IBOutlet private var forwardButton: UIButton!
@IBOutlet private var gearButton: UIButton!
@IBOutlet private var mastodonButton: UIButton! {
didSet {
mastodonButton.imageView?.contentMode = .scaleAspectFit
mastodonButton.contentHorizontalAlignment = .fill
mastodonButton.contentVerticalAlignment = .fill
}
}
@IBOutlet private var twitterButton: UIButton! {
didSet {
twitterButton.imageView?.contentMode = .scaleAspectFit
twitterButton.contentHorizontalAlignment = .fill
twitterButton.contentVerticalAlignment = .fill
}
}
// MARK: - Initialize
init(dependency: Dependency) {
self.viewModel = dependency
super.init(nibName: Self.className, bundle: .main)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
bind(to: viewModel)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard previousTraitCollection?.userInterfaceStyle != traitCollection.userInterfaceStyle else { return }
coverImageView.layer.shadowColor = Asset.Colors.shadowMain.color.cgColor
}
}
// MARK: - Private method
private extension PlayViewController {
func bind(to viewModel: PlayViewModelType) {
// カバー写真
viewModel.outputs.artworkImage.drive(coverImageView.rx.image).disposed(by: disposeBag)
viewModel.outputs.artworkScale
.drive(with: self, onNext: { strongSelf, scale in
UIView.animate(withDuration: 0.3, delay: 0) { [weak strongSelf] in
strongSelf?.coverImageView.transform = .init(scaleX: scale, y: scale)
}
})
.disposed(by: disposeBag)
// 曲名
viewModel.outputs.songName.drive(songNameLabel.rx.text).disposed(by: disposeBag)
// アーティスト名
viewModel.outputs.artistName.drive(artistNameLabel.rx.text).disposed(by: disposeBag)
// 戻るボタン
backButton.rx.tap.asSignal().emit(to: viewModel.inputs.back).disposed(by: disposeBag)
// 再生ボタン
playButton.rx.tap.asSignal().emit(to: viewModel.inputs.playPause).disposed(by: disposeBag)
viewModel.outputs.playPauseImage.drive(playButton.rx.image()).disposed(by: disposeBag)
// 次へボタン
forwardButton.rx.tap.asSignal().emit(to: viewModel.inputs.forward).disposed(by: disposeBag)
// 設定ボタン
gearButton.rx.tap.asSignal().emit(to: viewModel.inputs.setting).disposed(by: disposeBag)
// Mastodonボタン
mastodonButton.rx.tap.asSignal().emit(to: viewModel.inputs.mastodon).disposed(by: disposeBag)
// Twitterボタン
twitterButton.rx.tap.asSignal().emit(to: viewModel.inputs.twitter).disposed(by: disposeBag)
}
}
// MARK: - ViewControllerInjectable
extension PlayViewController: ViewControllerInjectable {}
| mit | 9392b594ea38a5e027d380b64729b61a | 37.248 | 111 | 0.667224 | 5.022059 | false | false | false | false |
darkbrow/iina | iina/MPVCommand.swift | 1 | 6242 | import Foundation
struct MPVCommand: RawRepresentable {
typealias RawValue = String
var rawValue: RawValue
init(_ string: String) { self.rawValue = string }
init?(rawValue: RawValue) { self.rawValue = rawValue }
/** ignore */
static let ignore = MPVCommand("ignore")
/** seek <target> [<flags>] */
static let seek = MPVCommand("seek")
/** revert-seek [<flags>] */
static let revertSeek = MPVCommand("revert-seek")
/** frame-step */
static let frameStep = MPVCommand("frame-step")
/** frame-back-step */
static let frameBackStep = MPVCommand("frame-back-step")
/** set <name> <value> */
static let set = MPVCommand("set")
/** add <name> [<value>] */
static let add = MPVCommand("add")
/** cycle <name> [<value>] */
static let cycle = MPVCommand("cycle")
/** multiply <name> <value> */
static let multiply = MPVCommand("multiply")
/** screenshot <flags> */
static let screenshot = MPVCommand("screenshot")
/** screenshot-to-file <filename> <flags> */
static let screenshotToFile = MPVCommand("screenshot-to-file")
/** playlist-next <flags> */
static let playlistNext = MPVCommand("playlist-next")
/** playlist-prev <flags> */
static let playlistPrev = MPVCommand("playlist-prev")
/** loadfile <url> [<flags> [<options>]] */
static let loadfile = MPVCommand("loadfile")
/** loadlist <url> [<flags>] */
static let loadlist = MPVCommand("loadlist")
/** playlist-clear */
static let playlistClear = MPVCommand("playlist-clear")
/** playlist-remove <index> */
static let playlistRemove = MPVCommand("playlist-remove")
/** playlist-move <index1> <index2> */
static let playlistMove = MPVCommand("playlist-move")
/** playlist-shuffle */
static let playlistShuffle = MPVCommand("playlist-shuffle")
/** run <command> [<arg1> [<arg2> [...]]] */
static let run = MPVCommand("run")
/** subprocess */
static let subprocess = MPVCommand("subprocess")
/** quit [<code>] */
static let quit = MPVCommand("quit")
/** quit-watch-later [<code>] */
static let quitWatchLater = MPVCommand("quit-watch-later")
/** sub-add <url> [<flags> [<title> [<lang>]]] */
static let subAdd = MPVCommand("sub-add")
/** sub-remove [<id>] */
static let subRemove = MPVCommand("sub-remove")
/** sub-reload [<id>] */
static let subReload = MPVCommand("sub-reload")
/** sub-step <skip> */
static let subStep = MPVCommand("sub-step")
/** sub-seek <skip> */
static let subSeek = MPVCommand("sub-seek")
/** print-text <text> */
static let printText = MPVCommand("print-text")
/** show-text <text> [<duration>|-1 [<level>]] */
static let showText = MPVCommand("show-text")
/** expand-text <string> */
static let expandText = MPVCommand("expand-text")
/** expand-path "<string>" */
static let expandPath = MPVCommand("expand-path")
/** show-progress */
static let showProgress = MPVCommand("show-progress")
/** write-watch-later-config */
static let writeWatchLaterConfig = MPVCommand("write-watch-later-config")
/** stop */
static let stop = MPVCommand("stop")
/** mouse <x> <y> [<button> [<mode>]] */
static let mouse = MPVCommand("mouse")
/** keypress <name> */
static let keypress = MPVCommand("keypress")
/** keydown <name> */
static let keydown = MPVCommand("keydown")
/** keyup [<name>] */
static let keyup = MPVCommand("keyup")
/** keybind <name> <command> */
static let keybind = MPVCommand("keybind")
/** audio-add <url> [<flags> [<title> [<lang>]]] */
static let audioAdd = MPVCommand("audio-add")
/** audio-remove [<id>] */
static let audioRemove = MPVCommand("audio-remove")
/** audio-reload [<id>] */
static let audioReload = MPVCommand("audio-reload")
/** video-add <url> [<flags> [<title> [<lang>]]] */
static let videoAdd = MPVCommand("video-add")
/** video-remove [<id>] */
static let videoRemove = MPVCommand("video-remove")
/** video-reload [<id>] */
static let videoReload = MPVCommand("video-reload")
/** rescan-external-files [<mode>] */
static let rescanExternalFiles = MPVCommand("rescan-external-files")
/** af <operation> <value> */
static let af = MPVCommand("af")
/** vf <operation> <value> */
static let vf = MPVCommand("vf")
/** cycle-values [<"!reverse">] <property> <value1> [<value2> [...]] */
static let cycleValues = MPVCommand("cycle-values")
/** enable-section <name> [<flags>] */
static let enableSection = MPVCommand("enable-section")
/** disable-section <name> */
static let disableSection = MPVCommand("disable-section")
/** define-section <name> <contents> [<flags>] */
static let defineSection = MPVCommand("define-section")
/** overlay-add <id> <x> <y> <file> <offset> <fmt> <w> <h> <stride> */
static let overlayAdd = MPVCommand("overlay-add")
/** overlay-remove <id> */
static let overlayRemove = MPVCommand("overlay-remove")
/** osd-overlay */
static let osdOverlay = MPVCommand("osd-overlay")
/** script-message [<arg1> [<arg2> [...]]] */
static let scriptMessage = MPVCommand("script-message")
/** script-message-to <target> [<arg1> [<arg2> [...]]] */
static let scriptMessageTo = MPVCommand("script-message-to")
/** script-binding <name> */
static let scriptBinding = MPVCommand("script-binding")
/** ab-loop */
static let abLoop = MPVCommand("ab-loop")
/** drop-buffers */
static let dropBuffers = MPVCommand("drop-buffers")
/** screenshot-raw [<flags>] */
static let screenshotRaw = MPVCommand("screenshot-raw")
/** vf-command <label> <command> <argument> */
static let vfCommand = MPVCommand("vf-command")
/** af-command <label> <command> <argument> */
static let afCommand = MPVCommand("af-command")
/** apply-profile <name> */
static let applyProfile = MPVCommand("apply-profile")
/** load-script <filename> */
static let loadScript = MPVCommand("load-script")
/** change-list <name> <operation> <value> */
static let changeList = MPVCommand("change-list")
/** dump-cache <start> <end> <filename> */
static let dumpCache = MPVCommand("dump-cache")
/** ab-loop-dump-cache <filename> */
static let abLoopDumpCache = MPVCommand("ab-loop-dump-cache")
/** ab-loop-align-cache */
static let abLoopAlignCache = MPVCommand("ab-loop-align-cache")
}
| gpl-3.0 | 45e5d6693926fbefa026847d90cd477f | 39.797386 | 75 | 0.652035 | 3.80842 | false | false | false | false |
Tardis-x/iOS | Tardis/BlogTableViewController.swift | 1 | 3933 | //
// BlogTableViewController.swift
// Tardis
//
// Created by Molnar Kristian on 7/22/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import Foundation
import Firebase
class BlogTableViewController: UITableViewController {
let ref = FIRDatabase.database().reference()
var blogItemsArray:[[String:AnyObject]] = []
var contentHeight:CGFloat = 132.0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 15/255.0, green: 157/255.0, blue: 88/255.0, alpha: 1.0)
let blogRef = ref.child("prod/blog")
blogRef.keepSynced(true)
let refHandle = blogRef.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
let postDict = snapshot.value as! [String : AnyObject]
let arrayKeys = Array(postDict.keys)
for key:String in arrayKeys {
let fetchedItem = postDict[key] as! [String: AnyObject]
self.blogItemsArray.append(fetchedItem)
}
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.blogItemsArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "row")
let contentView = BlogTableViewCellContent(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.contentHeight))
contentView.setUp(self.blogItemsArray[indexPath.row])
cell.addSubview(contentView)
cell.backgroundColor = UIColor.clearColor()
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.contentHeight
}
/*
// 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.
}
*/
}
| apache-2.0 | 151e62e278b64a164212d09520236b21 | 31.766667 | 156 | 0.709054 | 4.795122 | false | false | false | false |
edmw/Volumio_ios | Pods/Eureka/Source/Rows/PickerInlineRow.swift | 4 | 3168 | // PickerInlineRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class PickerInlineCell<T: Equatable> : Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
}
//MARK: PickerInlineRow
open class _PickerInlineRow<T> : Row<PickerInlineCell<T>>, NoValueDisplayTextConformance where T: Equatable {
public typealias InlineRow = PickerRow<T>
open var options = [T]()
open var noValueDisplayText: String?
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A generic inline row where the user can pick an option from a picker view
public final class PickerInlineRow<T> : _PickerInlineRow<T>, RowType, InlineRowType where T: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
onExpandInlineRow { cell, row, _ in
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
}
public override func customDidSelect() {
super.customDidSelect()
if !isDisabled {
toggleInlineRow()
}
}
public func setupInlineRow(_ inlineRow: InlineRow) {
inlineRow.options = self.options
inlineRow.displayValueFor = self.displayValueFor
}
}
| gpl-3.0 | de85387d4b59d19888772512e9be3489 | 33.064516 | 109 | 0.675821 | 4.792738 | false | false | false | false |
qiandashuai/YH-IOS | Charts-master/Source/Charts/Data/Implementations/Standard/CandleChartDataEntry.swift | 1 | 2057 | //
// CandleChartDataEntry.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class CandleChartDataEntry: ChartDataEntry
{
/// shadow-high value
open var high = Double(0.0)
/// shadow-low value
open var low = Double(0.0)
/// close value
open var close = Double(0.0)
/// open value
open var open = Double(0.0)
public required init()
{
super.init()
}
public init(x: Double, shadowH: Double, shadowL: Double, open: Double, close: Double)
{
super.init(x: x, y: (shadowH + shadowL) / 2.0)
self.high = shadowH
self.low = shadowL
self.open = open
self.close = close
}
public init(x: Double, shadowH: Double, shadowL: Double, open: Double, close: Double, data: AnyObject?)
{
super.init(x: x, y: (shadowH + shadowL) / 2.0, data: data)
self.high = shadowH
self.low = shadowL
self.open = open
self.close = close
}
/// - returns: The overall range (difference) between shadow-high and shadow-low.
open var shadowRange: Double
{
return abs(high - low)
}
/// - returns: The body size (difference between open and close).
open var bodyRange: Double
{
return abs(open - close)
}
/// the center value of the candle. (Middle value between high and low)
open override var y: Double
{
get
{
return super.y
}
set
{
super.y = (high + low) / 2.0
}
}
// MARK: NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! CandleChartDataEntry
copy.high = high
copy.low = low
copy.open = open
copy.close = close
return copy
}
}
| gpl-3.0 | fcc44244480bb4d835fea51a21f2baeb | 22.11236 | 107 | 0.558094 | 4.065217 | false | false | false | false |
CatchChat/Yep | Yep/Views/MessageToolbar/MessageToolbar.swift | 1 | 20573 | //
// MessageToolbar.swift
// Yep
//
// Created by NIX on 15/3/24.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import Ruler
import YepKit
@IBDesignable
final class MessageToolbar: UIToolbar {
var lastToolbarFrame: CGRect?
var messageTextViewHeightConstraint: NSLayoutConstraint!
let messageTextAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(15)]
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
finishNotifyTypingTimer?.invalidate()
}
struct Notification {
static let updateDraft = "UpdateDraftOfConversation"
}
var conversation: Conversation? {
willSet {
if let _ = newValue {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MessageToolbar.updateDraft(_:)), name: Notification.updateDraft, object: nil)
}
}
}
var stateTransitionAction: ((messageToolbar: MessageToolbar, previousState: MessageToolbarState, currentState: MessageToolbarState) -> Void)?
var previousState: MessageToolbarState = .Default
var state: MessageToolbarState = .Default {
willSet {
updateHeightOfMessageTextView()
previousState = state
if let action = stateTransitionAction {
action(messageToolbar: self, previousState: previousState, currentState: newValue)
}
switch newValue {
case .Default:
moreButton.hidden = false
sendButton.hidden = true
messageTextView.hidden = false
voiceRecordButton.hidden = true
micButton.setImage(UIImage.yep_itemMic, forState: .Normal)
moreButton.setImage(UIImage.yep_itemMore, forState: .Normal)
micButton.tintColor = UIColor.messageToolBarColor()
moreButton.tintColor = UIColor.messageToolBarColor()
hideVoiceButtonAnimation()
case .BeginTextInput:
moreButton.hidden = false
sendButton.hidden = true
moreButton.setImage(UIImage.yep_itemMore, forState: .Normal)
case .TextInputing:
moreButton.hidden = true
sendButton.hidden = false
messageTextView.hidden = false
voiceRecordButton.hidden = true
notifyTyping()
case .VoiceRecord:
moreButton.hidden = false
sendButton.hidden = true
messageTextView.hidden = true
voiceRecordButton.hidden = false
messageTextView.text = ""
micButton.setImage(UIImage.yep_iconKeyboard, forState: .Normal)
moreButton.setImage(UIImage.yep_itemMore, forState: .Normal)
micButton.tintColor = UIColor.messageToolBarColor()
moreButton.tintColor = UIColor.messageToolBarColor()
showVoiceButtonAnimation()
}
}
didSet {
switch state {
case .BeginTextInput, .TextInputing:
// 由用户手动触发键盘弹出,回复时要注意
break
default:
messageTextView.resignFirstResponder()
}
}
}
var notifyTypingAction: (() -> Void)?
var needDetectMention = false
var initMentionUserAction: (() -> Void)?
var tryMentionUserAction: ((usernamePrefix: String) -> Void)?
var giveUpMentionUserAction: (() -> Void)?
var textSendAction: ((messageToolBar: MessageToolbar) -> Void)?
var moreMessageTypesAction: (() -> Void)?
var voiceRecordBeginAction: ((messageToolBar: MessageToolbar) -> Void)?
var voiceRecordEndAction: ((messageToolBar: MessageToolbar) -> Void)?
var voiceRecordCancelAction: ((messageToolBar: MessageToolbar) -> Void)?
var voiceRecordingUpdateUIAction: ((topOffset: CGFloat) -> Void)?
lazy var micButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.yep_itemMic, forState: .Normal)
button.tintColor = UIColor.messageToolBarColor()
button.tintAdjustmentMode = .Normal
button.addTarget(self, action: #selector(MessageToolbar.toggleRecordVoice), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
let normalCornerRadius: CGFloat = 6
lazy var messageTextView: UITextView = {
let textView = UITextView()
textView.textContainerInset = UIEdgeInsets(top: 8, left: 4, bottom: 8, right: 4)
textView.font = UIFont.systemFontOfSize(15)
textView.layer.borderWidth = 1
textView.layer.borderColor = UIColor.yepMessageToolbarSubviewBorderColor().CGColor
textView.layer.cornerRadius = self.normalCornerRadius
textView.delegate = self
textView.scrollEnabled = false // 重要:若没有它,换行时可能有 top inset 不正确
return textView
}()
lazy var voiceRecordButton: VoiceRecordButton = {
let button = VoiceRecordButton()
button.backgroundColor = UIColor.whiteColor()
button.layer.cornerRadius = self.normalCornerRadius
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.yepMessageToolbarSubviewBorderColor().CGColor
button.tintColor = UIColor.messageToolBarHighlightColor()
button.touchesBegin = { [weak self] in
self?.tryVoiceRecordBegin()
}
button.touchesEnded = { [weak self] needAbort in
if needAbort {
self?.tryVoiceRecordCancel()
} else {
self?.tryVoiceRecordEnd()
}
}
button.touchesCancelled = { [weak self] in
self?.tryVoiceRecordCancel()
}
button.checkAbort = { [weak self] topOffset in
self?.voiceRecordingUpdateUIAction?(topOffset: topOffset)
return topOffset > 40
}
return button
}()
lazy var moreButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.yep_itemMore, forState: .Normal)
button.tintColor = UIColor.messageToolBarColor()
button.tintAdjustmentMode = .Normal
button.addTarget(self, action: #selector(MessageToolbar.moreMessageTypes), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
lazy var sendButton: UIButton = {
let button = UIButton()
button.setTitle(NSLocalizedString("Send", comment: ""), forState: .Normal)
button.tintColor = UIColor.messageToolBarHighlightColor()
button.tintAdjustmentMode = .Normal
button.setTitleColor(UIColor.messageToolBarHighlightColor(), forState: .Normal)
button.addTarget(self, action: #selector(MessageToolbar.trySendTextMessage), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
private var searchTask: CancelableTask?
// MARK: UI
override func didMoveToSuperview() {
super.didMoveToSuperview()
makeUI()
state = .Default
}
var messageTextViewMinHeight: CGFloat {
let textContainerInset = messageTextView.textContainerInset
return ceil(messageTextView.font!.lineHeight + textContainerInset.top + textContainerInset.bottom)
}
func makeUI() {
self.addSubview(messageTextView)
messageTextView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(micButton)
micButton.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(voiceRecordButton)
voiceRecordButton.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(moreButton)
moreButton.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(sendButton)
sendButton.translatesAutoresizingMaskIntoConstraints = false
let viewsDictionary: [String: AnyObject] = [
"moreButton": moreButton,
"messageTextView": messageTextView,
"micButton": micButton,
"voiceRecordButton": voiceRecordButton,
"sendButton": sendButton,
]
let buttonBottom: CGFloat = 8
let constraintsV1 = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=0)-[micButton]-(bottom)-|", options: [], metrics: ["bottom": buttonBottom], views: viewsDictionary)
let constraintsV2 = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=0)-[moreButton(==micButton)]-(bottom)-|", options: [], metrics: ["bottom": buttonBottom], views: viewsDictionary)
let constraintsV3 = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=0)-[sendButton(==micButton)]-(bottom)-|", options: [], metrics: ["bottom": buttonBottom], views: viewsDictionary)
let messageTextViewConstraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|-7-[messageTextView]-8-|", options: [], metrics: nil, views: viewsDictionary)
println("messageTextViewMinHeight: \(messageTextViewMinHeight)")
messageTextViewHeightConstraint = NSLayoutConstraint(item: messageTextView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: messageTextViewMinHeight)
messageTextViewHeightConstraint.priority = UILayoutPriorityDefaultHigh
let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[micButton(48)][messageTextView][moreButton(==micButton)]|", options: [], metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(constraintsV1)
NSLayoutConstraint.activateConstraints(constraintsV2)
NSLayoutConstraint.activateConstraints(constraintsV3)
NSLayoutConstraint.activateConstraints(constraintsH)
NSLayoutConstraint.activateConstraints(messageTextViewConstraintsV)
NSLayoutConstraint.activateConstraints([messageTextViewHeightConstraint])
let sendButtonConstraintCenterY = NSLayoutConstraint(item: sendButton, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: micButton, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
let sendButtonConstraintHeight = NSLayoutConstraint(item: sendButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: micButton, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)
let sendButtonConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:[messageTextView][sendButton(==moreButton)]|", options: [], metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints([sendButtonConstraintCenterY])
NSLayoutConstraint.activateConstraints([sendButtonConstraintHeight])
NSLayoutConstraint.activateConstraints(sendButtonConstraintsH)
// void record button
let voiceRecordButtonConstraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|-7-[voiceRecordButton]-8-|", options: [], metrics: nil, views: viewsDictionary)
let voiceRecordButtonConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[micButton][voiceRecordButton][moreButton]|", options: [], metrics: nil, views: viewsDictionary)
let voiceRecordButtonHeightConstraint = NSLayoutConstraint(item: voiceRecordButton, attribute: .Height, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: messageTextViewMinHeight)
voiceRecordButtonHeightConstraint.priority = UILayoutPriorityDefaultHigh
NSLayoutConstraint.activateConstraints(voiceRecordButtonConstraintsV)
NSLayoutConstraint.activateConstraints(voiceRecordButtonConstraintsH)
NSLayoutConstraint.activateConstraints([voiceRecordButtonHeightConstraint])
}
// MARK: Animations
func showVoiceButtonAnimation() {
let animation = CABasicAnimation(keyPath: "cornerRadius")
animation.fromValue = normalCornerRadius
let newCornerRadius: CGFloat = 17
animation.toValue = newCornerRadius
animation.timingFunction = CAMediaTimingFunction(name: "easeInEaseOut")
animation.repeatCount = 0
voiceRecordButton.layer.addAnimation(animation, forKey: "cornerRadius")
voiceRecordButton.layer.cornerRadius = newCornerRadius
messageTextView.layer.cornerRadius = newCornerRadius
UIView.animateWithDuration(0.1, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
if let strongSelf = self {
strongSelf.messageTextViewHeightConstraint.constant = strongSelf.messageTextViewMinHeight
strongSelf.layoutIfNeeded()
}
}, completion: { _ in })
}
func hideVoiceButtonAnimation() {
let animation = CABasicAnimation(keyPath: "cornerRadius")
animation.fromValue = messageTextView.layer.cornerRadius
animation.toValue = normalCornerRadius
animation.repeatCount = 0
animation.timingFunction = CAMediaTimingFunction(name: "easeInEaseOut")
messageTextView.layer.addAnimation(animation, forKey: "cornerRadius")
messageTextView.layer.cornerRadius = normalCornerRadius
voiceRecordButton.layer.cornerRadius = normalCornerRadius
}
// Mark: Helpers
func updateHeightOfMessageTextView() {
let size = messageTextView.sizeThatFits(CGSize(width: CGRectGetWidth(messageTextView.bounds), height: CGFloat(FLT_MAX)))
let newHeight = size.height
let limitedNewHeight = min(Ruler.iPhoneVertical(60, 80, 100, 100).value, newHeight)
//println("oldHeight: \(messageTextViewHeightConstraint.constant), newHeight: \(newHeight)")
if newHeight != messageTextViewHeightConstraint.constant {
UIView.animateWithDuration(0.1, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.messageTextViewHeightConstraint.constant = limitedNewHeight
self?.layoutIfNeeded()
}, completion: { [weak self] finished in
// hack for scrollEnabled when input lots of text
if finished, let strongSelf = self {
let enabled = newHeight > strongSelf.messageTextView.bounds.height
strongSelf.messageTextView.scrollEnabled = enabled
}
})
}
}
// MARK: Actions
func updateDraft(notification: NSNotification) {
guard let conversation = conversation where !conversation.invalidated, let realm = conversation.realm else {
return
}
if let draft = conversation.draft {
let _ = try? realm.write { [weak self] in
if let strongSelf = self {
draft.messageToolbarState = strongSelf.state.rawValue
//println("strongSelf.messageTextView.text: \(strongSelf.messageTextView.text)")
draft.text = strongSelf.messageTextView.text
}
}
} else {
let draft = Draft()
draft.messageToolbarState = state.rawValue
let _ = try? realm.write {
conversation.draft = draft
}
}
}
func trySendTextMessage() {
if let textSendAction = textSendAction {
textSendAction(messageToolBar: self)
}
}
func toggleRecordVoice() {
if state == .VoiceRecord {
state = .Default
} else {
state = .VoiceRecord
}
}
func moreMessageTypes() {
moreMessageTypesAction?()
}
private var mentionUsernameRange: Range<String.Index>?
func replaceMentionedUsername(username: String) {
defer {
mentionUsernameRange = nil
}
guard !username.isEmpty else {
return
}
let mentionUsernameWithSpaceSuffix = "@" + username + " "
var text = messageTextView.text
if let range = mentionUsernameRange {
text.replaceRange(range, with: mentionUsernameWithSpaceSuffix)
messageTextView.text = text
updateHeightOfMessageTextView()
}
}
func tryVoiceRecordBegin() {
voiceRecordButton.state = .Touched
voiceRecordBeginAction?(messageToolBar: self)
}
func tryVoiceRecordEnd() {
voiceRecordButton.state = .Default
voiceRecordEndAction?(messageToolBar: self)
}
func tryVoiceRecordCancel() {
voiceRecordButton.state = .Default
voiceRecordCancelAction?(messageToolBar: self)
}
// Notify typing
private var finishNotifyTypingTimer: NSTimer?
private var inNotifyTyping: Bool = false
private func notifyTyping() {
if inNotifyTyping {
//println("inNotifyTyping")
return
} else {
inNotifyTyping = true
//println("notifyTypingAction")
notifyTypingAction?()
finishNotifyTypingTimer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: #selector(MessageToolbar.finishNotifyTyping(_:)), userInfo: nil, repeats: false)
}
}
@objc private func finishNotifyTyping(sender: NSTimer) {
inNotifyTyping = false
}
}
// MARK: UITextViewDelegate
extension MessageToolbar: UITextViewDelegate {
func textViewDidBeginEditing(textView: UITextView) {
guard let text = textView.text else { return }
state = text.isEmpty ? .BeginTextInput : .TextInputing
}
func textViewDidChange(textView: UITextView) {
guard let text = textView.text else { return }
state = text.isEmpty ? .BeginTextInput : .TextInputing
if needDetectMention {
cancel(searchTask)
// 刚刚输入 @
if text.hasSuffix("@") {
mentionUsernameRange = text.endIndex.advancedBy(-1)..<text.endIndex
initMentionUserAction?()
return
}
searchTask = delay(0.4) { [weak self] in
// 对于拼音输入法等,输入时会先显示拼音,然后才上字,拼音间有空格(这个空格似乎不是普通空格)
if let markedTextRange = textView.markedTextRange, markedText = textView.textInRange(markedTextRange) {
var text = text
let beginning = textView.beginningOfDocument
let start = markedTextRange.start
let end = markedTextRange.end
let location = textView.offsetFromPosition(beginning, toPosition: start)
// 保证前面至少还有一个字符,for mentionNSRange
guard location > 0 else {
return
}
let length = textView.offsetFromPosition(start, toPosition: end)
let nsRange = NSMakeRange(location, length)
let mentionNSRange = NSMakeRange(location - 1, length + 1)
guard let range = text.yep_rangeFromNSRange(nsRange), mentionRange = text.yep_rangeFromNSRange(mentionNSRange) else {
return
}
text.removeRange(range)
if text.hasSuffix("@") {
self?.mentionUsernameRange = mentionRange
let wordString = markedText.yep_removeAllWhitespaces
//println("wordString from markedText: >\(wordString)<")
self?.tryMentionUserAction?(usernamePrefix: wordString)
return
}
}
// 正常查询 mention
let currentLetterIndex = textView.selectedRange.location - 1
if let (wordString, mentionWordRange) = text.yep_mentionWordInIndex(currentLetterIndex) {
//println("mentionWord: \(wordString), \(mentionWordRange)")
self?.mentionUsernameRange = mentionWordRange
let wordString = wordString.trimming(.Whitespace)
self?.tryMentionUserAction?(usernamePrefix: wordString)
return
}
// 都没有就放弃
self?.giveUpMentionUserAction?()
}
}
}
}
| mit | 39f15480c5a2d97da24b2a4e7452408f | 34.714035 | 236 | 0.644005 | 5.873341 | false | false | false | false |
kences/swift_weibo | Swift-SinaWeibo/Classes/Module/Main/Controller/LGBasicTableViewController.swift | 1 | 3455 |
//
// LGBasicTableViewController.swift
// Swift-SinaWeibo
//
// Created by lu on 15/10/26.
// Copyright © 2015年 lg. All rights reserved.
//
import UIKit
class LGBasicTableViewController: UITableViewController
{
let startVisitor = !(LGUserAccount.isLogin)
/// 判断是否启动访客视图
override func loadView()
{
startVisitor ? setupVisitorView() : super.loadView()
}
override func viewDidLoad()
{
super.viewDidLoad()
// 监听程序进入后台或者前台的通知,使转轮正常动画
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil)
// 导航栏的按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "didSelectedRegisterButton")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "didSelectedLoginButton")
}
/// 创建访客视图
private func setupVisitorView()
{
let visitorView = LGVisitorView()
view = visitorView
visitorView.visitorViewDelegate = self
// print(self)
// 如果是切换到各个子类,self就是当前子类的对象:控制器的view是懒加载
if self is LGHomeViewController {
// 开始动画
visitorView.startRotationAnimation()
}
else if self is LGMessageViewController {
visitorView .changeVisitorView("visitordiscover_image_message", title: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
else if self is LGDiscoverViewController {
visitorView .changeVisitorView("visitordiscover_image_message", title: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过")
}
else if self is LGProfileViewController {
visitorView .changeVisitorView("visitordiscover_image_profile", title: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
}
}
// MARK: - 监听通知
/// 程序进入后台
func applicationDidEnterBackground()
{
}
/// 程序进入前台
func applicationDidBecomeActive()
{
}
// 移除通知
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
}
// MARK: - LGVisitorViewDelegate 代理方法
// 一般写在扩展中,方便代码的管理
extension LGBasicTableViewController: LGVisitorViewDelegate
{
func didSelectedLoginButton()
{
// modal控制器
let webVC = LGOAuthViewController()
let nav = UINavigationController(rootViewController: webVC)
presentViewController(nav, animated: true, completion: nil)
}
func didSelectedRegisterButton()
{
print("点击了注册按钮")
}
}
| apache-2.0 | c0f9e1a02bc45e635320c55f715c6f30 | 30.216495 | 169 | 0.674042 | 5.123519 | false | false | false | false |
yq616775291/DiliDili-Fun | DiliDili/Tool/swiftTool.swift | 1 | 1396 | //
// swiftTool.swift
// DiliDili
//
// Created by yq on 16/3/7.
// Copyright © 2016年 yq. All rights reserved.
//
import Foundation
import ObjectiveC
func swiftClassFromString(className: String) -> AnyClass! {
//method1
//方法 NSClassFromString 在Swift中已经不起作用了no effect,需要适当更改
if let appName: String? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String? {
// generate the full name of your class (take a look into your "appname-swift.h" file)
// let classStringName = "_TtC\(appName!.utf16Count)\(appName!)\(count(className))\(className)"//xcode 6.1-6.2 beta
let classStringName = "_TtC\(appName?.characters.count))\(appName!)\(appName?.characters.count)\(className)"
let cls: AnyClass? = NSClassFromString(classStringName)
// method2
//cls = NSClassFromString("\(appName!).\(className)")
assert(cls != nil, "class not found,please check className")
return cls
}
return nil;
}
private var custom: String?
extension UIViewController {
var pagesTitle: String? {
get {
return (objc_getAssociatedObject(self, &custom) as? String)!
}
set(newValue) {
objc_setAssociatedObject(self, &custom, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
| mit | baf2a1b3bc91136296410fdb82a5aaaa | 28.5 | 134 | 0.644805 | 4.188272 | false | false | false | false |
shedowHuang/MyLiveBySwift | MyLiveBySwift/MyLiveBySwift/Classes/Home/View/RecommendCycleView.swift | 1 | 4066 | //
// RecommendCycleView.swift
// MyLiveBySwift
//
// Created by Shedows on 2017/1/2.
// Copyright © 2017年 Shedows. All rights reserved.
//
import UIKit
private let kCycleCellID = "kCycleCellID"
class RecommendCycleView: UIView {
// MARK: 定义属性
var cycleTimer : Timer? // 定时器
var cycleModels : [CycleModel]? {
didSet {
// 1.刷新collectionView
collectionView.reloadData()
// 2.设置pageControl个数
pageControl.numberOfPages = cycleModels?.count ?? 0
// 3.默认滚动到中间某一个位置
let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
// 4.添加定时器
removeCycleTimer()
addCycleTimer()
}
}
// MARK: 控件属性
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
// MARK: 系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
// 设置该控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
// 注册Cell
collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
// 设置collectionView的layout
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
// MARK:- 提供一个快速创建View的类方法
extension RecommendCycleView {
static func recommendCycleView() ->RecommendCycleView{
return Bundle.main.loadNibNamed("RecommendCycleView", owner: nil, options: nil)?.first as! RecommendCycleView
}
}
// MARK:- 遵守UICollectionView的数据源协议
extension RecommendCycleView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (cycleModels?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell
cell.cycleModel = cycleModels![indexPath.item % cycleModels!.count]
return cell
}
}
// MARK:- 遵守UICollectionView的代理协议
extension RecommendCycleView : UICollectionViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 1.获取位置的偏移量
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
// 2.计算pagecontroller的currentIndex
pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeCycleTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addCycleTimer()
}
}
// MARK:- 对定时器操作的方法
extension RecommendCycleView{
fileprivate func addCycleTimer(){
cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(cycleTimer!, forMode: .commonModes)
}
fileprivate func removeCycleTimer(){
cycleTimer?.invalidate() // 从运行循环中移除
cycleTimer = nil
}
@objc func scrollToNext(){
let currentOffsetX = collectionView.contentOffset.x
let offsetX = currentOffsetX + collectionView.bounds.width
collectionView.setContentOffset(CGPoint(x: offsetX ,y:0), animated: true)
}
}
| mit | 9158ebca0b1bfee46e26a6bd48b5a8d1 | 29.632 | 128 | 0.651867 | 5.347765 | false | false | false | false |
CodePath2017Group4/travel-app | RoadTripPlanner/TabBarViewController.swift | 1 | 3598 | //
// TabBarViewController.swift
// RoadTripPlanner
//
// Created by Diana Fisher on 10/17/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
import Parse
class TabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// Create view controllers from storyboard.
let tripsNavigtaionController = storyboard.instantiateViewController(withIdentifier: Constants.ViewControllerIdentifiers.TripsNavigationController) as! UINavigationController
// let tripsNavigtaionController = TempLandingViewController.storyboardInstance()!
tripsNavigtaionController.tabBarItem = UITabBarItem(title: "Trips", image: #imageLiteral(resourceName: "trip-tab"), tag: 0)
// Add the log out button to the view controller navigation item.
addLogoutButton(to: tripsNavigtaionController)
let albumsNavigtaionViewController = storyboard.instantiateViewController(withIdentifier: Constants.ViewControllerIdentifiers.AlbumsNavigationController) as! UINavigationController
albumsNavigtaionViewController.tabBarItem = UITabBarItem(title: "Albums", image: #imageLiteral(resourceName: "album-tab"), tag: 1)
addLogoutButton(to: albumsNavigtaionViewController)
let notificationsNavigationController = storyboard.instantiateViewController(withIdentifier: Constants.ViewControllerIdentifiers.NotificationNavigationController) as! UINavigationController
notificationsNavigationController.tabBarItem = UITabBarItem(title: "Notifications", image: #imageLiteral(resourceName: "notification-tab"), tag: 2)
let profileNavigationController = storyboard.instantiateViewController(withIdentifier: Constants.ViewControllerIdentifiers.ProfileNavigationController) as! UINavigationController
profileNavigationController.tabBarItem = UITabBarItem(title: "Profile", image: #imageLiteral(resourceName: "profile-tab"), tag: 3)
addLogoutButton(to: profileNavigationController)
// Set the appearance of the tab bar
UITabBar.appearance().tintColor = Constants.Colors.ColorPalette3495Color2
let viewControllerList = [tripsNavigtaionController, albumsNavigtaionViewController, notificationsNavigationController, profileNavigationController]
// Set the viewControllers property of our UITabBarController
viewControllers = viewControllerList
}
fileprivate func addLogoutButton(to navigationController: UINavigationController) {
let topViewController = navigationController.topViewController
// topViewController?.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Log Out", style: .plain, target: self, action: #selector(logoutButtonPressed))
topViewController?.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "md_logout"), style: .plain, target: self, action: #selector(logoutButtonPressed))
}
func logoutButtonPressed() {
PFUser.logOut()
// Return to login screen.
dismiss(animated: true, completion: nil)
// Post a notification
NotificationCenter.default.post(name: Constants.NotificationNames.LogoutPressedNotification, object: nil, userInfo: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | a665907be814f462f15a1515be564653 | 49.661972 | 197 | 0.741173 | 6.035235 | false | false | false | false |
yangchenghu/actor-platform | actor-apps/app-ios/ActorCore/Providers/CocoaNetworkRuntime.swift | 11 | 3755 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import Foundation
class CocoaNetworkRuntime : ARManagedNetworkProvider {
override init() {
super.init(factory: CocoaTcpConnectionFactory())
}
}
class CocoaTcpConnectionFactory: NSObject, ARAsyncConnectionFactory {
func createConnectionWithConnectionId(connectionId: jint,
withEndpoint endpoint: ARConnectionEndpoint!,
withInterface connectionInterface: ARAsyncConnectionInterface!) -> ARAsyncConnection! {
return CocoaTcpConnection(connectionId: Int(connectionId), endpoint: endpoint, connection: connectionInterface)
}
}
class CocoaTcpConnection: ARAsyncConnection, GCDAsyncSocketDelegate {
static let queue = dispatch_queue_create("im.actor.queue.TCP", nil);
let READ_HEADER = 1
let READ_BODY = 2
var TAG: String!
var gcdSocket:GCDAsyncSocket? = nil
var header: NSData?
init(connectionId: Int, endpoint: ARConnectionEndpoint!, connection: ARAsyncConnectionInterface!) {
super.init(endpoint: endpoint, withInterface: connection)
TAG = "🎍ConnectionTcp#\(connectionId)"
}
override func doConnect() {
let endpoint = getEndpoint()
gcdSocket = GCDAsyncSocket(delegate: self, delegateQueue: CocoaTcpConnection.queue)
do {
try self.gcdSocket!.connectToHost(endpoint.getHost()!, onPort: UInt16(endpoint.getPort()), withTimeout: Double(ARManagedConnection_CONNECTION_TIMEOUT) / 1000.0)
} catch _ {
}
}
// Affer successful connection
func socket(sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) {
if (UInt(self.getEndpoint().getType().ordinal()) == ARConnectionEndpoint_Type.TCP_TLS.rawValue) {
// NSLog("\(TAG) Starring TLS Session...")
sock.startTLS(nil)
} else {
startConnection()
}
}
// After TLS successful
func socketDidSecure(sock: GCDAsyncSocket!) {
// NSLog("\(TAG) TLS Session started...")
startConnection()
}
func startConnection() {
gcdSocket?.readDataToLength(UInt(9), withTimeout: -1, tag: READ_HEADER)
onConnected()
}
// On connection closed
func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) {
// NSLog("\(TAG) Connection closed...")
onClosed()
}
func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
if (tag == READ_HEADER) {
// NSLog("\(TAG) Header received")
self.header = data
data.readUInt32(0) // IGNORE: package id
let size = data.readUInt32(5)
gcdSocket?.readDataToLength(UInt(size + 4), withTimeout: -1, tag: READ_BODY)
} else if (tag == READ_BODY) {
// NSLog("\(TAG) Body received")
let package = NSMutableData()
package.appendData(self.header!)
package.appendData(data)
package.readUInt32(0) // IGNORE: package id
self.header = nil
onReceived(package.toJavaBytes())
gcdSocket?.readDataToLength(UInt(9), withTimeout: -1, tag: READ_HEADER)
} else {
fatalError("Unknown tag in read data")
}
}
override func doClose() {
if (gcdSocket != nil) {
// NSLog("\(TAG) Closing...")
gcdSocket?.disconnect()
gcdSocket = nil
}
}
override func doSend(data: IOSByteArray!) {
gcdSocket?.writeData(data.toNSData(), withTimeout: -1, tag: 0)
}
} | mit | 850a75174f1a0e34b5b1066c5f3de8cb | 32.508929 | 172 | 0.598081 | 5.009346 | false | false | false | false |
danthorpe/Examples | Operations/Permissions/Permissions/PermissionViewController.swift | 1 | 10218 | //
// PermissionViewController.swift
// Permissions
//
// Created by Daniel Thorpe on 28/07/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import UIKit
import PureLayout
import Operations
class PermissionViewController: UIViewController {
class InfoBox: UIView {
let informationLabel = UILabel.newAutoLayoutView()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(informationLabel)
informationLabel.autoPinEdgesToSuperviewMargins()
configure()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure() {
informationLabel.textAlignment = .Center
informationLabel.numberOfLines = 4
informationLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
}
}
class InfoInstructionButtonBox: InfoBox {
let instructionLabel = UILabel.newAutoLayoutView()
let button = UIButton(type: .Custom)
var verticalSpaceBetweenLabels: NSLayoutConstraint!
var verticalSpaceBetweenButton: NSLayoutConstraint!
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(instructionLabel)
addSubview(button)
removeConstraints(constraints)
informationLabel.autoPinEdgesToSuperviewMarginsExcludingEdge(.Bottom)
verticalSpaceBetweenLabels = instructionLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: informationLabel, withOffset: 10)
instructionLabel.autoPinEdgeToSuperviewMargin(.Leading)
instructionLabel.autoPinEdgeToSuperviewMargin(.Trailing)
verticalSpaceBetweenButton = button.autoPinEdge(.Top, toEdge: .Bottom, ofView: instructionLabel, withOffset: 10)
button.autoPinEdgeToSuperviewMargin(.Bottom)
button.autoAlignAxisToSuperviewMarginAxis(.Vertical)
configure()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configure() {
super.configure()
instructionLabel.textAlignment = .Center
instructionLabel.numberOfLines = 0
instructionLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
button.titleLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
}
}
enum Action {
case RequestPermission
case PerformOperation
var selector: Selector {
switch self {
case .RequestPermission:
return #selector(PermissionViewController.requestPermissionAction(_:))
case .PerformOperation:
return #selector(PermissionViewController.performOperationAction(_:))
}
}
}
enum State: Int {
case Unknown, Authorized, Denied, Completed
static var all: [State] = [ .Unknown, .Authorized, .Denied, .Completed ]
}
// UIViews
let permissionNotDetermined = InfoInstructionButtonBox.newAutoLayoutView()
let permissionDenied = InfoInstructionButtonBox.newAutoLayoutView()
let permissionGranted = InfoInstructionButtonBox.newAutoLayoutView()
let permissionReset = InfoInstructionButtonBox.newAutoLayoutView()
let operationResults = InfoBox.newAutoLayoutView()
let queue = OperationQueue()
private var _state: State = .Unknown
var state: State {
get {
return _state
}
set {
switch (_state, newValue) {
case (.Completed, _):
break
case (.Unknown, _):
_state = newValue
queue.addOperation(displayOperationForState(newValue, silent: true))
default:
_state = newValue
queue.addOperation(displayOperationForState(newValue, silent: false))
}
}
}
override func loadView() {
let _view = UIView(frame: CGRectZero)
_view.backgroundColor = UIColor.whiteColor()
func configureHierarchy() {
_view.addSubview(permissionNotDetermined)
_view.addSubview(permissionDenied)
_view.addSubview(permissionGranted)
_view.addSubview(operationResults)
_view.addSubview(permissionReset)
}
func configureLayout() {
for view in [permissionNotDetermined, permissionDenied, permissionGranted] {
view.autoSetDimension(.Width, toSize: 300)
view.autoCenterInSuperview()
}
operationResults.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero)
permissionReset.button.hidden = true
permissionReset.verticalSpaceBetweenButton.constant = 0
permissionReset.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Top)
}
configureHierarchy()
configureLayout()
view = _view
}
override func viewDidLoad() {
super.viewDidLoad()
permissionNotDetermined.informationLabel.text = "We haven't yet asked permission to access your Address Book."
permissionNotDetermined.instructionLabel.text = "Tap the button below to ask for permissions."
permissionNotDetermined.button.setTitle("Start", forState: .Normal)
permissionNotDetermined.button.addTarget(self, action: Action.RequestPermission.selector, forControlEvents: .TouchUpInside)
permissionGranted.informationLabel.text = "Permissions was granted. Yay!"
permissionGranted.instructionLabel.text = "We can now perform an operation as we've been granted the required permissions."
permissionGranted.button.setTitle("Run", forState: .Normal)
permissionGranted.button.addTarget(self, action: Action.PerformOperation.selector, forControlEvents: .TouchUpInside)
permissionDenied.informationLabel.text = "Permission was denied or restricted. Oh Nos!"
permissionDenied.instructionLabel.hidden = true
permissionDenied.button.enabled = false
permissionDenied.button.hidden = true
permissionReset.informationLabel.text = "iOS remembers permissions for apps between launches and installes. But you can get around this."
permissionReset.informationLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
permissionReset.informationLabel.textColor = UIColor.redColor()
permissionReset.instructionLabel.text = "Either, run the app with a different bundle identififier. or reset your global permissions in General > Reset > Location & Address Book for example."
permissionReset.instructionLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1)
permissionReset.instructionLabel.textColor = UIColor.redColor()
permissionReset.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.3)
for view in [permissionNotDetermined, permissionGranted, permissionDenied, permissionReset, operationResults] {
view.hidden = true
}
for button in [permissionNotDetermined.button, permissionGranted.button] {
button.setTitleColor(UIColor.globalTintColor ?? UIColor.blueColor(), forState: .Normal)
}
}
// For Overriding
func requestPermission() {
assertionFailure("Must be overridden")
}
func performOperation() {
assertionFailure("Must be overridden")
}
// MARK: Update UI
func configureConditionsForState<C: Condition>(state: State, silent: Bool = true) -> (C) -> [Condition] {
return { condition in
switch (silent, state) {
case (true, .Unknown):
return [ SilentCondition(NegatedCondition(condition)) ]
case (false, .Unknown):
return [ NegatedCondition(condition) ]
case (true, .Authorized):
return [ SilentCondition(condition) ]
case (false, .Authorized):
return [ condition ]
default:
return []
}
}
}
func conditionsForState(state: State, silent: Bool = true) -> [Condition] {
// Subclasses should override and call this...
// return configureConditionsForState(state, silent: silent)(BlockCondition { true })
fatalError("Requires subclassing otherwise view controller will be left hanging.")
}
func viewsForState(state: State) -> [UIView] {
switch state {
case .Unknown:
return [permissionNotDetermined]
case .Authorized:
return [permissionGranted, permissionReset]
case .Denied:
return [permissionDenied, permissionReset]
case .Completed:
return [operationResults]
}
}
func displayOperationForState(state: State, silent: Bool = true) -> Operation {
let others: [State] = {
var all = Set(State.all)
let _ = all.remove(state)
return Array(all)
}()
let viewsToHide = others.flatMap { self.viewsForState($0) }
let viewsToShow = viewsForState(state)
let update = BlockOperation { (continueWithError: BlockOperation.ContinuationBlockType) in
dispatch_async(Queue.Main.queue) {
viewsToHide.forEach { $0.hidden = true }
viewsToShow.forEach { $0.hidden = false }
continueWithError(error: nil)
}
}
update.name = "Update UI for state \(state)"
let conditions = conditionsForState(state, silent: silent)
conditions.forEach { update.addCondition($0) }
return update
}
// Actions
@IBAction func requestPermissionAction(sender: UIButton) {
requestPermission()
}
@IBAction func performOperationAction(sender: UIButton) {
performOperation()
}
}
| mit | 837ebae129d3a779a0d41fa00f2cf4b0 | 36.428571 | 198 | 0.642885 | 5.802385 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/XMTV/Classes/Entertainment/Model/LivelistModel.swift | 2 | 1706 | //
// LivelistModel.swift
// XMTV
//
// Created by Mac on 2017/1/11.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class LivelistModel: NSObject {
var id: String = ""
var ver: String = ""
var createtime: String = ""
var updatetime: String = ""
var name: String = ""
var hostid: String = ""
var person_num: Int = 0
var announcement: String = ""
var classification: [String: Any]?
var pictures: [String: Any]?
var userinfo: [String: Any]?
var status: Int = 0
var start_time: String = ""
var end_time: String = ""
var duration: String = ""
var schedule: Int = 0
var remind_switch: Int = 0
var remind_content: String = ""
var level: Int = 0
var stream_status: Int = 0
var classify_switch: Int = 0
var reliable: Int = 0
var banned_reason: Int = 0
var unlock_time: Int = 0
var speak_interval: Int = 0
var person_num_thres: String = ""
var reduce_ratio: String = ""
var person_switch: String = ""
var watermark_switch: Int = 0
var watermark_loc: Int = 0
var account_status: Int = 0
var person_src: String = ""
var display_type: Int = 0
var tag: String = ""
var tag_switch: Int = 0
var tag_color: Int = 0
var rcmd_ratio: Int = 0
var show_pos: Int = 0
var rtype_usable: Int = 0
var room_type: Int = 0
var rtype_value: Int = 0
var style_type: Int = 0
var cdn_rate: Int = 0
var room_key: String = ""
var fans: Int = 0
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| apache-2.0 | d9bba59305f66af20b1fb36621188f3e | 24.41791 | 73 | 0.580153 | 3.447368 | false | false | false | false |
arbitur/Func | source/Core/Extensions/NSAttributedString+Func.swift | 1 | 8426 | //
// NSAttributedString+Func.swift
// Func
//
// Created by Philip Fryklund on 8/Dec/17.
//
import Foundation
public extension NSAttributedString {
convenience init?(html: String) {
guard
let data = html.data(using: .utf16, allowLossyConversion: false),
let string = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
else {
return nil
}
self.init(attributedString: string)
}
}
public extension NSAttributedString {
typealias Attributes = [NSAttributedString.Key: Any]
class AttributesBuilder {
public var font: UIFont?
public var foregroundColor: UIColor? // UIColor, default blackColor
public var backgroundColor: UIColor? // UIColor, default nil: no background
public var ligature: Bool? // NSNumber containing integer, default 1: default ligatures, 0: no ligatures
public var kern: Float? // NSNumber containing floating point value, in points; amount to modify default kerning. 0 means kerning is disabled.
public var strikethroughStyle: Int? // NSNumber containing integer, default 0: no strikethrough
public var underlineStyle: Int? // NSNumber containing integer, default 0: no underline
public var strokeColor: UIColor? // UIColor, default nil: same as foreground color
public var strokeWidth: Float? // NSNumber containing floating point value, in percent of font point size, default 0: no stroke; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0)
public var shadow: NSShadow? // NSShadow, default nil: no shadow
public var textEffect: String? // NSString, default nil: no text effect
public var attachment: NSTextAttachment? // NSTextAttachment, default nil
public var link: URL? // NSURL (preferred) or NSString
public var baselineOffset: Float? // NSNumber containing floating point value, in points; offset from baseline, default 0
public var underlineColor: UIColor? // UIColor, default nil: same as foreground color
public var strikethroughColor: UIColor? // UIColor, default nil: same as foreground color
public var obliqueness: Float? // NSNumber containing floating point value; skew to be applied to glyphs, default 0: no skew
public var expansion: Float? // NSNumber containing floating point value; log of expansion factor to be applied to glyphs, default 0: no expansion
public var writingDirection: [Int]? // NSArray of NSNumbers representing the nested levels of writing direction overrides as defined by Unicode LRE, RLE, LRO, and RLO characters. The control characters can be obtained by masking NSWritingDirection and NSWritingDirectionFormatType values. LRE: NSWritingDirectionLeftToRight|NSWritingDirectionEmbedding, RLE: NSWritingDirectionRightToLeft|NSWritingDirectionEmbedding, LRO: NSWritingDirectionLeftToRight|NSWritingDirectionOverride, RLO: NSWritingDirectionRightToLeft|NSWritingDirectionOverride,
public var verticalGlyphForm: Bool? // An NSNumber containing an integer value. 0 means horizontal text. 1 indicates vertical text. If not specified, it could follow higher-level vertical orientation settings. Currently on iOS, it's always horizontal. The behavior for any other value is undefined.
public var attributes: Attributes {
var attributes = Attributes()
font.map { attributes[.font] = $0 }
foregroundColor.map { attributes[.foregroundColor] = $0 }
backgroundColor.map { attributes[.backgroundColor] = $0 }
ligature.map { attributes[.ligature] = NSNumber(value: $0) }
kern.map { attributes[.kern] = NSNumber(value: $0) }
strikethroughStyle.map { attributes[.strikethroughStyle] = NSNumber(value: $0) }
underlineStyle.map { attributes[.underlineStyle] = NSNumber(value: $0) }
strokeColor.map { attributes[.strokeColor] = $0 }
strokeWidth.map { attributes[.strokeWidth] = $0 }
shadow.map { attributes[.shadow] = $0 }
textEffect.map { attributes[.textEffect] = NSString(string: $0) }
attachment.map { attributes[.attachment] = $0 }
link.map { attributes[.link] = $0 as NSURL }
baselineOffset.map { attributes[.baselineOffset] = NSNumber(value: $0) }
underlineColor.map { attributes[.underlineColor] = $0 }
strikethroughColor.map { attributes[.strikethroughColor] = $0 }
obliqueness.map { attributes[.obliqueness] = NSNumber(value: $0) }
expansion.map { attributes[.expansion] = NSNumber(value: $0) }
writingDirection.map { attributes[.writingDirection] = NSArray(array: $0.map(NSNumber.init)) }
verticalGlyphForm.map { attributes[.verticalGlyphForm] = NSNumber(value: $0) }
return attributes
}
}
class Builder: AttributesBuilder {
public var paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
public override var attributes: Attributes {
var attributes = super.attributes
attributes[.paragraphStyle] = paragraphStyle
return attributes
}
public var string: String = ""
private var attributedStrings = [(string: String, attributes: Attributes)]()
public func append(_ string: String, closure: (AttributesBuilder) -> () = {_ in}) {
let attributesBuilder = AttributesBuilder()
closure(attributesBuilder)
attributedStrings.append((string, attributesBuilder.attributes))
}
internal func build() -> NSAttributedString {
let completeString = string + attributedStrings.map({ $0.string }).joined()
guard completeString.isNotEmpty else {
fatalError("Builder should not build an empty string")
}
let mutableAttributedString = NSMutableAttributedString(string: completeString, attributes: attributes)
for attributedString in attributedStrings {
let range = completeString.range(of: attributedString.string)!
let nsRange = NSRange.init(range, in: completeString)
mutableAttributedString.addAttributes(attributedString.attributes, range: nsRange)
}
return mutableAttributedString
}
}
static func build(with closure: (Builder) -> ()) -> NSAttributedString {
let builder = Builder()
closure(builder)
return builder.build()
}
func modifiedAttributes(for string: String, closure: (AttributesBuilder) -> ()) -> NSAttributedString {
let builder = AttributesBuilder()
closure(builder)
let range = self.string.range(of: string)!
let nsRange = NSRange.init(range, in: self.string)
let mutableString = self.mutableCopy() as! NSMutableAttributedString
mutableString.addAttributes(builder.attributes, range: nsRange)
return mutableString
}
}
public extension NSParagraphStyle {
class Builder {
public var lineSpacing: CGFloat?
public var paragraphSpacing: CGFloat?
public var alignment: NSTextAlignment?
public var firstLineHeadIndent: CGFloat?
public var headIndent: CGFloat?
public var tailIndent: CGFloat?
public var lineBreakMode: NSLineBreakMode?
public var minimumLineHeight: CGFloat?
public var maximumLineHeight: CGFloat?
public var baseWritingDirection: NSWritingDirection?
public var lineHeightMultiple: CGFloat?
public var paragraphSpacingBefore: CGFloat?
public var hyphenationFactor: Float?
public var tabStops: [NSTextTab]?
public var defaultTabInterval: CGFloat?
public var allowsDefaultTighteningForTruncation: Bool?
// open var isConfigured: Bool {
// return lineSpacing != nil || alignment != nil
// }
internal func build() -> NSParagraphStyle {
let p = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
lineSpacing.map { p.lineSpacing = $0 }
paragraphSpacing.map { p.paragraphSpacing = $0 }
alignment.map { p.alignment = $0 }
firstLineHeadIndent.map { p.firstLineHeadIndent = $0 }
headIndent.map { p.headIndent = $0 }
tailIndent.map { p.tailIndent = $0 }
lineBreakMode.map { p.lineBreakMode = $0 }
minimumLineHeight.map { p.minimumLineHeight = $0 }
maximumLineHeight.map { p.maximumLineHeight = $0 }
baseWritingDirection.map { p.baseWritingDirection = $0 }
lineHeightMultiple.map { p.lineHeightMultiple = $0 }
paragraphSpacingBefore.map { p.paragraphSpacingBefore = $0 }
hyphenationFactor.map { p.hyphenationFactor = $0 }
tabStops.map { p.tabStops = $0 }
defaultTabInterval.map { p.defaultTabInterval = $0 }
allowsDefaultTighteningForTruncation.map { p.allowsDefaultTighteningForTruncation = $0 }
return p
}
}
}
| mit | cbb947b8d173cbf3ddcff8507f2a90b6 | 41.771574 | 546 | 0.745787 | 4.437072 | 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.