repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JaSpa/swift | refs/heads/master | test/DebugInfo/bbentry-location.swift | apache-2.0 | 26 | // REQUIRES: OS=ios
// REQUIRES: objc_interop
// RUN: %target-swift-frontend -emit-ir -g %s -o - | %FileCheck %s
import UIKit
@available(iOS, introduced: 8.0)
class ActionViewController
{
var imageView: UIImageView!
func viewDidLoad(_ inputItems: [Any]) {
for item in inputItems {
let inputItem = item as! NSExtensionItem
for provider in inputItem.attachments! {
let itemProvider = provider as! NSItemProvider
// CHECK: load {{.*}}selector
// CHECK:; <label>{{.*}} ; preds = %{{[0-9]+}}
// CHECK: @swift_rt_swift_allocObject({{.*}}, !dbg ![[DBG:[0-9]+]]
// Test that the location is reset at the entry of a new basic block.
// CHECK: ![[DBG]] = {{.*}}line: 0
if itemProvider.hasItemConformingToTypeIdentifier("") {
weak var weakImageView = self.imageView
itemProvider.loadItem(forTypeIdentifier: "", options: nil,
completionHandler: { (image, error) in
if let imageView = weakImageView {
}
})
}
}
}
}
}
| cd683586e7ac9c317173cc1755c01363 | 32.677419 | 77 | 0.599617 | false | false | false | false |
CNKCQ/DigitalKeyboard | refs/heads/master | DigitalKeyboard/Classes/DigitalKeyboard.swift | mit | 1 | //
// DigitalKeyboard.swift
// KeyBoard forKey
//
// Created by Jack on 16/9/15.
// Copyright © 2016年 Jack. All rights reserved.
//
import UIKit
import LocalAuthentication
extension UIDevice {
/// is iPhone X ?
///
/// - Returns: iPhone X
public var iPhoneXSeries: Bool {
if (UIDevice.current.userInterfaceIdiom != .phone) {
return false;
}
if #available(iOS 11.0, *) {
let mainWindow: UIWindow! = UIApplication.shared.delegate!.window!
if (mainWindow.safeAreaInsets.bottom > 0.0) {
return true
}
}
return false
}
}
private let marginvalue = CGFloat(0.5)
private let screenWith = UIScreen.main.bounds.size.width
private let safeAreaHeight: CGFloat = 224.0
private let dkAreaHeight: CGFloat = UIDevice().iPhoneXSeries ? safeAreaHeight + 34 : safeAreaHeight
public enum DKStyle {
case idcard
case number
}
public protocol DigitalKeyboardDelete: NSObjectProtocol {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: UITextRange, replacementString string: String) -> Bool
}
public class DigitalKeyboard: UIInputView {
public static let `default` = DigitalKeyboard(frame: CGRect(x: 0, y: 0, width: screenWith, height: dkAreaHeight), inputViewStyle: .keyboard)
public static let defaultDoneColor = UIColor(red: 28 / 255, green: 171 / 255, blue: 235 / 255, alpha: 1)
public var accessoryView: UIView?
public var dkstyle = DKStyle.idcard {
didSet {
setDigitButton(style: dkstyle)
}
}
public var isSafety: Bool = false {
didSet {
if isSafety {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotify(notifiction:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
}
}
public var shouldHighlight = true {
didSet {
highlight(heghlight: shouldHighlight)
}
}
public func customDoneButton(title: String, titleColor: UIColor = UIColor.white, theme: UIColor = DigitalKeyboard.defaultDoneColor, target: UIViewController? = nil, callback: Selector? = nil) {
setDoneButton(title: title, titleColor: titleColor, theme: theme, target: target, callback: callback)
}
private var textFields = [UITextField]()
private var superView: UIView?
private var buttions: [UIButton] = []
private lazy var bottomView: UIView = {
let subView: UIView = UIView(frame: CGRect(x: 0, y: safeAreaHeight + marginvalue * 4, width: screenWith, height: 44))
subView.backgroundColor = .white
return subView;
}()
public var delegate: DigitalKeyboardDelete?
public convenience init(_ view: UIView, accessoryView: UIView? = nil, field: UITextField? = nil) {
self.init(frame: CGRect.zero, inputViewStyle: .keyboard)
self.accessoryView = accessoryView
addKeyboard(view, field: field)
}
private override init(frame _: CGRect, inputViewStyle: UIInputView.Style) {
super.init(frame: CGRect(x: 0, y: 0, width: screenWith, height: dkAreaHeight), inputViewStyle: inputViewStyle)
backgroundColor = .lightGray
}
public required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func addKeyboard(_ view: UIView, field: UITextField? = nil) {
superView = view
customSubview()
if let textField = field {
textFields.append(textField)
textField.inputView = self
textField.inputAccessoryView = accessoryView
} else {
for view in (superView?.subviews)! {
if view.isKind(of: UITextField.self) {
let textField = view as! UITextField
textField.inputView = self
textField.inputAccessoryView = accessoryView
textFields.append(textField)
}
}
}
}
private func customSubview() {
var backSpace: UIImage?
var dismiss: UIImage?
let podBundle = Bundle(for: classForCoder)
if let bundleURL = podBundle.url(forResource: "DigitalKeyboard", withExtension: "bundle") {
if let bundle = Bundle(url: bundleURL) {
backSpace = UIImage(named: "Keyboard_Backspace", in: bundle, compatibleWith: nil)
dismiss = UIImage(named: "Keyboard_DismissKey", in: bundle, compatibleWith: nil)
} else {
backSpace = UIImage(named: "Keyboard_Backspace")
dismiss = UIImage(named: "Keyboard_DismissKey")
}
} else {
backSpace = UIImage(named: "Keyboard_Backspace")
dismiss = UIImage(named: "Keyboard_DismissKey")
}
for idx in 0 ... 13 {
let button = UIButton()
button.titleLabel?.font = UIFont.systemFont(ofSize: 28)
button.backgroundColor = UIColor.white
button.tag = idx
highlight(heghlight: shouldHighlight)
addSubview(button)
addSubview(self.bottomView)
button.setTitleColor(UIColor.black, for: .normal)
switch idx {
case 9:
button.setTitle("", for: .normal)
button.setImage(dismiss, for: .normal)
case 10:
button.setTitle("0", for: .normal)
buttions.append(button)
case 11:
button.setTitle("X", for: .normal)
case 12:
button.setTitle("", for: .normal)
button.setImage(backSpace, for: .normal)
case 13:
button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
button.backgroundColor = DigitalKeyboard.defaultDoneColor
button.setTitleColor(UIColor.white, for: .normal)
button.setBackgroundImage(nil, for: .normal)
button.setBackgroundImage(nil, for: .highlighted)
button.setTitle(LocalizedString(key: "Done"), for: .normal)
default:
button.setTitle("\(idx + 1)", for: .normal)
buttions.append(button)
}
button.addTarget(self, action: #selector(tap), for: .touchUpInside)
}
}
@objc func tap(sender: UIButton) {
guard let text = sender.currentTitle else {
fatalError("not found the sender's currentTitle")
}
switch sender.tag {
case 12:
firstResponder()?.deleteBackward()
case 13, 9:
firstResponder()?.resignFirstResponder()
default:
if let proxy = self.delegate, let responderField = firstResponder(), let range = responderField.selectedTextRange {
if proxy.textField(responderField, shouldChangeCharactersIn: range, replacementString: text) {
firstResponder()?.insertText(text)
}
} else {
firstResponder()?.insertText(text)
}
}
}
func firstResponder() -> UITextField? {
var firstResponder: UITextField?
for field in textFields {
if field.isFirstResponder {
firstResponder = field
}
}
return firstResponder
}
public override func layoutSubviews() {
super.layoutSubviews()
for view in subviews {
if view.isKind(of: UIButton.self) {
let width = frame.width / 4 * 3
let idx = view.tag
if idx >= 12 {
view.frame = CGRect(x: width + marginvalue, y: CGFloat((idx - 12) % 2) * (safeAreaHeight / 2.0 + marginvalue), width: frame.width / 4, height: (safeAreaHeight - marginvalue) / 2.0)
} else {
view.frame = CGRect(x: CGFloat(idx % 3) * ((width - 2 * marginvalue) / 3 + marginvalue), y: CGFloat(idx / 3) * (safeAreaHeight / 4.0 + marginvalue), width: (width - 2 * marginvalue) / 3, height: safeAreaHeight / 4.0)
}
}
}
}
func highlight(heghlight: Bool) {
for view in subviews {
if let button = view as? UIButton {
if button.tag == 13 { return }
if heghlight {
button.setBackgroundImage(UIImage.dk_image(with: .white), for: .normal)
button.setBackgroundImage(UIImage.dk_image(with: .lightGray), for: .highlighted)
} else {
button.setBackgroundImage(UIImage.dk_image(with: .white), for: .normal)
button.setBackgroundImage(UIImage.dk_image(with: .white), for: .highlighted)
}
}
}
}
func setDigitButton(style: DKStyle) {
guard let button = findButton(by: 11) else {
fatalError("not found the button with the tag")
}
switch style {
case .idcard:
button.setTitle("X", for: .normal)
case .number:
let locale = Locale.current
let decimalSeparator = locale.decimalSeparator! as String
button.setTitle(decimalSeparator, for: .normal)
}
}
func findButton(by tag: Int) -> UIButton? {
for button in subviews {
if button.tag == tag {
return button as? UIButton
}
}
return nil
}
func LocalizedString(key: String) -> String {
return (Bundle(identifier: "com.apple.UIKit")?.localizedString(forKey: key, value: nil, table: nil))!
}
func setDoneButton(title: String, titleColor: UIColor, theme: UIColor, target: UIViewController?, callback: Selector?) {
guard let itemButton = findButton(by: 13) else {
fatalError("not found the button with the tag")
}
if let selector = callback, let target = target {
itemButton.addTarget(target, action: selector, for: .touchUpInside)
}
itemButton.titleLabel?.font = UIFont.systemFont(ofSize: 17)
itemButton.setTitle(title, for: .normal)
itemButton.backgroundColor = theme
itemButton.setTitleColor(titleColor, for: .normal)
}
@objc func keyboardWillShowNotify(notifiction _: NSNotification) {
titles = titles.sorted { _, _ in
arc4random() < arc4random()
}
if !buttions.isEmpty {
for (idx, item) in buttions.enumerated() {
item.setTitle(titles[idx], for: .normal)
}
}
}
private lazy var titles = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
}
extension UIImage {
public class func dk_image(with color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
UIGraphicsBeginImageContext(size)
color.set()
UIRectFill(CGRect(origin: CGPoint.zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
// MARK: UIInputViewAudioFeedback
extension DigitalKeyboard: UIInputViewAudioFeedback {
open var enableInputClicksWhenVisible: Bool {
return true
}
}
| 0a776e93e0de42726e5d42af4a69d234 | 35.931373 | 236 | 0.58747 | false | false | false | false |
hanhailong/practice-swift | refs/heads/master | Calendar/Adding Alarms to Calendars/Adding Alarms to Calendars/AppDelegate.swift | mit | 2 | //
// AppDelegate.swift
// Adding Alarms to Calendars
//
// Created by Domenico on 25/05/15.
// License MIT
//
import UIKit
import EventKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.requestAuthorization()
return true
}
// Request calendar authorization
func requestAuthorization(){
let eventStore = EKEventStore()
switch EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent){
case .Authorized:
addAlarmToCalendarWithStore(eventStore)
case .Denied:
displayAccessDenied()
case .NotDetermined:
eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion:
{[weak self] (granted: Bool, error: NSError!) -> Void in
if granted{
self!.addAlarmToCalendarWithStore(eventStore)
} else {
self!.displayAccessDenied()
}
})
case .Restricted:
displayAccessRestricted()
}
}
// Find source in the event store
func sourceInEventStore(
eventStore: EKEventStore,
type: EKSourceType,
title: String) -> EKSource?{
for source in eventStore.sources() as! [EKSource]{
if source.sourceType.value == type.value &&
source.title.caseInsensitiveCompare(title) ==
NSComparisonResult.OrderedSame{
return source
}
}
return nil
}
// Find calendar by Title
func calendarWithTitle(
title: String,
type: EKCalendarType,
source: EKSource,
eventType: EKEntityType) -> EKCalendar?{
for calendar in source.calendarsForEntityType(eventType)
as! Set<EKCalendar>{
if calendar.title.caseInsensitiveCompare(title) ==
NSComparisonResult.OrderedSame &&
calendar.type.value == type.value{
return calendar
}
}
return nil
}
func addAlarmToCalendarWithStore(store: EKEventStore, calendar: EKCalendar){
/* The event starts 60 seconds from now */
let startDate = NSDate(timeIntervalSinceNow: 60.0)
/* And end the event 20 seconds after its start date */
let endDate = startDate.dateByAddingTimeInterval(20.0)
let eventWithAlarm = EKEvent(eventStore: store)
eventWithAlarm.calendar = calendar
eventWithAlarm.startDate = startDate
eventWithAlarm.endDate = endDate
/* The alarm goes off 2 seconds before the event happens */
let alarm = EKAlarm(relativeOffset: -2.0)
eventWithAlarm.title = "Event with Alarm"
eventWithAlarm.addAlarm(alarm)
var error:NSError?
if store.saveEvent(eventWithAlarm, span: EKSpanThisEvent, error: &error){
println("Saved an event that fires 60 seconds from now.")
} else if let theError = error{
println("Failed to save the event. Error = \(theError)")
}
}
func addAlarmToCalendarWithStore(store: EKEventStore){
let icloudSource = sourceInEventStore(store,
type: EKSourceTypeCalDAV,
title: "iCloud")
if icloudSource == nil{
println("You have not configured iCloud for your device.")
return
}
let calendar = calendarWithTitle("Calendar",
type: EKCalendarTypeCalDAV,
source: icloudSource!,
eventType: EKEntityTypeEvent)
if calendar == nil{
println("Could not find the calendar we were looking for.")
return
}
addAlarmToCalendarWithStore(store, calendar: calendar!)
}
//- MARK: Helper methods
func displayAccessDenied(){
println("Access to the event store is denied.")
}
func displayAccessRestricted(){
println("Access to the event store is restricted.")
}
}
| 414fe3b833be516ca4c1577bf3e2e51a | 29.70068 | 127 | 0.56437 | false | false | false | false |
alantsev/mal | refs/heads/master | swift3/Sources/types.swift | mpl-2.0 | 3 |
enum MalError: ErrorType {
case Reader(msg: String)
case General(msg: String)
case MalException(obj: MalVal)
}
class MutableAtom {
var val: MalVal
init(val: MalVal) {
self.val = val
}
}
enum MalVal {
case MalNil
case MalTrue
case MalFalse
case MalInt(Int)
case MalFloat(Float)
case MalString(String)
case MalSymbol(String)
case MalList(Array<MalVal>, meta: Array<MalVal>?)
case MalVector(Array<MalVal>, meta: Array<MalVal>?)
case MalHashMap(Dictionary<String,MalVal>, meta: Array<MalVal>?)
// TODO: internal MalVals are wrapped in arrays because otherwise
// compiler throws a fault
case MalFunc((Array<MalVal>) throws -> MalVal,
ast: Array<MalVal>?,
env: Env?,
params: Array<MalVal>?,
macro: Bool,
meta: Array<MalVal>?)
case MalAtom(MutableAtom)
}
typealias MV = MalVal
// General functions
func wraptf(a: Bool) -> MalVal {
return a ? MV.MalTrue : MV.MalFalse
}
// equality functions
func cmp_seqs(a: Array<MalVal>, _ b: Array<MalVal>) -> Bool {
if a.count != b.count { return false }
var idx = a.startIndex
while idx < a.endIndex {
if !equal_Q(a[idx], b[idx]) { return false }
idx = idx.successor()
}
return true
}
func cmp_maps(a: Dictionary<String,MalVal>,
_ b: Dictionary<String,MalVal>) -> Bool {
if a.count != b.count { return false }
for (k,v1) in a {
if b[k] == nil { return false }
if !equal_Q(v1, b[k]!) { return false }
}
return true
}
func equal_Q(a: MalVal, _ b: MalVal) -> Bool {
switch (a, b) {
case (MV.MalNil, MV.MalNil): return true
case (MV.MalFalse, MV.MalFalse): return true
case (MV.MalTrue, MV.MalTrue): return true
case (MV.MalInt(let i1), MV.MalInt(let i2)): return i1 == i2
case (MV.MalString(let s1), MV.MalString(let s2)): return s1 == s2
case (MV.MalSymbol(let s1), MV.MalSymbol(let s2)): return s1 == s2
case (MV.MalList(let l1,_), MV.MalList(let l2,_)):
return cmp_seqs(l1, l2)
case (MV.MalList(let l1,_), MV.MalVector(let l2,_)):
return cmp_seqs(l1, l2)
case (MV.MalVector(let l1,_), MV.MalList(let l2,_)):
return cmp_seqs(l1, l2)
case (MV.MalVector(let l1,_), MV.MalVector(let l2,_)):
return cmp_seqs(l1, l2)
case (MV.MalHashMap(let d1,_), MV.MalHashMap(let d2,_)):
return cmp_maps(d1, d2)
default:
return false
}
}
// list and vector functions
func list(lst: Array<MalVal>) -> MalVal {
return MV.MalList(lst, meta:nil)
}
func list(lst: Array<MalVal>, meta: MalVal) -> MalVal {
return MV.MalList(lst, meta:[meta])
}
func vector(lst: Array<MalVal>) -> MalVal {
return MV.MalVector(lst, meta:nil)
}
func vector(lst: Array<MalVal>, meta: MalVal) -> MalVal {
return MV.MalVector(lst, meta:[meta])
}
// hash-map functions
func _assoc(src: Dictionary<String,MalVal>, _ mvs: Array<MalVal>)
throws -> Dictionary<String,MalVal> {
var d = src
if mvs.count % 2 != 0 {
throw MalError.General(msg: "Odd number of args to assoc_BANG")
}
var pos = mvs.startIndex
while pos < mvs.count {
switch (mvs[pos], mvs[pos+1]) {
case (MV.MalString(let k), let mv):
d[k] = mv
default:
throw MalError.General(msg: "Invalid _assoc call")
}
pos += 2
}
return d
}
func _dissoc(src: Dictionary<String,MalVal>, _ mvs: Array<MalVal>)
throws -> Dictionary<String,MalVal> {
var d = src
for mv in mvs {
switch mv {
case MV.MalString(let k): d.removeValueForKey(k)
default: throw MalError.General(msg: "Invalid _dissoc call")
}
}
return d
}
func hash_map(dict: Dictionary<String,MalVal>) -> MalVal {
return MV.MalHashMap(dict, meta:nil)
}
func hash_map(dict: Dictionary<String,MalVal>, meta:MalVal) -> MalVal {
return MV.MalHashMap(dict, meta:[meta])
}
func hash_map(arr: Array<MalVal>) throws -> MalVal {
let d = Dictionary<String,MalVal>();
return MV.MalHashMap(try _assoc(d, arr), meta:nil)
}
// function functions
func malfunc(fn: (Array<MalVal>) throws -> MalVal) -> MalVal {
return MV.MalFunc(fn, ast: nil, env: nil, params: nil,
macro: false, meta: nil)
}
func malfunc(fn: (Array<MalVal>) throws -> MalVal,
ast: Array<MalVal>?,
env: Env?,
params: Array<MalVal>?) -> MalVal {
return MV.MalFunc(fn, ast: ast, env: env, params: params,
macro: false, meta: nil)
}
func malfunc(fn: (Array<MalVal>) throws -> MalVal,
ast: Array<MalVal>?,
env: Env?,
params: Array<MalVal>?,
macro: Bool,
meta: MalVal?) -> MalVal {
return MV.MalFunc(fn, ast: ast, env: env, params: params,
macro: macro, meta: meta != nil ? [meta!] : nil)
}
func malfunc(fn: (Array<MalVal>) throws -> MalVal,
ast: Array<MalVal>?,
env: Env?,
params: Array<MalVal>?,
macro: Bool,
meta: Array<MalVal>?) -> MalVal {
return MV.MalFunc(fn, ast: ast, env: env, params: params,
macro: macro, meta: meta)
}
// sequence functions
func _rest(a: MalVal) throws -> Array<MalVal> {
switch a {
case MV.MalList(let lst,_):
let slc = lst[lst.startIndex.successor()..<lst.endIndex]
return Array(slc)
case MV.MalVector(let lst,_):
let slc = lst[lst.startIndex.successor()..<lst.endIndex]
return Array(slc)
default:
throw MalError.General(msg: "Invalid rest call")
}
}
func rest(a: MalVal) throws -> MalVal {
return list(try _rest(a))
}
func _nth(a: MalVal, _ idx: Int) throws -> MalVal {
switch a {
case MV.MalList(let l,_): return l[l.startIndex.advancedBy(idx)]
case MV.MalVector(let l,_): return l[l.startIndex.advancedBy(idx)]
default: throw MalError.General(msg: "Invalid nth call")
}
}
| e3753fa357c7a3bb1ca87e8ceb713da9 | 27.938095 | 71 | 0.587296 | false | false | false | false |
apple/swift-nio-ssl | refs/heads/main | apache-2.0 | 1 | // swift-tools-version:5.5
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import PackageDescription
// Used only for environment variables, does not make its way
// into the product code.
import class Foundation.ProcessInfo
// This package contains a vendored copy of BoringSSL. For ease of tracking
// down problems with the copy of BoringSSL in use, we include a copy of the
// commit hash of the revision of BoringSSL included in the given release.
// This is also reproduced in a file called hash.txt in the
// Sources/CNIOBoringSSL directory. The source repository is at
// https://boringssl.googlesource.com/boringssl.
//
// BoringSSL Commit: b819f7e9392d25db6705a6bd3c92be3bb91775e2
/// This function generates the dependencies we want to express.
///
/// Importantly, it tolerates the possibility that we are being used as part
/// of the Swift toolchain, and so need to use local checkouts of our
/// dependencies.
func generateDependencies() -> [Package.Dependency] {
if ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {
return [
.package(url: "https://github.com/apple/swift-nio.git", from: "2.42.0"),
]
} else {
return [
.package(path: "../swift-nio"),
]
}
}
let package = Package(
name: "swift-nio-ssl",
products: [
.library(name: "NIOSSL", targets: ["NIOSSL"]),
.executable(name: "NIOTLSServer", targets: ["NIOTLSServer"]),
.executable(name: "NIOSSLHTTP1Client", targets: ["NIOSSLHTTP1Client"]),
/* This target is used only for symbol mangling. It's added and removed automatically because it emits build warnings. MANGLE_START
.library(name: "CNIOBoringSSL", type: .static, targets: ["CNIOBoringSSL"]),
MANGLE_END */
],
dependencies: generateDependencies(),
targets: [
.target(name: "CNIOBoringSSL"),
.target(
name: "CNIOBoringSSLShims",
dependencies: [
"CNIOBoringSSL"
]),
.target(
name: "NIOSSL",
dependencies: [
"CNIOBoringSSL",
"CNIOBoringSSLShims",
.product(name: "NIO", package: "swift-nio"),
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOConcurrencyHelpers", package: "swift-nio"),
.product(name: "NIOTLS", package: "swift-nio"),
]),
.executableTarget(
name: "NIOTLSServer",
dependencies: [
"NIOSSL",
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOPosix", package: "swift-nio"),
.product(name: "NIOConcurrencyHelpers", package: "swift-nio"),
],
exclude: [
"README.md"
]),
.executableTarget(
name: "NIOSSLHTTP1Client",
dependencies: [
"NIOSSL",
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOPosix", package: "swift-nio"),
.product(name: "NIOHTTP1", package: "swift-nio"),
.product(name: "NIOFoundationCompat", package: "swift-nio"),
],
exclude: [
"README.md"
]),
.executableTarget(
name: "NIOSSLPerformanceTester",
dependencies: [
"NIOSSL",
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOEmbedded", package: "swift-nio"),
.product(name: "NIOTLS", package: "swift-nio"),
]),
.testTarget(
name: "NIOSSLTests",
dependencies: [
"NIOSSL",
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOEmbedded", package: "swift-nio"),
.product(name: "NIOPosix", package: "swift-nio"),
.product(name: "NIOTLS", package: "swift-nio"),
]),
],
cxxLanguageStandard: .cxx14
)
| 7a68ad6689fce842189fd91e6ad84598 | 37.423729 | 131 | 0.557345 | false | false | false | false |
|
LoopKit/LoopKit | refs/heads/dev | LoopKitUI/View Controllers/DismissibleHostingController.swift | mit | 1 | //
// DismissibleHostingController.swift
// LoopKitUI
//
// Created by Michael Pangburn on 5/7/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import SwiftUI
public class DismissibleHostingController: UIHostingController<AnyView> {
public enum DismissalMode {
case modalDismiss
case pop(to: UIViewController.Type)
}
private var onDisappear: () -> Void = {}
public convenience init<Content: View> (
rootView: Content,
dismissalMode: DismissalMode = .modalDismiss,
isModalInPresentation: Bool = true,
onDisappear: @escaping () -> Void = {},
colorPalette: LoopUIColorPalette
) {
self.init(rootView: rootView,
dismissalMode: dismissalMode,
isModalInPresentation: isModalInPresentation,
onDisappear: onDisappear,
guidanceColors: colorPalette.guidanceColors,
carbTintColor: colorPalette.carbTintColor,
glucoseTintColor: colorPalette.glucoseTintColor,
insulinTintColor: colorPalette.insulinTintColor)
}
public convenience init<Content: View>(
rootView: Content,
dismissalMode: DismissalMode = .modalDismiss,
isModalInPresentation: Bool = true,
onDisappear: @escaping () -> Void = {},
guidanceColors: GuidanceColors = GuidanceColors(),
carbTintColor: Color = .green,
glucoseTintColor: Color = Color(.systemTeal),
insulinTintColor: Color = .orange
) {
// Delay initialization of dismissal closure pushed into SwiftUI Environment until after calling the designated initializer
var dismiss = {}
self.init(rootView: AnyView(rootView.environment(\.dismissAction, { dismiss() })
.environment(\.guidanceColors, guidanceColors)
.environment(\.carbTintColor, carbTintColor)
.environment(\.glucoseTintColor, glucoseTintColor)
.environment(\.insulinTintColor, insulinTintColor)))
switch dismissalMode {
case .modalDismiss:
dismiss = { [weak self] in self?.dismiss(animated: true) }
case .pop(to: let PredecessorViewController):
dismiss = { [weak self] in
guard
let navigationController = self?.navigationController,
let predecessor = navigationController.viewControllers.last(where: { $0.isKind(of: PredecessorViewController) })
else {
return
}
navigationController.popToViewController(predecessor, animated: true)
}
}
self.onDisappear = onDisappear
self.isModalInPresentation = isModalInPresentation
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
onDisappear()
}
}
| 7bf4c44dbe4f4410828bf390aa8d1010 | 36.423077 | 132 | 0.631723 | false | false | false | false |
JackEsad/Eureka | refs/heads/master | Eureka-master/Example/Example/CustomRows/ImageRow/ImageRow.swift | gpl-3.0 | 6 | // ImageRow.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
import Eureka
public struct ImageRowSourceTypes : OptionSet {
public let rawValue: Int
public var imagePickerControllerSourceTypeRawValue: Int { return self.rawValue >> 1 }
public init(rawValue: Int) { self.rawValue = rawValue }
init(_ sourceType: UIImagePickerControllerSourceType) { self.init(rawValue: 1 << sourceType.rawValue) }
public static let PhotoLibrary = ImageRowSourceTypes(.photoLibrary)
public static let Camera = ImageRowSourceTypes(.camera)
public static let SavedPhotosAlbum = ImageRowSourceTypes(.savedPhotosAlbum)
public static let All: ImageRowSourceTypes = [Camera, PhotoLibrary, SavedPhotosAlbum]
}
extension ImageRowSourceTypes {
// MARK: Helpers
var localizedString: String {
switch self {
case ImageRowSourceTypes.Camera:
return "Take photo"
case ImageRowSourceTypes.PhotoLibrary:
return "Photo Library"
case ImageRowSourceTypes.SavedPhotosAlbum:
return "Saved Photos"
default:
return ""
}
}
}
public enum ImageClearAction {
case no
case yes(style: UIAlertActionStyle)
}
//MARK: Row
open class _ImageRow<Cell: CellType>: SelectorRow<Cell, ImagePickerController> where Cell: BaseCell, Cell: TypedCellType, Cell.Value == UIImage {
open var sourceTypes: ImageRowSourceTypes
open internal(set) var imageURL: URL?
open var clearAction = ImageClearAction.yes(style: .destructive)
private var _sourceType: UIImagePickerControllerSourceType = .camera
public required init(tag: String?) {
sourceTypes = .All
super.init(tag: tag)
presentationMode = .presentModally(controllerProvider: ControllerProvider.callback { return ImagePickerController() }, onDismiss: { [weak self] vc in
self?.select()
vc.dismiss(animated: true)
})
self.displayValueFor = nil
}
// copy over the existing logic from the SelectorRow
func displayImagePickerController(_ sourceType: UIImagePickerControllerSourceType) {
if let presentationMode = presentationMode, !isDisabled {
if let controller = presentationMode.makeController(){
controller.row = self
controller.sourceType = sourceType
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.present(controller, row: self, presentingController: cell.formViewController()!)
}
else{
_sourceType = sourceType
presentationMode.present(nil, row: self, presentingController: cell.formViewController()!)
}
}
}
open override func customDidSelect() {
guard !isDisabled else {
super.customDidSelect()
return
}
deselect()
var availableSources: ImageRowSourceTypes = []
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let _ = availableSources.insert(.PhotoLibrary)
}
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let _ = availableSources.insert(.Camera)
}
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
let _ = availableSources.insert(.SavedPhotosAlbum)
}
sourceTypes.formIntersection(availableSources)
if sourceTypes.isEmpty {
super.customDidSelect()
return
}
// now that we know the number of actions aren't empty
let sourceActionSheet = UIAlertController(title: nil, message: selectorTitle, preferredStyle: .actionSheet)
guard let tableView = cell.formViewController()?.tableView else { fatalError() }
if let popView = sourceActionSheet.popoverPresentationController {
popView.sourceView = tableView
popView.sourceRect = tableView.convert(cell.accessoryView?.frame ?? cell.contentView.frame, from: cell)
}
createOptionsForAlertController(sourceActionSheet)
if case .yes(let style) = clearAction, value != nil {
let clearPhotoOption = UIAlertAction(title: NSLocalizedString("Clear Photo", comment: ""), style: style, handler: { [weak self] _ in
self?.value = nil
self?.imageURL = nil
self?.updateCell()
})
sourceActionSheet.addAction(clearPhotoOption)
}
// check if we have only one source type given
if sourceActionSheet.actions.count == 1 {
if let imagePickerSourceType = UIImagePickerControllerSourceType(rawValue: sourceTypes.imagePickerControllerSourceTypeRawValue) {
displayImagePickerController(imagePickerSourceType)
}
} else {
let cancelOption = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler:nil)
sourceActionSheet.addAction(cancelOption)
if let presentingViewController = cell.formViewController() {
presentingViewController.present(sourceActionSheet, animated: true)
}
}
}
open override func prepare(for segue: UIStoryboardSegue) {
super.prepare(for: segue)
guard let rowVC = segue.destination as? ImagePickerController else {
return
}
rowVC.sourceType = _sourceType
}
open override func customUpdateCell() {
super.customUpdateCell()
cell.accessoryType = .none
if let image = self.value {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
imageView.contentMode = .scaleAspectFill
imageView.image = image
imageView.clipsToBounds = true
cell.accessoryView = imageView
}
else{
cell.accessoryView = nil
}
}
}
extension _ImageRow {
//MARK: Helpers
func createOptionForAlertController(_ alertController: UIAlertController, sourceType: ImageRowSourceTypes) {
guard let pickerSourceType = UIImagePickerControllerSourceType(rawValue: sourceType.imagePickerControllerSourceTypeRawValue), sourceTypes.contains(sourceType) else { return }
let option = UIAlertAction(title: NSLocalizedString(sourceType.localizedString, comment: ""), style: .default, handler: { [weak self] _ in
self?.displayImagePickerController(pickerSourceType)
})
alertController.addAction(option)
}
func createOptionsForAlertController(_ alertController: UIAlertController) {
createOptionForAlertController(alertController, sourceType: .Camera)
createOptionForAlertController(alertController, sourceType: .PhotoLibrary)
createOptionForAlertController(alertController, sourceType: .SavedPhotosAlbum)
}
}
/// A selector row where the user can pick an image
public final class ImageRow : _ImageRow<PushSelectorCell<UIImage>>, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
| 4be930ecb0412c8799e13624ab11b4e8 | 38.905213 | 182 | 0.669952 | false | false | false | false |
fgengine/quickly | refs/heads/master | Quickly/ViewControllers/Stack/Animation/QStackViewControllerInteractiveAnimation.swift | mit | 1 | //
// Quickly
//
public final class QStackViewControllerinteractiveDismissAnimation : IQStackViewControllerInteractiveDismissAnimation {
public var containerViewController: IQStackContainerViewController!
public var shadow: QViewShadow
public var currentBeginFrame: CGRect
public var currentEndFrame: CGRect
public var currentViewController: IQStackViewController!
public var currentGroupbarVisibility: CGFloat
public var previousBeginFrame: CGRect
public var previousEndFrame: CGRect
public var previousViewController: IQStackViewController!
public var previousGroupbarVisibility: CGFloat
public var position: CGPoint
public var deltaPosition: CGFloat
public var velocity: CGPoint
public var distance: CGFloat
public var dismissDistanceRate: CGFloat
public var overlapping: CGFloat
public var acceleration: CGFloat
public var ease: IQAnimationEase
public private(set) var canFinish: Bool
public init(
shadow: QViewShadow = QViewShadow(color: UIColor.black, opacity: 0.45, radius: 6, offset: CGSize.zero),
overlapping: CGFloat = 1,
acceleration: CGFloat = 1200,
dismissDistanceRate: CGFloat = 0.4,
ease: IQAnimationEase = QAnimationEaseQuadraticOut()
) {
self.shadow = shadow
self.currentBeginFrame = CGRect.zero
self.currentEndFrame = CGRect.zero
self.currentGroupbarVisibility = 1
self.previousBeginFrame = CGRect.zero
self.previousEndFrame = CGRect.zero
self.previousGroupbarVisibility = 1
self.position = CGPoint.zero
self.deltaPosition = 0
self.velocity = CGPoint.zero
self.distance = 0
self.dismissDistanceRate = dismissDistanceRate
self.overlapping = overlapping
self.acceleration = acceleration
self.ease = ease
self.canFinish = false
}
public func prepare(
containerViewController: IQStackContainerViewController,
contentView: UIView,
currentViewController: IQStackViewController,
currentGroupbarVisibility: CGFloat,
previousViewController: IQStackViewController,
previousGroupbarVisibility: CGFloat,
position: CGPoint,
velocity: CGPoint
) {
let bounds = contentView.bounds
self.containerViewController = containerViewController
self.currentBeginFrame = bounds
self.currentEndFrame = CGRect(
x: bounds.maxX,
y: bounds.minY,
width: bounds.width,
height: bounds.height
)
self.currentViewController = currentViewController
self.currentViewController.view.frame = self.currentBeginFrame
self.currentViewController.view.shadow = self.shadow
self.currentViewController.layoutIfNeeded()
self.currentViewController.prepareInteractiveDismiss()
self.currentGroupbarVisibility = currentGroupbarVisibility
self.previousBeginFrame = CGRect(
x: bounds.minX - (bounds.width * self.overlapping),
y: bounds.minY,
width: bounds.width,
height: bounds.height
)
self.previousEndFrame = bounds
self.previousViewController = previousViewController
self.previousViewController.view.frame = self.previousBeginFrame
self.previousViewController.layoutIfNeeded()
self.previousViewController.prepareInteractivePresent()
self.previousGroupbarVisibility = previousGroupbarVisibility
self.position = position
self.velocity = velocity
self.distance = bounds.width
containerViewController.groupbarVisibility = currentGroupbarVisibility
contentView.insertSubview(currentViewController.view, aboveSubview: previousViewController.view)
}
public func update(position: CGPoint, velocity: CGPoint) {
self.deltaPosition = self.ease.lerp(max(0, position.x - self.position.x), from: 0, to: self.distance)
let progress = self.deltaPosition / self.distance
self.containerViewController.groupbarVisibility = self.currentGroupbarVisibility.lerp(self.previousGroupbarVisibility, progress: progress)
self.currentViewController.view.frame = self.currentBeginFrame.lerp(self.currentEndFrame, progress: progress)
self.previousViewController.view.frame = self.previousBeginFrame.lerp(self.previousEndFrame, progress: progress)
self.canFinish = self.deltaPosition > (self.distance * self.dismissDistanceRate)
}
public func finish(_ complete: @escaping (_ completed: Bool) -> Void) {
let duration = TimeInterval((self.distance - self.deltaPosition) / self.acceleration)
UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
self.containerViewController.groupbarVisibility = self.previousGroupbarVisibility
self.currentViewController.view.frame = self.currentEndFrame
self.previousViewController.view.frame = self.previousEndFrame
}, completion: { [weak self] (completed: Bool) in
if let self = self {
self.containerViewController.groupbarVisibility = self.previousGroupbarVisibility
self.containerViewController = nil
self.currentViewController.view.frame = self.currentEndFrame
self.currentViewController.view.shadow = nil
self.currentViewController.finishInteractiveDismiss()
self.currentViewController = nil
self.previousViewController.view.frame = self.previousEndFrame
self.previousViewController.finishInteractivePresent()
self.previousViewController = nil
}
complete(completed)
})
}
public func cancel(_ complete: @escaping (_ completed: Bool) -> Void) {
let duration = TimeInterval(self.deltaPosition / self.acceleration)
UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
self.containerViewController.groupbarVisibility = self.currentGroupbarVisibility
self.currentViewController.view.frame = self.currentBeginFrame
self.previousViewController.view.frame = self.previousBeginFrame
}, completion: { [weak self] (completed: Bool) in
if let self = self {
self.containerViewController.groupbarVisibility = self.currentGroupbarVisibility
self.containerViewController = nil
self.currentViewController.view.frame = self.currentBeginFrame
self.currentViewController.view.shadow = nil
self.currentViewController.cancelInteractiveDismiss()
self.currentViewController = nil
self.previousViewController.view.frame = self.previousBeginFrame
self.previousViewController.cancelInteractivePresent()
self.previousViewController = nil
}
complete(completed)
})
}
}
| d7e4b4e237094fd89fc400802345507c | 45.551948 | 146 | 0.693821 | false | false | false | false |
vapor/vapor | refs/heads/main | Tests/VaporTests/ValidationTests.swift | mit | 1 | import Vapor
import XCTest
class ValidationTests: XCTestCase {
func testValidate() throws {
struct User: Validatable, Codable {
enum Gender: String, CaseIterable, Codable {
case male, female, other
}
var id: Int?
var name: String
var age: Int
var gender: Gender
var email: String?
var pet: Pet
var favoritePet: Pet?
var luckyNumber: Int?
var profilePictureURL: String?
var preferredColors: [String]
var isAdmin: Bool
struct Pet: Codable {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
init(id: Int? = nil, name: String, age: Int, gender: Gender, pet: Pet, preferredColors: [String] = [], isAdmin: Bool) {
self.id = id
self.name = name
self.age = age
self.gender = gender
self.pet = pet
self.preferredColors = preferredColors
self.isAdmin = isAdmin
}
static func validations(_ v: inout Validations) {
// validate name is at least 5 characters and alphanumeric
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
// validate age is 18 or older
v.add("age", as: Int.self, is: .range(18...))
// validate gender is of type Gender
v.add("gender", as: String.self, is: .case(of: Gender.self))
// validate the email is valid and is not nil
v.add("email", as: String?.self, is: !.nil && .email)
v.add("email", as: String?.self, is: .email && !.nil) // test other way
// validate the email is valid or is nil
v.add("email", as: String?.self, is: .nil || .email)
v.add("email", as: String?.self, is: .email || .nil) // test other way
// validate that the lucky number is nil or is 5 or 7
v.add("luckyNumber", as: Int?.self, is: .nil || .in(5, 7))
// validate that the profile picture is nil or a valid URL
v.add("profilePictureURL", as: String?.self, is: .url || .nil)
v.add("preferredColors", as: [String].self, is: !.empty)
// pet validations
v.add("pet") { pet in
pet.add("name", as: String.self, is: .count(5...) && .characterSet(.alphanumerics + .whitespaces))
pet.add("age", as: Int.self, is: .range(3...))
}
// optional favorite pet validations
v.add("favoritePet", required: false) { pet in
pet.add(
"name", as: String.self,
is: .count(5...) && .characterSet(.alphanumerics + .whitespaces)
)
pet.add("age", as: Int.self, is: .range(3...))
}
v.add("isAdmin", as: Bool.self)
}
}
let valid = """
{
"name": "Tanner",
"age": 24,
"gender": "male",
"email": "[email protected]",
"luckyNumber": 5,
"profilePictureURL": "https://foo.jpg",
"preferredColors": ["blue"],
"pet": {
"name": "Zizek",
"age": 3
},
"hobbies": [
{
"title": "Football"
},
{
"title": "Computer science"
}
],
"favoritePet": null,
"isAdmin": true
}
"""
XCTAssertNoThrow(try User.validate(json: valid))
let validURL: URI = "https://tanner.xyz/user?name=Tanner&age=24&gender=male&[email protected]&luckyNumber=5&profilePictureURL=https://foo.jpg&preferredColors=[blue]&pet[name]=Zizek&pet[age]=3&isAdmin=true"
XCTAssertNoThrow(try User.validate(query: validURL))
let invalidUser = """
{
"name": "Tan!ner",
"age": 24,
"gender": "other",
"email": "[email protected]",
"luckyNumber": 5,
"profilePictureURL": "https://foo.jpg",
"preferredColors": ["blue"],
"pet": {
"name": "Zizek",
"age": 3
},
"isAdmin": true,
"hobbies": [
{
"title": "Football"
},
{
"title": "Computer science"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidUser)) { error in
XCTAssertEqual("\(error)", "name contains '!' (allowed: A-Z, a-z, 0-9)")
}
let invalidUserURL: URI = "https://tanner.xyz/user?name=Tan!ner&age=24&gender=other&[email protected]&luckyNumber=5&profilePictureURL=https://foo.jpg&preferredColors=[blue]&pet[name]=Zizek&pet[age]=3&isAdmin=true"
XCTAssertThrowsError(try User.validate(query: invalidUserURL)) { error in
XCTAssertEqual("\(error)", "name contains '!' (allowed: A-Z, a-z, 0-9)")
}
}
func testValidateInternationalEmail() throws {
struct Email: Validatable, Codable {
var email: String?
init(email: String) {
self.email = email
}
static func validations(_ v: inout Validations) {
// validate the international email is valid and is not nil
v.add("email", as: String?.self, is: !.nil && .internationalEmail)
v.add("email", as: String?.self, is: .internationalEmail && !.nil) // test other way
}
}
let valid = """
{
"email": "ß@tanner.xyz"
}
"""
XCTAssertNoThrow(try Email.validate(json: valid))
let validURL: URI = "https://tanner.xyz/email?email=ß@tanner.xyz"
XCTAssertNoThrow(try Email.validate(query: validURL))
let validURL2: URI = "https://tanner.xyz/email?email=me@ßanner.xyz"
XCTAssertNoThrow(try Email.validate(query: validURL2))
let invalidUser = """
{
"email": "me@[email protected]",
}
"""
XCTAssertThrowsError(try Email.validate(json: invalidUser)) { error in
XCTAssertEqual("\(error)", "email is not a valid email address, email is not a valid email address")
}
let invalidUserURL: URI = "https://tanner.xyz/email?email=me@[email protected]"
XCTAssertThrowsError(try Email.validate(query: invalidUserURL)) { error in
XCTAssertEqual("\(error)", "email is not a valid email address, email is not a valid email address")
}
}
func testValidateNested() throws {
struct User: Validatable, Codable {
var name: String
var age: Int
var pet: Pet
struct Pet: Codable {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
static func validations(_ v: inout Validations) {
// validate name is at least 5 characters and alphanumeric
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
// validate age is 18 or older
v.add("age", as: Int.self, is: .range(18...))
// pet validations
v.add("pet") { pet in
pet.add("name", as: String.self, is: .count(5...) && .characterSet(.alphanumerics + .whitespaces))
pet.add("age", as: Int.self, is: .range(3...))
}
}
}
let invalidPetJSON = """
{
"name": "Tanner",
"age": 24,
"pet": {
"name": "Zi!zek",
"age": 3
}
}
"""
XCTAssertThrowsError(try User.validate(json: invalidPetJSON)) { error in
XCTAssertEqual("\(error)", "pet name contains '!' (allowed: whitespace, A-Z, a-z, 0-9)")
}
let invalidPetURL: URI = "https://tanner.xyz/user?name=Tanner&age=24&pet[name]=Zi!ek&pet[age]=3"
XCTAssertThrowsError(try User.validate(query: invalidPetURL)) { error in
XCTAssertEqual("\(error)", "pet name contains '!' (allowed: whitespace, A-Z, a-z, 0-9)")
}
}
func testValidateNestedEach() throws {
struct User: Validatable {
var name: String
var age: Int
var hobbies: [Hobby]
var allergies: [Allergy]?
struct Hobby: Codable {
var title: String
init(title: String) {
self.title = title
}
}
struct Allergy: Codable {
var title: String
init(title: String) {
self.title = title
}
}
static func validations(_ v: inout Validations) {
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
v.add("age", as: Int.self, is: .range(18...))
v.add(each: "hobbies") { i, hobby in
hobby.add("title", as: String.self, is: .count(5...) && .characterSet(.alphanumerics + .whitespaces))
}
v.add("hobbies", as: [Hobby].self, is: !.empty)
v.add(each: "allergies", required: false) { i, allergy in
allergy.add("title", as: String.self, is: .characterSet(.letters))
}
}
}
let invalidNestedArray = """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "Football€"
},
{
"title": "Co"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray)) { error in
XCTAssertEqual("\(error)", "hobbies at index 0 title contains '€' (allowed: whitespace, A-Z, a-z, 0-9) and at index 1 title is less than minimum of 5 character(s)")
}
let invalidNestedArray2 = """
{
"name": "Tanner",
"age": 24,
"allergies": [
{
"title": "Peanuts"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray2)) { error in
XCTAssertEqual("\(error)", "hobbies is required, hobbies is required")
}
let invalidNestedArray3 = """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "Football"
}
],
"allergies": [
{
"title": "Peanuts€"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray3)) { error in
XCTAssertEqual("\(error)", "allergies at index 0 title contains '€' (allowed: A-Z, a-z)")
}
let validNestedArray = """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "Football"
}
],
}
"""
XCTAssertNoThrow(try User.validate(json: validNestedArray))
}
func testValidateNestedEachIndex() throws {
struct User: Validatable {
var name: String
var age: Int
var hobbies: [Hobby]
struct Hobby: Codable {
var title: String
init(title: String) {
self.title = title
}
}
static func validations(_ v: inout Validations) {
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
v.add("age", as: Int.self, is: .range(18...))
v.add(each: "hobbies") { i, hobby in
// don't validate first item
if i != 0 {
hobby.add("title", as: String.self, is: .characterSet(.alphanumerics + .whitespaces))
}
}
v.add("hobbies", as: [Hobby].self, is: !.empty)
}
}
XCTAssertNoThrow(try User.validate(json: """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "€"
},
{
"title": "hello"
}
]
}
"""))
XCTAssertThrowsError(try User.validate(json: """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "hello"
},
{
"title": "€"
}
]
}
""")) { error in
XCTAssertEqual("\(error)", "hobbies at index 1 title contains '€' (allowed: whitespace, A-Z, a-z, 0-9)")
}
}
func testCatchError() throws {
struct User: Validatable, Codable {
var name: String
var age: Int
static func validations(_ v: inout Validations) {
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
v.add("age", as: Int.self, is: .range(18...))
}
}
let invalidUser = """
{
"name": "Tan!ner",
"age": 24
}
"""
do {
try User.validate(json: invalidUser)
} catch let error as ValidationsError {
XCTAssertEqual(error.failures.count, 1)
let name = error.failures[0]
XCTAssertEqual(name.key.stringValue, "name")
XCTAssertEqual(name.result.isFailure, true)
XCTAssertEqual(name.result.failureDescription, "contains '!' (allowed: A-Z, a-z, 0-9)")
let and = name.result as! ValidatorResults.And
let count = and.left as! ValidatorResults.Range<Int>
XCTAssertEqual(count.result, .greaterThanOrEqualToMin(5))
let character = and.right as! ValidatorResults.CharacterSet
XCTAssertEqual(character.invalidSlice, "!")
}
}
func testNotReadability() {
assert("vapor!🤠", fails: .ascii && .alphanumeric, "contains '🤠' (allowed: ASCII) and contains '!' (allowed: A-Z, a-z, 0-9)")
assert("vapor", fails: !(.ascii && .alphanumeric), "contains only ASCII and contains only A-Z, a-z, 0-9")
}
func testASCII() {
assert("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", passes: .ascii)
assert("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", fails: !.ascii, "contains only ASCII")
assert("\n\r\t", passes: .ascii)
assert("\n\r\t\u{129}", fails: .ascii, "contains 'ĩ' (allowed: ASCII)")
assert(" !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", passes: .ascii)
assert("ABCDEFGHIJKLMNOPQR🤠STUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", fails: .ascii, "contains '🤠' (allowed: ASCII)")
}
func testCollectionASCII() {
assert(["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"], passes: .ascii)
assert(["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"], fails: !.ascii, "contains only ASCII")
assert(["\n\r\t"], passes: .ascii)
assert(["\n\r\t", "\u{129}"], fails: .ascii, "string at index 1 contains 'ĩ' (allowed: ASCII)")
assert([" !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"], passes: .ascii)
assert(["ABCDEFGHIJKLMNOPQR🤠STUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"], fails: .ascii, "string at index 0 contains '🤠' (allowed: ASCII)")
}
func testAlphanumeric() {
assert("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", passes: .alphanumeric)
assert("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", fails: .alphanumeric, "contains '+' (allowed: A-Z, a-z, 0-9)")
}
func testCollectionAlphanumeric() {
assert(["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"], passes: .alphanumeric)
assert(["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef", "ghijklmnopqrstuvwxyz0123456789+/"], fails: .alphanumeric, "string at index 1 contains '+' (allowed: A-Z, a-z, 0-9)")
}
func testEmpty() {
assert("", passes: .empty)
assert("something", fails: .empty, "is not empty")
assert([Int](), passes: .empty)
assert([Int](), fails: !.empty, "is empty")
assert([1, 2], fails: .empty, "is not empty")
assert([1, 2], passes: !.empty)
}
func testEmail() {
assert("[email protected]", passes: .email)
assert("[email protected]", fails: !.email, "is a valid email address")
assert("[email protected]@vapor.codes", fails: .email, "is not a valid email address")
assert("[email protected].", fails: .email, "is not a valid email address")
assert("tanner@@vapor.codes", fails: .email, "is not a valid email address")
assert("@vapor.codes", fails: .email, "is not a valid email address")
assert("tanner@codes", fails: .email, "is not a valid email address")
assert("asdf", fails: .email, "is not a valid email address")
assert("asdf", passes: !.email)
}
func testEmailWithSpecialCharacters() {
assert("ß@b.com", passes: .internationalEmail)
assert("ß@b.com", fails: !.internationalEmail, "is a valid email address")
assert("b@ß.com", passes: .internationalEmail)
assert("b@ß.com", fails: !.internationalEmail, "is a valid email address")
}
func testRange() {
assert(4, passes: .range(-5...5))
assert(4, passes: .range(..<5))
assert(5, fails: .range(..<5), "is greater than maximum of 4")
assert(5, passes: .range(...10))
assert(11, fails: .range(...10), "is greater than maximum of 10")
assert(4, fails: !.range(-5...5), "is between -5 and 5")
assert(5, passes: .range(-5...5))
assert(-5, passes: .range(-5...5))
assert(6, fails: .range(-5...5), "is greater than maximum of 5")
assert(-6, fails: .range(-5...5), "is less than minimum of -5")
assert(.max, passes: .range(5...))
assert(4, fails: .range(5...), "is less than minimum of 5")
assert(-5, passes: .range(-5..<6))
assert(-4, passes: .range(-5..<6))
assert(5, passes: .range(-5..<6))
assert(-6, fails: .range(-5..<6), "is less than minimum of -5")
assert(6, fails: .range(-5..<6), "is greater than maximum of 5")
assert(6, passes: !.range(-5..<6))
}
func testCountCharacters() {
assert("1", passes: .count(1...6))
assert("1", fails: !.count(1...6), "is between 1 and 6 character(s)")
assert("123", passes: .count(1...6))
assert("123456", passes: .count(1...6))
assert("", fails: .count(1...6), "is less than minimum of 1 character(s)")
assert("1234567", fails: .count(1...6), "is greater than maximum of 6 character(s)")
}
func testCountItems() {
assert([1], passes: .count(1...6))
assert([1], fails: !.count(1...6), "is between 1 and 6 item(s)")
assert([1], passes: .count(...1))
assert([1], fails: .count(..<1), "is greater than maximum of 0 item(s)")
assert([1, 2, 3], passes: .count(1...6))
assert([1, 2, 3, 4, 5, 6], passes: .count(1...6))
assert([Int](), fails: .count(1...6), "is less than minimum of 1 item(s)")
assert([1, 2, 3, 4, 5, 6, 7], fails: .count(1...6), "is greater than maximum of 6 item(s)")
}
func testURL() {
assert("https://www.somedomain.com/somepath.png", passes: .url)
assert("https://www.somedomain.com/somepath.png", fails: !.url, "is a valid URL")
assert("https://www.somedomain.com/", passes: .url)
assert("file:///Users/vapor/rocks/somePath.png", passes: .url)
assert("www.somedomain.com/", fails: .url, "is an invalid URL")
assert("bananas", fails: .url, "is an invalid URL")
assert("bananas", passes: !.url)
}
func testValid() {
assert("some random string", passes: .valid)
assert(true, passes: .valid)
assert("123", passes: .valid)
assert([1, 2, 3], passes: .valid)
assert(Date.init(), passes: .valid)
assert("some random string", fails: !.valid, "is valid")
assert(true, fails: !.valid, "is valid")
assert("123", fails: !.valid, "is valid")
}
func testPattern() {
assert("this are not numbers", fails: .pattern("^[0-9]*$"), "is not a valid pattern ^[0-9]*$")
assert("12345", passes: .pattern("^[0-9]*$"))
}
func testPreexistingValidatorResultIsIncluded() throws {
struct CustomValidatorResult: ValidatorResult {
var isFailure: Bool {
true
}
var successDescription: String? {
nil
}
var failureDescription: String? {
"custom description"
}
}
var validations = Validations()
validations.add("key", result: CustomValidatorResult())
let error = try validations.validate(json: "{}").error
XCTAssertEqual(error?.description, "key custom description")
}
func testDoubleNegationIsAvoided() throws {
var validations = Validations()
validations.add("key", as: String.self, is: !.empty)
let error = try validations.validate(json: #"{"key": ""}"#).error
XCTAssertEqual(error?.description, "key is empty")
}
func testCaseOf() {
enum StringEnumType: String, CaseIterable {
case case1, case2, case3 = "CASE3"
}
assert("case1", passes: .case(of: StringEnumType.self))
assert("case2", passes: .case(of: StringEnumType.self))
assert("case1", fails: !.case(of: StringEnumType.self), "is case1, case2, or CASE3")
assert("case3", fails: .case(of: StringEnumType.self), "is not case1, case2, or CASE3")
enum IntEnumType: Int, CaseIterable {
case case1 = 1, case2 = 2
}
assert(1, passes: .case(of: IntEnumType.self))
assert(2, passes: .case(of: IntEnumType.self))
assert(1, fails: !.case(of: IntEnumType.self), "is 1 or 2")
assert(3, fails: .case(of: IntEnumType.self), "is not 1 or 2")
enum SingleCaseEnum: String, CaseIterable {
case case1 = "CASE1"
}
assert("CASE1", passes: .case(of: SingleCaseEnum.self))
assert("CASE1", fails: !.case(of: SingleCaseEnum.self), "is CASE1")
assert("CASE2", fails: .case(of: SingleCaseEnum.self), "is not CASE1")
}
func testCustomResponseMiddleware() throws {
// Test item
struct User: Validatable {
let name: String
let age: Int
static func validations(_ v: inout Validations) {
// validate name is at least 5 characters and alphanumeric
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
// validate age is 18 or older
v.add("age", as: Int.self, is: .range(18...))
}
}
// Setup
let app = Application(.testing)
defer { app.shutdown() }
// Converts validation errors to a custom response.
final class ValidationErrorMiddleware: Middleware {
// Defines the format of the custom error response.
struct ErrorResponse: Content {
var errors: [String]
}
func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
next.respond(to: request).flatMapErrorThrowing { error in
// Check to see if this is a validation error.
if let validationError = error as? ValidationsError {
// Convert each failed ValidatorResults to a String
// for the sake of this example.
let errorMessages = validationError.failures.map { failure -> String in
let reason: String
// The failure result will be one of the ValidatorResults subtypes.
//
// Each validator extends ValidatorResults with a nested type.
// For example, the .email validator's result type is:
//
// struct ValidatorResults.Email {
// let isValidEmail: Bool
// }
//
// You can handle as many or as few of these types as you want.
// Vapor and third party packages may add additional types.
// This switch is only handling two cases as an example.
//
// If you want to localize your validation failures, this is a
// good place to do it.
switch failure.result {
case is ValidatorResults.Missing:
reason = "is required"
case let error as ValidatorResults.TypeMismatch:
reason = "is not \(error.type)"
default:
reason = "unknown"
}
return "\(failure.key) \(reason)"
}
// Create the 400 response and encode the custom error content.
let response = Response(status: .badRequest)
try response.content.encode(ErrorResponse(errors: errorMessages))
return response
} else {
// This isn't a validation error, rethrow it and let
// ErrorMiddleware handle it.
throw error
}
}
}
}
app.middleware.use(ValidationErrorMiddleware())
app.post("users") { req -> HTTPStatus in
try User.validate(content: req)
return .ok
}
// Test that the custom validation error middleware is working.
try app.test(.POST, "users", beforeRequest: { req in
try req.content.encode([
"name": "Vapor",
"age": "asdf"
])
}, afterResponse: { res in
XCTAssertEqual(res.status, .badRequest)
let content = try res.content.decode(ValidationErrorMiddleware.ErrorResponse.self)
XCTAssertEqual(content.errors.count, 1)
})
}
func testValidateNullWhenNotRequired() throws {
struct Site: Validatable, Codable {
var url: String?
var number: Int?
var name: String?
static func validations(_ v: inout Validations) {
v.add("url", as: String.self, is: .url, required: false)
v.add("number", as: Int.self, required: false)
v.add("name", as: String.self, required: false)
}
}
let valid = """
{
"url": null
}
"""
XCTAssertNoThrow(try Site.validate(json: valid))
let valid2 = """
{
}
"""
XCTAssertNoThrow(try Site.validate(json: valid2))
let valid3 = """
{
"name": "Tim"
}
"""
XCTAssertNoThrow(try Site.validate(json: valid3))
let valid4 = """
{
"name": null
}
"""
XCTAssertNoThrow(try Site.validate(json: valid4))
let valid5 = """
{
"number": 3
}
"""
XCTAssertNoThrow(try Site.validate(json: valid5))
let valid6 = """
{
"number": null
}
"""
XCTAssertNoThrow(try Site.validate(json: valid6))
let invalid1 = """
{
"number": "Tim"
}
"""
do {
try Site.validate(json: invalid1)
} catch let error as ValidationsError {
XCTAssertEqual(error.failures.count, 1)
let name = error.failures[0]
XCTAssertEqual(name.key.stringValue, "number")
XCTAssertEqual(name.result.isFailure, true)
XCTAssertEqual(name.result.failureDescription, "is not a(n) Int")
}
let invalid2 = """
{
"name": 3
}
"""
do {
try Site.validate(json: invalid2)
} catch let error as ValidationsError {
XCTAssertEqual(error.failures.count, 1)
let name = error.failures[0]
XCTAssertEqual(name.key.stringValue, "name")
XCTAssertEqual(name.result.isFailure, true)
XCTAssertEqual(name.result.failureDescription, "is not a(n) String")
}
}
func testCustomFailureDescriptions() throws {
struct User: Validatable {
var name: String
var age: Int
var hobbies: [Hobby]
struct Hobby: Codable {
var title: String
init(title: String) {
self.title = title
}
}
static func validations(_ v: inout Validations) {
struct CustomValidatorResult: ValidatorResult {
var isFailure: Bool {
true
}
var successDescription: String? {
nil
}
var failureDescription: String? {
"custom description"
}
}
v.add("key", result: CustomValidatorResult(), customFailureDescription: "Something went wrong with the provided data")
v.add("name", as: String.self, is: .count(5...) && !.alphanumeric, customFailureDescription: "The provided name is invalid")
v.add(each: "hobbies", customFailureDescription: "A provided hobby value was not alphanumeric") { i, hobby in
hobby.add("title", as: String.self, is: .count(5...) && .characterSet(.alphanumerics + .whitespaces))
}
v.add("hobbies", customFailureDescription: "A provided hobby value was empty") { hobby in
hobby.add("title", as: String.self, is: !.empty)
}
}
}
let invalidNestedArray = """
{
"name": "Andre",
"age": 26,
"hobbies": [
{
"title": "Running€"
},
{
"title": "Co"
},
{
"title": ""
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray)) { error in
XCTAssertEqual("\(error)", "Something went wrong with the provided data, The provided name is invalid, A provided hobby value was not alphanumeric, A provided hobby value was empty")
}
}
override class func setUp() {
XCTAssert(isLoggingConfigured)
}
}
private func assert<T>(
_ data: T,
fails validator: Validator<T>,
_ description: String,
file: StaticString = #file,
line: UInt = #line
) {
let file = (file)
let result = validator.validate(data)
XCTAssert(result.isFailure, result.successDescription ?? "n/a", file: file, line: line)
XCTAssertEqual(description, result.failureDescription ?? "n/a", file: file, line: line)
}
private func assert<T>(
_ data: T,
passes validator: Validator<T>,
file: StaticString = #file,
line: UInt = #line
) {
let file = (file)
let result = validator.validate(data)
XCTAssert(!result.isFailure, result.failureDescription ?? "n/a", file: file, line: line)
}
| 08940085cfe38ac909ecff40f6118408 | 37.316338 | 223 | 0.498745 | false | false | false | false |
AngryLi/Onmyouji | refs/heads/master | Carthage/Checkouts/RxSwift/RxExample/RxExample-iOSTests/TestScheduler+MarbleTests.swift | mit | 14 | //
// TestScheduler+MarbleTests.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import RxTest
import RxCocoa
/**
There are examples like this all over the web, but I think that I've first something like this here
https://github.com/ReactiveX/RxJS/blob/master/doc/writing-marble-tests.md
These tests are called marble tests.
*/
extension TestScheduler {
/**
Transformation from this format:
---a---b------c-----
to this format
schedule onNext(1) @ 0.6s
schedule onNext(2) @ 1.4s
schedule onNext(3) @ 7.0s
....
]
You can also specify retry data in this format:
---a---b------c----#|----a--#|----b
- letters and digits mark values
- `#` marks unknown error
- `|` marks sequence completed
*/
func parseEventsAndTimes<T>(timeline: String, values: [String: T], errors: [String: Swift.Error] = [:]) -> [[Recorded<Event<T>>]] {
//print("parsing: \(timeline)")
typealias RecordedEvent = Recorded<Event<T>>
let timelines = timeline.components(separatedBy: "|")
let allExceptLast = timelines[0 ..< timelines.count - 1]
return (allExceptLast.map { $0 + "|" } + [timelines.last!])
.filter { $0.characters.count > 0 }
.map { timeline -> [Recorded<Event<T>>] in
let segments = timeline.components(separatedBy:"-")
let (time: _, events: events) = segments.reduce((time: 0, events: [RecordedEvent]())) { state, event in
let tickIncrement = event.characters.count + 1
if event.characters.count == 0 {
return (state.time + tickIncrement, state.events)
}
if event == "#" {
let errorEvent = RecordedEvent(time: state.time, value: Event<T>.error(NSError(domain: "Any error domain", code: -1, userInfo: nil)))
return (state.time + tickIncrement, state.events + [errorEvent])
}
if event == "|" {
let completed = RecordedEvent(time: state.time, value: Event<T>.completed)
return (state.time + tickIncrement, state.events + [completed])
}
guard let next = values[event] else {
guard let error = errors[event] else {
fatalError("Value with key \(event) not registered as value:\n\(values)\nor error:\n\(errors)")
}
let nextEvent = RecordedEvent(time: state.time, value: Event<T>.error(error))
return (state.time + tickIncrement, state.events + [nextEvent])
}
let nextEvent = RecordedEvent(time: state.time, value: Event<T>.next(next))
return (state.time + tickIncrement, state.events + [nextEvent])
}
//print("parsed: \(events)")
return events
}
}
/**
Creates driver for marble test.
- parameter timeline: Timeline in the form `---a---b------c--|`
- parameter values: Dictionary of values in timeline. `[a:1, b:2]`
- returns: Driver specified by timeline and values.
*/
func createDriver<T>(timeline: String, values: [String: T]) -> Driver<T> {
return createObservable(timeline: timeline, values: values, errors: [:]).asDriver(onErrorRecover: { (error) -> Driver<T> in
genericFatal("This can't error out")
})
}
/**
Creates observable for marble tests.
- parameter timeline: Timeline in the form `---a---b------c--|`
- parameter values: Dictionary of values in timeline. `[a:1, b:2]`
- parameter errors: Dictionary of errors in timeline.
- returns: Observable sequence specified by timeline and values.
*/
func createObservable<T>(timeline: String, values: [String: T], errors: [String: Swift.Error] = [:]) -> Observable<T> {
let events = self.parseEventsAndTimes(timeline: timeline, values: values, errors: errors)
return createObservable(events)
}
/**
Creates observable for marble tests.
- parameter events: Recorded events to replay.
- returns: Observable sequence specified by timeline and values.
*/
func createObservable<T>(_ events: [Recorded<Event<T>>]) -> Observable<T> {
return createObservable([events])
}
/**
Creates observable for marble tests.
- parameter events: Recorded events to replay. This overloads enables modeling of retries.
`---a---b------c----#|----a--#|----b`
When next observer is subscribed, next sequence will be replayed. If all sequences have
been replayed and new observer is subscribed, `fatalError` will be raised.
- returns: Observable sequence specified by timeline and values.
*/
func createObservable<T>(_ events: [[Recorded<Event<T>>]]) -> Observable<T> {
var attemptCount = 0
print("created for \(events)")
return Observable.create { observer in
if attemptCount >= events.count {
fatalError("This is attempt # \(attemptCount + 1), but timeline only allows \(events.count).\n\(events)")
}
let scheduledEvents = events[attemptCount].map { event in
return self.scheduleRelative((), dueTime: resolution * TimeInterval(event.time)) { _ in
observer.on(event.value)
return Disposables.create()
}
}
attemptCount += 1
return Disposables.create(scheduledEvents)
}
}
/**
Enables simple construction of mock implementations from marble timelines.
- parameter Arg: Type of arguments of mocked method.
- parameter Ret: Return type of mocked method. `Observable<Ret>`
- parameter values: Dictionary of values in timeline. `[a:1, b:2]`
- parameter errors: Dictionary of errors in timeline.
- parameter timelineSelector: Method implementation. The returned string value represents timeline of
returned observable sequence. `---a---b------c----#|----a--#|----b`
- returns: Implementation of method that accepts arguments with parameter `Arg` and returns observable sequence
with parameter `Ret`.
*/
func mock<Arg, Ret>(values: [String: Ret], errors: [String: Swift.Error] = [:], timelineSelector: @escaping (Arg) -> String) -> (Arg) -> Observable<Ret> {
return { (parameters: Arg) -> Observable<Ret> in
let timeline = timelineSelector(parameters)
return self.createObservable(timeline: timeline, values: values, errors: errors)
}
}
/**
Builds testable observer for s specific observable sequence, binds it's results and sets up disposal.
- parameter source: Observable sequence to observe.
- returns: Observer that records all events for observable sequence.
*/
func record<O: ObservableConvertibleType>(source: O) -> TestableObserver<O.E> {
let observer = self.createObserver(O.E.self)
let disposable = source.asObservable().bind(to: observer)
self.scheduleAt(100000) {
disposable.dispose()
}
return observer
}
}
| a874a738a439927ad171a7a15f450dd0 | 37.106599 | 158 | 0.588517 | false | true | false | false |
XWebView/XWebView | refs/heads/master | XWebView/XWVObject.swift | apache-2.0 | 2 | /*
Copyright 2015 XWebView
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 WebKit
private let webViewInvalidated =
NSError(domain: WKErrorDomain, code: WKError.webViewInvalidated.rawValue, userInfo: nil)
public class XWVObject : NSObject {
public let namespace: String
private(set) public weak var webView: WKWebView?
private weak var origin: XWVObject?
private let reference: Int
// initializer for plugin object.
init(namespace: String, webView: WKWebView) {
self.namespace = namespace
self.webView = webView
reference = 0
super.init()
origin = self
}
// initializer for script object with global namespace.
init(namespace: String, origin: XWVObject) {
self.namespace = namespace
self.origin = origin
webView = origin.webView
reference = 0
super.init()
}
// initializer for script object which is retained on script side.
init(reference: Int, origin: XWVObject) {
self.reference = reference
self.origin = origin
webView = origin.webView
namespace = "\(origin.namespace).$references[\(reference)]"
super.init()
}
deinit {
guard let webView = webView else { return }
let script: String
if origin === self {
script = "delete \(namespace)"
} else if reference != 0, let origin = origin {
script = "\(origin.namespace).$releaseObject(\(reference))"
} else {
return
}
webView.asyncEvaluateJavaScript(script, completionHandler: nil)
}
// Evaluate JavaScript expression
public func evaluateExpression(_ expression: String) throws -> Any {
guard let webView = webView else {
throw webViewInvalidated
}
let result = try webView.syncEvaluateJavaScript(scriptForRetaining(expression))
return wrapScriptObject(result)
}
public typealias Handler = ((Any?, Error?) -> Void)?
public func evaluateExpression(_ expression: String, completionHandler: Handler) {
guard let webView = webView else {
completionHandler?(nil, webViewInvalidated)
return
}
guard let completionHandler = completionHandler else {
webView.asyncEvaluateJavaScript(expression, completionHandler: nil)
return
}
webView.asyncEvaluateJavaScript(scriptForRetaining(expression)) {
[weak self](result: Any?, error: Error?)->Void in
if let error = error {
completionHandler(nil, error)
} else if let result = result {
completionHandler(self?.wrapScriptObject(result) ?? result, nil)
} else {
completionHandler(undefined, error)
}
}
}
private func scriptForRetaining(_ script: String) -> String {
guard let origin = origin else { return script }
return "\(origin.namespace).$retainObject(\(script))"
}
func wrapScriptObject(_ object: Any) -> Any {
guard let origin = origin else { return object }
if let dict = object as? [String: Any], dict["$sig"] as? NSNumber == 0x5857574F {
if let num = dict["$ref"] as? NSNumber, num != 0 {
return XWVScriptObject(reference: num.intValue, origin: origin)
} else if let namespace = dict["$ns"] as? String {
return XWVScriptObject(namespace: namespace, origin: origin)
}
}
return object
}
}
extension XWVObject : CustomJSONStringable {
public var jsonString: String? {
return namespace
}
}
| fa9ba622a8a9b13bf8b429355d45fe3d | 33.925 | 92 | 0.635409 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | Mac/Preferences/Accounts/AccountsFeedWranglerWindowController.swift | mit | 1 | //
// AccountsFeedWranglerWindowController.swift
// NetNewsWire
//
// Created by Jonathan Bennett on 2019-08-29.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import AppKit
import Account
import RSWeb
import Secrets
class AccountsFeedWranglerWindowController: NSWindowController {
@IBOutlet weak var signInTextField: NSTextField!
@IBOutlet weak var noAccountTextField: NSTextField!
@IBOutlet weak var createNewAccountButton: NSButton!
@IBOutlet weak var progressIndicator: NSProgressIndicator!
@IBOutlet weak var usernameTextField: NSTextField!
@IBOutlet weak var passwordTextField: NSSecureTextField!
@IBOutlet weak var errorMessageLabel: NSTextField!
@IBOutlet weak var actionButton: NSButton!
var account: Account?
private weak var hostWindow: NSWindow?
convenience init() {
self.init(windowNibName: NSNib.Name("AccountsFeedWrangler"))
}
override func windowDidLoad() {
if let account = account, let credentials = try? account.retrieveCredentials(type: .basic) {
usernameTextField.stringValue = credentials.username
actionButton.title = NSLocalizedString("Update", comment: "Update")
signInTextField.stringValue = NSLocalizedString("Update your Feed Wrangler account credentials.", comment: "SignIn")
noAccountTextField.isHidden = true
createNewAccountButton.isHidden = true
} else {
actionButton.title = NSLocalizedString("Create", comment: "Create")
signInTextField.stringValue = NSLocalizedString("Sign in to your Feed Wrangler account.", comment: "SignIn")
}
enableAutofill()
usernameTextField.becomeFirstResponder()
}
// MARK: API
func runSheetOnWindow(_ hostWindow: NSWindow, completion: ((NSApplication.ModalResponse) -> Void)? = nil) {
self.hostWindow = hostWindow
hostWindow.beginSheet(window!, completionHandler: completion)
}
// MARK: Actions
@IBAction func cancel(_ sender: Any) {
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel)
}
@IBAction func action(_ sender: Any) {
self.errorMessageLabel.stringValue = ""
guard !usernameTextField.stringValue.isEmpty && !passwordTextField.stringValue.isEmpty else {
self.errorMessageLabel.stringValue = NSLocalizedString("Username & password required.", comment: "Credentials Error")
return
}
guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .feedWrangler, username: usernameTextField.stringValue) else {
self.errorMessageLabel.stringValue = NSLocalizedString("There is already a FeedWrangler account with that username created.", comment: "Duplicate Error")
return
}
actionButton.isEnabled = false
progressIndicator.isHidden = false
progressIndicator.startAnimation(self)
let credentials = Credentials(type: .feedWranglerBasic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue)
Account.validateCredentials(type: .feedWrangler, credentials: credentials) { [weak self] result in
guard let self = self else { return }
self.actionButton.isEnabled = true
self.progressIndicator.isHidden = true
self.progressIndicator.stopAnimation(self)
switch result {
case .success(let validatedCredentials):
guard let validatedCredentials = validatedCredentials else {
self.errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error")
return
}
if self.account == nil {
self.account = AccountManager.shared.createAccount(type: .feedWrangler)
}
do {
try self.account?.removeCredentials(type: .feedWranglerBasic)
try self.account?.removeCredentials(type: .feedWranglerToken)
try self.account?.storeCredentials(credentials)
try self.account?.storeCredentials(validatedCredentials)
self.account?.refreshAll() { result in
switch result {
case .success:
break
case .failure(let error):
NSApplication.shared.presentError(error)
}
}
self.hostWindow?.endSheet(self.window!, returnCode: NSApplication.ModalResponse.OK)
} catch {
self.errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error")
}
case .failure:
self.errorMessageLabel.stringValue = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error")
}
}
}
@IBAction func createAccountWithProvider(_ sender: Any) {
NSWorkspace.shared.open(URL(string: "https://feedwrangler.net/users/new")!)
}
// MARK: Autofill
func enableAutofill() {
if #available(macOS 11, *) {
usernameTextField.contentType = .username
passwordTextField.contentType = .password
}
}
}
| 478e38e9a9d25fc89b190ae74f10ad31 | 33.343066 | 156 | 0.750691 | false | false | false | false |
Binur/SubscriptionPrompt | refs/heads/master | SubscriptionPrompt/SlideCollectionViewCell.swift | mit | 1 | //
// SlideCollectionViewCell.swift
// SubscriptionPrompt
//
// Created by Binur Konarbayev on 4/29/16.
// Copyright © 2016 binchik. All rights reserved.
//
import UIKit
final class SlideCollectionViewCell: UICollectionViewCell {
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
return imageView
}()
lazy var titleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.setContentCompressionResistancePriority(1000, for: .vertical)
return label
}()
lazy var subtitleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.setContentCompressionResistancePriority(1000, for: .vertical)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
private func setUp() {
setUpViews()
setUpConstraints()
}
private func setUpViews() {
let views: [UIView] = [imageView, titleLabel, subtitleLabel]
views.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview($0)
}
}
private func setUpConstraints() {
[
NSLayoutConstraint(item: imageView, attribute: .top,
relatedBy: .equal, toItem: contentView,
attribute: .top, multiplier: 1,
constant: 0),
NSLayoutConstraint(item: imageView, attribute: .leading,
relatedBy: .equal, toItem: contentView,
attribute: .leading, multiplier: 1,
constant: 0),
NSLayoutConstraint(item: imageView, attribute: .trailing,
relatedBy: .equal, toItem: contentView,
attribute: .trailing, multiplier: 1,
constant: 0),
NSLayoutConstraint(item: titleLabel, attribute: .top,
relatedBy: .equal, toItem: imageView,
attribute: .bottom, multiplier: 1,
constant: 4),
NSLayoutConstraint(item: titleLabel, attribute: .leading,
relatedBy: .equal, toItem: contentView,
attribute: .leading, multiplier: 1,
constant: 4),
NSLayoutConstraint(item: titleLabel, attribute: .trailing,
relatedBy: .equal, toItem: contentView,
attribute: .trailing, multiplier: 1,
constant: -4),
NSLayoutConstraint(item: subtitleLabel, attribute: .top,
relatedBy: .equal, toItem: titleLabel,
attribute: .bottom, multiplier: 1,
constant: 4),
NSLayoutConstraint(item: subtitleLabel, attribute: .leading,
relatedBy: .equal, toItem: contentView,
attribute: .leading, multiplier: 1,
constant: 4),
NSLayoutConstraint(item: subtitleLabel, attribute: .trailing,
relatedBy: .equal, toItem: contentView,
attribute: .trailing, multiplier: 1,
constant: -4),
NSLayoutConstraint(item: subtitleLabel, attribute: .bottom,
relatedBy: .equal, toItem: contentView,
attribute: .bottom, multiplier: 1,
constant: -4)
].forEach { $0.isActive = true }
}
}
extension SlideCollectionViewCell {
func setUp(withSlide slide: Slide) {
imageView.image = slide.image
titleLabel.text = slide.title
subtitleLabel.text = slide.subtitle
}
func setUp(withSlideStyle style: SlideStyle) {
backgroundColor = style.backgroundColor
titleLabel.font = style.titleFont
subtitleLabel.font = style.subtitleFont
titleLabel.textColor = style.titleColor
subtitleLabel.textColor = style.titleColor
}
}
| b8388ecea3b44a5823b2852cfac2290c | 34.10084 | 75 | 0.583912 | false | false | false | false |
jemartti/OnTheMap | refs/heads/master | OnTheMap/LoginViewController.swift | mit | 1 | //
// LoginViewController.swift
// OnTheMap
//
// Created by Jacob Marttinen on 2/12/17.
// Copyright © 2017 Jacob Marttinen. All rights reserved.
//
import UIKit
// MARK: - LoginViewController: UIViewController
class LoginViewController: UIViewController {
// MARK: Properties
var keyboardOnScreen = false
// MARK: Outlets
@IBOutlet weak var headerImageView: UIImageView!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: BorderedButton!
@IBOutlet weak var debugTextLabel: UILabel!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
subscribeToNotification(.UIKeyboardWillShow, selector: #selector(keyboardWillShow))
subscribeToNotification(.UIKeyboardWillHide, selector: #selector(keyboardWillHide))
subscribeToNotification(.UIKeyboardDidShow, selector: #selector(keyboardDidShow))
subscribeToNotification(.UIKeyboardDidHide, selector: #selector(keyboardDidHide))
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.debugTextLabel.text = ""
unsubscribeFromAllNotifications()
}
// MARK: Login
@IBAction func loginPressed(_ sender: AnyObject) {
userTappedView(self)
if usernameTextField.text!.isEmpty || passwordTextField.text!.isEmpty {
alertUserOfFailure(message: "Both username and password are required.")
} else {
setUIEnabled(false)
createSession()
}
}
private func completeLogin() {
performUIUpdatesOnMain {
self.usernameTextField.text = ""
self.passwordTextField.text = ""
self.debugTextLabel.text = ""
self.setUIEnabled(true)
let controller = self.storyboard!.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
self.present(controller, animated: true, completion: nil)
}
}
private func alertUserOfFailure( message: String) {
performUIUpdatesOnMain {
let alertController = UIAlertController(
title: "Login Failed",
message: message,
preferredStyle: UIAlertControllerStyle.alert
)
alertController.addAction(UIAlertAction(
title: "Dismiss",
style: UIAlertActionStyle.default,
handler: nil
))
self.present(alertController, animated: true, completion: nil)
self.setUIEnabled(true)
}
}
// MARK: Udacity
private func createSession() {
UdacityClient.sharedInstance().postSession(usernameTextField.text!, password: passwordTextField.text!) { (error) in
if let error = error {
self.alertUserOfFailure(message: error.localizedDescription)
} else {
self.getUserData()
}
}
}
private func getUserData() {
UdacityClient.sharedInstance().getUserData() { (error) in
if let error = error {
self.alertUserOfFailure(message: error.localizedDescription)
} else {
if let error = error {
self.alertUserOfFailure(message: error.localizedDescription)
} else {
self.completeLogin()
}
}
}
}
}
// MARK: - LoginViewController: UITextFieldDelegate
extension LoginViewController: UITextFieldDelegate {
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: Show/Hide Keyboard
func keyboardWillShow(_ notification: Notification) {
if !keyboardOnScreen {
view.frame.origin.y -= keyboardHeight(notification)
headerImageView.isHidden = true
}
}
func keyboardWillHide(_ notification: Notification) {
if keyboardOnScreen {
view.frame.origin.y += keyboardHeight(notification)
headerImageView.isHidden = false
}
}
func keyboardDidShow(_ notification: Notification) {
keyboardOnScreen = true
}
func keyboardDidHide(_ notification: Notification) {
keyboardOnScreen = false
}
private func keyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = (notification as NSNotification).userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
private func resignIfFirstResponder(_ textField: UITextField) {
if textField.isFirstResponder {
textField.resignFirstResponder()
}
}
@IBAction func userTappedView(_ sender: AnyObject) {
resignIfFirstResponder(usernameTextField)
resignIfFirstResponder(passwordTextField)
}
}
// MARK: - LoginViewController (Configure UI)
private extension LoginViewController {
func setUIEnabled(_ enabled: Bool) {
usernameTextField.isEnabled = enabled
passwordTextField.isEnabled = enabled
loginButton.isEnabled = enabled
debugTextLabel.text = ""
debugTextLabel.isEnabled = enabled
// adjust login button alpha
if enabled {
loginButton.alpha = 1.0
} else {
loginButton.alpha = 0.5
}
}
func configureUI() {
// configure background gradient
let backgroundGradient = CAGradientLayer()
backgroundGradient.colors = [Constants.UI.LoginColorTop, Constants.UI.LoginColorBottom]
backgroundGradient.locations = [0.0, 1.0]
backgroundGradient.frame = view.frame
view.layer.insertSublayer(backgroundGradient, at: 0)
configureTextField(usernameTextField)
configureTextField(passwordTextField)
}
func configureTextField(_ textField: UITextField) {
let textFieldPaddingViewFrame = CGRect(x: 0.0, y: 0.0, width: 13.0, height: 0.0)
let textFieldPaddingView = UIView(frame: textFieldPaddingViewFrame)
textField.leftView = textFieldPaddingView
textField.leftViewMode = .always
textField.textColor = Constants.UI.OrangeColor
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder!, attributes: [NSForegroundColorAttributeName: Constants.UI.OrangeColor])
textField.delegate = self
}
}
// MARK: - LoginViewController (Notifications)
private extension LoginViewController {
func subscribeToNotification(_ notification: NSNotification.Name, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: notification, object: nil)
}
func unsubscribeFromAllNotifications() {
NotificationCenter.default.removeObserver(self)
}
}
| 5549ae758ab48bbf55f095cc2f96f58a | 30.786026 | 164 | 0.631955 | false | false | false | false |
SwiftFMI/iOS_2017_2018 | refs/heads/master | Upr/28.10.17/SecondTaskComplexSolution/SecondTaskComplexSolution/Model/Song.swift | apache-2.0 | 1 | //
// Song.swift
// SecondTaskComplexSolution
//
// Created by Petko Haydushki on 31.10.17.
// Copyright © 2017 Petko Haydushki. All rights reserved.
//
import UIKit
class Song: NSObject {
var name = "";
var artistName = "";
var artworkImageName = "";
override init() {
super.init()
}
init(name : String,artist : String, artwork : String) {
self.name = name;
self.artistName = artist;
self.artworkImageName = artwork;
}
}
| f048c76218c7dd972e115060e08e53f6 | 17.814815 | 59 | 0.580709 | false | false | false | false |
netguru/ResponseDetective | refs/heads/develop | ResponseDetective/Tests/Specs/RequestRepresentationSpec.swift | mit | 1 | //
// RequestRepresentationSpec.swift
//
// Copyright © 2016-2020 Netguru S.A. All rights reserved.
// Licensed under the MIT License.
//
import Foundation
import Nimble
import ResponseDetective
import Quick
internal final class RequestRepresentationSpec: QuickSpec {
override func spec() {
describe("RequestRepresentation") {
context("after initializing with a request") {
let fixtureRequest = NSMutableURLRequest(
URL: URL(string: "https://httpbin.org/post")!,
HTTPMethod: "POST",
headerFields: [
"Content-Type": "application/json",
"X-Foo": "bar",
],
HTTPBody: try! JSONSerialization.data(withJSONObject: ["foo": "bar"], options: [])
)
let fixtureIdentifier = "1"
var sut: RequestRepresentation!
beforeEach {
sut = RequestRepresentation(identifier: fixtureIdentifier, request: fixtureRequest as URLRequest, deserializedBody: nil)
}
it("should have a correct identifier") {
expect(sut.identifier).to(equal(fixtureIdentifier))
}
it("should have a correct URLString") {
expect(sut.urlString).to(equal(fixtureRequest.url!.absoluteString))
}
it("should have a correct method") {
expect(sut.method).to(equal(fixtureRequest.httpMethod))
}
it("should have correct headers") {
expect(sut.headers).to(equal(fixtureRequest.allHTTPHeaderFields))
}
it("should have a correct body") {
expect(sut.body).to(equal(fixtureRequest.httpBody))
}
}
}
}
}
private extension NSMutableURLRequest {
convenience init(URL: Foundation.URL, HTTPMethod: String, headerFields: [String: String], HTTPBody: Data?) {
self.init(url: URL)
self.httpMethod = HTTPMethod
self.allHTTPHeaderFields = headerFields
self.httpBody = HTTPBody
}
}
| 14b771321330c8c0eadaea70dce52f18 | 22.381579 | 125 | 0.691615 | false | false | false | false |
PumpMagic/ostrich | refs/heads/master | gameboy/gameboy/Source/Memories/RAM.swift | mit | 1 | //
// RAM.swift
// ostrichframework
//
// Created by Ryan Conway on 4/4/16.
// Copyright © 2016 Ryan Conway. All rights reserved.
//
import Foundation
/// A random-access memory.
open class RAM: Memory, HandlesWrites {
var data: Array<UInt8>
/// An offset: specifies what memory location the first byte of the supplied data occupies
open let firstAddress: Address
open var lastAddress: Address {
return UInt16(UInt32(self.firstAddress) + UInt32(self.data.count) - 1)
}
open var addressRange: CountableClosedRange<Address> {
return self.firstAddress ... self.lastAddress
}
var addressRangeString: String {
return "[\(self.firstAddress.hexString), \(self.lastAddress.hexString)]"
}
public init(size: UInt16, fillByte: UInt8, firstAddress: Address) {
self.data = Array<UInt8>(repeating: fillByte, count: Int(size))
self.firstAddress = firstAddress
}
public convenience init(size: UInt16) {
self.init(size: size, fillByte: 0x00, firstAddress: 0x0000)
}
open func read(_ addr: Address) -> UInt8 {
if addr < self.firstAddress ||
Int(addr) > Int(self.firstAddress) + Int(self.data.count)
{
print("FATAL: attempt to access address \(addr.hexString) but our range is \(self.addressRangeString)")
exit(1)
}
return self.data[Int(addr - self.firstAddress)]
}
open func write(_ val: UInt8, to addr: Address) {
self.data[Int(addr - self.firstAddress)] = val
}
open func nonzeroes() -> String {
var nonzeroes: String = ""
for (index, datum) in self.data.enumerated() {
if datum != 0x00 {
nonzeroes += "\((firstAddress + UInt16(index)).hexString): \(datum.hexString) "
}
}
return nonzeroes
}
}
| bec23d29301a060ef6241020ad954a13 | 28.984375 | 115 | 0.601876 | false | false | false | false |
wyzzarz/SwiftCollection | refs/heads/master | SwiftCollectionExample/SwiftCollectionExample/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// SwiftCollectionExample
//
// Copyright 2017 Warner Zee
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import SwiftCollection
/// `Document` sublcasses `SCDocument` and provides an additional field `name`.
///
/// Loading from persistent storage is updated for the `name` field.
class Document: SCDocument {
var name: String?
convenience init(id: SwiftCollection.Id, name: String) {
self.init(id: id)
self.name = name
}
override func load(propertyWithName name: String, currentValue: Any, potentialValue: Any, json: AnyObject) {
switch name {
case Keys.name: if let value = (json as? [String: Any])?[Keys.name] as? String { self.name = value }
default: super.load(propertyWithName: name, currentValue: currentValue, potentialValue: potentialValue, json: json)
}
}
}
extension Document.Keys {
static let name = "name"
}
/// `OrderedSet` provides a concrete implementation of `SCOrderedSet` for a collection of `Document`
/// objects.
///
/// A new persistent storage key is provided. And loading from persistent storage is performed
/// for documents in the collection.
class OrderedSet: SCOrderedSet<Document> {
override func storageKey() -> String {
return "OrderedSetExample"
}
override func load(jsonObject json: AnyObject) throws -> AnyObject? {
if let array = json as? [AnyObject] {
for item in array {
try? append(Document(json: item))
}
}
return json
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// create a new ordered set
let orderedSet = OrderedSet()
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
// add documents to the collection
try? orderedSet.append(Document(id: 1, name: "First"))
try? orderedSet.append(Document(id: 2, name: "Second"))
try? orderedSet.append(Document(id: 3, name: "Third"))
tableView.dataSource = self
tableView.delegate = self
tableView.frame = UIEdgeInsetsInsetRect(self.view.frame, UIEdgeInsetsMake(20, 0, 0, 0))
self.view.addSubview(tableView)
DispatchQueue.main.async {
self.saveAndLoad()
}
}
/// An example to save the collection to persistent storage. And load saved data from persistent
/// storage.
func saveAndLoad() {
try? orderedSet.save(jsonStorage: .userDefaults) { (success) in
print("saved", success)
let anotherOrderedSet = OrderedSet()
try? anotherOrderedSet.load(jsonStorage: .userDefaults) { (success, json) in
print("loaded", success)
try? OrderedSet().remove(jsonStorage: .userDefaults, completion: nil)
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return orderedSet.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellId = "doc"
// get cell
var cell: UITableViewCell?
if let aCell = tableView.dequeueReusableCell(withIdentifier: cellId) { cell = aCell }
if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: cellId) }
// setup cell
let doc = orderedSet[orderedSet.index(orderedSet.startIndex, offsetBy: indexPath.row)]
cell?.textLabel?.text = doc.name
cell?.detailTextLabel?.text = String(doc.id)
return cell!
}
}
| 215d3eb60ab4bd094d3cf0fe382996f4 | 29.171642 | 119 | 0.690329 | false | false | false | false |
mbeloded/LoadingViewController | refs/heads/master | LoadingViewController/Classes/LoadingViewController.swift | mit | 1 | //
// BaseLoadingViewController.swift
// LoadingControllerDemo
//
// Created by Sapozhnik Ivan on 23.06.16.
// Copyright © 2016 Sapozhnik Ivan. All rights reserved.
//
import UIKit
// This extension should be used for testing purposes
extension UIViewController {
public func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
}
public enum ContentType: Int {
case undefined = 0
case empty
case noData
case failure
case content
case loading
}
let FromViewKey = "fromView"
let ToViewKey = "toView"
let AnimatedKey = "animated"
let ScreenKey = "screen"
let animationDuration: TimeInterval = 0.3
typealias AnimationDict = Dictionary<String, AnyObject>
public typealias ActionHandler = () -> ()
open class LoadingViewController: UIViewController {
@IBOutlet open var contentView: UIView!
open var lastError: NSError?
var defaultLoadingColor = UIColor(colorLiteralRed: 250/255, green: 250/255, blue: 250/255, alpha: 1)
open var loadingViewColor: UIColor?
open var noDataViewColor: UIColor?
open var errorViewColor: UIColor?
open var errorActionTitle: String? = NSLocalizedString("Try again", comment: "")
var visibleContentType: ContentType = .undefined
var activeView: UIView?
var animationQueue = Array<AnimationDict>()
var currentAnimation: AnimationDict?
open var customErrorTitle: String?
open var customErrorMessage: String?
open var errorTitle: String {
get {
return lastError?.localizedDescription ?? customErrorTitle ?? NSLocalizedString("Oops, something went wrong", comment: "")
}
}
open var errorMessage: String {
get {
return lastError?.localizedFailureReason ?? customErrorMessage ?? NSLocalizedString("Please try again later", comment: "")
}
}
open var errorIcon: UIImage?
open var noDataMessage: String = NSLocalizedString("No data available. Please, try another request.", comment: "")
var contentViewAllwaysAvailabel: Bool = false
//MARK:- Default views
func defaultNoDataView() -> UIView {
let view = NoDataView.viewWithStyle(style: noDataViewStyle())
view.backgroundColor = noDataViewColor ?? loadingViewColor
view.message = noDataMessage
return view
}
func defaultErrorView(_ action: ActionHandler? = nil) -> UIView {
let view = ErrorView.viewWithStyle(errorViewStyle(), actionHandler: action)
view.backgroundColor = errorViewColor ?? loadingViewColor
view.title = errorTitle
view.message = errorMessage
view.image = errorIcon
view.actionTitle = errorActionTitle
return view
}
func defaultLoadingView() -> UIView {
let view = LoadingView.viewWithStyle(loadingViewStyle())
view.backgroundColor = loadingViewColor ?? defaultLoadingColor
//TODO: add title, background image, etc.
view.title = "Loading"
return view
}
open func loadingViewStyle() -> LoadingViewStyle {
return .indicator
}
open func errorViewStyle() -> ErrorViewStyle {
return .simple
}
open func noDataViewStyle() -> NoDataViewStyle {
return .Simple
}
open func showsErrorView() -> Bool {
return true
}
open func showsNoDataView() -> Bool {
return true
}
open func showsLoadingView() -> Bool {
return true
}
func addView(_ viewToAdd: UIView) {
view.addSubview(viewToAdd)
viewToAdd.translatesAutoresizingMaskIntoConstraints = false
let bindings = ["view": viewToAdd]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[view]|", options: [.alignAllLeading, .alignAllTrailing], metrics: nil, views: bindings))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [.alignAllTop, .alignAllBottom], metrics: nil, views: bindings))
view.layoutIfNeeded()
}
func viewForScreen(_ contentType: ContentType, action: ActionHandler? = nil) -> UIView {
switch contentType {
case .content:
return contentView
case .failure:
return defaultErrorView(action)
case .loading:
return defaultLoadingView()
case .noData:
return defaultNoDataView()
case .undefined, .empty:
let result = UIView()
result.backgroundColor = .red
return result
}
}
// TODO: add ActionHandler support to handle 'Retry' tap on ErrorViews
open func setVisibleScreen(_ contentType: ContentType, animated: Bool = true, actionHandler:ActionHandler? = nil) {
if visibleContentType != contentType {
visibleContentType = contentType
let view = viewForScreen(visibleContentType, action: actionHandler)
setActiveView(view, animated: animated)
}
}
func setActiveView(_ viewToSet: UIView, animated: Bool) {
if viewToSet != activeView {
let oldView = activeView ?? nil
activeView = viewToSet
let animation = animationFormView(oldView, toView: viewToSet, contentType: visibleContentType, animated: animated)
if animated {
addAnimation(animation)
} else {
performAnimation(animation)
}
}
}
fileprivate func animationFormView(_ fromView: UIView?, toView: UIView, contentType: ContentType, animated: Bool) -> AnimationDict {
var data = AnimationDict()
data[FromViewKey] = fromView
data[ToViewKey] = toView
data[AnimatedKey] = animated as AnyObject?
data[ScreenKey] = contentType.rawValue as AnyObject?
return data
}
fileprivate func mergedAnimation(_ animation1: AnimationDict, animation2: AnimationDict) -> AnimationDict {
var result: AnimationDict = [:]
let fromView = animation1[FromViewKey]
let toView = animation2[ToViewKey]
let contentType = animation2[ScreenKey]
let animated = animation2[AnimatedKey]
if (fromView as? UIView) != nil {
result[FromViewKey] = fromView!
}
if (toView as? UIView) != nil {
result[ToViewKey] = toView!
}
if (contentType as? ContentType.RawValue) != nil {
result[ScreenKey] = contentType!
}
if (animated as? Bool) != nil {
result[AnimatedKey] = animated!
}
return result
}
fileprivate func addAnimation(_ animation: AnimationDict) {
if animationQueue.count > 0 {
let animationFromQueue = animationQueue.first!
animationQueue.removeAll()
animationQueue.append(mergedAnimation(animationFromQueue, animation2: animation))
} else {
animationQueue.insert(animation, at: 0)
}
delay(0.0) {
self.startNextAnimationIfNeeded()
}
}
fileprivate func cancellAllAnimations() {
animationQueue.removeAll()
currentAnimation = nil
}
fileprivate func performAnimation(_ animation: AnimationDict) {
let fromView = animation[FromViewKey]
let toView = animation[ToViewKey]
let contentType = animation[ScreenKey]
let animated = animation[AnimatedKey]
if (animated as? Bool) != true {
for queueAnimation in animationQueue.reversed() {
let fromView = queueAnimation[FromViewKey]
let toView = queueAnimation[ToViewKey]
let contentType = queueAnimation[ScreenKey]
performTransitionFromView(fromView as? UIView, toView: toView! as! UIView, animated: false, contentType: ContentType(rawValue: contentType! as! Int)!)
}
}
performTransitionFromView(fromView as? UIView, toView: toView! as! UIView, animated: animated! as! Bool, contentType: ContentType(rawValue: contentType! as! Int)!)
}
fileprivate func isContentViewAvailable(_ checkingView: UIView?) -> Bool {
var result = false
if checkingView == nil {
return result
}
let theView = checkingView!
while let theViewUnw = theView.superview {
if theViewUnw == self.view { break }
if theViewUnw == self.contentView {
result = true
break
}
}
return result
}
fileprivate func animationOptions() -> UIViewAnimationOptions {
return [.transitionCrossDissolve, .layoutSubviews]
}
fileprivate func performTransitionFromView(_ fromView: UIView?, toView: UIView, animated: Bool, contentType: ContentType) {
func finish() {
currentAnimation = nil
startNextAnimationIfNeeded()
}
if contentType != .content {
addView(toView)
}
let theFromView = fromView
let theFromViewInConentView = isContentViewAvailable(theFromView)
let fromViewIsContentView = (theFromView == self.contentView)
let theToView = toView
let theToViewInContentView = isContentViewAvailable(theToView)
let toViewIsContentView = (theToView == self.contentView)
if fromViewIsContentView && toViewIsContentView {
finish()
return
}
let contentViewAlpha = (theToViewInContentView || toViewIsContentView) ? 1.0 : 0.0
let removesFromView = !fromViewIsContentView
let animatesToView = (!theFromViewInConentView || !fromViewIsContentView)
let animatesFromView = !fromViewIsContentView
func animations() {
if animatesToView {
toView.alpha = 1.0
}
if animatesFromView {
if let fromView = fromView {
fromView.alpha = 0.0
}
}
self.contentView.alpha = CGFloat(contentViewAlpha)
}
func completion() {
if removesFromView {
if let fromView = fromView {
fromView.removeFromSuperview()
}
}
finish()
}
if animated {
theToView.alpha = 0.0
UIView.animate(withDuration: animationDuration, delay: 0.0, options: animationOptions(), animations: {
animations()
}, completion: { finished in
if finished {
completion()
}
})
} else {
animations()
completion()
}
}
fileprivate func startNextAnimationIfNeeded() {
guard self.currentAnimation == nil else { return }
guard let lastAnimation = animationQueue.last else { return }
self.currentAnimation = lastAnimation
self.animationQueue.removeLast()
self.performAnimation(lastAnimation)
}
}
| a7e0ddd12a78f0f1629d4d488f1cb6ac | 27.114035 | 165 | 0.725533 | false | false | false | false |
huangboju/Moots | refs/heads/master | UICollectionViewLayout/CollectionKit-master/Examples/PresenterExample/EdgeShrinkPresenter.swift | mit | 1 | //
// EdgeShrinkPresenter.swift
// CollectionKit
//
// Created by Luke Zhao on 2017-08-15.
// Copyright © 2017 lkzhao. All rights reserved.
//
import UIKit
import CollectionKit
open class EdgeShrinkPresenter: CollectionPresenter {
open override func update(collectionView: CollectionView, view: UIView, at: Int, frame: CGRect) {
super.update(collectionView: collectionView, view: view, at: at, frame: frame)
let effectiveRange: ClosedRange<CGFloat> = -500...16
let absolutePosition = frame.origin - collectionView.contentOffset
if absolutePosition.x < effectiveRange.lowerBound {
view.transform = .identity
return
}
let scale = (absolutePosition.x.clamp(effectiveRange.lowerBound, effectiveRange.upperBound) - effectiveRange.lowerBound) / (effectiveRange.upperBound - effectiveRange.lowerBound)
let alpha = scale
let translation = absolutePosition.x < effectiveRange.upperBound ? effectiveRange.upperBound - absolutePosition.x - (1 - scale) / 2 * frame.width : 0
view.alpha = alpha
view.transform = CGAffineTransform.identity.translatedBy(x: translation, y: 0).scaledBy(x: scale, y: scale)
}
}
| 5058a9ab83118594e9272267d3bef23e | 41.814815 | 182 | 0.740484 | false | false | false | false |
blokadaorg/blokada | refs/heads/main | ios/App/Model/StatsModel.swift | mpl-2.0 | 1 | //
// This file is part of Blokada.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
struct Stats: Codable {
let allowed: UInt64
let denied: UInt64
let entries: [HistoryEntry]
}
struct HistoryEntry: Codable {
let name: String
let type: HistoryEntryType
let time: Date
let requests: UInt64
let device: String
let list: String?
}
enum HistoryEntryType: Int, Codable {
case whitelisted
case blocked
case passed
}
extension HistoryEntry: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(type)
hasher.combine(device)
}
}
extension HistoryEntry: Equatable {
static func == (lhs: HistoryEntry, rhs: HistoryEntry) -> Bool {
lhs.name == rhs.name && lhs.type == rhs.type && lhs.device == rhs.device
}
}
| e946ec5152f6fad90b34ddddea206c61 | 21.854167 | 80 | 0.659982 | false | false | false | false |
ilyapuchka/SwiftNetworking | refs/heads/master | SwiftNetworking/Pagination.swift | mit | 1 | //
// Pagination.swift
// SwiftNetworking
//
// Created by Ilya Puchka on 11.09.15.
// Copyright © 2015 Ilya Puchka. All rights reserved.
//
import Foundation
public protocol PaginationMetadata: JSONDecodable {
var page: Int {get}
var limit: Int {get}
var pages: Int {get}
init(page: Int, limit: Int, pages: Int)
}
extension PaginationMetadata {
func nextPage() -> Self? {
guard page < pages else { return nil }
return Self(page: page+1, limit: limit, pages: pages)
}
func prevPage() -> Self? {
guard page > 0 else { return nil }
return Self(page: page-1, limit: limit, pages: pages)
}
}
public protocol Pagination {
var metadata: PaginationMetadataType? {get}
typealias PaginationMetadataType: PaginationMetadata
init(metadata: PaginationMetadataType?)
}
extension Pagination {
public init(page: Int, limit: Int, pages: Int = 0) {
self.init(metadata: PaginationMetadataType(page: page, limit: limit, pages: pages))
}
public func nextPage() -> Self? {
guard let next = metadata?.nextPage() else { return nil }
return Self(metadata: next)
}
public func prevPage() -> Self? {
guard let prev = metadata?.prevPage() else { return nil }
return Self(metadata: prev)
}
}
public protocol AnyPagination: Pagination, JSONDecodable, APIResponseDecodable {
typealias Element: JSONDecodable
var items: [Element] {get}
init(items: [Element], metadata: PaginationMetadataType?)
static func paginationKey() -> String
static func itemsKey() -> String
}
extension AnyPagination {
public init?(jsonDictionary: JSONDictionary?) {
guard let
json = JSONObject(jsonDictionary),
items: [Element] = json.keyPath(Self.itemsKey()),
metadata: PaginationMetadataType = json.keyPath(Self.paginationKey())
else {
return nil
}
self.init(items: items, metadata: metadata)
}
}
extension AnyPagination {
public init?(apiResponseData: NSData) throws {
guard let jsonDictionary: JSONDictionary = try apiResponseData.decodeToJSON() else {
return nil
}
self.init(jsonDictionary: jsonDictionary)
}
}
public struct PaginationOf<T: JSONDecodable, M: PaginationMetadata>: AnyPagination {
public var items: [T]
public var metadata: M?
public init(items: [T] = [], metadata: M? = nil) {
self.items = items
self.metadata = metadata
}
public init(metadata: M?) {
self.init(items: [], metadata: metadata)
}
}
extension AnyPagination {
public static func paginationKey() -> String {
return "pagination"
}
public static func itemsKey() -> String {
return "items"
}
}
| 7461be6f4f17998a2dc672f3b1c2c23e | 24.086957 | 92 | 0.623224 | false | false | false | false |
duycao2506/SASCoffeeIOS | refs/heads/master | SAS Coffee/Controller/KasperViewController.swift | gpl-3.0 | 1 | //
// KasperViewController.swift
// SAS Coffee
//
// Created by Duy Cao on 8/30/17.
// Copyright © 2017 Duy Cao. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class KasperViewController: UIViewController, NVActivityIndicatorViewable, KasperObserverDelegate {
var activityData : ActivityData!
var backcomplete : (() -> Void)?
var continueCondition : ((Any, Any) -> Bool)?
@IBOutlet weak var notiViewHeightConstraint : NSLayoutConstraint?
@IBOutlet weak var notiTextview : UILabel?
var maxheightnoti = 36
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func actionBack (_sender: Any){
if let nav = self.navigationController {
if nav.viewControllers.first != self {
self.navigationController?.popViewController(animated: true)
}
}
dismiss(animated: true, completion: backcomplete)
}
func showNotification(){
if self.notiViewHeightConstraint != nil {
self.view.layoutIfNeeded()
self.notiViewHeightConstraint?.constant = CGFloat(maxheightnoti)
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
})
}
}
func hideNotfication(){
if self.notiViewHeightConstraint != nil {
self.view.layoutIfNeeded()
self.notiViewHeightConstraint?.constant = 0
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
})
}
}
func callback(_ code: Int?, _ succ: Bool?, _ data: Any) {
}
}
| ace8107c583bc61960570494b4f515f1 | 27.614458 | 106 | 0.625684 | false | false | false | false |
hsusmita/SHResponsiveLabel | refs/heads/master | SHResponsiveLabel/Source/Demo/ExpandableCell.swift | mit | 1 | //
// ExpandibleCell.swift
// SHResponsiveLabel
//
// Created by hsusmita on 11/08/15.
// Copyright (c) 2015 hsusmita.com. All rights reserved.
//
import UIKit
let kCollapseToken = "Read Less"
class ExpandableCell: UITableViewCell {
@IBOutlet weak var customLabel: SHResponsiveLabel!
var delegate : ExpandableCellDelegate?
override func awakeFromNib() {
let token = NSAttributedString(string: "...Read More",
attributes: [NSFontAttributeName:self.customLabel.font,
NSForegroundColorAttributeName:UIColor.brownColor(),
RLHighlightedBackgroundColorAttributeName:UIColor.blackColor(),
RLHighlightedForegroundColorAttributeName:UIColor.greenColor()])
let action = PatternTapResponder {(tappedString)-> (Void) in
self.delegate?.didTapOnMoreButton(self)
let messageString = "You have tapped token string"
}
customLabel.setAttributedTruncationToken(token, action: action)
}
func configureCell(text:String, shouldExpand:Bool) {
if shouldExpand {
//expand
let expandedString = text + kCollapseToken
let finalString = NSMutableAttributedString(string: expandedString)
let action = PatternTapResponder{(tappedString)-> (Void) in
self.delegate?.didTapOnMoreButton(self)
}
let range = NSMakeRange(count(text), count(kCollapseToken))
finalString.addAttributes([NSForegroundColorAttributeName:UIColor.redColor(),
RLTapResponderAttributeName:action], range: range)
finalString.addAttribute( NSFontAttributeName,value:customLabel.font, range: NSMakeRange(0,finalString.length))
// customLabel.numberOfLines = 0
// customLabel.attributedText = finalString
customLabel.customTruncationEnabled = false
customLabel.setAttributedTextWithTruncation(finalString, truncation: false)
}else {
// customLabel.numberOfLines = 4
// customLabel.text = text
customLabel.customTruncationEnabled = true
customLabel.setTextWithTruncation(text, truncation: true)
}
}
}
protocol ExpandableCellDelegate {
func didTapOnMoreButton(cell:ExpandableCell)
}
| 6ba859c652c17fbe153c0a7e9bdbf643 | 34.622951 | 118 | 0.720663 | false | false | false | false |
buyiyang/iosstar | refs/heads/master | iOSStar/Scenes/Market/CustomView/FansListHeaderView.swift | gpl-3.0 | 3 | //
// FansListHeaderView.swift
// iOSStar
//
// Created by J-bb on 17/5/19.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
protocol SelectFansDelegate {
func selectAtIndex(index:Int)
}
class FansListHeaderView: UITableViewHeaderFooterView {
var currentSelectIndex = 0
var delegate:SelectFansDelegate?
lazy var buyButton:UIButton = {
let button = UIButton(type: .custom)
button.tag = 2222
button.setTitle("求购榜单", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 13.0)
button.setTitleColor(UIColor(hexString: "333333"), for: .normal)
return button
}()
lazy var sellButton:UIButton = {
let button = UIButton(type: .custom)
button.tag = 2223
button.titleLabel?.font = UIFont.systemFont(ofSize: 13.0)
button.setTitle("转让榜单", for: .normal)
button.setTitleColor(UIColor(hexString: "333333"), for: .normal)
return button
}()
lazy var backView:UIView = {
let view = UIView()
view.layer.cornerRadius = 12
view.backgroundColor = UIColor(hexString: "ECECEC")
return view
}()
lazy var imageView:UIImageView = {
let imageView = UIImageView(image: UIImage.init(named: "fanslist_bangdan"))
imageView.isUserInteractionEnabled = true
return imageView
}()
var isShowImage = false {
didSet {
imageView.isHidden = !isShowImage
if !isShowImage {
buyButton.snp.remakeConstraints({ (make) in
make.centerX.equalTo(kScreenWidth / 4)
make.centerY.equalTo(self)
})
sellButton.snp.remakeConstraints({ (make) in
make.centerX.equalTo(kScreenWidth / 4 * 3)
make.centerY.equalTo(buyButton)
})
}
}
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIColor(hexString: "fafafa")
addSubview(buyButton)
addSubview(sellButton)
addSubview(backView)
backView.addSubview(imageView)
buyButton.snp.makeConstraints { (make) in
make.centerX.equalTo(kScreenWidth / 4 + 5)
make.centerY.equalTo(self)
}
sellButton.snp.makeConstraints { (make) in
make.centerX.equalTo(kScreenWidth / 4 * 3 + 5)
make.centerY.equalTo(buyButton)
}
backView.snp.makeConstraints { (make) in
make.centerX.equalTo(kScreenWidth / 4 - 4)
make.centerY.equalTo(buyButton.snp.centerY)
make.width.equalTo(80)
make.height.equalTo(23)
}
imageView.snp.makeConstraints { (make) in
make.centerX.equalTo(backView)
make.centerY.equalTo(backView.snp.centerY).offset(-6)
}
bringSubview(toFront: buyButton)
bringSubview(toFront: sellButton)
buyButton.addTarget(self, action: #selector(selectAtIndex(sender:)), for: .touchUpInside)
sellButton.addTarget(self, action: #selector(selectAtIndex(sender:)), for: .touchUpInside)
}
func settitles(titles:[String]) {
buyButton.setTitle(titles.first, for: .normal)
sellButton.setTitle(titles.last, for: .normal)
}
func selectIndex(index:Int) {
currentSelectIndex = index
var x:CGFloat = 0.0
if index == 0 {
x = kScreenWidth * 0.25
} else {
x = kScreenWidth * 0.75
}
backView.snp.remakeConstraints { (make) in
make.centerX.equalTo(x)
make.centerY.equalTo(buyButton.snp.centerY)
make.width.equalTo(80)
make.height.equalTo(23)
}
self.backView.setNeedsDisplay()
self.backView.setNeedsLayout()
}
func selectAtIndex(sender:UIButton) {
let index = sender.tag - 2222
// if index == currentSelectIndex {
// return
// }
currentSelectIndex = index
var x:CGFloat = 0.0
if index == 0 {
x = kScreenWidth * 0.25
} else {
x = kScreenWidth * 0.75
}
UIView.animate(withDuration: 0.5) {
self.backView.center = CGPoint(x: x, y: self.backView.center.y)
}
delegate?.selectAtIndex(index: index)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| a5ee2ecf8f1e2d2df5fd0a9ac68fc88f | 31.195804 | 98 | 0.584057 | false | false | false | false |
wscqs/QSWB | refs/heads/master | DSWeibo/DSWeibo/Classes/OAuth/OAuthViewController.swift | mit | 1 | //
// OAuthViewController.swift
// DSWeibo
//
// Created by xiaomage on 15/9/10.
// Copyright © 2015年 小码哥. All rights reserved.
//
import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {
let WB_App_Key = "2058474898"
let WB_App_Secret = "a3ec3f8fa797fac21d702671a0cbfbf1"
let WB_redirect_uri = "https://wscqs.github.io/"
override func loadView() {
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// 0.初始化导航条
navigationItem.title = "小码哥微博"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
// 1.获取未授权的RequestToken
// 要求SSL1.2
let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_redirect_uri)"
let url = NSURL(string: urlStr)
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
func close()
{
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - 懒加载
private lazy var webView: UIWebView = {
let wv = UIWebView()
wv.delegate = self
return wv
}()
}
extension OAuthViewController: UIWebViewDelegate
{
// 返回ture正常加载 , 返回false不加载
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
// 1.判断是否是授权回调页面, 如果不是就继续加载
let urlStr = request.URL!.absoluteString
if !urlStr.hasPrefix(WB_redirect_uri)
{
// 继续加载
return true
}
// 2.判断是否授权成功
let codeStr = "code="
if request.URL!.query!.hasPrefix(codeStr)
{
// 授权成功
// 1.取出已经授权的RequestToken
let code = request.URL!.query?.substringFromIndex(codeStr.endIndex)
// 2.利用已经授权的RequestToken换取AccessToken
loadAccessToken(code!)
}else
{
// 取消授权
// 关闭界面
close()
}
return false
}
func webViewDidStartLoad(webView: UIWebView) {
// 提示用户正在加载
SVProgressHUD.showInfoWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black)
}
func webViewDidFinishLoad(webView: UIWebView) {
// 关闭提示
SVProgressHUD.dismiss()
}
/**
换取AccessToken
:param: code 已经授权的RequestToken
*/
private func loadAccessToken(code: String)
{
// 1.定义路径
let path = "oauth2/access_token"
// 2.封装参数
let params = ["client_id":WB_App_Key, "client_secret":WB_App_Secret, "grant_type":"authorization_code", "code":code, "redirect_uri":WB_redirect_uri]
// 3.发送POST请求
NetworkTools.shareNetworkTools().POST(path, parameters: params, success: { (_, JSON) -> Void in
// 1.字典转模型
let account = UserAccount(dict: JSON as! [String : AnyObject])
// 2.获取用户信息
account.loadUserInfo { (account, error) -> () in
if account != nil
{
account!.saveAccount()
// 去欢迎界面
NSNotificationCenter.defaultCenter().postNotificationName(XMGSwitchRootViewControllerKey, object: false)
return
}
SVProgressHUD.showInfoWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Black)
}
}) { (_, error) -> Void in
print(error)
}
}
}
| 7de6012b01079247d0e24529b9743d82 | 27.700787 | 156 | 0.564883 | false | false | false | false |
Geor9eLau/WorkHelper | refs/heads/master | WorkoutHelper/HomePageViewController.swift | mit | 1 | //
// HomePageViewController.swift
// WorkoutHelper
//
// Created by George on 2016/12/26.
// Copyright © 2016年 George. All rights reserved.
//
import UIKit
class HomePageViewController: BaseViewController, iCarouselDataSource, iCarouselDelegate {
@IBOutlet weak var carousel: iCarousel!
// private lazy var colltectionView: UICollectionView = {
// let layout = UICollectionViewFlowLayout()
// layout.itemSize = CGSize(width: 70, height:90.0)
// layout.minimumLineSpacing = 5.0;
//
// layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20)
// let tmpCollectionView = UICollectionView(frame: CGRect(x: 0, y: 100, width: SCREEN_WIDTH , height: SCREEN_HEIGHT - 250), collectionViewLayout: layout)
// tmpCollectionView.delegate = self
// tmpCollectionView.dataSource = self
// tmpCollectionView.register(UINib.init(nibName: "ChooseCollectionCell", bundle: nil), forCellWithReuseIdentifier: "cell")
// tmpCollectionView.collectionViewLayout = layout
// tmpCollectionView.backgroundColor = UIColor.clear
// return tmpCollectionView
// }()
private var recordTf: UITextField = {
let tmp = UITextField(frame: CGRect(x: 20, y: SCREEN_HEIGHT - 200, width: SCREEN_WIDTH - 40, height: 150))
tmp.allowsEditingTextAttributes = false
tmp.isEnabled = false
return tmp
}()
private var dataSource: [BodyPart] = ALL_BODY_PART_CHOICES
override func viewDidLoad() {
super.viewDidLoad()
title = "Home Page"
carousel.type = .coverFlow
carousel.bounces = false
carousel.currentItemIndex = 1
// Do any additional setup after loading the view.
}
// MARK: - Private
private func setupUI() {
}
// MARK: - Event Handler
@IBAction func workoutBtnDidClicked(_ sender: UIButton) {
let motionVC = MotionViewController(part: dataSource[carousel.currentItemIndex])
motionVC.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(motionVC, animated: true)
}
// MARK: - iCarouselDataSource
func numberOfItems(in carousel: iCarousel) -> Int {
return dataSource.count
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
var itemView: CarouselItemView
let part = dataSource[index]
if (view as? CarouselItemView) != nil{
itemView = view as! CarouselItemView
} else {
//don't do anything specific to the index within
//this `if ... else` statement because the view will be
//recycled and used with other index values later
itemView = CarouselItemView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
}
itemView.imgView.image = UIImage(named: part.rawValue)
itemView.titleLbl.text = part.rawValue
return itemView
}
// MARK: - iCarouselDelegate
func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
if (option == .spacing) {
return value * 1.1
}
return value
}
}
| f698d587efeeda51cd660f774e0ea931 | 32.11 | 160 | 0.631833 | false | false | false | false |
ykay/twitter-with-menu | refs/heads/master | Twitter/TweetView.swift | mit | 1 | //
// TweetView.swift
// Twitter
//
// Created by Yuichi Kuroda on 10/10/15.
// Copyright © 2015 Yuichi Kuroda. All rights reserved.
//
import UIKit
class TweetView: UIView {
var nameLabel: UILabel!
var screennameLabel: UILabel!
var tweetTextLabel: UILabel!
var dateLabel: UILabel!
var favoriteLabel: UILabel!
var profileThumbImageView: UIImageView!
var favoriteImageView: UIImageView!
var retweetImageView: UIImageView!
var replyImageView: UIImageView!
var replyActionHandler: ((tweetId: String, tweetUserScreenname: String) -> ())?
var userProfileShowHandler: ((user: User) -> ())?
var tweet: Tweet! {
didSet {
nameLabel.text = tweet.user!.name
screennameLabel.text = "@\(tweet.user!.screenname)"
tweetTextLabel.text = tweet.text
dateLabel.text = tweet.createdAt?.description
profileThumbImageView.setImageWithURL(tweet.user!.profileImageUrl)
if tweet.favorited {
favoriteImageView.image = UIImage(named: "favorite_on.png")
favoriteLabel.textColor = UIColor(red:0.99, green:0.61, blue:0.16, alpha:1.0)
} else {
favoriteImageView.image = UIImage(named: "favorite_hover.png")
favoriteLabel.textColor = UIColor.lightGrayColor()
}
favoriteLabel.text = "\(tweet.favoriteCount)"
if tweet.user!.name == User.currentUser!.name {
retweetImageView.image = UIImage(named: "retweet.png")
} else {
if tweet.retweeted {
retweetImageView.image = UIImage(named: "retweet_on.png")
} else {
retweetImageView.image = UIImage(named: "retweet_hover.png")
}
}
/* Fade in code
profileThumbImageView.setImageWithURLRequest(NSURLRequest(URL: tweet.user!.profileImageUrl!), placeholderImage: nil,
success: { (request: NSURLRequest!, response: NSHTTPURLResponse!, image: UIImage!) -> Void in
let retrievedImage = image
UIView.transitionWithView(self.profileThumbImageView, duration: 2.0, options: UIViewAnimationOptions.TransitionCrossDissolve,
animations: { () -> Void in
self.profileThumbImageView.image = retrievedImage
},
completion: nil)
},
failure: { (request: NSURLRequest!, response: NSHTTPURLResponse!, error: NSError!) -> Void in
})*/
}
}
// Since super.init(coder) is failable, we must conform to that.
init?(_ coder: NSCoder?, frame: CGRect?) {
if let coder = coder {
super.init(coder: coder)
} else {
super.init(frame: frame ?? CGRectZero)
}
setupSubviews()
setupConstraints()
}
override convenience init(frame: CGRect) {
// Since we won't call the failable init(coder), we know this call will never fail, thus the '!' force unwrap is okay.
self.init(nil, frame: frame)!
}
required convenience init?(coder: NSCoder) {
self.init(coder, frame: nil)
}
func setupSubviews() {
nameLabel = UILabel()
nameLabel.font = UIFont.boldSystemFontOfSize(13.0)
nameLabel.textColor = Appearance.colorTwitterBlack
addSubview(nameLabel)
screennameLabel = UILabel()
screennameLabel.font = UIFont.systemFontOfSize(11.0)
screennameLabel.textColor = Appearance.colorTwitterDarkGray
addSubview(screennameLabel)
tweetTextLabel = UILabel()
tweetTextLabel.font = UIFont.systemFontOfSize(16)
tweetTextLabel.textColor = Appearance.colorTwitterBlack
tweetTextLabel.numberOfLines = 0
addSubview(tweetTextLabel)
dateLabel = UILabel()
dateLabel.font = screennameLabel.font
dateLabel.textColor = screennameLabel.textColor
addSubview(dateLabel)
favoriteLabel = UILabel()
favoriteLabel.font = UIFont.systemFontOfSize(10.0)
favoriteLabel.textColor = screennameLabel.textColor
addSubview(favoriteLabel)
profileThumbImageView = UIImageView()
addSubview(profileThumbImageView)
favoriteImageView = UIImageView()
addSubview(favoriteImageView)
retweetImageView = UIImageView()
addSubview(retweetImageView)
replyImageView = UIImageView()
replyImageView.image = UIImage(named: "reply_hover.png")
addSubview(replyImageView)
// Other initialization steps
profileThumbImageView.layer.cornerRadius = 10.0
profileThumbImageView.clipsToBounds = true
let userProfileTap = UITapGestureRecognizer(target: self, action: "onUserProfileTap")
userProfileTap.numberOfTapsRequired = 1
profileThumbImageView.userInteractionEnabled = true
profileThumbImageView.addGestureRecognizer(userProfileTap)
let retweetTap = UITapGestureRecognizer(target: self, action: "onRetweetTap")
retweetTap.numberOfTapsRequired = 1
retweetImageView.userInteractionEnabled = true
retweetImageView.addGestureRecognizer(retweetTap)
// Make favorite image tap-able.
let favoriteTap = UITapGestureRecognizer(target: self, action: "onFavoriteTap")
favoriteTap.numberOfTapsRequired = 1
favoriteImageView.userInteractionEnabled = true
favoriteImageView.addGestureRecognizer(favoriteTap)
let replyTap = UITapGestureRecognizer(target: self, action: "onReplyTap")
replyTap.numberOfTapsRequired = 1
replyImageView.userInteractionEnabled = true
replyImageView.addGestureRecognizer(replyTap)
}
func setupConstraints() {
nameLabel.translatesAutoresizingMaskIntoConstraints = false
screennameLabel.translatesAutoresizingMaskIntoConstraints = false
tweetTextLabel.translatesAutoresizingMaskIntoConstraints = false
dateLabel.translatesAutoresizingMaskIntoConstraints = false
favoriteLabel.translatesAutoresizingMaskIntoConstraints = false
profileThumbImageView.translatesAutoresizingMaskIntoConstraints = false
favoriteImageView.translatesAutoresizingMaskIntoConstraints = false
retweetImageView.translatesAutoresizingMaskIntoConstraints = false
replyImageView.translatesAutoresizingMaskIntoConstraints = false
let views = [
"nameLabel":nameLabel,
"screennameLabel":screennameLabel,
"tweetTextLabel":tweetTextLabel,
"dateLabel":dateLabel,
"favoriteLabel":favoriteLabel,
"profileThumbImageView":profileThumbImageView,
"favoriteImageView":favoriteImageView,
"retweetImageView":retweetImageView,
"replyImageView":replyImageView,
]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(11)-[profileThumbImageView(65)]-(11)-[nameLabel]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(8)-[profileThumbImageView(65)]-(8)-[tweetTextLabel]-(8)-[dateLabel]-(10)-[replyImageView(16)]-(>=8)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[tweetTextLabel]-(>=8)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraint(NSLayoutConstraint(item: screennameLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: nameLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: tweetTextLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: profileThumbImageView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: dateLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: profileThumbImageView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(8)-[nameLabel]-(8)-[screennameLabel]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(48)-[replyImageView(16)]-(48)-[retweetImageView(16)]-(48)-[favoriteImageView(16)]-(2)-[favoriteLabel]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[retweetImageView(16)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[favoriteImageView(16)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraint(NSLayoutConstraint(item: retweetImageView, attribute: .Top, relatedBy: .Equal, toItem: replyImageView, attribute: .Top, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: favoriteImageView, attribute: .Top, relatedBy: .Equal, toItem: replyImageView, attribute: .Top, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: favoriteLabel, attribute: .Top, relatedBy: .Equal, toItem: favoriteImageView, attribute: .Top, multiplier: 1.0, constant: 0))
}
func onRetweetTap() {
// Only retweet if not own tweet
if tweet.user!.name != User.currentUser!.name {
// Only allow retweeting if it hasn't been retweeted yet.
if !tweet.retweeted {
TwitterClient.sharedInstance.retweet(tweet.id) { (data: [String:AnyObject]?, error: NSError?) -> Void in
self.retweetImageView.image = UIImage(named: "retweet_on.png")
}
}
} else {
print("Can't retweet own tweet")
}
}
func onFavoriteTap() {
if tweet.favorited {
TwitterClient.sharedInstance.unfavorite(tweet.id) { (data: [String:AnyObject]?, error: NSError?) -> Void in
if let data = data {
self.tweet = Tweet(data)
}
}
} else {
TwitterClient.sharedInstance.favorite(tweet.id) { (data: [String:AnyObject]?, error: NSError?) -> Void in
if let data = data {
self.tweet = Tweet(data)
}
}
}
}
func onReplyTap() {
if let replyActionHandler = self.replyActionHandler {
replyActionHandler(tweetId: tweet.id, tweetUserScreenname: tweet.user!.screenname)
}
}
func onUserProfileTap() {
if let userProfileShowHandler = self.userProfileShowHandler {
userProfileShowHandler(user: tweet.user!)
}
}
}
| 07cce6ff7fe853eaaae5eb6e126c6534 | 40.429719 | 249 | 0.716654 | false | false | false | false |
RockyAo/RxSwift_learn | refs/heads/master | 06-LoginDemo/06-LoginDemo/Service.swift | mit | 1 | //
// Service.swift
// 06-LoginDemo
//
// Created by Rocky on 2017/3/23.
// Copyright © 2017年 Rocky. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
let minCharacterCount = 6
let maxCharacterCount = 12
class ValidationService {
static let instance = ValidationService()
func validateUserName(_ userName:String) -> Observable<Result>{
if userName.characters.count == 0 {
return .just(.empty)
}
if userName.characters.count < minCharacterCount{
return .just(.faild(message:"账号至少\(minCharacterCount)个字符"))
}
if validateLocalUserName(userName) {
return .just(.faild(message:"用户名已存在"))
}
if userName.characters.count > maxCharacterCount {
return .just(.faild(message:"账号不能大于\(maxCharacterCount)个字符"))
}
return .just(.ok(message:"用户名可用"))
}
func validateLocalUserName(_ userName:String) -> Bool{
let filePath = NSHomeDirectory() + "/Documents/user.plist"
guard let userDictionary = NSDictionary(contentsOfFile: filePath) else {
return false
}
let usernameArray = userDictionary.allKeys as NSArray
if usernameArray.contains(userName) {
return true
} else {
return false
}
}
func validatePassword(_ password:String) -> Result {
if password.characters.count == 0 {
return .empty
}
if password.characters.count < minCharacterCount {
return .faild(message:"密码至少6位")
}
if password.characters.count > maxCharacterCount {
return .faild(message:"密码最多12位")
}
return .ok(message:"验证通过")
}
func validateRepeatPassword(_ password:String,_ repeatPassword:String) -> Result{
if repeatPassword.characters.count == 0 {
return .empty
}
if repeatPassword == password {
return .ok(message:"密码可用")
}
return .faild(message:"两次输入不一致")
}
func register(_ username:String,_ password:String) -> Observable<Result> {
let userdic = [username:password]
let filePath = NSHomeDirectory() + "/Documents/users.plist"
if (userdic as NSDictionary).write(toFile: filePath, atomically: true) {
return .just(.ok(message:"写入成功"))
}
return .just(.ok(message:"注册失败"))
}
}
| f8397470c49e50b48bab40aa3e9f1edd | 22.939655 | 85 | 0.529348 | false | false | false | false |
apple/swift-format | refs/heads/main | Sources/SwiftFormatRules/ValidateDocumentationComments.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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 Foundation
import SwiftFormatCore
import SwiftSyntax
/// Documentation comments must be complete and valid.
///
/// "Command + Option + /" in Xcode produces a minimal valid documentation comment.
///
/// Lint: Documentation comments that are incomplete (e.g. missing parameter documentation) or
/// invalid (uses `Parameters` when there is only one parameter) will yield a lint error.
public final class ValidateDocumentationComments: SyntaxLintRule {
/// Identifies this rule as being opt-in. Accurate and complete documentation comments are
/// important, but this rule isn't able to handle situations where portions of documentation are
/// redundant. For example when the returns clause is redundant for a simple declaration.
public override class var isOptIn: Bool { return true }
public override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind {
return checkFunctionLikeDocumentation(
DeclSyntax(node), name: "init", signature: node.signature)
}
public override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind {
return checkFunctionLikeDocumentation(
DeclSyntax(node), name: node.identifier.text, signature: node.signature,
returnClause: node.signature.output)
}
private func checkFunctionLikeDocumentation(
_ node: DeclSyntax,
name: String,
signature: FunctionSignatureSyntax,
returnClause: ReturnClauseSyntax? = nil
) -> SyntaxVisitorContinueKind {
guard let declComment = node.docComment else { return .skipChildren }
guard let commentInfo = node.docCommentInfo else { return .skipChildren }
guard let params = commentInfo.parameters else { return .skipChildren }
// If a single sentence summary is the only documentation, parameter(s) and
// returns tags may be ommitted.
if commentInfo.oneSentenceSummary != nil && commentInfo.commentParagraphs!.isEmpty && params
.isEmpty && commentInfo.returnsDescription == nil
{
return .skipChildren
}
// Indicates if the documentation uses 'Parameters' as description of the
// documented parameters.
let hasPluralDesc = declComment.components(separatedBy: .newlines).contains {
$0.trimmingCharacters(in: .whitespaces).starts(with: "- Parameters")
}
validateThrows(
signature.throwsOrRethrowsKeyword, name: name, throwsDesc: commentInfo.throwsDescription, node: node)
validateReturn(
returnClause, name: name, returnDesc: commentInfo.returnsDescription, node: node)
let funcParameters = funcParametersIdentifiers(in: signature.input.parameterList)
// If the documentation of the parameters is wrong 'docCommentInfo' won't
// parse the parameters correctly. First the documentation has to be fix
// in order to validate the other conditions.
if hasPluralDesc && funcParameters.count == 1 {
diagnose(.useSingularParameter, on: node)
return .skipChildren
} else if !hasPluralDesc && funcParameters.count > 1 {
diagnose(.usePluralParameters, on: node)
return .skipChildren
}
// Ensures that the parameters of the documantation and the function signature
// are the same.
if (params.count != funcParameters.count) || !parametersAreEqual(
params: params, funcParam: funcParameters)
{
diagnose(.parametersDontMatch(funcName: name), on: node)
}
return .skipChildren
}
/// Ensures the function has a return documentation if it actually returns
/// a value.
private func validateReturn(
_ returnClause: ReturnClauseSyntax?,
name: String,
returnDesc: String?,
node: DeclSyntax
) {
if returnClause == nil && returnDesc != nil {
diagnose(.removeReturnComment(funcName: name), on: node)
} else if let returnClause = returnClause, returnDesc == nil {
if let returnTypeIdentifier = returnClause.returnType.as(SimpleTypeIdentifierSyntax.self),
returnTypeIdentifier.name.text == "Never"
{
return
}
diagnose(.documentReturnValue(funcName: name), on: returnClause)
}
}
/// Ensures the function has throws documentation if it may actually throw
/// an error.
private func validateThrows(
_ throwsOrRethrowsKeyword: TokenSyntax?,
name: String,
throwsDesc: String?,
node: DeclSyntax
) {
// If a function is marked as `rethrows`, it doesn't have any errors of its
// own that should be documented. So only require documentation for
// functions marked `throws`.
let needsThrowsDesc = throwsOrRethrowsKeyword?.tokenKind == .throwsKeyword
if !needsThrowsDesc && throwsDesc != nil {
diagnose(.removeThrowsComment(funcName: name), on: throwsOrRethrowsKeyword ?? node.firstToken)
} else if needsThrowsDesc && throwsDesc == nil {
diagnose(.documentErrorsThrown(funcName: name), on: throwsOrRethrowsKeyword)
}
}
}
/// Iterates through every parameter of paramList and returns a list of the
/// paramters identifiers.
fileprivate func funcParametersIdentifiers(in paramList: FunctionParameterListSyntax) -> [String] {
var funcParameters = [String]()
for parameter in paramList {
// If there is a label and an identifier, then the identifier (`secondName`) is the name that
// should be documented. Otherwise, the label and identifier are the same, occupying
// `firstName`.
guard let parameterIdentifier = parameter.secondName ?? parameter.firstName else {
continue
}
funcParameters.append(parameterIdentifier.text)
}
return funcParameters
}
/// Indicates if the parameters name from the documentation and the parameters
/// from the declaration are the same.
fileprivate func parametersAreEqual(params: [ParseComment.Parameter], funcParam: [String]) -> Bool {
for index in 0..<params.count {
if params[index].name != funcParam[index] {
return false
}
}
return true
}
extension Finding.Message {
public static func documentReturnValue(funcName: String) -> Finding.Message {
"document the return value of \(funcName)"
}
public static func removeReturnComment(funcName: String) -> Finding.Message {
"remove the return comment of \(funcName), it doesn't return a value"
}
public static func parametersDontMatch(funcName: String) -> Finding.Message {
"change the parameters of \(funcName)'s documentation to match its parameters"
}
public static let useSingularParameter: Finding.Message =
"replace the plural form of 'Parameters' with a singular inline form of the 'Parameter' tag"
public static let usePluralParameters: Finding.Message =
"""
replace the singular inline form of 'Parameter' tag with a plural 'Parameters' tag \
and group each parameter as a nested list
"""
public static func removeThrowsComment(funcName: String) -> Finding.Message {
"remove the 'Throws' tag for non-throwing function \(funcName)"
}
public static func documentErrorsThrown(funcName: String) -> Finding.Message {
"add a 'Throws' tag describing the errors thrown by \(funcName)"
}
}
| 92dec11315fb59f93d3c61d4ba3dd68a | 38.947368 | 107 | 0.709618 | false | false | false | false |
designatednerd/GoCubs | refs/heads/master | GoCubs/Views/CubsGameCell.swift | mit | 1 | //
// CubsGameCell.swift
// GoCubs
//
// Created by Ellen Shapiro on 10/11/15.
// Copyright © 2015 Designated Nerd Software. All rights reserved.
//
import UIKit
class CubsGameCell: UITableViewCell {
static let identifier = "CubsGameCell"
// Use a static let so this only gets instantiated once across all cells.
private static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMM d"
return formatter
}()
@IBOutlet var dateLabel: UILabel!
@IBOutlet var vsLabel: UILabel!
@IBOutlet var primaryColorView: UIView!
@IBOutlet var secondaryColorView: UIView!
func configure(forGame game: CubsGame) {
self.dateLabel.text = CubsGameCell.dateFormatter.string(from: game.date as Date)
if game.opponent.isHomeTeam {
self.vsLabel.text = LocalizedString.versus(Team.Cubs.rawValue, homeTeam: game.opponent.name)
} else {
self.vsLabel.text = LocalizedString.versus(game.opponent.name, homeTeam: Team.Cubs.rawValue)
}
if game.result.type == .postponed {
self.vsLabel.alpha = 0.5
} else {
self.vsLabel.alpha = 1
}
self.primaryColorView.backgroundColor = game.opponent.team.primaryColor
self.secondaryColorView.backgroundColor = game.opponent.team.secondaryColor
}
//MARK: - Cell silliness
// Override these methods to prevent cell selection from futzing with
// the background color of the cell's color views.
override func setSelected(_ selected: Bool, animated: Bool) {
let primary = self.primaryColorView.backgroundColor
let secondary = self.secondaryColorView.backgroundColor
super.setSelected(selected, animated: animated)
self.primaryColorView.backgroundColor = primary
self.secondaryColorView.backgroundColor = secondary
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
let primary = self.primaryColorView.backgroundColor
let secondary = self.secondaryColorView.backgroundColor
super.setHighlighted(highlighted, animated: animated)
self.primaryColorView.backgroundColor = primary
self.secondaryColorView.backgroundColor = secondary
}
}
| 4bd53551697d2c9331e98f87d29c9be0 | 33.478261 | 104 | 0.670029 | false | false | false | false |
Herb-Sun/OKKLineSwift | refs/heads/master | OKKLineSwift/Models/Indicators/OKEMAModel.swift | mit | 1 | //
// OKKLineSwift
//
// Copyright © 2016年 Herb - https://github.com/Herb-Sun/OKKLineSwift
//
// 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
struct OKEMAModel {
let indicatorType: OKIndicatorType
let klineModels: [OKKLineModel]
init(indicatorType: OKIndicatorType, klineModels: [OKKLineModel]) {
self.indicatorType = indicatorType
self.klineModels = klineModels
}
public func fetchDrawEMAData(drawRange: NSRange? = nil) -> [OKKLineModel] {
var datas = [OKKLineModel]()
guard klineModels.count > 0 else {
return datas
}
for (index, model) in klineModels.enumerated() {
switch indicatorType {
case .EMA(let days):
var values = [Double?]()
for (idx, day) in days.enumerated() {
let previousEMA: Double? = index > 0 ? datas[index - 1].EMAs?[idx] : nil
values.append(handleEMA(day: day, model: model, index: index, previousEMA: previousEMA))
}
model.EMAs = values
default:
break
}
datas.append(model)
}
if let range = drawRange {
return Array(datas[range.location..<range.location+range.length])
} else {
return datas
}
}
private func handleEMA(day: Int, model: OKKLineModel, index: Int, previousEMA: Double?) -> Double? {
if day <= 0 || index < (day - 1) {
return nil
} else {
if previousEMA != nil {
return Double(day - 1) / Double(day + 1) * previousEMA! + 2 / Double(day + 1) * model.close
} else {
return 2 / Double(day + 1) * model.close
}
}
}
}
| 0de2854f6283b18ac5cf3fb7d066eb10 | 35.604938 | 108 | 0.595278 | false | false | false | false |
vector-im/riot-ios | refs/heads/develop | Riot/Modules/Secrets/Setup/RecoveryPassphrase/SecretsSetupRecoveryPassphraseViewController.swift | apache-2.0 | 1 | // File created from ScreenTemplate
// $ createScreen.sh Test SecretsSetupRecoveryPassphrase
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
final class SecretsSetupRecoveryPassphraseViewController: UIViewController {
// MARK: - Constants
private enum Constants {
static let animationDuration: TimeInterval = 0.3
}
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var scrollView: UIScrollView!
@IBOutlet private weak var securePassphraseImageView: UIImageView!
@IBOutlet private weak var informationLabel: UILabel!
@IBOutlet private weak var formBackgroundView: UIView!
@IBOutlet private weak var passphraseTitleLabel: UILabel!
@IBOutlet private weak var passphraseTextField: UITextField!
@IBOutlet private weak var passphraseVisibilityButton: UIButton!
@IBOutlet private weak var passphraseAdditionalInfoView: UIView!
@IBOutlet private weak var passphraseStrengthContainerView: UIView!
@IBOutlet private weak var passphraseStrengthView: PasswordStrengthView!
@IBOutlet private weak var passphraseAdditionalLabel: UILabel!
@IBOutlet private weak var additionalInformationLabel: UILabel!
@IBOutlet private weak var validateButton: RoundedButton!
// MARK: Private
private var viewModel: SecretsSetupRecoveryPassphraseViewModelType!
private var theme: Theme!
private var keyboardAvoider: KeyboardAvoider?
private var errorPresenter: MXKErrorPresentation!
private var activityPresenter: ActivityIndicatorPresenter!
private var isFirstViewAppearing: Bool = true
private var isPassphraseTextFieldEditedOnce: Bool = false
private var currentViewData: SecretsSetupRecoveryPassphraseViewData?
// MARK: - Setup
class func instantiate(with viewModel: SecretsSetupRecoveryPassphraseViewModelType) -> SecretsSetupRecoveryPassphraseViewController {
let viewController = StoryboardScene.SecretsSetupRecoveryPassphraseViewController.initialScene.instantiate()
viewController.viewModel = viewModel
viewController.theme = ThemeService.shared().theme
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupViews()
self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.scrollView)
self.activityPresenter = ActivityIndicatorPresenter()
self.errorPresenter = MXKErrorAlertPresentation()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
self.viewModel.viewDelegate = self
self.viewModel.process(viewAction: .loadData)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.keyboardAvoider?.startAvoiding()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.isFirstViewAppearing {
self.isFirstViewAppearing = false
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.view.endEditing(true)
self.keyboardAvoider?.stopAvoiding()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
// MARK: - Private
private func setupViews() {
let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in
self?.cancelButtonAction()
}
self.navigationItem.rightBarButtonItem = cancelBarButtonItem
self.vc_removeBackTitle()
self.title = VectorL10n.secretsSetupRecoveryPassphraseTitle
self.scrollView.keyboardDismissMode = .interactive
self.securePassphraseImageView.image = Asset.Images.secretsSetupPassphrase.image.withRenderingMode(.alwaysTemplate)
self.passphraseTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.passphraseAdditionalInfoView.isHidden = true
let visibilityImage = Asset.Images.revealPasswordButton.image.withRenderingMode(.alwaysTemplate)
self.passphraseVisibilityButton.setImage(visibilityImage, for: .normal)
self.additionalInformationLabel.text = VectorL10n.secretsSetupRecoveryPassphraseAdditionalInformation
self.validateButton.setTitle(VectorL10n.continue, for: .normal)
}
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.headerBackgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
self.securePassphraseImageView.tintColor = theme.textPrimaryColor
self.informationLabel.textColor = theme.textPrimaryColor
self.formBackgroundView.backgroundColor = theme.backgroundColor
self.passphraseTitleLabel.textColor = theme.textPrimaryColor
theme.applyStyle(onTextField: self.passphraseTextField)
let passphraseTitle: String
if let viewData = self.currentViewData, case .confimPassphrase = viewData.mode {
passphraseTitle = VectorL10n.secretsSetupRecoveryPassphraseConfirmPassphrasePlaceholder
} else {
passphraseTitle = VectorL10n.keyBackupSetupPassphrasePassphrasePlaceholder
}
self.passphraseTextField.attributedPlaceholder = NSAttributedString(string: passphraseTitle,
attributes: [.foregroundColor: theme.placeholderTextColor])
self.passphraseVisibilityButton.tintColor = theme.tintColor
self.additionalInformationLabel.textColor = theme.textSecondaryColor
self.validateButton.update(theme: theme)
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
private func render(viewState: SecretsSetupRecoveryPassphraseViewState) {
switch viewState {
case .loaded(let viewData):
self.renderLoaded(viewData: viewData)
case .formUpdated(let viewData):
self.renderFormUpdated(viewData: viewData)
case .error(let error):
self.render(error: error)
}
}
private func renderLoaded(viewData: SecretsSetupRecoveryPassphraseViewData) {
self.currentViewData = viewData
let informationText: String
let passphraseTitle: String
let showPasswordStrength: Bool
switch viewData.mode {
case .newPassphrase(strength: let strength):
informationText = VectorL10n.secretsSetupRecoveryPassphraseInformation
passphraseTitle = VectorL10n.keyBackupSetupPassphrasePassphraseTitle
showPasswordStrength = true
self.passphraseStrengthView.strength = strength
case .confimPassphrase:
informationText = VectorL10n.secretsSetupRecoveryPassphraseConfirmInformation
passphraseTitle = VectorL10n.secretsSetupRecoveryPassphraseConfirmPassphraseTitle
showPasswordStrength = false
}
self.informationLabel.text = informationText
self.passphraseTitleLabel.text = passphraseTitle
self.passphraseStrengthContainerView.isHidden = !showPasswordStrength
self.update(theme: self.theme)
}
private func renderFormUpdated(viewData: SecretsSetupRecoveryPassphraseViewData) {
self.currentViewData = viewData
if case .newPassphrase(strength: let strength) = viewData.mode {
self.passphraseStrengthView.strength = strength
}
self.validateButton.isEnabled = viewData.isFormValid
self.updatePassphraseAdditionalLabel(viewData: viewData)
// Show passphrase additional info at first character entered
if self.isPassphraseTextFieldEditedOnce == false, self.passphraseTextField.text?.isEmpty == false {
self.isPassphraseTextFieldEditedOnce = true
self.showPassphraseAdditionalInfo(animated: true)
}
}
private func render(error: Error) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil)
}
private func showPassphraseAdditionalInfo(animated: Bool) {
guard self.passphraseAdditionalInfoView.isHidden else {
return
}
// Workaround to layout passphraseStrengthView corner radius
self.passphraseStrengthView.setNeedsLayout()
UIView.animate(withDuration: Constants.animationDuration) {
self.passphraseAdditionalInfoView.isHidden = false
}
}
private func updatePassphraseAdditionalLabel(viewData: SecretsSetupRecoveryPassphraseViewData) {
let text: String
let textColor: UIColor
if viewData.isFormValid {
switch viewData.mode {
case .newPassphrase:
text = VectorL10n.keyBackupSetupPassphrasePassphraseValid
case .confimPassphrase:
text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseValid
}
textColor = self.theme.tintColor
} else {
switch viewData.mode {
case .newPassphrase:
text = VectorL10n.keyBackupSetupPassphrasePassphraseInvalid
case .confimPassphrase:
text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseInvalid
}
textColor = self.theme.noticeColor
}
self.passphraseAdditionalLabel.text = text
self.passphraseAdditionalLabel.textColor = textColor
}
// MARK: - Actions
@IBAction private func passphraseVisibilityButtonAction(_ sender: Any) {
guard self.isPassphraseTextFieldEditedOnce else {
return
}
self.passphraseTextField.isSecureTextEntry.toggle()
}
@objc private func textFieldDidChange(_ textField: UITextField) {
guard textField == self.passphraseTextField else {
return
}
self.viewModel.process(viewAction: .updatePassphrase(textField.text))
}
@IBAction private func validateButtonAction(_ sender: Any) {
self.viewModel.process(viewAction: .validate)
}
private func cancelButtonAction() {
self.viewModel.process(viewAction: .cancel)
}
}
// MARK: - SecretsSetupRecoveryPassphraseViewModelViewDelegate
extension SecretsSetupRecoveryPassphraseViewController: SecretsSetupRecoveryPassphraseViewModelViewDelegate {
func secretsSetupRecoveryPassphraseViewModel(_ viewModel: SecretsSetupRecoveryPassphraseViewModelType, didUpdateViewState viewSate: SecretsSetupRecoveryPassphraseViewState) {
self.render(viewState: viewSate)
}
}
| 7846777755d46134f9b81428790b33ad | 36.73065 | 178 | 0.689833 | false | false | false | false |
i-schuetz/rest_client_ios | refs/heads/master | clojushop_client_ios/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
//
// Created by ischuetz on 13/06/2014.
// Copyright (c) 2014 ivanschuetz. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate {
var tabBarController:UITabBarController!
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
initTabs()
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
tabBarController.delegate = self;
return true
}
func initTabs() {
let productsListController:ProductListViewController = ProductListViewController(nibName: "ProductsListViewController", bundle: nil)
var prodController:UIViewController
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
let productsListNavController = UINavigationController(rootViewController: productsListController)
let productDetailsController = ProductDetailViewController(nibName: "ProductDetailViewController", bundle: nil)
productsListController.detailsViewController = productDetailsController
let productDetailsNav:UINavigationController = UINavigationController(rootViewController: productDetailsController)
let splitViewControllers = [productsListNavController, productDetailsNav]
let splitController = UISplitViewController()
splitController.delegate = productDetailsController
splitController.viewControllers = splitViewControllers
prodController = splitController
} else {
let prodNavController = UINavigationController(rootViewController: productsListController)
prodController = prodNavController
}
prodController.tabBarItem.title = "Products"
let cartController:CartViewController = CartViewController(nibName: "CartViewController", bundle: nil)
let cartNavController = UINavigationController(rootViewController: cartController)
cartNavController.title = "Cart"
let loginRegisterController:LoginRegisterViewController = LoginRegisterViewController(nibName: "LoginRegisterViewController", bundle: nil)
let loginRegisterNavController = UINavigationController(rootViewController: loginRegisterController)
loginRegisterController.title = "Login / Register"
tabBarController = UITabBarController()
let viewControllers = [prodController, cartNavController, loginRegisterNavController]
tabBarController.viewControllers = viewControllers
self.window!.rootViewController = tabBarController
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
func saveContext () {
var error: NSError? = nil
if self.managedObjectContext.hasChanges && !self.managedObjectContext.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() 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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if _managedObjectContext == nil {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = self.persistentStoreCoordinator
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if _managedObjectModel == nil {
let modelURL = NSBundle.mainBundle().URLForResource("tmp", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if _persistentStoreCoordinator == nil{
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("tmp.sqlite")
var error: NSError? = nil
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
/*
Replace this implementation with code to handle the error appropriately.
abort() 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 persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil)
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
// #pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
}
| cfaa5bd9adf46f57593f594a9945df80 | 51.153005 | 285 | 0.696878 | false | false | false | false |
trujillo138/MyExpenses | refs/heads/master | MyExpenses/MyExpenses/Services/ModelController.swift | apache-2.0 | 1 | //
// ModelController.swift
// MyExpenses
//
// Created by Tomas Trujillo on 5/22/17.
// Copyright © 2017 TOMApps. All rights reserved.
//
import Foundation
class ModelController {
//MARK: Properties
var user: User
private let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
private var expensesURL: URL {
return documentsDirectoryURL.appendingPathComponent("Expenses").appendingPathExtension("plist")
}
//MARK: Model methods
func save(_ user: User) {
self.user = user
saveData()
}
//MARK: Loading and Saving
required init() {
user = User()
loadData()
}
private func loadData() {
guard let expenseModelPlist = NSDictionary.init(contentsOf: expensesURL) as? [String: AnyObject] else {
return
}
user = User(plist: expenseModelPlist)
}
private func saveData() {
let expenseDictionary = user.plistRepresentation as NSDictionary
expenseDictionary.write(to: expensesURL, atomically: true)
}
}
| 3ee24d2ab044c093f8a00543e44f924c | 22.34 | 117 | 0.61868 | false | false | false | false |
arnav-gudibande/SwiftTweet | refs/heads/master | Swifter-master/Swifter/SwifterMessages.swift | apache-2.0 | 2 | //
// SwifterMessages.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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 Swifter {
/**
GET direct_messages
Returns the 20 most recent direct messages sent to the authenticating user. Includes detailed information about the sender and recipient user. You can request up to 200 direct messages per call, up to a maximum of 800 incoming DMs.
*/
public func getDirectMessagesSinceID(sinceID: String? = nil, maxID: String? = nil, count: Int? = nil, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((messages: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "direct_messages.json"
var parameters = Dictionary<String, Any>()
parameters["since_id"] ??= sinceID
parameters["max_id"] ??= maxID
parameters["count"] ??= count
parameters["include_entities"] ??= includeEntities
parameters["skip_status"] ??= skipStatus
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, success: { json, _ in
success?(messages: json.array)
}, failure: failure)
}
/**
GET direct_messages/sent
Returns the 20 most recent direct messages sent by the authenticating user. Includes detailed information about the sender and recipient user. You can request up to 200 direct messages per call, up to a maximum of 800 outgoing DMs.
*/
public func getSentDirectMessagesSinceID(sinceID: String? = nil, maxID: String? = nil, count: Int? = nil, page: Int? = nil, includeEntities: Bool? = nil, success: ((messages: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "direct_messages/sent.json"
var parameters = Dictionary<String, Any>()
parameters["since_id"] ??= sinceID
parameters["max_id"] ??= maxID
parameters["count"] ??= count
parameters["page"] ??= page
parameters["include_entities"] ??= includeEntities
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, success: { json, _ in
success?(messages: json.array)
}, failure: failure)
}
/**
GET direct_messages/show
Returns a single direct message, specified by an id parameter. Like the /1.1/direct_messages.format request, this method will include the user objects of the sender and recipient.
*/
public func getDirectMessagesShowWithID(id: String, success: ((messages: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "direct_messages/show.json"
let parameters: [String: Any] = ["id" : id]
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, success: { json, _ in
success?(messages: json.array)
}, failure: failure)
}
/**
POST direct_messages/destroy
Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message.
*/
public func postDestroyDirectMessageWithID(id: String, includeEntities: Bool? = nil, success: ((messages: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "direct_messages/destroy.json"
var parameters = Dictionary<String, Any>()
parameters["id"] = id
parameters["include_entities"] ??= includeEntities
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, success: { json, _ in
success?(messages: json.object)
}, failure: failure)
}
/**
POST direct_messages/new
Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters and must be a POST. Returns the sent message in the requested format if successful.
*/
public func postDirectMessageToUser(userID: String, text: String, success: ((statuses: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "direct_messages/new.json"
var parameters = Dictionary<String, Any>()
parameters["user_id"] = userID
parameters["text"] = text
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, success: { json, _ in
success?(statuses: json.object)
}, failure: failure)
}
}
| 0eb0f0668b9d46df8508ff93b1b077bb | 45.881356 | 246 | 0.67679 | false | false | false | false |
Erickson0806/TableSearchwithUISearchController | refs/heads/master | Swift/TableSearch/Product.swift | apache-2.0 | 1 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The data model object describing the product displayed in both main and results tables.
*/
import Foundation
class Product: NSObject, NSCoding {
// MARK: Types
enum CoderKeys: String {
case nameKey
case typeKey
case yearKey
case priceKey
}
enum Hardware: String {
case iPhone = "iPhone"
case iPod = "iPod"
case iPodTouch = "iPod touch"
case iPad = "iPad"
case iPadMini = "iPad Mini"
case iMac = "iMac"
case MacPro = "Mac Pro"
case MacBookAir = "Mac Book Air"
case MacBookPro = "Mac Book Pro"
}
// MARK: Properties
let title: String
let hardwareType: String
let yearIntroduced: Int
let introPrice: Double
// MARK: Initializers
init(hardwareType: String, title: String, yearIntroduced: Int, introPrice: Double) {
self.hardwareType = hardwareType
self.title = title
self.yearIntroduced = yearIntroduced
self.introPrice = introPrice
}
// MARK: NSCoding
required init?(coder aDecoder: NSCoder) {
title = aDecoder.decodeObjectForKey(CoderKeys.nameKey.rawValue) as! String
hardwareType = aDecoder.decodeObjectForKey(CoderKeys.typeKey.rawValue) as! String
yearIntroduced = aDecoder.decodeIntegerForKey(CoderKeys.yearKey.rawValue)
introPrice = aDecoder.decodeDoubleForKey(CoderKeys.priceKey.rawValue)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: CoderKeys.nameKey.rawValue)
aCoder.encodeObject(hardwareType, forKey: CoderKeys.typeKey.rawValue)
aCoder.encodeInteger(yearIntroduced, forKey: CoderKeys.yearKey.rawValue)
aCoder.encodeDouble(introPrice, forKey: CoderKeys.priceKey.rawValue)
}
// MARK: Device Type Info
class var deviceTypeNames: [String] {
return [
Product.deviceTypeTitle,
Product.desktopTypeTitle,
Product.portableTypeTitle
]
}
class var deviceTypeTitle: String {
return NSLocalizedString("Device", comment:"Device type title")
}
class var desktopTypeTitle: String {
return NSLocalizedString("Desktop", comment:"Desktop type title")
}
class var portableTypeTitle: String {
return NSLocalizedString("Portable", comment:"Portable type title")
}
}
| 7657297762e39fd900fee24548e3a7c3 | 28.616279 | 89 | 0.655281 | false | false | false | false |
Bygo/BGChatBotMessaging-iOS | refs/heads/master | BGChatBotMessaging/Classes/BGMessagingOutgoingOptionsContainer.swift | mit | 1 | //
// BGMessagingOutgoingOptionsContainer.swift
// Pods
//
// Created by Nicholas Garfield on 17/6/16.
//
//
import UIKit
class BGMessagingOutgoingOptionsContainer: UIView {
var delegate: BGMessagingOutgoingOptionsContainerDelegate?
@IBOutlet var optionA: BGMessagingOutgoingOptionButton!
@IBOutlet var optionB: BGMessagingOutgoingOptionButton!
@IBOutlet var optionsHorizontalSpacingLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionABottomLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionBBottomLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionALeadingLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionBTrailingLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionACenterXLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionBCenterXLayoutConstraint: NSLayoutConstraint!
var layoutConfiguration: BGMessagingOutgoingOptionsLayoutConfiguration = .Horizontal {
didSet {
switch layoutConfiguration {
case .Vertical:
optionALeadingLayoutConstraint.active = false
optionBTrailingLayoutConstraint.active = false
optionsHorizontalSpacingLayoutConstraint.active = false
optionACenterXLayoutConstraint.active = true
optionBCenterXLayoutConstraint.active = true
optionABottomLayoutConstraint.constant = 8.0 + optionA.bounds.height
optionBBottomLayoutConstraint.constant = 8.0 + optionA.bounds.height + 4.0 + optionB.bounds.height
case .Horizontal:
optionACenterXLayoutConstraint.active = false
optionBCenterXLayoutConstraint.active = false
optionsHorizontalSpacingLayoutConstraint.active = true
optionALeadingLayoutConstraint.active = true
optionBTrailingLayoutConstraint.active = true
optionABottomLayoutConstraint.constant = 8.0 + optionA.bounds.height
optionBBottomLayoutConstraint.constant = 8.0 + optionB.bounds.height
}
layoutIfNeeded()
}
}
init() {
super.init(frame: CGRectZero)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configure() {
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .clearColor()
userInteractionEnabled = true
configureOptions()
}
private func configureOptions() {
if optionA == nil {
optionA = BGMessagingOutgoingOptionButton()
addSubview(optionA)
optionALeadingLayoutConstraint = optionA.leadingAnchor.constraintEqualToAnchor(leadingAnchor)
optionALeadingLayoutConstraint.active = true
optionABottomLayoutConstraint = optionA.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: 8.0 + optionA.bounds.height)
optionABottomLayoutConstraint.active = true
optionA.topAnchor.constraintGreaterThanOrEqualToAnchor(topAnchor, constant: 8.0).active = true
optionACenterXLayoutConstraint = optionA.centerXAnchor.constraintEqualToAnchor(centerXAnchor)
optionACenterXLayoutConstraint.active = false
optionA.addTarget(self, action: #selector(BGMessagingOutgoingOptionsContainer.optionAButtonTapped(_:)), forControlEvents: .TouchUpInside)
}
if optionB == nil {
optionB = BGMessagingOutgoingOptionButton()
addSubview(optionB)
optionBTrailingLayoutConstraint = optionB.trailingAnchor.constraintEqualToAnchor(trailingAnchor)
optionBTrailingLayoutConstraint.active = true
optionBBottomLayoutConstraint = optionB.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: 8.0 + optionB.bounds.height)
optionBBottomLayoutConstraint.active = true
optionB.topAnchor.constraintGreaterThanOrEqualToAnchor(topAnchor, constant: 8.0).active = true
optionBCenterXLayoutConstraint = optionB.centerXAnchor.constraintEqualToAnchor(centerXAnchor)
optionBCenterXLayoutConstraint.active = false
optionB.addTarget(self, action: #selector(BGMessagingOutgoingOptionsContainer.optionBButtonTapped(_:)), forControlEvents: .TouchUpInside)
}
optionsHorizontalSpacingLayoutConstraint = optionB.leadingAnchor.constraintEqualToAnchor(optionA.trailingAnchor, constant: 4.0)
optionsHorizontalSpacingLayoutConstraint.active = true
layoutIfNeeded()
}
func showOptions() {
switch layoutConfiguration {
case .Horizontal:
if optionA.enabled {
optionABottomLayoutConstraint.constant = -8.0
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
if optionA.enabled && optionB.enabled {
optionBBottomLayoutConstraint.constant = -8.0
UIView.animateWithDuration(0.5, delay: 0.15, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
case .Vertical:
if optionA.enabled {
optionABottomLayoutConstraint.constant = -8.0 - optionB.bounds.height - 4.0
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
if optionA.enabled && optionB.enabled {
optionBBottomLayoutConstraint.constant = -8.0
UIView.animateWithDuration(0.5, delay: 0.15, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
}
}
func hideOptions() {
switch layoutConfiguration {
case .Horizontal:
optionABottomLayoutConstraint.constant = 8.0 + optionA.bounds.height
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
optionBBottomLayoutConstraint.constant = 8.0 + optionB.bounds.height
UIView.animateWithDuration(0.5, delay: 0.15, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
case .Vertical:
optionBBottomLayoutConstraint.constant = 8.0 + optionA.bounds.height + 4.0 + optionB.bounds.height
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
optionABottomLayoutConstraint.constant = 8.0 + optionA.bounds.height
UIView.animateWithDuration(0.5, delay: 0.15, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
}
// MARK: - UI Actions
@IBAction func optionAButtonTapped(sender: BGMessagingOutgoingOptionButton) {
sender.selected = true
delegate?.didSelectOptionA(sender)
}
@IBAction func optionBButtonTapped(sender: BGMessagingOutgoingOptionButton) {
sender.selected = true
delegate?.didSelectOptionB(sender)
}
}
enum BGMessagingOutgoingOptionsLayoutConfiguration {
case Vertical
case Horizontal
}
protocol BGMessagingOutgoingOptionsContainerDelegate {
func didSelectOptionA(optionA: UIButton)
func didSelectOptionB(optionB: UIButton)
} | 19307a5584cd7702b2a607b5889bb430 | 44.178378 | 156 | 0.662199 | false | true | false | false |
edwinbosire/YAWA | refs/heads/master | YAWA-Weather/Model/Forecast.swift | gpl-2.0 | 1 | //
// Forecast.swift
// YAWA-Weather
//
// Created by edwin bosire on 15/06/2015.
// Copyright (c) 2015 Edwin Bosire. All rights reserved.
//
import Foundation
import CoreData
import UIKit
@objc(Forecast)
class Forecast: NSManagedObject {
@NSManaged var time: String
@NSManaged var temperature: NSNumber
@NSManaged var humidity: NSNumber
@NSManaged var precipitationProbability: NSNumber
@NSManaged var windSpeed: NSNumber
@NSManaged var windDirection: String
@NSManaged var summary: String
@NSManaged var icon: String
@NSManaged var weeklyForecast: NSSet
@NSManaged var city: City
class func createNewForecast() -> Forecast {
let forecast = NSEntityDescription.insertNewObjectForEntityForName("Forecast", inManagedObjectContext: StoreManager.sharedInstance.managedObjectContext!) as! Forecast
return forecast
}
class func forecastWithDictionary(weatherDictionary: NSDictionary) -> Forecast {
let forecast = Forecast.createNewForecast()
let currentWeather = weatherDictionary["currently"] as! NSDictionary
forecast.temperature = currentWeather["temperature"] as! Int
forecast.humidity = currentWeather["humidity"] as! Double
forecast.precipitationProbability = currentWeather["precipProbability"] as! Double
forecast.windSpeed = currentWeather["windSpeed"] as! Int
forecast.summary = currentWeather["summary"] as! String
forecast.icon = currentWeather["icon"] as! String
let myWeeklyForecast = Forecast.weeklyForecastFromDictionary(weatherDictionary)
let set = NSSet(array: myWeeklyForecast)
forecast.weeklyForecast = set
let windDirectionDegrees = currentWeather["windBearing"] as! Int
forecast.windDirection = forecast.windDirectionFromDegress(windDirectionDegrees)
let currentTimeIntVale = currentWeather["time"] as! Int
forecast.time = forecast.dateStringFromUnixTime(currentTimeIntVale)
return forecast
}
func image() -> UIImage {
return weatherIconFromString(icon)
}
class func weeklyForecastFromDictionary(weatherDictionary: NSDictionary) ->[Daily]{
var weeklyForcasts = [Daily]()
let weeklyWeather = weatherDictionary["daily"] as! NSDictionary
let weeklyForcast = weeklyWeather["data"] as! NSArray
for dailyDict in weeklyForcast {
let dailyForecast = Daily.dailyWithDictionary(dailyDict as! NSDictionary)
weeklyForcasts.append(dailyForecast)
}
return weeklyForcasts
}
func windDirectionFromDegress(degrees: Int) -> String {
switch degrees {
case (0...45):
return "North"
case (315...360):
return "North"
case (45...135):
return "East"
case (135...225):
return "South"
case (225...315):
return "West"
default:
return "Unknown"
}
}
func dateStringFromUnixTime(unixTime: Int) -> String {
let timeInSeconds = NSTimeInterval(unixTime)
let weatherDate = NSDate(timeIntervalSince1970: timeInSeconds)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d"
return dateFormatter.stringFromDate(weatherDate)
}
func dayOne() -> Daily {
return weeklyForecast.allObjects[0] as! Daily
}
func dayTwo() -> Daily {
return weeklyForecast.allObjects[1] as! Daily
}
func dayThree() -> Daily {
return weeklyForecast.allObjects[2] as! Daily
}
func dayFour() -> Daily {
return weeklyForecast.allObjects[3] as! Daily
}
func dayFive() -> Daily {
return weeklyForecast.allObjects[4] as! Daily
}
}
| 32d6114d9c0f5d87c451f4bc5ad49946 | 26.333333 | 168 | 0.738966 | false | false | false | false |
arnav-gudibande/SwiftTweet | refs/heads/master | Swifter-master/Swifter/Swifter.swift | apache-2.0 | 2 | //
// Swifter.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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 Accounts
public class Swifter {
// MARK: - Types
public typealias JSONSuccessHandler = (json: JSON, response: NSHTTPURLResponse) -> Void
public typealias FailureHandler = (error: NSError) -> Void
internal struct CallbackNotification {
static let notificationName = "SwifterCallbackNotificationName"
static let optionsURLKey = "SwifterCallbackNotificationOptionsURLKey"
}
internal struct SwifterError {
static let domain = "SwifterErrorDomain"
static let appOnlyAuthenticationErrorCode = 1
}
internal struct DataParameters {
static let dataKey = "SwifterDataParameterKey"
static let fileNameKey = "SwifterDataParameterFilename"
}
// MARK: - Properties
let apiURL = NSURL(string: "https://api.twitter.com/1.1/")!
let uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")!
let streamURL = NSURL(string: "https://stream.twitter.com/1.1/")!
let userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")!
let siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")!
public var client: SwifterClientProtocol
// MARK: - Initializers
public init(consumerKey: String, consumerSecret: String, appOnly: Bool = false) {
self.client = appOnly
? SwifterAppOnlyClient(consumerKey: consumerKey, consumerSecret: consumerSecret)
: SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret)
}
public init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String) {
self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret , accessToken: oauthToken, accessTokenSecret: oauthTokenSecret)
}
public init(account: ACAccount) {
self.client = SwifterAccountsClient(account: account)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - JSON Requests
internal func jsonRequestWithPath(path: String, baseURL: NSURL, method: HTTPMethodType, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler? = nil, failure: SwifterHTTPRequest.FailureHandler? = nil) -> SwifterHTTPRequest {
let jsonDownloadProgressHandler: SwifterHTTPRequest.DownloadProgressHandler = { data, _, _, response in
guard downloadProgress != nil else { return }
if let jsonResult = try? JSON.parseJSONData(data) {
downloadProgress?(json: jsonResult, response: response)
} else {
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonChunks = jsonString!.componentsSeparatedByString("\r\n") as [String]
for chunk in jsonChunks where !chunk.utf16.isEmpty {
if let chunkData = chunk.dataUsingEncoding(NSUTF8StringEncoding),
let jsonResult = try? JSON.parseJSONData(chunkData) {
downloadProgress?(json: jsonResult, response: response)
}
}
}
}
let jsonSuccessHandler: SwifterHTTPRequest.SuccessHandler = { data, response in
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) {
do {
let jsonResult = try JSON.parseJSONData(data)
dispatch_async(dispatch_get_main_queue()) {
success?(json: jsonResult, response: response)
}
} catch let error as NSError {
dispatch_async(dispatch_get_main_queue()) {
failure?(error: error)
}
}
}
}
if method == .GET {
return self.client.get(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure)
}
else {
return self.client.post(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure)
}
}
internal func getJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest {
return self.jsonRequestWithPath(path, baseURL: baseURL, method: .GET, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure)
}
internal func postJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest {
return self.jsonRequestWithPath(path, baseURL: baseURL, method: .POST, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure)
}
}
| 86618a3ac4285c5639f496eac0979156 | 48.022222 | 349 | 0.690994 | false | false | false | false |
josve05a/wikipedia-ios | refs/heads/develop | WMF Framework/SummaryExtensions.swift | mit | 2 | extension WMFArticle {
func merge(_ article: WMFArticle) {
guard article.objectID != objectID else {
return
}
// merge important keys not set by the summary
let keysToMerge = [#keyPath(WMFArticle.savedDate), #keyPath(WMFArticle.placesSortOrder), #keyPath(WMFArticle.pageViews)]
for key in keysToMerge {
guard let valueToMerge = article.value(forKey: key) else {
continue
}
// keep the later date when both have date values
if let dateValueToMerge = valueToMerge as? Date, let dateValue = value(forKey: key) as? Date, dateValue > dateValueToMerge {
continue
}
// prefer existing values
if value(forKey: key) != nil {
continue
}
setValue(valueToMerge, forKey: key)
}
if let articleReadingLists = article.readingLists {
addReadingLists(articleReadingLists)
}
if let articlePreviewReadingLists = article.previewReadingLists {
addPreviewReadingLists(articlePreviewReadingLists)
}
if article.isExcludedFromFeed {
isExcludedFromFeed = true
}
let mergeViewedProperties: Bool
if let viewedDateToMerge = article.viewedDate {
if let existingViewedDate = viewedDate, existingViewedDate > viewedDateToMerge {
mergeViewedProperties = false
} else {
mergeViewedProperties = true
}
} else {
mergeViewedProperties = false
}
if mergeViewedProperties {
viewedDate = article.viewedDate
viewedFragment = article.viewedFragment
viewedScrollPosition = article.viewedScrollPosition
wasSignificantlyViewed = article.wasSignificantlyViewed
}
}
@objc public func update(withSummary summary: ArticleSummary) {
if let original = summary.original {
imageURLString = original.source
imageWidth = NSNumber(value: original.width)
imageHeight = NSNumber(value: original.height)
} else {
imageURLString = nil
imageWidth = NSNumber(value: 0)
imageHeight = NSNumber(value: 0)
}
wikidataDescription = summary.articleDescription
displayTitleHTML = summary.displayTitle ?? summary.title ?? ""
snippet = summary.extract?.wmf_summaryFromText()
if let summaryCoordinate = summary.coordinates {
coordinate = CLLocationCoordinate2D(latitude: summaryCoordinate.lat, longitude: summaryCoordinate.lon)
} else {
coordinate = nil
}
}
}
extension NSManagedObjectContext {
@objc public func wmf_createOrUpdateArticleSummmaries(withSummaryResponses summaryResponses: [String: ArticleSummary]) throws -> [String: WMFArticle] {
guard !summaryResponses.isEmpty else {
return [:]
}
var keys: [String] = []
var reverseRedirectedKeys: [String: String] = [:]
keys.reserveCapacity(summaryResponses.count)
for (key, summary) in summaryResponses {
guard
let summaryKey = summary.key,
key != summaryKey // find the mismatched keys
else {
keys.append(key)
continue
}
reverseRedirectedKeys[summaryKey] = key
keys.append(summaryKey)
do {
let articlesWithKey = try fetchArticles(withKey: key)
let articlesWithSummaryKey = try fetchArticles(withKey: summaryKey)
guard let canonicalArticle = articlesWithSummaryKey.first ?? articlesWithKey.first else {
continue
}
for article in articlesWithKey {
canonicalArticle.merge(article)
delete(article)
}
for article in articlesWithSummaryKey {
canonicalArticle.merge(article)
delete(article)
}
canonicalArticle.key = summaryKey
} catch let error {
DDLogError("Error fetching articles for merge: \(error)")
}
}
var keysToCreate = Set(keys)
let articlesToUpdateFetchRequest = WMFArticle.fetchRequest()
articlesToUpdateFetchRequest.predicate = NSPredicate(format: "key IN %@", keys)
var articles: [String: WMFArticle] = [:]
articles.reserveCapacity(keys.count)
let fetchedArticles = try self.fetch(articlesToUpdateFetchRequest)
for articleToUpdate in fetchedArticles {
guard let articleKey = articleToUpdate.key else {
continue
}
let requestedKey = reverseRedirectedKeys[articleKey] ?? articleKey
guard let result = summaryResponses[requestedKey] else {
articles[requestedKey] = articleToUpdate
continue
}
articleToUpdate.update(withSummary: result)
articles[requestedKey] = articleToUpdate
keysToCreate.remove(articleKey)
}
for key in keysToCreate {
let requestedKey = reverseRedirectedKeys[key] ?? key
guard let result = summaryResponses[requestedKey], // responses are by requested key
let article = self.createArticle(withKey: key) else { // article should have redirected key
continue
}
article.update(withSummary: result)
articles[requestedKey] = article
}
try self.save()
return articles
}
}
| 54b329137369a9f83abe9646058f3a21 | 39.165517 | 155 | 0.586538 | false | false | false | false |
ustwo/mockingbird | refs/heads/master | Sources/SwaggerKit/Model/Endpoint+Kitura.swift | mit | 1 | //
// Endpoint.swift
// Mockingbird
//
// Created by Aaron McTavish on 20/12/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
import Kitura
extension Endpoint {
// MARK: - Properties
var handler: RouterHandler {
let summary = self.summary
return { request, response, next in
var responseText = summary
if !request.parameters.isEmpty {
var parametersList: [String] = []
for (key, value) in request.parameters {
parametersList.append("- " + key + ": " + value)
}
responseText += "\n\nParameters:\n" +
parametersList.joined(separator: "\n")
}
response.send(responseText)
next()
}
}
static private let kituraPathRegexString = "\\{([^\\{\\}\\s]+)\\}"
var kituraPath: String {
#if os(Linux)
let regexObj = try? NSRegularExpression(pattern: Endpoint.kituraPathRegexString,
options: [])
#else
let regexObj = try? NSRegularExpression(pattern: Endpoint.kituraPathRegexString)
#endif
guard let regex = regexObj else {
return ""
}
let pathString = NSMutableString(string: path)
let range = NSRange(location: 0, length:pathString.length)
// swiftlint:disable:next redundant_discardable_let
let _ = regex.replaceMatches(in: pathString,
options: [],
range: range,
withTemplate: ":$1")
#if os(Linux)
return pathString._bridgeToSwift()
#else
return pathString as String
#endif
}
// MARK: - Routing
func add(to router: Router) {
let path = kituraPath
switch method {
case .connect:
router.connect(path, handler: handler)
case .delete:
router.delete(path, handler: handler)
case .get:
router.get(path, handler: handler)
case .head:
router.head(path, handler: handler)
case .options:
router.options(path, handler: handler)
case .patch:
router.patch(path, handler: handler)
case .post:
router.post(path, handler: handler)
case .put:
router.put(path, handler: handler)
case .trace:
router.trace(path, handler: handler)
}
}
}
| a3406556694f42f8d10a0691bd4949c4 | 28.083333 | 92 | 0.486032 | false | false | false | false |
gongmingqm10/DriftBook | refs/heads/master | DriftReading/DriftReading/CreateBookViewController.swift | mit | 1 | //
// CreateBookViewController.swift
// DriftReading
//
// Created by Ming Gong on 7/27/15.
// Copyright © 2015 gongmingqm10. All rights reserved.
//
import UIKit
class CreateBookViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
@IBOutlet weak var bookSearchBar: UISearchBar!
@IBOutlet weak var bookTableView: UITableView!
let doubanAPI = DoubanAPI()
let driftAPI = DriftAPI()
var books: [DoubanBook] = []
override func viewDidLoad() {
bookTableView.delegate = self
bookTableView.dataSource = self
bookSearchBar.delegate = self
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
doubanAPI.searchBooks(searchText, success: { (books) -> Void in
self.books = books
self.bookTableView.reloadData()
}) { (error) -> Void in
print(error.description)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 120
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = bookTableView.dequeueReusableCellWithIdentifier("DoubanTableCell", forIndexPath: indexPath) as! DoubanTableCell
let book = books[indexPath.row]
cell.populate(book)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let book = books[indexPath.row]
let alertController = UIAlertController(title: "提示", message: "确定将《\(book.name)》放漂吗?", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in
let user = DataUtils.sharedInstance.currentUser()
self.driftAPI.createDoubanBook(user.userId, book: book, success: { () -> Void in
self.navigationController?.popViewControllerAnimated(true)
}, failure: { (error) -> Void in
self.showErrorAlert()
})
}))
alertController.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
private func showErrorAlert() {
let alertController = UIAlertController(title: "提示", message: "图书添加失败,请稍后重试", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| 8326f5a5ae89825f09afab4e2f98e4af | 39.24 | 140 | 0.675613 | false | false | false | false |
AndreaMiotto/NASApp | refs/heads/master | NASApp/CollisionEventsTableViewController.swift | apache-2.0 | 1 | //
// CollisionEventsTableViewController.swift
// NASApp
//
// Created by Andrea Miotto on 23/03/17.
// Copyright © 2017 Andrea Miotto. All rights reserved.
//
import UIKit
class CollisionEventsTableViewController: UITableViewController {
//----------------------
// MARK: - Variables
//----------------------
///It keeps track of the asteroids
var asteroids : [Asteroid] = []
//----------------------
// MARK: - View Fuctions
//----------------------
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .done, target: nil, action: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//----------------------
// MARK: - Methods
//----------------------
/**This func will style the cell prperly */
func configureCell(cell: CollisionTableViewCell, withEntry entry: Asteroid) {
//setting the easy stuff
cell.nameLabel.text = entry.name
cell.dateLabel.text = entry.approachDate
if !entry.hazardous {
cell.hazardousLabel.isHidden = true
} else {
cell.hazardousLabel.isHidden = false
}
}
//----------------------
// MARK: - Table view data source
//----------------------
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return asteroids.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CollisionTableViewCell
let asteroid = self.asteroids[indexPath.row]
configureCell(cell: cell, withEntry: asteroid)
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "APPROACHING ASTEROIDS"
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
(view as! UITableViewHeaderFooterView).backgroundView?.backgroundColor = UIColor.black.withAlphaComponent(1)
(view as! UITableViewHeaderFooterView).textLabel?.textColor = UIColor.white.withAlphaComponent(0.4)
(view as! UITableViewHeaderFooterView).textLabel?.font = UIFont(name: "Helvetica", size: 15)
}
//----------------------
// MARK: - Navigation
//----------------------
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showAsteroid" {
if let indexPath = self.tableView.indexPathForSelectedRow {
if let nextVC = segue.destination as? AsteroidDetailsTableViewController {
nextVC.asteroid = asteroids[indexPath.row]
}
}
}
}
}
| 4b724bd38ae633db314af09103fe086d | 31.27551 | 116 | 0.59374 | false | false | false | false |
leschlogl/Programming-Contests | refs/heads/master | Hackerrank/30 Days of Code/day15.swift | mit | 1 |
func insert(head: Node?, data: Int!) -> Node? {
if head == nil {
return Node(data: data)
} else if head!.next == nil {
head!.next = Node(data: data)
} else {
insert(head: head!.next, data: data)
}
return head
}
| 23c7eb608c95f4ee023930bdf03deaf4 | 16.6 | 47 | 0.503788 | false | false | false | false |
google/JacquardSDKiOS | refs/heads/main | JacquardSDK/Classes/Internal/IMUDataCollectionAPI/IMUModuleComands.swift | apache-2.0 | 1 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Command request to retrieve all the modules available in the device.
struct ListIMUSessionsCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionTrialList
let sessionListRequest = Google_Jacquard_Protocol_DataCollectionTrialListRequest()
request.Google_Jacquard_Protocol_DataCollectionTrialListRequest_trialList = sessionListRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionTrialListResponse_trialList {
return .success(())
}
return .failure(CommandResponseStatus.errorAppUnknown)
}
}
struct IMUSessionNotificationSubscription: NotificationSubscription {
func extract(from outerProto: Any) -> IMUSessionInfo? {
guard let notification = outerProto as? Google_Jacquard_Protocol_Notification else {
jqLogger.assert(
"calling extract() with anything other than Google_Jacquard_Protocol_Notification is an error"
)
return nil
}
// Silently ignore other notifications.
guard notification.hasGoogle_Jacquard_Protocol_DataCollectionTrialListNotification_trialList
else {
return nil
}
let trial =
notification.Google_Jacquard_Protocol_DataCollectionTrialListNotification_trialList.trial
// If no trials are available, An empty session notification is sent by the tag.
if trial.hasTrialID {
let session = IMUSessionInfo(trial: trial)
return session
} else {
return nil
}
}
}
/// Command request to start IMU recording.
struct StartIMUSessionCommand: CommandRequest {
let sessionID: String
let campaignID: String
let groupID: String
let productID: String
let subjectID: String
init(
sessionID: String,
campaignID: String,
groupID: String,
productID: String,
subjectID: String
) {
self.sessionID = sessionID
self.campaignID = campaignID
self.groupID = groupID
self.productID = productID
self.subjectID = subjectID
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionStart
var metaData = Google_Jacquard_Protocol_DataCollectionMetadata()
metaData.mode = .store
metaData.campaignID = campaignID
// The `trialID` is named as `sessionID` for the client app.
// `groupID` is introduced to replace `sessionID` for any public api's
metaData.sessionID = groupID
metaData.trialID = sessionID
metaData.subjectID = subjectID
metaData.productID = productID
var sessionStartRequest = Google_Jacquard_Protocol_DataCollectionStartRequest()
sessionStartRequest.metadata = metaData
request.Google_Jacquard_Protocol_DataCollectionStartRequest_start = sessionStartRequest
return request
}
func parseResponse(outerProto: Any)
-> Result<Google_Jacquard_Protocol_DataCollectionStatus, Error>
{
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionStartResponse_start {
return .success(
outerProto.Google_Jacquard_Protocol_DataCollectionStartResponse_start.dcStatus)
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to stop IMU recording.
struct StopIMUSessionCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionStop
var sessionStopRequest = Google_Jacquard_Protocol_DataCollectionStopRequest()
sessionStopRequest.isError = true
request.Google_Jacquard_Protocol_DataCollectionStopRequest_stop = sessionStopRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionStopResponse_stop {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to get the current status of datacollection.
struct IMUDataCollectionStatusCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionStatus
let dcStatusRequest = Google_Jacquard_Protocol_DataCollectionStatusRequest()
request.Google_Jacquard_Protocol_DataCollectionStatusRequest_status = dcStatusRequest
return request
}
func parseResponse(
outerProto: Any
) -> Result<Google_Jacquard_Protocol_DataCollectionStatus, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
let dcStatus = outerProto.Google_Jacquard_Protocol_DataCollectionStatusResponse_status.dcStatus
return .success(dcStatus)
}
}
/// Command request to delete a session on the tag.
struct DeleteIMUSessionCommand: CommandRequest {
let session: IMUSessionInfo
init(session: IMUSessionInfo) {
self.session = session
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionTrialDataErase
var deleteTrialRequest = Google_Jacquard_Protocol_DataCollectionEraseTrialDataRequest()
deleteTrialRequest.campaignID = session.campaignID
deleteTrialRequest.sessionID = session.groupID
deleteTrialRequest.trialID = session.sessionID
deleteTrialRequest.productID = session.productID
deleteTrialRequest.subjectID = session.subjectID
request.Google_Jacquard_Protocol_DataCollectionEraseTrialDataRequest_eraseTrialData =
deleteTrialRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard
let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionEraseTrialDataResponse_eraseTrialData {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to delete all sessions on the tag.
struct DeleteAllIMUSessionsCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionDataErase
let deleteAllRequest = Google_Jacquard_Protocol_DataCollectionEraseAllDataRequest()
request.Google_Jacquard_Protocol_DataCollectionEraseAllDataRequest_eraseAllData =
deleteAllRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionEraseAllDataResponse_eraseAllData {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to retrieve session data.
struct RetreiveIMUSessionDataCommand: CommandRequest {
let session: IMUSessionInfo
let offset: UInt32
init(session: IMUSessionInfo, offset: UInt32) {
self.session = session
self.offset = offset
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionTrialData
var sessionDataRequest = Google_Jacquard_Protocol_DataCollectionTrialDataRequest()
sessionDataRequest.campaignID = session.campaignID
sessionDataRequest.sessionID = session.groupID
sessionDataRequest.trialID = session.sessionID
sessionDataRequest.productID = session.productID
sessionDataRequest.subjectID = session.subjectID
sessionDataRequest.sensorID = 0
sessionDataRequest.offset = offset
request.Google_Jacquard_Protocol_DataCollectionTrialDataRequest_trialData = sessionDataRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard
let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionTrialDataResponse_trialData {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
| dedee7e256097cf1ae3beca6d0eea119 | 33.063694 | 104 | 0.751309 | false | false | false | false |
paulgriffiths/macvideopoker | refs/heads/master | VideoPoker/AppDelegate.swift | gpl-3.0 | 1 | //
// AppDelegate.swift
//
// Application delegate class.
//
// Copyright (c) 2015 Paul Griffiths.
// Distributed under the terms of the GNU General Public License. <http://www.gnu.org/licenses/>
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var difficultyMenu: NSMenuItem?
@IBOutlet weak var easyMenu: NSMenuItem?
@IBOutlet weak var normalMenu: NSMenuItem?
private var mainWindowController: MainWindowController?
private let preferenceManager: PreferenceManager = PreferenceManager()
private var easyDifficulty = true {
didSet {
self.mainWindowController?.easyDifficulty = easyDifficulty
preferenceManager.easyDifficulty = easyDifficulty
easyMenu?.state = easyDifficulty ? NSOnState : NSOffState
normalMenu?.state = easyDifficulty ? NSOffState : NSOnState
}
}
// MARK: - NSApplicationDelegate methods
func applicationDidFinishLaunching(aNotification: NSNotification) {
let mainWindowController = MainWindowController()
mainWindowController.showWindow(self)
self.mainWindowController = mainWindowController
easyDifficulty = preferenceManager.easyDifficulty
}
// Terminate the app by the red button
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
return true
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
// MARK: - Menu actions
@IBAction func difficultyMenuOptionChanged(sender: NSMenuItem) {
if let easyMenu = easyMenu, normalMenu = normalMenu {
switch sender {
case easyMenu:
easyDifficulty = true
case normalMenu:
easyDifficulty = false
default:
fatalError("Unrecognized difficulty menu selection")
}
}
}
@IBAction func newGameSelected(sender: NSMenuItem) {
self.mainWindowController?.resetGame()
}
}
| 4d157a9d02a003508e6b0d07986fa19f | 30.057143 | 97 | 0.660074 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk | refs/heads/master | Sources/CoreAPI/CoreAPI_AuthVault.swift | mit | 1 | //
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2018 ShopGun. All rights reserved.
import Foundation
extension CoreAPI {
final class AuthVault {
// MARK: - Types
enum AuthRegenerationType: Equatable {
case create // destroy and recreate a new token
case renewOrCreate // just renew the current token's expiry (performs `create` if no token)
case reauthorize(LoginCredentials) // renew the current token the specified credentials (fails if no token)
}
typealias SignedRequestCompletion = ((Result<URLRequest, Error>) -> Void)
// MARK: Funcs
init(baseURL: URL, key: String, secret: String, tokenLife: Int = 7_776_000, urlSession: URLSession, dataStore: ShopGunSDKDataStore?) {
self.baseURL = baseURL
self.key = key
self.secret = secret
self.tokenLife = tokenLife
self.dataStore = dataStore
self.urlSession = urlSession
self.activeRegenerateTask = nil
// load clientId/authState from the store (if provided)
let storedAuth = AuthVault.loadFromDataStore(dataStore)
if let auth = storedAuth.auth {
// Apply stored auth if it exists
self.authState = .authorized(token: auth.token, user: auth.user, clientId: storedAuth.clientId)
} else if let legacyAuthState = AuthVault.loadLegacyAuthState() {
// load, apply & clear any legacy auth from the previous version of the SDK
self.authState = legacyAuthState
self.updateStore()
AuthVault.clearLegacyAuthState()
Logger.log("Loaded AuthState from Legacy cache", level: .debug, source: .CoreAPI)
} else {
// If no stored auth, or legacy auth to migrate, mark as unauthorized.
self.authState = .unauthorized(error: nil, clientId: storedAuth.clientId)
}
}
func regenerate(_ type: AuthRegenerationType, completion: ((Error?) -> Void)? = nil) {
self.queue.async { [weak self] in
self?.regenerateOnQueue(type, completion: completion)
}
}
// Returns a new urlRequest that has been signed with the authToken
// If we are not authorized, or in the process of authorizing, then this can take some time to complete.
func signURLRequest(_ urlRequest: URLRequest, completion: @escaping SignedRequestCompletion) {
self.queue.async { [weak self] in
self?.signURLRequestOnQueue(urlRequest, completion: completion)
}
}
var authorizedUserDidChangeCallback: ((_ prev: AuthorizedUser?, _ new: AuthorizedUser?) -> Void)?
var additionalRequestParams: [String: String] = [:]
/// If we are authorized, and have an authorized user, then this is non-nil
var currentAuthorizedUser: AuthorizedUser? {
if case .authorized(_, let user, _) = self.authState, user != nil {
return user
} else {
return nil
}
}
func resetStoredAuthState() {
self.queue.async { [weak self] in
guard let s = self else { return }
AuthVault.clearLegacyAuthState()
AuthVault.updateDataStore(s.dataStore, data: nil)
s.authState = .unauthorized(error: nil, clientId: nil)
}
}
// MARK: - Private Types
enum AuthState {
case unauthorized(error: Error?, clientId: ClientIdentifier?) // we currently have no auth (TODO: `reason` enum insted of error?)
case authorized(token: String, user: AuthorizedUser?, clientId: ClientIdentifier?) // we have signed headers to return
}
// MARK: Private Vars
private let baseURL: URL
private let key: String
private let secret: String
private let tokenLife: Int
private weak var dataStore: ShopGunSDKDataStore?
private let urlSession: URLSession
private let queue = DispatchQueue(label: "ShopGunSDK.CoreAPI.AuthVault.Queue")
// if we are in the process of regenerating the token, this is set
private var activeRegenerateTask: (type: AuthRegenerationType, task: URLSessionTask)?
private var pendingSignedRequests: [(URLRequest, SignedRequestCompletion)] = []
private var authState: AuthState {
didSet {
// save the current authState to the store
updateStore()
// TODO: change to 'authStateDidChange', and trigger for _any_ change to the authState
guard let authDidChangeCallback = self.authorizedUserDidChangeCallback else { return }
var prevAuthUser: AuthorizedUser? = nil
if case .authorized(_, let user?, _) = oldValue {
prevAuthUser = user
}
if prevAuthUser?.person != currentAuthorizedUser?.person || prevAuthUser?.provider != currentAuthorizedUser?.provider {
authDidChangeCallback(prevAuthUser, currentAuthorizedUser)
}
}
}
var clientId: ClientIdentifier? {
switch self.authState {
case .authorized(_, _, let clientId),
.unauthorized(_, let clientId):
return clientId
}
}
var sessionToken: String? {
guard case let .authorized(token, _, _) = self.authState else { return nil }
return token
}
// MARK: Funcs
private func regenerateOnQueue(_ type: AuthRegenerationType, completion: ((Error?) -> Void)? = nil) {
// If we are in the process of doing a different kind of regen, cancel it
cancelActiveRegenerateTask()
var mutableCompletion = completion
// generate a request based on the regenerate type
let request: CoreAPI.Request<AuthSessionResponse>
switch (type, self.authState) {
case (.create, _),
(.renewOrCreate, .unauthorized):
request = AuthSessionResponse.createRequest(clientId: self.clientId, apiKey: self.key, tokenLife: self.tokenLife)
case (.renewOrCreate, .authorized):
request = AuthSessionResponse.renewRequest(clientId: self.clientId)
case (.reauthorize(let credentials), .authorized):
request = AuthSessionResponse.renewRequest(clientId: self.clientId, additionalParams: credentials.requestParams)
case (.reauthorize, .unauthorized):
// if we have no valid token at all when trying to reauthorize then just create
request = AuthSessionResponse.createRequest(clientId: self.clientId, apiKey: self.key, tokenLife: self.tokenLife)
// once completed, if we are authorized, then reauthorize with the credentials
mutableCompletion = { [weak self] (createError) in
self?.queue.async { [weak self] in
guard case .authorized? = self?.authState else {
DispatchQueue.main.async {
completion?(createError)
}
return
}
self?.regenerate(type, completion: completion)
}
}
}
var urlRequest = request.urlRequest(for: self.baseURL, additionalParameters: self.additionalRequestParams)
if case .authorized(let token, _, _) = self.authState,
request.requiresAuth == true {
urlRequest = urlRequest.signedForCoreAPI(withToken: token, secret: self.secret)
}
let task = self.urlSession.coreAPIDataTask(with: urlRequest) { [weak self] (authSessionResult: Result<AuthSessionResponse, Error>) -> Void in
self?.queue.async { [weak self] in
self?.activeRegenerateTaskCompleted(authSessionResult)
DispatchQueue.main.async {
mutableCompletion?(authSessionResult.getFailure())
}
}
}
self.activeRegenerateTask = (type: type, task: task)
task.resume()
}
private func signURLRequestOnQueue(_ urlRequest: URLRequest, completion: @escaping SignedRequestCompletion) {
// check if we are in the process of regenerating the token
// if so just save the completion handler to be run once regeneration finishes
guard self.activeRegenerateTask == nil else {
self.pendingSignedRequests.append((urlRequest, completion))
return
}
switch self.authState {
case .unauthorized(let authError, _):
if let authError = authError {
// unauthorized, with an error, so perform completion and forward the error
DispatchQueue.main.async {
completion(.failure(authError))
}
} else {
// unauthorized, without an error, so cache completion & start regenerating token
self.pendingSignedRequests.append((urlRequest, completion))
self.regenerate(.renewOrCreate)
}
case let .authorized(token, _, _):
// we are authorized, so sign the request and perform the completion handler
let signedRequest = urlRequest.signedForCoreAPI(withToken: token, secret: self.secret)
DispatchQueue.main.async {
completion(.success(signedRequest))
}
}
}
/// Save the current AuthState to the store
private func updateStore() {
guard let store = self.dataStore else { return }
switch self.authState {
case .unauthorized(_, nil):
AuthVault.updateDataStore(store, data: nil)
case let .unauthorized(_, clientId):
AuthVault.updateDataStore(store, data: StoreData(auth: nil, clientId: clientId))
case let .authorized(token, user, clientId):
AuthVault.updateDataStore(store, data: StoreData(auth: (token: token, user: user), clientId: clientId))
}
}
// If we are in the process of doing a different kind of regen, cancel it
private func cancelActiveRegenerateTask() {
self.activeRegenerateTask?.task.cancel()
self.activeRegenerateTask = nil
}
private func activeRegenerateTaskCompleted(_ result: Result<AuthSessionResponse, Error>) {
switch result {
case .success(let authSession):
Logger.log("Successfully updated authSession \(authSession)", level: .debug, source: .CoreAPI)
self.authState = .authorized(token: authSession.token, user: authSession.authorizedUser, clientId: authSession.clientId)
self.activeRegenerateTask = nil
// we are authorized, so sign the requests and perform the completion handlers
for (urlRequest, completion) in self.pendingSignedRequests {
let signedRequest = urlRequest.signedForCoreAPI(withToken: authSession.token, secret: self.secret)
DispatchQueue.main.async {
completion(.success(signedRequest))
}
}
case .failure(let cancelError as NSError)
where cancelError.domain == NSURLErrorDomain && cancelError.code == URLError.Code.cancelled.rawValue:
// if cancelled then ignore
break
case .failure(let regenError):
Logger.log("Failed to update authSession \(regenError)", level: .error, source: .CoreAPI)
let type = activeRegenerateTask?.type
self.activeRegenerateTask = nil
// we weren't creating, and the error isnt a network error, so try to just create the token.
if type != .create
&& (regenError as NSError).isNetworkError == false {
self.regenerateOnQueue(.create)
} else {
for (_, completion) in self.pendingSignedRequests {
DispatchQueue.main.async {
completion(.failure(regenError))
}
}
}
}
}
}
}
// MARK: -
extension CoreAPI.AuthVault {
/// The response from requests to the API's session endpoint
fileprivate struct AuthSessionResponse: Decodable {
var clientId: CoreAPI.ClientIdentifier
var token: String
var expiry: Date
var authorizedUser: CoreAPI.AuthorizedUser?
enum CodingKeys: String, CodingKey {
case clientId = "client_id"
case token = "token"
case expiry = "expires"
case provider = "provider"
case person = "user"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.clientId = try values.decode(CoreAPI.ClientIdentifier.self, forKey: .clientId)
self.token = try values.decode(String.self, forKey: .token)
if let provider = try? values.decode(CoreAPI.AuthorizedUserProvider.self, forKey: .provider),
let person = try? values.decode(CoreAPI.Person.self, forKey: .person) {
self.authorizedUser = (person, provider)
}
let expiryString = try values.decode(String.self, forKey: .expiry)
if let expiryDate = CoreAPI.dateFormatter.date(from: expiryString) {
self.expiry = expiryDate
} else {
throw DecodingError.dataCorruptedError(forKey: .expiry, in: values, debugDescription: "Date string does not match format expected by formatter (\(String(describing: CoreAPI.dateFormatter.dateFormat))).")
}
}
// MARK: Response-generating requests
static func createRequest(clientId: CoreAPI.ClientIdentifier?, apiKey: String, tokenLife: Int) -> CoreAPI.Request<AuthSessionResponse> {
var params: [String: String] = [:]
params["api_key"] = apiKey
params["token_ttl"] = String(tokenLife)
params["clientId"] = clientId?.rawValue
return .init(path: "v2/sessions", method: .POST, requiresAuth: false, httpBody: params, timeoutInterval: 10)
}
static func renewRequest(clientId: CoreAPI.ClientIdentifier?, additionalParams: [String: String] = [:]) -> CoreAPI.Request<AuthSessionResponse> {
var params: [String: String] = additionalParams
params["clientId"] = clientId?.rawValue
return .init(path: "v2/sessions", method: .PUT, requiresAuth: true, httpBody: params, timeoutInterval: 10)
}
}
}
// MARK: - DataStore
extension CoreAPI.AuthVault {
fileprivate static let dataStoreKey = "ShopGunSDK.CoreAPI.AuthVault"
fileprivate static func updateDataStore(_ dataStore: ShopGunSDKDataStore?, data: CoreAPI.AuthVault.StoreData?) {
var authJSON: String? = nil
if let data = data,
let authJSONData: Data = try? JSONEncoder().encode(data) {
authJSON = String(data: authJSONData, encoding: .utf8)
}
dataStore?.set(value: authJSON, for: CoreAPI.AuthVault.dataStoreKey)
}
fileprivate static func loadFromDataStore(_ dataStore: ShopGunSDKDataStore?) -> CoreAPI.AuthVault.StoreData {
guard let authJSONData = dataStore?.get(for: CoreAPI.AuthVault.dataStoreKey)?.data(using: .utf8),
let auth = try? JSONDecoder().decode(CoreAPI.AuthVault.StoreData.self, from: authJSONData) else {
return .init(auth: nil, clientId: nil)
}
return auth
}
// The data to be saved/read from disk
fileprivate struct StoreData: Codable {
var auth: (token: String, user: CoreAPI.AuthorizedUser?)?
var clientId: CoreAPI.ClientIdentifier?
init(auth: (token: String, user: CoreAPI.AuthorizedUser?)?, clientId: CoreAPI.ClientIdentifier?) {
self.auth = auth
self.clientId = clientId
}
enum CodingKeys: String, CodingKey {
case authToken = "auth.token"
case authUserPerson = "auth.user.person"
case authUserProvider = "auth.user.provider"
case clientId = "clientId"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
if let token = try? values.decode(String.self, forKey: .authToken) {
let authorizedUser: CoreAPI.AuthorizedUser?
if let provider = try? values.decode(CoreAPI.AuthorizedUserProvider.self, forKey: .authUserProvider),
let person = try? values.decode(CoreAPI.Person.self, forKey: .authUserPerson) {
authorizedUser = (person, provider)
} else {
authorizedUser = nil
}
self.auth = (token: token, user: authorizedUser)
} else {
self.auth = nil
}
self.clientId = try? values.decode(CoreAPI.ClientIdentifier.self, forKey: .clientId)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try? container.encode(self.auth?.token, forKey: .authToken)
try? container.encode(self.auth?.user?.person, forKey: .authUserPerson)
try? container.encode(self.auth?.user?.provider, forKey: .authUserProvider)
try? container.encode(self.clientId, forKey: .clientId)
}
}
}
// MARK: -
extension URLRequest {
/// Generates a new URLRequest that includes the signed HTTPHeaders, given a token & secret
fileprivate func signedForCoreAPI(withToken token: String, secret: String) -> URLRequest {
// make an SHA256 Hex string
let hashString = (secret + token).sha256()
var signedRequest = self
signedRequest.setValue(token, forHTTPHeaderField: "X-Token")
signedRequest.setValue(hashString, forHTTPHeaderField: "X-Signature")
return signedRequest
}
}
// MARK: -
extension CoreAPI.LoginCredentials {
/// What are the request params that a specific loginCredential needs to send when reauthorizing
fileprivate var requestParams: [String: String] {
switch self {
case .logout:
return ["email": ""]
case let .shopgun(email, password):
return ["email": email,
"password": password]
case let .facebook(token):
return ["facebook_token": token]
}
}
}
| fbed6178097b40f300049954c96d3e00 | 43.067982 | 219 | 0.567952 | false | false | false | false |
tamanyan/PageTabViewController | refs/heads/master | Sakuin/RecyclablePageTabController.swift | mit | 1 | //
// RecyclablePageTabController.swift
// Sakuin
//
// Created by svpcadmin on 11/11/16.
// Copyright © 2016 tamanyan. All rights reserved.
//
import UIKit
class RecyclablePageTabController: UIViewController, PageTabControllerType {
let controllers: [UIViewController]
let menuTitles: [String]
internal(set) var currentViewController: UIViewController!
fileprivate(set) var visibleControllers = [UIViewController]()
let contentScrollView: UIScrollView = {
$0.isPagingEnabled = true
$0.isDirectionalLockEnabled = true
$0.showsHorizontalScrollIndicator = false
$0.showsVerticalScrollIndicator = false
$0.scrollsToTop = false
$0.bounces = true
$0.translatesAutoresizingMaskIntoConstraints = false
return $0
}(UIScrollView(frame: .zero))
fileprivate var showingPages = Set<Int>()
fileprivate let menuView: MenuView
fileprivate var ready: Bool = false
let options: PageTabConfigurable
fileprivate var currentIndex: Int = 0 {
didSet {
guard ready else {
return
}
self.menuView.moveTo(page: self.currentIndex)
if let child = self.controllers[self.currentIndex] as? Pageable {
child.pageTabDidMovePage(controller: self.controllers[self.currentIndex], page: self.currentIndex)
}
}
}
/**
Menu Options
*/
fileprivate var menuOptions: MenuViewConfigurable {
return self.options.menuOptions
}
fileprivate var centerContentOffsetX: CGFloat {
return CGFloat(self.numberOfVisiblePages / 2) * self.contentScrollView.frame.width
}
/**
number of valid page
*/
var numberOfVisiblePages: Int {
return 3
}
/**
unit page size
*/
var pageSize: CGSize {
return self.contentScrollView.frame.size
}
/**
Count of all pages
*/
var pageCount: Int {
return self.controllers.count
}
/**
current page index
*/
var currentPage: Int {
return self.currentIndex
}
/**
previous page index
*/
var previousPage: Int {
switch self.menuOptions.displayMode {
case .infinite:
return self.currentPage - 1 < 0 ? self.pageCount - 1 : self.currentPage - 1
default:
return self.currentPage - 1
}
}
/**
next page index
*/
var nextPage: Int {
switch self.menuOptions.displayMode {
case .infinite:
return self.currentPage + 1 > self.pageCount - 1 ? 0 : self.currentPage + 1
default:
return self.currentPage + 1
}
}
/**
last page index
*/
var lastPage: Int {
return self.controllers.count - 1
}
/**
first page index
*/
var firstPage: Int {
return 0
}
init(pageItems: [(viewController: UIViewController, menuTitle: String)], options: PageTabConfigurable) {
self.controllers = pageItems.map { $0.viewController }
self.menuTitles = pageItems.map { $0.menuTitle }
self.options = options
self.currentIndex = options.defaultPage
self.menuView = MenuView(titles: self.menuTitles, options: self.options.menuOptions)
super.init(nibName: nil, bundle: nil)
self.automaticallyAdjustsScrollViewInsets = false
self.view.backgroundColor = options.backgroundColor
}
func setupChildViews() {
self.view.addSubview(self.contentScrollView)
self.view.addSubview(self.menuView)
// set layout of TabMenu and Content ScrollView
self.layoutTabMenuView()
self.layoutContentScrollView()
self.setPageView(page: self.currentPage)
self.menuView.menuSelectedBlock = { [unowned self] (prevPage: Int, nextPage: Int) in
self.setPageView(page: nextPage)
// will be hidden pages
let hidingPages = self.showingPages.filter { $0 != nextPage }
hidingPages.forEach {
if let child = self.controllers[$0] as? Pageable {
child.pageTabWillHidePage(controller: self.controllers[$0], page: $0)
}
}
// will show pages
if let child = self.controllers[nextPage] as? Pageable {
child.pageTabWillShowPage(controller: self.controllers[nextPage], page: nextPage)
}
self.showingPages = [nextPage]
}
self.menuView.moveToInitialPosition()
self.menuView.moveTo(page: self.currentPage)
if self.currentPage < self.controllers.count {
if let child = self.controllers[self.currentPage] as? Pageable {
child.pageTabWillShowPage(controller: self.controllers[self.currentPage], page: self.currentPage)
child.pageTabDidMovePage(controller: self.controllers[self.currentPage], page: self.currentPage)
}
self.showingPages.insert(self.currentPage)
}
self.ready = true
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.contentScrollView.contentSize = CGSize(
width: self.contentScrollView.frame.width * CGFloat(self.visibleControllers.count),
height: self.contentScrollView.frame.height)
self.contentScrollView.delegate = nil
if case .standard(_) = self.menuOptions.displayMode {
if self.currentPage == self.lastPage {
self.contentScrollView.contentOffset.x = self.pageSize.width * 2
} else if self.currentPage == self.firstPage {
self.contentScrollView.contentOffset.x = 0
} else {
self.setCenterContentOffset()
}
} else {
self.setCenterContentOffset()
}
self.contentScrollView.delegate = self
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
fileprivate func setPageView(page: Int) {
if case .standard(_) = self.menuOptions.displayMode {
if page == self.lastPage {
self.updatePage(currentPage: page - 1)
} else if page == self.firstPage {
self.updatePage(currentPage: page + 1)
} else {
self.updatePage(currentPage: page)
}
self.contentScrollView.delegate = nil
self.constructPagingViewControllers()
self.layoutPagingViewControllers()
self.setCenterContentOffset()
self.contentScrollView.delegate = self
if page == self.lastPage {
self.contentScrollView.delegate = nil
self.contentScrollView.contentOffset.x += self.pageSize.width
self.updatePage(currentPage: page)
self.contentScrollView.delegate = self
} else if page == self.firstPage {
self.contentScrollView.delegate = nil
self.contentScrollView.contentOffset.x -= self.pageSize.width
self.updatePage(currentPage: page)
self.contentScrollView.delegate = self
}
} else {
self.updatePage(currentPage: page)
self.constructPagingViewControllers()
self.layoutPagingViewControllers()
}
}
fileprivate func layoutContentScrollView() {
self.contentScrollView.translatesAutoresizingMaskIntoConstraints = false
if self.menuOptions.menuPosition == .top {
self.contentScrollView.topAnchor.constraint(equalTo: self.menuView.bottomAnchor).isActive = true
self.contentScrollView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.contentScrollView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.contentScrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
} else {
self.contentScrollView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true
self.contentScrollView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.contentScrollView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.contentScrollView.bottomAnchor.constraint(equalTo: self.menuView.topAnchor).isActive = true
}
self.contentScrollView.layoutIfNeeded()
}
fileprivate func layoutTabMenuView() {
self.menuView.translatesAutoresizingMaskIntoConstraints = false
if self.menuOptions.menuPosition == .top {
self.menuView.heightAnchor.constraint(equalToConstant: self.menuOptions.height).isActive = true
self.menuView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true
self.menuView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.menuView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
} else {
self.menuView.heightAnchor.constraint(equalToConstant: self.menuOptions.height).isActive = true
self.menuView.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor).isActive = true
self.menuView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.menuView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
}
self.menuView.layoutIfNeeded()
}
fileprivate func constructPagingViewControllers() {
for (index, controller) in controllers.enumerated() {
guard self.shouldLoad(page: index) else {
// remove unnecessary child view controllers
if self.isVisible(controller: controller) {
controller.willMove(toParentViewController: nil)
controller.view!.removeFromSuperview()
controller.removeFromParentViewController()
let _ = visibleControllers.index(of: controller).flatMap { visibleControllers.remove(at: $0) }
}
continue
}
if self.isVisible(controller: controller) {
continue
}
guard let pagingView = controller.view else {
fatalError("\(controller) doesn't have any view")
}
pagingView.frame = .zero
pagingView.translatesAutoresizingMaskIntoConstraints = false
self.contentScrollView.addSubview(pagingView)
addChildViewController(controller as UIViewController)
controller.didMove(toParentViewController: self)
self.visibleControllers.append(controller)
}
}
fileprivate func layoutPagingViewControllers() {
NSLayoutConstraint.deactivate(self.contentScrollView.constraints)
for (index, controller) in controllers.enumerated() {
guard let pageView = controller.view, self.shouldLoad(page: index) else {
continue
}
switch index {
case self.previousPage:
pageView.leftAnchor.constraint(equalTo: self.contentScrollView.leftAnchor).isActive = true
break
case self.currentPage:
guard let previousPagingView = self.controllers[self.previousPage].view,
let nextPagingView = self.controllers[self.nextPage].view else { continue }
pageView.leftAnchor.constraint(equalTo: previousPagingView.rightAnchor).isActive = true
pageView.rightAnchor.constraint(equalTo: nextPagingView.leftAnchor).isActive = true
break
case self.nextPage:
pageView.rightAnchor.constraint(equalTo: self.contentScrollView.rightAnchor).isActive = true
break
default: break
}
pageView.topAnchor.constraint(equalTo: self.contentScrollView.topAnchor).isActive = true
pageView.bottomAnchor.constraint(equalTo: self.contentScrollView.bottomAnchor).isActive = true
pageView.widthAnchor.constraint(equalTo: self.contentScrollView.widthAnchor).isActive = true
pageView.heightAnchor.constraint(equalTo: self.contentScrollView.heightAnchor).isActive = true
pageView.layoutIfNeeded()
}
}
func updatePage(currentPage page: Int) {
self.currentIndex = page
}
func shouldLoad(page: Int) -> Bool {
if self.currentPage == page ||
self.previousPage == page ||
self.nextPage == page {
return true
}
return false
}
fileprivate func setCenterContentOffset() {
self.contentScrollView.contentOffset = CGPoint(x: self.centerContentOffsetX, y: self.contentScrollView.contentOffset.y)
}
fileprivate func isVisible(controller: UIViewController) -> Bool {
return self.childViewControllers.contains(controller)
}
fileprivate func isVaildPage(_ page: Int) -> Bool {
return page < self.controllers.count && page >= 0
}
}
// MARK: - Scroll view delegate
extension RecyclablePageTabController: UIScrollViewDelegate {
private var nextPageThresholdX: CGFloat {
return (self.contentScrollView.contentSize.width / 2) + self.pageSize.width * 1.5
}
private var prevPageThresholdX: CGFloat {
return (self.contentScrollView.contentSize.width / 2) - self.pageSize.width * 1.5
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let visibleBounds = self.contentScrollView.bounds
if visibleBounds.size.equalTo(CGSize.zero) {
return
}
var nowShowingPages = Set<Int>()
for (i, controller) in self.controllers.enumerated() {
if controller.view.frame.intersects(visibleBounds) && self.visibleControllers.contains(controller) {
nowShowingPages.insert(i)
}
}
let intersection = nowShowingPages.intersection(self.showingPages)
for i in nowShowingPages {
if (intersection.contains(i) == false) {
if let child = self.controllers[i] as? Pageable {
child.pageTabWillShowPage(controller: self.controllers[i], page: i)
}
}
}
for i in self.showingPages {
if (intersection.contains(i) == false) {
if let child = self.controllers[i] as? Pageable {
child.pageTabWillHidePage(controller: self.controllers[i], page: i)
}
}
}
self.showingPages = nowShowingPages
let minimumVisibleX = visibleBounds.minX
let maximumVisibleX = visibleBounds.maxX
if case .standard(_) = self.menuOptions.displayMode {
if self.lastPage == self.currentPage &&
maximumVisibleX <= (self.contentScrollView.contentSize.width / 2) + self.pageSize.width * 0.5 {
self.updatePage(currentPage: self.previousPage)
return
} else if self.firstPage == self.currentPage &&
minimumVisibleX >= (self.contentScrollView.contentSize.width / 2) - self.pageSize.width * 0.5 {
self.updatePage(currentPage: self.nextPage)
return
}
if self.nextPageThresholdX <= maximumVisibleX && self.isVaildPage(self.nextPage) {
self.updatePage(currentPage: self.nextPage)
guard self.isVaildPage(self.nextPage) else {
return
}
self.constructPagingViewControllers()
self.layoutPagingViewControllers()
self.contentScrollView.delegate = nil
self.contentScrollView.contentOffset.x -= self.pageSize.width
self.contentScrollView.delegate = self
} else if self.prevPageThresholdX >= minimumVisibleX && self.isVaildPage(self.previousPage) {
self.updatePage(currentPage: self.previousPage)
guard self.isVaildPage(self.previousPage) else {
return
}
self.constructPagingViewControllers()
self.layoutPagingViewControllers()
self.contentScrollView.delegate = nil
self.contentScrollView.contentOffset.x += self.pageSize.width
self.contentScrollView.delegate = self
}
} else {
if self.nextPageThresholdX <= maximumVisibleX && self.isVaildPage(self.nextPage) {
self.updatePage(currentPage: self.nextPage)
self.constructPagingViewControllers()
self.layoutPagingViewControllers()
self.contentScrollView.contentOffset.x -= self.pageSize.width
} else if self.prevPageThresholdX >= minimumVisibleX && self.isVaildPage(self.previousPage) {
self.updatePage(currentPage: self.previousPage)
self.constructPagingViewControllers()
self.layoutPagingViewControllers()
self.contentScrollView.contentOffset.x += self.pageSize.width
}
}
}
}
| a0fd7b6c9a950b889c32f5d2c4506756 | 36.87689 | 127 | 0.626048 | false | false | false | false |
Bartlebys/Bartleby | refs/heads/master | Bartleby.xOS/core/Bartleby.swift | apache-2.0 | 1 | //
// Bartleby.swift
// Bartleby
//
// Created by Benoit Pereira da Silva on 16/09/2015.
// Copyright © 2015 https://pereira-da-silva.com for Chaosmos SAS
// All rights reserved you can ask for a license.
import Foundation
#if os(OSX)
import AppKit
#else
import UIKit
#endif
//MARK: - Bartleby
// Bartleby's 1.0 approach is suitable for data set that can stored in memory.
open class Bartleby:NSObject,AliasResolution {
/// The standard singleton shared instance
open static let sharedInstance: Bartleby = {
let instance = Bartleby()
return instance
}()
static let b_version = "1.0"
static let b_release = "0"
open static let defaultLanguageCode = I18N.defaultLanguageCode
/// The version string of Bartleby framework
open static var versionString: String {
get {
return "\(self.b_version).\(self.b_release)"
}
}
// A unique run identifier that changes each time Bartleby is launched
open static let runUID: String=Bartleby.createUID()
// The configuration
public static var configuration: BartlebyConfiguration.Type=BartlebyDefaultConfiguration.self
// The crypto delegate
public static var cryptoDelegate: CryptoDelegate=NoCrypto()
// The File manager
// #TODO REMOVE BartlebyFileIO (simplification)
public static var fileManager: BartlebyFileIO=BFileManager()
/**
This method should be only used to cleanup in core unit test
*/
open func hardCoreCleanupForUnitTests() {
self._documents=[String:BartlebyDocument]()
}
/**
* When using ephemeralMode on registration Instance are marked ephemeral
*/
open static var ephemeral=false
open static var requestCounter=0
/**
Should be called on Init of the Document.
*/
open func configureWith(_ configuration: BartlebyConfiguration.Type) {
if configuration.DISABLE_DATA_CRYPTO {
// Use NoCrypto a neutral crypto delegate
Bartleby.cryptoDelegate=NoCrypto()
} else {
//Initialize the crypto delegate with the valid KEY & SALT
Bartleby.cryptoDelegate=CryptoHelper(salt: configuration.SHARED_SALT,keySize:configuration.KEY_SIZE)
}
// Store the configuration
Bartleby.configuration=configuration
// Ephemeral mode.
Bartleby.ephemeral=configuration.EPHEMERAL_MODE
// Configure the HTTP Manager
HTTPManager.configure()
}
override init() {
super.init()
}
// Bartleby's favourite
open static func please(_ message: String) -> String {
return "I would prefer not to!"
}
// MARK: -
// TODO: @md #crypto Check crypto key requirement
public static func isValidKey(_ key: String) -> Bool {
return key.count >= 32
}
// MARK: - Registries
// Each document is a stored separately
// Multiple documents can be openned at the same time
// and synchronized to different Servers.
// Bartleby supports multi-authentication and multi documents
/// Memory storage
fileprivate var _documents: [String:BartlebyDocument] = [String:BartlebyDocument]()
/**
Returns a document by its UID ( == document.metadata.persistentUID)
The SpaceUID is shared between multiple document.
- parameter UID: the uid of the document
- returns: the document
*/
open func getDocumentByUID(_ UID:UID) -> BartlebyDocument?{
if let document = self._documents[UID]{
return document
}
return nil
}
/**
Registers a document
- parameter document: the document
*/
open func declare(_ document: BartlebyDocument) {
self._documents[document.UID]=document
}
/**
Unloads the collections
- parameter documentUID: the target document UID
*/
open func forget(_ documentUID: UID) {
self._documents.removeValue(forKey: documentUID)
}
/**
Replaces the UID of a proxy Document
The proxy document is an instance that is created before to deserialize asynchronously the document Data
Should be exclusively used when re-openning an existing document.
- parameter documentProxyUID: the proxy UID
- parameter documentUID: the final UID
*/
open func replaceDocumentUID(_ documentProxyUID: UID, by documentUID: UID) {
if( documentProxyUID != documentUID) {
if let document=self._documents[documentProxyUID] {
self._documents[documentUID]=document
self._documents.removeValue(forKey: documentProxyUID)
}
}
}
/**
An UID generator compliant with MONGODB primary IDS constraints
- returns: the UID
*/
open static func createUID() -> UID {
// (!) NSUUID are not suitable for MONGODB as Primary Ids.
// We need to encode them we have choosen base64
let uid=UUID().uuidString
let utf8str = uid.data(using: Default.STRING_ENCODING)
return utf8str!.base64EncodedString(options: Data.Base64EncodingOptions(rawValue:0))
}
open static let startTime=CFAbsoluteTimeGetCurrent()
open static var elapsedTime:Double {
return CFAbsoluteTimeGetCurrent()-Bartleby.startTime
}
/**
Returns a random string of a given size.
- parameter len: the length
- parameter signs: the possible signs By default We exclude possibily confusing signs "oOiI01" to make random strings less ambiguous
- returns: the string
*/
open static func randomStringWithLength (_ len: UInt, signs: String="abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789") -> String {
var randomString = ""
for _ in (0 ..< len) {
let length = UInt32 (signs.count)
let rand = Int(arc4random_uniform(length))
let idx = signs.index(signs.startIndex, offsetBy: rand, limitedBy:signs.endIndex)
let c=signs[idx!]
randomString.append(c)
}
return randomString
}
// MARK: - Paths & URL
/**
Returns the search path directory
- parameter searchPath: the search Path
- returns: the path string
*/
open static func getSearchPath(_ searchPath: FileManager.SearchPathDirectory) -> String? {
let urls = FileManager.default.urls(for: searchPath, in: .userDomainMask)
if urls.count>0 {
let path = urls[0].path
return path
}
return nil
}
// MARK: - Maintenance
open func destroyLocalEphemeralInstances() {
for (dataSpaceUID, document) in self._documents {
document.log("Destroying EphemeralInstances on \(dataSpaceUID)", file:#file, function:#function, line:#line, category: Default.LOG_DEFAULT)
document.superIterate({ (element) in
if element.ephemeral {
document.delete(element)
}
})
}
}
//MARK: - Centralized ObjectList By UID
// this centralized dictionary allows to access to any referenced object by its UID
// to resolve externalReferences, cross reference, it simplify instance mobility from a Document to another, etc..
// future implementation may include extension for lazy Storage
fileprivate static var _instancesByUID=Dictionary<String, Collectible>()
// The number of registred object
open static var numberOfRegistredObject: Int {
get {
return _instancesByUID.count
}
}
/**
Registers an instance
- parameter instance: the Identifiable instance
*/
open static func register<T: Collectible>(_ instance: T) {
// Store the instance by its UID
self._instancesByUID[instance.UID]=instance
// Check if some deferred Ownership has been recorded
if let owneesUIDS = self._deferredOwnerships[instance.UID] {
/// This situation occurs for example
/// when the ownee has been triggered but not the owner
// or the deserialization of the ownee preceeds the owner
if let o=instance as? ManagedModel{
for owneeUID in owneesUIDS{
if let _ = Bartleby.registredManagedModelByUID(owneeUID){
// Add the owns entry
if !o.owns.contains(owneeUID){
o.owns.append(owneeUID)
}else{
print("### !")
}
}else{
print("----")
glog("Deferred ownership has failed to found \(owneeUID) for \(o.UID)", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false)
}
}
}
self._deferredOwnerships.removeValue(forKey: instance.UID)
}
}
/**
UnRegisters an instance
- parameter instance: the collectible instance
*/
open static func unRegister(_ instance: Collectible) {
self._instancesByUID.removeValue(forKey: instance.UID)
}
/**
UnRegisters an instance
- parameter instance: the collectible instance
*/
open static func unRegister(_ instances: [Collectible]) {
for instance in instances{
self._instancesByUID.removeValue(forKey: instance.UID)
}
}
/**
Returns the registred instance of by its UID
- parameter UID:
- returns: the instance
*/
open static func registredObjectByUID<T: Collectible>(_ UID: UID) throws-> T {
if let instance=self._instancesByUID[UID]{
if let casted=instance as? T{
return casted
}else{
throw DocumentError.instanceTypeMissMatch(found: instance.runTimeTypeName())
}
}
throw DocumentError.instanceNotFound
}
/// Returns a ManagedModel by its UID
/// Those instance are not casted.
/// You should most of the time use : `registredObjectByUID<T: Collectible>(_ UID: String) throws-> T`
/// - parameter UID:
/// - returns: the instance
open static func registredManagedModelByUID(_ UID: UID)-> ManagedModel? {
return try? Bartleby.registredObjectByUID(UID)
}
/// Returns a collection of ManagedModel by UIDs
/// Those instance are not casted.
/// You should most of the time use : `registredObjectByUID<T: Collectible>(_ UID: String) throws-> T`
/// - parameter UID:
/// - returns: the instance
open static func registredManagedModelByUIDs(_ UIDs: [UID])-> [ManagedModel]? {
return try? Bartleby.registredObjectsByUIDs(UIDs)
}
/// Returns the registred instance of by UIDs
///
/// - Parameter UIDs: the UIDs
/// - Returns: the registred Instances
open static func registredObjectsByUIDs<T: Collectible>(_ UIDs: [UID]) throws-> [T] {
var items=[T]()
for UID in UIDs{
items.append(try Bartleby.registredObjectByUID(UID))
}
return items
}
/**
Returns the instance by its UID
- parameter UID: needle
î
- returns: the instance
*/
open static func collectibleInstanceByUID(_ UID: UID) -> Collectible? {
return self._instancesByUID[UID]
}
/// Resolve the alias
///
/// - Parameter alias: the alias
/// - Returns: the reference
open static func instance(from alias:Alias)->Aliasable?{
return registredManagedModelByUID(alias.UID)
}
// MARK: - Deferred Ownwerships
/// If we receive a Instance that refers to an unexisting Owner
/// We store its missing entry is the deferredOwnerships dictionary
/// For future resolution (on registration)
/// [notAvailableOwnerUID][relatedOwnedUIDS]
fileprivate static var _deferredOwnerships=[UID:[UID]]()
/// Stores the ownee when the owner is not already available
/// This situation may occur on collection deserialization
/// when the owner is deserialized before the ownee.
///
/// - Parameters:
/// - ownee: the ownee
/// - ownerUID: the currently unavailable owner UID
open static func appendToDeferredOwnershipsList(_ ownee:Collectible,ownerUID:UID){
if self._deferredOwnerships.keys.contains(ownerUID) {
self._deferredOwnerships[ownerUID]!.append(ownee.UID)
}else{
self._deferredOwnerships[ownerUID]=[ownee.UID]
}
}
// MARK: - Report
/// Report the metrics to general endpoint calls (not clearly attached to a specific document)
///
/// - parameter metrics: the metrics
/// - parameter forURL: the concerned URL
open func report(_ metrics:Metrics,forURL:URL){
for( _ , document) in self._documents{
let s=document.baseURL.absoluteString
let us=forURL.absoluteString
if us.contains(s){
document.report(metrics)
}
}
}
// MARK: - Commit / Push Distribution (dynamic)
open static func markCommitted(_ instanceUID:UID){
if let instance=Bartleby.collectibleInstanceByUID(instanceUID){
instance.hasBeenCommitted()
}else{
glog("\(instanceUID) not found", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false)
}
}
}
| 6a4433ea4ea7e4dc962206aa33469cc5 | 29.441441 | 192 | 0.628588 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/TypeCoercion/overload_noncall.swift | apache-2.0 | 17 | // RUN: %target-typecheck-verify-swift
struct X { }
struct Y { }
struct Z { }
func f0(_ x1: X, x2: X) -> X {} // expected-note{{found this candidate}}
func f0(_ y1: Y, y2: Y) -> Y {} // expected-note{{found this candidate}}
var f0 : X // expected-note {{found this candidate}} expected-note {{'f0' previously declared here}}
func f0_init(_ x: X, y: Y) -> X {}
var f0 : (_ x : X, _ y : Y) -> X = f0_init // expected-error{{invalid redeclaration}}
func f1(_ x: X) -> X {}
func f2(_ g: (_ x: X) -> X) -> ((_ y: Y) -> Y) { }
func test_conv() {
var _ : (_ x1 : X, _ x2 : X) -> X = f0
var _ : (X, X) -> X = f0
var _ : (Y, X) -> X = f0 // expected-error{{ambiguous reference to member 'f0(_:x2:)'}}
var _ : (X) -> X = f1
var a7 : (X) -> (X) = f1
var a8 : (_ x2 : X) -> (X) = f1
var a9 : (_ x2 : X) -> ((X)) = f1
a7 = a8
a8 = a9
a9 = a7
var _ : ((X) -> X) -> ((Y) -> Y) = f2
var _ : ((_ x2 : X) -> (X)) -> (((_ y2 : Y) -> (Y))) = f2
typealias fp = ((X) -> X) -> ((Y) -> Y)
var _ = f2
}
var xy : X // expected-note {{previously declared here}}
var xy : Y // expected-error {{invalid redeclaration of 'xy'}}
func accept_X(_ x: inout X) { }
func accept_XY(_ x: inout X) -> X { }
func accept_XY(_ y: inout Y) -> Y { }
func accept_Z(_ z: inout Z) -> Z { }
func test_inout() {
var x : X
accept_X(&x);
accept_X(xy); // expected-error{{passing value of type 'X' to an inout parameter requires explicit '&'}} {{12-12=&}}
accept_X(&xy);
_ = accept_XY(&x);
x = accept_XY(&xy);
x = xy
x = &xy; // expected-error{{'&' used with non-inout argument of type 'X'}}
accept_Z(&xy); // expected-error{{cannot convert value of type 'X' to expected argument type 'Z'}}
}
func lvalue_or_rvalue(_ x: inout X) -> X { }
func lvalue_or_rvalue(_ x: X) -> Y { }
func test_lvalue_or_rvalue() {
var x : X
var y : Y
let x1 = lvalue_or_rvalue(&x)
x = x1
let y1 = lvalue_or_rvalue(x)
y = y1
_ = y
}
| a2ce8ec31196167d7f2c08bf00a70d66 | 26.6 | 118 | 0.522257 | false | false | false | false |
emilianoeloi/ios-estudosGerais | refs/heads/master | ios-estudosGerais/DezenoveViewController.swift | mit | 1 | //
// DezenoveViewController.swift
// ios-estudosGerais
//
// Created by Emiliano Barbosa on 1/12/16.
// Copyright © 2016 Emiliano E. S. Barbosa. All rights reserved.
//
import UIKit
class DezenoveViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = "Oi"
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| f6ea9eac32b49b4b9934eacf57b14bab | 33.231579 | 157 | 0.687884 | false | false | false | false |
fantast1k/Swiftent | refs/heads/master | Swiftent/Swiftent/Source/UIKit/UITextView+Contentable.swift | gpl-3.0 | 1 | //
// UITextView+Contentable.swift
// Swiftent
//
// Created by Dmitry Fa[n]tastik on 26/08/2016.
// Copyright © 2016 Fantastik Solution. All rights reserved.
//
import UIKit
extension UITextView : Contentable {
public typealias Content = UITextViewContent
public func installContent(_ content: UITextViewContent) {
switch content.text {
case .Raw(let txt):
if let txt = txt {
self.text = txt
}
case .Attributed(let txt):
if let txt = txt {
self.attributedText = txt
}
}
}
}
| 13d85c90e56f82c9c28c57aa69ebd871 | 20.714286 | 62 | 0.570724 | false | false | false | false |
ted005/Qiu_Suo | refs/heads/master | Qiu Suo/Qiu Suo/TWNodeSearchTableViewController.swift | gpl-2.0 | 2 | //
// TWNodeSearchTableViewController.swift
// V2EX Explorer
//
// Created by Robbie on 15/8/23.
// Copyright (c) 2015年 Ted Wei. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class TWNodeSearchTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate{
var searchController: UISearchController?
var nodes: [TWNode] = []
var filteredNodes: [TWNode] = []
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = true
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "seachCell")
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
//search
searchController = UISearchController(searchResultsController: nil)
self.searchController!.searchResultsUpdater = self
self.navigationItem.titleView = searchController?.searchBar
self.searchController?.dimsBackgroundDuringPresentation = false
self.searchController?.searchBar.barStyle = UIBarStyle.Default
self.searchController?.hidesNavigationBarDuringPresentation = false
self.searchController?.searchBar.delegate = self
//load all nodes
Alamofire.request(.GET, "https://www.v2ex.com/api/nodes/all.json")
.responseJSON { (req, res, result)in
if(result.isFailure) {
NSLog("Fail to load data.")
}
else {
let json = JSON(result.value!)
for subJson in json {
let node: TWNode = TWNode()
node.title = subJson.1["title"].stringValue
node.name = subJson.1["name"].stringValue
node.header = subJson.1["header"].stringValue
node.topics = subJson.1["topics"].intValue
node.url = subJson.1["url"].stringValue
self.nodes.append(node)
}
self.filteredNodes = self.nodes
//dont show all nodes
// self.tableView.reloadData()
}
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
filteredNodes.removeAll(keepCapacity: true)
let searchText = searchController.searchBar.text
for node in nodes {
if (node.title?.lowercaseString.rangeOfString(searchText!.lowercaseString) != nil) {
filteredNodes.append(node)
}
}
tableView.reloadData()
tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredNodes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath)
cell.textLabel?.text = filteredNodes[indexPath.row].title
cell.detailTextLabel?.text = filteredNodes[indexPath.row].header
return cell
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
//placeholder
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
//placeholder
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//wrong, will trigger receiver has no segue with identifier '***' error
// let destVC = TWExplorePostsTableViewController()
//init vc with storyboard, it has segue configured
let destVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("topicsInNodeVC") as! TWExplorePostsTableViewController
destVC.nodeName = filteredNodes[indexPath.row].name!
destVC.nodeNameForTitle = filteredNodes[indexPath.row].title!
self.navigationController?.pushViewController(destVC, animated: 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.
}
*/
//fix select back to Explore showing black screen
override func viewWillDisappear(animated: Bool) {
NSLog("will dispappear......")
super.viewWillDisappear(true)
self.searchController?.active = false
}
}
| a13ae1d1946ca60b77ee6137ad9b24c2 | 35.642857 | 156 | 0.635478 | false | false | false | false |
lucas34/SwiftQueue | refs/heads/master | Sources/SwiftQueue/Constraint+Retry.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2022 Lucas Nelaupe
//
// 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
internal final class JobRetryConstraint: SimpleConstraint, CodableConstraint {
/// Maximum number of authorised retried
internal var limit: Limit
required init(limit: Limit) {
self.limit = limit
}
convenience init?(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: RetryConstraintKey.self)
if container.contains(.retryLimit) {
try self.init(limit: container.decode(Limit.self, forKey: .retryLimit))
} else { return nil }
}
func onCompletionFail(sqOperation: SqOperation, error: Error) {
switch limit {
case .limited(let value):
if value > 0 {
sqOperation.retryJob(actual: self, retry: sqOperation.handler.onRetry(error: error), origin: error)
} else {
sqOperation.onTerminate()
}
case .unlimited:
sqOperation.retryJob(actual: self, retry: sqOperation.handler.onRetry(error: error), origin: error)
}
}
private enum RetryConstraintKey: String, CodingKey {
case retryLimit
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: RetryConstraintKey.self)
try container.encode(limit, forKey: .retryLimit)
}
}
fileprivate extension SqOperation {
func retryJob(actual: JobRetryConstraint, retry: RetryConstraint, origin: Error) {
func exponentialBackoff(initial: TimeInterval) -> TimeInterval {
currentRepetition += 1
return currentRepetition == 1 ? initial : initial * pow(2, Double(currentRepetition - 1))
}
func retryInBackgroundAfter(_ delay: TimeInterval) {
nextRunSchedule = Date().addingTimeInterval(delay)
dispatchQueue.runAfter(delay) { [weak actual, weak self] in
actual?.limit.decreaseValue(by: 1)
self?.run()
}
}
switch retry {
case .cancel:
lastError = SwiftQueueError.onRetryCancel(origin)
onTerminate()
case .retry(let after):
guard after > 0 else {
// Retry immediately
actual.limit.decreaseValue(by: 1)
self.run()
return
}
// Retry after time in parameter
retryInBackgroundAfter(after)
case .exponential(let initial):
retryInBackgroundAfter(exponentialBackoff(initial: initial))
case .exponentialWithLimit(let initial, let maxDelay):
retryInBackgroundAfter(min(maxDelay, exponentialBackoff(initial: initial)))
}
}
}
/// Behaviour for retrying the job
public enum RetryConstraint {
/// Retry after a certain time. If set to 0 it will retry immediately
case retry(delay: TimeInterval)
/// Will not retry, onRemoved will be called immediately
case cancel
/// Exponential back-off
case exponential(initial: TimeInterval)
/// Exponential back-off with max delay
case exponentialWithLimit(initial: TimeInterval, maxDelay: TimeInterval)
}
| 8acaf313cc87550813b8269a0cbd57b6 | 36.5 | 115 | 0.665731 | false | false | false | false |
AndrewBennet/readinglist | refs/heads/master | ReadingList/Views/BookTableHeader.swift | gpl-3.0 | 1 | import Foundation
import UIKit
class BookTableHeader: UITableViewHeaderFooterView {
var orderable: Orderable?
weak var presenter: UITableViewController?
var onSortChanged: (() -> Void)?
var alertOrMenu: AlertOrMenu! {
didSet {
if #available(iOS 14.0, *) {
sortButton.showsMenuAsPrimaryAction = true
// Rebuild the menu each time alertOrMenu is reassigned
sortButton.menu = alertOrMenu.menu()
}
}
}
static let height: CGFloat = 50
@IBOutlet private weak var label: UILabel!
@IBOutlet private weak var sortButton: UIButton!
@IBOutlet private weak var numberBadgeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
if let descriptor = label.font.fontDescriptor.withDesign(.rounded) {
label.font = UIFont(descriptor: descriptor, size: label.font.pointSize)
}
numberBadgeLabel.font = .rounded(ofSize: numberBadgeLabel.font.pointSize, weight: .semibold)
}
@IBAction private func sortButtonTapped(_ sender: UIButton) {
if #available(iOS 14.0, *) {
assert(sender.showsMenuAsPrimaryAction)
return
}
let alert = alertOrMenu.actionSheet()
alert.popoverPresentationController?.setButton(sortButton)
presenter?.present(alert, animated: true, completion: nil)
}
func configure(labelText: String, badgeNumber: Int?, enableSort: Bool) {
label.text = labelText
sortButton.isEnabled = enableSort
if let badgeNumber = badgeNumber {
numberBadgeLabel.superview!.isHidden = false
numberBadgeLabel.text = "\(badgeNumber)"
} else {
numberBadgeLabel.superview!.isHidden = true
}
}
private func buildBookSortAlertOrMenu() -> AlertOrMenu {
guard let orderable = orderable else { preconditionFailure() }
let selectedSort = orderable.getSort()
return AlertOrMenu(title: "Choose Order", items: BookSort.allCases.filter { orderable.supports($0) }.map { sort in
AlertOrMenu.Item(title: sort == selectedSort ? "\(sort.description) ✓" : sort.description) { [weak self] in
if selectedSort == sort { return }
orderable.setSort(sort)
guard let `self` = self else { return }
// Rebuild the menu, so the tick is in the right place next time
if #available(iOS 14.0, *) {
self.alertOrMenu = self.buildBookSortAlertOrMenu()
}
self.onSortChanged?()
}
})
}
func configure(readState: BookReadState, bookCount: Int, enableSort: Bool) {
configure(labelText: "\(readState.description)", badgeNumber: bookCount, enableSort: enableSort)
orderable = .book(readState)
alertOrMenu = buildBookSortAlertOrMenu()
}
func configure(list: List, bookCount: Int, enableSort: Bool) {
configure(labelText: "\(bookCount) book\(bookCount == 1 ? "" : "s")", badgeNumber: nil, enableSort: enableSort)
orderable = .list(list)
alertOrMenu = buildBookSortAlertOrMenu()
}
}
| b86d21f6804f52137828ff1f0fda37af | 38.280488 | 122 | 0.625893 | false | true | false | false |
coffee-cup/solis | refs/heads/master | SunriseSunset/Sunline.swift | mit | 1 | //
// SunLine.swift
// SunriseSunset
//
// Created by Jake Runzer on 2016-05-18.
// Copyright © 2016 Puddllee. All rights reserved.
//
import Foundation
import UIKit
class Sunline: UIView {
var line: UIView!
var timeLabel: UILabel!
var nameLabel: UILabel!
var parentView: UIView!
var topConstraint: NSLayoutConstraint!
var lineLeftConstraint: NSLayoutConstraint!
var lineRightConstraint: NSLayoutConstraint!
var nameLeftConstraint: NSLayoutConstraint!
var time: Date!
var colliding = false
let CollidingMinutesThreshhold = 12
let LineHorizontalPadding: CGFloat = 100
let NameHorizontalPadding: CGFloat = 20
let CollideAnimationDuration: TimeInterval = 0.25
override init (frame : CGRect) {
super.init(frame : frame)
}
convenience init () {
self.init(frame:CGRect.zero)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
func createLine(_ parentView: UIView, type: SunType) {
self.parentView = parentView
DispatchQueue.main.async {
self.line = UIView()
self.timeLabel = UILabel()
self.nameLabel = UILabel()
self.translatesAutoresizingMaskIntoConstraints = false
self.line.translatesAutoresizingMaskIntoConstraints = false
self.timeLabel.translatesAutoresizingMaskIntoConstraints = false
self.nameLabel.translatesAutoresizingMaskIntoConstraints = false
parentView.addSubview(self)
self.addSubview(self.line)
self.addSubview(self.timeLabel)
self.addSubview(self.nameLabel)
// View Contraints
self.topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: parentView, attribute: .top, multiplier: 1, constant: 0)
let edgeConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": self])
NSLayoutConstraint.activate(edgeConstraints + [self.topConstraint])
// Line Constraints
self.lineLeftConstraint = NSLayoutConstraint(item: self.line!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
self.lineRightConstraint = NSLayoutConstraint(item: self.line!, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -self.LineHorizontalPadding)
let lineVerticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[view]|", options: [], metrics: nil, views: ["view": self.line!])
let lineHeightContraint = NSLayoutConstraint(item: self.line!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 1)
NSLayoutConstraint.activate([self.lineLeftConstraint, self.lineRightConstraint, lineHeightContraint] + lineVerticalConstraints)
// Name Constraints
self.nameLeftConstraint = NSLayoutConstraint(item: self.nameLabel!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: self.NameHorizontalPadding)
let nameVerticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[view]-2-|", options: [], metrics: nil, views: ["view": self.nameLabel!])
NSLayoutConstraint.activate(nameVerticalConstraints + [self.nameLeftConstraint])
// Time Contstraints
let timeCenterConstraint = NSLayoutConstraint(item: self.timeLabel!, attribute: .centerY, relatedBy: .equal, toItem: self.line, attribute: .centerY, multiplier: 1, constant: 0)
let timeHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-10-|", options: [], metrics: nil, views: ["view": self.timeLabel!])
NSLayoutConstraint.activate(timeHorizontalConstraints + [timeCenterConstraint])
self.backgroundColor = UIColor.red
self.line.backgroundColor = type.lineColour
self.nameLabel.text = type.description.lowercased()
self.nameLabel.textColor = nameTextColour
self.nameLabel.font = fontTwilight
self.timeLabel.textColor = timeTextColour
self.timeLabel.text = "12:12"
self.timeLabel.font = fontDetail
self.nameLabel.addSimpleShadow()
self.timeLabel.addSimpleShadow()
self.isHidden = true
self.alpha = 0
}
}
func getTimeText(_ offset: TimeInterval) -> String {
let text = TimeFormatters.currentFormattedString(time, timeZone: TimeZones.currentTimeZone)
return text
}
// Animates the items in the sunline to avoid collision with now line
// Returns whether there will be a collision with now line
func animateAvoidCollision(_ offset: TimeInterval) -> Bool {
let offsetTime = Date().addingTimeInterval(offset)
let difference = abs(offsetTime.getDifferenceInMinutes(time))
if difference < CollidingMinutesThreshhold {
animateForCollision()
return true
} else {
animateToNormal()
}
return false
}
func animateForCollision() {
if !colliding {
// Fixes sunline overlap on iphone5 screens and smaller
let namePaddingFraction: CGFloat = parentView.frame.width < 375 ? 3 : 1
lineLeftConstraint.constant = LineHorizontalPadding
nameLeftConstraint.constant = LineHorizontalPadding + (NameHorizontalPadding / namePaddingFraction)
UIView.animate(withDuration: CollideAnimationDuration, delay: 0, options: UIView.AnimationOptions(), animations: {
self.layoutIfNeeded()
self.timeLabel.alpha = 0
}, completion: nil)
}
colliding = true
}
func animateToNormal() {
if colliding {
lineLeftConstraint.constant = 0
nameLeftConstraint.constant = NameHorizontalPadding
UIView.animate(withDuration: CollideAnimationDuration, delay: 0, options: UIView.AnimationOptions(), animations: {
self.layoutIfNeeded()
self.timeLabel.alpha = 1
}, completion: nil)
}
colliding = false
}
// Returns whether there will be a collision with now line
func updateTime(_ offset: TimeInterval = 0) -> Bool {
if time == nil {
return false
}
let timeText = getTimeText(offset)
let isCollision = animateAvoidCollision(offset)
DispatchQueue.main.async {
if self.time != nil {
self.timeLabel.text = timeText
}
}
return isCollision
}
func updateLine(_ time: Date, percent: Float, happens: Bool) {
DispatchQueue.main.async {
self.time = time
let _ = self.updateTime()
self.topConstraint.constant = self.parentView.frame.height * CGFloat(percent)
UIView.animate(withDuration: 0.5) {
self.parentView.layoutIfNeeded()
}
if happens {
self.isHidden = false
UIView.animate(withDuration: 0.5, delay: 1, options: UIView.AnimationOptions(), animations: {
self.alpha = 1
}, completion: nil)
} else {
UIView.animate(withDuration: 0.5, delay: 1, options: UIView.AnimationOptions(), animations: {
self.alpha = 0
}, completion: nil)
}
}
}
}
| d0901724a22db27c31cb7737e3826427 | 40.936842 | 207 | 0.622741 | false | false | false | false |
cdmx/MiniMancera | refs/heads/master | miniMancera/Model/Option/WhistlesVsZombies/Strategy/MOptionWhistlesVsZombiesStrategyDefeated.swift | mit | 1 | import Foundation
class MOptionWhistlesVsZombiesStrategyDefeated:MGameStrategyMain<MOptionWhistlesVsZombies>
{
private var startingTime:TimeInterval?
private let kWait:TimeInterval = 3.5
init(model:MOptionWhistlesVsZombies)
{
let updateItems:[MGameUpdate<MOptionWhistlesVsZombies>] = [
model.player,
model.sonicBoom,
model.zombie,
model.points,
model.hud]
super.init(
model:model,
updateItems:updateItems)
}
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
super.update(elapsedTime:elapsedTime, scene:scene)
if let startingTime:TimeInterval = self.startingTime
{
let deltaTime:TimeInterval = elapsedTime - startingTime
if deltaTime > kWait
{
timeOut(scene:scene)
}
}
else
{
startingTime = elapsedTime
}
}
//MARK: private
private func timeOut(scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
guard
let controller:COptionWhistlesVsZombies = scene.controller as? COptionWhistlesVsZombies
else
{
return
}
controller.showGameOver()
}
}
| ecf81804564af8fc9cefc68e5a32b4f0 | 23.448276 | 99 | 0.569111 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/stmt/statements.swift | apache-2.0 | 12 | // RUN: %target-typecheck-verify-swift
/* block comments */
/* /* nested too */ */
func markUsed<T>(_ t: T) {}
func f1(_ a: Int, _ y: Int) {}
func f2() {}
func f3() -> Int {}
func invalid_semi() {
; // expected-error {{';' statements are not allowed}} {{3-5=}}
}
func nested1(_ x: Int) {
var y : Int
func nested2(_ z: Int) -> Int {
return x+y+z
}
_ = nested2(1)
}
func funcdecl5(_ a: Int, y: Int) {
var x : Int
// a few statements
if (x != 0) {
if (x != 0 || f3() != 0) {
// while with and without a space after it.
while(true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}}
while (true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}}
}
}
// Assignment statement.
x = y
(x) = y
1 = x // expected-error {{cannot assign to a literal value}}
(1) = x // expected-error {{cannot assign to a literal value}}
(x:1).x = 1 // expected-error {{cannot assign to immutable expression of type 'Int'}}
var tup : (x:Int, y:Int)
tup.x = 1
_ = tup
let B : Bool
// if/then/else.
if (B) {
} else if (y == 2) {
}
// This diagnostic is terrible - rdar://12939553
if x {} // expected-error {{'Int' is not convertible to 'Bool'}}
if true {
if (B) {
} else {
}
}
if (B) {
f1(1,2)
} else {
f2()
}
if (B) {
if (B) {
f1(1,2)
} else {
f2()
}
} else {
f2()
}
// while statement.
while (B) {
}
// It's okay to leave out the spaces in these.
while(B) {}
if(B) {}
}
struct infloopbool {
var boolValue: infloopbool {
return self
}
}
func infloopbooltest() {
if (infloopbool()) {} // expected-error {{'infloopbool' is not convertible to 'Bool'}}
}
// test "builder" API style
extension Int {
static func builder() -> Int { }
var builderProp: Int { return 0 }
func builder2() {}
}
Int
.builder()
.builderProp
.builder2()
struct SomeGeneric<T> {
static func builder() -> SomeGeneric<T> { }
var builderProp: SomeGeneric<T> { return .builder() }
func builder2() {}
}
SomeGeneric<Int>
.builder()
.builderProp
.builder2()
break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}}
continue // expected-error {{'continue' is only allowed inside a loop}}
while true {
func f() {
break // expected-error {{'break' is only allowed inside a loop}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
// Labeled if
MyIf: if 1 != 2 {
break MyIf
continue MyIf // expected-error {{'continue' cannot be used with if statements}}
break // break the while
continue // continue the while.
}
}
// Labeled if
MyOtherIf: if 1 != 2 {
break MyOtherIf
continue MyOtherIf // expected-error {{'continue' cannot be used with if statements}}
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
do {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
func tuple_assign() {
var a,b,c,d : Int
(a,b) = (1,2)
func f() -> (Int,Int) { return (1,2) }
((a,b), (c,d)) = (f(), f())
}
func missing_semicolons() {
var w = 321
func g() {}
g() w += 1 // expected-error{{consecutive statements}} {{6-6=;}}
var z = w"hello" // expected-error{{consecutive statements}} {{12-12=;}} expected-warning {{string literal is unused}}
class C {}class C2 {} // expected-error{{consecutive statements}} {{14-14=;}}
struct S {}struct S2 {} // expected-error{{consecutive statements}} {{14-14=;}}
func j() {}func k() {} // expected-error{{consecutive statements}} {{14-14=;}}
}
//===--- Return statement.
return 42 // expected-error {{return invalid outside of a func}}
return // expected-error {{return invalid outside of a func}}
func NonVoidReturn1() -> Int {
return // expected-error {{non-void function should return a value}}
}
func NonVoidReturn2() -> Int {
return + // expected-error {{unary operator cannot be separated from its operand}} {{11-1=}} expected-error {{expected expression in 'return' statement}}
}
func VoidReturn1() {
if true { return }
// Semicolon should be accepted -- rdar://11344875
return; // no-error
}
func VoidReturn2() {
return () // no-error
}
func VoidReturn3() {
return VoidReturn2() // no-error
}
//===--- If statement.
func IfStmt1() {
if 1 > 0 // expected-error {{expected '{' after 'if' condition}}
_ = 42
}
func IfStmt2() {
if 1 > 0 {
} else // expected-error {{expected '{' after 'else'}}
_ = 42
}
//===--- While statement.
func WhileStmt1() {
while 1 > 0 // expected-error {{expected '{' after 'while' condition}}
_ = 42
}
//===-- Do statement.
func DoStmt() {
// This is just a 'do' statement now.
do {
}
}
func DoWhileStmt() {
do { // expected-error {{'do-while' statement is not allowed; use 'repeat-while' instead}} {{3-5=repeat}}
} while true
}
//===--- Repeat-while statement.
func RepeatWhileStmt1() {
repeat {} while true
repeat {} while false
repeat { break } while true
repeat { continue } while true
}
func RepeatWhileStmt2() {
repeat // expected-error {{expected '{' after 'repeat'}} expected-error {{expected 'while' after body of 'repeat' statement}}
}
func RepeatWhileStmt4() {
repeat {
} while + // expected-error {{unary operator cannot be separated from its operand}} {{12-1=}} expected-error {{expected expression in 'repeat-while' condition}}
}
func brokenSwitch(_ x: Int) -> Int {
switch x {
case .Blah(var rep): // expected-error{{pattern cannot match values of type 'Int'}}
return rep
}
}
func switchWithVarsNotMatchingTypes(_ x: Int, y: Int, z: String) -> Int {
switch (x,y,z) {
case (let a, 0, _), (0, let a, _): // OK
return a
case (let a, _, _), (_, _, let a): // expected-error {{pattern variable bound to type 'String', expected type 'Int'}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
return a
}
}
func breakContinue(_ x : Int) -> Int {
Outer:
for _ in 0...1000 {
Switch: // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
switch x {
case 42: break Outer
case 97: continue Outer
case 102: break Switch
case 13: continue
case 139: break // <rdar://problem/16563853> 'break' should be able to break out of switch statements
}
}
// <rdar://problem/16692437> shadowing loop labels should be an error
Loop: // expected-note {{previously declared here}}
for _ in 0...2 {
Loop: // expected-error {{label 'Loop' cannot be reused on an inner statement}}
for _ in 0...2 {
}
}
// <rdar://problem/16798323> Following a 'break' statement by another statement on a new line result in an error/fit-it
switch 5 {
case 5:
markUsed("before the break")
break
markUsed("after the break") // 'markUsed' is not a label for the break.
default:
markUsed("")
}
let x : Int? = 42
// <rdar://problem/16879701> Should be able to pattern match 'nil' against optionals
switch x { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.some(_)'}}
case .some(42): break
case nil: break
}
}
enum MyEnumWithCaseLabels {
case Case(one: String, two: Int)
}
func testMyEnumWithCaseLabels(_ a : MyEnumWithCaseLabels) {
// <rdar://problem/20135489> Enum case labels are ignored in "case let" statements
switch a {
case let .Case(one: _, two: x): break // ok
case let .Case(xxx: _, two: x): break // expected-error {{tuple pattern element label 'xxx' must be 'one'}}
// TODO: In principle, reordering like this could be supported.
case let .Case(two: _, one: x): break // expected-error {{tuple pattern element label}}
}
}
// "defer"
func test_defer(_ a : Int) {
defer { VoidReturn1() }
defer { breakContinue(1)+42 } // expected-warning {{result of operator '+' is unused}}
// Ok:
defer { while false { break } }
// Not ok.
while false { defer { break } } // expected-error {{'break' cannot transfer control out of a defer statement}}
defer { return } // expected-error {{'return' cannot transfer control out of a defer statement}}
}
class SomeTestClass {
var x = 42
func method() {
defer { x = 97 } // self. not required here!
}
}
class SomeDerivedClass: SomeTestClass {
override init() {
defer {
super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
}
}
func test_guard(_ x : Int, y : Int??, cond : Bool) {
// These are all ok.
guard let a = y else {}
markUsed(a)
guard let b = y, cond else {}
guard case let c = x, cond else {}
guard case let Optional.some(d) = y else {}
guard x != 4, case _ = x else { }
guard let e, cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard case let f? : Int?, cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard let g = y else {
markUsed(g) // expected-error {{variable declared in 'guard' condition is not usable in its body}}
}
guard let h = y, cond {} // expected-error {{expected 'else' after 'guard' condition}} {{25-25=else }}
guard case _ = x else {} // expected-warning {{'guard' condition is always true, body is unreachable}}
}
func test_is_as_patterns() {
switch 4 {
case is Int: break // expected-warning {{'is' test is always true}}
case _ as Int: break // expected-warning {{'as' test is always true}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
}
// <rdar://problem/21387308> Fuzzing SourceKit: crash in Parser::parseStmtForEach(...)
func matching_pattern_recursion() {
switch 42 {
case { // expected-error {{expression pattern of type '() -> ()' cannot match values of type 'Int'}}
for i in zs {
}
}: break
}
}
// <rdar://problem/18776073> Swift's break operator in switch should be indicated in errors
func r18776073(_ a : Int?) {
switch a {
case nil: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{14-14= break}}
case _?: break
}
}
// <rdar://problem/22491782> unhelpful error message from "throw nil"
func testThrowNil() throws {
throw nil // expected-error {{cannot infer concrete Error for thrown 'nil' value}}
}
// rdar://problem/23684220
// Even if the condition fails to typecheck, save it in the AST anyway; the old
// condition may have contained a SequenceExpr.
func r23684220(_ b: Any) {
if let _ = b ?? b {} // expected-error {{initializer for conditional binding must have Optional type, not 'Any'}}
// expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type 'Any', so the right side is never used}}
}
// <rdar://problem/21080671> QoI: try/catch (instead of do/catch) creates silly diagnostics
func f21080671() {
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
} catch { }
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
f21080671()
} catch let x as Int {
} catch {
}
}
// <rdar://problem/24467411> QoI: Using "&& #available" should fixit to comma
// https://twitter.com/radexp/status/694561060230184960
func f(_ x : Int, y : Int) {
if x == y && #available(iOS 52, *) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}}
if #available(iOS 52, *) && x == y {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{27-30=,}}
// https://twitter.com/radexp/status/694790631881883648
if x == y && let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}}
if x == y&&let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-14=,}}
}
// <rdar://problem/25178926> QoI: Warn about cases where switch statement "ignores" where clause
enum Type {
case Foo
case Bar
}
func r25178926(_ a : Type) {
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Bar'}}
case .Foo, .Bar where 1 != 100:
// expected-warning @-1 {{'where' only applies to the second pattern match in this case}}
// expected-note @-2 {{disambiguate by adding a line break between them if this is desired}} {{14-14=\n }}
// expected-note @-3 {{duplicate the 'where' on both patterns to check both patterns}} {{12-12= where 1 != 100}}
break
}
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Bar'}}
case .Foo: break
case .Bar where 1 != 100: break
}
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Bar'}}
case .Foo, // no warn
.Bar where 1 != 100:
break
}
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Foo'}}
// expected-note@-2 {{missing case: '.Bar'}}
case .Foo where 1 != 100, .Bar where 1 != 100:
break
}
}
do {
guard 1 == 2 else {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
}
func fn(a: Int) {
guard a < 1 else {
break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}}
}
}
func fn(x: Int) {
if x >= 0 {
guard x < 1 else {
guard x < 2 else {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
return
}
}
}
func bad_if() {
if 1 {} // expected-error {{'Int' is not convertible to 'Bool'}}
if (x: false) {} // expected-error {{'(x: Bool)' is not convertible to 'Bool'}}
if (x: 1) {} // expected-error {{'(x: Int)' is not convertible to 'Bool'}}
}
// Errors in case syntax
class
case, // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{expected pattern}}
case // expected-error {{expected identifier after comma in enum 'case' declaration}} expected-error {{expected identifier in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} expected-error {{expected pattern}}
// NOTE: EOF is important here to properly test a code path that used to crash the parser
| dd05a600ef538177ed068c80260834b1 | 27.55 | 253 | 0.627038 | false | false | false | false |
codefellows/sea-d40-iOS | refs/heads/master | Sample Code/Week2Filtering/ParseSwiftStarterProject/ParseStarterProject/FilterService.swift | mit | 1 | //
// FilterService.swift
// ParseStarterProject
//
// Created by Bradley Johnson on 8/12/15.
// Copyright (c) 2015 Parse. All rights reserved.
//
import UIKit
class FilterService {
class func sepiaImageFromOriginalImage(original : UIImage, context : CIContext) -> UIImage! {
let image = CIImage(image: original)
let filter = CIFilter(name: "CISepiaTone")
filter.setValue(image, forKey: kCIInputImageKey)
return filteredImageFromFilter(filter, context: context)
}
class func instantImageFromOriginalImage(original : UIImage,context : CIContext) -> UIImage! {
let image = CIImage(image: original)
let filter = CIFilter(name: "CIPhotoEffectInstant")
filter.setValue(image, forKey: kCIInputImageKey)
//set the vector for the colors
return filteredImageFromFilter(filter, context: context)
}
private class func filteredImageFromFilter(filter : CIFilter, context : CIContext) -> UIImage {
let outputImage = filter.outputImage
let extent = outputImage.extent()
let cgImage = context.createCGImage(outputImage, fromRect: extent)
return UIImage(CGImage: cgImage)!
}
}
| 7bfc1db1ef61f5a9e64191c27519d27b | 28.820513 | 97 | 0.713672 | false | false | false | false |
YaxinCheng/Weather | refs/heads/master | Weather/WeatherStation.swift | apache-2.0 | 1 | //
// WeatherStation.swift
// Weather
//
// Created by Yaxin Cheng on 2016-07-28.
// Copyright © 2016 Yaxin Cheng. All rights reserved.
//
import Foundation
import CoreLocation.CLLocation
import WeatherKit
struct WeatherStation {
let locationStorage: LocationStorage
fileprivate var weatherSource: WeatherKit.WeatherStation
static var sharedStation = WeatherStation()
var temperatureUnit: TemperatureUnit {
get {
return weatherSource.temperatureUnit
} set {
weatherSource.temperatureUnit = newValue
}
}
var speedUnit: SpeedUnit {
get {
return weatherSource.speedUnit
} set {
weatherSource.speedUnit = newValue
}
}
var distanceUnit: DistanceUnit {
get {
return weatherSource.distanceUnit
} set {
weatherSource.distanceUnit = newValue
}
}
var directionUnit: DirectionUnit {
get {
return weatherSource.directionUnit
} set {
weatherSource.directionUnit = newValue
}
}
fileprivate init() {
weatherSource = WeatherKit.WeatherStation()
locationStorage = LocationStorage()
let userDefault = UserDefaults.standard
temperatureUnit = userDefault.integer(forKey: "Temperature") == 1 ? .fahrenheit : .celsius
speedUnit = userDefault.integer(forKey: "Speed") == 1 ? .kmph : .mph
distanceUnit = userDefault.integer(forKey: "Distance") == 1 ? .km : .mi
directionUnit = userDefault.integer(forKey: "Direction") == 1 ? .degree : .direction
}
func all(_ completion: (Weather?, Error?) -> Void) {
let location: CLLocation?
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways {
location = locationStorage.location
} else {
let error = WeatherError.notAuthorized("Location service of the weather app is blocked, please turn it on in the setting app")
completion(nil, error)
return
}
guard let currentLocation = location else {
let error = WeatherError.noAvailableLocation("Location is not available")
completion(nil, error)
return
}
let cityLoader = CityLoader()
cityLoader.locationParse(location: currentLocation) {
guard let JSON = $0, let city = City(from: JSON) else { return }
CityManager.sharedManager.currentCity = city
}
}
func all(for city: City, ignoreCache: Bool = false, completion: @escaping (Weather?, Error?) -> Void) {
weatherSource.weather(city: city.name, province: city.province, country: city.country, ignoreCache: ignoreCache) {
switch $0 {
case .success(let JSON):
guard let weather = Weather(with: JSON) else {
completion(nil, WeatherStationError.weatherLoadError)
return
}
if CityManager.sharedManager.isLocal {
self.saveForWidget(weather)
}
completion(weather, nil)
case .failure(let error):
completion(nil, error)
}
}
}
func forecast(_ completion: @escaping ([Forecast], Error?) -> Void) {
let location: CLLocation?
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways {
location = locationStorage.location
} else {
let error = WeatherError.notAuthorized("Location service of the weather app is blocked, please turn it on in the setting app")
completion([], error)
return
}
guard let currentLocation = location else {
let error = WeatherError.noAvailableLocation("Location is not available")
completion([], error)
return
}
weatherSource.forecast(location: currentLocation) {
switch $0 {
case .success(let JSONs):
let forecasts = JSONs.flatMap { Forecast(with: $0) }
if forecasts.count != 0 && CityManager.sharedManager.isLocal {
self.saveForWidget(forecasts.first!)
}
completion(forecasts, nil)
case .failure(let error):
completion([], error)
}
}
}
func forecast(for city: City, completion: @escaping ([Forecast], Error?) -> Void) {
weatherSource.forecast(city: city.name, province: city.province, country: city.country) {
switch $0 {
case .success(let JSONs):
let forecasts = JSONs.flatMap { Forecast(with: $0) }
if forecasts.count != 0 && CityManager.sharedManager.isLocal {
self.saveForWidget(forecasts.first!)
}
completion(forecasts, nil)
case .failure(let error):
completion([], error)
}
}
}
fileprivate func saveForWidget(_ weather: Weather) {
let userDefault = UserDefaults(suiteName: "group.NCGroup")
userDefault?.set(CityManager.sharedManager.currentCity?.name ?? "Local", forKey: "City")
userDefault?.set(weather.temprature, forKey: "Temperature")
userDefault?.set(weather.condition.rawValue, forKey: "Condition")
userDefault?.set(weather.humidity, forKey: "Humidity")
userDefault?.set(weather.condition.iconName, forKey: "Icon")
userDefault?.set(temperatureUnit.description, forKey: "unit")
}
fileprivate func saveForWidget(_ forecast: Forecast) {
let userDefault = UserDefaults(suiteName: "group.NCGroup")
userDefault?.set(forecast.highTemp, forKey: "highTemp")
userDefault?.set(forecast.lowTemp, forKey: "lowTemp")
}
func clearCache() {
weatherSource.clearCache()
}
}
enum WeatherStationError: Error {
case weatherLoadError
}
| 74405eeaf99807a429dd5dad715c7ae1 | 29.904192 | 134 | 0.715559 | false | false | false | false |
AmyKelly56/Assignment3 | refs/heads/master | App/AlbumViewController.swift | mit | 1 | //
// AlbumViewController.swift
// App
//
// Created by Amy Kelly on 01/03/2017.
// Copyright © 2017 Amy Kelly. All rights reserved.
//
import UIKit
class AlbumViewController: UIViewController {
var album: Album?
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var albumCoverImageView: UIImageView!
@IBOutlet weak var descriptionTextView: UITextView!
func updateUI() {
let albumName = "\((album?.coverImageName)!)"
backgroundImageView?.image = UIImage(named: albumName)
albumCoverImageView?.image = UIImage(named: albumName)
let songList = ((album?.songs)! as NSArray).componentsJoined(by: ", ")
descriptionTextView.text = "\((album?.description)!)\n\n Songs: \n\(songList)"
}
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
backgroundImageView?.removeFromSuperview()
}
}
| 68cc4864bc00714b28b1e9eb489af55b | 23.466667 | 86 | 0.619437 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/ViewRelated/QR Login/Coordinators/QRLoginCoordinator.swift | gpl-2.0 | 1 | import UIKit
struct QRLoginCoordinator: QRLoginParentCoordinator {
enum QRLoginOrigin: String {
case menu
case deepLink = "deep_link"
}
let navigationController: UINavigationController
let origin: QRLoginOrigin
init(navigationController: UINavigationController = UINavigationController(), origin: QRLoginOrigin) {
self.navigationController = navigationController
self.origin = origin
configureNavigationController()
}
static func didHandle(url: URL) -> Bool {
guard
let token = QRLoginURLParser(urlString: url.absoluteString).parse(),
let source = UIApplication.shared.leafViewController
else {
return false
}
self.init(origin: .deepLink).showVerifyAuthorization(token: token, from: source)
return true
}
func showCameraScanningView(from source: UIViewController? = nil) {
pushOrPresent(scanningViewController(), from: source)
}
func showVerifyAuthorization(token: QRLoginToken, from source: UIViewController? = nil) {
let controller = QRLoginVerifyAuthorizationViewController()
controller.coordinator = QRLoginVerifyCoordinator(token: token,
view: controller,
parentCoordinator: self)
pushOrPresent(controller, from: source)
}
}
// MARK: - QRLoginParentCoordinator Child Coordinator Interactions
extension QRLoginCoordinator {
func dismiss() {
navigationController.dismiss(animated: true)
}
func didScanToken(_ token: QRLoginToken) {
showVerifyAuthorization(token: token)
}
func scanAgain() {
QRLoginCameraPermissionsHandler().checkCameraPermissions(from: navigationController, origin: origin) {
self.navigationController.setViewControllers([self.scanningViewController()], animated: true)
}
}
func track(_ event: WPAnalyticsEvent) {
self.track(event, properties: nil)
}
func track(_ event: WPAnalyticsEvent, properties: [AnyHashable: Any]? = nil) {
var props: [AnyHashable: Any] = ["origin": origin.rawValue]
guard let properties = properties else {
WPAnalytics.track(event, properties: props)
return
}
props.merge(properties) { (_, new) in new }
WPAnalytics.track(event, properties: props)
}
}
// MARK: - Private
private extension QRLoginCoordinator {
func configureNavigationController() {
navigationController.isNavigationBarHidden = true
navigationController.modalPresentationStyle = .fullScreen
}
func pushOrPresent(_ controller: UIViewController, from source: UIViewController?) {
guard source != nil else {
navigationController.pushViewController(controller, animated: true)
return
}
navigationController.setViewControllers([controller], animated: false)
source?.present(navigationController, animated: true)
}
private func scanningViewController() -> QRLoginScanningViewController {
let controller = QRLoginScanningViewController()
controller.coordinator = QRLoginScanningCoordinator(view: controller, parentCoordinator: self)
return controller
}
}
// MARK: - Presenting the QR Login Flow
extension QRLoginCoordinator {
/// Present the QR login flow starting with the scanning step
static func present(from source: UIViewController, origin: QRLoginOrigin) {
QRLoginCameraPermissionsHandler().checkCameraPermissions(from: source, origin: origin) {
QRLoginCoordinator(origin: origin).showCameraScanningView(from: source)
}
}
/// Display QR validation flow with a specific code, skipping the scanning step
/// and going to the validation flow
static func present(token: QRLoginToken, from source: UIViewController, origin: QRLoginOrigin) {
QRLoginCoordinator(origin: origin).showVerifyAuthorization(token: token, from: source)
}
}
| 5fcff0203d17765af24892e0f200299f | 34.153846 | 110 | 0.676392 | false | false | false | false |
spacedrabbit/Swift-CatGram | refs/heads/master | The CatTasticals/CatViewerTableViewCell.swift | mit | 1 | //
// CatViewerTableViewCell.swift
// The CatTasticals
//
// Created by Louis Tur on 5/11/15.
// Copyright (c) 2015 Louis Tur. All rights reserved.
//
import UIKit
class CatViewerTableViewCell: PFTableViewCell {
@IBOutlet weak var catImageView:UIImageView?
@IBOutlet weak var catNameLabel:UILabel?
@IBOutlet weak var catVotesLabel:UILabel?
@IBOutlet weak var catCreditLabel:UILabel?
@IBOutlet weak var catPawIcon:UIImageView?
var parseObject:PFObject?
override func awakeFromNib() {
let gesture = UITapGestureRecognizer(target: self, action: Selector("onDoubleTap:"))
gesture.numberOfTapsRequired = 2
contentView.addGestureRecognizer(gesture)
catPawIcon?.hidden = true
super.awakeFromNib()
// Initialization code
}
func onDoubleTap(sender: AnyObject){
if (parseObject != nil){
if var votes:Int? = parseObject!.objectForKey("votes") as? Int{
votes!++
parseObject!.setObject(votes!, forKey: "votes")
parseObject!.saveInBackground()
catVotesLabel?.text = "\(votes!) votes"
}
}
catPawIcon?.hidden = false
catPawIcon?.alpha = 1.0
UIView.animateKeyframesWithDuration(1.0, delay: 1.0, options: nil, animations: {
self.catPawIcon?.alpha = 0
}, completion: {
(value:Bool) in
self.catPawIcon?.hidden = true
})
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 1341883a89395fb089898966d588c843 | 27.253968 | 92 | 0.58764 | false | false | false | false |
alessiobrozzi/firefox-ios | refs/heads/master | XCUITests/ActivityStreamTest.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
class ActivityStreamTest: BaseTestCase {
override func setUp() {
super.setUp()
dismissFirstRunUI()
}
override func tearDown() {
super.tearDown()
}
func testDefaultSites() {
let app = XCUIApplication()
let topSites = app.tables["Top sites"].cells["TopSitesCell"]
let numberOfTopSites = topSites.children(matching: .other).matching(identifier: "TopSite").count
XCTAssertEqual(numberOfTopSites, 5, "There should be a total of 5 default Top Sites.")
}
func testTopSitesAdd() {
let app = XCUIApplication()
let topSites = app.tables["Top sites"].cells["TopSitesCell"]
let numberOfTopSites = topSites.children(matching: .other).matching(identifier: "TopSite").count
loadWebPage("http://example.com")
app.buttons["TabToolbar.backButton"].tap()
let sitesAfter = topSites.children(matching: .other).matching(identifier: "TopSite").count
XCTAssertTrue(sitesAfter == numberOfTopSites + 1, "A new site should have been added to the topSites")
}
func testTopSitesRemove() {
let app = XCUIApplication()
let topSites = app.tables["Top sites"].cells["TopSitesCell"]
let numberOfTopSites = topSites.children(matching: .other).matching(identifier: "TopSite").count
loadWebPage("http://example.com")
app.buttons["TabToolbar.backButton"].tap()
let sitesAfter = topSites.children(matching: .other).matching(identifier: "TopSite").count
XCTAssertTrue(sitesAfter == numberOfTopSites + 1, "A new site should have been added to the topSites")
app.tables["Top sites"].otherElements["example"].press(forDuration: 1) //example is the name of the domain. (example.com)
app.tables["Context Menu"].cells["Remove"].tap()
let sitesAfterDelete = topSites.children(matching: .other).matching(identifier: "TopSite").count
XCTAssertTrue(sitesAfterDelete == numberOfTopSites, "A site should have been deleted to the topSites")
}
func testTopSitesOpenInNewTab() {
let app = XCUIApplication()
loadWebPage("http://example.com")
app.buttons["TabToolbar.backButton"].tap()
app.tables["Top sites"].otherElements["example"].press(forDuration: 1)
app.tables["Context Menu"].cells["Open in New Tab"].tap()
XCTAssert(app.tables["Top sites"].exists)
XCTAssertFalse(app.staticTexts["Example Domain"].exists)
app.buttons["URLBarView.tabsButton"].tap()
app.cells["Example Domain"].tap()
XCTAssertFalse(app.tables["Top sites"].exists)
XCTAssert(app.staticTexts["Example Domain"].exists)
}
func testTopSitesOpenInNewPrivateTab() {
let app = XCUIApplication()
loadWebPage("http://example.com")
app.buttons["TabToolbar.backButton"].tap()
app.tables["Top sites"].otherElements["example"].press(forDuration: 1)
app.tables["Context Menu"].cells["Open in New Private Tab"].tap()
XCTAssert(app.tables["Top sites"].exists)
XCTAssertFalse(app.staticTexts["example"].exists)
app.buttons["URLBarView.tabsButton"].tap()
app.buttons["TabTrayController.maskButton"].tap()
app.cells["Example Domain"].tap()
XCTAssertFalse(app.tables["Top sites"].exists)
XCTAssert(app.staticTexts["Example Domain"].exists)
}
func testActivityStreamPages() {
let app = XCUIApplication()
let topSitesTable = app.tables["Top sites"]
let pagecontrolButton = topSitesTable.buttons["pageControl"]
XCTAssertFalse(pagecontrolButton.exists, "The Page Control button must not exist. Only 5 elements should be on the page")
loadWebPage("http://example.com")
app.buttons["TabToolbar.backButton"].tap()
loadWebPage("http://mozilla.org")
app.buttons["TabToolbar.backButton"].tap()
XCTAssert(pagecontrolButton.exists, "The Page Control button must exist if more than 6 elements are displayed.")
pagecontrolButton.tap()
pagecontrolButton.tap()
// Sleep so the pageControl animation finishes.
sleep(2)
app.tables["Top sites"].otherElements["example"].press(forDuration: 1)
app.tables["Context Menu"].cells["Remove"].tap()
XCTAssertFalse(pagecontrolButton.exists, "The Page Control button should disappear after an item is deleted.")
}
func testContextMenuInLandscape() {
XCUIDevice.shared().orientation = .landscapeLeft
let app = XCUIApplication()
loadWebPage("http://example.com")
app.buttons["URLBarView.backButton"].tap()
app.tables["Top sites"].otherElements["example"].press(forDuration: 1)
let contextMenuHeight = app.tables["Context Menu"].frame.size.height
let parentViewHeight = app.otherElements["Action Overlay"].frame.size.height
XCTAssertLessThanOrEqual(contextMenuHeight, parentViewHeight)
}
}
| 8ed45ae8f1a0ebc8a3543b79b5e96801 | 38.789474 | 129 | 0.660998 | false | true | false | false |
NeAres/1706C.C. | refs/heads/master | PDFMakers/PDFMakers/Customize Theme.swift | mit | 1 | //
// Customize Theme.swift
// PDFMakers
//
// Created by Arendelle on 2017/7/19.
// Copyright © 2017年 AdTech. All rights reserved.
//
import UIKit
func fitFileRead(fileDir:String, theme:Int) {
let themeImage = Bundle.main.path(forResource: "\(theme)", ofType: "png")
let image = UIImage(contentsOfFile: fileDir)!
if Double((image.cgImage?.width)!)/Double((image.cgImage?.height)!) > 2480.0/3508.0 {
let croppedWidth = Double((image.cgImage?.height)!) / 3508.0 * 2480.0
var themedImage = UIImage(contentsOfFile: themeImage!)
UIGraphicsBeginImageContext(CGSize(width: 2480, height: 3508))
var croppedCGImage = image.cgImage?.cropping(to: CGRect(x: (Double((image.cgImage?.width)!) - croppedWidth) / 2.0, y: 0, width: croppedWidth, height: Double((image.cgImage?.height)!)))
var croppedUIImage = UIImage(cgImage: croppedCGImage!)
var blackMask = #imageLiteral(resourceName: "ZERO.png")
croppedUIImage.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
blackMask.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
themedImage?.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
var finalDerivedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var imageData = UIImageJPEGRepresentation(finalDerivedImage!, 1.0)
do {
try imageData?.write(to: URL.init(fileURLWithPath: fileDir))
} catch {
print(error)
}
imageData = nil
finalDerivedImage = nil
croppedCGImage = nil
themedImage = nil
} else {
let croppedHeight = Double((image.cgImage?.width)!) / 2480.0 * 3508.0
var themedImage = UIImage(contentsOfFile: themeImage!)
UIGraphicsBeginImageContext(CGSize(width: 2480, height: 3508))
var croppedCGImage = image.cgImage?.cropping(to: CGRect(x: 0, y: (Double((image.cgImage?.height)!) - croppedHeight) / 2.0, width: Double((image.cgImage?.width)!), height: croppedHeight))
var croppedUIImage = UIImage(cgImage: croppedCGImage!)
var blackMask = #imageLiteral(resourceName: "ZERO.png")
croppedUIImage.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
blackMask.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
themedImage?.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
var finalDerivedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var imageData = UIImageJPEGRepresentation(finalDerivedImage!, 1.0)
do {
try imageData?.write(to: URL.init(fileURLWithPath: fileDir))
} catch {
print(error)
}
imageData = nil
finalDerivedImage = nil
croppedCGImage = nil
themedImage = nil
}
}
func enlongFile(fileInString:String) {
let image = UIImage(contentsOfFile: fileInString)
var image0 = UIImage()
if (image?.cgImage?.width)! > (image?.cgImage?.height)! {
image0 = UIImage(ciImage: (image?.ciImage?.applyingOrientation(Int32(UIImageOrientation.right.rawValue)))!)
}
var imageData = UIImageJPEGRepresentation(image0, 1.0)
do {
try imageData?.write(to: URL(fileURLWithPath: fileInString))
} catch {
print(error)
}
imageData = nil
}
func enlongImage(image:UIImage) -> UIImage {
if (image.cgImage?.width)! > (image.cgImage?.height)! {
return UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: UIImageOrientation.right)
} else {
return image
}
}
func blurImage(cgImage:CGImage) -> UIImage {
return UIImage(cgImage: cgImage)
}
class CustomThemeManager {
func fitDirRead(fileDir:String) { //one for all, read every image, random select font, synth.
var allImages = [String]()
do {
try allImages = FileManager.default.contentsOfDirectory(atPath: fileDir)
} catch {
print(error)
}
let theme = arc4random()%10
let themeImage = Bundle.main.path(forResource: "\(theme)", ofType: "png")
for imageSingle in allImages {
if imageSingle == ".DS_Store" {
continue
}
let image = UIImage(contentsOfFile: (fileDir as NSString).appendingPathComponent(imageSingle))!
if Double((image.cgImage?.width)!)/Double((image.cgImage?.height)!) > 2480.0/3508.0 {
let croppedWidth = Double((image.cgImage?.height)!) / 3508.0 * 2480.0
UIGraphicsBeginImageContext(CGSize(width: 2480, height: 3508))
let croppedCGImage = image.cgImage?.cropping(to: CGRect(x: (Double((image.cgImage?.width)!) - croppedWidth) / 2.0, y: 0, width: croppedWidth, height: Double((image.cgImage?.height)!)))
blurImage(cgImage: croppedCGImage!).draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
UIImage(contentsOfFile: themeImage!)?.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
let finalDerivedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print("x")
let imageData = UIImageJPEGRepresentation(finalDerivedImage!, 1.0)
do {
try imageData?.write(to: URL.init(fileURLWithPath: (fileDir as NSString).appendingPathComponent(imageSingle)))
} catch {
print(error)
}
} else {
let croppedHeight = Double((image.cgImage?.width)!) / 2480.0 * 3508.0
UIGraphicsBeginImageContext(CGSize(width: 2480, height: 3508))
let croppedCGImage = image.cgImage?.cropping(to: CGRect(x: 0, y: (Double((image.cgImage?.height)!) - croppedHeight) / 2.0, width: Double((image.cgImage?.width)!), height: croppedHeight))
blurImage(cgImage: croppedCGImage!).draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
UIImage(ciImage: CIImage(color: CIColor(red: 0, green: 0, blue: 0, alpha: 0.4))).draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
UIImage(contentsOfFile: themeImage!)?.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
let finalDerivedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageData = UIImageJPEGRepresentation(finalDerivedImage!, 1.0)
do {
try imageData?.write(to: URL.init(fileURLWithPath: (fileDir as NSString).appendingPathComponent(imageSingle)))
} catch {
print(error)
}
}
}
}
}
| a61886082922602d4501363d2be26471 | 47.746377 | 202 | 0.621674 | false | false | false | false |
WaterReporter/WaterReporter-iOS | refs/heads/master | WaterReporter/WaterReporter/NewReportGroupsTableViewController.swift | agpl-3.0 | 1 | //
// NewReportGroupsTableViewController.swift
// Water-Reporter
//
// Created by Viable Industries on 11/15/16.
// Copyright © 2016 Viable Industries, L.L.C. All rights reserved.
//
import Alamofire
import Foundation
import Kingfisher
import SwiftyJSON
import UIKit
protocol NewReportGroupSelectorDelegate {
func sendGroups(groups: [String])
}
class NewReportGroupsTableViewController: UITableViewController, UINavigationControllerDelegate {
//
// MARK: @IBOutlets
//
@IBOutlet var viewActivityIndicator: UIView!
@IBAction func refreshTableView(refreshControl: UIRefreshControl) {
// If the view is not already refreshing, send a
// request to load all gorups
if (self.refreshControl?.refreshing == false) {
// Clear all groups currently listed
self.groups = []
// Attempt to load all groups again
self.attemptLoadUserGroups()
}
}
@IBAction func selectGroup(sender: UISwitch) {
if sender.on {
let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])"
self.tempGroups.append(_organization_id_number)
print("addGroup::finished::tempGroups \(self.tempGroups)")
} else {
let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])"
self.tempGroups = self.tempGroups.filter() {$0 != _organization_id_number}
print("removeGroup::finished::tempGroups \(self.tempGroups)")
}
}
@IBAction func dismissGroupSelector(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func saveGroupSelections(sender: UIBarButtonItem) {
if let del = delegate {
del.sendGroups(self.tempGroups)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
//
// MARK: Variables
//
var loadingView: UIView!
var groups: JSON?
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
var delegate: NewReportGroupSelectorDelegate?
var tempGroups: [String]!
//
// MARK: Overrides
//
override func viewDidLoad() {
super.viewDidLoad()
// Show loading symbol while Groups load
self.status("loading")
// Load all of the groups on WaterReporter.org
self.attemptLoadUserGroups()
print("self.tempGroups \(self.tempGroups)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//
// MARK: Statuses
//
func status(statusType: String) {
switch (statusType) {
case "loading":
// Create a view that covers the entire screen
self.loadingView = self.viewActivityIndicator
self.loadingView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
self.view.addSubview(self.loadingView)
self.view.bringSubviewToFront(self.loadingView)
// Make sure that the Done button is disabled
self.navigationItem.rightBarButtonItem?.enabled = false
self.navigationItem.leftBarButtonItem?.enabled = false
// Hide table view separators
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
break
case "complete":
// Hide the loading view
self.loadingView.removeFromSuperview()
// Hide table view separators
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
// Make sure that the Done button is disabled
self.navigationItem.rightBarButtonItem?.enabled = true
self.navigationItem.leftBarButtonItem?.enabled = true
break
case "saving":
print("Saving groups page and dismiss modal")
break
case "doneLoadingWithError":
// Hide the loading view
self.loadingView.removeFromSuperview()
default:
break
}
}
//
// MARK: Table Overrides
//
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reportGroupTableViewCell", forIndexPath: indexPath) as! ReportGroupTableViewCell
//
// Assign the organization logo to the UIImageView
//
cell.imageViewGroupLogo.tag = indexPath.row
var organizationImageUrl:NSURL!
if let thisOrganizationImageUrl: String = self.groups?["features"][indexPath.row]["properties"]["organization"]["properties"]["picture"].string {
organizationImageUrl = NSURL(string: thisOrganizationImageUrl)
}
cell.imageViewGroupLogo.kf_indicatorType = .Activity
cell.imageViewGroupLogo.kf_showIndicatorWhenLoading = true
cell.imageViewGroupLogo.kf_setImageWithURL(organizationImageUrl, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: {
(image, error, cacheType, imageUrl) in
cell.imageViewGroupLogo.image = image
cell.imageViewGroupLogo.layer.cornerRadius = cell.imageViewGroupLogo.frame.size.width / 2
cell.imageViewGroupLogo.clipsToBounds = true
})
//
// Assign the organization name to the UILabel
//
if let thisOrganizationName: String = self.groups?["features"][indexPath.row]["properties"]["organization"]["properties"]["name"].string {
cell.labelGroupName.text = thisOrganizationName
}
// Assign existing groups to the group field
cell.switchSelectGroup.tag = indexPath.row
if let _organization_id_number = self.groups?["features"][indexPath.row]["properties"]["organization_id"] {
if self.tempGroups.contains("\(_organization_id_number)") {
cell.switchSelectGroup.on = true
}
else {
cell.switchSelectGroup.on = false
}
}
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.groups == nil {
return 1
}
return (self.groups?["features"].count)!
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 72.0
}
//
// MARK: HTTP Request/Response Functionality
//
func buildRequestHeaders() -> [String: String] {
let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken")
return [
"Authorization": "Bearer " + (accessToken! as! String)
]
}
func attemptLoadUserGroups() {
// Set headers
let _headers = self.buildRequestHeaders()
if let userId = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") as? NSNumber {
let GET_GROUPS_ENDPOINT = Endpoints.GET_USER_PROFILE + "\(userId)" + "/groups"
Alamofire.request(.GET, GET_GROUPS_ENDPOINT, headers: _headers, encoding: .JSON).responseJSON { response in
print("response.result \(response.result)")
switch response.result {
case .Success(let value):
print("Request Success: \(value)")
// Assign response to groups variable
self.groups = JSON(value)
// Tell the refresh control to stop spinning
self.refreshControl?.endRefreshing()
// Set status to complete
self.status("complete")
// Refresh the data in the table so the newest items appear
self.tableView.reloadData()
break
case .Failure(let error):
print("Request Failure: \(error)")
// Stop showing the loading indicator
self.status("doneLoadingWithError")
break
}
}
} else {
self.attemptRetrieveUserID()
}
}
func attemptRetrieveUserID() {
// Set headers
let _headers = self.buildRequestHeaders()
Alamofire.request(.GET, Endpoints.GET_USER_ME, headers: _headers, encoding: .JSON)
.responseJSON { response in
switch response.result {
case .Success(let value):
let json = JSON(value)
if let data: AnyObject = json.rawValue {
NSUserDefaults.standardUserDefaults().setValue(data["id"], forKeyPath: "currentUserAccountUID")
self.attemptLoadUserGroups()
}
case .Failure(let error):
print(error)
}
}
}
}
| dfc9186bfa8a018c334e607864166b9a | 32.445946 | 154 | 0.560808 | false | false | false | false |
esttorhe/Moya | refs/heads/master | Source/Moya.swift | mit | 2 | import Foundation
import Result
/// Closure to be executed when a request has completed.
public typealias Completion = (result: Result<Moya.Response, Moya.Error>) -> ()
/// Represents an HTTP method.
public enum Method: String {
case GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH, TRACE, CONNECT
}
public enum StubBehavior {
case Never
case Immediate
case Delayed(seconds: NSTimeInterval)
}
/// Protocol to define the base URL, path, method, parameters and sample data for a target.
public protocol TargetType {
var baseURL: NSURL { get }
var path: String { get }
var method: Moya.Method { get }
var parameters: [String: AnyObject]? { get }
var sampleData: NSData { get }
}
public enum StructTarget: TargetType {
case Struct(TargetType)
public init(_ target: TargetType) {
self = StructTarget.Struct(target)
}
public var path: String {
return target.path
}
public var baseURL: NSURL {
return target.baseURL
}
public var method: Moya.Method {
return target.method
}
public var parameters: [String: AnyObject]? {
return target.parameters
}
public var sampleData: NSData {
return target.sampleData
}
public var target: TargetType {
switch self {
case .Struct(let t): return t
}
}
}
/// Protocol to define the opaque type returned from a request
public protocol Cancellable {
func cancel()
}
/// Request provider class. Requests should be made through this class only.
public class MoyaProvider<Target: TargetType> {
/// Closure that defines the endpoints for the provider.
public typealias EndpointClosure = Target -> Endpoint<Target>
/// Closure that decides if and what request should be performed
public typealias RequestResultClosure = Result<NSURLRequest, Moya.Error> -> Void
/// Closure that resolves an Endpoint into an RequestResult.
public typealias RequestClosure = (Endpoint<Target>, RequestResultClosure) -> Void
/// Closure that decides if/how a request should be stubbed.
public typealias StubClosure = Target -> Moya.StubBehavior
public let endpointClosure: EndpointClosure
public let requestClosure: RequestClosure
public let stubClosure: StubClosure
public let manager: Manager
/// A list of plugins
/// e.g. for logging, network activity indicator or credentials
public let plugins: [PluginType]
public let trackInflights:Bool
public private(set) var inflightRequests = Dictionary<Endpoint<Target>, [Moya.Completion]>()
/// Initializes a provider.
public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = MoyaProvider<Target>.DefaultAlamofireManager(),
plugins: [PluginType] = [],
trackInflights:Bool = false) {
self.endpointClosure = endpointClosure
self.requestClosure = requestClosure
self.stubClosure = stubClosure
self.manager = manager
self.plugins = plugins
self.trackInflights = trackInflights
}
/// Returns an Endpoint based on the token, method, and parameters by invoking the endpointsClosure.
public func endpoint(token: Target) -> Endpoint<Target> {
return endpointClosure(token)
}
/// Designated request-making method with queue option. Returns a Cancellable token to cancel the request later.
public func request(target: Target, queue:dispatch_queue_t?, completion: Moya.Completion) -> Cancellable {
let endpoint = self.endpoint(target)
let stubBehavior = self.stubClosure(target)
var cancellableToken = CancellableWrapper()
if trackInflights {
objc_sync_enter(self)
var inflightCompletionBlocks = self.inflightRequests[endpoint]
inflightCompletionBlocks?.append(completion)
self.inflightRequests[endpoint] = inflightCompletionBlocks
objc_sync_exit(self)
if inflightCompletionBlocks != nil {
return cancellableToken
} else {
objc_sync_enter(self)
self.inflightRequests[endpoint] = [completion]
objc_sync_exit(self)
}
}
let performNetworking = { (requestResult: Result<NSURLRequest, Moya.Error>) in
if cancellableToken.isCancelled { return }
var request: NSURLRequest!
switch requestResult {
case .Success(let urlRequest):
request = urlRequest
case .Failure(let error):
completion(result: .Failure(error))
return
}
switch stubBehavior {
case .Never:
cancellableToken.innerCancellable = self.sendRequest(target, request: request, queue: queue, completion: { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result: result) })
objc_sync_enter(self)
self.inflightRequests.removeValueForKey(endpoint)
objc_sync_exit(self)
} else {
completion(result: result)
}
})
default:
cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result: result) })
objc_sync_enter(self)
self.inflightRequests.removeValueForKey(endpoint)
objc_sync_exit(self)
} else {
completion(result: result)
}
}, endpoint: endpoint, stubBehavior: stubBehavior)
}
}
requestClosure(endpoint, performNetworking)
return cancellableToken
}
/// Designated request-making method. Returns a Cancellable token to cancel the request later.
public func request(target: Target, completion: Moya.Completion) -> Cancellable {
return self.request(target, queue:nil, completion:completion)
}
/// When overriding this method, take care to `notifyPluginsOfImpendingStub` and to perform the stub using the `createStubFunction` method.
/// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override.
internal func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken {
let cancellableToken = CancellableToken { }
notifyPluginsOfImpendingStub(request, target: target)
let plugins = self.plugins
let stub: () -> () = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins)
switch stubBehavior {
case .Immediate:
stub()
case .Delayed(let delay):
let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC))
let killTime = dispatch_time(DISPATCH_TIME_NOW, killTimeOffset)
dispatch_after(killTime, dispatch_get_main_queue()) {
stub()
}
case .Never:
fatalError("Method called to stub request when stubbing is disabled.")
}
return cancellableToken
}
}
/// Mark: Defaults
public extension MoyaProvider {
// These functions are default mappings to MoyaProvider's properties: endpoints, requests, manager, etc.
public final class func DefaultEndpointMapping(target: Target) -> Endpoint<Target> {
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
public final class func DefaultRequestMapping(endpoint: Endpoint<Target>, closure: RequestResultClosure) {
return closure(.Success(endpoint.urlRequest))
}
public final class func DefaultAlamofireManager() -> Manager {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
let manager = Manager(configuration: configuration)
manager.startRequestsImmediately = false
return manager
}
}
/// Mark: Stubbing
public extension MoyaProvider {
// Swift won't let us put the StubBehavior enum inside the provider class, so we'll
// at least add some class functions to allow easy access to common stubbing closures.
public final class func NeverStub(_: Target) -> Moya.StubBehavior {
return .Never
}
public final class func ImmediatelyStub(_: Target) -> Moya.StubBehavior {
return .Immediate
}
public final class func DelayedStub(seconds: NSTimeInterval) -> (Target) -> Moya.StubBehavior {
return { _ in return .Delayed(seconds: seconds) }
}
}
internal extension MoyaProvider {
func sendRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, completion: Moya.Completion) -> CancellableToken {
let alamoRequest = manager.request(request)
let plugins = self.plugins
// Give plugins the chance to alter the outgoing request
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
// Perform the actual request
alamoRequest.response(queue: queue) { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in
let result = convertResponseToResult(response, data: data, error: error)
// Inform all plugins about the response
plugins.forEach { $0.didReceiveResponse(result, target: target) }
completion(result: result)
}
alamoRequest.resume()
return CancellableToken(request: alamoRequest)
}
/// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters.
internal final func createStubFunction(token: CancellableToken, forTarget target: Target, withCompletion completion: Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType]) -> (() -> ()) {
return {
if (token.canceled) {
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
return
}
switch endpoint.sampleResponseClosure() {
case .NetworkResponse(let statusCode, let data):
let response = Moya.Response(statusCode: statusCode, data: data, response: nil)
plugins.forEach { $0.didReceiveResponse(.Success(response), target: target) }
completion(result: .Success(response))
case .NetworkError(let error):
let error = Moya.Error.Underlying(error)
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
}
}
}
/// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`.
internal final func notifyPluginsOfImpendingStub(request: NSURLRequest, target: Target) {
let alamoRequest = manager.request(request)
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
}
}
public func convertResponseToResult(response: NSHTTPURLResponse?, data: NSData?, error: NSError?) ->
Result<Moya.Response, Moya.Error> {
switch (response, data, error) {
case let (.Some(response), .Some(data), .None):
let response = Moya.Response(statusCode: response.statusCode, data: data, response: response)
return .Success(response)
case let (_, _, .Some(error)):
let error = Moya.Error.Underlying(error)
return .Failure(error)
default:
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil))
return .Failure(error)
}
}
internal struct CancellableWrapper: Cancellable {
internal var innerCancellable: CancellableToken? = nil
private var isCancelled = false
internal func cancel() {
innerCancellable?.cancel()
}
}
| 39134626487667127049360060e5adf4 | 38.488024 | 204 | 0.637728 | false | false | false | false |
taoguan/firefox-ios | refs/heads/master | Client/Frontend/Browser/TabTrayController.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(4.0)
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1)
static let TextBoxHeight = CGFloat(32.0)
static let FaviconSize = CGFloat(18.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let TabTitleTextFont = UIConstants.DefaultSmallFontBold
static let CloseButtonSize = CGFloat(18.0)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(10)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
// Moved from UIConstants temporarily until animation code is merged
static var StatusBarHeight: CGFloat {
if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact {
return 0
}
return 20
}
}
struct LightTabCellUX {
static let TabTitleTextColor = UIColor.blackColor()
}
struct DarkTabCellUX {
static let TabTitleTextColor = UIColor.whiteColor()
}
protocol TabCellDelegate: class {
func tabCellDidClose(cell: TabCell)
}
class TabCell: UICollectionViewCell {
enum Style {
case Light
case Dark
}
static let Identifier = "TabCellIdentifier"
var style: Style = .Light {
didSet {
applyStyle(style)
}
}
let backgroundHolder = UIView()
let background = UIImageViewAligned()
let titleText: UILabel
let innerStroke: InnerStrokedView
let favicon: UIImageView = UIImageView()
let closeButton: UIButton
var title: UIVisualEffectView!
var animator: SwipeAnimator!
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
self.backgroundHolder.backgroundColor = UIColor.whiteColor()
self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
self.backgroundHolder.clipsToBounds = true
self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
self.background.contentMode = UIViewContentMode.ScaleAspectFill
self.background.clipsToBounds = true
self.background.userInteractionEnabled = false
self.background.alignLeft = true
self.background.alignTop = true
self.favicon.backgroundColor = UIColor.clearColor()
self.favicon.layer.cornerRadius = 2.0
self.favicon.layer.masksToBounds = true
self.titleText = UILabel()
self.titleText.textAlignment = NSTextAlignment.Left
self.titleText.userInteractionEnabled = false
self.titleText.numberOfLines = 1
self.titleText.font = TabTrayControllerUX.TabTitleTextFont
self.closeButton = UIButton()
self.closeButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal)
self.closeButton.imageEdgeInsets = UIEdgeInsetsMake(TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset)
self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame)
self.innerStroke.layer.backgroundColor = UIColor.clearColor().CGColor
super.init(frame: frame)
self.opaque = true
self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self)
self.closeButton.addTarget(self.animator, action: "SELcloseWithoutGesture", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(backgroundHolder)
backgroundHolder.addSubview(self.background)
backgroundHolder.addSubview(innerStroke)
// Default style is light
applyStyle(style)
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: "SELcloseWithoutGesture")
]
}
private func applyStyle(style: Style) {
self.title?.removeFromSuperview()
let title: UIVisualEffectView
switch style {
case .Light:
title = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight))
self.titleText.textColor = LightTabCellUX.TabTitleTextColor
case .Dark:
title = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
self.titleText.textColor = DarkTabCellUX.TabTitleTextColor
}
titleText.backgroundColor = UIColor.clearColor()
title.layer.shadowColor = UIColor.blackColor().CGColor
title.layer.shadowOpacity = 0.2
title.layer.shadowOffset = CGSize(width: 0, height: 0.5)
title.layer.shadowRadius = 0
title.addSubview(self.closeButton)
title.addSubview(self.titleText)
title.addSubview(self.favicon)
backgroundHolder.addSubview(title)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.width
let h = frame.height
backgroundHolder.frame = CGRect(x: margin,
y: margin,
width: w,
height: h)
background.frame = CGRect(origin: CGPointMake(0, 0), size: backgroundHolder.frame.size)
title.frame = CGRect(x: 0,
y: 0,
width: backgroundHolder.frame.width,
height: TabTrayControllerUX.TextBoxHeight)
favicon.frame = CGRect(x: 6,
y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2,
width: TabTrayControllerUX.FaviconSize,
height: TabTrayControllerUX.FaviconSize)
let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6
titleText.frame = CGRect(x: titleTextLeft,
y: 0,
width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2,
height: title.frame.height)
innerStroke.frame = background.frame
closeButton.snp_makeConstraints { make in
make.size.equalTo(title.snp_height)
make.trailing.centerY.equalTo(title)
}
let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0
titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top))
}
override func prepareForReuse() {
// Reset any close animations.
backgroundHolder.transform = CGAffineTransformIdentity
backgroundHolder.alpha = 1
}
override func accessibilityScroll(direction: UIAccessibilityScrollDirection) -> Bool {
var right: Bool
switch direction {
case .Left:
right = false
case .Right:
right = true
default:
return false
}
animator.close(right: right)
return true
}
}
@available(iOS 9, *)
struct PrivateModeStrings {
static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode")
static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode")
static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value")
static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value")
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
var collectionView: UICollectionView!
var navBar: UIView!
var addTabButton: UIButton!
var settingsButton: UIButton!
var collectionViewTransitionSnapshot: UIView?
private var privateMode: Bool = false {
didSet {
if #available(iOS 9, *) {
togglePrivateMode.selected = privateMode
togglePrivateMode.accessibilityValue = privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff
emptyPrivateTabsView.hidden = !(privateMode && tabManager.privateTabs.count == 0)
tabDataSource.tabs = tabsToDisplay
collectionView.reloadData()
}
}
}
private var tabsToDisplay: [Browser] {
return self.privateMode ? tabManager.privateTabs : tabManager.normalTabs
}
@available(iOS 9, *)
lazy var togglePrivateMode: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "smallPrivateMask"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "smallPrivateMaskSelected"), forState: UIControlState.Selected)
button.addTarget(self, action: "SELdidTogglePrivateMode", forControlEvents: .TouchUpInside)
button.accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel
button.accessibilityHint = PrivateModeStrings.toggleAccessibilityHint
button.accessibilityValue = self.privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff
return button
}()
@available(iOS 9, *)
private lazy var emptyPrivateTabsView: EmptyPrivateTabsView = {
return EmptyPrivateTabsView()
}()
private lazy var tabDataSource: TabManagerDataSource = {
return TabManagerDataSource(tabs: self.tabsToDisplay, cellDelegate: self)
}()
private lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection)
delegate.tabSelectionDelegate = self
return delegate
}()
private var removedTabIndexPath: NSIndexPath?
init(tabManager: TabManager, profile: Profile) {
self.tabManager = tabManager
self.profile = profile
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
tabManager.addDelegate(self)
navBar = UIView()
navBar.backgroundColor = TabTrayControllerUX.BackgroundColor
addTabButton = UIButton()
addTabButton.setImage(UIImage(named: "add"), forState: .Normal)
addTabButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: .TouchUpInside)
addTabButton.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
settingsButton = UIButton()
settingsButton.setImage(UIImage(named: "settings"), forState: .Normal)
settingsButton.addTarget(self, action: "SELdidClickSettingsItem", forControlEvents: .TouchUpInside)
settingsButton.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.")
let flowLayout = TabTrayCollectionViewLayout()
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
collectionView.dataSource = tabDataSource
collectionView.delegate = tabLayoutDelegate
collectionView.registerClass(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor
view.addSubview(collectionView)
view.addSubview(navBar)
view.addSubview(addTabButton)
view.addSubview(settingsButton)
makeConstraints()
if #available(iOS 9, *) {
view.addSubview(togglePrivateMode)
togglePrivateMode.snp_makeConstraints { make in
make.right.equalTo(addTabButton.snp_left).offset(-10)
make.size.equalTo(UIConstants.ToolbarHeight)
make.centerY.equalTo(self.navBar)
}
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.hidden = !(privateMode && tabManager.privateTabs.count == 0)
emptyPrivateTabsView.snp_makeConstraints { make in
make.edges.equalTo(self.view)
}
if let tab = tabManager.selectedTab where tab.isPrivate {
privateMode = true
}
}
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
collectionView.collectionViewLayout.invalidateLayout()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
private func makeConstraints() {
let viewBindings: [String: AnyObject] = [
"topLayoutGuide" : topLayoutGuide,
"navBar" : navBar
]
let topConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[topLayoutGuide][navBar]", options: [], metrics: nil, views: viewBindings)
view.addConstraints(topConstraints)
navBar.snp_makeConstraints { make in
make.height.equalTo(UIConstants.ToolbarHeight)
make.left.right.equalTo(self.view)
}
addTabButton.snp_makeConstraints { make in
make.trailing.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
settingsButton.snp_makeConstraints { make in
make.leading.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp_makeConstraints { make in
make.top.equalTo(navBar.snp_bottom)
make.left.right.bottom.equalTo(self.view)
}
}
// MARK: Selectors
func SELdidClickDone() {
presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
}
func SELdidClickSettingsItem() {
let settingsTableViewController = SettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet
presentViewController(controller, animated: true, completion: nil)
}
func SELdidClickAddTab() {
if #available(iOS 9, *) {
if privateMode {
emptyPrivateTabsView.hidden = true
}
}
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
var tab: Browser
if #available(iOS 9, *) {
tab = self.tabManager.addTab(isPrivate: self.privateMode)
} else {
tab = self.tabManager.addTab()
}
self.tabManager.selectTab(tab)
}, completion: { finished in
if finished {
self.navigationController?.popViewControllerAnimated(true)
}
})
}
@available(iOS 9, *)
func SELdidTogglePrivateMode() {
privateMode = !privateMode
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
self.navigationController?.popViewControllerAnimated(true)
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(modalViewController: UIViewController, animated: Bool) {
dismissViewControllerAnimated(animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) {
}
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) {
}
func tabManager(tabManager: TabManager, didAddTab tab: Browser, restoring: Bool) {
// Get the index of the added tab from it's set (private or normal)
guard let index = tabsToDisplay.indexOf(tab) else { return }
tabDataSource.tabs.append(tab)
self.collectionView.performBatchUpdates({ _ in
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tab)
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
self.navigationController?.popViewControllerAnimated(true)
}
}
})
}
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser) {
if let removedIndex = removedTabIndexPath {
tabDataSource.tabs.removeAtIndex(removedIndex.item)
removedTabIndexPath = nil
self.collectionView.deleteItemsAtIndexPaths([removedIndex])
// Workaround: On iOS 8.* devices, cells don't get reloaded during the deletion but after the
// animation has finished which causes cells that animate from above to suddenly 'appear'. This
// is fixed on iOS 9 but for iOS 8 we force a reload on non-visible cells during the animation.
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_8_3) {
let visibleCount = collectionView.indexPathsForVisibleItems().count
var offscreenIndexPaths = [NSIndexPath]()
for i in 0..<(tabsToDisplay.count - visibleCount) {
offscreenIndexPaths.append(NSIndexPath(forItem: i, inSection: 0))
}
self.collectionView.reloadItemsAtIndexPaths(offscreenIndexPaths)
}
if #available(iOS 9, *) {
if privateMode && tabsToDisplay.count == 0 {
emptyPrivateTabsView.hidden = false
}
}
}
}
func tabManagerDidAddTabs(tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(tabManager: TabManager) {
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatusForScrollView(scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells() as! [TabCell]
var bounds = collectionView.bounds
bounds = CGRectOffset(bounds, collectionView.contentInset.left, collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !CGRectIsEmpty(CGRectIntersection($0.frame, bounds)) }
var indexPaths = visibleCells.map { self.collectionView.indexPathForCell($0)! }
indexPaths.sortInPlace { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) }
if indexPaths.count == 0 {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItemsInSection(0)
if (firstTab == lastTab) {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: tabCount))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: lastTab), NSNumber(integer: tabCount))
}
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = collectionView.indexPathForCell(tabCell) {
let tab = tabsToDisplay[indexPath.item]
removedTabIndexPath = indexPath
tabManager.removeTab(tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: ""))
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(cell: TabCell) {
let indexPath = collectionView.indexPathForCell(cell)!
let tab = tabsToDisplay[indexPath.item]
removedTabIndexPath = indexPath
tabManager.removeTab(tab)
}
}
private class TabManagerDataSource: NSObject, UICollectionViewDataSource {
unowned var cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>
var tabs: [Browser]
init(tabs: [Browser], cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>) {
self.cellDelegate = cellDelegate
self.tabs = tabs
super.init()
}
@objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let tabCell = collectionView.dequeueReusableCellWithReuseIdentifier(TabCell.Identifier, forIndexPath: indexPath) as! TabCell
tabCell.animator.delegate = cellDelegate
tabCell.delegate = cellDelegate
let tab = tabs[indexPath.item]
tabCell.style = tab.isPrivate ? .Dark : .Light
tabCell.titleText.text = tab.displayTitle
if !tab.displayTitle.isEmpty {
tabCell.accessibilityLabel = tab.displayTitle
} else {
tabCell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url)
}
tabCell.isAccessibilityElement = true
tabCell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.")
if let favIcon = tab.displayFavicon {
tabCell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!)
} else {
tabCell.favicon.image = UIImage(named: "defaultFavicon")
}
tabCell.background.image = tab.screenshot
return tabCell
}
@objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabs.count
}
}
@objc protocol TabSelectionDelegate: class {
func didSelectTabAtIndex(index :Int)
}
private class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
private var traitCollection: UITraitCollection
private var profile: Profile
private var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection) {
self.profile = profile
self.traitCollection = traitCollection
super.init()
}
private func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let cellWidth = (collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns)
return CGSizeMake(cellWidth, self.cellHeightForCurrentDevice())
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin)
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
// There seems to be a bug with UIKit where when the UICollectionView changes its contentSize
// from > frame.size to <= frame.size: the contentSet animation doesn't properly happen and 'jumps' to the
// final state.
// This workaround forces the contentSize to always be larger than the frame size so the animation happens more
// smoothly. This also makes the tabs be able to 'bounce' when there are not enough to fill the screen, which I
// think is fine, but if needed we can disable user scrolling in this case.
private class TabTrayCollectionViewLayout: UICollectionViewFlowLayout {
private override func collectionViewContentSize() -> CGSize {
var calculatedSize = super.collectionViewContentSize()
let collectionViewHeight = collectionView?.bounds.size.height ?? 0
if calculatedSize.height < collectionViewHeight && collectionViewHeight > 0 {
calculatedSize.height = collectionViewHeight + 1
}
return calculatedSize
}
}
// A transparent view with a rectangular border with rounded corners, stroked
// with a semi-transparent white border.
class InnerStrokedView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let strokeWidth = 1.0 as CGFloat
let halfWidth = strokeWidth/2 as CGFloat
let path = UIBezierPath(roundedRect: CGRect(x: halfWidth,
y: halfWidth,
width: rect.width - strokeWidth,
height: rect.height - strokeWidth),
cornerRadius: TabTrayControllerUX.CornerRadius)
path.lineWidth = strokeWidth
UIColor.whiteColor().colorWithAlphaComponent(0.2).setStroke()
path.stroke()
}
}
struct EmptyPrivateTabsViewUX {
static let TitleColor = UIColor.whiteColor()
static let TitleFont = UIFont.systemFontOfSize(22, weight: UIFontWeightMedium)
static let DescriptionColor = UIColor.whiteColor()
static let DescriptionFont = UIFont.systemFontOfSize(17)
static let TextMargin: CGFloat = 18
static let MaxDescriptionWidth: CGFloat = 250
}
// View we display when there are no private tabs created
private class EmptyPrivateTabsView: UIView {
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.TitleColor
label.font = EmptyPrivateTabsViewUX.TitleFont
label.textAlignment = NSTextAlignment.Center
return label
}()
private var descriptionLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.DescriptionColor
label.font = EmptyPrivateTabsViewUX.DescriptionFont
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 3
label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth
return label
}()
private var iconImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "largePrivateMask"))
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = NSLocalizedString("Private Browsing",
tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode")
descriptionLabel.text = NSLocalizedString("Firefox won't remember any of your history or cookies, but new bookmarks will be saved.",
tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode")
// This landed last-minute as a new string that is needed in the EmptyPrivateTabsView
let learnMoreLabelText = NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode")
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(iconImageView)
titleLabel.snp_makeConstraints { make in
make.center.equalTo(self)
}
iconImageView.snp_makeConstraints { make in
make.bottom.equalTo(titleLabel.snp_top).offset(-EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
descriptionLabel.snp_makeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 998032c86c554f81e1e1bf34d6792b9f | 40.257732 | 304 | 0.69306 | false | false | false | false |
hyouuu/Centa | refs/heads/master | Sources/App/Helpers/Helpers.swift | mit | 1 | //
// Helpers.swift
// Centa
//
// Created by Shawn Gong on 10/31/16.
//
//
import Foundation
import HTTP
/*
public func pr(
_ message: @autoclosure () -> String,
file: String = #file,
line: Int = #line)
{
// #if DEBUG
let msg = message()
print("\(file.lastPathComponent.stringByDeletingPathExtension):\(line): \(msg)")
// #endif
}
*/
// MARK: Short UID
func dbContainsUid(_ uid: String) -> Bool {
do {
if let _ = try Trip.query().filter(Prop.uid, uid).first() {
return true
}
if let _ = try User.query().filter(Prop.uid, uid).first() {
return true
}
} catch {
return false
}
return false
}
// 56 billion possibilities - should be sufficient for global use
public func genUid(len: Int = 6) -> String {
var uid = ""
repeat {
uid = randomStringWithLength(len: len)
} while dbContainsUid(uid)
return uid
}
// It chooses from 26 + 26 + 10 = 62 chars, so 62^len in possible outcomes.
// e.g. 62^8 = 218,340,105,584,896
// 62^16 = 4.76 e+28
public func randomStringWithLength(len: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString = ""
for _ in 0..<len {
let max = letters.count
var idx = 0
// Currently linux doesn't support arc4random https://bugs.swift.org/browse/SR-685
#if os(Linux)
idx = Int(random() % (max + 1))
#else
idx = Int(arc4random_uniform(UInt32(max)))
#endif
let index = letters.index(letters.startIndex, offsetBy: idx)
randomString += String(letters[index])
}
return randomString
}
| 25a7e9c753b18e05a5451fa9243364ea | 22.186667 | 90 | 0.581369 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformUIKit/Components/SelectionScreen/Cells/SelectionItemTableViewCell.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxSwift
final class SelectionItemTableViewCell: UITableViewCell {
// MARK: - Injected
var presenter: SelectionItemViewPresenter! {
willSet {
disposeBag = DisposeBag()
}
didSet {
guard let presenter = presenter else { return }
switch presenter.thumb {
case .image(let content):
thumbImageView.set(content)
thumbLabel.content = .empty
thumbImageViewWidthConstraint.constant = 40
case .label(let content):
thumbLabel.content = content
thumbImageView.set(.empty)
thumbImageViewWidthConstraint.constant = 40
case .none:
thumbImageViewWidthConstraint.constant = 0.5
}
titleLabel.content = presenter.title
descriptionLabel.content = presenter.description
presenter.selectionImage
.bindAndCatch(to: selectionImageView.rx.content)
.disposed(by: disposeBag)
button.rx.tap
.bindAndCatch(to: presenter.tapRelay)
.disposed(by: disposeBag)
accessibility = presenter.accessibility
}
}
// MARK: - UI Properties
private let thumbImageView = UIImageView()
private let thumbLabel = UILabel()
private let stackView = UIStackView()
private let titleLabel = UILabel()
private let descriptionLabel = UILabel()
private let selectionImageView = UIImageView()
private let button = UIButton()
private var thumbImageViewWidthConstraint: NSLayoutConstraint!
// MARK: - Accessors
private var disposeBag = DisposeBag()
// MARK: - Setup
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
setup()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
presenter = nil
}
// MARK: - Setup
private func setup() {
contentView.addSubview(thumbImageView)
contentView.addSubview(thumbLabel)
contentView.addSubview(stackView)
contentView.addSubview(selectionImageView)
contentView.addSubview(button)
button.addTargetForTouchDown(self, selector: #selector(touchDown))
button.addTargetForTouchUp(self, selector: #selector(touchUp))
button.fillSuperview()
thumbImageView.layout(dimension: .height, to: 40)
thumbImageViewWidthConstraint = thumbImageView.layout(dimension: .width, to: 40)
thumbImageView.layoutToSuperview(.leading, offset: 24)
thumbImageView.layoutToSuperview(.centerY)
thumbImageView.layoutToSuperview(axis: .vertical, offset: 16, priority: .defaultHigh)
thumbLabel.layout(to: .leading, of: thumbImageView)
thumbLabel.layout(to: .trailing, of: thumbImageView)
thumbLabel.layout(to: .top, of: thumbImageView)
thumbLabel.layout(to: .bottom, of: thumbImageView)
stackView.layoutToSuperview(axis: .vertical, offset: 24)
stackView.layout(edge: .leading, to: .trailing, of: thumbImageView, offset: 16)
stackView.layout(edge: .trailing, to: .leading, of: selectionImageView, offset: -16)
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 4
stackView.insertArrangedSubview(titleLabel, at: 0)
stackView.insertArrangedSubview(descriptionLabel, at: 1)
titleLabel.verticalContentHuggingPriority = .required
titleLabel.verticalContentCompressionResistancePriority = .required
descriptionLabel.verticalContentHuggingPriority = .required
descriptionLabel.verticalContentCompressionResistancePriority = .required
selectionImageView.layout(size: .init(edge: 20))
selectionImageView.layoutToSuperview(.trailing, offset: -24)
selectionImageView.layoutToSuperview(.centerY)
}
@objc
private func touchDown() {
UIView.animate(
withDuration: 0.2,
delay: 0,
options: .beginFromCurrentState,
animations: {
self.contentView.backgroundColor = .hightlightedBackground
},
completion: nil
)
}
@objc
private func touchUp() {
UIView.animate(
withDuration: 0.2,
delay: 0,
options: .beginFromCurrentState,
animations: {
self.contentView.backgroundColor = .clear
},
completion: nil
)
}
}
| 33e383fa609488041d0c87539d951824 | 32.204082 | 93 | 0.638189 | false | false | false | false |
yotao/YunkuSwiftSDKTEST | refs/heads/master | YunkuSwiftSDK/YunkuSwiftSDK/Class/Utils/Digest.swift | mit | 1 | //
// Digest.swift
// SwiftDigest
//
// Created by Brent Royal-Gordon on 8/26/14.
// Copyright (c) 2014 Groundbreaking Software. All rights reserved.
//
import Foundation
import CommonCrypto
/// Digest is an immutable object representing a completed digest. Use the Digest
/// object to fetch the completed digest in various forms.
final public class Digest: Equatable, Comparable, Hashable {
/// The digest as a series of bytes.
public let bytes: [UInt8]
/// The digest as an NSData object.
public lazy var data: NSData = {
var temp = self.bytes
return NSData(bytes: &temp, length: temp.count)
}()
/// The digest as a hexadecimal string.
public lazy var hex: String = self.bytes.map { byte in byte.toHex() }.reduce("", +)
/// The digest as a base64-encoded String.
public func base64WithOptions(options: NSData.Base64EncodingOptions) -> String {
return data.base64EncodedString(options: options)
}
/// The digest as an NSData object of base64-encoded bytes.
public func base64DataWithOptions(options: NSData.Base64EncodingOptions) -> NSData {
return data.base64EncodedData(options: options) as NSData
}
/// Creates a Digest from an array of bytes. You should not normally need to
/// call this yourself.
public init(bytes: [UInt8]) {
self.bytes = bytes
}
/// Creates a Digest by copying the algorithm object and finish()ing it. You
/// should not normally need to call this yourself.
public convenience init<Algorithm: AlgorithmType>( algorithm: Algorithm) {
var algorithm = algorithm
self.init(bytes: algorithm.finish())
}
public lazy var hashValue: Int = {
// This should actually be a great hashValue for cryptographic digest
// algorithms, since each bit should contain as much entropy as
// every other.
var value: Int = 0
let usedBytes = self.bytes[0 ..< min(self.bytes.count, MemoryLayout<Int>.size)]
for byte in usedBytes {
value <<= 8
value &= Int(byte)
}
return value
}()
}
/// Tests if two digests are exactly equal.
public func == (lhs: Digest, rhs: Digest) -> Bool {
return lhs.bytes == rhs.bytes
}
/// Tests which digest is "less than" the other. Note that this comparison treats
/// shorter digests as "less than" longer digests; this should only occur if you
/// compare digests created by different algorithms.
public func < (lhs: Digest, rhs: Digest) -> Bool {
if lhs.bytes.count < rhs.bytes.count {
// rhs is a larger number
return true
}
if lhs.bytes.count > rhs.bytes.count {
// lhs is a larger number
return false
}
return lhs.bytes.lexicographicallyPrecedes(rhs.bytes)
}
| e052db87aa96841c12e680cae05672e9 | 32.290698 | 88 | 0.646525 | false | false | false | false |
chatnuere/whatTheFete | refs/heads/master | What The Fête/People.swift | mit | 1 | //
// People.swift
// What The Fête
//
// Created by Pierre-Jean DUGUÉ on 17/12/2014.
// Copyright (c) 2014 Pierre-Jean DUGUÉ. All rights reserved.
//
import UIKit
class People: NSObject {
var people_id:Int!
var user_id:Int!
var event_id:Int!
var mark:String!
var markBibine:String!
var markDance:String!
var markDrague:String!
var markStyle:String!
var markVanne:String!
init( people_id:Int!,user_id:Int!,event_id:Int!, mark:String!, markBibine:String!, markDance:String!, markDrague:String!, markStyle:String!, markVanne:String! ) {
self.people_id = people_id
self.user_id = user_id
self.event_id = event_id
self.mark = mark
self.markBibine = markBibine
self.markDance = markDance
self.markDrague = markDrague
self.markStyle = markStyle
self.markVanne = markVanne
}
}
| 970f94444e8e886df51833d016594798 | 23.815789 | 167 | 0.611877 | false | false | false | false |
TMTBO/TTAMusicPlayer | refs/heads/master | TTAMusicPlayer/TTAMusicPlayer/Classes/MusicList/Controllers/MusicListViewController.swift | mit | 1 | //
// MusicListViewController.swift
// MusicPlayer
//
// Created by ys on 16/11/22.
// Copyright © 2016年 TobyoTenma. All rights reserved.
//
import UIKit
import MediaPlayer
class MusicListViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView?.rowHeight = 60 * kSCALEP
cells = ["music_list_cell" : MusicLisbleViewCell.self]
}
func item(at indexPaht : IndexPath) -> MPMediaItem {
return PlayerManager.shared.musics[indexPaht.row]
}
}
// MARK: - UITableViewController
extension MusicListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return PlayerManager.shared.musics.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reuseCell = tableView.dequeueReusableCell(withIdentifier: "music_list_cell", for: indexPath)
guard let cell = reuseCell as? MusicLisbleViewCell else {
return reuseCell
}
cell.music = item(at: indexPath)
return cell
}
}
extension MusicListViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let playerVc = PlayerViewController()
playerVc.music = item(at: indexPath)
playerVc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(playerVc, animated: true)
}
}
| e3c4fcfcc2db086e4c20b0524a213844 | 30.46 | 109 | 0.696758 | false | false | false | false |
Nefuln/LNAddressBook | refs/heads/master | LNAddressBook/LNAddressBook/LNAddressBookUI/AddContact/view/LNContactHeaderFieldView.swift | mit | 1 | //
// LNContactHeaderFieldView.swift
// LNAddressBook
//
// Created by 浪漫满屋 on 2017/8/2.
// Copyright © 2017年 com.man.www. All rights reserved.
//
import UIKit
class LNContactHeaderFieldView: UIView {
public let textField: UITextField = {
let field = UITextField()
field.textColor = UIColor.black
return field
}()
override init(frame: CGRect) {
super.init(frame: frame)
initUI()
layout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func initUI() {
addSubview(textField)
addSubview(line)
}
private func layout() {
textField.snp.makeConstraints { (make) in
make.top.right.equalTo(self)
make.left.equalTo(self.snp.left).offset(10)
make.bottom.equalTo(self.line.snp.top)
}
line.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(self)
make.height.equalTo(0.5)
}
}
// MARK:- Private property
private let line: UIView = {
let line = UIView()
line.backgroundColor = UIColor.lightGray
return line
}()
}
| 024b4a7bf04f7086b0f33bf37c164c1d | 22.240741 | 59 | 0.575299 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/CryptoAssets/Tests/BitcoinKitTests/Models/Accounts/KeyPair/BitcoinKeyPairDeriverTests.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import BitcoinKit
import TestKit
import XCTest
class BitcoinKeyPairDeriverTests: XCTestCase {
var subject: AnyBitcoinKeyPairDeriver!
override func setUp() {
super.setUp()
subject = AnyBitcoinKeyPairDeriver()
}
override func tearDown() {
subject = nil
super.tearDown()
}
func test_derive_passphrase() throws {
// Arrange
let expectedKeyPair = BitcoinKeyPair(
privateKey: BitcoinPrivateKey(
xpriv: "xprv9yiFNv3Esk6JkJH1xDggWsRVp37cNbd92qEsRVMRC2Z9eJXnCDjUmmwqL6CDMc7iQjdDibUw433staJVz6RENGEeWkciWQ4kYGV5vLgv1PE"
),
xpub: "xpub6ChbnRa8i7ebxnMV4FDgt1NEN4x6n4LzQ4AUDsm2kN68X6rvjm3jKaGKBQCSF4ZQ4T2ctoTtgME3uYb76ZhZ7BLNrtSQM9FXTja2cZMF8Xr"
)
let keyDerivationInput = BitcoinKeyDerivationInput(
mnemonic: MockWalletTestData.Bip39.mnemonic,
passphrase: MockWalletTestData.Bip39.passphrase
)
// Act
guard let result = try? subject.derive(input: keyDerivationInput).get() else {
XCTFail("Derivation failed")
return
}
// Assert
XCTAssertEqual(result, expectedKeyPair)
}
func test_derive_empty_passphrase() throws {
// Arrange
let expectedKeyPair = BitcoinKeyPair(
privateKey: BitcoinPrivateKey(
xpriv: "xprv9zDrURuhy9arxJ4tWiwnBXvcyNT88wvnSitdTnu3x6571yWTfqgyjY6TqVqhG26fy39JPdzb1VX6zXinGQtHi3Wys3qPwdkatg1KSWM2uHs"
),
xpub: "xpub6DDCswSboX9AAn9MckUnYfsMXQHcYQedowpEGBJfWRc5tmqcDP1EHLQwgmXFmkYvfhNigZqUHdWJUpf6t3ufdYrdUCHUrZUhgKj3diWoSm6"
)
let keyDerivationInput = BitcoinKeyDerivationInput(
mnemonic: MockWalletTestData.Bip39.mnemonic,
passphrase: MockWalletTestData.Bip39.emptyPassphrase
)
// Act
guard let result = try? subject.derive(input: keyDerivationInput).get() else {
XCTFail("Derivation failed")
return
}
// Assert
XCTAssertEqual(result, expectedKeyPair)
}
}
| 93f7a2df605ec773533fefd23365ae9f | 31.893939 | 136 | 0.672041 | false | true | false | false |
EventsNetwork/Source | refs/heads/master | LetsTravel/TravelClient.swift | apache-2.0 | 1 | //
// TravelClient.swift
// LetsTravel
//
// Created by TriNgo on 4/13/16.
// Copyright © 2016 TriNgo. All rights reserved.
//
import UIKit
import AFNetworking
let TravelClientSharedInstance = TravelClient()
class TravelClient: NSObject {
let BASE_URL = "http://school.naptiengame.net/user"
let functionSessionManager: AFHTTPSessionManager
class var sharedInstance: TravelClient {
get {
return TravelClientSharedInstance;
}
}
override init() {
self.functionSessionManager = AFHTTPSessionManager(baseURL: NSURL(string: BASE_URL))
self.functionSessionManager.requestSerializer = AFJSONRequestSerializer()
self.functionSessionManager.responseSerializer = AFJSONResponseSerializer()
}
private func fetchData(dictionary: NSDictionary) -> NSDictionary?
{
let statusCode = dictionary["code"] as! Int
if (statusCode != -1) {
return dictionary["data"] as? NSDictionary
}else {
return nil
}
}
private func fetchDataWithArray(dictionary: NSDictionary) -> [NSDictionary]?
{
let statusCode = dictionary["code"] as! Int
if (statusCode != -1) {
return dictionary["data"] as? [NSDictionary]
}else {
return nil
}
}
private func generateError(response: AnyObject) -> NSError {
let errorCode = (response as! NSDictionary)["code"] as! Int
let errorMessage = (response as! NSDictionary)["msg"] as! String
let error = NSError(domain: self.BASE_URL, code: errorCode, userInfo: ["error": errorMessage])
return error
}
// Login
func login(facebookId: String, fullName: String, avatarUrl: String, success: (User) -> (), failure: (NSError) -> ()) {
let postData = ["facebook_id":facebookId, "full_name":fullName, "avatar_url":avatarUrl]
let params = ["command": "U_LOGIN", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in
let userDictionary = self.fetchData(response as! NSDictionary)
if (userDictionary != nil) {
let user = User(dictionary: userDictionary!)
User.currentUser = user
success(user)
}else{
failure(self.generateError(response!))
}
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error)
})
}
// Logout
func logout() {
User.currentUser = nil
NSNotificationCenter.defaultCenter().postNotificationName(User.userDidLogoutNotification, object: nil)
}
// Search places with category and province
func searchPlaceViaCategoryAndProvince(provinceId: Int, categoryId: String, placeName: String, success: ([Place]) -> (), failure: (NSError) -> ()) {
let postData = ["province_id":provinceId, "category_id":categoryId, "place_name":placeName]
let params = ["command": "U_PLACE_SEARCH_CATEGORY", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let placesDictionary = self.fetchDataWithArray(response as! NSDictionary)
if (placesDictionary != nil) {
let places = Place.getPlaces(placesDictionary!)
success(places)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
// Get province list
func getProvinces(success: ([Province]) -> (), failure: (NSError) -> ()) {
let params = ["command": "U_PROVINCE_LIST", "data" : ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let provinceDictionaries = self.fetchDataWithArray(response as! NSDictionary)
if (provinceDictionaries != nil) {
let provinces = Province.getProvinces(provinceDictionaries!)
success(provinces)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
// Get categories list
func getCategories(success: ([Category]) -> (), failure: (NSError) -> ()) {
let params = ["command": "U_CATEGORY_LIST", "data" : ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let categoryDictionaries = self.fetchDataWithArray(response as! NSDictionary)
if (categoryDictionaries != nil) {
let categories = Category.getCategories(categoryDictionaries!)
success(categories)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
// Get hot tours
func getHotTours(success: ([Tour]) -> (), failure: (NSError) -> ()) {
let params = ["command": "U_TOUR_HOT_LIST", "data" : ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in
let tourDictionaries = self.fetchDataWithArray(response as! NSDictionary)
if (tourDictionaries != nil) {
let tours = Tour.getTours(tourDictionaries!)
success(tours)
} else {
failure(self.generateError(response!))
}
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error)
})
}
// Get tour detail
func getTourDetail(tourId: Int, success: (Tour) -> (), failure: (NSError) -> ()) {
let postData = ["tour_id": tourId]
let params = ["command": "U_TOUR_DETAIL", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let tourDictionary = self.fetchData(response as! NSDictionary)
if (tourDictionary != nil) {
let tour = Tour(dictionary: tourDictionary!)
success(tour)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
// Get list my tour
func getMyTours(success: ([Tour]) -> (), failure: (NSError) -> ()) {
let token = User.currentUser?.token as! String
let params = ["command": "U_TOUR_MYSELF", "token" : token, "data" : ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in
let tourDictionaries = self.fetchDataWithArray(response as! NSDictionary)
if (tourDictionaries != nil) {
let tours = Tour.getTours(tourDictionaries!)
success(tours)
} else {
failure(self.generateError(response!))
}
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error)
})
}
func createTour(tour: Tour, success: (Tour) -> (), failure: (NSError) -> ()) {
var postData = [String: AnyObject]()
postData["tour"] = ["start_time": tour.startTime ?? 0, "description": tour.desc ?? "", "province_id": tour.provinceId ?? 0]
var events = [[String: AnyObject]]()
for event in tour.tourEvents! {
events.append(["day" : event.dayOrder ?? 1, "place_id": event.place.placeId ?? 0])
}
postData["tour_events"] = events
let params = ["command": "U_TOUR_ADD", "data" : postData, "token": User.currentUser?.token ?? ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let responseDictionary = self.fetchData(response as! NSDictionary)
if let responseDictionary = responseDictionary {
if let tourId = responseDictionary["tour_id"] as? String {
tour.tourId = Int(tourId)
}
success(tour)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
func generateShareUrl(tour: Tour, success: (FBHostLink) -> (), failure: (NSError) -> ()) {
let postData = ["tour_id": tour.tourId ?? 0]
let params = ["command": "U_TOUR_GET_HOST_LINK", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let responseDictionary = self.fetchData(response as! NSDictionary)
if let responseDictionary = responseDictionary {
let hostLink = FBHostLink(dictionary: responseDictionary)
success(hostLink)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
func getPlaceDetail(placeId: Int, success: (Place) -> (), failure: (NSError) -> ()) {
let postData = ["place_id": placeId]
let params = ["command": "U_PLACE_DETAIL", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let placeDictionary = self.fetchData(response as! NSDictionary)
if (placeDictionary != nil) {
let place = Place(dictionary: placeDictionary!)
success(place)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
}
| 57111050425ac2ab071eba44647bd268 | 38.151625 | 158 | 0.583956 | false | false | false | false |
lionchina/RxSwiftBook | refs/heads/master | RxImagePicker/RxImagePicker/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// RxImagePicker
//
// Created by MaxChen on 03/08/2017.
// Copyright © 2017 com.linglustudio. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "RxImagePicker")
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)")
}
}
}
}
| 8f6fff099cf978b286ad056e83051bde | 48.505376 | 285 | 0.686794 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Client/Frontend/Accessors/NewTabAccessors.swift | mpl-2.0 | 2 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
/// Accessors to find what a new tab should do when created without a URL.
struct NewTabAccessors {
static let NewTabPrefKey = PrefsKeys.KeyNewTab
static let HomePrefKey = PrefsKeys.HomePageTab
static let Default = NewTabPage.topSites
static func getNewTabPage(_ prefs: Prefs) -> NewTabPage {
guard let raw = prefs.stringForKey(NewTabPrefKey) else { return Default }
let option = NewTabPage(rawValue: raw) ?? Default
// Check if the user has chosen to open a homepage, but no homepage is set,
// then use the default.
if option == .homePage && NewTabHomePageAccessors.getHomePage(prefs) == nil {
return Default
}
return option
}
static func getHomePage(_ prefs: Prefs) -> NewTabPage {
guard let raw = prefs.stringForKey(HomePrefKey) else { return Default }
let option = NewTabPage(rawValue: raw) ?? Default
// Check if the user has chosen to open a homepage, but no homepage is set,
// then use the default.
if option == .homePage && HomeButtonHomePageAccessors.getHomePage(prefs) == nil {
return Default
}
return option
}
}
/// Enum to encode what should happen when the user opens a new tab without a URL.
enum NewTabPage: String {
case blankPage = "Blank"
case homePage = "HomePage"
case topSites = "TopSites"
var settingTitle: String {
switch self {
case .blankPage:
return .SettingsNewTabBlankPage
case .homePage:
return .SettingsNewTabHomePage
case .topSites:
return .SettingsNewTabTopSites
}
}
var homePanelType: HomePanelType? {
switch self {
case .topSites:
return HomePanelType.topSites
default:
return nil
}
}
var url: URL? {
guard let homePanel = self.homePanelType else { return nil }
return homePanel.internalUrl as URL
}
static func fromAboutHomeURL(url: URL) -> NewTabPage? {
guard let internalUrl = InternalURL(url),
internalUrl.isAboutHomeURL,
let panelNumber = url.fragment?.split(separator: "=").last
else { return nil }
switch panelNumber {
case "0":
return NewTabPage.topSites
default:
return nil
}
}
static let allValues = [blankPage, topSites, homePage]
}
| fe1d565b858f818284252aa31bbe14cf | 30.232558 | 89 | 0.628071 | false | false | false | false |
cp3hnu/PrivacyManager | refs/heads/master | PrivacyManagerDemo/PrivacyManagerDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// PrivacyManagerDemo
//
// Created by CP3 on 17/4/13.
// Copyright © 2017年 CP3. All rights reserved.
//
import UIKit
import RxSwift
import CoreLocation
import PrivacyManager
import PrivacyPhoto
import PrivacyCamera
import PrivacyMicrophone
import PrivacyContact
import PrivacyLocation
import PrivacySpeech
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// MARK: - 获取状态
let locationStatus = PrivacyManager.shared.locationStatus
print("locationStatus = ", locationStatus)
let cameraStatus = PrivacyManager.shared.cameraStatus
print("cameraStatus = ", cameraStatus)
let phoneStatus = PrivacyManager.shared.photoStatus
print("phoneStatus = ", phoneStatus)
let microphoneStatus = PrivacyManager.shared.microphoneStatus
print("microphoneStatus = ", microphoneStatus)
let contactStatus = PrivacyManager.shared.contactStatus
print("contactStatus = ", contactStatus)
// MARK: - UIViewController 请求权限 - 使用 UIViewcontroller 扩展方法 `privacyPermission`
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
PrivacyManager.shared.locationPermission(presenting: self, always: false, authorized: {
self.present("定位服务已授权")
})
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
_ = PrivacyManager.shared.rxLocations.subscribe(onNext: { locations in
print("locations", locations)
}, onError: { error in
print("error", error)
}, onCompleted: {
print("onCompleted")
}, onDisposed: {
print("onDisposed")
})
}
view.backgroundColor = UIColor.white
let button1 = UIButton()
button1.setTitle("相机", for: .normal)
button1.setTitleColor(UIColor.black, for: .normal)
_ = button1.rx.tap.subscribe(
onNext: { [weak self] _ in
guard let self = self else { return }
PrivacyManager.shared.cameraPermission(presenting: self, authorized: {
self.present("相机已授权")
})
}
)
let button2 = UIButton()
button2.setTitle("照片", for: .normal)
button2.setTitleColor(UIColor.black, for: .normal)
_ = button2.rx.tap.subscribe(
onNext: { [weak self] _ in
guard let self = self else { return }
PrivacyManager.shared.photoPermission(presenting: self, authorized: {
self.present("照片已授权")
})
}
)
let button3 = UIButton()
button3.setTitle("麦克风", for: .normal)
button3.setTitleColor(UIColor.black, for: .normal)
_ = button3.rx.tap.subscribe(
onNext: { [weak self] _ in
guard let self = self else { return }
PrivacyManager.shared.microphonePermission(presenting: self, authorized: {
self.present("麦克风已授权")
})
}
)
let button4 = UIButton()
button4.setTitle("语音识别", for: .normal)
button4.setTitleColor(UIColor.black, for: .normal)
_ = button4.rx.tap.subscribe(
onNext: { [weak self] _ in
guard let self = self else { return }
PrivacyManager.shared.speechPermission(presenting: self, authorized: {
self.present("语音识别已授权")
})
}
)
// MARK: - 使用 PrivacyManager 的 observable
let button5 = UIButton()
button5.setTitle("通讯录", for: .normal)
button5.setTitleColor(UIColor.black, for: .normal)
_ = button5.rx.tap
.flatMap{ () -> Observable<Bool> in
return PrivacyManager.shared.rxContactPermission
}
.subscribe(
onNext: { [weak self] granted in
if !granted {
self?.presentPrivacySetting(type: PermissionType.contact)
} else {
self?.present("通讯录已授权")
}
}
)
[button1, button2, button3, button4, button5].forEach { button in
button.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(button)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[button]-15-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["button" : button]))
}
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-80-[button1(==40)]-40-[button2(==40)]-40-[button3(==40)]-40-[button4(==40)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["button1" : button1, "button2" : button2, "button3" : button3, "button4" : button4]))
button5.topAnchor.constraint(equalTo: button4.bottomAnchor, constant: 40).isActive = true
}
}
private extension ViewController {
func present(_ content: String) {
let alert = UIAlertController(title: content, message: "", preferredStyle: UIAlertController.Style.alert)
let action = UIAlertAction(title: "确定", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(action)
alert.preferredAction = action
present(alert, animated: true, completion: nil)
}
}
| bad0f79da87a800bbd0e40db9f5df819 | 35.928571 | 323 | 0.573061 | false | false | false | false |
airspeedswift/swift | refs/heads/master | test/IRGen/objc_subclass.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize %s
// REQUIRES: objc_interop
// The order of the output seems to change between asserts/noasserts build of
// the stlib.
// REQUIRES: swift_stdlib_asserts
// CHECK: [[SGIZMO:T13objc_subclass10SwiftGizmoC]] = type
// CHECK: [[OBJC_CLASS:%objc_class]] = type
// CHECK: [[OPAQUE:%swift.opaque]] = type
// CHECK: [[INT:%TSi]] = type <{ [[LLVM_PTRSIZE_INT:i(32|64)]] }>
// CHECK: [[TYPE:%swift.type]] = type
// CHECK-DAG: [[GIZMO:%TSo5GizmoC]] = type <{ %objc_class* }>
// CHECK-DAG: [[OBJC:%objc_object]] = type opaque
// CHECK-32: @"$s13objc_subclass10SwiftGizmoC1xSivpWvd" = hidden global i32 4, align [[WORD_SIZE_IN_BYTES:4]]
// CHECK-64: @"$s13objc_subclass10SwiftGizmoC1xSivpWvd" = hidden global i64 8, align [[WORD_SIZE_IN_BYTES:8]]
// CHECK: @"OBJC_METACLASS_$__TtC13objc_subclass10SwiftGizmo" = hidden global [[OBJC_CLASS]] { [[OBJC_CLASS]]* @"OBJC_METACLASS_$_NSObject", [[OBJC_CLASS]]* @"OBJC_METACLASS_$_Gizmo", [[OPAQUE]]* @_objc_empty_cache, [[OPAQUE]]* null, [[LLVM_PTRSIZE_INT]] ptrtoint ({{.*}} @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo to [[LLVM_PTRSIZE_INT]]) }
// CHECK: [[STRING_SWIFTGIZMO:@.*]] = private unnamed_addr constant [32 x i8] c"_TtC13objc_subclass10SwiftGizmo\00"
// CHECK-32: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = internal constant { {{.*}}* } {
// CHECK-32: i32 129,
// CHECK-32: i32 20,
// CHECK-32: i32 20,
// CHECK-32: i8* null,
// CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0),
// CHECK-32: i8* null,
// CHECK-32: i8* null,
// CHECK-32: i8* null,
// CHECK-32: i8* null,
// CHECK-32: i8* null
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = internal constant { {{.*}}* } {
// CHECK-64: i32 129,
// CHECK-64: i32 40,
// CHECK-64: i32 40,
// CHECK-64: i32 0,
// CHECK-64: i8* null,
// CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0),
// CHECK-64: i8* null,
// CHECK-64: i8* null,
// CHECK-64: i8* null,
// CHECK-64: i8* null,
// CHECK-64: i8* null
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-32: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [7 x i8] c"l8@0:4\00"
// CHECK-64: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [8 x i8] c"q16@0:8\00"
// CHECK-32: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4l8\00"
// CHECK-64: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8q16\00"
// CHECK-32: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"@8@0:4\00"
// CHECK-64: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00"
// CHECK-32: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [13 x i8] c"@16@0:4l8@12\00"
// CHECK-64: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [14 x i8] c"@32@0:8q16@24\00"
// CHECK-32: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"v8@0:4\00"
// CHECK-64: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = internal constant { {{.*}}] } {
// CHECK-32: i32 12,
// CHECK-32: i32 11,
// CHECK-32: [11 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0),
// CHECK-32: i8* bitcast {{.*}}* @"$s13objc_subclass10SwiftGizmoC1xSivgTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[METHOD_TYPE_ENCODING2]], i32 0, i32 0),
// CHECK-32: i8* bitcast {{.*}}* @"$s13objc_subclass10SwiftGizmoC1xSivsTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0),
// CHECK-32: i8* bitcast {{.*}}* @"$s13objc_subclass10SwiftGizmoC4getXSiyFTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoCACycfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([13 x i8], [13 x i8]* [[INIT_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC3int6stringACSi_SStcfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[DEALLOC_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast {{.*}}* @"$s13objc_subclass10SwiftGizmoCfDTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC7enabledSbvgTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC7enabledSbvsTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC7bellsOnACSgSi_tcfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, { i8*, i8*, i8* } {
// CHECK-32: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoCfeTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }]
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = internal constant { {{.*}}] } {
// CHECK-64: i32 24,
// CHECK-64: i32 11,
// CHECK-64: [11 x { i8*, i8*, i8* }] [{
// CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0)
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC1xSivgTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[METHOD_TYPE_ENCODING2]], i64 0, i64 0)
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC1xSivsTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0)
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC4getXSiyFTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoCACycfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* [[INIT_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC3int6stringACSi_SStcfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoCfDTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC7enabledSbvgTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC7enabledSbvsTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoC7bellsOnACSgSi_tcfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass10SwiftGizmoCfeTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }]
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK: [[STRING_X:@.*]] = private unnamed_addr constant [2 x i8] c"x\00"
// CHECK-64: [[STRING_EMPTY:@.*]] = private unnamed_addr constant [1 x i8] zeroinitializer
// CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo = internal constant { {{.*}}] } {
// CHECK-32: i32 20,
// CHECK-32: i32 1,
// CHECK-32: [1 x { i32*, i8*, i8*, i32, i32 }] [{ i32*, i8*, i8*, i32, i32 } {
// CHECK-32: i32* @"$s13objc_subclass10SwiftGizmoC1xSivpWvd",
// CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([1 x i8], [1 x i8]* {{.*}}, i32 0, i32 0),
// CHECK-32: i32 2,
// CHECK-32: i32 4 }]
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo = internal constant { {{.*}}] } {
// CHECK-64: i32 32,
// CHECK-64: i32 1,
// CHECK-64: [1 x { i64*, i8*, i8*, i32, i32 }] [{ i64*, i8*, i8*, i32, i32 } {
// CHECK-64: i64* @"$s13objc_subclass10SwiftGizmoC1xSivpWvd",
// CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i64 0, i64 0),
// CHECK-64: i32 3,
// CHECK-64: i32 8 }]
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-32: @_DATA__TtC13objc_subclass10SwiftGizmo = internal constant { {{.*}}* } {
// CHECK-32: i32 132,
// CHECK-32: i32 4,
// CHECK-32: i32 8,
// CHECK-32: i8* null,
// CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0),
// CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo,
// CHECK-32: i8* null,
// CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo,
// CHECK-32: i8* null,
// CHECK-32: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_DATA__TtC13objc_subclass10SwiftGizmo = internal constant { {{.*}}* } {
// CHECK-64: i32 132,
// CHECK-64: i32 8,
// CHECK-64: i32 16,
// CHECK-64: i32 0,
// CHECK-64: i8* null,
// CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0),
// CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo,
// CHECK-64: i8* null,
// CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo,
// CHECK-64: i8* null,
// CHECK-64: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo
// CHECK-64: }, section "__DATA, __objc_const", align 8
// CHECK-NOT: @_TMCSo13SwiftGizmo = {{.*NSObject}}
// CHECK: @_INSTANCE_METHODS__TtC13objc_subclass12GenericGizmo
// CHECK-32: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4@8\00"
// CHECK-64: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = internal constant { i32, i32, [5 x { i8*, i8*, i8* }] } {
// CHECK-32: i32 12,
// CHECK-32: i32 5,
// CHECK-32: [5 x { i8*, i8*, i8* }] [
// CHECK-32: {
// CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCvgTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[SETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCvsTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2CACycfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2C7bellsOnACSgSi_tcfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }, {
// CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i32 0, i32 0),
// CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* {{@[0-9]+}}, i32 0, i32 0),
// CHECK-32: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2CfETo{{(\.ptrauth)?}}" to i8*)
// CHECK-32: }
// CHECK-32: ]
// CHECK-32: }, section "__DATA, __objc_const", align 4
// CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = internal constant { i32, {{.*}}] } {
// CHECK-64: i32 24,
// CHECK-64: i32 5,
// CHECK-64: [5 x { i8*, i8*, i8* }] [
// CHECK-64: {
// CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCvgTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCvsTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2CACycfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2C7bellsOnACSgSi_tcfcTo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }, {
// CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0),
// CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* {{@[0-9]+}}, i64 0, i64 0)
// CHECK-64: i8* bitcast ({{.*}}* @"$s13objc_subclass11SwiftGizmo2CfETo{{(\.ptrauth)?}}" to i8*)
// CHECK-64: }
// CHECK-64: ] }
// CHECK: @objc_classes = internal global [2 x i8*] [i8* bitcast (%swift.type* @"$s13objc_subclass10SwiftGizmoCN" to i8*), i8* bitcast (%swift.type* @"$s13objc_subclass11SwiftGizmo2CN" to i8*)], section "__DATA,__objc_classlist,regular,no_dead_strip", align [[WORD_SIZE_IN_BYTES]]
// CHECK: @objc_non_lazy_classes = internal global [1 x i8*] [i8* bitcast (%swift.type* @"$s13objc_subclass11SwiftGizmo2CN" to i8*)], section "__DATA,__objc_nlclslist,regular,no_dead_strip", align [[WORD_SIZE_IN_BYTES]]
import Foundation
import gizmo
@requires_stored_property_inits
class SwiftGizmo : Gizmo {
@objc var x = Int()
@objc func getX() -> Int {
return x
}
override func duplicate() -> Gizmo {
return SwiftGizmo()
}
override init() {
super.init(bellsOn:0)
}
@objc init(int i: Int, string str : String) {
super.init(bellsOn:i)
}
deinit { var x = 10 }
@objc var enabled: Bool {
@objc(isEnabled) get {
return true
}
@objc(setIsEnabled:) set {
}
}
}
class GenericGizmo<T> : Gizmo {
@objc func foo() {}
@objc var x : Int {
return 0
}
var array : [T] = []
}
// CHECK: define hidden swiftcc [[LLVM_PTRSIZE_INT]] @"$s13objc_subclass12GenericGizmoC1xSivg"(
var sg = SwiftGizmo()
sg.duplicate()
@_objc_non_lazy_realization
class SwiftGizmo2 : Gizmo {
@objc var sg : SwiftGizmo
override init() {
sg = SwiftGizmo()
super.init()
}
deinit { }
}
| 19f8173f6e3f8f3835e2f4581a202417 | 57.209302 | 347 | 0.593787 | false | false | false | false |
KYawn/myiOS | refs/heads/master | scrowllView/scrowllView/RootViewController.swift | apache-2.0 | 1 | //
// RootViewController.swift
// scrowllView
//
// Created by K.Yawn Xoan on 3/22/15.
// Copyright (c) 2015 K.Yawn Xoan. All rights reserved.
//
import UIKit
class RootViewController: UIViewController, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil)
self.pageViewController!.delegate = self
let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers: NSArray = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self.modelController
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
// Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
var pageViewRect = self.view.bounds
self.pageViewController!.view.frame = pageViewRect
self.pageViewController!.didMoveToParentViewController(self)
// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var modelController: ModelController {
// Return the model controller object, creating it if necessary.
// In more complex implementations, the model controller may be passed to the view controller.
if _modelController == nil {
_modelController = ModelController()
}
return _modelController!
}
var _modelController: ModelController? = nil
// MARK: - UIPageViewController delegate methods
func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
// Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
let currentViewController = self.pageViewController!.viewControllers[0] as UIViewController
let viewControllers: NSArray = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
self.pageViewController!.doubleSided = false
return .Min
}
}
| f702f2b4309eea3ac588cf6eeca322fa | 43.819444 | 291 | 0.737837 | false | false | false | false |
haranicle/AlcatrazTour | refs/heads/master | AlcatrazTour/GithubClient.swift | mit | 1 | //
// GithubClient.swift
// AlcatrazTour
//
// Copyright (c) 2015年 haranicle. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Realm
import OAuthSwift
import SVProgressHUD
import JDStatusBarNotification
class GithubClient: NSObject {
// MARK: - Const
let alcatrazPackagesUrl = "https://raw.githubusercontent.com/supermarin/alcatraz-packages/master/packages.json"
let githubRepoUrl = "https://github.com"
let githubRepoApiUrl = "https://api.github.com/repos"
let githubStarApiUrl = "https://api.github.com/user/starred/"
let appScheme = "alcatraztour:"
// MARK: - Status
var isLoading = false
var loadCompleteCount:Int = 0
// MARK: - Create URL
func createRepoDetailUrl(repoUrl:String) -> String {
// create api url
var repoDetailUrl:String = repoUrl.stringByReplacingOccurrencesOfString(githubRepoUrl, withString: githubRepoApiUrl, options: [], range: nil)
// remove last "/"
if repoDetailUrl.hasSuffix("/") {
repoDetailUrl = repoDetailUrl[repoDetailUrl.startIndex..<repoDetailUrl.endIndex.advancedBy(-1)]
}
// remove last ".git"
if repoDetailUrl.hasSuffix(".git") {
repoDetailUrl = repoDetailUrl[repoDetailUrl.startIndex..<repoDetailUrl.endIndex.advancedBy(-4)]
}
return repoDetailUrl
}
// MARK: - OAuth
let githubOauthTokenKey = "githubTokenKey"
func isSignedIn()->Bool {
if let token = NSUserDefaults.standardUserDefaults().stringForKey(githubOauthTokenKey) {
return true
}
return false
}
func signOut() {
NSUserDefaults.standardUserDefaults().removeObjectForKey(githubOauthTokenKey)
}
func requestOAuth(onSucceed:Void->Void, onFailed:NSError -> Void ){
let oauthswift = OAuth2Swift(
consumerKey: GithubKey["consumerKey"]!,
consumerSecret: GithubKey["consumerSecret"]!,
authorizeUrl: "https://github.com/login/oauth/authorize",
accessTokenUrl: "https://github.com/login/oauth/access_token",
responseType: "code"
)
let oAuthTokenKey = githubOauthTokenKey
oauthswift.authorize_url_handler = LoginWebViewController()
oauthswift.authorizeWithCallbackURL( NSURL(string: "\(appScheme)//oauth-callback/github")!, scope: "user,repo,public_repo", state: "GITHUB", success: {
credential, response, parameters in
NSUserDefaults.standardUserDefaults().setObject(credential.oauth_token, forKey:oAuthTokenKey)
onSucceed()
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func oAuthToken() -> String? {
let token = NSUserDefaults.standardUserDefaults().stringForKey(githubOauthTokenKey)
if token == nil {
JDStatusBarNotification.showWithStatus("Not signed in.", dismissAfter: 3, styleName: JDStatusBarStyleError)
}
return token
}
// MARK: - Request
func requestPlugins(onSucceed:[Plugin] -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) {
Alamofire
.request(.GET, alcatrazPackagesUrl)
.validate(statusCode: 200..<400)
.responseJSON { response in
if let aError = response.result.error {
onFailed(response.request!, response.response, response.data, aError)
return
}
if let aResponseData: AnyObject = response.data {
var plugins:[Plugin] = []
let jsonData = JSON(aResponseData)
let jsonPlugins = jsonData["packages"]["plugins"].array
if let count = jsonPlugins?.count {
for i in 0 ..< count {
if let pluginParams = jsonPlugins?[i].object as? NSDictionary {
let plugin = Plugin()
plugin.setParams(pluginParams)
plugins.append(plugin)
}
}
}
onSucceed(plugins)
} else {
onFailed(response.request!, response.response, response.data, nil)
}
}
}
func requestRepoDetail(token:String, plugin:Plugin, onSucceed:(Plugin?, NSDictionary) -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) {
Alamofire
.request(Method.GET, createRepoDetailUrl(plugin.url), parameters: ["access_token": token])
.validate(statusCode: 200..<400)
.responseJSON { response in
if let aError = response.result.error {
onFailed(response.request!, response.response, response.data, aError)
return
}
if let aResponseData: AnyObject = response.data {
let jsonData = JSON(aResponseData)
if let pluginDetail = jsonData.object as? NSDictionary {
onSucceed(plugin, pluginDetail)
}
} else {
onFailed(response.request!, response.response, response.data, nil)
}
}
}
// MARK: - Processing Flow
func reloadAllPlugins(onComplete:NSError?->Void) {
if(isLoading) {
print("NOW LOADING!!")
return
}
print("START LOADING!!")
SVProgressHUD.showWithStatus("Loading list", maskType: SVProgressHUDMaskType.Black)
isLoading = true
loadCompleteCount = 0
// loading plugin list
let onSucceedRequestingPlugins = {[weak self] (plugins:[Plugin]) -> Void in
print("PLUGIN LIST LOAD COMPLETE!!")
SVProgressHUD.dismiss()
SVProgressHUD.showProgress(0, status: "Loading data", maskType: SVProgressHUDMaskType.Black)
// Dispatch Group
let group = dispatch_group_create()
var successCount = 0
// loading plugin details
let onSucceedRequestingRepoDetail = {[weak self] (plugin:Plugin?, pluginDetail:NSDictionary) -> Void in
plugin?.setDetails(pluginDetail)
if let p = plugin {
p.save()
}
successCount++
self?.updateProgress(plugins.count)
dispatch_group_leave(group)
}
let onFailed = {[weak self] (request:NSURLRequest, response:NSHTTPURLResponse?, responseData:AnyObject?, error:NSError?) -> Void in
self?.updateProgress(plugins.count)
dispatch_group_leave(group)
}
// start writing
RLMRealm.defaultRealm().beginWriteTransaction()
Plugin.deleteAll()
let token = self?.oAuthToken()
if token == nil {
return
}
for plugin in plugins {
dispatch_group_enter(group)
self?.requestRepoDetail(token!, plugin: plugin, onSucceed: onSucceedRequestingRepoDetail, onFailed: onFailed)
}
dispatch_group_notify(group, dispatch_get_main_queue(), {
// Yay!!! All done!!!
SVProgressHUD.dismiss()
self?.isLoading = false
do {
try RLMRealm.defaultRealm().commitWriteTransaction()
} catch {
fatalError()
}
print("successCount = \(successCount)")
print("plugins.count = \(plugins.count)")
onComplete(nil)
})
}
let onFailed = {[weak self] (request:NSURLRequest, response:NSHTTPURLResponse?, responseData:AnyObject?, error:NSError?) -> Void in
print("request = \(request)")
print("response = \(response)")
print("responseData = \(responseData)")
print("error = \(error?.description)")
self?.isLoading = false
SVProgressHUD.dismiss()
onComplete(error)
}
requestPlugins(onSucceedRequestingPlugins, onFailed: onFailed)
}
func updateProgress(pluginsCount:Int) {
self.loadCompleteCount++
SVProgressHUD.showProgress(Float(self.loadCompleteCount) / Float(pluginsCount) , status: "Loading data", maskType: SVProgressHUDMaskType.Black)
}
// MARK: - Staring
func checkIfStarredRepository(token:String, owner:String, repositoryName:String, onSucceed:(Bool) -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Request {
let apiUrl = githubStarApiUrl + owner + "/" + repositoryName
return Alamofire
.request(Method.GET, apiUrl, parameters: ["access_token": token])
.validate(statusCode: 204...404)
.responseString { response in
if let aError = response.result.error {
onFailed(response.request!, response.response, response.data, aError)
return
}
if(response.response?.statusCode==204){
onSucceed(true)
return
}
if(response.response?.statusCode==404){
onSucceed(false)
return
}
onFailed(response.request!, response.response, response.data, nil)
}
}
func starRepository(token:String, isStarring:Bool, owner:String, repositoryName:String, onSucceed:() -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) {
let apiUrl = githubStarApiUrl + owner + "/" + repositoryName
let method = isStarring ? Method.PUT : Method.DELETE
Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = [
"Content-Length" : "0",
"Authorization" : "token \(token)"
]
Alamofire
.request(method, apiUrl, parameters: nil)
.validate(statusCode: 200..<400)
.responseString { response in
if let aError = response.result.error {
onFailed(response.request!, response.response, response.data, aError)
return
}
onSucceed()
}
}
func checkAndStarRepository(token:String, isStarring:Bool, owner:String, repositoryName:String, onSucceed:() -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void){
checkIfStarredRepository(token, owner: owner, repositoryName: repositoryName, onSucceed: { (isStarred) -> Void in
if isStarring && isStarred {
JDStatusBarNotification.showWithStatus("Already starred.", dismissAfter: 3, styleName: JDStatusBarStyleWarning)
return
} else if !isStarring && !isStarred {
JDStatusBarNotification.showWithStatus("Already unstarred.", dismissAfter: 3, styleName: JDStatusBarStyleWarning)
return;
}
self.starRepository(token, isStarring: isStarring, owner: owner, repositoryName: repositoryName, onSucceed: { (responseObject) -> Void in
let action = isStarring ? "starred" : "unstarred"
JDStatusBarNotification.showWithStatus("Your \(action) \(repositoryName).", dismissAfter: 3, styleName: JDStatusBarStyleSuccess)
onSucceed()
}, onFailed: onFailed)
}, onFailed: onFailed)
}
}
| f822d597a37396d29e0936350cd8bf09 | 37.924528 | 199 | 0.552997 | false | false | false | false |
acavanaghww/ImagePickerSheetController | refs/heads/master | ImagePickerSheetController/ImagePickerSheetController/ImageCollectionViewCell.swift | mit | 1 | //
// ImageCollectionViewCell.swift
// ImagePickerSheet
//
// Created by Laurin Brandner on 06/09/14.
// Copyright (c) 2014 Laurin Brandner. All rights reserved.
//
import UIKit
class ImageCollectionViewCell : UICollectionViewCell {
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .ScaleAspectFill
return imageView
}()
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
addSubview(imageView)
}
// MARK: - Other Methods
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
}
}
| 2b773478d270511d5e5e4e730ea26007 | 18.849057 | 60 | 0.574144 | false | false | false | false |
SwiftyJSON/SwiftyJSON | refs/heads/master | Source/SwiftyJSON/SwiftyJSON.swift | mit | 1 | // SwiftyJSON.swift
//
// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang
//
// 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
// MARK: - Error
// swiftlint:disable line_length
public enum SwiftyJSONError: Int, Swift.Error {
case unsupportedType = 999
case indexOutOfBounds = 900
case elementTooDeep = 902
case wrongType = 901
case notExist = 500
case invalidJSON = 490
}
extension SwiftyJSONError: CustomNSError {
/// return the error domain of SwiftyJSONError
public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" }
/// return the error code of SwiftyJSONError
public var errorCode: Int { return self.rawValue }
/// return the userInfo of SwiftyJSONError
public var errorUserInfo: [String: Any] {
switch self {
case .unsupportedType:
return [NSLocalizedDescriptionKey: "It is an unsupported type."]
case .indexOutOfBounds:
return [NSLocalizedDescriptionKey: "Array Index is out of bounds."]
case .wrongType:
return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]
case .notExist:
return [NSLocalizedDescriptionKey: "Dictionary key does not exist."]
case .invalidJSON:
return [NSLocalizedDescriptionKey: "JSON is invalid."]
case .elementTooDeep:
return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."]
}
}
}
// MARK: - JSON Type
/**
JSON's type definitions.
See http://www.json.org
*/
public enum Type: Int {
case number
case string
case bool
case array
case dictionary
case null
case unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `[]` by default.
- returns: The created JSON
*/
public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws {
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(jsonObject: object)
}
/**
Creates a JSON object
- note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)`
- parameter object: the object
- returns: the created JSON object
*/
public init(_ object: Any) {
switch object {
case let object as Data:
do {
try self.init(data: object)
} catch {
self.init(jsonObject: NSNull())
}
default:
self.init(jsonObject: object)
}
}
/**
Parses the JSON string into a JSON object
- parameter json: the JSON string
- returns: the created JSON object
*/
public init(parseJSON jsonString: String) {
if let data = jsonString.data(using: .utf8) {
self.init(data)
} else {
self.init(NSNull())
}
}
/**
Creates a JSON using the object.
- parameter jsonObject: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
fileprivate init(jsonObject: Any) {
object = jsonObject
}
/**
Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONs getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
*/
public mutating func merge(with other: JSON) throws {
try self.merge(with: other, typecheck: true)
}
/**
Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONS getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
- returns: New merged JSON
*/
public func merged(with other: JSON) throws -> JSON {
var merged = self
try merged.merge(with: other, typecheck: true)
return merged
}
/**
Private woker function which does the actual merging
Typecheck is set to true for the first recursion level to prevent total override of the source JSON
*/
fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws {
if type == other.type {
switch type {
case .dictionary:
for (key, _) in other {
try self[key].merge(with: other[key], typecheck: false)
}
case .array:
self = JSON(arrayValue + other.arrayValue)
default:
self = other
}
} else {
if typecheck {
throw SwiftyJSONError.wrongType
} else {
self = other
}
}
}
/// Private object
fileprivate var rawArray: [Any] = []
fileprivate var rawDictionary: [String: Any] = [:]
fileprivate var rawString: String = ""
fileprivate var rawNumber: NSNumber = 0
fileprivate var rawNull: NSNull = NSNull()
fileprivate var rawBool: Bool = false
/// JSON type, fileprivate setter
public fileprivate(set) var type: Type = .null
/// Error in JSON, fileprivate setter
public fileprivate(set) var error: SwiftyJSONError?
/// Object in JSON
public var object: Any {
get {
switch type {
case .array: return rawArray
case .dictionary: return rawDictionary
case .string: return rawString
case .number: return rawNumber
case .bool: return rawBool
default: return rawNull
}
}
set {
error = nil
switch unwrap(newValue) {
case let number as NSNumber:
if number.isBool {
type = .bool
rawBool = number.boolValue
} else {
type = .number
rawNumber = number
}
case let string as String:
type = .string
rawString = string
case _ as NSNull:
type = .null
case Optional<Any>.none:
type = .null
case let array as [Any]:
type = .array
rawArray = array
case let dictionary as [String: Any]:
type = .dictionary
rawDictionary = dictionary
default:
type = .unknown
error = SwiftyJSONError.unsupportedType
}
}
}
/// The static null JSON
@available(*, unavailable, renamed:"null")
public static var nullJSON: JSON { return null }
public static var null: JSON { return JSON(NSNull()) }
}
/// Private method to unwarp an object recursively
private func unwrap(_ object: Any) -> Any {
switch object {
case let json as JSON:
return unwrap(json.object)
case let array as [Any]:
return array.map(unwrap)
case let dictionary as [String: Any]:
var d = dictionary
dictionary.forEach { pair in
d[pair.key] = unwrap(pair.value)
}
return d
default:
return object
}
}
public enum Index<T: Any>: Comparable {
case array(Int)
case dictionary(DictionaryIndex<String, T>)
case null
static public func == (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)): return left == right
case (.dictionary(let left), .dictionary(let right)): return left == right
case (.null, .null): return true
default: return false
}
}
static public func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)): return left < right
case (.dictionary(let left), .dictionary(let right)): return left < right
default: return false
}
}
}
public typealias JSONIndex = Index<JSON>
public typealias JSONRawIndex = Index<Any>
extension JSON: Swift.Collection {
public typealias Index = JSONRawIndex
public var startIndex: Index {
switch type {
case .array: return .array(rawArray.startIndex)
case .dictionary: return .dictionary(rawDictionary.startIndex)
default: return .null
}
}
public var endIndex: Index {
switch type {
case .array: return .array(rawArray.endIndex)
case .dictionary: return .dictionary(rawDictionary.endIndex)
default: return .null
}
}
public func index(after i: Index) -> Index {
switch i {
case .array(let idx): return .array(rawArray.index(after: idx))
case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx))
default: return .null
}
}
public subscript (position: Index) -> (String, JSON) {
switch position {
case .array(let idx): return (String(idx), JSON(rawArray[idx]))
case .dictionary(let idx): return (rawDictionary[idx].key, JSON(rawDictionary[idx].value))
default: return ("", JSON.null)
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public enum JSONKey {
case index(Int)
case key(String)
}
public protocol JSONSubscriptType {
var jsonKey: JSONKey { get }
}
extension Int: JSONSubscriptType {
public var jsonKey: JSONKey {
return JSONKey.index(self)
}
}
extension String: JSONSubscriptType {
public var jsonKey: JSONKey {
return JSONKey.key(self)
}
}
extension JSON {
/// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error.
fileprivate subscript(index index: Int) -> JSON {
get {
if type != .array {
var r = JSON.null
r.error = self.error ?? SwiftyJSONError.wrongType
return r
} else if rawArray.indices.contains(index) {
return JSON(rawArray[index])
} else {
var r = JSON.null
r.error = SwiftyJSONError.indexOutOfBounds
return r
}
}
set {
if type == .array &&
rawArray.indices.contains(index) &&
newValue.error == nil {
rawArray[index] = newValue.object
}
}
}
/// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error.
fileprivate subscript(key key: String) -> JSON {
get {
var r = JSON.null
if type == .dictionary {
if let o = rawDictionary[key] {
r = JSON(o)
} else {
r.error = SwiftyJSONError.notExist
}
} else {
r.error = self.error ?? SwiftyJSONError.wrongType
}
return r
}
set {
if type == .dictionary && newValue.error == nil {
rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
fileprivate subscript(sub sub: JSONSubscriptType) -> JSON {
get {
switch sub.jsonKey {
case .index(let index): return self[index: index]
case .key(let key): return self[key: key]
}
}
set {
switch sub.jsonKey {
case .index(let index): self[index: index] = newValue
case .key(let key): self[key: key] = newValue
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
Example:
```
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
```
The same as: let name = json[9]["list"]["person"]["name"]
- parameter path: The target json's path.
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0: return
case 1: self[sub:path[0]].object = newValue.object
default:
var aPath = path
aPath.remove(at: 0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: Swift.ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: Swift.ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: Swift.ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: Swift.ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Any)...) {
let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1})
self.init(dictionary)
}
}
extension JSON: Swift.ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Any...) {
self.init(elements)
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: Any) {
if JSON(rawValue).type == .unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: Any {
return object
}
public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data {
guard JSONSerialization.isValidJSONObject(object) else {
throw SwiftyJSONError.invalidJSON
}
return try JSONSerialization.data(withJSONObject: object, options: opt)
}
public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? {
do {
return try _rawString(encoding, options: [.jsonSerialization: opt])
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
public func rawString(_ options: [writingOptionsKeys: Any]) -> String? {
let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8
let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10
do {
return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth)
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? {
guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON }
switch type {
case .dictionary:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let dict = object as? [String: Any?] else {
return nil
}
let body = try dict.keys.map { key throws -> String in
guard let value = dict[key] else {
return "\"\(key)\": null"
}
guard let unwrappedValue = value else {
return "\"\(key)\": null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw SwiftyJSONError.elementTooDeep
}
if nestedValue.type == .string {
return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return "\"\(key)\": \(nestedString)"
}
}
return "{\(body.joined(separator: ","))}"
} catch _ {
return nil
}
case .array:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let array = object as? [Any?] else {
return nil
}
let body = try array.map { value throws -> String in
guard let unwrappedValue = value else {
return "null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw SwiftyJSONError.invalidJSON
}
if nestedValue.type == .string {
return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return nestedString
}
}
return "[\(body.joined(separator: ","))]"
} catch _ {
return nil
}
case .string: return rawString
case .number: return rawNumber.stringValue
case .bool: return rawBool.description
case .null: return "null"
default: return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible {
public var description: String {
return rawString(options: .prettyPrinted) ?? "unknown"
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
return type == .array ? rawArray.map { JSON($0) } : nil
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
return self.array ?? []
}
//Optional [Any]
public var arrayObject: [Any]? {
get {
switch type {
case .array: return rawArray
default: return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String: JSON]? {
if type == .dictionary {
var d = [String: JSON](minimumCapacity: rawDictionary.count)
rawDictionary.forEach { pair in
d[pair.key] = JSON(pair.value)
}
return d
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String: JSON] {
return dictionary ?? [:]
}
//Optional [String : Any]
public var dictionaryObject: [String: Any]? {
get {
switch type {
case .dictionary: return rawDictionary
default: return nil
}
}
set {
object = newValue ?? NSNull()
}
}
}
// MARK: - Bool
extension JSON { // : Swift.Bool
//Optional bool
public var bool: Bool? {
get {
switch type {
case .bool: return rawBool
default: return nil
}
}
set {
object = newValue ?? NSNull()
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch type {
case .bool: return rawBool
case .number: return rawNumber.boolValue
case .string: return ["true", "y", "t", "yes", "1"].contains { rawString.caseInsensitiveCompare($0) == .orderedSame }
default: return false
}
}
set {
object = newValue
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch type {
case .string: return object as? String
default: return nil
}
}
set {
object = newValue ?? NSNull()
}
}
//Non-optional string
public var stringValue: String {
get {
switch type {
case .string: return object as? String ?? ""
case .number: return rawNumber.stringValue
case .bool: return (object as? Bool).map { String($0) } ?? ""
default: return ""
}
}
set {
object = newValue
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch type {
case .number: return rawNumber
case .bool: return NSNumber(value: rawBool ? 1 : 0)
default: return nil
}
}
set {
object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch type {
case .string:
let decimal = NSDecimalNumber(string: object as? String)
return decimal == .notANumber ? .zero : decimal
case .number: return object as? NSNumber ?? NSNumber(value: 0)
case .bool: return NSNumber(value: rawBool ? 1 : 0)
default: return NSNumber(value: 0.0)
}
}
set {
object = newValue
}
}
}
// MARK: - Null
extension JSON {
public var null: NSNull? {
set {
object = NSNull()
}
get {
switch type {
case .null: return rawNull
default: return nil
}
}
}
public func exists() -> Bool {
if let errorValue = error, (400...1000).contains(errorValue.errorCode) {
return false
}
return true
}
}
// MARK: - URL
extension JSON {
//Optional URL
public var url: URL? {
get {
switch type {
case .string:
// Check for existing percent escapes first to prevent double-escaping of % character
if rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil {
return Foundation.URL(string: rawString)
} else if let encodedString_ = rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
// We have to use `Foundation.URL` otherwise it conflicts with the variable name.
return Foundation.URL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return number?.doubleValue
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return numberValue.doubleValue
}
set {
object = NSNumber(value: newValue)
}
}
public var float: Float? {
get {
return number?.floatValue
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var floatValue: Float {
get {
return numberValue.floatValue
}
set {
object = NSNumber(value: newValue)
}
}
public var int: Int? {
get {
return number?.intValue
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var intValue: Int {
get {
return numberValue.intValue
}
set {
object = NSNumber(value: newValue)
}
}
public var uInt: UInt? {
get {
return number?.uintValue
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return numberValue.uintValue
}
set {
object = NSNumber(value: newValue)
}
}
public var int8: Int8? {
get {
return number?.int8Value
}
set {
if let newValue = newValue {
object = NSNumber(value: Int(newValue))
} else {
object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return numberValue.int8Value
}
set {
object = NSNumber(value: Int(newValue))
}
}
public var uInt8: UInt8? {
get {
return number?.uint8Value
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return numberValue.uint8Value
}
set {
object = NSNumber(value: newValue)
}
}
public var int16: Int16? {
get {
return number?.int16Value
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return numberValue.int16Value
}
set {
object = NSNumber(value: newValue)
}
}
public var uInt16: UInt16? {
get {
return number?.uint16Value
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return numberValue.uint16Value
}
set {
object = NSNumber(value: newValue)
}
}
public var int32: Int32? {
get {
return number?.int32Value
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return numberValue.int32Value
}
set {
object = NSNumber(value: newValue)
}
}
public var uInt32: UInt32? {
get {
return number?.uint32Value
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return numberValue.uint32Value
}
set {
object = NSNumber(value: newValue)
}
}
public var int64: Int64? {
get {
return number?.int64Value
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return numberValue.int64Value
}
set {
object = NSNumber(value: newValue)
}
}
public var uInt64: UInt64? {
get {
return number?.uint64Value
}
set {
if let newValue = newValue {
object = NSNumber(value: newValue)
} else {
object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return numberValue.uint64Value
}
set {
object = NSNumber(value: newValue)
}
}
}
// MARK: - Comparable
extension JSON: Swift.Comparable {}
public func == (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number): return lhs.rawNumber == rhs.rawNumber
case (.string, .string): return lhs.rawString == rhs.rawString
case (.bool, .bool): return lhs.rawBool == rhs.rawBool
case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null): return true
default: return false
}
}
public func <= (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number): return lhs.rawNumber <= rhs.rawNumber
case (.string, .string): return lhs.rawString <= rhs.rawString
case (.bool, .bool): return lhs.rawBool == rhs.rawBool
case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null): return true
default: return false
}
}
public func >= (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number): return lhs.rawNumber >= rhs.rawNumber
case (.string, .string): return lhs.rawString >= rhs.rawString
case (.bool, .bool): return lhs.rawBool == rhs.rawBool
case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null): return true
default: return false
}
}
public func > (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number): return lhs.rawNumber > rhs.rawNumber
case (.string, .string): return lhs.rawString > rhs.rawString
default: return false
}
}
public func < (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number): return lhs.rawNumber < rhs.rawNumber
case (.string, .string): return lhs.rawString < rhs.rawString
default: return false
}
}
private let trueNumber = NSNumber(value: true)
private let falseNumber = NSNumber(value: false)
private let trueObjCType = String(cString: trueNumber.objCType)
private let falseObjCType = String(cString: falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber {
fileprivate var isBool: Bool {
let objCType = String(cString: self.objCType)
if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) {
return true
} else {
return false
}
}
}
func == (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) == .orderedSame
}
}
func != (lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
func < (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) == .orderedAscending
}
}
func > (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) == ComparisonResult.orderedDescending
}
}
func <= (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) != .orderedDescending
}
}
func >= (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) != .orderedAscending
}
}
public enum writingOptionsKeys {
case jsonSerialization
case castNilToNSNull
case maxObjextDepth
case encoding
}
// MARK: - JSON: Codable
extension JSON: Codable {
private static var codableTypes: [Codable.Type] {
return [
Bool.self,
Int.self,
Int8.self,
Int16.self,
Int32.self,
Int64.self,
UInt.self,
UInt8.self,
UInt16.self,
UInt32.self,
UInt64.self,
Double.self,
String.self,
[JSON].self,
[String: JSON].self
]
}
public init(from decoder: Decoder) throws {
var object: Any?
if let container = try? decoder.singleValueContainer(), !container.decodeNil() {
for type in JSON.codableTypes {
if object != nil {
break
}
// try to decode value
switch type {
case let boolType as Bool.Type:
object = try? container.decode(boolType)
case let intType as Int.Type:
object = try? container.decode(intType)
case let int8Type as Int8.Type:
object = try? container.decode(int8Type)
case let int32Type as Int32.Type:
object = try? container.decode(int32Type)
case let int64Type as Int64.Type:
object = try? container.decode(int64Type)
case let uintType as UInt.Type:
object = try? container.decode(uintType)
case let uint8Type as UInt8.Type:
object = try? container.decode(uint8Type)
case let uint16Type as UInt16.Type:
object = try? container.decode(uint16Type)
case let uint32Type as UInt32.Type:
object = try? container.decode(uint32Type)
case let uint64Type as UInt64.Type:
object = try? container.decode(uint64Type)
case let doubleType as Double.Type:
object = try? container.decode(doubleType)
case let stringType as String.Type:
object = try? container.decode(stringType)
case let jsonValueArrayType as [JSON].Type:
object = try? container.decode(jsonValueArrayType)
case let jsonValueDictType as [String: JSON].Type:
object = try? container.decode(jsonValueDictType)
default:
break
}
}
}
self.init(object ?? NSNull())
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if object is NSNull {
try container.encodeNil()
return
}
switch object {
case let intValue as Int:
try container.encode(intValue)
case let int8Value as Int8:
try container.encode(int8Value)
case let int32Value as Int32:
try container.encode(int32Value)
case let int64Value as Int64:
try container.encode(int64Value)
case let uintValue as UInt:
try container.encode(uintValue)
case let uint8Value as UInt8:
try container.encode(uint8Value)
case let uint16Value as UInt16:
try container.encode(uint16Value)
case let uint32Value as UInt32:
try container.encode(uint32Value)
case let uint64Value as UInt64:
try container.encode(uint64Value)
case let doubleValue as Double:
try container.encode(doubleValue)
case let boolValue as Bool:
try container.encode(boolValue)
case let stringValue as String:
try container.encode(stringValue)
case is [Any]:
let jsonValueArray = array ?? []
try container.encode(jsonValueArray)
case is [String: Any]:
let jsonValueDictValue = dictionary ?? [:]
try container.encode(jsonValueDictValue)
default:
break
}
}
}
| b21e2965363c309152da3ab40256dc1c | 27.828694 | 266 | 0.554483 | false | false | false | false |
Eonil/Editor | refs/heads/develop | Editor4/FileNavigatorMenuPalette.swift | mit | 1 | //
// FileNavigatorMenuPalette.swift
// Editor4
//
// Created by Hoon H. on 2016/05/25.
// Copyright © 2016 Eonil. All rights reserved.
//
import AppKit
struct FileNavigatorMenuPalette {
let context = MenuItemController(type: MenuItemTypeID.Submenu(.FileNavigator(.ContextMenuRoot)))
let showInFinder = menuItemWithAction(.showInFinder)
let showInTerminal = menuItemWithAction(.showInTerminal)
let createNewFolder = menuItemWithAction(.createNewFolder)
let createNewFile = menuItemWithAction(.createNewFile)
let delete = menuItemWithAction(.delete)
init() {
// Configure hierarchy here if needed.
context.subcontrollers = [
showInFinder,
showInTerminal,
separator(),
createNewFolder,
createNewFile,
separator(),
delete,
]
}
}
private func separator() -> MenuItemController {
return MenuItemController(type: .Separator)
}
//private func submenuContainerWithTitle(mainMenuSubmenuID: MainMenuSubmenuID) -> MenuItemController {
// let submenuID = FileNavigator(mainMenuSubmenuID)
// return MenuItemController(type: .Submenu(submenuID))
//}
private func menuItemWithAction(mainMenuCommand: FileNavigatorMenuCommand) -> MenuItemController {
let command = MenuCommand.fileNavigator(mainMenuCommand)
return MenuItemController(type: .MenuItem(command))
}
| b053fc8bce5ab700fe3a616b1e1830b5 | 34.883721 | 126 | 0.650032 | false | false | false | false |
dschwartz783/MandelbrotSet | refs/heads/master | Sources/MandelbrotSet/main.swift | gpl-3.0 | 1 | //
// main.swift
// MandelbrotSet
//
// Created by David Schwartz on 6/4/17.
// Copyright © 2017 DDS Programming. All rights reserved.
//
import Cocoa
class MandelbrotDrawClass {
let maxIterations = 50000
var Ox: Float80 = -2 {
willSet {
print("old Ox: \(Ox)")
}
didSet {
print("new Ox: \(Ox)")
}
}
var Oy: Float80 = -2 {
willSet {
print("old Oy: \(Oy)")
}
didSet {
print("new Oy: \(Oy)")
}
}
var Lx: Float80 = 4 {
willSet {
print("old Lx: \(Lx)")
}
didSet {
print("new Lx: \(Lx)")
}
}
var Ly: Float80 = 4 {
willSet {
print("old Ly: \(Ly)")
}
didSet {
print("new Ly: \(Ly)")
}
}
// let height = Int(ProcessInfo.processInfo.arguments[1]) ?? 1000
// let width = Int(ProcessInfo.processInfo.arguments[1]) ?? 1000
let rect: CGRect
var randomColorList: [Int: NSColor] = [:]
let saveThread = DispatchQueue(label: "savethread")
let cgContext = CGDisplayGetDrawingContext(CGMainDisplayID())!
let newContext: NSGraphicsContext
let drawQueue = DispatchQueue(label: "drawQueue")
init() {
for i in 0...maxIterations {
self.randomColorList[i] = NSColor(
calibratedRed: CGFloat(arc4random()) / CGFloat(UInt32.max),
green: CGFloat(arc4random()) / CGFloat(UInt32.max),
blue: CGFloat(arc4random()) / CGFloat(UInt32.max),
alpha: CGFloat(arc4random()) / CGFloat(UInt32.max))
}
newContext = NSGraphicsContext(cgContext: cgContext, flipped: false)
rect = CGDisplayBounds(CGMainDisplayID())
self.Ox = -(Lx / 2) * Float80(rect.width) / Float80(rect.height)
self.Lx = Ly * Float80(rect.width) / Float80(rect.height)
NSGraphicsContext.current = newContext
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "draw"), object: nil, queue: nil) { (aNotification) in
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "zoomDec"), object: nil, queue: nil) { (aNotification) in
self.Ox -= self.Lx / 2
self.Oy -= self.Ly / 2
self.Lx *= 2
self.Ly *= 2
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "zoomInc"), object: nil, queue: nil) { (aNotification) in
self.Ox += self.Lx / 4
self.Oy += self.Ly / 4
self.Lx /= 2
self.Ly /= 2
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetDecX"), object: nil, queue: nil) { (aNotification) in
self.Ox -= self.Lx / 4
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetIncX"), object: nil, queue: nil) { (aNotification) in
self.Ox += self.Lx / 4
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetDecY"), object: nil, queue: nil) { (aNotification) in
self.Oy -= self.Ly / 4
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetIncY"), object: nil, queue: nil) { (aNotification) in
self.Oy += self.Ly / 4
self.draw()
}
}
func draw() {
self.drawQueue.async {
autoreleasepool {
let offscreenRep = NSBitmapImageRep(
bitmapDataPlanes:nil,
pixelsWide:Int(self.rect.width),
pixelsHigh:Int(self.rect.height),
bitsPerSample:8,
samplesPerPixel:4,
hasAlpha:true,
isPlanar:false,
colorSpaceName:NSColorSpaceName.deviceRGB,
bitmapFormat:NSBitmapImageRep.Format.alphaFirst,
bytesPerRow:0,
bitsPerPixel:0
)!
let context = NSGraphicsContext(bitmapImageRep: offscreenRep)!
// NSGraphicsContext.current = context
let image = context.cgContext.makeImage()!
let nsImage = NSImage(cgImage: image, size: self.rect.size)
var rawTiff = nsImage.tiffRepresentation!
let bytes = rawTiff.withUnsafeMutableBytes { $0 }
DispatchQueue.concurrentPerform(iterations: Int(self.rect.width)) { (x) in
for y in 0..<Int(self.rect.height) {
let calcX = self.Ox + Float80(x) / Float80(self.rect.width) * self.Lx
let calcY = self.Oy + Float80(y) / Float80(self.rect.height) * self.Ly
let iterations = Mandelbrot.calculate(
x: calcX,
y: calcY,
i: self.maxIterations
)
let color = self.randomColorList[iterations]!
bytes[8 + 4 * (y * Int(self.rect.width) + x)] = UInt8(color.redComponent * CGFloat(UInt8.max))
bytes[9 + 4 * (y * Int(self.rect.width) + x)] = UInt8(color.greenComponent * CGFloat(UInt8.max))
bytes[10 + 4 * (y * Int(self.rect.width) + x)] = UInt8(color.blueComponent * CGFloat(UInt8.max))
bytes[11 + 4 * (y * Int(self.rect.width) + x)] = 0xff
}
}
let resultImage = NSImage(data: rawTiff)
DispatchQueue.main.sync {
resultImage?.draw(in: self.rect)
}
}
}
}
}
CGDisplayCapture(CGMainDisplayID())
let drawObject = MandelbrotDrawClass()
drawObject.draw()
RunLoop.current.add(generateKeyTracker(), forMode: .default)
RunLoop.current.run()
| 6f5298abb431ac657f326acb6cd2d54d | 34.259459 | 146 | 0.503143 | false | false | false | false |
PureSwift/Bluetooth | refs/heads/master | Sources/BluetoothHCI/HCILEReadResolvingListSize.swift | mit | 1 | //
// HCILEReadResolvingListSize.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/15/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// LE Read Resolving List Size Command
///
/// This command is used to read the total number of address translation
/// entries in the resolving list that can be stored in the Controller.
func lowEnergyReadResolvingListSize(timeout: HCICommandTimeout = .default) async throws -> UInt8 {
let value = try await deviceRequest(HCILEReadResolvingListSize.self,
timeout: timeout)
return value.resolvingListSize
}
}
// MARK: - Return parameter
/// LE Read Resolving List Size Command
///
/// The command is used to read the total number of address translation entries
/// in the resolving list that can be stored in the Controller.
/// Note: The number of entries that can be stored is not fixed and
/// the Controller can change it at any time (e.g. because the memory
/// used to store the list can also be used for other purposes).
@frozen
public struct HCILEReadResolvingListSize: HCICommandReturnParameter {
public static let command = HCILowEnergyCommand.readResolvedListSize //0x002A
public static let length: Int = 1
public let resolvingListSize: UInt8 //Resolving_List_Size
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
self.resolvingListSize = data[0]
}
}
| 59e4fc7de15864eff6aecbcb04b94871 | 30.018868 | 102 | 0.677616 | false | false | false | false |
avito-tech/Marshroute | refs/heads/master | Example/NavigationDemo/VIPER/Advertisement/View/AdvertisementViewController.swift | mit | 1 | import UIKit
import Marshroute
final class AdvertisementViewController: BasePeekAndPopViewController, AdvertisementViewInput {
// MARK: - Private properties
private let advertisementView = AdvertisementView()
private let peekAndPopStateViewControllerObservable: PeekAndPopStateViewControllerObservable
// MARK: - Init
init(
peekAndPopStateViewControllerObservable: PeekAndPopStateViewControllerObservable,
peekAndPopUtility: PeekAndPopUtility)
{
self.peekAndPopStateViewControllerObservable = peekAndPopStateViewControllerObservable
super.init(peekAndPopUtility: peekAndPopUtility)
subscribeForPeekAndPopStateChanges()
}
// MARK: - Lifecycle
override func loadView() {
view = advertisementView
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "recursion".localized, // to Recursion module
style: .plain,
target: self,
action: #selector(onRecursionButtonTap(_:))
)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
advertisementView.defaultContentInsets = defaultContentInsets
}
// MARK: - BasePeekAndPopViewController
override var peekSourceViews: [UIView] {
return advertisementView.peekSourceViews + [navigationController?.navigationBar].compactMap { $0 }
}
@available(iOS 9.0, *)
override func startPeekWith(
previewingContext: UIViewControllerPreviewing,
location: CGPoint)
{
if advertisementView.peekSourceViews.contains(previewingContext.sourceView) {
if let peekData = advertisementView.peekDataAt(
location: location,
sourceView: previewingContext.sourceView)
{
previewingContext.sourceRect = peekData.sourceRect
peekData.viewData.onTap()
}
} else {
super.startPeekWith(
previewingContext: previewingContext,
location: location
)
}
}
// MARK: - Private
@objc private func onRecursionButtonTap(_ sender: UIBarButtonItem) {
onRecursionButtonTap?(sender)
}
private func subscribeForPeekAndPopStateChanges() {
peekAndPopStateViewControllerObservable.addObserver(
disposableViewController: self,
onPeekAndPopStateChange: { [weak self] peekAndPopState in
switch peekAndPopState {
case .inPeek:
self?.onPeek?()
case .popped:
self?.onPop?()
case .interrupted:
break
}
}
)
}
// MARK: - AdvertisementViewInput
@nonobjc func setTitle(_ title: String?) {
self.title = title
}
func setPatternAssetName(_ assetName: String?) {
advertisementView.setPatternAssetName(assetName)
}
func setPlaceholderAssetName(_ assetName: String?) {
advertisementView.setPlaceholderAssetName(assetName)
}
func setBackgroundRGB(_ rgb: (red: Double, green: Double, blue: Double)?) {
advertisementView.setBackgroundRGB(rgb)
}
func setSimilarSearchResults(_ searchResults: [SearchResultsViewData]) {
advertisementView.setSimilarSearchResults(searchResults)
}
func setSimilarSearchResultsHidden(_ hidden: Bool) {
advertisementView.setSimilarSearchResultsHidden(hidden)
}
var onRecursionButtonTap: ((_ sender: AnyObject) -> ())?
var onPeek: (() -> ())?
var onPop: (() -> ())?
}
| 4b4f213f64cef21f5661aae4d6b238d7 | 30.719008 | 106 | 0.621678 | false | false | false | false |
groue/GRDB.swift | refs/heads/master | Tests/CombineExpectations/Recorder.swift | mit | 1 | #if canImport(Combine)
import Combine
import XCTest
/// A Combine subscriber which records all events published by a publisher.
///
/// You create a Recorder with the `Publisher.record()` method:
///
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
///
/// You can build publisher expectations from the Recorder. For example:
///
/// let elements = try wait(for: recorder.elements, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public class Recorder<Input, Failure: Error>: Subscriber {
public typealias Input = Input
public typealias Failure = Failure
private enum RecorderExpectation {
case onInput(XCTestExpectation, remainingCount: Int)
case onCompletion(XCTestExpectation)
var expectation: XCTestExpectation {
switch self {
case let .onCompletion(expectation):
return expectation
case let .onInput(expectation, remainingCount: _):
return expectation
}
}
}
/// The recorder state
private enum State {
/// Publisher is not subscribed yet. The recorder may have an
/// expectation to fulfill.
case waitingForSubscription(RecorderExpectation?)
/// Publisher is subscribed. The recorder may have an expectation to
/// fulfill. It keeps track of all published elements.
case subscribed(Subscription, RecorderExpectation?, [Input])
/// Publisher is completed. The recorder keeps track of all published
/// elements and completion.
case completed([Input], Subscribers.Completion<Failure>)
var elementsAndCompletion: (elements: [Input], completion: Subscribers.Completion<Failure>?) {
switch self {
case .waitingForSubscription:
return (elements: [], completion: nil)
case let .subscribed(_, _, elements):
return (elements: elements, completion: nil)
case let .completed(elements, completion):
return (elements: elements, completion: completion)
}
}
var recorderExpectation: RecorderExpectation? {
switch self {
case let .waitingForSubscription(exp), let .subscribed(_, exp, _):
return exp
case .completed:
return nil
}
}
}
private let lock = NSLock()
private var state = State.waitingForSubscription(nil)
private var consumedCount = 0
/// The elements and completion recorded so far.
var elementsAndCompletion: (elements: [Input], completion: Subscribers.Completion<Failure>?) {
synchronized {
state.elementsAndCompletion
}
}
/// Use Publisher.record()
fileprivate init() { }
deinit {
if case let .subscribed(subscription, _, _) = state {
subscription.cancel()
}
}
private func synchronized<T>(_ execute: () throws -> T) rethrows -> T {
lock.lock()
defer { lock.unlock() }
return try execute()
}
// MARK: - PublisherExpectation API
/// Registers the expectation so that it gets fulfilled when publisher
/// publishes elements or completes.
///
/// - parameter expectation: An XCTestExpectation.
/// - parameter includingConsumed: This flag controls how elements that were
/// already published at the time this method is called fulfill the
/// expectation. If true, all published elements fulfill the expectation.
/// If false, only published elements that are not consumed yet fulfill
/// the expectation. For example, the Prefix expectation uses true, but
/// the NextOne expectation uses false.
func fulfillOnInput(_ expectation: XCTestExpectation, includingConsumed: Bool) {
synchronized {
preconditionCanFulfillExpectation()
let expectedFulfillmentCount = expectation.expectedFulfillmentCount
switch state {
case .waitingForSubscription:
let exp = RecorderExpectation.onInput(expectation, remainingCount: expectedFulfillmentCount)
state = .waitingForSubscription(exp)
case let .subscribed(subscription, _, elements):
let maxFulfillmentCount = includingConsumed
? elements.count
: elements.count - consumedCount
let fulfillmentCount = min(expectedFulfillmentCount, maxFulfillmentCount)
expectation.fulfill(count: fulfillmentCount)
let remainingCount = expectedFulfillmentCount - fulfillmentCount
if remainingCount > 0 {
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount)
state = .subscribed(subscription, exp, elements)
}
case .completed:
expectation.fulfill(count: expectedFulfillmentCount)
}
}
}
/// Registers the expectation so that it gets fulfilled when
/// publisher completes.
func fulfillOnCompletion(_ expectation: XCTestExpectation) {
synchronized {
preconditionCanFulfillExpectation()
switch state {
case .waitingForSubscription:
let exp = RecorderExpectation.onCompletion(expectation)
state = .waitingForSubscription(exp)
case let .subscribed(subscription, _, elements):
let exp = RecorderExpectation.onCompletion(expectation)
state = .subscribed(subscription, exp, elements)
case .completed:
expectation.fulfill()
}
}
}
/// Returns a value based on the recorded state of the publisher.
///
/// - parameter value: A function which returns the value, given the
/// recorded state of the publisher.
/// - parameter elements: All recorded elements.
/// - parameter completion: The eventual publisher completion.
/// - parameter remainingElements: The elements that were not consumed yet.
/// - parameter consume: A function which consumes elements.
/// - parameter count: The number of consumed elements.
/// - returns: The value
func value<T>(_ value: (
_ elements: [Input],
_ completion: Subscribers.Completion<Failure>?,
_ remainingElements: ArraySlice<Input>,
_ consume: (_ count: Int) -> ()) throws -> T)
rethrows -> T
{
try synchronized {
let (elements, completion) = state.elementsAndCompletion
let remainingElements = elements[consumedCount...]
return try value(elements, completion, remainingElements, { count in
precondition(count >= 0)
precondition(count <= remainingElements.count)
consumedCount += count
})
}
}
/// Checks that recorder can fulfill an expectation.
///
/// The reason this method exists is that a recorder can fulfill a single
/// expectation at a given time. It is a programmer error to wait for two
/// expectations concurrently.
///
/// This method MUST be called within a synchronized block.
private func preconditionCanFulfillExpectation() {
if let exp = state.recorderExpectation {
// We are already waiting for an expectation! Is it a programmer
// error? Recorder drops references to non-inverted expectations
// when they are fulfilled. But inverted expectations are not
// fulfilled, and thus not dropped. We can't quite know if an
// inverted expectations has expired yet, so just let it go.
precondition(exp.expectation.isInverted, "Already waiting for an expectation")
}
}
// MARK: - Subscriber
public func receive(subscription: Subscription) {
synchronized {
switch state {
case let .waitingForSubscription(exp):
state = .subscribed(subscription, exp, [])
default:
XCTFail("Publisher recorder is already subscribed")
}
}
subscription.request(.unlimited)
}
public func receive(_ input: Input) -> Subscribers.Demand {
return synchronized {
switch state {
case let .subscribed(subscription, exp, elements):
var elements = elements
elements.append(input)
if case let .onInput(expectation, remainingCount: remainingCount) = exp {
assert(remainingCount > 0)
expectation.fulfill()
if remainingCount > 1 {
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount - 1)
state = .subscribed(subscription, exp, elements)
} else {
state = .subscribed(subscription, nil, elements)
}
} else {
state = .subscribed(subscription, exp, elements)
}
return .unlimited
case .waitingForSubscription:
XCTFail("Publisher recorder got unexpected input before subscription: \(String(reflecting: input))")
return .none
case .completed:
XCTFail("Publisher recorder got unexpected input after completion: \(String(reflecting: input))")
return .none
}
}
}
public func receive(completion: Subscribers.Completion<Failure>) {
synchronized {
switch state {
case let .subscribed(_, exp, elements):
if let exp = exp {
switch exp {
case let .onCompletion(expectation):
expectation.fulfill()
case let .onInput(expectation, remainingCount: remainingCount):
expectation.fulfill(count: remainingCount)
}
}
state = .completed(elements, completion)
case .waitingForSubscription:
XCTFail("Publisher recorder got unexpected completion before subscription: \(String(describing: completion))")
case .completed:
XCTFail("Publisher recorder got unexpected completion after completion: \(String(describing: completion))")
}
}
}
}
// MARK: - Publisher Expectations
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension PublisherExpectations {
/// The type of the publisher expectation returned by `Recorder.completion`.
public typealias Completion<Input, Failure: Error> = Map<Recording<Input, Failure>, Subscribers.Completion<Failure>>
/// The type of the publisher expectation returned by `Recorder.elements`.
public typealias Elements<Input, Failure: Error> = Map<Recording<Input, Failure>, [Input]>
/// The type of the publisher expectation returned by `Recorder.last`.
public typealias Last<Input, Failure: Error> = Map<Elements<Input, Failure>, Input?>
/// The type of the publisher expectation returned by `Recorder.single`.
public typealias Single<Input, Failure: Error> = Map<Elements<Input, Failure>, Input>
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension Recorder {
/// Returns a publisher expectation which waits for the timeout to expire,
/// or the recorded publisher to complete.
///
/// When waiting for this expectation, the publisher error is thrown if
/// the publisher fails before the expectation has expired.
///
/// Otherwise, an array of all elements published before the expectation
/// has expired is returned.
///
/// Unlike other expectations, `availableElements` does not make a test fail
/// on timeout expiration. It just returns the elements published so far.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testTimerPublishesIncreasingDates() throws {
/// let publisher = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()
/// let recorder = publisher.record()
/// let dates = try wait(for: recorder.availableElements, timeout: ...)
/// XCTAssertEqual(dates.sorted(), dates)
/// }
public var availableElements: PublisherExpectations.AvailableElements<Input, Failure> {
PublisherExpectations.AvailableElements(recorder: self)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError.notCompleted is
/// thrown if the publisher does not complete on time.
///
/// Otherwise, a [Subscribers.Completion](https://developer.apple.com/documentation/combine/subscribers/completion)
/// is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherCompletesWithSuccess() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let completion = try wait(for: recorder.completion, timeout: 1)
/// if case let .failure(error) = completion {
/// XCTFail("Unexpected error \(error)")
/// }
/// }
public var completion: PublisherExpectations.Completion<Input, Failure> {
recording.map { $0.completion }
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError.notCompleted is
/// thrown if the publisher does not complete on time, and the publisher
/// error is thrown if the publisher fails.
///
/// Otherwise, an array of published elements is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherPublishesArrayElements() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let elements = try wait(for: recorder.elements, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
/// }
public var elements: PublisherExpectations.Elements<Input, Failure> {
recording.map { recording in
if case let .failure(error) = recording.completion {
throw error
}
return recording.output
}
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, the publisher error is thrown if the
/// publisher fails.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherFinishesWithoutError() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// try wait(for: recorder.finished, timeout: 1)
/// }
///
/// This publisher expectation can be inverted:
///
/// // SUCCESS: no timeout, no error
/// func testPassthroughSubjectDoesNotFinish() throws {
/// let publisher = PassthroughSubject<String, Never>()
/// let recorder = publisher.record()
/// try wait(for: recorder.finished.inverted, timeout: 1)
/// }
public var finished: PublisherExpectations.Finished<Input, Failure> {
PublisherExpectations.Finished(recorder: self)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError.notCompleted is
/// thrown if the publisher does not complete on time, and the publisher
/// error is thrown if the publisher fails.
///
/// Otherwise, the last published element is returned, or nil if the publisher
/// completes before it publishes any element.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherPublishesLastElementLast() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// if let element = try wait(for: recorder.last, timeout: 1) {
/// XCTAssertEqual(element, "baz")
/// } else {
/// XCTFail("Expected one element")
/// }
/// }
public var last: PublisherExpectations.Last<Input, Failure> {
elements.map { $0.last }
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to emit one element, or to complete.
///
/// When waiting for this expectation, a `RecordingError.notEnoughElements`
/// is thrown if the publisher does not publish one element after last
/// waited expectation. The publisher error is thrown if the publisher fails
/// before publishing the next element.
///
/// Otherwise, the next published element is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayOfTwoElementsPublishesElementsInOrder() throws {
/// let publisher = ["foo", "bar"].publisher
/// let recorder = publisher.record()
///
/// var element = try wait(for: recorder.next(), timeout: 1)
/// XCTAssertEqual(element, "foo")
///
/// element = try wait(for: recorder.next(), timeout: 1)
/// XCTAssertEqual(element, "bar")
/// }
public func next() -> PublisherExpectations.NextOne<Input, Failure> {
PublisherExpectations.NextOne(recorder: self)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to emit `count` elements, or to complete.
///
/// When waiting for this expectation, a `RecordingError.notEnoughElements`
/// is thrown if the publisher does not publish `count` elements after last
/// waited expectation. The publisher error is thrown if the publisher fails
/// before publishing the next `count` elements.
///
/// Otherwise, an array of exactly `count` elements is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayOfThreeElementsPublishesTwoThenOneElement() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
///
/// var elements = try wait(for: recorder.next(2), timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar"])
///
/// elements = try wait(for: recorder.next(1), timeout: 1)
/// XCTAssertEqual(elements, ["baz"])
/// }
///
/// - parameter count: The number of elements.
public func next(_ count: Int) -> PublisherExpectations.Next<Input, Failure> {
PublisherExpectations.Next(recorder: self, count: count)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to emit `maxLength` elements, or to complete.
///
/// When waiting for this expectation, the publisher error is thrown if the
/// publisher fails before `maxLength` elements are published.
///
/// Otherwise, an array of received elements is returned, containing at
/// most `maxLength` elements, or less if the publisher completes early.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayOfThreeElementsPublishesTwoFirstElementsWithoutError() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let elements = try wait(for: recorder.prefix(2), timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar"])
/// }
///
/// This publisher expectation can be inverted:
///
/// // SUCCESS: no timeout, no error
/// func testPassthroughSubjectPublishesNoMoreThanSentValues() throws {
/// let publisher = PassthroughSubject<String, Never>()
/// let recorder = publisher.record()
/// publisher.send("foo")
/// publisher.send("bar")
/// let elements = try wait(for: recorder.prefix(3).inverted, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar"])
/// }
///
/// - parameter maxLength: The maximum number of elements.
public func prefix(_ maxLength: Int) -> PublisherExpectations.Prefix<Input, Failure> {
PublisherExpectations.Prefix(recorder: self, maxLength: maxLength)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError.notCompleted is
/// thrown if the publisher does not complete on time.
///
/// Otherwise, a [Record.Recording](https://developer.apple.com/documentation/combine/record/recording)
/// is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherRecording() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let recording = try wait(for: recorder.recording, timeout: 1)
/// XCTAssertEqual(recording.output, ["foo", "bar", "baz"])
/// if case let .failure(error) = recording.completion {
/// XCTFail("Unexpected error \(error)")
/// }
/// }
public var recording: PublisherExpectations.Recording<Input, Failure> {
PublisherExpectations.Recording(recorder: self)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError is thrown if the
/// publisher does not complete on time, or does not publish exactly one
/// element before it completes. The publisher error is thrown if the
/// publisher fails.
///
/// Otherwise, the single published element is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testJustPublishesExactlyOneElement() throws {
/// let publisher = Just("foo")
/// let recorder = publisher.record()
/// let element = try wait(for: recorder.single, timeout: 1)
/// XCTAssertEqual(element, "foo")
/// }
public var single: PublisherExpectations.Single<Input, Failure> {
elements.map { elements in
guard let element = elements.first else {
throw RecordingError.notEnoughElements
}
if elements.count > 1 {
throw RecordingError.tooManyElements
}
return element
}
}
}
// MARK: - Publisher + Recorder
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension Publisher {
/// Returns a subscribed Recorder.
///
/// For example:
///
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
///
/// You can build publisher expectations from the Recorder. For example:
///
/// let elements = try wait(for: recorder.elements, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
public func record() -> Recorder<Output, Failure> {
let recorder = Recorder<Output, Failure>()
subscribe(recorder)
return recorder
}
}
// MARK: - Convenience
extension XCTestExpectation {
fileprivate func fulfill(count: Int) {
for _ in 0..<count {
fulfill()
}
}
}
#endif
| 2cbfb5d7ec3a2a910c609846276da165 | 39.512397 | 126 | 0.596328 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Stats/Helpers/BottomScrollAnalyticsTracker.swift | gpl-2.0 | 1 |
import Foundation
// MARK: - BottomScrollAnalyticsTracker
final class BottomScrollAnalyticsTracker: NSObject {
private func captureAnalyticsEvent(_ event: WPAnalyticsStat) {
if let blogIdentifier = SiteStatsInformation.sharedInstance.siteID {
WPAppAnalytics.track(event, withBlogID: blogIdentifier)
} else {
WPAppAnalytics.track(event)
}
}
private func trackScrollToBottomEvent() {
captureAnalyticsEvent(.statsScrolledToBottom)
}
}
// MARK: - UIScrollViewDelegate
extension BottomScrollAnalyticsTracker: UIScrollViewDelegate {
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let targetOffsetY = Int(targetContentOffset.pointee.y)
let scrollViewContentHeight = scrollView.contentSize.height
let visibleScrollViewHeight = scrollView.bounds.height
let effectiveScrollViewHeight = Int(scrollViewContentHeight - visibleScrollViewHeight)
if targetOffsetY >= effectiveScrollViewHeight {
trackScrollToBottomEvent()
}
}
}
| bb9a5ffeae831c36e62ed3859a46239a | 31.222222 | 148 | 0.733621 | false | false | false | false |
samodom/UIKitSwagger | refs/heads/master | UIKitSwagger/AutoLayout/NSLayoutConstraintSearch.swift | mit | 1 | //
// NSLayoutConstraintSearch.swift
// UIKitSwagger
//
// Created by Sam Odom on 9/25/14.
// Copyright (c) 2014 Sam Odom. All rights reserved.
//
import UIKit
internal extension NSLayoutConstraint {
internal func hasItem(item: AnyObject) -> Bool {
return firstItem.isEqual(item) || (secondItem != nil && secondItem!.isEqual(item))
}
internal func hasItems(itemOne: AnyObject, _ itemTwo: AnyObject) -> Bool {
assert(itemOne !== itemTwo, "The items must be different")
return secondItem != nil && itemsMatch(itemOne, itemTwo)
}
private func itemsMatch(itemOne: AnyObject, _ itemTwo: AnyObject) -> Bool {
return firstItem.isEqual(itemOne) && secondItem!.isEqual(itemTwo) ||
firstItem.isEqual(itemTwo) && secondItem!.isEqual(itemOne)
}
internal func hasAttribute(attribute: NSLayoutAttribute) -> Bool {
return firstAttribute == attribute || secondAttribute == attribute
}
internal func hasAttributedItem(attributedItem: AutoLayoutAttributedItem) -> Bool {
switch attributedItem.attribute {
case firstAttribute:
return firstItem.isEqual(attributedItem.item)
case secondAttribute:
return secondItem != nil && secondItem!.isEqual(attributedItem.item)
default:
return false
}
}
internal func hasAttributedItems(itemOne: AutoLayoutAttributedItem, _ itemTwo: AutoLayoutAttributedItem) -> Bool {
return hasAttributedItem(itemOne) && hasAttributedItem(itemTwo)
}
}
| d17471b66bd9ab24e03d4575ae10a1b4 | 31.354167 | 118 | 0.675467 | false | false | false | false |
rohan1989/FacebookOauth2Swift | refs/heads/master | FacebookOauth2Swift/GraphRootViewController.swift | mit | 1 | //
// GraphRootViewController.swift
// FacebookOauth2Swift
//
// Created by Rohan Sonawane on 06/12/16.
// Copyright © 2016 Rohan Sonawane. All rights reserved.
//
import UIKit
struct GraphRootViewControllerConstants {
static let graphSegueIdentifier = "showGraphView"
}
class GraphRootViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var enterCityTextField: UITextField!
var weatherArray:Array<WeatherForecast>?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.enterCityTextField.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
Generalise method to show alerts
@param title -- Alert Title.
@param message -- Alert message.
@return None.
*/
private func showAlert(title:String, message:String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
private func showWeatherGraph(){
self.performSegue(withIdentifier: GraphRootViewControllerConstants.graphSegueIdentifier, sender: nil)
}
@IBAction func showWeatherButtonAction(_ sender: Any) {
if enterCityTextField.text?.characters.count == 0 {return}
let openWeatherManager:OpenWeatherManager = OpenWeatherManager()
openWeatherManager.getWeatherForCity(city: enterCityTextField.text!, completionWithWeatherArray: {weatherArray, error in
DispatchQueue.main.async() { () -> Void in
if((error?.code) != 111){
self.weatherArray = weatherArray as? Array<WeatherForecast>
self.showWeatherGraph()
}
else{
self.showAlert(title: "Error Occurred", message: (error?.localizedDescription)!)
}
}
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if GraphRootViewControllerConstants.graphSegueIdentifier == segue.identifier {
let destinationViewController = segue.destination as! GraphViewController
destinationViewController.weatherArray = self.weatherArray
destinationViewController.city = enterCityTextField.text
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| b555a1645dc7cca8b02e9b82bfbf3bbe | 33.298969 | 128 | 0.661557 | false | false | false | false |
peterlafferty/LuasLife | refs/heads/master | Carthage/Checkouts/Decodable/Tests/Vehicle.swift | mit | 1 | //
// Vehicle.swift
// Decodable
//
// Created by Charlotte Tortorella on 12/04/2016.
// Copyright © 2016 anviking. All rights reserved.
//
@testable import Decodable
protocol Vehicle {
var driverless: Bool {get}
}
struct Car: Vehicle {
let driverless: Bool
}
extension Car: Decodable {
static func decode(_ json: Any) throws -> Car {
return try Car(driverless: json => "driverless")
}
}
struct Train: Vehicle {
let driverless: Bool
let electric: Bool
}
extension Train: Decodable {
static func decode(_ json: Any) throws -> Train {
return try Train(driverless: json => "driverless",
electric: json => "electric")
}
}
struct Truck: Vehicle {
let driverless: Bool
let wheels: UInt8
}
extension Truck: Decodable {
static func decode(_ json: Any) throws -> Truck {
return try Truck(driverless: json => "driverless",
wheels: json => "wheels")
}
}
| 4ff2780290dcd2df795bc935dbd08eb6 | 17.916667 | 52 | 0.662996 | false | false | false | false |
zarkopopovski/IOS-Tutorials | refs/heads/master | BookmarkIN/BookmarkIN/BookmarksListViewController.swift | mit | 1 | //
// BookmarksListViewController.swift
// BookmarkIN
//
// Created by Zarko Popovski on 5/2/17.
// Copyright © 2017 ZPOTutorials. All rights reserved.
//
import UIKit
import SVProgressHUD
import SwiftyJSON
class BookmarksListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var bookmarksTableView: UITableView!
@IBOutlet weak var btnAdd: UIButton!
let API_CONNECTOR = ApiConnector.sharedInstance
var userBookmarks:[[String:String]] = [[String:String]]()
var userGroups:[[String:String]] = [[String:String]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.reloadBookmarksData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userBookmarks.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let CELL_ID = "Cell"
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: CELL_ID, for: indexPath)
let bookmarkData = self.userBookmarks[indexPath.row]
cell.textLabel?.text = bookmarkData["title"]
cell.detailTextLabel?.text = bookmarkData["url"]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
@IBAction func btnAddAction(_ sender: UIButton) {
let bookmarkURLEntryAlert = UIAlertController(title: "Bookmark Entry", message: "URL Field", preferredStyle: .alert)
bookmarkURLEntryAlert.addTextField { (urlField) in
urlField.placeholder = ""
}
let okAction = UIAlertAction(title: "Ok", style: .default) { (newAction) in
let urlField = bookmarkURLEntryAlert.textFields![0] as UITextField
let bookmarkURL = urlField.text!
SVProgressHUD.show(withStatus: "Loading")
self.API_CONNECTOR.createNewBookmark(bookmarkURL: bookmarkURL, completition: {(hasError, result) in
SVProgressHUD.dismiss()
if !hasError {
self.reloadBookmarksData()
} else {
let errorAlert = UIAlertController(title: "Error", message: "Error saving.", preferredStyle: .alert)
let alertClose = UIAlertAction(title: "Close", style: .cancel, handler: { (alert) in
self.dismiss(animated: true, completion: nil)
})
errorAlert.addAction(alertClose)
self.present(errorAlert, animated: true, completion: nil)
}
})
}
let closeAction = UIAlertAction(title: "Close", style: .destructive) { (newAction) in
bookmarkURLEntryAlert.dismiss(animated: true, completion: nil)
}
bookmarkURLEntryAlert.addAction(okAction)
bookmarkURLEntryAlert.addAction(closeAction)
present(bookmarkURLEntryAlert, animated: true, completion: nil)
}
func reloadBookmarksData() {
SVProgressHUD.show(withStatus: "Loading")
API_CONNECTOR.findAllBookmarks(completition: {(hasError, result) in
SVProgressHUD.dismiss()
if !hasError {
self.userBookmarks = result
self.bookmarksTableView.reloadData()
} else {
let errorAlert = UIAlertController(title: "Error", message: "No data.", preferredStyle: .alert)
let alertClose = UIAlertAction(title: "Close", style: .cancel, handler: { (alert) in
self.dismiss(animated: true, completion: nil)
})
errorAlert.addAction(alertClose)
self.present(errorAlert, animated: true, completion: nil)
}
})
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| d526786ba69df130b8c76a4c12dc91fa | 35.238806 | 124 | 0.612232 | false | false | false | false |
WebAPIKit/WebAPIKit | refs/heads/master | Sources/WebAPIKit/Request/Request.swift | mit | 1 | /**
* WebAPIKit
*
* Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows:
*
* 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 typealias ResultHandler = (WebAPIResult) -> Void
open class WebAPIRequest {
open let provider: WebAPIProvider
open let path: String
open let method: HTTPMethod
open var requireAuthentication: Bool?
open var authentication: WebAPIAuthentication?
/// `HttpClient` to send out the http request.
open var httpClient: HTTPClient?
/// Plugins only apply to this request.
open var plugins: PluginHub?
/// Query items in url.
open var queryItems = [URLQueryItem]()
/// Http header fileds.
open var headers = HTTPHeaders()
/// Parameters for POST, PUT, PATCH requests.
/// To be encoded to `httpBody` by `parameterEncoding`.
/// Will be ignored if `httpBody` is set.
open var parameters = Parameters()
/// Encoding to encode `parameters` to `httpBody`.
open var parameterEncoding: ParameterEncoding?
/// Http body for POST, PUT, PATCH requests.
/// Will ignore `parameters` if value provided.
open var httpBody: Data?
public init(provider: WebAPIProvider, path: String, method: HTTPMethod = .get) {
self.provider = provider
self.path = path
self.method = method
}
@discardableResult
open func send(by httpClient: HTTPClient? = nil, handler: @escaping ResultHandler) -> Cancelable {
let httpClient = httpClient ?? self.httpClient ?? provider.httpClient ?? SessionManager.default
return WebAPISender(provider: provider, request: self, httpClient: httpClient, handler: handler)
}
/// Turn to an `URLRequest`, to be sent by `HttpClient` or `URLSession` or any other networking library.
open func toURLRequest() throws -> URLRequest {
let url = try makeURL()
let request = try makeURLRequest(with: url)
return try processURLRequest(request)
}
/// Step 1/3 of `toURLRequest()`: make `URL` from `baseURL`, `path`, and `queryItems`.
open func makeURL() throws -> URL {
let url = provider.baseURL.appendingPathComponent(path)
if queryItems.isEmpty {
return url
}
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
throw AFError.invalidURL(url: url)
}
components.queryItems = queryItems
return try components.asURL()
}
/// Step 2/3 of `toURLRequest()`: make `URLRequest` from `URL`, `method`, `headers`, and `parameters`/`httpBody`.
open func makeURLRequest(with url: URL) throws -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
if !headers.isEmpty {
request.allHTTPHeaderFields = headers
}
if let httpBody = httpBody {
request.httpBody = httpBody
} else if !parameters.isEmpty {
let encoding = parameterEncoding ?? provider.parameterEncoding
return try encoding.encode(request, with: parameters)
}
return request
}
/// Step 3/3 of `toURLRequest()`: process `URLRequest` by `Authentication` and `RequestProcessor` plugins.
open func processURLRequest(_ request: URLRequest) throws -> URLRequest {
var request = request
if requireAuthentication ?? provider.requireAuthentication {
guard let authentication = authentication ?? provider.authentication else {
throw WebAPIError.authentication(.missing)
}
request = try authentication.authenticate(request)
}
try provider.plugins.requestProcessors.forEach {
request = try $0.processRequest(request)
}
try plugins?.requestProcessors.forEach {
request = try $0.processRequest(request)
}
return request
}
}
| 1e07adf63276d18bdb07e1b9ae8877af | 35.764706 | 117 | 0.6732 | false | false | false | false |
MrLSPBoy/LSPDouYu | refs/heads/master | LSPDouYuTV/LSPDouYuTV/Classes/Main/View/LSPageContentView.swift | mit | 1 | //
// LSPageContentView.swift
// LSPDouYuTV
//
// Created by lishaopeng on 17/2/28.
// Copyright © 2017年 lishaopeng. All rights reserved.
//
import UIKit
protocol LSPageContentViewDelegate : class {
func pageContentView(contentView: LSPageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
}
fileprivate let cellId = "cellId"
class LSPageContentView: UIView {
//MARK: - 定义属性
fileprivate var childVCs: [UIViewController]
fileprivate weak var parentViewController: UIViewController?
fileprivate var startOffsetX: CGFloat = 0
fileprivate var isForbidScrollDelegate : Bool = false
weak var delegate : LSPageContentViewDelegate?
//MARK: - 懒加载属性
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
//1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//创建UICollectionView
let collectionView = UICollectionView(frame:CGRect(x: 0, y: 0, width: 0, height: 0) , collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
return collectionView
}()
//MARK: - 自定义构造函数
init(frame: CGRect,childVCs : [UIViewController], parentViewController : UIViewController?) {
self.childVCs = childVCs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - 设置UI界面
extension LSPageContentView{
fileprivate func setupUI(){
//1.将所有的子控制器添加到父控制器中
for childVC in childVCs {
parentViewController?.addChildViewController(childVC)
}
//2.添加UICollectionView,用于在cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
//MARK: - UICollectionViewDataSource
extension LSPageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
//2.给cell设置内容
let childVc = childVCs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK: - UICollectionViewDelegate
extension LSPageContentView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//0.判断是否是点击事件
if isForbidScrollDelegate { return }
//1.定义获取需要的数据
var progress: CGFloat = 0
var sourceIndex: Int = 0
var targetIndex: Int = 0
//2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewWidth = scrollView.bounds.width
if currentOffsetX > startOffsetX {//左滑
//1.计算progress
progress = currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth)
//2.计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewWidth)
//3.计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVCs.count {
targetIndex = childVCs.count - 1
}
//4.如果完全划过去
if currentOffsetX - startOffsetX == scrollViewWidth{
progress = 1
targetIndex = sourceIndex
}
}else{//右滑
//1.计算progress
progress = 1 - (currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth))
//2.计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewWidth)
//3.计算soureIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVCs.count {
sourceIndex = childVCs.count - 1
}
}
// print("progress\(progress) sourceIndex\(sourceIndex) targetIndex\(targetIndex)")
//3.将progress/sourceIndex/targetIndex传递给titleView
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//MARK:--对外暴露的方法
extension LSPageContentView{
func setCurrentIndex(currentIndex: Int) {
//1.记录需要禁止我们的执行代理方法
isForbidScrollDelegate = true
//2.滚动正确的位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
| 1f36997e73a16406d1f13a4723eabe7a | 30.92 | 124 | 0.639456 | false | false | false | false |
radioboo/SemanticVersion | refs/heads/master | SemanticVersion/Regexp.swift | mit | 1 | //
// Regexp.swift
// SemanticVersion
//
// Created by atsushi.sakai on 2016/03/07.
// Copyright © 2016年 Atsushi Sakai. All rights reserved.
//
// Inspired by https://gist.github.com/takafumir/317b9325bebf677326b4
// Thanks, takafumir!!
import Foundation
class Regexp {
let internalRegexp: NSRegularExpression
let pattern: String
init(_ pattern: String) {
self.pattern = pattern
do {
self.internalRegexp = try NSRegularExpression(pattern: pattern, options: [])
} catch let error as NSError {
print(error.localizedDescription)
self.internalRegexp = NSRegularExpression()
}
}
func isMatch(_ input: String) -> Bool {
let inputAsNSString = input as NSString
let matches = self.internalRegexp.matches(
in: input,
options: [],
range:NSMakeRange(0, inputAsNSString.length)
)
return matches.count > 0
}
func matches(_ input: String) -> [String]? {
if self.isMatch(input) {
let inputAsNSString = input as NSString
let matches = self.internalRegexp.matches(
in: input,
options: [],
range:NSMakeRange(0, inputAsNSString.length)
)
var results: [String] = []
for i in 0 ..< matches.count {
results.append( inputAsNSString.substring(with: matches[i].range) )
}
return results
}
return nil
}
}
| ae0c8c3ac32b0d93d5d0098232563772 | 28.056604 | 88 | 0.571429 | false | false | false | false |
gouyz/GYZBaking | refs/heads/master | baking/Classes/Main/GYZMainTabBarVC.swift | mit | 1 | //
// GYZMainTabBarVC.swift
// baking
//
// Created by gouyz on 2017/3/23.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
class GYZMainTabBarVC: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
setUp()
}
func setUp(){
tabBar.tintColor = kYellowFontColor
addViewController(GYZHomeVC(), title: "首页", normalImgName: "icon_tab_home")
addViewController(GYZCategoryVC(), title: "分类", normalImgName: "icon_tab_category")
addViewController(GYZOrderVC(), title: "订单", normalImgName: "icon_tab_order")
addViewController(GYZMineVC(), title: "我的", normalImgName: "icon_tab_mine")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 添加子控件
fileprivate func addViewController(_ childController: UIViewController, title: String,normalImgName: String) {
let nav = GYZBaseNavigationVC(rootViewController:childController)
addChildViewController(nav)
childController.tabBarItem.title = title
childController.tabBarItem.image = UIImage(named: normalImgName)
childController.tabBarItem.selectedImage = UIImage(named: normalImgName + "_selected")
}
}
| 6e6f4750bdcd7957e2b8656e8b4ee7a6 | 30.738095 | 114 | 0.675169 | false | false | false | false |
Rag0n/QuNotes | refs/heads/master | Core/Utility/Extensions/Array+Extensions.swift | gpl-3.0 | 1 | //
// Array+Extensions.swift
// QuNotes
//
// Created by Alexander Guschin on 12.07.17.
// Copyright © 2017 Alexander Guschin. All rights reserved.
//
extension Array where Element: Equatable {
func appending(_ newElement: Element) -> [Element] {
var updatedArray = self
updatedArray.append(newElement)
return updatedArray
}
func removing(_ element: Element) -> [Element] {
guard let index = index(of: element) else { return self }
var updatedArray = self
updatedArray.remove(at: index)
return updatedArray
}
func removing(at index: Int) -> [Element] {
var updatedArray = self
updatedArray.remove(at: index)
return updatedArray
}
func replacing(at index: Int, with element: Element) -> [Element] {
var updatedArray = self
updatedArray[index] = element
return updatedArray
}
}
| e2cad8264983a457b89653fee6fb753b | 26.058824 | 71 | 0.629348 | 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.