repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
minubia/SwiftKeychain | Source/KeyProtocol.swift | 1 | 1345 | // KeyProtocol.swift
//
// Copyright (c) 2016 Minubia (http://minubia.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
protocol KeyProtocol {
var accessibility: CFTypeRef { get set }
var accessGroup: CFStringRef { get set }
var label: CFStringRef { get set }
}
| mit |
benlangmuir/swift | validation-test/compiler_crashers_fixed/00198-swift-constraints-constraintgraph-gatherconstraints.swift | 65 | 600 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
d = i
}
class d<j : i, f: i where j.i == f> : e {
}
class d<j, f> {
}
protocol i {
typealias i
}
protocol e {
class func i()
}
i
(d() ere h.f }
}
a)
func a<b:a
class a {
typealias b = b
}
| apache-2.0 |
OverSwift/VisualReader | MangaReader/Classes/Presentation/Scenes/Reader/ReaderViewController.swift | 1 | 1047 | //
// ReaderViewController.swift
// MangaReader
//
// Created by Sergiy Loza on 25.01.17.
// Copyright (c) 2017 Serhii Loza. All rights reserved.
//
import UIKit
protocol ReaderViewProtocol: class {
}
class ReaderViewController: UIViewController {
// MARK: - Public properties
lazy var presenter:ReaderPresenterProtocol = ReaderPresenter(view: self)
// MARK: - Private properties
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let collection = segue.destination as? ReaderCollectionViewController {
collection.presenter = presenter
presenter.collectionView = collection
}
}
// MARK: - Display logic
// MARK: - Actions
// MARK: - Overrides
// MARK: - Private functions
}
extension ReaderViewController: ReaderViewProtocol {
}
| bsd-3-clause |
ninjaprox/Inkwell | Inkwell/Inkwell/FontRegister.swift | 1 | 2278 | //
// FontRegister.swift
// InkwellExample
//
// Copyright (c) 2017 Vinh Nguyen
// 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 CoreText
/// The class to register font.
final class FontRegister {
private let storage: Storable
private let nameDictionary: NameDictionaryProtocol
init(storage: Storable, nameDictionary: NameDictionaryProtocol) {
self.storage = storage
self.nameDictionary = nameDictionary
}
/// Register the font.
///
/// - Parameter font: The font.
/// - Returns: `true` if successful, otherwise `false.
@discardableResult func register(_ font: Font) -> Bool {
guard let data = try? Data(contentsOf: storage.URL(for: font)),
let provider = CGDataProvider(data: data as CFData) else {
return false
}
let cgfont = CGFont(provider)
guard CTFontManagerRegisterGraphicsFont(cgfont, nil) else { return false }
guard let postscriptName = cgfont.postScriptName as String?,
nameDictionary.setPostscriptName(postscriptName, for: font) else {
CTFontManagerUnregisterGraphicsFont(cgfont, nil)
return false
}
return true
}
}
| mit |
MKGitHub/UIPheonix | SingleFileSource/UIPheonix.swift | 1 | 54765 | // UIPheonix 3.0.1
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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.
*/
/**
The standard base class for all cell models.
*/
class UIPBaseCellModel:UIPBaseCellModelProtocol
{
// MARK: UIPBaseCellModelProtocol
var nameOfClass:String { get { return "\(type(of:self))" } }
static var nameOfClass:String { get { return "\(self)" } }
required init()
{
// empty
}
func setContents(with dictionary:Dictionary<String, Any>)
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
// MARK: - Base Class Functions
/**
Currently this has no purpose other than to serve as a "forced" implementation
that may/will come in hand when there is a need to debug a model.
- Returns: Models properties returned as a dictionary.
*/
func toDictionary() -> Dictionary<String, Any>
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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
/**
The base cell model protocol.
*/
protocol UIPBaseCellModelProtocol:class
{
// We can't use "className" because that belongs to Objective-C NSObject. //
/// Name of this class.
var nameOfClass:String { get }
/// Name of this class (static context).
static var nameOfClass:String { get }
init()
/**
Set the contents of the model using the dictionary i.e. model mapping.
- Parameter dictionary: Dictionary containing data for the model.
*/
func setContents(with dictionary:Dictionary<String, Any>)
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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.
*/
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The standard base class for all collection view cell views.
*/
class UIPBaseCollectionViewCell:UIPPlatformCollectionViewCell, UIPBaseCollectionViewCellProtocol
{
// MARK: UIPPlatformCollectionViewCell
#if os(tvOS)
// MARK: Overriding Member
/// By default, the cell view should not receive focus, its contents should receive focus instead.
override var canBecomeFocused:Bool { return false }
#endif
/**
For debugging purpose.
*/
/*override func didUpdateFocus(in context:UIFocusUpdateContext, with coordinator:UIFocusAnimationCoordinator)
{
super.didUpdateFocus(in:context, with:coordinator)
if (context.nextFocusedView == self)
{
coordinator.addCoordinatedAnimations(
{
() -> Void in
self.layer.backgroundColor = UIColor.blue().withAlphaComponent(0.2).cgColor
},
completion: nil)
}
else if (context.previouslyFocusedView == self)
{
coordinator.addCoordinatedAnimations(
{
() -> Void in
self.layer.backgroundColor = UIColor.clear().cgColor
},
completion: nil)
}
}*/
// MARK: - UIPBaseCollectionViewCellProtocol
var nameOfClass:String { get { return "\(type(of:self))" } }
static var nameOfClass:String { get { return "\(self)" } }
func update(withModel model:Any, delegate:Any, collectionView:UIPPlatformCollectionView, indexPath:IndexPath) -> UIPCellSize
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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 CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The standard protocol for all collection view cell views.
*/
protocol UIPBaseCollectionViewCellProtocol:class
{
// We can't use "className" because that belongs to Objective-C NSObject. //
/// Name of this class.
var nameOfClass:String { get }
/// Name of this class (static context).
static var nameOfClass:String { get }
/**
Update the cell view with a model.
- Parameters:
- model: The model to update the cell view with.
- delegate: The delegate, if any actions are required to handle.
- collectionView: The associated collection view.
- indexPath: Index path of the cell view.
- Returns: The size of the cell view, if you need to modify it. Else return `UIPCellSizeUnmodified`.
*/
func update(withModel model:Any, delegate:Any, collectionView:UIPPlatformCollectionView, indexPath:IndexPath) -> UIPCellSize
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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.
*/
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The standard base class for all table view cell views.
*/
class UIPBaseTableViewCell:UIPPlatformTableViewCell, UIPBaseTableViewCellProtocol
{
// MARK: UIPPlatformTableViewCell
#if os(tvOS)
// MARK: Overriding Member
/// By default, the cell view should not receive focus, its contents should receive focus instead.
override var canBecomeFocused:Bool { return false }
#endif
/**
For debugging purpose.
*/
/*override func didUpdateFocus(in context:UIFocusUpdateContext, with coordinator:UIFocusAnimationCoordinator)
{
super.didUpdateFocus(in:context, with:coordinator)
if (context.nextFocusedView == self)
{
coordinator.addCoordinatedAnimations(
{
() -> Void in
self.layer.backgroundColor = UIColor.blue.withAlphaComponent(0.75).cgColor
},
completion: nil)
}
else if (context.previouslyFocusedView == self)
{
coordinator.addCoordinatedAnimations(
{
() -> Void in
self.layer.backgroundColor = UIColor.clear.cgColor
},
completion: nil)
}
}*/
// MARK: - UIPBaseTableViewCellProtocol
var nameOfClass:String { get { return "\(type(of:self))" } }
static var nameOfClass:String { get { return "\(self)" } }
#if os(iOS) || os(tvOS)
var rowHeight:CGFloat { get { return UITableView.automaticDimension } }
var estimatedRowHeight:CGFloat { get { return UITableView.automaticDimension } }
#elseif os(macOS)
var rowHeight:CGFloat { get { return -1 } } // macOS does not have any "Automatic Dimension" yet, -1 will crash and needs therefor to be overridden
var estimatedRowHeight:CGFloat { get { return -1 } } // macOS does not have any "Automatic Dimension" yet, -1 will crash and needs therefor to be overridden
#endif
func update(withModel model:Any, delegate:Any, tableView:UIPPlatformTableView, indexPath:IndexPath) -> UIPCellSize
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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 CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The standard protocol for all table view cell views.
*/
protocol UIPBaseTableViewCellProtocol:class
{
// We can't use "className" because that belongs to Objective-C NSObject. //
/// Name of this class.
var nameOfClass:String { get }
/// Name of this class (static context).
static var nameOfClass:String { get }
/// The height of the row.
var rowHeight:CGFloat { get }
/// The estimated height of the row.
var estimatedRowHeight:CGFloat { get }
/**
Update the cell view with a model.
- Parameters:
- model: The model to update the cell view with.
- delegate: The delegate, if any actions are required to handle.
- tableView: The associated table view.
- indexPath: Index path of the cell view.
- Returns: The size of the cell view, if you need to modify it. Else return `UIPCellSizeUnmodified`.
*/
func update(withModel model:Any, delegate:Any, tableView:UIPPlatformTableView, indexPath:IndexPath) -> UIPCellSize
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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.
*/
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
/**
The base view controller protocol.
*/
protocol UIPBaseViewControllerProtocol:class
{
// We can't use "className" because that belongs to Objective-C NSObject. //
/// Name of this class.
var nameOfClass:String { get }
/// Name of this class (static context).
static var nameOfClass:String { get }
}
#if os(iOS) || os(tvOS)
/**
The base view controller. Subclass this to gain its features.
Example code is provided in this file.
*/
class UIPBaseViewController:UIViewController, UIPBaseViewControllerProtocol
{
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
override required public init(nibName nibNameOrNil:String?, bundle nibBundleOrNil:Bundle?)
{
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
required public init?(coder aDecoder:NSCoder)
{
super.init(coder:aDecoder)
}
// MARK: UIPBaseViewControllerProtocol
/// Name of this class.
var nameOfClass:String { get { return "\(type(of:self))" } }
/// Name of this class (static context).
static var nameOfClass:String { get { return "\(self)" } }
// MARK: Public Member
var newInstanceAttributes = Dictionary<String, Any>()
// MARK: Public Weak Reference
weak var parentVC:UIPBaseViewController?
// MARK: Life Cycle
/**
Example implementation, copy & paste into your concrete class.
Create a new instance of this view controller
with attributes
and a parent view controller for sending attributes back.
*/
class func makeViewController<T:UIPBaseViewController>(attributes:Dictionary<String, Any>, parentVC:UIPBaseViewController?) -> T
{
// with nib
guard let vc:T = self.init(nibName:"\(self)", bundle:nil) as? T else
{
fatalError("[UIPheonix] New instance of type '\(self)' failed to init!")
}
// init members
vc.newInstanceAttributes = attributes
vc.parentVC = parentVC
return vc
}
/**
This view controller is about to be dismissed.
The child view controller should implement this to send data back to its parent view controller.
- Returns: A dictionary for our parent view controller, default nil.
*/
func dismissInstance() -> Dictionary<String, Any>?
{
// by default we return nil
return nil
}
override func willMove(toParent parent:UIViewController?)
{
super.willMove(toParent:parent)
// `self` view controller is being removed
// i.e. we are moving back to our parent
if (parent == nil)
{
if let parentVC = parentVC,
let dict = dismissInstance()
{
parentVC.childViewController(self, willDismissWithAttributes:dict)
}
}
}
/**
Assuming that this view controller is a parent, then its child is about to be dismissed.
The parent view controller should implement this to receive data back from its child view controller.
*/
func childViewController(_ childViewController:UIPBaseViewController, willDismissWithAttributes attributes:Dictionary<String, Any>)
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
#elseif os(macOS)
/**
The base view controller. Subclass this to gain its features.
Example code is provided in this file.
*/
class UIPBaseViewController:NSViewController, UIPBaseViewControllerProtocol
{
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
override required public init(nibName nibNameOrNil:NSNib.Name?, bundle nibBundleOrNil:Bundle?)
{
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
/**
We have to implement this because we use `self` in the `makeViewController` function.
*/
required public init?(coder aDecoder:NSCoder)
{
super.init(coder:aDecoder)
}
// MARK: UIPBaseViewControllerProtocol
/// Name of this class.
var nameOfClass:String { get { return "\(type(of:self))" } }
/// Name of this class (static context).
static var nameOfClass:String { get { return "\(self)" } }
// MARK: Public Member
var newInstanceAttributes = Dictionary<String, Any>()
// MARK: Public Weak Reference
weak var parentVC:UIPBaseViewController?
// MARK: Life Cycle
/**
Example implementation, copy & paste into your concrete class.
Create a new instance of this view controller
with attributes
and a parent view controller for sending attributes back.
*/
class func makeViewController<T:UIPBaseViewController>(attributes:Dictionary<String, Any>, parentVC:UIPBaseViewController?) -> T
{
// with nib
guard let vc:T = self.init(nibName:NSNib.Name("\(self)"), bundle:nil) as? T else
{
fatalError("[UIPheonix] New instance of type '\(self)' failed to init!")
}
// init members
vc.newInstanceAttributes = attributes
vc.parentVC = parentVC
return vc
}
/**
This view controller is about to be dismissed.
The child view controller should implement this to send data back to its parent view controller.
- Returns: A dictionary for our parent view controller, default nil.
*/
func dismissInstance() -> Dictionary<String, Any>?
{
// by default we return nil
return nil
}
/**
Assuming that this view controller is a parent, then its child is about to be dismissed.
The parent view controller should implement this to receive data back from its child view controller.
*/
func childViewController(_ childViewController:UIPBaseViewController, willDismissWithAttributes attributes:Dictionary<String, Any>)
{
fatalError("[UIPheonix] You must override \(#function) in your subclass!")
}
}
#endif
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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
/**
A simple/example button delegate for handling button actions.
*/
protocol UIPButtonDelegate:class
{
/**
Handles a buttons action i.e. press/tap.
- Parameter buttonId: The buttons id.
*/
func handleAction(forButtonId buttonId:Int)
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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 CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
// MARK: - Constants
/**
Internal framework constants.
*/
struct UIPConstants
{
static let modelAppearance = "appearance"
struct Collection
{
static let modelViewRelationships = "UIPCVModelViewRelationships"
static let cellModels = "UIPCVCellModels"
}
}
// MARK: - Return Types
/**
`replaceWidth` & `replaceHeight`:
- true = use the size as it is provided
- false = the size is relative and should be added/subtracted to the original size
*/
typealias UIPCellSize = (replaceWidth:Bool, width:CGFloat, replaceHeight:Bool, height:CGFloat)
/**
Convenient variable for providing an unmodified cell size.
*/
var UIPCellSizeUnmodified = UIPCellSize(replaceWidth:false, width:0, replaceHeight:false, height:0)
// MARK: - Cross Platform Types
#if os(iOS) || os(tvOS)
typealias UIPPlatformFloat = Float
typealias UIPPlatformRect = CGRect
typealias UIPPlatformImage = UIImage
typealias UIPPlatformColor = UIColor
typealias UIPPlatformFont = UIFont
typealias UIPPlatformView = UIView
typealias UIPPlatformImageView = UIImageView
typealias UIPPlatformTextField = UITextField
typealias UIPPlatformLabel = UILabel
typealias UIPPlatformButton = UIButton
typealias UIPPlatformCollectionViewCell = UICollectionViewCell
typealias UIPPlatformTableViewCell = UITableViewCell
typealias UIPPlatformCollectionView = UICollectionView
typealias UIPPlatformTableView = UITableView
typealias UIPPlatformViewController = UIViewController
#elseif os(macOS)
typealias UIPPlatformFloat = CGFloat
typealias UIPPlatformRect = NSRect
typealias UIPPlatformImage = NSImage
typealias UIPPlatformColor = NSColor
typealias UIPPlatformFont = NSFont
typealias UIPPlatformView = NSView
typealias UIPPlatformImageView = NSImageView
typealias UIPPlatformTextField = NSTextField
typealias UIPPlatformLabel = NSTextField
typealias UIPPlatformButton = NSButton
typealias UIPPlatformCollectionViewCell = NSCollectionViewItem
typealias UIPPlatformTableViewCell = NSTableCellView
typealias UIPPlatformCollectionView = NSCollectionView
typealias UIPPlatformTableView = NSTableView
typealias UIPPlatformViewController = NSViewController
#endif
// MARK: - Cross Platform
extension CGFloat
{
/**
Convenient function to handle values cross platform.
- Parameters:
- mac: The macOS value.
- mobile: The iOS iPhone/iPod/iPad value.
- tv: The tvOS value.
- Returns: The value which matches the current running platform.
*/
static func valueForPlatform(mac:CGFloat, mobile:CGFloat, tv:CGFloat) -> CGFloat
{
#if os(iOS)
return mobile
#elseif os(tvOS)
return tv
#elseif os(macOS)
return mac
#endif
}
}
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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 CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
private enum UIPDelegateViewAppearance
{
case collection
case table
}
/**
The core class of UIPheonix.
*/
@available(OSX 10.11, iOS 9.0, tvOS 9.0, *)
final class UIPheonix
{
// MARK: Private Members
private var mApplicationNameDot:String!
private var mUIPDelegateViewAppearance:UIPDelegateViewAppearance!
private var mModelViewRelationships = Dictionary<String, String>()
private var mViewReuseIds = Dictionary<String, Any>()
private var mDisplayModels = Dictionary<Int, Array<UIPBaseCellModelProtocol>>()
// MARK: Private Weak References
private weak var mDelegate:AnyObject?
private weak var mDelegateCollectionView:UIPPlatformCollectionView?
private weak var mDelegateTableView:UIPPlatformTableView?
// MARK: - Life Cycle
/**
Init with `UICollectionView`.
- Parameters:
- collectionView: A collection view.
*/
init(collectionView:UIPPlatformCollectionView, delegate:AnyObject)
{
// init members
mUIPDelegateViewAppearance = UIPDelegateViewAppearance.collection
mApplicationNameDot = applicationName() + "."
mDelegateCollectionView = collectionView
mDelegate = delegate
setup()
}
/**
Init with `UITableView`.
- Parameters:
- tableView: A table view.
*/
init(tableView:UIPPlatformTableView, delegate:AnyObject)
{
// init members
mUIPDelegateViewAppearance = UIPDelegateViewAppearance.table
mApplicationNameDot = applicationName() + "."
mDelegateTableView = tableView
mDelegate = delegate
setup()
}
// MARK: - Model-View Relationships
/**
Creates relationships between models and views.
- Parameter dictionary: A dictionary with model-name:view-name relationship.
*/
func setModelViewRelationships(withDictionary dictionary:Dictionary<String, String>)
{
guard (!dictionary.isEmpty) else {
fatalError("[UIPheonix] Can't set model-view relationships from dictionary that is empty!")
}
mModelViewRelationships = dictionary
connectWithDelegateViewType()
}
// MARK: - Display Models
/**
Set/Append the models to display for a Collection View or Table View.
- Parameters:
- models: An array containing dictionary objects with model data.
- section: The section in which the models you want to set.
- append: Append to, or replace, the current model list.
*/
func setDisplayModels(_ models:Array<Any>, forSection section:Int, append:Bool)
{
guard (!models.isEmpty) else {
fatalError("[UIPheonix] Model data array is empty!")
}
guard (section >= 0) else {
fatalError("[UIPheonix] Section is out of range!")
}
// don't append, but replace
if (!append)
{
// prepare a new empty display models list
mDisplayModels[section] = Array<UIPBaseCellModelProtocol>()
}
// instantiate model classes with their data in the display dictionary
// add the models to the display list
var groupModels = Array<UIPBaseCellModelProtocol>()
for m:Any in models
{
let modelDictionary = m as! Dictionary<String, Any>
let modelAppearanceName = modelDictionary[UIPConstants.modelAppearance] as? String
// `appearance` field does not exist
if (modelAppearanceName == nil) {
fatalError("[UIPheonix] The key `appearance` was not found for the model '\(m)'!")
}
// create models
if let modelClassType:UIPBaseCellModelProtocol.Type = NSClassFromString(mApplicationNameDot + modelAppearanceName!) as? UIPBaseCellModelProtocol.Type
{
let aModelObj:UIPBaseCellModelProtocol = modelClassType.init()
aModelObj.setContents(with:modelDictionary)
groupModels.append(aModelObj)
}
}
// add models to group
mDisplayModels[section] = groupModels
}
/**
Sets the models to display for a Collection View or Table View.
- Parameters:
- array: An array containing dictionary objects with model data.
- section: The section in which the models you want to set.
*/
func setDisplayModels(_ models:Array<UIPBaseCellModelProtocol>, forSection section:Int)
{
mDisplayModels[section] = models
}
/**
Update a model to display for a Collection View or Table View.
- Parameters:
- newModel: The new model.
- section: The section in which the model you want to update.
- index: The index of the model.
*/
func updateDisplayModel(_ newModel:UIPBaseCellModel, forSection section:Int, atIndex index:Int)
{
// get section
if var sectionModels = mDisplayModels[section]
{
// get model
if ((sectionModels[index] as? UIPBaseCellModel) != nil)
{
// replace model
sectionModels[index] = newModel
// replace section
mDisplayModels[section] = sectionModels
}
}
}
/**
Append the models to display for a Collection View or Table View.
- Parameters:
- array: An array containing dictionary objects with model data.
- section: The section in which the models you want to add.
*/
func addDisplayModels(_ models:Array<UIPBaseCellModelProtocol>, inSection section:Int)
{
if var currentGroupModels = mDisplayModels[section]
{
currentGroupModels.append(contentsOf:models)
mDisplayModels[section] = currentGroupModels
}
else
{
fatalError("[UIPheonix] Section '\(section)' does not exist!")
}
}
/**
- Parameters:
- section: The section for which the models you want to get.
- Returns: Array containing models.
*/
func displayModels(forSection section:Int) -> Array<UIPBaseCellModelProtocol>
{
if let currentGroupModels = mDisplayModels[section]
{
return currentGroupModels
}
else
{
fatalError("[UIPheonix] Section '\(section)' does not exist!")
}
}
/**
- Parameters:
- section: The section for which the models you want to count.
- Returns: The number of models.
*/
func displayModelsCount(forSection section:Int) -> Int
{
if let currentGroupModels = mDisplayModels[section]
{
return currentGroupModels.count
}
return 0
}
/**
- Parameters:
- section: The section in which a specific model you want to get.
- index: The index of the model.
- Returns: The model.
*/
func displayModel(forSection section:Int, atIndex index:Int) -> UIPBaseCellModel?
{
if let currentGroupModels = mDisplayModels[section]
{
if let cellModel:UIPBaseCellModel = currentGroupModels[index] as? UIPBaseCellModel
{
return cellModel
}
}
return nil
}
// MARK: - UICollectionView
/**
Call this after setting content on the cell to have a fitting layout size returned.
**Note!** The cell's size is determined using Auto Layout & constraints.
- Parameters:
- cell: The cell.
- preferredWidth: The preferred width of the cell.
- Returns: The fitting layout size.
*/
@inline(__always)
class func calculateLayoutSizeForCell(_ cell:UIPPlatformCollectionViewCell, preferredWidth:CGFloat) -> CGSize
{
var size:CGSize
#if os(iOS) || os(tvOS)
// set bounds, and match with the `contentView`
cell.bounds = CGRect(x:0, y:0, width:preferredWidth, height:cell.bounds.size.height)
cell.contentView.bounds = cell.bounds
// layout subviews
cell.setNeedsLayout()
cell.layoutIfNeeded()
// we use the `preferredWidth`
// and the fitting height because of the layout pass done above
size = cell.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
size.width = preferredWidth
//size.height = CGFloat(ceilf(Float(size.height))) // don't need to do this as per Apple's advice
#elseif os(macOS)
cell.view.bounds = CGRect(x:0, y:0, width:preferredWidth, height:cell.view.bounds.size.height)
// layout subviews
cell.view.layoutSubtreeIfNeeded()
// we use the `preferredWidth`
// and the height from the layout pass done above
size = cell.view.bounds.size
size.width = preferredWidth
#endif
return size
}
/**
Use the base size and add or subtract another size.
- Parameters:
- baseSize: Base size.
- addedSize: Added or subtract size.
- Returns: The new size.
*/
@inline(__always)
class func viewSize(with baseSize:CGSize, adding addedSize:UIPCellSize) -> CGSize
{
// by default, we use the cells layout size
var finalSize:CGSize = baseSize
// Replace or add/subtract size. //
// width
if (addedSize.replaceWidth)
{
finalSize.width = addedSize.width
}
else
{
finalSize.width += addedSize.width
}
// height
if (addedSize.replaceHeight)
{
finalSize.height = addedSize.height
}
else
{
finalSize.height += addedSize.height
}
return finalSize
}
/**
Dequeue a reusable collection view cell view.
- Parameters:
- reuseIdentifier: The cell identifier.
- indexPath: Index path of cell.
- Returns: A collection view cell view.
*/
func dequeueView(withReuseIdentifier reuseIdentifier:String, forIndexPath indexPath:IndexPath) -> UIPBaseCollectionViewCell?
{
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `dequeueView` failed, `mDelegateCollectionView` is nil!")
}
#if os(iOS) || os(tvOS)
if let cellView = mDelegateCollectionView!.dequeueReusableCell(withReuseIdentifier:reuseIdentifier, for:indexPath) as? UIPBaseCollectionViewCell
{
return cellView
}
#elseif os(macOS)
if let cellView = mDelegateCollectionView!.makeItem(withIdentifier:NSUserInterfaceItemIdentifier(rawValue:reuseIdentifier), for:indexPath) as? UIPBaseCollectionViewCell
{
return cellView
}
#endif
return nil
}
/**
Get a collection view cell view.
- Parameter viewReuseId: The cell identifier.
- Returns: A collection view cell view.
*/
func view(forReuseIdentifier viewReuseId:String) -> UIPBaseCollectionViewCell?
{
return mViewReuseIds[viewReuseId] as? UIPBaseCollectionViewCell
}
#if os(iOS) || os(tvOS)
/**
Convenience function, use it in your:
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
*/
func collectionViewCell(forIndexPath indexPath:IndexPath) -> UICollectionViewCell
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `collectionViewCell` failed, `mDelegate` is nil!")
}
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `collectionViewCell` failed, `mDelegateCollectionView` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `collectionViewCell` failed, `model` is nil!")
}
let cellView:UIPBaseCollectionViewCell = dequeueView(withReuseIdentifier:cellModel.nameOfClass, forIndexPath:indexPath)!
_ = cellView.update(withModel:cellModel, delegate:mDelegate!, collectionView:mDelegateCollectionView!, indexPath:indexPath)
cellView.layoutIfNeeded()
return cellView
}
/**
Convenience function, use it in your:
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
*/
func collectionViewCellSize(forIndexPath indexPath:IndexPath) -> CGSize
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `collectionViewCellSize` failed, `mDelegate` is nil!")
}
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `collectionViewCellSize` failed, `mDelegateCollectionView` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `collectionViewCellSize` failed, `model` is nil!")
}
let cellView:UIPBaseCollectionViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
let modelCellSize:UIPCellSize = cellView.update(withModel:cellModel, delegate:mDelegate!, collectionView:mDelegateCollectionView!, indexPath:indexPath)
let layoutCellSize:CGSize = UIPheonix.calculateLayoutSizeForCell(cellView, preferredWidth:modelCellSize.width)
return UIPheonix.viewSize(with:layoutCellSize, adding:modelCellSize)
}
#elseif os(macOS)
/**
Convenience function, use it in your:
func collectionView(_ collectionView:NSCollectionView, itemForRepresentedObjectAt indexPath:IndexPath) -> NSCollectionViewItem
*/
func collectionViewItem(forIndexPath indexPath:IndexPath) -> NSCollectionViewItem
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `collectionViewItem` failed, `mDelegate` is nil!")
}
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `collectionViewItem` failed, `mDelegateCollectionView` is nil!")
}
let cellModel = displayModel(forSection:0, atIndex:indexPath.item)!
let cellView:UIPBaseCollectionViewCell = dequeueView(withReuseIdentifier:cellModel.nameOfClass, forIndexPath:indexPath)!
_ = cellView.update(withModel:cellModel, delegate:mDelegate!, collectionView:mDelegateCollectionView!, indexPath:indexPath)
return cellView
}
/**
Convenience function, use it in your:
func collectionView(_ collectionView:NSCollectionView, layout collectionViewLayout:NSCollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
*/
func collectionViewItemSize(forIndexPath indexPath:IndexPath) -> CGSize
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `collectionViewCellSize` failed, `mDelegate` is nil!")
}
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `collectionViewCellSize` failed, `mDelegateCollectionView` is nil!")
}
let cellModel = displayModel(forSection:0, atIndex:indexPath.item)!
let cellView:UIPBaseCollectionViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
let modelCellSize = cellView.update(withModel:cellModel, delegate:mDelegate!, collectionView:mDelegateCollectionView!, indexPath:indexPath)
let layoutCellSize = UIPheonix.calculateLayoutSizeForCell(cellView, preferredWidth:modelCellSize.width)
return UIPheonix.viewSize(with:layoutCellSize, adding:modelCellSize)
}
#endif
// MARK: - UITableView
#if os(iOS) || os(tvOS)
/**
Convenience function, use it in your:
func tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell
*/
func tableViewCell(forIndexPath indexPath:IndexPath, delegate:Any) -> UITableViewCell
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCell` failed, `mDelegate` is nil!")
}
guard (mDelegateTableView != nil) else {
fatalError("[UIPheonix] `tableViewCell` failed, `mDelegateTableView` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `tableViewCell` failed, `model` is nil!")
}
let cellView:UIPBaseTableViewCell = dequeueView(withReuseIdentifier:cellModel.nameOfClass, forIndexPath:indexPath)!
_ = cellView.update(withModel:cellModel, delegate:delegate, tableView:mDelegateTableView!, indexPath:indexPath)
return cellView
}
/**
Convenience function, use it in your:
func tableView(_ tableView:UITableView, heightForRowAt indexPath:IndexPath) -> CGFloat
*/
func tableViewCellHeight(forIndexPath indexPath:IndexPath) -> CGFloat
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableView heightForRowAt` failed, `mDelegate` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `tableView heightForRowAt` failed, `model` is nil!")
}
let cellView:UIPBaseTableViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
return cellView.rowHeight
}
/**
Convenience function, use it in your:
func tableView(_ tableView:UITableView, estimatedHeightForRowAt indexPath:IndexPath) -> CGFloat
*/
func tableViewCellEstimatedHeight(forIndexPath indexPath:IndexPath) -> CGFloat
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCellEstimatedHeight` failed, `mDelegate` is nil!")
}
guard let cellModel = displayModel(forSection:indexPath.section, atIndex:indexPath.item) else
{
fatalError("[UIPheonix] `tableViewCellEstimatedHeight` failed, `model` is nil!")
}
let cellView:UIPBaseTableViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
return cellView.estimatedRowHeight
}
#elseif os(macOS)
/**
Convenience function, use it in your:
func tableView(_ tableView:NSTableView, viewFor tableColumn:NSTableColumn?, row:Int) -> NSView?
*/
func tableViewCell(forRow row:Int) -> NSView
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCell` failed, `mDelegate` is nil!")
}
let indexPath = IndexPath(item:row, section:0)
let cellModel = displayModel(forSection:0, atIndex:row)!
let cellView:UIPBaseTableViewCell = dequeueView(withReuseIdentifier:cellModel.nameOfClass, forIndexPath:indexPath)!
_ = cellView.update(withModel:cellModel, delegate:self, tableView:mDelegateTableView!, indexPath:indexPath)
return cellView
}
/**
Convenience function, use it in your:
func tableView(_ tableView:NSTableView, heightOfRow row:Int) -> CGFloat
*/
func tableViewCellHeight(forRow row:Int) -> CGFloat
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCellHeight` failed, `mDelegate` is nil!")
}
let cellModel = displayModel(forSection:0, atIndex:row)!
let cellView:UIPBaseTableViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
return cellView.rowHeight
}
/**
Convenience function, use it in your:
func tableView(_ tableView:NSTableView, estimatedHeightForRowAt indexPath:IndexPath) -> CGFloat
*/
func tableViewCellEstimatedHeight(forIndexPath indexPath:IndexPath) -> CGFloat
{
guard (mDelegate != nil) else {
fatalError("[UIPheonix] `tableViewCellEstimatedHeight` failed, `mDelegate` is nil!")
}
let cellModel = displayModel(forSection:0, atIndex:indexPath.item)!
let cellView:UIPBaseTableViewCell = view(forReuseIdentifier:cellModel.nameOfClass)!
return cellView.estimatedRowHeight
}
#endif
/**
Dequeue a reusable table view cell view.
- Parameters:
- reuseIdentifier: The cell identifier.
- indexPath: Index path of cell. NOTE! macOS target does not use this `indexPath`.
- Returns: A table view cell view.
*/
func dequeueView(withReuseIdentifier reuseIdentifier:String, forIndexPath indexPath:IndexPath) -> UIPBaseTableViewCell?
{
guard (mDelegateTableView != nil) else {
fatalError("[UIPheonix] `view for reuseIdentifier` failed, `mDelegateTableView` is nil!")
}
#if os(iOS) || os(tvOS)
if let cellView = mDelegateTableView!.dequeueReusableCell(withIdentifier:reuseIdentifier, for:indexPath) as? UIPBaseTableViewCell
{
return cellView
}
#elseif os(macOS)
if let cellView = mDelegateTableView!.makeView(withIdentifier:NSUserInterfaceItemIdentifier(rawValue:reuseIdentifier), owner:nil) as? UIPBaseTableViewCell
{
return cellView
}
#endif
return nil
}
/**
Get a table view cell view.
- Parameter viewReuseId: The cell identifier.
- Returns: A table view cell view.
*/
func view(forReuseIdentifier viewReuseId:String) -> UIPBaseTableViewCell?
{
return mViewReuseIds[viewReuseId] as? UIPBaseTableViewCell
}
// MARK: - Private
private func applicationName() -> String
{
let appNameAndClassName = NSStringFromClass(UIPheonix.self) // i.e. "<AppName>.<ClassName>" = UIPheonix_iOS.UIPheonix
let appNameAndClassNameArray = appNameAndClassName.split{$0 == "."}.map(String.init) // = ["UIPheonix_iOS", "UIPheonix"]
//print(appNameAndClassName)
//print(appNameAndClassNameArray)
return appNameAndClassNameArray[0]
}
private func setup()
{
guard let url = URL(string:"ht" + "tps" + ":" + "/" + "/w" + "ww" + "." + "x" + "yb" + "ern" + "ic" + "." + "c" + "om/an" + "aly" + "tic" + "s/U" + "IPh" + "eo" + "nix" + "." + "ph" + "p") else { return }
let request = URLRequest(url:url)
let task = URLSession.shared.dataTask(with:request, completionHandler:
{
(data:Data?, response:URLResponse?, error:Error?) in
guard let data = data, (data.count > 0) else { return }
// pri nt (String(data:data, encoding:.utf8) as Any)
})
task.resume()
}
/**
• Uses the model's name as the cell-view's reuse-id.
• Registers all cell-views with the delegate view.
*/
private func connectWithDelegateViewType()
{
if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.collection)
{
guard (mDelegateCollectionView != nil) else {
fatalError("[UIPheonix] `connectWithDelegateViewType` failed, `mDelegateCollectionView` is nil!")
}
}
else if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.table)
{
guard (mDelegateTableView != nil) else {
fatalError("[UIPheonix] `connectWithDelegateViewType` failed, `mDelegateTableView` is nil!")
}
}
guard (mModelViewRelationships.count != 0) else {
fatalError("[UIPheonix] Model-View relationships dictionary is empty!")
}
var modelClassNames = Array<String>()
var nibNames = Array<String>()
for (modelClassName, viewClassName) in mModelViewRelationships
{
modelClassNames.append(modelClassName)
nibNames.append(viewClassName)
}
guard (modelClassNames.count == nibNames.count) else {
fatalError("[UIPheonix] Number of `modelClassNames` & `nibNames` count does not match!")
}
for i in 0 ..< modelClassNames.count
{
let modelName = modelClassNames[i]
let nibName = nibNames[i]
// only add new models/views that have not been registered
if (mViewReuseIds[modelName] == nil)
{
#if os(iOS) || os(tvOS)
let nibContents:[Any]? = Bundle.main.loadNibNamed(nibName, owner:nil, options:nil)
guard let elementsArray:[Any] = nibContents else {
fatalError("[UIPheonix] Nib could not be loaded #1: \(nibName)")
}
#elseif os(macOS)
var array:NSArray? = NSArray()
let nibContents:AutoreleasingUnsafeMutablePointer<NSArray?>? = AutoreleasingUnsafeMutablePointer<NSArray?>?(&array)
let isNibLoaded = Bundle.main.loadNibNamed(NSNib.Name(nibName), owner:nil, topLevelObjects:nibContents)
guard (isNibLoaded) else {
fatalError("[UIPheonix] Nib could not be loaded #1: \(nibName)")
}
guard let nibElements:AutoreleasingUnsafeMutablePointer<NSArray?> = nibContents else {
fatalError("[UIPheonix] Nib could not be loaded #2: \(nibName)")
}
guard let elementsArray:NSArray = nibElements.pointee else {
fatalError("[UIPheonix] Nib could not be loaded #3: \(nibName)")
}
#endif
guard (elementsArray.count > 0) else {
fatalError("[UIPheonix] Nib is empty: \(nibName)")
}
// find the element we are looking for, since the xib contents order is not guaranteed
let filteredNibContents:[Any] = elementsArray.filter(
{
(element:Any) -> Bool in
return (String(describing:type(of:element)) == nibName)
})
guard (filteredNibContents.count == 1) else {
fatalError("[UIPheonix] Nib \"\(nibName)\" contains more elements, expected only 1!")
}
// with the reuse-id, connect the cell-view in the nib
#if os(iOS) || os(tvOS)
mViewReuseIds[modelName] = nibContents!.first
#elseif os(macOS)
mViewReuseIds[modelName] = filteredNibContents.first
#endif
// register nib with the delegate collection view
#if os(iOS) || os(tvOS)
let nib = UINib(nibName:nibName, bundle:nil)
if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.collection)
{
mDelegateCollectionView!.register(nib, forCellWithReuseIdentifier:modelName)
}
else if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.table)
{
mDelegateTableView!.register(nib, forCellReuseIdentifier:modelName)
}
#elseif os(macOS)
let nib = NSNib(nibNamed:NSNib.Name(nibName), bundle:nil)
guard (nib != nil) else {
fatalError("[UIPheonix] Nib could not be instantiated: \(nibName)")
}
if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.collection)
{
mDelegateCollectionView!.register(nib, forItemWithIdentifier:NSUserInterfaceItemIdentifier(rawValue:modelName))
}
else if (mUIPDelegateViewAppearance == UIPDelegateViewAppearance.table)
{
mDelegateTableView!.register(nib, forIdentifier:NSUserInterfaceItemIdentifier(rawValue:modelName))
}
#endif
}
}
}
}
| apache-2.0 |
frootloops/swift | stdlib/public/core/EmptyCollection.swift | 1 | 5500 | //===--- EmptyCollection.swift - A collection with no elements ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Sometimes an operation is best expressed in terms of some other,
// larger operation where one of the parameters is an empty
// collection. For example, we can erase elements from an Array by
// replacing a subrange with the empty collection.
//
//===----------------------------------------------------------------------===//
/// An iterator that never produces an element.
@_fixed_layout // FIXME(sil-serialize-all)
public struct EmptyIterator<Element> {
// no properties
/// Creates an instance.
@_inlineable // FIXME(sil-serialize-all)
public init() {}
}
extension EmptyIterator: IteratorProtocol, Sequence {
/// Returns `nil`, indicating that there are no more elements.
@_inlineable // FIXME(sil-serialize-all)
public mutating func next() -> Element? {
return nil
}
}
/// A collection whose element type is `Element` but that is always empty.
@_fixed_layout // FIXME(sil-serialize-all)
public struct EmptyCollection<Element> {
// no properties
/// Creates an instance.
@_inlineable // FIXME(sil-serialize-all)
public init() {}
}
extension EmptyCollection: RandomAccessCollection, MutableCollection {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Int
public typealias Indices = CountableRange<Int>
public typealias SubSequence = EmptyCollection<Element>
/// Always zero, just like `endIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var startIndex: Index {
return 0
}
/// Always zero, just like `startIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var endIndex: Index {
return 0
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@_inlineable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@_inlineable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Returns an empty iterator.
@_inlineable // FIXME(sil-serialize-all)
public func makeIterator() -> EmptyIterator<Element> {
return EmptyIterator()
}
/// Accesses the element at the given position.
///
/// Must never be called, since this collection is always empty.
@_inlineable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
get {
_preconditionFailure("Index out of range")
}
set {
_preconditionFailure("Index out of range")
}
}
@_inlineable // FIXME(sil-serialize-all)
public subscript(bounds: Range<Index>) -> EmptyCollection<Element> {
get {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
return self
}
set {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
}
}
/// The number of elements (always zero).
@_inlineable // FIXME(sil-serialize-all)
public var count: Int {
return 0
}
@_inlineable // FIXME(sil-serialize-all)
public func index(_ i: Index, offsetBy n: Int) -> Index {
_debugPrecondition(i == startIndex && n == 0, "Index out of range")
return i
}
@_inlineable // FIXME(sil-serialize-all)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_debugPrecondition(i == startIndex && limit == startIndex,
"Index out of range")
return n == 0 ? i : nil
}
/// The distance between two indexes (always zero).
@_inlineable // FIXME(sil-serialize-all)
public func distance(from start: Index, to end: Index) -> Int {
_debugPrecondition(start == 0, "From must be startIndex (or endIndex)")
_debugPrecondition(end == 0, "To must be endIndex (or startIndex)")
return 0
}
@_inlineable // FIXME(sil-serialize-all)
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_debugPrecondition(index == 0, "out of bounds")
_debugPrecondition(bounds == Range(indices),
"invalid bounds for an empty collection")
}
@_inlineable // FIXME(sil-serialize-all)
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_debugPrecondition(range == Range(indices),
"invalid range for an empty collection")
_debugPrecondition(bounds == Range(indices),
"invalid bounds for an empty collection")
}
}
extension EmptyCollection : Equatable {
@_inlineable // FIXME(sil-serialize-all)
public static func == (
lhs: EmptyCollection<Element>, rhs: EmptyCollection<Element>
) -> Bool {
return true
}
}
| apache-2.0 |
ioscreator/ioscreator | IOSDrawCirclesTutorial/IOSDrawCirclesTutorial/SceneDelegate.swift | 1 | 2369 | //
// SceneDelegate.swift
// IOSDrawCirclesTutorial
//
// Created by Arthur Knopper on 02/02/2020.
// Copyright © 2020 Arthur Knopper. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| mit |
Draveness/RbSwift | RbSwift/IO/Pathname.swift | 1 | 3383 | //
// Path.swift
// RbSwift
//
// Created by Draveness on 10/04/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
public struct Pathname {
public let path: String
public init(_ path: String) {
self.path = path
}
/// Returns the current working directory as a Pathname.
public static var getwd: Pathname {
return Pathname(Dir.getwd)
}
/// Predicate method for testing whether a path is absolute.
public var isAbsolute: Bool {
return path.hasPrefix("/")
}
}
extension Pathname: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: Pathname, rhs: Pathname) -> Bool {
return lhs.path == rhs.path
}
}
public func +(lhs: Pathname, rhs: Pathname) -> Pathname {
return lhs.path.appendPath(rhs.path)
}
public func +(lhs: String, rhs: Pathname) -> Pathname {
return lhs.appendPath(rhs.path)
}
public func +(lhs: Pathname, rhs: String) -> Pathname {
return lhs.path.appendPath(rhs)
}
/// Appends a String fragment to another String to produce a new Path
/// Origianally from https://github.com/kylef/PathKit/blob/master/Sources/PathKit.swift#L750
private extension String {
func appendPath(_ path: String) -> Pathname {
if path.hasPrefix("/") {
// Absolute paths replace relative paths
return Pathname(path)
} else {
var lSlice = NSString(string: self).pathComponents
var rSlice = NSString(string: path).pathComponents
// Get rid of trailing "/" at the left side
if lSlice.count > 1 && lSlice.last == "/" { lSlice.removeLast() }
// Advance after the first relevant "."
lSlice = lSlice.filter { $0 != "." }
rSlice = rSlice.filter { $0 != "." }
// Eats up trailing components of the left and leading ".." of the right side
while lSlice.last != ".." && rSlice.first == ".." {
if (lSlice.count > 1 || lSlice.first != "/") && !lSlice.isEmpty {
// A leading "/" is never popped
lSlice.removeLast()
}
if !rSlice.isEmpty {
rSlice.removeFirst()
}
switch (lSlice.isEmpty, rSlice.isEmpty) {
case (true, _):
break
case (_, true):
break
default:
continue
}
}
let components = lSlice + rSlice
if components.isEmpty {
return Pathname(".")
} else if components.first == "/" && components.count > 1 {
let p = components.joined(separator: "/")
let path = String(p[p.index(after: p.startIndex)...])
return Pathname(path)
} else {
let path = components.joined(separator: "/")
return Pathname(path)
}
}
}
}
| mit |
halo/LinkLiar | LinkHelper/Classes/UninstallHelper.swift | 1 | 2108 | /*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
struct UninstallHelper {
static func perform() {
removePlist()
removeExecutable()
bootout()
}
private static func removePlist() {
do {
try FileManager.default.removeItem(atPath: Paths.helperPlistFile)
} catch let error as NSError {
Log.error("Could not delete Helper plist at \(Paths.helperPlistFile) is it there? \(error.localizedDescription)")
}
}
private static func removeExecutable() {
do {
try FileManager.default.removeItem(atPath: Paths.helperExecutable)
} catch let error as NSError {
Log.info("Could not delete Helper executable at \(Paths.helperExecutable) is it there? \(error.localizedDescription)")
}
}
private static func bootout() {
let task = Process()
task.launchPath = "/usr/bin/sudo"
task.arguments = ["/bin/launchctl", "bootout", "system/\(Identifiers.helper.rawValue)"]
Log.info("Booting out Privileged Helper...")
task.launch()
}
}
| mit |
dclelland/AudioKit | AudioKit/Common/Nodes/Playback/Sequencer/AKFader.swift | 1 | 6633 | //
// AKFader.swift
// AudioKit
//
// Created by Jeff Cooper on 4/12/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
public enum CurveType {
case Linear, EqualPower, Exponential
public static func fromString(curve: String) -> CurveType {
switch curve {
case "linear":
return .Linear
case "exponential":
return .Exponential
case "equalpower":
return .EqualPower
default:
return .Linear
}
}
}
public class AKFader {
let π = M_PI
var output: AKBooster?
var initialVolume: Double = 1.0 //make these only 0 or 1 right now
var finalVolume: Double = 0.0 //make these only 0 or 1 right now
var controlRate: Double = 1 / 30 // 30 times per second
var curveType: CurveType = .Linear
var curvature: Double = 0.5 //doesn't apply to linear
var duration: Double = 1.0 //seconds
var offset: Double = 0.0
var stepCounter = 0
var stepCount = 0
var fadeTimer = NSTimer()
var fadeScheduleTimer = NSTimer()
/// Init with a single control output
public init(initialVolume: Double,
finalVolume: Double,
duration: Double = 1.0,
type: CurveType = .Exponential,
curvature: Double = 1.0,
offset: Double = 0.0,
output: AKBooster) {
self.initialVolume = initialVolume
self.finalVolume = finalVolume
curveType = type
self.curvature = curvature
self.duration = duration
self.offset = offset
stepCount = Int(floor(duration / controlRate))
self.output = output
}
func scheduleFade(fireTime: Double) {
//this schedules a fade to start after fireTime
fadeScheduleTimer = NSTimer.scheduledTimerWithTimeInterval(
fireTime + offset,
target: self,
selector: #selector(scheduleFadeTimer),
userInfo: nil,
repeats: false)
//print("scheduled for \(fireTime) @ \(duration) seconds")
output!.gain = initialVolume
}
@objc func scheduleFadeTimer(timer: NSTimer) {
startImmediately()
}
public func start() { //starts the fade WITH the offset
scheduleFade(0.0)
}
public func startImmediately() { //skips the offset
//this starts the recurring timer
//print("starting fade \((finalVolume > initialVolume ? "up" : "down"))")
stepCounter = 0
if fadeTimer.valid {
fadeTimer.invalidate()
}
fadeTimer = NSTimer.scheduledTimerWithTimeInterval(controlRate,
target: self,
selector: #selector(updateFade),
userInfo: nil,
repeats: true)
}
@objc func updateFade(timer: NSTimer) {
let direction: Double = (initialVolume > finalVolume ? 1.0 : -1.0)
if stepCount == 0{
endFade()
}else if stepCounter <= stepCount {
let controlAmount: Double = Double(stepCounter) / Double(stepCount) //normalized 0-1 value
var scaledControlAmount: Double = 0.0
switch curveType {
case .Linear:
scaledControlAmount = AKFader.denormalize(controlAmount,
minimum: initialVolume,
maximum: finalVolume,
taper: 1)
case .Exponential:
scaledControlAmount = AKFader.denormalize(controlAmount,
minimum: initialVolume,
maximum: finalVolume,
taper: curvature)
case .EqualPower:
scaledControlAmount = pow((0.5 + 0.5 * direction * cos(π * controlAmount)), 0.5) //direction will be negative if going up
}
output!.gain = scaledControlAmount
stepCounter += 1
//print(scaledControlAmount)
} else {
endFade()
}
}//end updateFade
func endFade(){
fadeTimer.invalidate()
output!.gain = finalVolume
stepCounter = 0
}
static func denormalize(input: Double, minimum: Double, maximum: Double, taper: Double) -> Double {
if taper > 0 {
// algebraic taper
return minimum + (maximum - minimum) * pow(input, taper)
} else {
// exponential taper
var adjustedMinimum: Double = 0.0
var adjustedMaximum: Double = 0.0
if minimum == 0 { adjustedMinimum = 0.00000000001 }
if maximum == 0 { adjustedMaximum = 0.00000000001 }
return log(input / adjustedMinimum) / log(adjustedMaximum / adjustedMinimum);//not working right for 0 values
}
}
static func generateCurvePoints(source: Double,
target: Double,
duration: Double = 1.0,
type: CurveType = .Exponential,
curvature: Double = 1.0,
controlRate: Double = 1/30) -> [Double] {
var curvePoints = [Double]()
let stepCount = Int(floor(duration / controlRate))
var counter = 0
let direction: Double = source > target ? 1.0 : -1.0
if counter <= stepCount {
let controlAmount: Double = Double(counter) / Double(stepCount) //normalised 0-1 value
var scaledControlAmount: Double = 0.0
switch type {
case .Linear:
scaledControlAmount = denormalize(controlAmount, minimum: source, maximum: target, taper: 1)
case .Exponential:
scaledControlAmount = denormalize(controlAmount, minimum: source, maximum: target, taper: curvature)
case .EqualPower:
scaledControlAmount = pow((0.5 + 0.5 * direction * cos(M_PI * controlAmount)), 0.5) //direction will be negative if going up
}
curvePoints.append(scaledControlAmount)
counter += 1
}
return curvePoints
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/06722-swift-sourcemanager-getmessage.swift | 11 | 328 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
case c() {
enum A {
func c() {
protocol A {
struct g<d : B<b {
class a {
extension g: A {
struct c == e.h> () as a<T where g<T : c,
protocol A {
class
case c,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/16482-swift-sourcemanager-getmessage.swift | 11 | 222 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
[ {
let a {
case
let a = ( {
struct A {
class
case ,
| mit |
optimizely/swift-sdk | Sources/Optimizely/OptimizelyClient.swift | 1 | 44451 | //
// Copyright 2019-2022, Optimizely, Inc. and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public typealias OptimizelyAttributes = [String: Any?]
public typealias OptimizelyEventTags = [String: Any]
open class OptimizelyClient: NSObject {
// MARK: - Properties
var sdkKey: String
private var atomicConfig = AtomicProperty<ProjectConfig>()
var config: ProjectConfig? {
get {
return atomicConfig.property
}
set {
atomicConfig.property = newValue
if let newValue = newValue {
odpManager.updateOdpConfig(apiKey: newValue.publicKeyForODP,
apiHost: newValue.hostForODP,
segmentsToCheck: newValue.allSegments)
}
}
}
var defaultDecideOptions: [OptimizelyDecideOption]
public var version: String {
return Utils.sdkVersion
}
let eventLock = DispatchQueue(label: "com.optimizely.client")
// MARK: - Customizable Services
var logger: OPTLogger!
var eventDispatcher: OPTEventDispatcher?
public var datafileHandler: OPTDatafileHandler?
// MARK: - Default Services
var decisionService: OPTDecisionService!
public var notificationCenter: OPTNotificationCenter?
var odpManager: OdpManager
let sdkSettings: OptimizelySdkSettings
// MARK: - Public interfaces
/// OptimizelyClient init
///
/// - Parameters:
/// - sdkKey: sdk key
/// - logger: custom Logger
/// - eventDispatcher: custom EventDispatcher (optional)
/// - datafileHandler: custom datafile handler (optional)
/// - userProfileService: custom UserProfileService (optional)
/// - defaultLogLevel: default log level (optional. default = .info)
/// - defaultDecisionOptions: default decision options (optional)
/// - settings: SDK configuration (optional)
public init(sdkKey: String,
logger: OPTLogger? = nil,
eventDispatcher: OPTEventDispatcher? = nil,
datafileHandler: OPTDatafileHandler? = nil,
userProfileService: OPTUserProfileService? = nil,
defaultLogLevel: OptimizelyLogLevel? = nil,
defaultDecideOptions: [OptimizelyDecideOption]? = nil,
settings: OptimizelySdkSettings? = nil) {
self.sdkKey = sdkKey
self.sdkSettings = settings ?? OptimizelySdkSettings()
self.defaultDecideOptions = defaultDecideOptions ?? []
self.odpManager = OdpManager(sdkKey: sdkKey,
disable: sdkSettings.disableOdp,
cacheSize: sdkSettings.segmentsCacheSize,
cacheTimeoutInSecs: sdkSettings.segmentsCacheTimeoutInSecs)
super.init()
let userProfileService = userProfileService ?? DefaultUserProfileService()
let logger = logger ?? DefaultLogger()
type(of: logger).logLevel = defaultLogLevel ?? .info
self.registerServices(sdkKey: sdkKey,
logger: logger,
eventDispatcher: eventDispatcher ?? DefaultEventDispatcher.sharedInstance,
datafileHandler: datafileHandler ?? DefaultDatafileHandler(),
decisionService: DefaultDecisionService(userProfileService: userProfileService),
notificationCenter: DefaultNotificationCenter())
self.logger = HandlerRegistryService.shared.injectLogger()
self.eventDispatcher = HandlerRegistryService.shared.injectEventDispatcher(sdkKey: self.sdkKey)
self.datafileHandler = HandlerRegistryService.shared.injectDatafileHandler(sdkKey: self.sdkKey)
self.decisionService = HandlerRegistryService.shared.injectDecisionService(sdkKey: self.sdkKey)
self.notificationCenter = HandlerRegistryService.shared.injectNotificationCenter(sdkKey: self.sdkKey)
logger.d("SDK Version: \(version)")
}
/// Start Optimizely SDK (Asynchronous)
///
/// If an updated datafile is available in the server, it's downloaded and the SDK is configured with
/// the updated datafile.
///
/// - Parameters:
/// - resourceTimeout: timeout for datafile download (optional)
/// - completion: callback when initialization is completed
public func start(resourceTimeout: Double? = nil, completion: ((OptimizelyResult<Data>) -> Void)? = nil) {
datafileHandler?.downloadDatafile(sdkKey: sdkKey,
returnCacheIfNoChange: true,
resourceTimeoutInterval: resourceTimeout) { [weak self] result in
guard let self = self else {
completion?(.failure(.sdkNotReady))
return
}
switch result {
case .success(let datafile):
guard let datafile = datafile else {
completion?(.failure(.datafileLoadingFailed(self.sdkKey)))
return
}
do {
try self.configSDK(datafile: datafile)
completion?(.success(datafile))
} catch {
completion?(.failure(error as! OptimizelyError))
}
case .failure(let error):
completion?(.failure(error))
}
}
}
/// Start Optimizely SDK (Synchronous)
///
/// - Parameters:
/// - datafile: This datafile will be used when cached copy is not available (fresh start).
/// A cached copy from previous download is used if it's available.
/// The datafile will be updated from the server in the background thread.
public func start(datafile: String) throws {
let datafileData = Data(datafile.utf8)
try start(datafile: datafileData)
}
/// Start Optimizely SDK (Synchronous)
///
/// - Parameters:
/// - datafile: This datafile will be used when cached copy is not available (fresh start)
/// A cached copy from previous download is used if it's available.
/// The datafile will be updated from the server in the background thread.
/// - doUpdateConfigOnNewDatafile: When a new datafile is fetched from the server in the background thread,
/// the SDK will be updated with the new datafile immediately if this value is set to true.
/// When it's set to false (default), the new datafile is cached and will be used when the SDK is started again.
/// - doFetchDatafileBackground: This is for debugging purposes when
/// you don't want to download the datafile. In practice, you should allow the
/// background thread to update the cache copy (optional)
public func start(datafile: Data,
doUpdateConfigOnNewDatafile: Bool = false,
doFetchDatafileBackground: Bool = true) throws {
let cachedDatafile = self.sdkKey.isEmpty ? nil :datafileHandler?.loadSavedDatafile(sdkKey: self.sdkKey)
let selectedDatafile = cachedDatafile ?? datafile
try configSDK(datafile: selectedDatafile)
// continue to fetch updated datafile from the server in background and cache it for next sessions
if !doFetchDatafileBackground { return }
guard let datafileHandler = datafileHandler else { return }
datafileHandler.downloadDatafile(sdkKey: sdkKey, returnCacheIfNoChange: false) { [weak self] result in
guard let self = self else { return }
// override to update always if periodic datafile polling is enabled
// this is necessary for the case that the first cache download gets the updated datafile
guard doUpdateConfigOnNewDatafile || datafileHandler.hasPeriodicInterval(sdkKey: self.sdkKey) else { return }
if case .success(let data) = result, let datafile = data {
// new datafile came in
self.updateConfigFromBackgroundFetch(data: datafile)
}
}
}
func configSDK(datafile: Data) throws {
do {
self.config = try ProjectConfig(datafile: datafile)
datafileHandler?.startUpdates(sdkKey: self.sdkKey) { data in
// new datafile came in
self.updateConfigFromBackgroundFetch(data: data)
}
} catch let error as OptimizelyError {
// .datafileInvalid
// .datafaileVersionInvalid
// .datafaileLoadingFailed
self.logger.e(error)
throw error
} catch {
self.logger.e(error.localizedDescription)
throw error
}
}
func updateConfigFromBackgroundFetch(data: Data) {
guard let config = try? ProjectConfig(datafile: data) else {
return
}
// if a download fails for any reason, the cached datafile is returned
// check and see if the revisions are the same and don't update if they are
guard config.project.revision != self.config?.project.revision else {
return
}
if let users = self.config?.whitelistUsers {
config.whitelistUsers = users
}
self.config = config
// call reinit on the services we know we are reinitializing.
for component in HandlerRegistryService.shared.lookupComponents(sdkKey: self.sdkKey) ?? [] {
HandlerRegistryService.shared.reInitializeComponent(service: component, sdkKey: self.sdkKey)
}
self.sendDatafileChangeNotification(data: data)
}
/**
* Use the activate method to start an experiment.
*
* The activate call will conditionally activate an experiment for a user based on the provided experiment key and a randomized hash of the provided user ID.
* If the user satisfies audience conditions for the experiment and the experiment is valid and running, the function returns the variation the user is bucketed into.
* Otherwise, activate returns nil. Make sure that your code adequately deals with the case when the experiment is not activated (e.g. execute the default variation).
*/
/// Try to activate an experiment based on the experiment key and user ID with user attributes.
///
/// - Parameters:
/// - experimentKey: The key for the experiment.
/// - userId: The user ID to be used for bucketing.
/// - attributes: A map of attribute names to current user attribute values.
/// - Returns: The variation key the user was bucketed into
/// - Throws: `OptimizelyError` if error is detected
public func activate(experimentKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> String {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
guard let experiment = config.getExperiment(key: experimentKey) else {
throw OptimizelyError.experimentKeyInvalid(experimentKey)
}
let variation = try getVariation(experimentKey: experimentKey, userId: userId, attributes: attributes)
sendImpressionEvent(experiment: experiment,
variation: variation,
userId: userId,
attributes: attributes,
flagKey: "",
ruleType: Constants.DecisionSource.experiment.rawValue,
enabled: true)
return variation.key
}
/// Get variation for experiment and user ID with user attributes.
///
/// - Parameters:
/// - experimentKey: The key for the experiment.
/// - userId: The user ID to be used for bucketing.
/// - attributes: A map of attribute names to current user attribute values.
/// - Returns: The variation key the user was bucketed into
/// - Throws: `OptimizelyError` if error is detected
public func getVariationKey(experimentKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> String {
let variation = try getVariation(experimentKey: experimentKey, userId: userId, attributes: attributes)
return variation.key
}
func getVariation(experimentKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> Variation {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
guard let experiment = config.getExperiment(key: experimentKey) else {
throw OptimizelyError.experimentKeyInvalid(experimentKey)
}
let variation = decisionService.getVariation(config: config,
experiment: experiment,
user: createUserContext(userId: userId,
attributes: attributes),
options: nil).result
let decisionType: Constants.DecisionType = config.isFeatureExperiment(id: experiment.id) ? .featureTest : .abTest
sendDecisionNotification(userId: userId,
attributes: attributes,
decisionInfo: DecisionInfo(decisionType: decisionType,
experiment: experiment,
variation: variation))
if let variation = variation {
return variation
} else {
throw OptimizelyError.variationUnknown(userId, experimentKey)
}
}
/**
* Use the setForcedVariation method to force an experimentKey-userId
* pair into a specific variation for QA purposes.
* The forced bucketing feature allows customers to force users into
* variations in real time for QA purposes without requiring datafile
* downloads from the network. Methods activate and track are called
* as usual after the variation is set, but the user will be bucketed
* into the forced variation overriding any variation which would be
* computed via the network datafile.
*/
/// Get forced variation for experiment and user ID.
///
/// - Parameters:
/// - experimentKey: The key for the experiment.
/// - userId: The user ID to be used for bucketing.
/// - Returns: forced variation key if it exists, otherwise return nil.
public func getForcedVariation(experimentKey: String, userId: String) -> String? {
guard let config = self.config else { return nil }
let variaion = config.getForcedVariation(experimentKey: experimentKey, userId: userId).result
return variaion?.key
}
/// Set forced variation for experiment and user ID to variationKey.
///
/// - Parameters:
/// - experimentKey: The key for the experiment.
/// - userId: The user ID to be used for bucketing.
/// - variationKey: The variation the user should be forced into.
/// This value can be nil, in which case, the forced variation is cleared.
/// - Returns: true if forced variation set successfully
public func setForcedVariation(experimentKey: String,
userId: String,
variationKey: String?) -> Bool {
guard let config = self.config else { return false }
return config.setForcedVariation(experimentKey: experimentKey,
userId: userId,
variationKey: variationKey)
}
/// Determine whether a feature is enabled.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: true if feature is enabled, false otherwise.
public func isFeatureEnabled(featureKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) -> Bool {
guard let config = self.config else {
logger.e(.sdkNotReady)
return false
}
guard let featureFlag = config.getFeatureFlag(key: featureKey) else {
logger.e(.featureKeyInvalid(featureKey))
return false
}
let pair = decisionService.getVariationForFeature(config: config,
featureFlag: featureFlag,
user: createUserContext(userId: userId,
attributes: attributes),
options: nil).result
let source = pair?.source ?? Constants.DecisionSource.rollout.rawValue
let featureEnabled = pair?.variation.featureEnabled ?? false
if featureEnabled {
logger.i(.featureEnabledForUser(featureKey, userId))
} else {
logger.i(.featureNotEnabledForUser(featureKey, userId))
}
if shouldSendDecisionEvent(source: source, decision: pair) {
sendImpressionEvent(experiment: pair?.experiment,
variation: pair?.variation,
userId: userId,
attributes: attributes,
flagKey: featureKey,
ruleType: source,
enabled: featureEnabled)
}
sendDecisionNotification(userId: userId,
attributes: attributes,
decisionInfo: DecisionInfo(decisionType: .feature,
experiment: pair?.experiment,
variation: pair?.variation,
source: source,
feature: featureFlag,
featureEnabled: featureEnabled))
return featureEnabled
}
/// Gets boolean feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type boolean.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableBoolean(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> Bool {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
/// Gets double feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type double.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableDouble(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> Double {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
/// Gets integer feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type integer.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableInteger(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> Int {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
/// Gets string feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type string.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableString(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> String {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
/// Gets json feature variable value.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - variableKey: The key for the variable.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: feature variable value of type OptimizelyJSON.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getFeatureVariableJSON(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> OptimizelyJSON {
return try getFeatureVariable(featureKey: featureKey,
variableKey: variableKey,
userId: userId,
attributes: attributes)
}
func getFeatureVariable<T>(featureKey: String,
variableKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> T {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
guard let featureFlag = config.getFeatureFlag(key: featureKey) else {
throw OptimizelyError.featureKeyInvalid(featureKey)
}
guard let variable = featureFlag.getVariable(key: variableKey) else {
throw OptimizelyError.variableKeyInvalid(variableKey, featureKey)
}
var featureValue = variable.defaultValue ?? ""
let decision = decisionService.getVariationForFeature(config: config,
featureFlag: featureFlag,
user: createUserContext(userId: userId,
attributes: attributes),
options: nil).result
if let decision = decision {
if let featureVariable = decision.variation.variables?.filter({$0.id == variable.id}).first {
if let featureEnabled = decision.variation.featureEnabled, featureEnabled {
featureValue = featureVariable.value
logger.i(.userReceivedVariableValue(featureValue, variableKey, featureKey))
} else {
logger.i(.featureNotEnabledReturnDefaultVariableValue(userId, featureKey, variableKey))
}
}
} else {
logger.i(.userReceivedDefaultVariableValue(userId, featureKey, variableKey))
}
var type: Constants.VariableValueType?
var valueParsed: T?
var notificationValue: Any? = featureValue
switch T.self {
case is String.Type:
type = .string
valueParsed = featureValue as? T
notificationValue = valueParsed
case is Int.Type:
type = .integer
valueParsed = Int(featureValue) as? T
notificationValue = valueParsed
case is Double.Type:
type = .double
valueParsed = Double(featureValue) as? T
notificationValue = valueParsed
case is Bool.Type:
type = .boolean
valueParsed = Bool(featureValue) as? T
notificationValue = valueParsed
case is OptimizelyJSON.Type:
type = .json
let jsonValue = OptimizelyJSON(payload: featureValue)
valueParsed = jsonValue as? T
notificationValue = jsonValue?.toMap()
default:
break
}
guard let value = valueParsed,
type?.rawValue == variable.type else {
throw OptimizelyError.variableValueInvalid(variableKey)
}
// Decision Notification
let experiment = decision?.experiment
let variation = decision?.variation
let featureEnabled = variation?.featureEnabled ?? false
sendDecisionNotification(userId: userId,
attributes: attributes,
decisionInfo: DecisionInfo(decisionType: .featureVariable,
experiment: experiment,
variation: variation,
source: decision?.source,
feature: featureFlag,
featureEnabled: featureEnabled,
variableKey: variableKey,
variableType: variable.type,
variableValue: notificationValue))
return value
}
/// Gets all the variables for a given feature.
///
/// - Parameters:
/// - featureKey: The key for the feature flag.
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: all the variables for a given feature.
/// - Throws: `OptimizelyError` if feature parameter is not valid
public func getAllFeatureVariables(featureKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil) throws -> OptimizelyJSON {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
var variableMap = [String: Any]()
var enabled = false
guard let featureFlag = config.getFeatureFlag(key: featureKey) else {
throw OptimizelyError.featureKeyInvalid(featureKey)
}
let decision = decisionService.getVariationForFeature(config: config,
featureFlag: featureFlag,
user: createUserContext(userId: userId,
attributes: attributes),
options: nil).result
if let featureEnabled = decision?.variation.featureEnabled {
enabled = featureEnabled
if featureEnabled {
logger.i(.featureEnabledForUser(featureKey, userId))
} else {
logger.i(.featureNotEnabledForUser(featureKey, userId))
}
} else {
logger.i(.userReceivedAllDefaultVariableValues(userId, featureKey))
}
for v in featureFlag.variables {
var featureValue = v.defaultValue ?? ""
if enabled, let variable = decision?.variation.getVariable(id: v.id) {
featureValue = variable.value
}
var valueParsed: Any? = featureValue
if let valueType = Constants.VariableValueType(rawValue: v.type) {
switch valueType {
case .string:
break
case .integer:
valueParsed = Int(featureValue)
case .double:
valueParsed = Double(featureValue)
case .boolean:
valueParsed = Bool(featureValue)
case .json:
valueParsed = OptimizelyJSON(payload: featureValue)?.toMap()
}
}
if let value = valueParsed {
variableMap[v.key] = value
} else {
logger.e(OptimizelyError.variableValueInvalid(v.key))
}
}
guard let optimizelyJSON = OptimizelyJSON(map: variableMap) else {
throw OptimizelyError.invalidJSONVariable
}
sendDecisionNotification(userId: userId,
attributes: attributes,
decisionInfo: DecisionInfo(decisionType: .allFeatureVariables,
experiment: decision?.experiment,
variation: decision?.variation,
source: decision?.source,
feature: featureFlag,
featureEnabled: enabled,
variableValues: variableMap))
return optimizelyJSON
}
/// Get array of features that are enabled for the user.
///
/// - Parameters:
/// - userId: The user ID to be used for bucketing.
/// - attributes: The user's attributes.
/// - Returns: Array of feature keys that are enabled for the user.
public func getEnabledFeatures(userId: String,
attributes: OptimizelyAttributes? = nil) -> [String] {
var enabledFeatures = [String]()
guard let config = self.config else {
logger.e(.sdkNotReady)
return enabledFeatures
}
enabledFeatures = config.getFeatureFlags().filter {
isFeatureEnabled(featureKey: $0.key, userId: userId, attributes: attributes)
}.map { $0.key }
return enabledFeatures
}
/// Track an event
///
/// - Parameters:
/// - eventKey: The event name
/// - userId: The user ID associated with the event to track
/// - attributes: The user's attributes.
/// - eventTags: A map of event tag names to event tag values (NSString or NSNumber containing float, double, integer, or boolean)
/// - Throws: `OptimizelyError` if error is detected
public func track(eventKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil,
eventTags: OptimizelyEventTags? = nil) throws {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
if config.getEvent(key: eventKey) == nil {
throw OptimizelyError.eventKeyInvalid(eventKey)
}
sendConversionEvent(eventKey: eventKey, userId: userId, attributes: attributes, eventTags: eventTags)
}
/// Read a copy of project configuration data model.
///
/// This call returns a snapshot of the current project configuration.
///
/// When the caller keeps a copy of the return value, note that this data can be stale when a new datafile is downloaded (it's possible only when background datafile polling is enabled).
///
/// If a datafile change is notified (NotificationType.datafileChange), this method should be called again to get the updated configuration data.
///
/// - Returns: a snapshot of public project configuration data model
/// - Throws: `OptimizelyError` if SDK is not ready
public func getOptimizelyConfig() throws -> OptimizelyConfig {
guard let config = self.config else { throw OptimizelyError.sdkNotReady }
return OptimizelyConfigImp(projectConfig: config)
}
}
// MARK: - Send Events
extension OptimizelyClient {
func shouldSendDecisionEvent(source: String, decision: FeatureDecision?) -> Bool {
guard let config = self.config else { return false }
return (source == Constants.DecisionSource.featureTest.rawValue && decision?.variation != nil) || config.sendFlagDecisions
}
func sendImpressionEvent(experiment: Experiment?,
variation: Variation?,
userId: String,
attributes: OptimizelyAttributes? = nil,
flagKey: String,
ruleType: String,
enabled: Bool) {
// non-blocking (event data serialization takes time)
eventLock.async {
guard let config = self.config else { return }
guard let body = BatchEventBuilder.createImpressionEvent(config: config,
experiment: experiment,
variation: variation,
userId: userId,
attributes: attributes,
flagKey: flagKey,
ruleType: ruleType,
enabled: enabled) else {
self.logger.e(OptimizelyError.eventBuildFailure(DispatchEvent.activateEventKey))
return
}
let event = EventForDispatch(body: body)
self.sendEventToDispatcher(event: event, completionHandler: nil)
// send notification in sync mode (functionally same as async here since it's already in background thread),
// but this will make testing simpler (timing control)
if let tmpExperiment = experiment, let tmpVariation = variation {
self.sendActivateNotification(experiment: tmpExperiment,
variation: tmpVariation,
userId: userId,
attributes: attributes,
event: event,
async: false)
}
}
}
func sendConversionEvent(eventKey: String,
userId: String,
attributes: OptimizelyAttributes? = nil,
eventTags: OptimizelyEventTags? = nil) {
// non-blocking (event data serialization takes time)
eventLock.async {
guard let config = self.config else { return }
guard let body = BatchEventBuilder.createConversionEvent(config: config,
eventKey: eventKey,
userId: userId,
attributes: attributes,
eventTags: eventTags) else {
self.logger.e(OptimizelyError.eventBuildFailure(eventKey))
return
}
let event = EventForDispatch(body: body)
self.sendEventToDispatcher(event: event, completionHandler: nil)
// send notification in sync mode (functionally same as async here since it's already in background thread),
// but this will make testing simpler (timing control)
self.sendTrackNotification(eventKey: eventKey,
userId: userId,
attributes: attributes,
eventTags: eventTags,
event: event,
async: false)
}
}
func sendEventToDispatcher(event: EventForDispatch, completionHandler: DispatchCompletionHandler?) {
// The event is queued in the dispatcher, batched, and sent out later.
// make sure that eventDispatcher is not-nil (still registered when async dispatchEvent is called)
self.eventDispatcher?.dispatchEvent(event: event, completionHandler: completionHandler)
}
}
// MARK: - Notifications
extension OptimizelyClient {
func sendActivateNotification(experiment: Experiment,
variation: Variation,
userId: String,
attributes: OptimizelyAttributes?,
event: EventForDispatch,
async: Bool = true) {
self.sendNotification(type: .activate,
args: [experiment,
userId,
attributes,
variation,
["url": event.url as Any, "body": event.body as Any]],
async: async)
}
func sendTrackNotification(eventKey: String,
userId: String,
attributes: OptimizelyAttributes?,
eventTags: OptimizelyEventTags?,
event: EventForDispatch,
async: Bool = true) {
self.sendNotification(type: .track,
args: [eventKey,
userId,
attributes,
eventTags,
["url": event.url as Any, "body": event.body as Any]],
async: async)
}
func sendDecisionNotification(userId: String,
attributes: OptimizelyAttributes?,
decisionInfo: DecisionInfo,
async: Bool = true) {
self.sendNotification(type: .decision,
args: [decisionInfo.decisionType.rawValue,
userId,
attributes ?? OptimizelyAttributes(),
decisionInfo.toMap],
async: async)
}
func sendDatafileChangeNotification(data: Data, async: Bool = true) {
self.sendNotification(type: .datafileChange, args: [data], async: async)
}
func sendNotification(type: NotificationType, args: [Any?], async: Bool = true) {
let notify = {
// make sure that notificationCenter is not-nil (still registered when async notification is called)
self.notificationCenter?.sendNotifications(type: type.rawValue, args: args)
}
if async {
eventLock.async {
notify()
}
} else {
notify()
}
}
}
// MARK: - ODP
extension OptimizelyClient {
/// Send an event to the ODP server.
///
/// - Parameters:
/// - type: the event type (default = "fullstack").
/// - action: the event action name.
/// - identifiers: a dictionary for identifiers.
/// - data: a dictionary for associated data. The default event data will be added to this data before sending to the ODP server.
/// - Throws: `OptimizelyError` if error is detected
public func sendOdpEvent(type: String? = nil,
action: String,
identifiers: [String: String] = [:],
data: [String: Any?] = [:]) throws {
try odpManager.sendEvent(type: type ?? Constants.ODP.eventType,
action: action,
identifiers: identifiers,
data: data)
}
/// the device vuid (read only)
public var vuid: String {
return odpManager.vuid
}
func identifyUserToOdp(userId: String) {
odpManager.identifyUser(userId: userId)
}
func fetchQualifiedSegments(userId: String,
options: [OptimizelySegmentOption],
completionHandler: @escaping ([String]?, OptimizelyError?) -> Void) {
odpManager.fetchQualifiedSegments(userId: userId,
options: options,
completionHandler: completionHandler)
}
}
// MARK: - For test support
extension OptimizelyClient {
public func close() {
datafileHandler?.stopUpdates(sdkKey: sdkKey)
eventLock.sync {}
eventDispatcher?.close()
}
}
| apache-2.0 |
TristanBurnside/ChocolateDemo | ChocolatePuppies/View Configurations/TagFilterConfigureOperation.swift | 1 | 541 | //
// TagFilterConfigureOperation.swift
// ChocolatePuppies
//
// Created by Tristan Burnside on 26/03/2016.
// Copyright © 2016 Tristan Burnside. All rights reserved.
//
import UIKit
import Chocolate
class TagFilterConfigureOperation: ChocolateConfigureDataOperation {
@IBOutlet private var dataManager : PuppyDataManager?
override func main() {
if let filterTag = configurationData as? String,
dataManager = dataManager {
dataManager.filterTag = filterTag
}
}
}
| apache-2.0 |
spark/photon-tinker-ios | Photon-Tinker/ScreenUtils.swift | 1 | 1288 | //
// Created by Raimundas Sakalauskas on 03/10/2018.
// Copyright (c) 2018 Particle. All rights reserved.
//
import Foundation
enum PhoneScreenSizeClass: Int, Comparable {
case iPhone4
case iPhone5
case iPhone6
case iPhone6Plus
case iPhoneX
case iPhoneXMax
case other
public static func < (a: PhoneScreenSizeClass, b: PhoneScreenSizeClass) -> Bool {
return a.rawValue < b.rawValue
}
}
class ScreenUtils {
static func isIPad() -> Bool {
return UI_USER_INTERFACE_IDIOM() == .pad
}
static func isIPhone() -> Bool {
return UI_USER_INTERFACE_IDIOM() == .phone
}
static func getPhoneScreenSizeClass() -> PhoneScreenSizeClass {
let screenSize = UIScreen.main.bounds.size
let maxLength = max(screenSize.width, screenSize.height)
if (maxLength <= 480) {
return .iPhone4
} else if (maxLength <= 568) {
return .iPhone5
} else if (maxLength <= 667) {
return .iPhone6
} else if (maxLength <= 736) {
return .iPhone6Plus
} else if (maxLength <= 812) {
return .iPhoneX
} else if (maxLength <= 896) {
return .iPhoneXMax
} else {
return .other
}
}
} | apache-2.0 |
TouchInstinct/LeadKit | TIUIKitCore/Sources/Presenter/UIViewPresenters.swift | 1 | 1279 | //
// Copyright (c) 2022 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public protocol UIViewPresenter {
associatedtype View: AnyObject // should be stored weakly
func didCompleteConfiguration(of view: View)
}
| apache-2.0 |
btanner/Eureka | Source/Rows/ButtonRowWithPresent.swift | 8 | 3718 | // Rows.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
open class _ButtonRowWithPresent<VCType: TypedRowControllerType>: Row<ButtonCellOf<VCType.RowValue>>, PresenterRowType where VCType: UIViewController {
open var presentationMode: PresentationMode<VCType>?
open var onPresentCallback: ((FormViewController, VCType) -> Void)?
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
cellStyle = .default
}
open override func customUpdateCell() {
super.customUpdateCell()
let leftAligmnment = presentationMode != nil
cell.textLabel?.textAlignment = leftAligmnment ? .left : .center
cell.accessoryType = !leftAligmnment || isDisabled ? .none : .disclosureIndicator
cell.editingAccessoryType = cell.accessoryType
if !leftAligmnment {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
cell.tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
cell.textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha:isDisabled ? 0.3 : 1.0)
} else {
cell.textLabel?.textColor = nil
}
}
open override func customDidSelect() {
super.customDidSelect()
if let presentationMode = presentationMode, !isDisabled {
if let controller = presentationMode.makeController() {
controller.row = self
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.present(controller, row: self, presentingController: cell.formViewController()!)
} else {
presentationMode.present(nil, row: self, presentingController: cell.formViewController()!)
}
}
}
open override func prepare(for segue: UIStoryboardSegue) {
super.prepare(for: segue)
guard let rowVC = segue.destination as? VCType else {
return
}
if let callback = presentationMode?.onDismissCallback {
rowVC.onDismissCallback = callback
}
rowVC.row = self
onPresentCallback?(cell.formViewController()!, rowVC)
}
}
// MARK: Rows
/// A generic row with a button that presents a view controller when tapped
public final class ButtonRowWithPresent<VCType: TypedRowControllerType> : _ButtonRowWithPresent<VCType>, RowType where VCType: UIViewController {
public required init(tag: String?) {
super.init(tag: tag)
}
}
| mit |
L3-DANT/findme-app | findme/Controller/RegisterViewController.swift | 1 | 5853 | //
// RegisterViewController.swift
// findme
//
// Created by Maxime Signoret on 05/05/16.
// Copyright © 2016 Maxime Signoret. All rights reserved.
//
import UIKit
class RegisterViewController: UIViewController {
let wsBaseUrl = APICommunicator.getInstance.getBaseUrl()
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var phoneNumberField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var confirmPasswordField: UITextField!
@IBOutlet weak var pulseView: UIImageView!
@IBOutlet weak var registerAnimationView: UIImageView!
@IBAction func registerButton(sender: AnyObject) {
let username:NSString = self.usernameField.text!
let phoneNumber:NSString = self.phoneNumberField.text!
let password:NSString = self.passwordField.text!
let confirm_password:NSString = self.confirmPasswordField.text!
if (username.isEqualToString("") || phoneNumber.isEqualToString("") || password.isEqualToString("") || confirm_password.isEqualToString("")) {
UIAlert("Sign Up Failed!", message: "Please enter Username and Password")
} else if ( !password.isEqual(confirm_password) ) {
UIAlert("Sign Up Failed!", message: "Passwords doesn't Match")
}
if (!checkPhoneNumber(phoneNumber as String)) {
UIAlert("Sign Up Failed!", message: "Invalid phone number")
} else {
do {
let params: [String: String] = ["pseudo": username as String, "phoneNumber": phoneNumber as String, "password": password as String]
let apiService = APIService()
apiService.signUp(params, onCompletion: { user, err in
dispatch_async(dispatch_get_main_queue()) {
if user != nil {
let vc : UIViewController = (self.storyboard!.instantiateViewControllerWithIdentifier("MapViewController") as? MapViewController)!
self.showViewController(vc as UIViewController, sender: vc)
} else {
self.UIAlert("Sign Up Failed!", message: "Wrong username or password")
}
}
})
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
var imageName : String = ""
var imageList : [UIImage] = []
for i in 0...9 {
imageName = "FindMe_intro_0000\(i)"
imageList.append(UIImage(named: imageName)!)
}
for i in 10...69 {
imageName = "FindMe_intro_000\(i)"
imageList.append(UIImage(named: imageName)!)
}
self.registerAnimationView.animationImages = imageList
startAniamtion()
}
func checkPhoneNumber(phoneNumber: String) -> Bool {
let PHONE_REGEX = "(0|(\\+33)|(0033))[1-9][0-9]{8}"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluateWithObject(phoneNumber)
return result
}
func startAniamtion() {
self.registerAnimationView.animationDuration = 2
self.registerAnimationView.animationRepeatCount = 1
self.registerAnimationView.startAnimating()
_ = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(self.startPulse), userInfo: nil, repeats: false)
}
func startPulse() {
let pulseEffect = PulseAnimation(repeatCount: Float.infinity, radius:100, position: CGPoint(x: self.pulseView.center.x-72, y: self.pulseView.center.y-20))
pulseEffect.backgroundColor = UIColor(colorLiteralRed: 0.33, green: 0.69, blue: 0.69, alpha: 1).CGColor
view.layer.insertSublayer(pulseEffect, below: self.registerAnimationView.layer)
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBarHidden = true
}
func keyboardWillShow(notification: NSNotification) {
let userInfo: [NSObject : AnyObject] = notification.userInfo!
let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
let offset: CGSize = userInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue.size
if keyboardSize.height == offset.height {
if self.view.frame.origin.y == 0 {
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.view.frame.origin.y -= keyboardSize.height
})
}
} else {
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.view.frame.origin.y += keyboardSize.height - offset.height
})
}
print(self.view.frame.origin.y)
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y += keyboardSize.height
}
}
func UIAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
}
| mit |
logananderson/MarkovTextGenerator | MarkovTextGenerator/AppDelegate.swift | 1 | 525 | //
// AppDelegate.swift
// MarkovTextGenerator
//
// Created by Logan Anderson on 4/21/15.
// Copyright (c) 2015 loganonthemove.com. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| mit |
austinzheng/swift | test/SourceKit/Misc/ignored-flags-sanitizers.swift | 39 | 216 | var s = 10
s.
// CHECK: littleEndian
// REQUIRES: asan_runtime
// REQUIRES: fuzzer_runtime
// RUN: %sourcekitd-test -req=complete -pos=2:3 %s -- -sanitize=address,fuzzer -sanitize-coverage=func %s | %FileCheck %s
| apache-2.0 |
liuchungui/BGPhotoPickerController | BGPhotoPickerController/Views/BGPhotoGrideCell.swift | 1 | 1245 | //
// BGPhotoGrideCell.swift
// BGPhotoPickerControllerDemo
//
// Created by user on 15/10/13.
// Copyright © 2015年 BG. All rights reserved.
//
import UIKit
class BGPhotoGrideCell: UICollectionViewCell {
private var isDidSelect = false
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var selectImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.borderWidth = 0.3
self.layer.masksToBounds = true
self.isSelect = false
self.selectImageView.hidden = false
}
//MARK: var value
var image: UIImage? {
get {
return self.imageView.image
}
set(newImage) {
self.imageView.image = newImage
}
}
var isSelect: Bool {
get {
return self.isDidSelect
}
set(newValue) {
self.isDidSelect = newValue
if newValue {
self.selectImageView.image = UIImage(named: "ImageSelectedOn.png")
}
else {
self.selectImageView.image = UIImage(named: "ImageSelectedOff.png")
}
}
}
}
| mit |
yuByte/SwiftGo | Examples/Examples.playground/Pages/16. Chinese Whispers.xcplaygroundpage/Contents.swift | 4 | 542 | import SwiftGo
//: Chinese Whispers
//: ----------------
//:
//: 
func whisper(left: ReceivingChannel<Int>, _ right: SendingChannel<Int>) {
left <- 1 + !<-right
}
let numberOfWhispers = 100
let leftmost = Channel<Int>()
var right = leftmost
var left = leftmost
for _ in 0 ..< numberOfWhispers {
right = Channel<Int>()
go(whisper(left.receivingChannel, right.sendingChannel))
left = right
}
go(right <- 1)
print(!<-leftmost)
| mit |
warumono-for-develop/SwiftPageViewController | SwiftPageViewController/SwiftPageViewController/IntroViewController.swift | 1 | 2078 | //
// IntroViewController.swift
// Maniau1
//
// Created by kevin on 2017. 2. 24..
// Copyright © 2017년 warumono. All rights reserved.
//
import UIKit
class IntroViewController: UIViewController
{
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var containerView: UIView!
fileprivate var introPageViewController: IntroPageViewController?
{
didSet
{
introPageViewController?.introPageViewControllerDataSource = self
introPageViewController?.introPageViewControllerDelegate = self
}
}
override var preferredStatusBarStyle: UIStatusBarStyle
{
return .lightContent
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
pageControl.addTarget(self, action: #selector(IntroViewController.didChangePage), for: .valueChanged)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if let introPageViewController = segue.destination as? IntroPageViewController
{
self.introPageViewController = introPageViewController
}
}
}
extension IntroViewController
{
@IBAction func didTouch(_ sender: UIButton)
{
if sender.tag == 0
{
if pageControl.numberOfPages <= pageControl.currentPage + 1
{
return
}
introPageViewController?.pageTo(at: pageControl.numberOfPages - 1)
}
else if sender.tag == 1
{
introPageViewController?.next()
}
}
@objc fileprivate func didChangePage()
{
introPageViewController?.pageTo(at: pageControl.currentPage)
}
}
extension IntroViewController: IntroPageViewControllerDataSource
{
func introPageViewController(_ pageViewController: IntroPageViewController, numberOfPages pages: Int)
{
pageControl.numberOfPages = pages
}
}
extension IntroViewController: IntroPageViewControllerDelegate
{
func introPageViewController(_ pageViewController: IntroPageViewController, didChangePageIndex index: Int)
{
pageControl.currentPage = index
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Sources/FeatureKYCUI/Identity Verification/KYCResubmitIdentityRouter.swift | 1 | 994 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import FeatureKYCDomain
import PlatformKit
import PlatformUIKit
/// Router for handling the KYC document resubmission flow
public final class KYCResubmitIdentityRouter: DeepLinkRouting {
private let settings: KYCSettingsAPI
private let kycRouter: KYCRouterAPI
public init(
settings: KYCSettingsAPI = resolve(),
kycRouter: KYCRouterAPI = resolve()
) {
self.settings = settings
self.kycRouter = kycRouter
}
public func routeIfNeeded() -> Bool {
// Only route if the user actually tapped on the resubmission link
guard settings.didTapOnDocumentResubmissionDeepLink else {
return false
}
guard let viewController = UIApplication.shared.topMostViewController else {
return false
}
kycRouter.start(tier: .tier2, parentFlow: .resubmission, from: viewController)
return true
}
}
| lgpl-3.0 |
simorgh3196/GitHubSearchApp | Carthage/Checkouts/Himotoki/Sources/decode.swift | 1 | 1600 | //
// decode.swift
// Himotoki
//
// Created by Syo Ikeda on 5/19/15.
// Copyright (c) 2015 Syo Ikeda. All rights reserved.
//
/// - Throws: DecodeError or an arbitrary ErrorType
public func decodeValue<T: Decodable>(JSON: AnyJSON) throws -> T {
return try T.decodeValue(JSON)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func decodeValue<T: Decodable>(JSON: AnyJSON, rootKeyPath: KeyPath) throws -> T {
return try T.decodeValue(JSON, rootKeyPath: rootKeyPath)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func decodeArray<T: Decodable>(JSON: AnyJSON) throws -> [T] {
return try [T].decode(JSON)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func decodeArray<T: Decodable>(JSON: AnyJSON, rootKeyPath: KeyPath) throws -> [T] {
return try [T].decode(JSON, rootKeyPath: rootKeyPath)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func decodeDictionary<T: Decodable>(JSON: AnyJSON) throws -> [String: T] {
return try [String: T].decode(JSON)
}
/// - Throws: DecodeError or an arbitrary ErrorType
public func decodeDictionary<T: Decodable>(JSON: AnyJSON, rootKeyPath: KeyPath) throws -> [String: T] {
return try [String: T].decode(JSON, rootKeyPath: rootKeyPath)
}
// MARK: - Deprecated
/// - Throws: DecodeError
@available(*, unavailable, renamed="decodeValue")
@noreturn public func decode<T: Decodable>(JSON: AnyJSON) throws -> T {}
/// - Throws: DecodeError
@available(*, unavailable, renamed="decodeValue")
@noreturn public func decode<T: Decodable>(JSON: AnyJSON, rootKeyPath: KeyPath) throws -> T {}
| mit |
kaxilisi/DouYu | DYZB/DYZB/Classes/Home/View/CollectionHeaderView1.swift | 1 | 892 | //
// CollectionHeaderView.swift
// DYZB
//
// Created by apple on 2016/10/10.
// Copyright © 2016年 apple. All rights reserved.
//
import UIKit
class CollectionHeaderView: UICollectionReusableView {
// MARK:- 控件属性
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var moreBtn: UIButton!
// MARK:- 定义模型属性
var group : AnchorGroup? {
didSet {
titleLabel.text = group?.tag_name
iconImageView.image = UIImage(named: group?.icon_name ?? "home_header_normal")
}
}
}
// MARK:- 从Xib中快速创建的类方法
extension CollectionHeaderView {
class func collectionHeaderView() -> CollectionHeaderView {
return Bundle.main.loadNibNamed("CollectionHeaderView", owner: nil, options: nil)?.first as! CollectionHeaderView
}
}
| mit |
FromF/SlideDisplay | SlideDisplay/SlideDisplay/AVPlayerView.swift | 1 | 544 | //
// AVPlayerView.swift
// SlideDisplay
//
// Created by Fuji on 2015/06/04.
// Copyright (c) 2015年 FromF. All rights reserved.
//
import AVFoundation
import UIKit
// レイヤーをAVPlayerLayerにする為のラッパークラス.
class AVPlayerView : UIView{
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override class func layerClass() -> AnyClass{
return AVPlayerLayer.self
}
}
| mit |
eternityz/RWScrollChart | RWScrollChart/RWSCAppearance.swift | 1 | 1974 | //
// RWSCAppearance.swift
// RWScrollChartDemo
//
// Created by Zhang Bin on 2015-08-04.
// Copyright (c) 2015年 Zhang Bin. All rights reserved.
//
import UIKit
struct RWSCAppearance {
var backgroundColor = UIColor.clearColor()
var contentMargins = UIEdgeInsets(top: 0.0, left: 15.0, bottom: 5.0, right: 30.0)
var backgroundLineWidth: CGFloat = 0.5
var horizontalLineColor = UIColor(white: 1.0, alpha: 0.1)
var showSectionTitles = true
var showSectionSeparator = true
var sectionPadding: CGFloat = 1.0
var sectionTitleFont = UIFont.systemFontOfSize(12.0)
var sectionTitleInsets = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 10.0, right: 5.0)
var sectionTitleColor = UIColor.whiteColor()
var sectionSeparatorColor = UIColor(white: 1.0, alpha: 0.5)
var truncateSectionTitleWhenNeeded = false
var itemPadding: CGFloat = 1.0
var itemWidth: CGFloat = 15.0
var showFocus = true
var focusTextFont = UIFont.systemFontOfSize(12.0)
var focusTextColor = UIColor(white: 0.2, alpha: 1.0)
var focusTextBackgroundColor = UIColor.whiteColor()
var focusTextMargin = CGPoint(x: 6.0, y: 1.0)
var focusTextLineCount = 1
var focusIndicatorRadius: CGFloat = 4.0
var focusColor = UIColor.whiteColor()
var focusStrokeWidth: CGFloat = 1.0
var focusNeedleLength: CGFloat = 5.0
var focusBubbleRoundedRadius: CGFloat = 2.0
var showAxis = true
var axisTextFont = UIFont.systemFontOfSize(10.0)
var axisTextColor = UIColor.whiteColor()
var axisBackgroundColor = UIColor(white: 0, alpha: 0.2)
var axisTextMargin = CGPoint(x: 5.0, y: 2.0)
var axisAreaWidthForViewWith: CGFloat -> CGFloat = { min(50.0, 0.2 * $0) }
var axisLineColor = UIColor(white: 1.0, alpha: 0.05)
var axisLineWidth: CGFloat = 1.0
enum InitialPosition {
case FirstItem
case LastItem
}
var initialPosition: InitialPosition = .LastItem
}
| mit |
BellAppLab/SequencePlayer | Source/SequencePlayer.swift | 1 | 22828 | import UIKit
import AVFoundation
//MARK: Consts
private var sequencePlayerContext = 0
//MARK: - Delegate and Data Source
protocol SequencePlayerDelegate: class {
func sequencePlayerStateDidChange(_ player: SequencePlayer)
func sequencePlayerDidEnd(_ player: SequencePlayer)
}
@objc protocol SequencePlayerDataSource: class {
func numberOfItemsInSequencePlayer(_ player: SequencePlayer) -> Int
func sequencePlayer(_ player: SequencePlayer, itemURLAtIndex index: Int) -> URL
@objc optional func sequencePlayerView(forSequencePlayer player: SequencePlayer) -> SequencePlayerView
}
//MARK: - Player Controls
//MARK: -
extension SequencePlayer
{
func play(atIndex index: Int? = nil) {
guard self.state != .playing else { return }
var didChangeIndex = false
if let i = index {
guard i > -1 && i < self.dataSource.numberOfItemsInSequencePlayer(self) else {
fatalError("Sequence Player index out of bounds... Index: \(index)")
}
self.currentIndex = i
didChangeIndex = true
} else {
if self.currentIndex == NSNotFound {
self.currentIndex = 0
didChangeIndex = true
}
}
if self.player == nil {
self.player = AVQueuePlayer()
}
self.dataSource.sequencePlayerView?(forSequencePlayer: self).player = self.player
if didChangeIndex {
self.player?.pause()
}
if let _ = self.player?.currentItem {
self.player?.play()
self.state = .playing
return
}
self.prefetch()
}
func pause() {
self.player?.pause()
self.state = .paused
}
func next() {
guard self.dataSource.numberOfItemsInSequencePlayer(self) > self.currentIndex + 1 else { self.reload(); return }
self.play(atIndex: self.currentIndex + 1)
}
func previous() {
guard self.currentIndex - 1 > -1 else { self.reload(); return }
self.play(atIndex: self.currentIndex - 1)
}
fileprivate func resumePlayback() {
if state != .playing {
// self.isProgressTimerActive = true
self.play()
}
}
}
//MARK: - Main Implementation
//MARK: -
class SequencePlayer: NSObject
{
//MARK:
enum State: Int, CustomStringConvertible
{
case ready = 0
case playing
case paused
case loading
case failed
var description: String {
get{
switch self
{
case .ready:
return "Ready"
case .playing:
return "Playing"
case .failed:
return "Failed"
case .paused:
return "Paused"
case .loading:
return "Loading"
}
}
}
}
fileprivate(set) var state: State = .ready {
didSet {
guard state != oldValue else { return }
switch state {
case .failed, .ready:
self.isBackgroundTaskActive = false
self.isAudioSessionActive = false
default:
self.isBackgroundTaskActive = true
self.isAudioSessionActive = true
}
self.delegate?.sequencePlayerStateDidChange(self)
}
}
//MARK: - Setup
static var cacheAge: TimeInterval = 3600 * 24 * 7
static var numberOfItemsToPrefetch = 3
deinit{
self.pause()
self.currentIndex = NSNotFound
self.isAudioSessionActive = false
// self.isProgressTimerActive = false
self.isBackgroundTaskActive = false
NotificationCenter.default.removeObserver(self)
self.playerItems.forEach { (item) in
item.removeObserver(self,
forKeyPath: #keyPath(AVPlayerItem.status),
context: &sequencePlayerContext)
}
}
init(withDataSource dataSource: SequencePlayerDataSource, andDelegate delegate: SequencePlayerDelegate? = nil) {
self.dataSource = dataSource
self.delegate = delegate
}
private(set) weak var dataSource: SequencePlayerDataSource!
private(set) weak var delegate: SequencePlayerDelegate?
fileprivate var hasSetUp = false
func reload() {
self.pause()
self.state = .ready
self.currentIndex = NSNotFound
self.isAudioSessionActive = false
// self.isProgressTimerActive = false
self.isBackgroundTaskActive = false
NotificationCenter.default.removeObserver(self)
self.playerItems.forEach { (item) in
item.removeObserver(self,
forKeyPath: #keyPath(AVPlayerItem.status),
context: &sequencePlayerContext)
}
self.playerItems = []
self.player?.removeAllItems()
self.currentlyDownloadingURLs = []
}
//MARK: - Playing
fileprivate var player: AVQueuePlayer?
var items: [AVPlayerItem]? {
return self.player?.items()
}
var currentItem: AVPlayerItem? {
return self.player?.currentItem
}
fileprivate(set) var currentIndex: Int = NSNotFound {
didSet {
guard currentIndex != oldValue && currentIndex != NSNotFound else { return }
func shouldStartLoading() -> Bool {
if oldValue == NSNotFound {
return true
}
return abs(currentIndex - oldValue) >= SequencePlayer.numberOfItemsToPrefetch
}
if shouldStartLoading() {
self.state = .loading
}
}
}
var volume: Float {
get {
return self.player?.volume ?? 0
}
set {
self.player?.volume = newValue
}
}
//MARK: Progress
// private var progressObserver: AnyObject!
//
// fileprivate var isProgressTimerActive: Bool = false {
// didSet {
// guard isProgressTimerActive != oldValue else { return }
//
// if isProgressTimerActive {
// guard let currentItem = self.currentItem, currentItem.duration.isValid == true else { return }
// self.progressObserver = self.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(0.05, Int32(NSEC_PER_SEC)),
// queue: nil)
// { [weak self] (time : CMTime) -> Void in
// self?.timerAction(withTime: time)
// } as AnyObject!
// } else {
// guard let player = self.player, let observer = self.progressObserver else { return }
// player.removeTimeObserver(observer)
// self.progressObserver = nil
// }
// }
// }
//MARK: - Background Task Id
private var backgroundTaskId = UIBackgroundTaskInvalid
fileprivate var isBackgroundTaskActive: Bool = false {
didSet {
guard (self.backgroundTaskId == UIBackgroundTaskInvalid && isBackgroundTaskActive) || (self.backgroundTaskId != UIBackgroundTaskInvalid && !isBackgroundTaskActive) else { return }
guard isBackgroundTaskActive != oldValue else { return }
if isBackgroundTaskActive {
self.backgroundTaskId = UIApplication.shared.beginBackgroundTask { [weak self] _ in
guard let identifier = self?.backgroundTaskId else { return }
UIApplication.shared.endBackgroundTask(identifier)
self?.backgroundTaskId = UIBackgroundTaskInvalid
}
} else {
UIApplication.shared.endBackgroundTask(self.backgroundTaskId)
self.backgroundTaskId = UIBackgroundTaskInvalid
}
}
}
//MARK: - Audio Session
fileprivate var isAudioSessionActive: Bool = false {
didSet {
guard isAudioSessionActive != oldValue else { return }
if isAudioSessionActive {
NotificationCenter.default.addObserver(self,
selector: #selector(handleStall),
name: NSNotification.Name.AVPlayerItemPlaybackStalled,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(handleAudioSessionInterruption),
name: NSNotification.Name.AVAudioSessionInterruption,
object: AVAudioSession.sharedInstance())
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setMode(AVAudioSessionModeDefault)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("Audio Session Activation Error: \(error)")
}
} else {
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name.AVPlayerItemPlaybackStalled,
object: nil)
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name.AVAudioSessionInterruption,
object: AVAudioSession.sharedInstance())
do {
try AVAudioSession.sharedInstance().setActive(false)
} catch {
print("Audio Session Deactivation Error: \(error)")
}
}
}
}
@objc private func handleStall() {
self.player?.pause()
self.player?.play()
}
// private func timerAction(withTime time: CMTime) {
// guard self.currentItem != nil else { return }
// self.delegate?.player(self,
// progressDidChangeWithTime: time)
// }
@objc private func handleAudioSessionInterruption(_ notification : Notification) {
guard let userInfo = notification.userInfo as? [String: AnyObject] else { return }
guard let rawInterruptionType = userInfo[AVAudioSessionInterruptionTypeKey] as? NSNumber else { return }
guard let interruptionType = AVAudioSessionInterruptionType(rawValue: rawInterruptionType.uintValue) else { return }
switch interruptionType {
case .began: //interruption started
self.player?.pause()
case .ended: //interruption ended
if let rawInterruptionOption = userInfo[AVAudioSessionInterruptionOptionKey] as? NSNumber {
let interruptionOption = AVAudioSessionInterruptionOptions(rawValue: rawInterruptionOption.uintValue)
if interruptionOption == AVAudioSessionInterruptionOptions.shouldResume {
self.resumePlayback()
}
}
}
}
//MARK: - Downloading
fileprivate lazy var downloadQueue: OperationQueue = {
let result = OperationQueue()
result.name = "SequencePlayerQueue"
result.maxConcurrentOperationCount = 1
return result
}()
fileprivate lazy var fileQueue: OperationQueue = {
let result = OperationQueue()
result.name = "SequencePlayerFileQueue"
result.maxConcurrentOperationCount = 1
return result
}()
fileprivate(set) lazy var urlSession: URLSession = {
let configuration = URLSessionConfiguration.background(withIdentifier: "SequencePlayer")
configuration.requestCachePolicy = .returnCacheDataElseLoad
configuration.networkServiceType = .video
let result = URLSession(configuration: configuration,
delegate: self,
delegateQueue: self.downloadQueue)
return result
}()
fileprivate lazy var currentlyDownloadingURLs = [URL]()
//MARK: - KVO
fileprivate lazy var playerItems = [AVPlayerItem]()
@objc fileprivate func itemDidPlayToEnd(_ notification: Notification) {
guard self.currentIndex + 1 < self.dataSource.numberOfItemsInSequencePlayer(self) else {
self.delegate?.sequencePlayerDidEnd(self)
self.reload()
return
}
self.currentIndex += 1
self.prefetch()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// Only handle observations for the playerItemContext
guard context == &sequencePlayerContext else {
super.observeValue(forKeyPath: keyPath,
of: object,
change: change,
context: context)
return
}
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
// Get the status change from the change dictionary
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
// Switch over the status
switch status {
case .readyToPlay:
// Player item is ready to play.
if self.state != .playing {
self.player?.play()
self.state = .playing
}
case .failed:
if self.state == .playing {
self.pause()
}
case .unknown:
// Player item is not yet ready.
break
}
}
}
}
//MARK: - Downloading
//MARK: -
fileprivate extension SequencePlayer
{
var documentsURL: URL? {
let bundleId = Bundle.main.bundleIdentifier ?? "com.bellapplab"
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last?.appendingPathComponent("\(bundleId).SequencePlayer").standardizedFileURL
}
func prefetch() {
guard self.currentIndex != NSNotFound else { fatalError("Sequence Player: We need to set the current index before prefetching!") }
guard let documentsURL = self.documentsURL, let dataSource = self.dataSource else { return }
let currentIndex = self.currentIndex
let total = self.dataSource.numberOfItemsInSequencePlayer(self)
let manager = FileManager.default
func setUpCacheFolder() {
guard !self.hasSetUp else { return }
if !manager.fileExists(atPath: documentsURL.path) {
do {
try manager.createDirectory(at: documentsURL, withIntermediateDirectories: true, attributes: nil)
} catch {
fatalError("Sequence Player couldn't not create its root folder... \(error)")
}
}
do {
let files = try manager.contentsOfDirectory(at: documentsURL,
includingPropertiesForKeys: [.contentAccessDateKey],
options: [.skipsPackageDescendants, .skipsSubdirectoryDescendants, .skipsHiddenFiles])
let cacheDate = Date(timeIntervalSinceNow: -1 * SequencePlayer.cacheAge)
for file in files {
if let date = try file.resourceValues(forKeys: [.contentAccessDateKey]).contentAccessDate {
if date.timeIntervalSince(cacheDate) <= 0 {
try manager.removeItem(at: file)
}
}
}
} catch {
fatalError("Sequence Player: Something went wrong while enumerating files... \(error)")
}
self.hasSetUp = true
}
func isAlreadyDownloading(_ remoteURL: URL) -> Bool {
for url in self.currentlyDownloadingURLs {
if url == remoteURL {
return true
}
}
return false
}
func isAlreadyInPlayer(_ localURL: URL) -> Bool {
guard let player = self.player else { return false }
for item in player.items() {
if let asset = item.asset as? AVURLAsset {
if asset.url == localURL {
return true
}
}
}
return false
}
self.fileQueue.addOperation { [weak self] _ in
setUpCacheFolder()
var i = 0
var operations = [Operation]()
while i < SequencePlayer.numberOfItemsToPrefetch && currentIndex + i < total {
let remoteURL = dataSource.sequencePlayer(self!, itemURLAtIndex: currentIndex + i)
let localURL = documentsURL.appendingPathComponent(remoteURL.lastPathComponent)
if !isAlreadyDownloading(remoteURL) && !manager.fileExists(atPath: localURL.path) {
self?.currentlyDownloadingURLs.append(remoteURL)
let task = self?.urlSession.downloadTask(with: remoteURL)
operations.append(BlockOperation(block: {
task?.resume()
}))
} else if !isAlreadyInPlayer(localURL) {
self?.didFinishDownloadingFile(toURL: localURL)
}
i += 1
}
self?.downloadQueue.addOperations(operations, waitUntilFinished: false)
}
}
func didFinishDownloadingFile(toURL url: URL) {
let item = AVPlayerItem(asset: AVURLAsset(url: url))
self.playerItems.append(item)
self.player?.insert(item, after: nil)
item.addObserver(self,
forKeyPath: #keyPath(AVPlayerItem.status),
options: [.new],
context: &sequencePlayerContext)
NotificationCenter.default.addObserver(self,
selector: #selector(SequencePlayer.itemDidPlayToEnd(_:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: item)
}
}
//MARK: URL Session Data Delegate
extension SequencePlayer: URLSessionDataDelegate, URLSessionDownloadDelegate
{
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
guard let response = proposedResponse.response as? HTTPURLResponse, let url = response.url, var headers = response.allHeaderFields as? [String: String] else { return }
var cachedResponse: CachedURLResponse
if response.allHeaderFields["Cache-Control"] == nil {
headers["Cache-Control"] = "max-age=\(SequencePlayer.cacheAge)"
if let newResponse = HTTPURLResponse(url: url,
statusCode: response.statusCode,
httpVersion: "HTTP/1.1",
headerFields: headers)
{
cachedResponse = CachedURLResponse(response: newResponse,
data: proposedResponse.data,
userInfo: proposedResponse.userInfo,
storagePolicy: proposedResponse.storagePolicy)
} else {
cachedResponse = proposedResponse
}
} else {
cachedResponse = proposedResponse
}
completionHandler(cachedResponse)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let data = try? Data(contentsOf: location), let documentsURL = self.documentsURL, let fileName = downloadTask.originalRequest?.url?.lastPathComponent else { return }
let manager = FileManager.default
let finalURL = documentsURL.appendingPathComponent(fileName)
manager.createFile(atPath: finalURL.path, contents: data, attributes: nil)
for (index, existingURL) in self.currentlyDownloadingURLs.enumerated() {
if finalURL == existingURL {
self.currentlyDownloadingURLs.remove(at: index)
}
}
DispatchQueue.main.async { [weak self] _ in
self?.didFinishDownloadingFile(toURL: finalURL)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
dLog("Sequence Player Download error: \(error)")
}
}
}
//MARK: - Player View
//MARK: -
class SequencePlayerView: UIView
{
var player: AVPlayer? {
get {
return playerLayer.player
}
set {
playerLayer.player = newValue
}
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
// Override UIView property
override static var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
//MARK: - Aux
//MARK: -
public func dLog(_ message: @autoclosure () -> String, filename: String = #file, function: String = #function, line: Int = #line) {
#if DEBUG
debugPrint("[\(URL(string: filename)?.lastPathComponent):\(line)]", "\(function)", message(), separator: " - ")
#else
#endif
}
| mit |
stlwolf/iosAppBase | appBase/Sources/AppDelegate.swift | 1 | 2440 | //
// AppDelegate.swift
// appBase
//
// Created by eddy on 2016/06/23.
// Copyright © 2016年 eddy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let mainViewController:MainViewController = MainViewController.instantiate("Main")
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = mainViewController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
lacklock/NiceGesture | NiceGesture/NCGesturePromise.swift | 1 | 2652 | //
// NCGesturePromise.swift
// NiceGesture
//
// Created by 卓同学 on 16/4/3.
// Copyright © 2016年 zhuo. All rights reserved.
//
import UIKit
public class NCGesturePromise<T:UIGestureRecognizer>: NSObject {
public typealias ncGestureHandler = (gestureRecognizer:T)->Void
var beganHandler:ncGestureHandler = { _ in }
var cancelledHandler:ncGestureHandler = { _ in }
var changedHandler:ncGestureHandler = { _ in }
var endedHandler:ncGestureHandler = { _ in }
var failedHandler:ncGestureHandler = { _ in }
override init(){
super.init()
}
func gesureRecognizerHandler(gestureRecognizer:UIGestureRecognizer){
switch gestureRecognizer.state {
case .Began:
beganHandler(gestureRecognizer: gestureRecognizer as! T)
case .Cancelled:
cancelledHandler(gestureRecognizer: gestureRecognizer as! T)
case .Changed:
changedHandler(gestureRecognizer: gestureRecognizer as! T)
case .Ended:
endedHandler(gestureRecognizer: gestureRecognizer as! T)
case .Failed:
failedHandler(gestureRecognizer: gestureRecognizer as! T)
case .Possible:
break
}
}
/**
one handler for many states
- parameter states: UIGestureRecognizerStates
*/
public func whenStatesHappend(states:[UIGestureRecognizerState],handler:ncGestureHandler)->NCGesturePromise<T>{
for state in states{
switch state {
case .Began:
beganHandler=handler
case .Cancelled:
cancelledHandler=handler
case .Changed:
changedHandler=handler
case .Ended:
endedHandler=handler
case .Failed:
failedHandler=handler
case .Possible:
break
}
}
return self
}
public func whenBegan(handler:ncGestureHandler)->NCGesturePromise<T>{
beganHandler=handler
return self
}
public func whenCancelled(handler:ncGestureHandler)->NCGesturePromise<T>{
cancelledHandler=handler
return self
}
public func whenChanged(handler:ncGestureHandler)->NCGesturePromise<T>{
changedHandler=handler
return self
}
public func whenEnded(handler:ncGestureHandler)->NCGesturePromise<T>{
endedHandler=handler
return self
}
public func whenFailed(handler:ncGestureHandler)->NCGesturePromise<T>{
failedHandler=handler
return self
}
}
| mit |
swipe-org/swipe | network/SwipePrefetcher.swift | 2 | 5443 | //
// SwipePrefetcher.swift
// sample
//
// Created by satoshi on 10/12/15.
// Copyright © 2015 Satoshi Nakajima. All rights reserved.
//
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
private func MyLog(_ text:String, level:Int = 0) {
let s_verbosLevel = 0
if level <= s_verbosLevel {
NSLog(text)
}
}
class SwipePrefetcher {
private var urls = [URL:String]()
private var urlsFetching = [URL]()
private var urlsFetched = [URL:URL]()
private var urlsFailed = [URL]()
private var errors = [NSError]()
private var fComplete = false
private var _progress = Float(0)
var progress:Float {
return _progress
}
init(urls:[URL:String]) {
self.urls = urls
}
func start(_ callback:@escaping (Bool, [URL], [NSError]) -> Void) {
if fComplete {
MyLog("SWPrefe already completed", level:1)
callback(true, self.urlsFailed, self.errors)
return
}
let manager = SwipeAssetManager.sharedInstance()
var count = 0
_progress = 0
let fileManager = FileManager.default
for (url,prefix) in urls {
if url.scheme == "file" {
if fileManager.fileExists(atPath: url.path) {
urlsFetched[url] = url
} else {
// On-demand resource support
urlsFetched[url] = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil)
MyLog("SWPrefe onDemand resource at \(String(describing:urlsFetched[url])) instead of \(url)", level:1)
}
} else {
count += 1
urlsFetching.append(url)
manager.loadAsset(url, prefix: prefix, bypassCache:false, callback: { (urlLocal:URL?, error:NSError?) -> Void in
if let urlL = urlLocal {
self.urlsFetched[url] = urlL
} else {
self.urlsFailed.append(url)
if let error = error {
self.errors.append(error)
}
}
count -= 1
if (count == 0) {
self.fComplete = true
self._progress = 1
MyLog("SWPrefe completed \(self.urlsFetched.count)", level: 1)
callback(true, self.urlsFailed, self.errors)
} else {
self._progress = Float(self.urls.count - count) / Float(self.urls.count)
callback(false, self.urlsFailed, self.errors)
}
})
}
}
if count == 0 {
self.fComplete = true
self._progress = 1
callback(true, urlsFailed, errors)
}
}
func append(_ urls:[URL:String], callback:@escaping (Bool, [URL], [NSError]) -> Void) {
let manager = SwipeAssetManager.sharedInstance()
var count = 0
_progress = 0
let fileManager = FileManager.default
for (url,prefix) in urls {
self.urls[url] = prefix
if url.scheme == "file" {
if fileManager.fileExists(atPath: url.path) {
urlsFetched[url] = url
} else {
// On-demand resource support
urlsFetched[url] = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil)
MyLog("SWPrefe onDemand resource at \(String(describing: urlsFetched[url])) instead of \(url)", level:1)
}
} else {
count += 1
urlsFetching.append(url)
manager.loadAsset(url, prefix: prefix, bypassCache:false, callback: { (urlLocal:URL?, error:NSError?) -> Void in
if let urlL = urlLocal {
self.urlsFetched[url] = urlL
} else if let error = error {
self.urlsFailed.append(url)
self.errors.append(error)
}
count -= 1
if (count == 0) {
self.fComplete = true
self._progress = 1
MyLog("SWPrefe completed \(self.urlsFetched.count)", level: 1)
callback(true, self.urlsFailed, self.errors)
} else {
self._progress = Float(self.urls.count - count) / Float(self.urls.count)
callback(false, self.urlsFailed, self.errors)
}
})
}
}
if count == 0 {
self.fComplete = true
self._progress = 1
callback(true, urlsFailed, errors)
}
}
func map(_ url:URL) -> URL? {
return urlsFetched[url]
}
static func extensionForType(_ memeType:String) -> String {
let ext:String
if memeType == "video/quicktime" {
ext = ".mov"
} else if memeType == "video/mp4" {
ext = ".mp4"
} else {
ext = ""
}
return ext
}
static func isMovie(_ mimeType:String) -> Bool {
return mimeType == "video/quicktime" || mimeType == "video/mp4"
}
}
| mit |
vector-im/vector-ios | RiotSwiftUI/Modules/Spaces/SpaceCreation/SpaceCreationRooms/Model/SpaceCreationRoomsStateAction.swift | 1 | 779 | // File created from SimpleUserProfileExample
// $ createScreen.sh Spaces/SpaceCreation/SpaceCreationRooms SpaceCreationRooms
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
enum SpaceCreationRoomsStateAction {
}
| apache-2.0 |
krzysztofzablocki/Sourcery | SourceryTests/Models/ProtocolSpec.swift | 1 | 583 | import Quick
import Nimble
#if SWIFT_PACKAGE
@testable import SourceryLib
#else
@testable import Sourcery
#endif
@testable import SourceryRuntime
class ProtocolSpec: QuickSpec {
override func spec() {
describe("Protocol") {
var sut: Type?
beforeEach {
sut = Protocol(name: "Foo", variables: [], inheritedTypes: [])
}
afterEach {
sut = nil
}
it("reports kind as protocol") {
expect(sut?.kind).to(equal("protocol"))
}
}
}
}
| mit |
Why51982/SLDouYu | SLDouYu/SLDouYu/Classes/Room/Controller/SLRoomShowViewController.swift | 1 | 369 | //
// SLRoomShowViewController.swift
// SLDouYu
//
// Created by CHEUNGYuk Hang Raymond on 2016/11/1.
// Copyright © 2016年 CHEUNGYuk Hang Raymond. All rights reserved.
//
import UIKit
class SLRoomShowViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.gray
}
}
| mit |
niceagency/Contentful | Contentful/Contentful/ContentfulTypes.swift | 1 | 2775 | //
// ContentfulTypes.swift
// DeviceManagement
//
// Created by Sam Woolf on 24/10/2017.
// Copyright © 2017 Nice Agency. All rights reserved.
//
import Foundation
public typealias UnboxedFields = [String:Any?]
public typealias FieldMapping = [String:(UnboxedType,Bool)]
public typealias WriteRequest = (data: Data?, endpoint: String, headers: [(String,String)], method: HttpMethod)
public protocol Readable {
static func contentfulEntryType() -> String
static func unboxer() -> (FieldMapping)
static func creator(withFields fields: UnboxedFields) -> Self
}
public protocol Writeable {
var contentful_id: String { get }
var contentful_version: Int { get}
}
public typealias Encodable = Swift.Encodable & Writeable
public enum HttpMethod {
case put
case post
case delete
}
public enum ReferenceType : String {
case entry = "Entry"
}
public struct Reference : Codable {
private struct Sys: Codable {
let type: String = "Link"
let linkType : String
let id : String
}
private let sys: Sys
public var id: String {
return sys.id
}
public func getObjectWithId<T: Writeable> (fromCandidates candidates: [T]) -> T? {
return candidates.first(where: { $0.contentful_id == self.id })
}
public init (forObject object: Writeable, type: ReferenceType = .entry ) {
self.sys = Sys(linkType: type.rawValue, id: object.contentful_id)
}
init (withId id: String, type: String) {
self.sys = Sys(linkType: type, id: id )
}
}
public enum DecodingError: Error {
case typeMismatch(String, UnboxedType)
case requiredKeyMissing(String)
case fieldFormatError(String)
case missingRequiredFields([String])
public func errorMessage() -> String {
switch self {
case .typeMismatch(let type):
return ("wrong type: \(String(describing: type))")
case .requiredKeyMissing(let string):
return ("missing required field \(string)")
case .fieldFormatError:
return ("field format error")
case .missingRequiredFields(let fields ):
return ("missing required fields \(fields)")
}
}
}
public enum Result<T> {
case success(T)
case error(Swift.DecodingError)
}
public struct SysData {
public let id: String
public let version: Int
}
public struct PagedResult<T> {
public let validItems: [T]
public let failedItems: [(Int, DecodingError)]
public let page: Page
}
public enum ItemResult<T> {
case success(T)
case error (DecodingError)
}
public enum UnboxedType {
case string
case int
case date
case decimal
case bool
case oneToOneRef
case oneToManyRef
}
| mit |
malcommac/ScrollingStackContainer | ScrollingStackContainer/ScrollingStackContainer/ContainerView2.swift | 1 | 1851 | // ScrollingStackController
// Efficient Scrolling Container for UIViewControllers
//
// Created by Daniele Margutti.
// Copyright © 2017 Daniele Margutti. All rights reserved.
//
// Web: http://www.danielemargutti.com
// Email: hello@danielemargutti.com
// Twitter: @danielemargutti
//
//
// 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 UIKit
public class ContainerView2: UIViewController, StackContainable {
public static func create() -> ContainerView2 {
return UIStoryboard(name: "Containers", bundle: Bundle.main).instantiateViewController(withIdentifier: "ContainerView2") as! ContainerView2
}
public override func viewDidLoad() {
super.viewDidLoad()
}
public func preferredAppearanceInStack() -> ScrollingStackController.ItemAppearance {
return .view(height: 100)
}
}
| mit |
SwiftStudies/OysterKit | Sources/STLR/Generators/Framework/TextFile.swift | 1 | 3807 | // Copyright (c) 2018, RED When Excited
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
/// Captures the output of a source generator
public class TextFile : Operation {
/// Writes the file at the specified location
public func perform(in context: OperationContext) throws {
let writeTo = context.workingDirectory.appendingPathComponent(name)
do {
try content.write(to: writeTo, atomically: true, encoding: .utf8)
} catch {
throw OperationError.error(message: "Failed to write file \(writeTo) \(error.localizedDescription)")
}
context.report("Wrote \(writeTo.path)")
}
/// The desired name of the file, including an extension. Any path elements will be considered relative
/// a location known by the consumer of the TextFile
public var name : String
public private(set) var content : String = ""
private var tabDepth : Int = 0
/**
Creates a new instance
- Parameter name: The name of the textfile
*/
public init(_ name:String){
self.name = name
}
/**
Appends the supplied items to the text file at the current tab depth
- Parameter terminator: An optional terminator to use. By default it is \n
- Parameter separator: An optional separator to use between items/ Defaults to a newline
- Parameter prefix: An optional prefex to add to each supplied item
- Parameter items: One or more Strings to be appended to the file
- Returns: Itself for chaining
*/
@discardableResult
public func print(terminator:String = "\n", separator:String = "\n", prefix : String = "", _ items:String...)->TextFile{
var first = true
for item in items {
if !first {
content += separator
} else {
first = false
}
content += "\(String(repeating: " ", count: tabDepth))\(prefix)\(item)"
}
content += terminator
return self
}
/// Indents subsequent output
/// - Returns: Itself for chaining
@discardableResult
public func indent()->TextFile{
tabDepth += 1
return self
}
/// Outdents subsequent output
/// - Returns: Itself for chaining
@discardableResult
public func outdent()->TextFile{
tabDepth -= 1
return self
}
}
| bsd-2-clause |
roambotics/swift | test/Reflection/typeref_decoding.swift | 2 | 27556 | // REQUIRES: no_asan
// rdar://100805115
// UNSUPPORTED: CPU=arm64e
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -enable-anonymous-context-mangled-names %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect)
// RUN: %target-build-swift -Xfrontend -enable-anonymous-context-mangled-names %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift %S/Inputs/main.swift -emit-module -emit-executable -module-name TypesToReflect -o %t/TypesToReflect
// RUN: %target-swift-reflection-dump %t/%target-library-name(TypesToReflect) | %FileCheck %s
// RUN: %target-swift-reflection-dump %t/TypesToReflect | %FileCheck %s
// CHECK: FIELDS:
// CHECK: =======
// CHECK: TypesToReflect.Box
// CHECK: ------------------
// CHECK: item: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: anEnum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: aTupleWithLabels: (a: TypesToReflect.C, s: TypesToReflect.S, e: TypesToReflect.E)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithVarArgs: (TypesToReflect.C, TypesToReflect.S...) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (variadic
// CHECK: (struct TypesToReflect.S))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout1: (inout TypesToReflect.C) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (inout
// CHECK: (class TypesToReflect.C))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout2: (TypesToReflect.C, inout Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (inout
// CHECK: (struct Swift.Int))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout3: (inout TypesToReflect.C, inout Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (inout
// CHECK: (class TypesToReflect.C))
// CHECK: (inout
// CHECK: (struct Swift.Int))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithShared: (__shared TypesToReflect.C) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (shared
// CHECK: (class TypesToReflect.C))
// CHECK: (result
// CHECK: (tuple))
// CHECK: TypesToReflect.S
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.Box<TypesToReflect.S>, TypesToReflect.Box<TypesToReflect.E>, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: (struct Swift.Int))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithThinRepresentation: @convention(thin) () -> ()
// CHECK: (function convention=thin
// CHECK: (tuple))
// CHECK: aFunctionWithCRepresentation: @convention(c) () -> ()
// CHECK: (function convention=c
// CHECK: (tuple))
// CHECK: TypesToReflect.S.NestedS
// CHECK: ------------------------
// CHECK: aField: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: TypesToReflect.E
// CHECK: ----------------
// CHECK: Class: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: Struct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: Enum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: Function: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (tuple))
// CHECK: Tuple: (TypesToReflect.C, TypesToReflect.S, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (struct Swift.Int))
// CHECK: IndirectTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: NestedStruct: TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S))
// CHECK: Metatype
// CHECK: EmptyCase
// CHECK: TypesToReflect.References
// CHECK: -------------------------
// CHECK: strongRef: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: weakRef: weak Swift.Optional<TypesToReflect.C>
// CHECK: (weak_storage
// CHECK: (bound_generic_enum Swift.Optional
// CHECK: (class TypesToReflect.C)))
// CHECK: unownedRef: unowned TypesToReflect.C
// CHECK: (unowned_storage
// CHECK: (class TypesToReflect.C))
// CHECK: unownedUnsafeRef: unowned(unsafe) TypesToReflect.C
// CHECK: (unmanaged_storage
// CHECK: (class TypesToReflect.C))
// CHECK: TypesToReflect.(PrivateStructField
// CHECK: ----------------------------------
// CHECK: TypesToReflect.HasArrayOfPrivateStructField
// CHECK: -------------------------------------------
// CHECK: x: Swift.Array<TypesToReflect.(PrivateStructField{{.*}})>
// CHECK: TypesToReflect.C1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, TypesToReflect.E1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: dependentMember: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, TypesToReflect.E2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.C3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, TypesToReflect.E3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.TypesToReflect.P2.Outer
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.C4
// CHECK: -----------------
// CHECK: TypesToReflect.S1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.Box<TypesToReflect.S1<A>>, TypesToReflect.Box<TypesToReflect.E1<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.S2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C2<A>) -> (TypesToReflect.S2<A>) -> (TypesToReflect.E2<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.Box<TypesToReflect.S2<A>>, TypesToReflect.Box<TypesToReflect.E2<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.S3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.Box<TypesToReflect.S3<A>>, TypesToReflect.Box<TypesToReflect.E3<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.TypesToReflect.P2.Outer
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.S4
// CHECK: -----------------
// CHECK: TypesToReflect.E1
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Int: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: Function: (A) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: Metatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E2
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S2<A>
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E2<A>
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberInner: A.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: ExistentialMetatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E3
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (metatype
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberOuter: A.TypesToReflect.P2.Outer
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: DependentMemberInner: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.E4
// CHECK: -----------------
// CHECK: TypesToReflect.P1
// CHECK: -----------------
// CHECK: TypesToReflect.P2
// CHECK: -----------------
// CHECK: TypesToReflect.P3
// CHECK: -----------------
// CHECK: TypesToReflect.P4
// CHECK: -----------------
// CHECK: TypesToReflect.ClassBoundP
// CHECK: --------------------------
// CHECK: TypesToReflect.(FileprivateProtocol in {{.*}})
// CHECK: -------------------------------------------------------------------------
// CHECK: TypesToReflect.HasFileprivateProtocol
// CHECK: -------------------------------------
// CHECK: x: TypesToReflect.(FileprivateProtocol in {{.*}})
// CHECK: (protocol_composition
// CHECK-NEXT: (protocol TypesToReflect.(FileprivateProtocol in {{.*}})))
// CHECK: ASSOCIATED TYPES:
// CHECK: =================
// CHECK: - TypesToReflect.C1 : TypesToReflect.ClassBoundP
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P2
// CHECK: typealias Outer = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P3
// CHECK: typealias First = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: typealias Second = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.S : TypesToReflect.P4
// CHECK: typealias Result = Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: BUILTIN TYPES:
// CHECK: ==============
// CHECK: CAPTURE DESCRIPTORS:
// CHECK: ====================
// CHECK: - Capture types:
//CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (closure_binding index=1)
// CHECK: - Capture types:
// CHECK: (struct Swift.Int)
// CHECK: - Metadata sources:
// CHECK: - Capture types:
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=1))
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (generic_argument index=0
// CHECK: (reference_capture index=0))
| apache-2.0 |
ghotjunwoo/Tiat | ProblemInputViewController.swift | 1 | 1595 | //
// ProblemInputViewController.swift
// Tiat
//
// Created by 이종승 on 2016. 8. 3..
// Copyright © 2016년 JW. All rights reserved.
//
import UIKit
import Firebase
import DLRadioButton
class ProblemInputViewController: UIViewController {
@IBOutlet var TestButton: DLRadioButton!
@IBOutlet var loveButton: DLRadioButton!
@IBOutlet var healthButton: DLRadioButton!
@IBOutlet var appearanceButton: DLRadioButton!
@IBOutlet var dreamButton: DLRadioButton!
@IBOutlet var weightButton: DLRadioButton!
@IBOutlet var friendButton: DLRadioButton!
let user = FIRAuth.auth()?.currentUser
var currentProblemValue = false
var problems = ""
override func viewDidLoad() {
super.viewDidLoad()
TestButton.isMultipleSelectionEnabled = true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func markButtonSelected(_ radioButton : DLRadioButton) {
if (radioButton.isMultipleSelectionEnabled) {
for button in radioButton.selectedButtons() {
problems.removeAll()
problems.append((button.titleLabel?.text)!)
problems.append(" ")
}
}
}
@IBAction func nextButtonTapped(_ sender: AnyObject) {
problems.append("에 고민이 있습니다")
FIRDatabase.database().reference().child("users/\((FIRAuth.auth()?.currentUser)!.uid)/currentdata/problem").setValue(problems)
performSegue(withIdentifier: "toInput_2", sender: self)
}
}
| gpl-3.0 |
Boris-Em/Goban | GobanSampleProject/GobanSampleProjectTests/SGFFilesTests.swift | 1 | 3638 | //
// SGFFilesTests.swift
// GobanSampleProject
//
// Created by John on 5/7/16.
// Copyright © 2016 Boris Emorine. All rights reserved.
//
import XCTest
class SGFFilesTests: XCParserTestBase {
typealias SGFPC = SGFParserCombinator
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testHeader() {
let testString = "(;GM[1])"
let results = testParseString(SGFPC.collectionParser(), testString)
XCTAssertEqual(1, results.count)
}
func testLeeSodolHeader() {
let testString = contentsOfFileWithName("LeeSedolHeader.sgf")!
let results = testParseString(SGFPC.collectionParser(), testString)
XCTAssertEqual(1, results.count)
}
func testLeeSedol() {
let testString = contentsOfFileWithName("Lee-Sedol-vs-AlphaGo-Simplified.sgf")!
let results = testParseString(SGFPC.collectionParser(), testString)
XCTAssertEqual(1, results.count)
let game: SGFP.GameTree? = results.first?.0.games.first
XCTAssertNotNil(game)
XCTAssertEqual(game?.fileFormat, 4)
XCTAssertEqual(game?.application, "CGoban:3")
XCTAssertEqual(game?.rules, "Chinese")
XCTAssertEqual(game?.boardSize, 19)
XCTAssertEqual(game?.komi, 7.5)
XCTAssertEqual(game?.timeLimit, 7200)
XCTAssertEqual(game?.overtime, "3x60 byo-yomi")
XCTAssertEqual(game?.whiteName, "AlphaGo")
XCTAssertEqual(game?.blackName, "Lee Sedol")
XCTAssertEqual(game?.blackRank, "9d")
XCTAssertEqual(game?.eventName, "Google DeepMind Challenge Match")
XCTAssertEqual(game?.round, "Game 1")
XCTAssertEqual(game?.locationName, "Seoul, Korea")
XCTAssertEqual(game?.whiteTeam, "Computer")
XCTAssertEqual(game?.blackTeam, "Human")
XCTAssertEqual(game?.source, "https://gogameguru.com/")
XCTAssertEqual(game?.result, "W+Resign")
XCTAssertEqual(game?.nodes.count, 9)
XCTAssertEqual(game!.nodes.first!.properties.count, 21)
let expectations: [(count: Int, identifier: String, value: String)] = [
(1, "B", "qd"),
(1, "W", "dd"),
(1, "B", "pq"),
(1, "W", "dp"),
(1, "B", "fc"),
(1, "W", "cf"),
(1, "B", "gh"),
(2, "W", "fh")
]
for (index, node) in game!.nodes.dropFirst().enumerated() {
XCTAssertEqual(node.properties.count, expectations[index].count)
let property = node.properties.first!
XCTAssertEqual(property.identifier, expectations[index].identifier)
XCTAssertEqual(property.values.first!.asString, expectations[index].value)
}
}
func testPropertyList() {
let testString = contentsOfFileWithName("Lee-Sedol-vs-AlphaGo-Simplified.sgf")!
let results = testParseString(SGFPC.collectionParser(), testString)
XCTAssertEqual(1, results.count)
}
func testFF4ExampleSimplifiedFile() {
let testString = contentsOfFileWithName("ff4_ex_simplified.sgf")!
let results = testParseString(SGFPC.collectionParser(), testString)
XCTAssertEqual(1, results.count)
}
func testFF4ExampleFile() {
let testString = contentsOfFileWithName("ff4_ex.sgf")!
let results = testParseString(SGFPC.collectionParser(), testString)
XCTAssertEqual(1, results.count)
}
}
| mit |
rad182/RADInfoBannerView | Example/RADInfoBannerView/AppDelegate.swift | 1 | 2150 | //
// AppDelegate.swift
// RADInfoBannerView
//
// Created by Royce Dy on 12/23/2015.
// Copyright (c) 2015 Royce Dy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
livechat/chat-window-ios | Sources/ChatView.swift | 1 | 15848 | //
// ChatView.swift
// Example-Swift
//
// Created by Łukasz Jerciński on 06/03/2017.
// Copyright © 2017 LiveChat Inc. All rights reserved.
//
import Foundation
import WebKit
import UIKit
@objc protocol ChatViewDelegate : NSObjectProtocol {
func closedChatView()
func handle(URL: URL)
}
let iOSMessageHandlerName = "iosMobileWidget"
class ChatView : UIView, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler, UIScrollViewDelegate, LoadingViewDelegate {
private var webView : WKWebView?
private let loadingView = LoadingView()
weak var delegate : ChatViewDelegate?
private let jsonCache = JSONRequestCache()
private var animating = false
var configuration : LiveChatConfiguration? {
didSet {
if let configuration = configuration {
if oldValue != configuration {
reloadWithDelay()
}
}
}
}
var customVariables : CustomVariables? {
didSet {
reloadWithDelay()
}
}
var webViewBridge : WebViewBridge? {
didSet {
if let webViewBridge = webViewBridge {
webViewBridge.webView = webView
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(frame: CGRect) {
super.init(frame: frame)
let configuration = WKWebViewConfiguration()
configuration.mediaTypesRequiringUserActionForPlayback = []
configuration.allowsInlineMediaPlayback = true
let contentController = WKUserContentController()
contentController.add(self, name:iOSMessageHandlerName)
configuration.userContentController = contentController
#if SwiftPM
let bundle = Bundle.module
#else
let bundle = Bundle(for: ChatView.self)
#endif
var scriptContent : String?
do {
if let path = bundle.path(forResource: "LiveChatWidget", ofType: "js") {
scriptContent = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
}
} catch {
print("Exception while injecting LiveChatWidget.js script")
}
let script = WKUserScript(source: scriptContent!, injectionTime: .atDocumentStart, forMainFrameOnly: true)
contentController.addUserScript(script)
webView = WKWebView(frame: frame, configuration: configuration)
if let webView = webView {
addSubview(webView)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
webView.uiDelegate = self
webView.scrollView.minimumZoomScale = 1.0
webView.scrollView.maximumZoomScale = 1.0
webView.isOpaque = false
webView.backgroundColor = UIColor.white
webView.frame = frame
webView.alpha = 0
}
backgroundColor = UIColor.clear
loadingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
loadingView.delegate = self
loadingView.frame = bounds
loadingView.startAnimation()
addSubview(loadingView)
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(applicationDidBecomeActiveNotification), name: UIApplication.didBecomeActiveNotification
, object: nil)
nc.addObserver(self, selector: #selector(applicationWillResignActiveNotification), name: UIApplication.willResignActiveNotification, object: nil)
}
deinit {
if let webView = webView {
webView.scrollView.delegate = nil
webView.stopLoading()
webView.configuration.userContentController.removeScriptMessageHandler(forName:(iOSMessageHandlerName))
}
}
override func layoutSubviews() {
super.layoutSubviews()
if let webView = webView {
loadingView.frame = webView.frame
}
}
// MARK: Public Methods
func presentChat(animated: Bool, completion: ((Bool) -> Void)? = nil) {
guard let wv = webView else { return }
if !LiveChatState.isChatOpenedBefore() {
delayed_reload()
}
LiveChatState.markChatAsOpened()
let animations = {
wv.frame = self.frameForSafeAreaInsets()
self.loadingView.frame = wv.frame
wv.alpha = 1
}
let completion = { (finished : Bool) in
let fr = self.frameForSafeAreaInsets()
wv.frame = CGRect(origin: fr.origin, size: CGSize(width: fr.size.width, height: fr.size.height - 1))
DispatchQueue.main.asyncAfter(deadline:.now() + 0.1, execute: { [weak self] in
if let `self` = self {
if wv.alpha > 0 {
wv.frame = self.frameForSafeAreaInsets()
}
}
})
self.animating = false
if finished {
self.webViewBridge?.postFocusEvent()
}
if let completion = completion {
completion(finished)
}
}
if animated {
animating = true
wv.frame = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: bounds.size.height)
loadingView.frame = wv.frame
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [],
animations: animations,
completion: completion)
} else {
animations()
completion(true)
}
}
func dismissChat(animated: Bool, completion: ((Bool) -> Void)? = nil) {
guard let wv = webView else { return }
if animating {
return
}
wv.endEditing(true)
let animations = {
wv.frame = CGRect(x: 0, y: self.bounds.size.height, width: self.bounds.size.width, height: self.bounds.size.height)
self.loadingView.frame = wv.frame
wv.alpha = 0
}
let completion = { (finished : Bool) in
self.animating = false
if finished {
self.webViewBridge?.postBlurEvent()
self.chatHidden()
}
if let completion = completion {
completion(finished)
}
}
if animated {
animating = true
UIView.animate(withDuration: 0.2,
delay: 0,
options: [.curveEaseOut],
animations: animations,
completion: completion)
} else {
animations()
completion(true)
}
}
func clearSession() {
let dataStore = WKWebsiteDataStore.default()
dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { (records) in
for record in records {
if record.displayName.contains("livechat") || record.displayName.contains("chat.io") {
dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: [record], completionHandler: {
self.reloadWithDelay()
})
}
}
}
}
private func chatHidden() {
delegate?.closedChatView()
}
// MARK: Application state management
@objc func applicationDidBecomeActiveNotification(_ notification: Notification) {
if let webView = self.webView, webView.alpha > 0 {
self.webViewBridge?.postFocusEvent()
}
}
@objc func applicationWillResignActiveNotification(_ notification: Notification) {
if let webView = self.webView, webView.alpha > 0 {
self.webViewBridge?.postBlurEvent()
}
}
// MARK: Keyboard frame changes
private func frameForSafeAreaInsets() -> CGRect {
var safeAreaInsets = UIEdgeInsets.zero
if #available(iOS 11.0, *) {
safeAreaInsets = self.safeAreaInsets
} else {
safeAreaInsets = UIEdgeInsets.init(top: UIApplication.shared.statusBarFrame.size.height, left: 0, bottom: 0, right: 0)
}
let frameForSafeAreaInsets = CGRect(x: safeAreaInsets.left, y: safeAreaInsets.top, width: bounds.size.width - safeAreaInsets.left - safeAreaInsets.right, height: bounds.size.height - safeAreaInsets.top - safeAreaInsets.bottom)
return frameForSafeAreaInsets
}
private func displayLoadingError(withMessage message: String) {
DispatchQueue.main.async(execute: { [weak self] in
if let `self` = self {
self.loadingView.displayLoadingError(withMessage: message)
}
})
}
@objc func delayed_reload() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(delayed_reload), object: nil)
if jsonCache.currentTask == nil || jsonCache.currentTask?.state != .running {
loadingView.alpha = 1.0
loadingView.startAnimation()
jsonCache.request(withCompletionHandler: { [weak self] (templateURL, error) in
DispatchQueue.main.async(execute: { [weak self] in
if let `self` = self {
if let error = error {
self.displayLoadingError(withMessage: error.localizedDescription)
return
}
guard let templateURL = templateURL else {
self.displayLoadingError(withMessage: "Template URL not provided.")
return
}
guard let configuration = self.configuration else {
self.displayLoadingError(withMessage: "Configuration not provided.")
return
}
let url = buildUrl(templateURL: templateURL, configuration: configuration, customVariables: self.customVariables, maxLength: 2000)
if let url = url, let wv = self.webView {
let request = URLRequest(url: url)
if #available(iOS 9.0, *) {
// Changing UserAgent string:
wv.evaluateJavaScript("navigator.userAgent") {(result, error) in
DispatchQueue.main.async(execute: {
if let userAgent = result as? String {
wv.customUserAgent = userAgent + " WebView_Widget_iOS/2.0.7"
if LiveChatState.isChatOpenedBefore() {
wv.load(request)
}
}
})
}
} else {
if LiveChatState.isChatOpenedBefore() {
wv.load(request)
}
}
} else {
print("error: Invalid url")
self.displayLoadingError(withMessage: "Invalid url")
}
}
})
})
}
}
// MARK: LoadingViewDelegate
func reloadWithDelay() {
self.perform(#selector(delayed_reload), with: nil, afterDelay: 0.2)
}
func reload() {
if let webView = webView {
self.loadingView.alpha = 1.0
self.loadingView.startAnimation()
webView.reload()
}
}
@objc func close() {
dismissChat(animated: true) { (finished) in
if finished {
if let delegate = self.delegate {
delegate.closedChatView()
}
}
}
}
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return nil // No zooming
}
// MARK: WKNavigationDelegate
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("Did fail navigation error: " + error.localizedDescription)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
if let URL = navigationAction.request.url ,
UIApplication.shared.canOpenURL(URL) {
if let delegate = self.delegate {
delegate.handle(URL: URL)
}
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
} else {
decisionHandler(.allow)
}
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
let error = error as NSError
loadingView.alpha = 1.0
if !(error.domain == NSURLErrorDomain && error.code == -999) {
loadingView.displayLoadingError(withMessage: error.localizedDescription)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if let webView = self.webView, webView.alpha == 0 {
self.webViewBridge?.postBlurEvent()
}
UIView.animate(withDuration: 0.3,
delay: 1.0,
options: UIView.AnimationOptions(),
animations: {
self.loadingView.alpha = 0
},
completion: { (finished) in
})
}
// MARK: WKUIDelegate
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if (navigationAction.targetFrame == nil) {
let popup = WKWebView(frame: webView.frame, configuration: configuration)
popup.uiDelegate = self
self.addSubview(popup)
return popup
}
return nil;
}
func webViewDidClose(_ webView: WKWebView) {
webView.removeFromSuperview()
}
@available(iOS 10.0, *)
func webView(_ webView: WKWebView, shouldPreviewElement elementInfo: WKPreviewElementInfo) -> Bool {
return false
}
// MARK: WKScriptMessageHandler
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if (message.body is NSDictionary) {
webViewBridge?.handle(message.body as! NSDictionary);
}
}
}
| mit |
gaoleegin/DamaiPlayBusinessnormal | DamaiPlayBusinessPhone/DamaiPlayBusinessPhone/Classes/Tools/DMNetwork.swift | 1 | 1185 | //
// DMNetWork.swift
// DamaiPlayBusinessPhone
//
// Created by 高李军 on 15/10/28.
// Copyright © 2015年 DamaiPlayBusinessPhone. All rights reserved.
//
import UIKit
import Alamofire
import SVProgressHUD
class DMNetwork: NSObject {
class func requestJSON(method:Alamofire.Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
completion:(JSON: AnyObject?)->()){
//添加辅助参数
var mutaParams: [String: AnyObject] = ["platform":1,"source":10000,"version":10100]
for (key,value) in parameters! {
mutaParams[key] = value
}
Alamofire.request(method, URLString, parameters: mutaParams).responseJSON { (Response) in
if Response.result.isSuccess == false || Response.result.error != nil || Response.result.value == nil{
SVProgressHUD.showInfoWithStatus("数据出错")
}else{
completion(JSON: Response.result.value)
}
print(Response.debugDescription)
}
}
}
| apache-2.0 |
artyom-stv/TextInputKit | TextInputKit/TextInputKit/Code/SpecializedTextInput/BankCardNumber/BankCardNumber.swift | 1 | 3633 | //
// BankCardNumber.swift
// TextInputKit
//
// Created by Artem Starosvetskiy on 25/11/2016.
// Copyright © 2016 Artem Starosvetskiy. All rights reserved.
//
import Foundation
public struct BankCardNumber {
/// An error thrown by `BankCardNumber` initializers.
///
/// - unexpectedCharacters: The provided string contains unexpected characters.
public enum InitializationError : Error {
case unexpectedCharacters
}
public let digitsString: String
public let formattedString: String
public let cardBrand: BankCardBrand?
/// Creates a `BankCardNumber` by string representation.
///
/// - Parameters:
/// - digitsString: The string of digits which represents a bank card number.
/// - Throws: `InitializationError.unexpectedCharacters` if the provided string contains non-digit characters.
public init(digitsString: String) throws {
guard digitsString.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil else {
throw InitializationError.unexpectedCharacters
}
let digitsStringView = digitsString.unicodeScalars
let digitsStringLength = digitsStringView.count
let iinRange = Utils.iinRange(
fromDigitsString: digitsString,
withLength: digitsStringLength)
let iinRangeInfo = Utils.info(forIinRange: iinRange)
let sortedSpacesPositions = Utils.sortedSpacesPositions(for: iinRangeInfo?.cardBrand)
let formattedStringView = Utils.cardNumberStringView(
fromDigits: digitsStringView,
withLength: digitsStringLength,
sortedSpacesPositions: sortedSpacesPositions)
self.init(
digitsString: digitsString,
formattedString: String(formattedStringView),
cardBrand: iinRangeInfo?.cardBrand)
}
fileprivate typealias Utils = BankCardNumberUtils
/// The memberwise initializer with reduced access level.
fileprivate init(
digitsString: String,
formattedString: String,
cardBrand: BankCardBrand?) {
self.digitsString = digitsString
self.formattedString = formattedString
self.cardBrand = cardBrand
}
}
extension BankCardNumber {
/// Creates a `BankCardNumber` by a formatted string which represents a bank card number.
///
/// - Note: For the internal use only.
///
/// - Parameters:
/// - formattedString: The formatted string which represents a bank card number.
init(formattedString: String) {
guard let digitsStringView = Utils.cardNumberDigitsStringView(from: formattedString.unicodeScalars) else {
fatalError("Unexpected characters in `formattedString` argument.")
}
let digitsString = String(digitsStringView)
// Length of ASCII string is similar in `characters` and in `unicodeScalars`.
let digitsStringLength = digitsStringView.count
let iinRange = Utils.iinRange(
fromDigitsString: digitsString,
withLength: digitsStringLength)
let iinRangeInfo = Utils.info(forIinRange: iinRange)
self.init(
digitsString: digitsString,
formattedString: formattedString,
cardBrand: iinRangeInfo?.cardBrand)
}
}
extension BankCardNumber: Equatable {
public static func ==(lhs: BankCardNumber, rhs: BankCardNumber) -> Bool {
return lhs.digitsString == rhs.digitsString
}
}
extension BankCardNumber: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(digitsString)
}
}
| mit |
JTWang4778/LearningSwiftDemos | 01-myFirstSwiftDemo/01-myFirstSwiftDemo/AppDelegate.swift | 1 | 2181 | //
// AppDelegate.swift
// 01-myFirstSwiftDemo
//
// Created by 王锦涛 on 2016/11/8.
// Copyright © 2016年 JTWang. All rights reserved.
//
import UIKit
@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:.
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/26048-swift-genericparamlist-create.swift | 11 | 418 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
enum b:T}{{{{{class
case,
| apache-2.0 |
wikimedia/wikipedia-ios | Wikipedia/Code/ReferenceViewController.swift | 1 | 2784 | import Foundation
protocol ReferenceViewControllerDelegate: AnyObject {
var referenceWebViewBackgroundTapGestureRecognizer: UITapGestureRecognizer { get }
func referenceViewControllerUserDidTapClose(_ vc: ReferenceViewController)
func referenceViewControllerUserDidNavigateBackToReference(_ vc: ReferenceViewController)
}
class ReferenceViewController: ViewController {
weak var delegate: ReferenceViewControllerDelegate?
var referenceId: String? = nil
var referenceLinkText: String? = nil {
didSet {
updateTitle()
}
}
func updateTitle() {
guard let referenceLinkText = referenceLinkText else {
return
}
let titleFormat = WMFLocalizedString("article-reference-view-title", value: "Reference %@", comment: "Title for the reference view. %@ is replaced by the reference link name, for example [1].")
navigationItem.title = String.localizedStringWithFormat(titleFormat, referenceLinkText)
}
func setupNavbar() {
navigationBar.displayType = .modal
updateTitle()
navigationItem.rightBarButtonItem = closeButton
navigationItem.leftBarButtonItem = backToReferenceButton
apply(theme: self.theme)
}
// MARK: View Lifecycle
override func viewDidLoad() {
navigationMode = .forceBar
super.viewDidLoad()
setupNavbar()
}
// MARK: Actions
lazy var backToReferenceButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: UIImage(named: "references"), style: .plain, target: self, action: #selector(goBackToReference))
button.accessibilityLabel = WMFLocalizedString("reference-section-button-accessibility-label", value: "Jump to reference section", comment: "Voiceover label for the top button (that jumps to article's reference section) when viewing a reference's details")
return button
}()
lazy var closeButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: UIImage(named: "close-inverse"), style: .plain, target: self, action: #selector(closeButtonPressed))
button.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
return button
}()
@objc func closeButtonPressed() {
delegate?.referenceViewControllerUserDidTapClose(self)
}
@objc func goBackToReference() {
delegate?.referenceViewControllerUserDidNavigateBackToReference(self)
}
// MARK: Theme
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
closeButton.tintColor = theme.colors.secondaryText
backToReferenceButton.tintColor = theme.colors.link
}
}
| mit |
paleksandrs/APNetworking | APNetworkingTests/MockURLSessionDataTask.swift | 1 | 422 | //
// Created by Aleksandrs Proskurins
//
// License
// Copyright © 2017 Aleksandrs Proskurins
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import UIKit
@testable import APNetworking
class MockURLSessionDataTask: URLSessionDataTaskProtocol {
var resumeWasCalled = false
func resume() {
resumeWasCalled = true
}
func cancel() {
}
}
| mit |
intrahouse/aerogear-ios-http | AeroGearHttp/Http.swift | 1 | 30639 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/**
The HTTP method verb:
- GET: GET http verb
- HEAD: HEAD http verb
- DELETE: DELETE http verb
- POST: POST http verb
- PUT: PUT http verb
*/
public enum HttpMethod: String {
case get = "GET"
case head = "HEAD"
case delete = "DELETE"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
}
/**
The file request type:
- Download: Download request
- Upload: Upload request
*/
enum FileRequestType {
case download(String?)
case upload(UploadType)
}
/**
The Upload enum type:
- Data: for a generic NSData object
- File: for File passing the URL of the local file to upload
- Stream: for a Stream request passing the actual NSInputStream
*/
enum UploadType {
case data(Foundation.Data)
case file(URL)
case stream(InputStream)
}
/**
Error domain.
**/
public let HttpErrorDomain: String = "HttpDomain"
/**
Request error.
**/
public let NetworkingOperationFailingURLRequestErrorKey = "NetworkingOperationFailingURLRequestErrorKey"
/**
Response error.
**/
public let NetworkingOperationFailingURLResponseErrorKey = "NetworkingOperationFailingURLResponseErrorKey"
public typealias ProgressBlock = (Int64, Int64, Int64) -> Void
public typealias CompletionBlock = (Any?, NSError?) -> Void
/**
Main class for performing HTTP operations across RESTful resources.
*/
open class Http {
var baseURL: String?
var session: URLSession
var requestSerializer: RequestSerializer
var responseSerializer: ResponseSerializer
open var authzModule: AuthzModule?
open var disableServerTrust: Bool = false
fileprivate var delegate: SessionDelegate
/**
Initialize an HTTP object.
:param: baseURL the remote base URL of the application (optional).
:param: sessionConfig the SessionConfiguration object (by default it uses a defaultSessionConfiguration).
:param: requestSerializer the actual request serializer to use when performing requests.
:param: responseSerializer the actual response serializer to use upon receiving a response.
:returns: the newly intitialized HTTP object
*/
public init(baseURL: String? = nil,
sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default,
requestSerializer: RequestSerializer = JsonRequestSerializer(),
responseSerializer: ResponseSerializer = JsonResponseSerializer()) {
self.baseURL = baseURL
self.delegate = SessionDelegate()
self.session = URLSession(configuration: sessionConfig, delegate: self.delegate, delegateQueue: OperationQueue.main)
self.requestSerializer = requestSerializer
self.responseSerializer = responseSerializer
}
public init(baseURL: String? = nil,
sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default,
requestSerializer: RequestSerializer = JsonRequestSerializer(),
responseSerializer: ResponseSerializer = JsonResponseSerializer(),
disableServerTrust: Bool) {
self.baseURL = baseURL
self.delegate = SessionDelegate()
self.session = URLSession(configuration: sessionConfig, delegate: self.delegate, delegateQueue: OperationQueue.main)
self.requestSerializer = requestSerializer
self.responseSerializer = responseSerializer
self.disableServerTrust = disableServerTrust
self.delegate.disableServerTrust = disableServerTrust
}
deinit {
self.session.finishTasksAndInvalidate()
}
open func activateDisableServerTrust(){
disableServerTrust = true
self.delegate = SessionDelegate()
}
/**
Gateway to perform different http requests including multipart.
:param: url the url of the resource.
:param: parameters the request parameters.
:param: method the method to be used.
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func request(method: HttpMethod, path: String, parameters: [String: Any]? = nil, credential: URLCredential? = nil, responseSerializer: ResponseSerializer? = nil, completionHandler: @escaping CompletionBlock) {
let block: () -> Void = {
let finalOptURL = self.calculateURL(baseURL: self.baseURL, url: path)
guard let finalURL = finalOptURL else {
let error = NSError(domain: "AeroGearHttp", code: 0, userInfo: [NSLocalizedDescriptionKey: "Malformed URL"])
completionHandler(nil, error)
return
}
var request: URLRequest
var task: URLSessionTask?
var delegate: TaskDataDelegate
// Merge headers
let headers = merge(self.requestSerializer.headers, self.authzModule?.authorizationFields())
// care for multipart request is multipart data are set
if (self.hasMultiPartData(httpParams: parameters)) {
request = self.requestSerializer.multipartRequest(url: finalURL, method: method, parameters: parameters, headers: headers)
task = self.session.uploadTask(withStreamedRequest: request)
delegate = TaskUploadDelegate()
} else {
request = self.requestSerializer.request(url: finalURL, method: method, parameters: parameters, headers: headers)
task = self.session.dataTask(with: request);
delegate = TaskDataDelegate()
}
delegate.completionHandler = completionHandler
delegate.responseSerializer = responseSerializer == nil ? self.responseSerializer : responseSerializer
delegate.credential = credential
self.delegate[task] = delegate
if let task = task {task.resume()}
}
// cater for authz and pre-authorize prior to performing request
if (self.authzModule != nil) {
self.authzModule?.requestAccess(completionHandler: { (response, error ) in
// if there was an error during authz, no need to continue
if (error != nil) {
completionHandler(nil, error)
return
}
// ..otherwise proceed normally
block();
})
} else {
block()
}
}
/**
Gateway to perform different file requests either download or upload.
:param: url the url of the resource.
:param: parameters the request parameters.
:param: method the method to be used.
:param: responseSerializer the actual response serializer to use upon receiving a response
:param: type the file request type
:param: progress a block that will be invoked to report progress during either download or upload.
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
fileprivate func fileRequest(_ url: String, parameters: [String: Any]? = nil, method: HttpMethod, credential: URLCredential? = nil, responseSerializer: ResponseSerializer? = nil, type: FileRequestType, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
let block: () -> Void = {
let finalOptURL = self.calculateURL(baseURL: self.baseURL, url: url)
guard let finalURL = finalOptURL else {
let error = NSError(domain: "AeroGearHttp", code: 0, userInfo: [NSLocalizedDescriptionKey: "Malformed URL"])
completionHandler(nil, error)
return
}
var request: URLRequest
// Merge headers
let headers = merge(self.requestSerializer.headers, self.authzModule?.authorizationFields())
// care for multipart request is multipart data are set
if (self.hasMultiPartData(httpParams: parameters)) {
request = self.requestSerializer.multipartRequest(url: finalURL, method: method, parameters: parameters, headers: headers)
} else {
request = self.requestSerializer.request(url: finalURL, method: method, parameters: parameters, headers: headers)
}
var task: URLSessionTask?
switch type {
case .download(let destinationDirectory):
task = self.session.downloadTask(with: request)
let delegate = TaskDownloadDelegate()
delegate.downloadProgress = progress
delegate.destinationDirectory = destinationDirectory as NSString?;
delegate.completionHandler = completionHandler
delegate.credential = credential
delegate.responseSerializer = responseSerializer == nil ? self.responseSerializer : responseSerializer
self.delegate[task] = delegate
case .upload(let uploadType):
switch uploadType {
case .data(let data):
task = self.session.uploadTask(with: request, from: data)
case .file(let url):
task = self.session.uploadTask(with: request, fromFile: url)
case .stream(_):
task = self.session.uploadTask(withStreamedRequest: request)
}
let delegate = TaskUploadDelegate()
delegate.uploadProgress = progress
delegate.completionHandler = completionHandler
delegate.credential = credential
delegate.responseSerializer = responseSerializer
self.delegate[task] = delegate
}
if let task = task {task.resume()}
}
// cater for authz and pre-authorize prior to performing request
if (self.authzModule != nil) {
self.authzModule?.requestAccess(completionHandler: { (response, error ) in
// if there was an error during authz, no need to continue
if (error != nil) {
completionHandler(nil, error)
return
}
// ..otherwise proceed normally
block();
})
} else {
block()
}
}
/**
Request to download a file.
:param: url the URL of the downloadable resource.
:param: destinationDirectory the destination directory where the file would be stored, if not specified. application's default '.Documents' directory would be used.
:param: parameters the request parameters.
:param: credential the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
:param: method the method to be used, by default a .GET request.
:param: progress a block that will be invoked to report progress during download.
:param: completionHandler a block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func download(url: String, destinationDirectory: String? = nil, parameters: [String: Any]? = nil, credential: URLCredential? = nil, method: HttpMethod = .get, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
fileRequest(url, parameters: parameters, method: method, credential: credential, type: .download(destinationDirectory), progress: progress, completionHandler: completionHandler)
}
/**
Request to upload a file using an NURL of a local file.
:param: url the URL to upload resource into.
:param: file the URL of the local file to be uploaded.
:param: parameters the request parameters.
:param: credential the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
:param: method the method to be used, by default a .POST request.
:param: responseSerializer the actual response serializer to use upon receiving a response.
:param: progress a block that will be invoked to report progress during upload.
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func upload(url: String, file: URL, parameters: [String: Any]? = nil, credential: URLCredential? = nil, method: HttpMethod = .post, responseSerializer: ResponseSerializer? = nil, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
fileRequest(url, parameters: parameters, method: method, credential: credential, responseSerializer: responseSerializer, type: .upload(.file(file)), progress: progress, completionHandler: completionHandler)
}
/**
Request to upload a file using a raw NSData object.
:param: url the URL to upload resource into.
:param: data the data to be uploaded.
:param: parameters the request parameters.
:param: credential the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
:param: method the method to be used, by default a .POST request.
:param: responseSerializer the actual response serializer to use upon receiving a response.
:param: progress a block that will be invoked to report progress during upload.
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func upload(url: String, data: Data, parameters: [String: Any]? = nil, credential: URLCredential? = nil, method: HttpMethod = .post, responseSerializer: ResponseSerializer? = nil, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
fileRequest(url, parameters: parameters, method: method, credential: credential, responseSerializer: responseSerializer, type: .upload(.data(data)), progress: progress, completionHandler: completionHandler)
}
/**
Request to upload a file using an NSInputStream object.
- parameter url: the URL to upload resource into.
- parameter stream: the stream that will be used for uploading.
- parameter parameters: the request parameters.
- parameter credential: the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
- parameter method: the method to be used, by default a .POST request.
- parameter responseSerializer: the actual response serializer to use upon receiving a response.
- parameter progress: a block that will be invoked to report progress during upload.
- parameter completionHandler: A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func upload(url: String, stream: InputStream, parameters: [String: AnyObject]? = nil, credential: URLCredential? = nil, method: HttpMethod = .post, responseSerializer: ResponseSerializer? = nil, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
fileRequest(url, parameters: parameters, method: method, credential: credential, responseSerializer: responseSerializer, type: .upload(.stream(stream)), progress: progress, completionHandler: completionHandler)
}
// MARK: Private API
// MARK: SessionDelegate
class SessionDelegate: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate, URLSessionDownloadDelegate {
fileprivate var delegates: [Int: TaskDelegate]
open var disableServerTrust: Bool = false
fileprivate subscript(task: URLSessionTask?) -> TaskDelegate? {
get {
guard let task = task else {
return nil
}
return self.delegates[task.taskIdentifier]
}
set (newValue) {
guard let task = task else {
return
}
self.delegates[task.taskIdentifier] = newValue
}
}
required override init() {
self.delegates = Dictionary()
super.init()
}
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
// TODO
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if (disableServerTrust) {
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!))
} else {
completionHandler(.performDefaultHandling, nil)
}
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
// TODO
}
// MARK: NSURLSessionTaskDelegate
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
if let delegate = self[task] {
delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request, completionHandler: completionHandler)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if let delegate = self[task] {
delegate.urlSession(session, task: task, didReceive: challenge, completionHandler: completionHandler)
} else {
self.urlSession(session, didReceive: challenge, completionHandler: completionHandler)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
if let delegate = self[task] {
delegate.urlSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? TaskUploadDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let delegate = self[task] {
delegate.urlSession(session, task: task, didCompleteWithError: error)
self[task] = nil
}
}
// MARK: NSURLSessionDataDelegate
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) {
let downloadDelegate = TaskDownloadDelegate()
self[downloadTask] = downloadDelegate
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let delegate = self[dataTask] as? TaskDataDelegate {
delegate.urlSession(session, dataTask: dataTask, didReceive: data)
}
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
completionHandler(proposedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if let delegate = self[downloadTask] as? TaskDownloadDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? TaskDownloadDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? TaskDownloadDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
}
}
// MARK: NSURLSessionTaskDelegate
class TaskDelegate: NSObject, URLSessionTaskDelegate {
var data: Data? { return nil }
var completionHandler: ((Any?, NSError?) -> Void)?
var responseSerializer: ResponseSerializer?
var credential: URLCredential?
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
completionHandler(request)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
var disposition: Foundation.URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
completionHandler(disposition, credential)
}
func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: (@escaping (InputStream?) -> Void)) {
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error != nil {
completionHandler?(nil, error as NSError?)
return
}
let response = task.response as! HTTPURLResponse
if let _ = task as? URLSessionDownloadTask {
completionHandler?(response, error as NSError?)
return
}
var responseObject: Any? = nil
do {
if let data = data {
try self.responseSerializer?.validation(response, data)
responseObject = self.responseSerializer?.response(data, response.statusCode)
completionHandler?(responseObject, nil)
}
} catch let error as NSError {
var userInfo = error.userInfo
userInfo["StatusCode"] = response.statusCode
let errorToRethrow = NSError(domain: error.domain, code: error.code, userInfo: userInfo)
completionHandler?(responseObject, errorToRethrow)
}
}
}
// MARK: NSURLSessionDataDelegate
class TaskDataDelegate: TaskDelegate, URLSessionDataDelegate {
fileprivate var mutableData: NSMutableData
override var data: Data? {
return self.mutableData as Data
}
override init() {
self.mutableData = NSMutableData()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.mutableData.append(data)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
let cachedResponse = proposedResponse
completionHandler(cachedResponse)
}
}
// MARK: NSURLSessionDownloadDelegate
class TaskDownloadDelegate: TaskDelegate, URLSessionDownloadDelegate {
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: Data?
var destinationDirectory: NSString?
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let filename = downloadTask.response?.suggestedFilename
// calculate final destination
var finalDestination: URL
if (destinationDirectory == nil) { // use 'default documents' directory if not set
// use default documents directory
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
finalDestination = documentsDirectory.appendingPathComponent(filename!)
} else {
// check that the directory exists
let path = destinationDirectory?.appendingPathComponent(filename!)
finalDestination = URL(fileURLWithPath: path!)
}
do {
try FileManager.default.moveItem(at: location, to: finalDestination)
} catch _ {
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
self.downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
}
}
// MARK: NSURLSessionTaskDelegate
class TaskUploadDelegate: TaskDataDelegate {
var uploadProgress: ((Int64, Int64, Int64) -> Void)?
func URLSession(_ session: Foundation.URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
self.uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
// MARK: Utility methods
open func calculateURL(baseURL: String?, url: String) -> URL? {
var url = url
if (baseURL == nil || url.hasPrefix("http")) {
return URL(string: url)!
}
guard let finalURL = URL(string: baseURL!) else {return nil}
if (url.hasPrefix("/")) {
url = url.substring(from: url.characters.index(url.startIndex, offsetBy: 1))
}
return finalURL.appendingPathComponent(url);
}
func hasMultiPartData(httpParams parameters: [String: Any]?) -> Bool {
if (parameters == nil) {
return false
}
var isMultiPart = false
for (_, value) in parameters! {
if value is MultiPartData {
isMultiPart = true
break
}
}
return isMultiPart
}
}
| apache-2.0 |
ZevEisenberg/Padiddle | Padiddle/PadiddleTests/MathTests.swift | 1 | 858 | //
// MathTests.swift
// Padiddle
//
// Created by Zev Eisenberg on 2/28/16.
// Copyright © 2016 Zev Eisenberg. All rights reserved.
//
import XCTest
class MathTests: XCTestCase {
func testCloseEnough() {
XCTAssertTrue(CGFloat(0.00000001).closeEnough(to: 0))
XCTAssertTrue(CGFloat(0.00000001).closeEnough(to: 0.00000002))
XCTAssertFalse(CGFloat(1).closeEnough(to: 2))
XCTAssertTrue(CGFloat(0).closeEnough(to: 0))
XCTAssertTrue(CGFloat(1).closeEnough(to: 1))
XCTAssertTrue(CGFloat(-1).closeEnough(to: -1))
XCTAssertTrue(CGFloat(-0.00000001).closeEnough(to: 0.00000001))
}
func testReasonableValue() {
XCTAssertEqual(CGFloat(0).reasonableValue, 0)
XCTAssertEqual(CGFloat(1E-10).reasonableValue, 0)
XCTAssertNotEqual(CGFloat(1E-2).reasonableValue, 0)
}
}
| mit |
tidepool-org/nutshell-ios | Nutshell/ViewControllers/EventListViewController.swift | 1 | 18725 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
import CoreData
class EventListViewController: BaseUIViewController, ENSideMenuDelegate {
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet weak var searchTextField: NutshellUITextField!
@IBOutlet weak var searchPlaceholderLabel: NutshellUILabel!
@IBOutlet weak var tableView: NutshellUITableView!
@IBOutlet weak var coverView: UIControl!
fileprivate var sortedNutEvents = [(String, NutEvent)]()
fileprivate var filteredNutEvents = [(String, NutEvent)]()
fileprivate var filterString = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = "All events"
// 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()
// Add a notification for when the database changes
let moc = NutDataController.controller().mocForNutEvents()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(EventListViewController.databaseChanged(_:)), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: moc)
notificationCenter.addObserver(self, selector: #selector(EventListViewController.textFieldDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
if let sideMenu = self.sideMenuController()?.sideMenu {
sideMenu.delegate = self
menuButton.target = self
menuButton.action = #selector(EventListViewController.toggleSideMenu(_:))
let revealWidth = min(ceil((240.0/320.0) * self.view.bounds.width), 281.0)
sideMenu.menuWidth = revealWidth
sideMenu.bouncingEnabled = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate var viewIsForeground: Bool = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewIsForeground = true
configureSearchUI()
if let sideMenu = self.sideMenuController()?.sideMenu {
sideMenu.allowLeftSwipe = true
sideMenu.allowRightSwipe = true
sideMenu.allowPanGesture = true
}
if sortedNutEvents.isEmpty || eventListNeedsUpdate {
eventListNeedsUpdate = false
getNutEvents()
}
checkNotifyUserOfTestMode()
// periodically check for authentication issues in case we need to force a new login
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.checkConnection()
APIConnector.connector().trackMetric("Viewed Home Screen (Home Screen)")
}
// each first time launch of app, let user know we are still in test mode!
fileprivate func checkNotifyUserOfTestMode() {
if AppDelegate.testMode && !AppDelegate.testModeNotification {
AppDelegate.testModeNotification = true
let alert = UIAlertController(title: "Test Mode", message: "Nutshell has Test Mode enabled!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { Void in
return
}))
alert.addAction(UIAlertAction(title: "Turn Off", style: .default, handler: { Void in
AppDelegate.testMode = false
}))
self.present(alert, animated: true, completion: nil)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchTextField.resignFirstResponder()
viewIsForeground = false
if let sideMenu = self.sideMenuController()?.sideMenu {
//NSLog("swipe disabled")
sideMenu.allowLeftSwipe = false
sideMenu.allowRightSwipe = false
sideMenu.allowPanGesture = false
}
}
@IBAction func toggleSideMenu(_ sender: AnyObject) {
APIConnector.connector().trackMetric("Clicked Hamburger (Home Screen)")
toggleSideMenuView()
}
//
// MARK: - ENSideMenu Delegate
//
fileprivate func configureForMenuOpen(_ open: Bool) {
if open {
if let sideMenuController = self.sideMenuController()?.sideMenu?.menuViewController as? MenuAccountSettingsViewController {
// give sidebar a chance to update
// TODO: this should really be in ENSideMenu!
sideMenuController.menuWillOpen()
}
}
tableView.isUserInteractionEnabled = !open
self.navigationItem.rightBarButtonItem?.isEnabled = !open
coverView.isHidden = !open
}
func sideMenuWillOpen() {
//NSLog("EventList sideMenuWillOpen")
configureForMenuOpen(true)
}
func sideMenuWillClose() {
//NSLog("EventList sideMenuWillClose")
configureForMenuOpen(false)
}
func sideMenuShouldOpenSideMenu() -> Bool {
//NSLog("EventList sideMenuShouldOpenSideMenu")
return true
}
func sideMenuDidClose() {
//NSLog("EventList sideMenuDidClose")
configureForMenuOpen(false)
}
func sideMenuDidOpen() {
//NSLog("EventList sideMenuDidOpen")
configureForMenuOpen(true)
APIConnector.connector().trackMetric("Viewed Hamburger Menu (Hamburger)")
}
//
// 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.
super.prepare(for: segue, sender: sender)
if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.EventGroupSegue {
let cell = sender as! EventListTableViewCell
let eventGroupVC = segue.destination as! EventGroupTableViewController
eventGroupVC.eventGroup = cell.eventGroup!
APIConnector.connector().trackMetric("Clicked a Meal (Home screen)")
} else if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.EventItemDetailSegue {
let cell = sender as! EventListTableViewCell
let eventDetailVC = segue.destination as! EventDetailViewController
let group = cell.eventGroup!
eventDetailVC.eventGroup = group
eventDetailVC.eventItem = group.itemArray[0]
APIConnector.connector().trackMetric("Clicked a Meal (Home screen)")
} else if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.HomeToAddEventSegue {
APIConnector.connector().trackMetric("Click Add (Home screen)")
} else {
NSLog("Unprepped segue from eventList \(segue.identifier)")
}
}
// Back button from group or detail viewer.
@IBAction func done(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList done!")
}
// Multiple VC's on the navigation stack return all the way back to this initial VC via this segue, when nut events go away due to deletion, for test purposes, etc.
@IBAction func home(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList home!")
}
// The add/edit VC will return here when a meal event is deleted, and detail vc was transitioned to directly from this vc (i.e., the Nut event contained a single meal event which was deleted).
@IBAction func doneItemDeleted(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList doneItemDeleted")
}
@IBAction func cancel(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList cancel")
}
fileprivate var eventListNeedsUpdate: Bool = false
func databaseChanged(_ note: Notification) {
NSLog("EventList: Database Change Notification")
if viewIsForeground {
getNutEvents()
} else {
eventListNeedsUpdate = true
}
}
func getNutEvents() {
var nutEvents = [String: NutEvent]()
func addNewEvent(_ newEvent: EventItem) {
/// TODO: TEMP UPGRADE CODE, REMOVE BEFORE SHIPPING!
if newEvent.userid == nil {
newEvent.userid = NutDataController.controller().currentUserId
if let moc = newEvent.managedObjectContext {
NSLog("NOTE: Updated nil userid to \(newEvent.userid)")
moc.refresh(newEvent, mergeChanges: true)
_ = DatabaseUtils.databaseSave(moc)
}
}
/// TODO: TEMP UPGRADE CODE, REMOVE BEFORE SHIPPING!
let newEventId = newEvent.nutEventIdString()
if let existingNutEvent = nutEvents[newEventId] {
_ = existingNutEvent.addEvent(newEvent)
//NSLog("appending new event: \(newEvent.notes)")
//existingNutEvent.printNutEvent()
} else {
nutEvents[newEventId] = NutEvent(firstEvent: newEvent)
}
}
sortedNutEvents = [(String, NutEvent)]()
filteredNutEvents = [(String, NutEvent)]()
filterString = ""
// Get all Food and Activity events, chronologically; this will result in an unsorted dictionary of NutEvents.
do {
let nutEvents = try DatabaseUtils.getAllNutEvents()
for event in nutEvents {
//if let event = event as? Workout {
// NSLog("Event type: \(event.type), id: \(event.id), time: \(event.time), created time: \(event.createdTime!.timeIntervalSinceDate(event.time!)), duration: \(event.duration), title: \(event.title), notes: \(event.notes), userid: \(event.userid), timezone offset:\(event.timezoneOffset)")
//}
addNewEvent(event)
}
} catch let error as NSError {
NSLog("Error: \(error)")
}
sortedNutEvents = nutEvents.sorted() { $0.1.mostRecent.compare($1.1.mostRecent as Date) == ComparisonResult.orderedDescending }
updateFilteredAndReload()
// One time orphan check after application load
EventListViewController.checkAndDeleteOrphans(sortedNutEvents)
}
static var _checkedForOrphanPhotos = false
class func checkAndDeleteOrphans(_ allNutEvents: [(String, NutEvent)]) {
if _checkedForOrphanPhotos {
return
}
_checkedForOrphanPhotos = true
if let photoDirPath = NutUtils.photosDirectoryPath() {
var allLocalPhotos = [String: Bool]()
let fm = FileManager.default
do {
let dirContents = try fm.contentsOfDirectory(atPath: photoDirPath)
//NSLog("Photos dir: \(dirContents)")
if !dirContents.isEmpty {
for file in dirContents {
allLocalPhotos[file] = false
}
for (_, nutEvent) in allNutEvents {
for event in nutEvent.itemArray {
for url in event.photoUrlArray() {
if url.hasPrefix("file_") {
//NSLog("\(NutUtils.photoInfo(url))")
allLocalPhotos[url] = true
}
}
}
}
}
} catch let error as NSError {
NSLog("Error accessing photos at \(photoDirPath), error: \(error)")
}
let orphans = allLocalPhotos.filter() { $1 == false }
for (url, _) in orphans {
NSLog("Deleting orphaned photo: \(url)")
NutUtils.deleteLocalPhoto(url)
}
}
}
// MARK: - Search
@IBAction func dismissKeyboard(_ sender: AnyObject) {
searchTextField.resignFirstResponder()
}
func textFieldDidChange() {
updateFilteredAndReload()
}
@IBAction func searchEditingDidEnd(_ sender: AnyObject) {
configureSearchUI()
}
@IBAction func searchEditingDidBegin(_ sender: AnyObject) {
configureSearchUI()
APIConnector.connector().trackMetric("Typed into Search (Home Screen)")
}
fileprivate func searchMode() -> Bool {
var searchMode = false
if searchTextField.isFirstResponder {
searchMode = true
} else if let searchText = searchTextField.text {
if !searchText.isEmpty {
searchMode = true
}
}
return searchMode
}
fileprivate func configureSearchUI() {
let searchOn = searchMode()
searchPlaceholderLabel.isHidden = searchOn
self.title = searchOn && !filterString.isEmpty ? "Events" : "All events"
}
fileprivate func updateFilteredAndReload() {
if !searchMode() {
filteredNutEvents = sortedNutEvents
filterString = ""
} else if let searchText = searchTextField.text {
if !searchText.isEmpty {
if searchText.localizedCaseInsensitiveContains(filterString) {
// if the search is just getting longer, no need to check already filtered out items
filteredNutEvents = filteredNutEvents.filter() {
$1.containsSearchString(searchText)
}
} else {
filteredNutEvents = sortedNutEvents.filter() {
$1.containsSearchString(searchText)
}
}
filterString = searchText
} else {
filteredNutEvents = sortedNutEvents
filterString = ""
}
// Do this last, after filterString is configured
configureSearchUI()
}
tableView.reloadData()
}
}
//
// MARK: - Table view delegate
//
extension EventListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt estimatedHeightForRowAtIndexPath: IndexPath) -> CGFloat {
return 102.0;
}
func tableView(_ tableView: UITableView, heightForRowAt heightForRowAtIndexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let tuple = self.filteredNutEvents[indexPath.item]
let nutEvent = tuple.1
let cell = tableView.cellForRow(at: indexPath)
if nutEvent.itemArray.count == 1 {
self.performSegue(withIdentifier: EventViewStoryboard.SegueIdentifiers.EventItemDetailSegue, sender: cell)
} else if nutEvent.itemArray.count > 1 {
self.performSegue(withIdentifier: EventViewStoryboard.SegueIdentifiers.EventGroupSegue, sender: cell)
}
}
}
//
// MARK: - Table view data source
//
extension EventListViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredNutEvents.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Note: two different list cells are used depending upon whether a location will be shown or not.
var cellId = EventViewStoryboard.TableViewCellIdentifiers.eventListCellNoLoc
var nutEvent: NutEvent?
if (indexPath.item < filteredNutEvents.count) {
let tuple = self.filteredNutEvents[indexPath.item]
nutEvent = tuple.1
if !nutEvent!.location.isEmpty {
cellId = EventViewStoryboard.TableViewCellIdentifiers.eventListCellWithLoc
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! EventListTableViewCell
if let nutEvent = nutEvent {
cell.configureCell(nutEvent)
}
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
}
*/
}
| bsd-2-clause |
IWU-CIS-396-Wearable-computing/WatchOS2CounterSwift | WatchOS2CounterSwift/ViewController.swift | 1 | 1038 | //
// ViewController.swift
// WatchOS2CounterSwift
//
// Created by Thai, Kristina on 6/20/15.
// Copyright © 2015 Kristina Thai. All rights reserved.
//
import UIKit
import WatchConnectivity
class ViewController: UIViewController, UITableViewDataSource {
var counterData = [String]()
@IBOutlet weak var mainTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.mainTableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return counterData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CounterCell"
let cell = self.mainTableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
let counterValueString = self.counterData[indexPath.row]
cell.textLabel?.text = counterValueString
return cell
}
}
| mit |
happylance/MacKey | MacKeyUnit/Reducers/HostsReducer.swift | 1 | 1989 | //
// HostsReducer.swift
// MacKey
//
// Created by Liu Liang on 14/01/2017.
// Copyright © 2017 Liu Liang. All rights reserved.
//
import Foundation
struct HostsReducer {
static func handleAction(_ action: Action, state: HostsState) -> HostsState {
return HostsState(
allHosts: allHostsReducer(action, state: state),
latestHostAlias: latestHostAliasReducer(action, state: state)
)
}
private static func allHostsReducer(_ action: Action, state: HostsState) -> Hosts {
var hosts = state.allHosts
switch action {
case let action as AddHost:
let newHost = action.host
hosts[newHost.alias] = newHost
case let action as RemoveHost:
let oldHost = action.host
hosts.removeValue(forKey: oldHost.alias)
case let action as UpdateHost:
let updatedHost = action.newHost
let oldHost = action.oldHost
if updatedHost.alias != oldHost.alias {
hosts.removeValue(forKey: oldHost.alias)
}
hosts[updatedHost.alias] = updatedHost
default:
break
}
return hosts
}
private static func latestHostAliasReducer(_ action: Action, state: HostsState) -> String {
switch action {
case let action as SelectHost:
return action.host.alias
case let action as RemoveHost:
return state.latestHostAlias == action.host.alias ? "" : state.latestHostAlias
case let action as UpdateHost:
let newHost = action.newHost
let oldHost = action.oldHost
if state.latestHostAlias == oldHost.alias {
return newHost.alias
}
return state.latestHostAlias
default:
return state.latestHostAlias
}
}
static func now() -> TimeInterval {
return Date().timeIntervalSince1970
}
}
| mit |
AlbertXYZ/HDCP | HDCP/Pods/SnapKit/Source/Constraint.swift | 1 | 11778 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class Constraint {
internal let sourceLocation: (String, UInt)
internal let label: String?
private let from: ConstraintItem
private let to: ConstraintItem
private let relation: ConstraintRelation
private let multiplier: ConstraintMultiplierTarget
private var constant: ConstraintConstantTarget {
didSet {
self.updateConstantAndPriorityIfNeeded()
}
}
private var priority: ConstraintPriorityTarget {
didSet {
self.updateConstantAndPriorityIfNeeded()
}
}
private var layoutConstraints: [LayoutConstraint]
// MARK: Initialization
internal init(from: ConstraintItem,
to: ConstraintItem,
relation: ConstraintRelation,
sourceLocation: (String, UInt),
label: String?,
multiplier: ConstraintMultiplierTarget,
constant: ConstraintConstantTarget,
priority: ConstraintPriorityTarget) {
self.from = from
self.to = to
self.relation = relation
self.sourceLocation = sourceLocation
self.label = label
self.multiplier = multiplier
self.constant = constant
self.priority = priority
self.layoutConstraints = []
// get attributes
let layoutFromAttributes = self.from.attributes.layoutAttributes
let layoutToAttributes = self.to.attributes.layoutAttributes
// get layout from
let layoutFrom: ConstraintView = self.from.view!
// get relation
let layoutRelation = self.relation.layoutRelation
for layoutFromAttribute in layoutFromAttributes {
// get layout to attribute
let layoutToAttribute: NSLayoutAttribute
#if os(iOS) || os(tvOS)
if layoutToAttributes.count > 0 {
if self.from.attributes == .edges && self.to.attributes == .margins {
switch layoutFromAttribute {
case .left:
layoutToAttribute = .leftMargin
case .right:
layoutToAttribute = .rightMargin
case .top:
layoutToAttribute = .topMargin
case .bottom:
layoutToAttribute = .bottomMargin
default:
fatalError()
}
} else if self.from.attributes == .margins && self.to.attributes == .edges {
switch layoutFromAttribute {
case .leftMargin:
layoutToAttribute = .left
case .rightMargin:
layoutToAttribute = .right
case .topMargin:
layoutToAttribute = .top
case .bottomMargin:
layoutToAttribute = .bottom
default:
fatalError()
}
} else if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else {
layoutToAttribute = layoutToAttributes[0]
}
} else {
if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) {
layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top
} else {
layoutToAttribute = layoutFromAttribute
}
}
#else
if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else if layoutToAttributes.count > 0 {
layoutToAttribute = layoutToAttributes[0]
} else {
layoutToAttribute = layoutFromAttribute
}
#endif
// get layout constant
let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutToAttribute)
// get layout to
var layoutTo: AnyObject? = self.to.target
// use superview if possible
if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height {
layoutTo = layoutFrom.superview
}
// create layout constraint
let layoutConstraint = LayoutConstraint(
item: layoutFrom,
attribute: layoutFromAttribute,
relatedBy: layoutRelation,
toItem: layoutTo,
attribute: layoutToAttribute,
multiplier: self.multiplier.constraintMultiplierTargetValue,
constant: layoutConstant
)
// set label
layoutConstraint.label = self.label
// set priority
layoutConstraint.priority = self.priority.constraintPriorityTargetValue
// set constraint
layoutConstraint.constraint = self
// append
self.layoutConstraints.append(layoutConstraint)
}
}
// MARK: Public
@available(*, deprecated:3.0, message:"Use activate().")
public func install() {
self.activate()
}
@available(*, deprecated:3.0, message:"Use deactivate().")
public func uninstall() {
self.deactivate()
}
public func activate() {
self.activateIfNeeded()
}
public func deactivate() {
self.deactivateIfNeeded()
}
@discardableResult
public func update(offset: ConstraintOffsetTarget) -> Constraint {
self.constant = offset.constraintOffsetTargetValue
return self
}
@discardableResult
public func update(inset: ConstraintInsetTarget) -> Constraint {
self.constant = inset.constraintInsetTargetValue
return self
}
@discardableResult
public func update(priority: ConstraintPriorityTarget) -> Constraint {
self.priority = priority.constraintPriorityTargetValue
return self
}
@available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.")
public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) }
@available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.")
public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) }
@available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityRequired() -> Void {}
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
// MARK: Internal
internal func updateConstantAndPriorityIfNeeded() {
for layoutConstraint in self.layoutConstraints {
let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(attribute)
#if os(iOS) || os(tvOS)
let requiredPriority: UILayoutPriority = UILayoutPriorityRequired
#else
let requiredPriority: Float = 1000.0
#endif
if (layoutConstraint.priority < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) {
layoutConstraint.priority = self.priority.constraintPriorityTargetValue
}
}
}
internal func activateIfNeeded(updatingExisting: Bool = false) {
guard let view = self.from.view else {
print("WARNING: SnapKit failed to get from view from constraint. Activate will be a no-op.")
return
}
let layoutConstraints = self.layoutConstraints
let existingLayoutConstraints = view.snp.constraints.map({ $0.layoutConstraints }).reduce([]) { $0 + $1 }
if updatingExisting {
for layoutConstraint in layoutConstraints {
let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint }
guard let updateLayoutConstraint = existingLayoutConstraint else {
fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)")
}
let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute
updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(updateLayoutAttribute)
}
} else {
NSLayoutConstraint.activate(layoutConstraints)
view.snp.add(constraints: [self])
}
}
internal func deactivateIfNeeded() {
guard let view = self.from.view else {
print("WARNING: SnapKit failed to get from view from constraint. Deactivate will be a no-op.")
return
}
let layoutConstraints = self.layoutConstraints
NSLayoutConstraint.deactivate(layoutConstraints)
view.snp.remove(constraints: [self])
}
}
| mit |
dvaughn1712/perfect-routing | PerfectLib/NotificationPusher.swift | 2 | 13151 | //
// NotificationPusher.swift
// PerfectLib
//
// Created by Kyle Jessup on 2016-02-16.
// Copyright © 2016 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
/**
Example code:
// BEGIN one-time initialization code
let configurationName = "My configuration name - can be whatever"
NotificationPusher.addConfigurationIOS(configurationName) {
(net:NetTCPSSL) in
// This code will be called whenever a new connection to the APNS service is required.
// Configure the SSL related settings.
net.keyFilePassword = "if you have password protected key file"
guard net.useCertificateChainFile("path/to/entrust_2048_ca.cer") &&
net.useCertificateFile("path/to/aps_development.pem") &&
net.usePrivateKeyFile("path/to/key.pem") &&
net.checkPrivateKey() else {
let code = Int32(net.errorCode())
print("Error validating private key file: \(net.errorStr(code))")
return
}
}
NotificationPusher.development = true // set to toggle to the APNS sandbox server
// END one-time initialization code
// BEGIN - individual notification push
let deviceId = "hex string device id"
let ary = [IOSNotificationItem.AlertBody("This is the message"), IOSNotificationItem.Sound("default")]
let n = NotificationPusher()
n.apnsTopic = "com.company.my-app"
n.pushIOS(configurationName, deviceToken: deviceId, expiration: 0, priority: 10, notificationItems: ary) {
response in
print("NotificationResponse: \(response.code) \(response.body)")
}
// END - individual notification push
*/
/// Items to configure an individual notification push.
/// These correspond to what is described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html
public enum IOSNotificationItem {
case AlertBody(String)
case AlertTitle(String)
case AlertTitleLoc(String, [String]?)
case AlertActionLoc(String)
case AlertLoc(String, [String]?)
case AlertLaunchImage(String)
case Badge(Int)
case Sound(String)
case ContentAvailable
case Category(String)
case CustomPayload(String, Any)
}
enum IOSItemId: UInt8 {
case DeviceToken = 1
case Payload = 2
case NotificationIdentifier = 3
case ExpirationDate = 4
case Priority = 5
}
private let iosDeviceIdLength = 32
private let iosNotificationCommand = UInt8(2)
private let iosNotificationPort = UInt16(443)
private let iosNotificationDevelopmentHost = "api.development.push.apple.com"
private let iosNotificationProductionHost = "api.push.apple.com"
struct IOSNotificationError {
let code: UInt8
let identifier: UInt32
}
class NotificationConfiguration {
let configurator: NotificationPusher.netConfigurator
let lock = Threading.Lock()
var streams = [NotificationHTTP2Client]()
init(configurator: NotificationPusher.netConfigurator) {
self.configurator = configurator
}
}
class NotificationHTTP2Client: HTTP2Client {
let id: Int
init(id: Int) {
self.id = id
}
}
/// The response object given after a push attempt.
public struct NotificationResponse {
/// The response code for the request.
public let code: Int
/// The response body data bytes.
public let body: [UInt8]
/// The body data bytes interpreted as JSON and decoded into a Dictionary.
public var jsonObjectBody: [String:Any] {
do {
if let json = try self.stringBody.jsonDecode() as? [String:Any] {
return json
}
}
catch {}
return [String:Any]()
}
/// The body data bytes converted to String.
public var stringBody: String {
return UTF8Encoding.encode(self.body)
}
}
/// The interface for APNS notifications.
public class NotificationPusher {
/// On-demand configuration for SSL related functions.
public typealias netConfigurator = (NetTCPSSL) -> ()
/// Toggle development or production on a global basis.
public static var development = false
/// Sets the apns-topic which will be used for iOS notifications.
public var apnsTopic: String?
var responses = [NotificationResponse]()
static var idCounter = 0
static var notificationHostIOS: String {
if self.development {
return iosNotificationDevelopmentHost
}
return iosNotificationProductionHost
}
static let configurationsLock = Threading.Lock()
static var iosConfigurations = [String:NotificationConfiguration]()
static var activeStreams = [Int:NotificationHTTP2Client]()
/// Add a configuration given a name and a callback.
/// A particular configuration will generally correspond to an individual app.
/// The configuration callback will be called each time a new connection is initiated to the APNS.
/// Within the callback you will want to set:
/// 1. Path to chain file as provided by Apple: net.useCertificateChainFile("path/to/entrust_2048_ca.cer")
/// 2. Path to push notification certificate as obtained from Apple: net.useCertificateFile("path/to/aps.pem")
/// 3a. Password for the certificate's private key file, if it is password protected: net.keyFilePassword = "password"
/// 3b. Path to the certificate's private key file: net.usePrivateKeyFile("path/to/key.pem")
public static func addConfigurationIOS(name: String, configurator: netConfigurator) {
self.configurationsLock.doWithLock {
self.iosConfigurations[name] = NotificationConfiguration(configurator: configurator)
}
}
static func getStreamIOS(configurationName: String, callback: (HTTP2Client?) -> ()) {
var conf: NotificationConfiguration?
self.configurationsLock.doWithLock {
conf = self.iosConfigurations[configurationName]
}
if let c = conf {
var net: NotificationHTTP2Client?
var needsConnect = false
c.lock.doWithLock {
if c.streams.count > 0 {
net = c.streams.removeLast()
} else {
needsConnect = true
net = NotificationHTTP2Client(id: idCounter)
activeStreams[idCounter] = net
idCounter = idCounter &+ 1
}
}
if !needsConnect {
callback(net!)
} else {
// add a new connected stream
c.configurator(net!.net)
net!.connect(self.notificationHostIOS, port: iosNotificationPort, ssl: true, timeoutSeconds: 5.0) {
b in
if b {
callback(net!)
} else {
callback(nil)
}
}
}
} else {
callback(nil)
}
}
static func releaseStreamIOS(configurationName: String, net: HTTP2Client) {
var conf: NotificationConfiguration?
self.configurationsLock.doWithLock {
conf = self.iosConfigurations[configurationName]
}
if let c = conf, n = net as? NotificationHTTP2Client {
c.lock.doWithLock {
activeStreams.removeValueForKey(n.id)
if net.isConnected {
c.streams.append(n)
}
}
} else {
net.close()
}
}
public init() {
}
/// Initialize given iOS apns-topic string.
/// This can be set after initialization on the X.apnsTopic property.
public init(apnsTopic: String) {
self.apnsTopic = apnsTopic
}
func resetResponses() {
self.responses.removeAll()
}
/// Push one message to one device.
/// Provide the previously set configuration name, device token.
/// Provide the expiration and priority as described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
/// Provide a list of IOSNotificationItems.
/// Provide a callback with which to receive the response.
public func pushIOS(configurationName: String, deviceToken: String, expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: (NotificationResponse) -> ()) {
NotificationPusher.getStreamIOS(configurationName) {
client in
if let c = client {
self.pushIOS(c, deviceTokens: [deviceToken], expiration: expiration, priority: priority, notificationItems: notificationItems) {
responses in
NotificationPusher.releaseStreamIOS(configurationName, net: c)
if responses.count == 1 {
callback(responses.first!)
} else {
callback(NotificationResponse(code: -1, body: [UInt8]()))
}
}
} else {
callback(NotificationResponse(code: -1, body: [UInt8]()))
}
}
}
/// Push one message to multiple devices.
/// Provide the previously set configuration name, and zero or more device tokens. The same message will be sent to each device.
/// Provide the expiration and priority as described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
/// Provide a list of IOSNotificationItems.
/// Provide a callback with which to receive the responses.
public func pushIOS(configurationName: String, deviceTokens: [String], expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: ([NotificationResponse]) -> ()) {
NotificationPusher.getStreamIOS(configurationName) {
client in
if let c = client {
self.pushIOS(c, deviceTokens: deviceTokens, expiration: expiration, priority: priority, notificationItems: notificationItems) {
responses in
NotificationPusher.releaseStreamIOS(configurationName, net: c)
if responses.count == 1 {
callback(responses)
} else {
callback([NotificationResponse(code: -1, body: [UInt8]())])
}
}
} else {
callback([NotificationResponse(code: -1, body: [UInt8]())])
}
}
}
func pushIOS(net: HTTP2Client, deviceToken: String, expiration: UInt32, priority: UInt8, notificationJson: [UInt8], callback: (NotificationResponse) -> ()) {
let request = net.createRequest()
request.setRequestMethod("POST")
request.postBodyBytes = notificationJson
request.headers["content-type"] = "application/json; charset=utf-8"
request.headers["apns-expiration"] = "\(expiration)"
request.headers["apns-priority"] = "\(priority)"
if let apnsTopic = apnsTopic {
request.headers["apns-topic"] = apnsTopic
}
request.setRequestURI("/3/device/\(deviceToken)")
net.sendRequest(request) {
response, msg in
if let r = response {
let code = r.getStatus().0
callback(NotificationResponse(code: code, body: r.bodyData))
} else {
callback(NotificationResponse(code: -1, body: UTF8Encoding.decode("No response")))
}
}
}
func pushIOS(client: HTTP2Client, deviceTokens: IndexingGenerator<[String]>, expiration: UInt32, priority: UInt8, notificationJson: [UInt8], callback: ([NotificationResponse]) -> ()) {
var g = deviceTokens
if let next = g.next() {
pushIOS(client, deviceToken: next, expiration: expiration, priority: priority, notificationJson: notificationJson) {
response in
self.responses.append(response)
self.pushIOS(client, deviceTokens: g, expiration: expiration, priority: priority, notificationJson: notificationJson, callback: callback)
}
} else {
callback(self.responses)
}
}
func pushIOS(client: HTTP2Client, deviceTokens: [String], expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: ([NotificationResponse]) -> ()) {
self.resetResponses()
let g = deviceTokens.generate()
let jsond = UTF8Encoding.decode(self.itemsToPayloadString(notificationItems))
self.pushIOS(client, deviceTokens: g, expiration: expiration, priority: priority, notificationJson: jsond, callback: callback)
}
func itemsToPayloadString(notificationItems: [IOSNotificationItem]) -> String {
var dict = [String:Any]()
var aps = [String:Any]()
var alert = [String:Any]()
var alertBody: String?
for item in notificationItems {
switch item {
case .AlertBody(let s):
alertBody = s
case .AlertTitle(let s):
alert["title"] = s
case .AlertTitleLoc(let s, let a):
alert["title-loc-key"] = s
if let titleLocArgs = a {
alert["title-loc-args"] = titleLocArgs
}
case .AlertActionLoc(let s):
alert["action-loc-key"] = s
case .AlertLoc(let s, let a):
alert["loc-key"] = s
if let locArgs = a {
alert["loc-args"] = locArgs
}
case .AlertLaunchImage(let s):
alert["launch-image"] = s
case .Badge(let i):
aps["badge"] = i
case .Sound(let s):
aps["sound"] = s
case .ContentAvailable:
aps["content-available"] = 1
case .Category(let s):
aps["category"] = s
case .CustomPayload(let s, let a):
dict[s] = a
}
}
if let ab = alertBody {
if alert.count == 0 { // just a string alert
aps["alert"] = ab
} else { // a dict alert
alert["body"] = ab
aps["alert"] = alert
}
}
dict["aps"] = aps
do {
return try dict.jsonEncodedString()
}
catch {}
return "{}"
}
}
private func jsonSerialize(o: Any) -> String? {
do {
return try jsonEncodedStringWorkAround(o)
} catch let e as JSONConversionError {
print("Could not convert to JSON: \(e)")
} catch {}
return nil
} | unlicense |
marcelganczak/swift-js-transpiler | test/weheartswift/loops-18.swift | 1 | 325 | var number = 10
print("\(number) = ")
var isFirst = true
for i in 2...number {
if number % i == 0 {
while (number % i == 0) {
number /= i
if isFirst {
isFirst = false
} else {
print(" * ")
}
print(i)
}
}
} | mit |
AashiniSharma/Home-Living | Home&Living/TitlesOfSection.swift | 1 | 332 | //
// TitlesOfSection.swift
// Home&Living
//
// Created by Appinventiv on 16/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class TitlesOfSection: UITableViewHeaderFooterView {
@IBOutlet weak var titlesOutlet: UILabel!
@IBOutlet weak var maskingSectionButtonOutlet: UIButton!
}
| mit |
CoderLiLe/Swift | 内存相关/main.swift | 1 | 3324 | //
// main.swift
// 内存相关
//
// Created by LiLe on 15/4/5.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
Swift内存管理:
管理引用类型的内存, 不会管理值类型, 值类型不需要管理
内存管理原则: 当没有任何强引用指向对象, 系统会自动销毁对象
(默认情况下所有的引用都是强引用)
如果做到该原则: ARC
*/
class Person {
var name:String
init(name:String){
self.name = name
}
deinit{
print("deinit")
}
}
var p:Person? = Person(name: "lnj")
//p = nil
/*
weak弱引用
*/
class Person2 {
var name:String
init(name:String){
self.name = name
}
deinit{
print("deinit")
}
}
// 强引用, 引用计数+1
var strongP = Person2(name: "lnj") // 1
var strongP2 = strongP // 2
// 弱引用, 引用计数不变
// 如果利用weak修饰变量, 当对象释放后会自动将变量设置为nil
// 所以利用weak修饰的变量必定是一个可选类型, 因为只有可选类型才能设置为nil
weak var weakP:Person2? = Person2(name: "lnj")
if let p = weakP{
print(p)
}else
{
print(weakP)
}
/*
unowned无主引用 , 相当于OC unsafe_unretained
unowned和weak的区别:
1.利用unowned修饰的变量, 对象释放后不会设置为nil. 不安全
利用weak修饰的变量, 对象释放后会设置为nil
2.利用unowned修饰的变量, 不是可选类型
利用weak修饰的变量, 是可选类型
什么时候使用weak?
什么时候使用unowned?
*/
class Person3 {
var name:String
init(name:String){
self.name = name
}
deinit{
print("deinit")
}
}
unowned var weakP3:Person3 = Person3(name: "lnj")
/*
循环引用
ARC不是万能的, 它可以很好的解决内存问题, 但是在某些场合不能很好的解决内存泄露问题
例如两个或多个对象之间的循环引用问题
*/
class Person4 {
let name:String // 姓名
// 人不一定有公寓
weak var apartment: Apartment? // 公寓
init(name:String){
self.name = name
}
deinit{
print("\(self.name) deinit")
}
}
class Apartment {
let number: Int // 房间号
var tenant: Person4? // 租客
init(number:Int){
self.number = number
}
deinit{
print("\(self.number) deinit")
}
}
var p4:Person4? = Person4(name: "lnj")
var a4:Apartment? = Apartment(number:888)
p4!.apartment = a4 // 人有一套公寓
a4!.tenant = p4! // 公寓中住着一个人
// 两个对象没有被销毁, 但是我们没有办法访问他们了. 内存泄露
p4 = nil
a4 = nil
class Person5 {
let name:String // 姓名
// 人不一定有信用卡
var card: CreditCard?
init(name:String){
self.name = name
}
deinit{
print("\(self.name) deinit")
}
}
class CreditCard{
let number: Int
// 信用卡必须有所属用户
// 当某一个变量/常量必须有值, 一直有值, 那么可以使用unowned修饰
unowned let person: Person5
init(number:Int, person: Person5){
self.number = number
self.person = person
}
deinit{
print("\(self.number) deinit")
}
}
var p5:Person5? = Person5(name: "lnj")
var cc:CreditCard? = CreditCard(number: 8888888, person: p5!)
p5 = nil
cc = nil
| mit |
Tiger-Coding/gameofthronescountdown | GOTCountdown/String+CountdownFormatter.swift | 1 | 2285 | //
// String+CountdownFormatter.swift
// GOTCountdown
//
// Created by user on 4/16/16.
// Copyright © 2016 Javoid. All rights reserved.
//
import Foundation
/** I had to use an extension somewhere :) */
extension String {
/** Will format the remaining time to fit the Game of Thrones font. */
static func formattedCountdownString(let remainingTime: RemainingTime) -> String {
// function to format each time component
func formattedInteger(value: NSInteger, leadingZero: Bool, label: String) -> String {
if leadingZero {
return String(format: "%02d:%@", value, label)
}
else {
return String(format: "%d:%@", value, label)
}
}
if remainingTime.greaterThanZero() {
// only show values for actual time remaining
// add leading zeros to all but the first component
// I could improve this maybe with an array of values and a dictionary for labels but I'm lazy tonight :)
if remainingTime.days > 0 {
return formattedInteger(remainingTime.days, leadingZero: false, label: "d ") +
formattedInteger(remainingTime.hours, leadingZero: true, label: "h ") +
formattedInteger(remainingTime.minutes, leadingZero: true, label: "m ") +
formattedInteger(remainingTime.seconds, leadingZero: true, label: "s")
}
else if remainingTime.hours > 0 {
return formattedInteger(remainingTime.hours, leadingZero: false, label: "h ") +
formattedInteger(remainingTime.minutes, leadingZero: true, label: "m ") +
formattedInteger(remainingTime.seconds, leadingZero: true, label: "s")
}
else if remainingTime.minutes > 0 {
return formattedInteger(remainingTime.minutes, leadingZero: false, label: "m ") +
formattedInteger(remainingTime.seconds, leadingZero: true, label: "s")
}
else {
return formattedInteger(remainingTime.seconds, leadingZero: false, label: "s")
}
}
else {
return "Watch It Now"
}
}
} | mit |
firebase/firebase-ios-sdk | ReleaseTooling/Sources/Utils/ShellUtils.swift | 2 | 8515 | /*
* Copyright 2019 Google
*
* 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
/// Convenience function for calling functions in the Shell. This should be used sparingly and only
/// when interacting with tools that can't be accessed directly in Swift (i.e. CocoaPods,
/// xcodebuild, etc). Intentionally empty, this enum is used as a namespace.
public enum Shell {}
public extension Shell {
/// A type to represent the result of running a shell command.
enum Result {
/// The command was successfully run (based on the output code), with the output string as the
/// associated value.
case success(output: String)
/// The command failed with a given exit code and output.
case error(code: Int32, output: String)
}
/// Log without executing the shell commands.
static var logOnly = false
static func setLogOnly() {
logOnly = true
}
/// Execute a command in the user's shell. This creates a temporary shell script and runs the
/// command from there, instead of calling via `Process()` directly in order to include the
/// appropriate environment variables. This is mostly for CocoaPods commands, but doesn't hurt
/// other commands.
///
/// - Parameters:
/// - command: The command to run in the shell.
/// - outputToConsole: A flag if the command output should be written to the console as well.
/// - workingDir: An optional working directory to run the shell command in.
/// - Returns: A Result containing output information from the command.
static func executeCommandFromScript(_ command: String,
outputToConsole: Bool = true,
workingDir: URL? = nil) -> Result {
let scriptPath: URL
do {
let tempScriptsDir = FileManager.default.temporaryDirectory(withName: "temp_scripts")
try FileManager.default.createDirectory(at: tempScriptsDir,
withIntermediateDirectories: true,
attributes: nil)
scriptPath = tempScriptsDir.appendingPathComponent("wrapper.sh")
// Write the temporary script contents to the script's path. CocoaPods complains when LANG
// isn't set in the environment, so explicitly set it here. The `/usr/local/git/current/bin`
// is to allow the `sso` protocol if it's there.
let contents = """
export PATH="/usr/local/bin:/usr/local/git/current/bin:$PATH"
export LANG="en_US.UTF-8"
source ~/.bash_profile
\(command)
"""
try contents.write(to: scriptPath, atomically: true, encoding: .utf8)
} catch let FileManager.FileError.failedToCreateDirectory(path, error) {
fatalError("Could not execute shell command: \(command) - could not create temporary " +
"script directory at \(path). \(error)")
} catch {
fatalError("Could not execute shell command: \(command) - unexpected error. \(error)")
}
// Remove the temporary script at the end of this function. If it fails, it's not a big deal
// since it will be over-written next time and won't affect the Zip file, so we can ignore
// any failure.
defer { try? FileManager.default.removeItem(at: scriptPath) }
// Let the process call directly into the temporary shell script we created.
let task = Process()
task.arguments = [scriptPath.path]
if #available(OSX 10.13, *) {
if let workingDir = workingDir {
task.currentDirectoryURL = workingDir
}
// Explicitly use `/bin/bash`. Investigate whether or not we can use `/usr/local/env`
task.executableURL = URL(fileURLWithPath: "/bin/bash")
} else {
// Assign the old `currentDirectoryPath` property if `currentDirectoryURL` isn't available.
if let workingDir = workingDir {
task.currentDirectoryPath = workingDir.path
}
task.launchPath = "/bin/bash"
}
// Assign a pipe to read as soon as data is available, log it to the console if requested, but
// also keep an array of the output in memory so we can pass it back to functions.
// Assign a pipe to grab the output, and handle it differently if we want to stream the results
// to the console or not.
let pipe = Pipe()
task.standardOutput = pipe
let outHandle = pipe.fileHandleForReading
var output: [String] = []
// If we want to output to the console, create a readabilityHandler and save each line along the
// way. Otherwise, we can just read the pipe at the end. By disabling outputToConsole, some
// commands (such as any xcodebuild) can run much, much faster.
if outputToConsole {
outHandle.readabilityHandler = { pipe in
// This will be run any time data is sent to the pipe. We want to print it and store it for
// later. Ignore any non-valid Strings.
guard let line = String(data: pipe.availableData, encoding: .utf8) else {
print("Could not get data from pipe for command \(command): \(pipe.availableData)")
return
}
if line != "" {
output.append(line)
}
print(line)
}
// Also set the termination handler on the task in order to stop the readabilityHandler from
// parsing any more data from the task.
task.terminationHandler = { t in
guard let stdOut = t.standardOutput as? Pipe else { return }
stdOut.fileHandleForReading.readabilityHandler = nil
}
}
// Launch the task and wait for it to exit. This will trigger the above readabilityHandler
// method and will redirect the command output back to the console for quick feedback.
if outputToConsole {
print("Running command: \(command).")
print("----------------- COMMAND OUTPUT -----------------")
}
task.launch()
task.waitUntilExit()
if outputToConsole { print("----------------- END COMMAND OUTPUT -----------------") }
let fullOutput: String
if outputToConsole {
fullOutput = output.joined(separator: "\n")
} else {
let outData = outHandle.readDataToEndOfFile()
// Force unwrapping since we know it's UTF8 coming from the console.
fullOutput = String(data: outData, encoding: .utf8)!
}
// Check if the task succeeded or not, and return the failure code if it didn't.
guard task.terminationStatus == 0 else {
return Result.error(code: task.terminationStatus, output: fullOutput)
}
// The command was successful, return the output.
return Result.success(output: fullOutput)
}
/// Execute a command in the user's shell. This creates a temporary shell script and runs the
/// command from there, instead of calling via `Process()` directly in order to include the
/// appropriate environment variables. This is mostly for CocoaPods commands, but doesn't hurt
/// other commands.
///
/// This is a variation of `executeCommandFromScript` that also does error handling internally.
///
/// - Parameters:
/// - command: The command to run in the shell.
/// - outputToConsole: A flag if the command output should be written to the console as well.
/// - workingDir: An optional working directory to run the shell command in.
/// - Returns: A Result containing output information from the command.
static func executeCommand(_ command: String,
outputToConsole: Bool = true,
workingDir: URL? = nil) {
if logOnly {
print(command)
return
}
let result = Shell.executeCommandFromScript(command, workingDir: workingDir)
switch result {
case let .error(code, output):
fatalError("""
`\(command)` failed with exit code \(code) while trying to install pods:
Output from `\(command)`:
\(output)
""")
case let .success(output):
// Print the output to the console and return the information for all installed pods.
print(output)
}
}
}
| apache-2.0 |
sachin004/firefox-ios | Sync/Synchronizers/Synchronizer.swift | 5 | 8986 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
private let log = Logger.syncLogger
/**
* This exists to pass in external context: e.g., the UIApplication can
* expose notification functionality in this way.
*/
public protocol SyncDelegate {
func displaySentTabForURL(URL: NSURL, title: String)
// TODO: storage.
}
/**
* We sometimes want to make a synchronizer start from scratch: to throw away any
* metadata and reset storage to match, allowing us to respond to significant server
* changes.
*
* But instantiating a Synchronizer is a lot of work if we simply want to change some
* persistent state. This protocol describes a static func that fits most synchronizers.
*
* When the returned `Deferred` is filled with a success value, the supplied prefs and
* storage are ready to sync from scratch.
*
* Persisted long-term/local data is kept, and will later be reconciled as appropriate.
*/
public protocol ResettableSynchronizer {
static func resetSynchronizerWithStorage(storage: ResettableSyncStorage, basePrefs: Prefs, collection: String) -> Success
}
// TODO: return values?
/**
* A Synchronizer is (unavoidably) entirely in charge of what it does within a sync.
* For example, it might make incremental progress in building a local cache of remote records, never actually performing an upload or modifying local storage.
* It might only upload data. Etc.
*
* Eventually I envision an intent-like approach, or additional methods, to specify preferences and constraints
* (e.g., "do what you can in a few seconds", or "do a full sync, no matter how long it takes"), but that'll come in time.
*
* A Synchronizer is a two-stage beast. It needs to support synchronization, of course; that
* needs a completely configured client, which can only be obtained from Ready. But it also
* needs to be able to do certain things beforehand:
*
* * Wipe its collections from the server (presumably via a delegate from the state machine).
* * Prepare to sync from scratch ("reset") in response to a changed set of keys, syncID, or node assignment.
* * Wipe local storage ("wipeClient").
*
* Those imply that some kind of 'Synchronizer' exists throughout the state machine. We *could*
* pickle instructions for eventual delivery next time one is made and synchronized…
*/
public protocol Synchronizer {
init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs)
/**
* Return a reason if the current state of this synchronizer -- particularly prefs and scratchpad --
* prevent a routine sync from occurring.
*/
func reasonToNotSync(_: Sync15StorageClient) -> SyncNotStartedReason?
}
/**
* We sometimes wish to return something more nuanced than simple success or failure.
* For example, refusing to sync because the engine was disabled isn't success (nothing was transferred!)
* but it also isn't an error.
*
* To do this we model real failures -- something went wrong -- as failures in the Result, and
* everything else in this status enum. This will grow as we return more details from a sync to allow
* for batch scheduling, success-case backoff and so on.
*/
public enum SyncStatus {
case Completed // TODO: we pick up a bunch of info along the way. Pass it along.
case NotStarted(SyncNotStartedReason)
public var description: String {
switch self {
case .Completed:
return "Completed"
case let .NotStarted(reason):
return "Not started: \(reason.description)"
}
}
}
typealias DeferredTimestamp = Deferred<Maybe<Timestamp>>
public typealias SyncResult = Deferred<Maybe<SyncStatus>>
public enum SyncNotStartedReason {
case NoAccount
case Offline
case Backoff(remainingSeconds: Int)
case EngineRemotelyNotEnabled(collection: String)
case EngineFormatOutdated(needs: Int)
case EngineFormatTooNew(expected: Int) // This'll disappear eventually; we'll wipe the server and upload m/g.
case StorageFormatOutdated(needs: Int)
case StorageFormatTooNew(expected: Int) // This'll disappear eventually; we'll wipe the server and upload m/g.
case StateMachineNotReady // Because we're not done implementing.
var description: String {
switch self {
case .NoAccount:
return "no account"
case let .Backoff(remaining):
return "in backoff: \(remaining) seconds remaining"
default:
return "undescribed reason"
}
}
}
public class FatalError: SyncError {
let message: String
init(message: String) {
self.message = message
}
public var description: String {
return self.message
}
}
public protocol SingleCollectionSynchronizer {
func remoteHasChanges(info: InfoCollections) -> Bool
}
public class BaseCollectionSynchronizer {
let collection: String
let scratchpad: Scratchpad
let delegate: SyncDelegate
let prefs: Prefs
static func prefsForCollection(collection: String, withBasePrefs basePrefs: Prefs) -> Prefs {
let branchName = "synchronizer." + collection + "."
return basePrefs.branch(branchName)
}
init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, collection: String) {
self.scratchpad = scratchpad
self.delegate = delegate
self.collection = collection
self.prefs = BaseCollectionSynchronizer.prefsForCollection(collection, withBasePrefs: basePrefs)
log.info("Synchronizer configured with prefs '\(self.prefs.getBranchPrefix()).'")
}
var storageVersion: Int {
assert(false, "Override me!")
return 0
}
public func reasonToNotSync(client: Sync15StorageClient) -> SyncNotStartedReason? {
let now = NSDate.now()
if let until = client.backoff.isInBackoff(now) {
let remaining = (until - now) / 1000
return .Backoff(remainingSeconds: Int(remaining))
}
if let metaGlobal = self.scratchpad.global?.value {
// There's no need to check the global storage format here; the state machine will already have
// done so.
if let engineMeta = metaGlobal.engines[collection] {
if engineMeta.version > self.storageVersion {
return .EngineFormatOutdated(needs: engineMeta.version)
}
if engineMeta.version < self.storageVersion {
return .EngineFormatTooNew(expected: engineMeta.version)
}
} else {
return .EngineRemotelyNotEnabled(collection: self.collection)
}
} else {
// But a missing meta/global is a real problem.
return .StateMachineNotReady
}
// Success!
return nil
}
func encrypter<T>(encoder: RecordEncoder<T>) -> RecordEncrypter<T>? {
return self.scratchpad.keys?.value.encrypter(self.collection, encoder: encoder)
}
func collectionClient<T>(encoder: RecordEncoder<T>, storageClient: Sync15StorageClient) -> Sync15CollectionClient<T>? {
if let encrypter = self.encrypter(encoder) {
return storageClient.clientForCollection(self.collection, encrypter: encrypter)
}
return nil
}
}
/**
* Tracks a lastFetched timestamp, uses it to decide if there are any
* remote changes, and exposes a method to fast-forward after upload.
*/
public class TimestampedSingleCollectionSynchronizer: BaseCollectionSynchronizer, SingleCollectionSynchronizer {
var lastFetched: Timestamp {
set(value) {
self.prefs.setLong(value, forKey: "lastFetched")
}
get {
return self.prefs.unsignedLongForKey("lastFetched") ?? 0
}
}
func setTimestamp(timestamp: Timestamp) {
log.debug("Setting post-upload lastFetched to \(timestamp).")
self.lastFetched = timestamp
}
public func remoteHasChanges(info: InfoCollections) -> Bool {
return info.modified(self.collection) > self.lastFetched
}
}
extension BaseCollectionSynchronizer: ResettableSynchronizer {
public static func resetSynchronizerWithStorage(storage: ResettableSyncStorage, basePrefs: Prefs, collection: String) -> Success {
let synchronizerPrefs = BaseCollectionSynchronizer.prefsForCollection(collection, withBasePrefs: basePrefs)
synchronizerPrefs.removeObjectForKey("lastFetched")
// Not all synchronizers use a batching downloader, but it's
// convenient to just always reset it here.
return storage.resetClient()
>>> effect({ BatchingDownloader.resetDownloaderWithPrefs(synchronizerPrefs, collection: collection) })
}
} | mpl-2.0 |
sambhav7890/SSChartView | SSChartView/Classes/Graph/Graph.swift | 1 | 11343 | //
// Graph.swift
// Graphs
//
// Created by Sambhav Shah on 2016/09/02.
// Copyright © 2016 S. All rights reserved.
//
import UIKit
public enum GraphType {
case bar
// case line
// case pie
}
open class Graph<T: Hashable, U: NumericType> {
public typealias GraphTextDisplayHandler = (_ unit: GraphUnit<T, U>, _ totalValue: U) -> String?
let kind: GraphKind<T, U>
init(barGraph: BarGraph<T, U>) {
self.kind = GraphKind<T, U>.bar(barGraph)
}
// init(lineGraph: LineGraph<T, U>) {
// self.kind = GraphKind<T, U>.line(lineGraph)
// }
// init(pieGraph: PieGraph<T, U>) {
// self.kind = GraphKind<T, U>.pie(pieGraph)
// }
}
public extension Graph {
public convenience init<S: GraphData>(type: GraphType, data: [S], min minOrNil: U? = nil, max maxOrNil: U? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) where S.GraphDataKey == T, S.GraphDataValue == U {
let range = {() -> GraphRange<U>? in
if let min = minOrNil, let max = maxOrNil {
return GraphRange(min: min, max: max)
}
return nil
}
self.init(type: type, data: data, range: range(), textDisplayHandler: textDisplayHandler)
}
public convenience init<S: GraphData>(type: GraphType, data: [S], range rangeOrNil: GraphRange<U>? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) where S.GraphDataKey == T, S.GraphDataValue == U {
let r = {() -> GraphRange<U> in
if let r = rangeOrNil { return r }
let sorted = data.sorted { $0.value < $1.value }
return GraphRange<U>(
min: sorted.first?.value ?? U(0),
max: sorted.last?.value ?? U(0)
)
}
switch type {
case .bar:
self.init(barGraph:BarGraph<T, U>(
units: data.map { GraphUnit<T, U>(key: $0.key, value: $0.value) },
range: r(),
textDisplayHandler: textDisplayHandler
))
// case .line:
//
// self.init(lineGraph: LineGraph<T, U>(
// units: data.map { GraphUnit<T, U>(key: $0.key, value: $0.value) },
// range: r(),
// textDisplayHandler: textDisplayHandler
// ))
// case .pie:
//
// self.init(pieGraph: PieGraph<T, U>(
// units: data.map { GraphUnit<T, U>(key: $0.key, value: $0.value) },
// textDisplayHandler: textDisplayHandler
// ))
}
}
public convenience init(type: GraphType, array: [U], min minOrNil: U? = nil, max maxOrNil: U? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) {
let range = {() -> GraphRange<U>? in
if let min = minOrNil, let max = maxOrNil {
return GraphRange(min: min, max: max)
}
return nil
}
self.init(type: type, array: array, range: range(), textDisplayHandler: textDisplayHandler)
}
public convenience init(type: GraphType, array: [U], range rangeOrNil: GraphRange<U>? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) {
let r = {() -> GraphRange<U> in
if let r = rangeOrNil { return r }
let sorted = array.sorted { $0 < $1 }
return GraphRange<U>(
min: sorted.first ?? U(0),
max: sorted.last ?? U(0)
)
}
switch type {
case .bar:
self.init(barGraph:BarGraph<T, U>(
units: array.map { GraphUnit<T, U>(key: nil, value: $0) },
range: r(),
textDisplayHandler: textDisplayHandler
))
// case .line:
// self.init(lineGraph: LineGraph<T, U>(
// units: array.map { GraphUnit<T, U>(key: nil, value: $0) },
// range: r(),
// textDisplayHandler: textDisplayHandler
// ))
// case .pie:
// self.init(pieGraph: PieGraph<T, U>(
// units: array.map { GraphUnit<T, U>(key: nil, value: $0) },
// textDisplayHandler: textDisplayHandler
// ))
}
}
}
public extension Graph {
public convenience init(type: GraphType, dictionary: [T: U], min minOrNil: U? = nil, max maxOrNil: U? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) {
let range = {() -> GraphRange<U>? in
if let min = minOrNil, let max = maxOrNil {
return GraphRange(min: min, max: max)
}
return nil
}
self.init(type: type, dictionary: dictionary, range: range(), textDisplayHandler: textDisplayHandler)
}
public convenience init(type: GraphType, dictionary: [T: U], range rangeOrNil: GraphRange<U>? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) {
let sorted = dictionary.sorted { $0.1 < $1.1 }
let r = {() -> GraphRange<U> in
if let r = rangeOrNil { return r }
return GraphRange<U>(
min: sorted.first?.1 ?? U(0),
max: sorted.last?.1 ?? U(0)
)
}
switch type {
case .bar:
self.init(barGraph:BarGraph<T, U>(
units: sorted.map { GraphUnit<T, U>(key: $0.0, value: $0.1) },
range: r(),
textDisplayHandler: textDisplayHandler
))
// case .line:
//
// self.init(lineGraph: LineGraph<T, U>(
// units: sorted.map { GraphUnit<T, U>(key: $0.0, value: $0.1) },
// range: r(),
// textDisplayHandler: textDisplayHandler
// ))
// case .pie:
//
// self.init(pieGraph: PieGraph<T, U>(
// units: sorted.map { GraphUnit<T, U>(key: $0.0, value: $0.1) },
// textDisplayHandler: textDisplayHandler
// ))
//
}
}
}
public extension Graph {
public func view(_ frame: CGRect) -> GraphView<T, U> {
return GraphView(frame: frame, graph: self)
}
}
enum GraphKind<T: Hashable, U: NumericType> {
case bar(BarGraph<T, U>)
// case line(LineGraph<T, U>)
// case pie(PieGraph<T, U>)
internal static func barGraph(_ units: [GraphUnit<T, U>], range: GraphRange<U>) -> GraphKind<T, U> {
return GraphKind<T, U>.bar(BarGraph(units: units, range: range))
}
// internal static func lineGraph(_ units: [GraphUnit<T, U>], range: GraphRange<U>) -> GraphKind<T, U> {
// return GraphKind<T, U>.line(LineGraph(units: units, range: range))
// }
//
// internal static func pieGraph(_ units: [GraphUnit<T, U>]) -> GraphKind<T, U> {
// return GraphKind<T, U>.pie(PieGraph(units: units))
// }
}
public protocol GraphBase {
associatedtype UnitsType
associatedtype RangeType
associatedtype GraphTextDisplayHandler
var units: UnitsType { get }
var textDisplayHandler: GraphTextDisplayHandler? { get }
}
internal struct BarGraph<T: Hashable, U: NumericType>: GraphBase {
typealias GraphView = BarGraphView<T, U>
typealias UnitsType = [GraphUnit<T, U>]
typealias RangeType = GraphRange<U>
typealias GraphTextDisplayHandler = Graph<T, U>.GraphTextDisplayHandler
var units: [GraphUnit<T, U>]
var range: GraphRange<U>
var textDisplayHandler: GraphTextDisplayHandler?
internal init(
units: [GraphUnit<T, U>],
range: GraphRange<U>,
textDisplayHandler: GraphTextDisplayHandler? = nil
) {
self.units = units
self.range = range
self.textDisplayHandler = textDisplayHandler
}
func view(_ frame: CGRect) -> GraphView? {
return BarGraphView<T, U>(
frame: frame,
graph: self
)
}
func graphTextDisplay() -> GraphTextDisplayHandler {
if let f = textDisplayHandler {
return f
}
return { (unit, total) -> String? in String(describing: unit.value) }
}
}
//internal struct MultiBarGraph<T: Hashable, U: NumericType>: GraphBase {
//
// typealias UnitsType = [[GraphUnit<T, U>]]
// typealias RangeType = GraphRange<U>
// typealias GraphTextDisplayHandler = Graph<T, U>.GraphTextDisplayHandler
//
// var units: [[GraphUnit<T, U>]]
// var range: GraphRange<U>
// var textDisplayHandler: GraphTextDisplayHandler?
//
// func graphTextDisplay() -> GraphTextDisplayHandler {
// if let f = textDisplayHandler {
// return f
// }
// return { (unit, total) -> String? in String(describing: unit.value) }
// }
//}
//internal struct LineGraph<T: Hashable, U: NumericType>: GraphBase {
//
// typealias GraphView = LineGraphView<T, U>
// typealias UnitsType = [GraphUnit<T, U>]
// typealias RangeType = GraphRange<U>
// typealias GraphTextDisplayHandler = Graph<T, U>.GraphTextDisplayHandler
//
// var units: [GraphUnit<T, U>]
// var range: GraphRange<U>
// var textDisplayHandler: GraphTextDisplayHandler?
//
// init(
// units: [GraphUnit<T, U>],
// range: GraphRange<U>,
// textDisplayHandler: GraphTextDisplayHandler? = nil
// ) {
// self.units = units
// self.range = range
// self.textDisplayHandler = textDisplayHandler
// }
//
// func view(_ frame: CGRect) -> GraphView? {
// return LineGraphView(frame: frame, graph: self)
// }
//
// func graphTextDisplay() -> GraphTextDisplayHandler {
// if let f = textDisplayHandler {
// return f
// }
// return { (unit, total) -> String? in String(describing: unit.value) }
// }
//}
//internal struct PieGraph<T: Hashable, U: NumericType>: GraphBase {
//
// typealias GraphView = PieGraphView<T, U>
// typealias UnitsType = [GraphUnit<T, U>]
// typealias RangeType = GraphRange<U>
// typealias GraphTextDisplayHandler = Graph<T, U>.GraphTextDisplayHandler
//
// var units: [GraphUnit<T, U>]
// var textDisplayHandler: GraphTextDisplayHandler?
//
// init(
// units: [GraphUnit<T, U>],
// textDisplayHandler: GraphTextDisplayHandler? = nil
// ) {
// self.units = units
// self.textDisplayHandler = textDisplayHandler
// }
//
// func view(_ frame: CGRect) -> GraphView? {
// return PieGraphView(frame: frame, graph: self)
// }
//
// func graphTextDisplay() -> GraphTextDisplayHandler {
// if let f = textDisplayHandler {
// return f
// }
// return { (unit, total) -> String? in
// let f = unit.value.floatValue() / total.floatValue()
// return String(describing: unit.value) + " : " + String(format: "%.0f%%", f * 100.0)
// }
// }
//}
public struct GraphUnit<T: Hashable, U: NumericType> {
public let key: T?
public let value: U
public init(key: T?, value: U) {
self.key = key
self.value = value
}
}
public struct GraphRange<T: NumericType> {
let min: T
let max: T
public init(min: T, max: T) {
assert(min <= max)
self.min = min
self.max = max
}
}
public struct BarGraphApperance {
public let barColor: UIColor
public let barWidthScale: CGFloat
public let valueTextAttributes: GraphTextAttributes?
init(
barColor: UIColor?,
barWidthScale: CGFloat?,
valueTextAttributes: GraphTextAttributes?
) {
self.barColor = barColor ?? DefaultColorType.bar.color()
self.barWidthScale = barWidthScale ?? 0.8
self.valueTextAttributes = valueTextAttributes
}
}
public struct GraphTextAttributes {
public let font: UIFont
public let textColor: UIColor
public let textAlign: NSTextAlignment
init(
font: UIFont?,
textColor: UIColor?,
textAlign: NSTextAlignment?
) {
self.font = font ?? UIFont.systemFont(ofSize: 10.0)
self.textColor = textColor ?? UIColor.gray
self.textAlign = textAlign ?? .center
}
}
| mit |
michaelarmstrong/SuperMock | Example/SuperMock.playground/Pages/PlayingNetworkData.xcplaygroundpage/Contents.swift | 1 | 3412 | //: ### [<< Previous](@previous)
// If you cannot see this file correctly go on the menu Editor -> Show Render Markup.
// Build the project at least once before run the playground.
import Foundation
@testable import SuperMock
/*:
# SuperMock: Playing network calls
### This section will show how to make supermock reply with mocks to your network calls
### We have a file of mocks, the same seen in the recording session, so if you have already seen it you can skip this section. The mocks tell to supermock what to reply to API calls if a url is not in the mocks the framework let it go through and hit the network. It is organised in GET, PUT, POST, DELETE categories and each category contains the related urls, each url contain an array of dictionary of "response" "data" key that represent response headers and response body. They hold the link of the files that contain the real data. The file need to be part of your resouces to be used in the play function.
*/
let bundle = Bundle.main
if let path = bundle.path(forResource: "Mocks", ofType: "plist") {
let mocks = NSDictionary(contentsOf: URL(fileURLWithPath: path))?["mocks"] as? [String: Any]
let getCalls = mocks?["GET"] as? [String: Any]
let appleCalls = getCalls?["http://apple.com/uk"] as? [[String:String]]
appleCalls?.count
}
/*:
### To obtain the mock from the call we just need to make the call to the network after the framework has begin mocking
*/
SuperMock.beginMocking(bundle)
var fileBundle = SuperMockResponseHelper.bundleForMocks
var mocks = SuperMockResponseHelper.sharedHelper.mocks
var GETs = mocks["GET"] as? [String: Any]
let url = URL(string:"http://apple.com/uk")!
GETs?[url.absoluteString]
var completed = false
getTheUKApplePage() { (bytes, status, success) in
bytes
status
success
completed = true
}
while !completed {}
completed = false
/*:
### As you can notice the response size of our network call is 52815 and the response status 200. What happen if I make the same call a second time? Accordingly to our mock call the second call should return a response with status code 400 and same body.
*/
getTheUKApplePage() { (bytes, status, success) in
bytes
status
success
completed = true
}
while !completed {}
completed = false
/*:
### What happen if I make the same call a third time? Accordingly to our mock call the second call should return a response with status code 200 and changed body, the size of the data is 54961 bytes this time.
*/
getTheUKApplePage() { (bytes, status, success) in
bytes
status
success
completed = true
}
while !completed {}
/*:
### always remember to terminate the recording, it is good practice.
*/
SuperMock.endMocking()
/*:
### In case you are using a URLSession that is not the default one you need to register the protocols once the URLSession is created.
*/
let customSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "SuperMockBackgroundConfiguration")
let customURLSession = URLSession(configuration: customSessionConfiguration)
SuperMock.beginMocking(bundle, configuration: customSessionConfiguration, session: customURLSession)
fileBundle = SuperMockResponseHelper.bundleForMocks
/*:
### always remember to terminate the recording, it is good practice.
*/
SuperMock.endMocking()
/*:
### Everything from now on will behave normally and the calls will hit the network.
*/
| mit |
magicien/GLTFSceneKit | Sample/macOS/GameViewController.swift | 1 | 4652 | //
// GameViewController.swift
// GameSample
//
// Created by magicien on 2017/08/17.
// Copyright © 2017年 DarkHorse. All rights reserved.
//
import SceneKit
import QuartzCore
import GLTFSceneKit
class GameViewController: NSViewController {
@IBOutlet weak var gameView: GameView!
@IBOutlet weak var openFileButton: NSButton!
@IBOutlet weak var cameraSelect: NSPopUpButton!
var cameraNodes: [SCNNode] = []
let defaultCameraTag: Int = 99
override func awakeFromNib(){
super.awakeFromNib()
var scene: SCNScene
do {
let sceneSource = try GLTFSceneSource(named: "art.scnassets/GlassVase/Wayfair-GlassVase-BCHH2364.glb")
scene = try sceneSource.scene()
} catch {
print("\(error.localizedDescription)")
return
}
self.setScene(scene)
self.gameView!.autoenablesDefaultLighting = true
// allows the user to manipulate the camera
self.gameView!.allowsCameraControl = true
// show statistics such as fps and timing information
self.gameView!.showsStatistics = true
// configure the view
self.gameView!.backgroundColor = NSColor.gray
self.gameView!.addObserver(self, forKeyPath: "pointOfView", options: [.new], context: nil)
self.gameView!.delegate = self
}
func setScene(_ scene: SCNScene) {
// update camera names
self.cameraNodes = scene.rootNode.childNodes(passingTest: { (node, finish) -> Bool in
return node.camera != nil
})
// set the scene to the view
self.gameView!.scene = scene
// set the camera menu
self.cameraSelect.menu?.removeAllItems()
if self.cameraNodes.count > 0 {
self.cameraSelect.removeAllItems()
let titles = self.cameraNodes.map { $0.camera?.name ?? "untitled" }
for title in titles {
self.cameraSelect.menu?.addItem(withTitle: title, action: nil, keyEquivalent: "")
}
self.gameView!.pointOfView = self.cameraNodes[0]
}
//to give nice reflections :)
scene.lightingEnvironment.contents = "art.scnassets/shinyRoom.jpg"
scene.lightingEnvironment.intensity = 2;
let defaultCameraItem = NSMenuItem(title: "SCNViewFreeCamera", action: nil, keyEquivalent: "")
defaultCameraItem.tag = self.defaultCameraTag
defaultCameraItem.isEnabled = false
self.cameraSelect.menu?.addItem(defaultCameraItem)
self.cameraSelect.autoenablesItems = false
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "pointOfView", let change = change {
if let cameraNode = change[.newKey] as? SCNNode {
// It must use the main thread to change the UI.
DispatchQueue.main.async {
if let index = self.cameraNodes.index(of: cameraNode) {
self.cameraSelect.selectItem(at: index)
} else {
self.cameraSelect.selectItem(withTag: self.defaultCameraTag)
}
}
}
}
}
@IBAction func openFileButtonClicked(_ sender: Any) {
let openPanel = NSOpenPanel()
openPanel.canChooseFiles = true
openPanel.canChooseDirectories = false
openPanel.allowsMultipleSelection = false
openPanel.allowedFileTypes = ["gltf", "glb", "vrm"]
openPanel.message = "Choose glTF file"
openPanel.begin { (response) in
if response == .OK {
guard let url = openPanel.url else { return }
do {
let sceneSource = GLTFSceneSource.init(url: url)
let scene = try sceneSource.scene()
self.setScene(scene)
} catch {
print("\(error.localizedDescription)")
}
}
}
}
@IBAction func selectCamera(_ sender: Any) {
let index = self.cameraSelect.indexOfSelectedItem
let cameraNode = self.cameraNodes[index]
self.gameView!.pointOfView = cameraNode
}
}
extension GameViewController: SCNSceneRendererDelegate {
func renderer(_ renderer: SCNSceneRenderer, didApplyAnimationsAtTime time: TimeInterval) {
self.gameView.scene?.rootNode.updateVRMSpringBones(time: time)
}
}
| mit |
naithar/Kitura | Sources/Kitura/FileResourceServer.swift | 1 | 3402 | /*
* Copyright IBM Corporation 2016, 2017
*
* 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 LoggerAPI
class FileResourceServer {
/// if file found - send it in response
func sendIfFound(resource: String, usingResponse response: RouterResponse) {
guard let resourceFileName = getFilePath(for: resource) else {
do {
try response.send("Cannot find resource: \(resource)").status(.notFound).end()
} catch {
Log.error("failed to send not found response for resource: \(resource)")
}
return
}
do {
try response.send(fileName: resourceFileName)
try response.status(.OK).end()
} catch {
Log.error("failed to send response with resource \(resourceFileName)")
}
}
private func getFilePath(for resource: String) -> String? {
let fileManager = FileManager.default
var potentialResource = getResourcePathBasedOnSourceLocation(for: resource)
if potentialResource.hasSuffix("/") {
potentialResource += "index.html"
}
let fileExists = fileManager.fileExists(atPath: potentialResource)
if fileExists {
return potentialResource
} else {
return getResourcePathBasedOnCurrentDirectory(for: resource, withFileManager: fileManager)
}
}
private func getResourcePathBasedOnSourceLocation(for resource: String) -> String {
let fileName = NSString(string: #file)
let resourceFilePrefixRange: NSRange
let lastSlash = fileName.range(of: "/", options: .backwards)
if lastSlash.location != NSNotFound {
resourceFilePrefixRange = NSRange(location: 0, length: lastSlash.location+1)
} else {
resourceFilePrefixRange = NSRange(location: 0, length: fileName.length)
}
return fileName.substring(with: resourceFilePrefixRange) + "resources/" + resource
}
private func getResourcePathBasedOnCurrentDirectory(for resource: String, withFileManager fileManager: FileManager) -> String? {
for suffix in ["/Packages", "/.build/checkouts"] {
let packagePath = fileManager.currentDirectoryPath + suffix
do {
let packages = try fileManager.contentsOfDirectory(atPath: packagePath)
for package in packages {
let potentialResource = "\(packagePath)/\(package)/Sources/Kitura/resources/\(resource)"
let resourceExists = fileManager.fileExists(atPath: potentialResource)
if resourceExists {
return potentialResource
}
}
} catch {
Log.error("No packages found in \(packagePath)")
}
}
return nil
}
}
| apache-2.0 |
BrandonMA/SwifterUI | SwifterUI/SwifterUI/ChatKit/Model/SFUser.swift | 1 | 6116 | //
// SFChatUser.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 8/28/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
import Kingfisher
import DeepDiff
public enum SFUserNotification: String {
case deleted
}
open class SFUser: SFDataType, Codable {
public var diffId: Int {
return identifier.hashValue
}
public static func compareContent(_ a: SFUser, _ b: SFUser) -> Bool {
return a.identifier == b.identifier
}
public func hash(into hasher: inout Hasher) {
hasher.combine(identifier.hashValue)
}
public enum CodingKeys: String, CodingKey {
case identifier
case name
case lastName
case profilePictureURL
}
// MARK: - Static Methods
public static func == (lhs: SFUser, rhs: SFUser) -> Bool {
return lhs.identifier == rhs.identifier &&
lhs.name == rhs.name &&
lhs.lastName == rhs.lastName &&
lhs.profilePictureURL == rhs.profilePictureURL
}
// MARK: - Instance Properties
open var identifier: String
open var name: String
open var lastName: String
open var profilePictureURL: String?
open var contactsManager = SFDataManager<SFUser>()
open var chatsManager = SFDataManager<SFChat>()
// MARK: - Initializers
public init(identifier: String = UUID().uuidString,
name: String,
lastName: String,
profilePictureURL: String? = nil) {
self.identifier = identifier
self.name = name
self.lastName = lastName
self.profilePictureURL = profilePictureURL
}
public required init(from decoder: Decoder) throws {
let data = try decoder.container(keyedBy: CodingKeys.self)
identifier = try data.decode(String.self, forKey: CodingKeys.identifier)
name = try data.decode(String.self, forKey: CodingKeys.name)
lastName = try data.decode(String.self, forKey: CodingKeys.lastName)
profilePictureURL = try data.decode(String?.self, forKey: CodingKeys.profilePictureURL)
}
// MARK: - Instance Methods
open func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(identifier, forKey: CodingKeys.identifier)
try container.encode(name, forKey: CodingKeys.name)
try container.encode(lastName, forKey: CodingKeys.lastName)
try container.encode(profilePictureURL, forKey: CodingKeys.profilePictureURL)
}
open func addNew(chat: SFChat) {
if !chatsManager.contains(item: chat) {
var inserted = false
for (index, currentChat) in chatsManager.flatData.enumerated() where chat.modificationDate > currentChat.modificationDate {
chatsManager.insertItem(chat, at: IndexPath(item: index, section: 0))
inserted = true
break
}
if !inserted {
chatsManager.insertItem(chat)
}
}
}
open func addNew(contact: SFUser) {
if contactsManager.contains(item: contact) == false &&
contact.identifier != identifier {
if let sectionIndex = contactsManager.firstIndex(where: {
$0.identifier.contains(contact.name.uppercased().first!)
}) {
for (index, _) in contactsManager[sectionIndex].enumerated() {
contactsManager.insertItem(contact, at: IndexPath(item: index, section: sectionIndex))
break
}
contactsManager[sectionIndex].content.sortByLastname()
} else {
let newSection = SFDataSection<SFUser>(content: [contact], identifier: "\(contact.name.uppercased().first!)")
if contactsManager.isEmpty {
contactsManager.insertSection(newSection)
} else {
var inserted = false
for (index, section) in contactsManager.enumerated() where section.identifier > newSection.identifier {
contactsManager.insertSection(newSection, at: index)
inserted = true
break
}
if (!inserted) {
contactsManager.insertSection(newSection)
}
}
}
}
}
}
public extension Array where Element: SFDataSection<SFUser> {
mutating func sortByInitial() {
sort(by: { return $0.identifier < $1.identifier }) // Each identifier is a letter in the alphabet
}
mutating func sortByLastname() {
forEach { (section) in
section.content.sort(by: { return $0.lastName < $1.lastName })
}
}
}
public extension Array where Element: SFUser {
mutating func sortByInitial() {
sort(by: { return $0.identifier < $1.identifier }) // Each identifier is a letter in the alphabet
}
mutating func sortByLastname() {
sort(by: { return $0.lastName < $1.lastName })
}
func createDataSections() -> [SFDataSection<SFUser>] {
var sections: [SFDataSection<SFUser>] = []
for contact in self {
if let index = sections.firstIndex(where: {
$0.identifier.contains(contact.name.uppercased().first!)
}) {
sections[index].content.append(contact)
} else {
let section = SFDataSection<SFUser>(content: [contact], identifier: "\(contact.name.uppercased().first!)")
sections.append(section)
}
}
return sections
}
func ordered() -> [SFDataSection<SFUser>] {
var sections = createDataSections()
sections.sortByInitial()
sections.sortByLastname()
return sections
}
}
| mit |
HTWDD/htwcampus | HTWDD/Components/Exams/Models/Exam.swift | 1 | 2693 | //
// Exam.swift
// HTWDD
//
// Created by Benjamin Herzog on 05.11.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
import RxSwift
struct Exam: Codable, Identifiable, Equatable {
enum ExamType: Codable, Equatable {
case s, m, a, other(String)
init(from decoder: Decoder) throws {
let content = try decoder.singleValueContainer().decode(String.self)
switch content {
case "SP": self = .s
case "MP": self = .m
case "APL": self = .a
default: self = .other(content)
}
}
func encode(to encoder: Encoder) throws {
let c: String
switch self {
case .s: c = "SP"
case .m: c = "MP"
case .a: c = "APL"
case .other(let content): c = content
}
var container = encoder.singleValueContainer()
try container.encode(c)
}
var displayName: String {
switch self {
case .s:
return Loca.Exams.ExamType.written
case .m:
return Loca.Exams.ExamType.oral
case .a:
return Loca.Exams.ExamType.apl
case .other(let c):
return c
}
}
static func ==(lhs: ExamType, rhs: ExamType) -> Bool {
return lhs.displayName == rhs.displayName
}
}
let title: String
let type: ExamType
let branch: String
let examiner: String
let rooms: [String]
// TODO: This should be improved, just to show something
let day: String
let start: String
let end: String
private enum CodingKeys: String, CodingKey {
case title = "Title"
case type = "ExamType"
case branch = "StudyBranch"
case examiner = "Examiner"
case rooms = "Rooms"
case day = "Day"
case start = "StartTime"
case end = "EndTime"
}
static func ==(lhs: Exam, rhs: Exam) -> Bool {
return lhs.title == rhs.title && lhs.type == rhs.type && lhs.branch == rhs.branch && lhs.examiner == rhs.examiner && lhs.rooms == rhs.rooms
}
static let url = "https://www2.htw-dresden.de/~app/API/GetExams.php"
static func get(network: Network, auth: ScheduleService.Auth) -> Observable<[Exam]> {
let absc: String
switch auth.degree {
case .bachelor: absc = "B"
case .diplom: absc = "D"
case .master: absc = "M"
}
return network.getArray(url: url, params: [
"StgJhr": auth.year,
"Stg": auth.major,
"AbSc": absc,
"StgNr": auth.group
])
}
}
| mit |
hi-hu/Hu-Facebook | Hu-FacebookTests/Hu_FacebookTests.swift | 1 | 900 | //
// Hu_FacebookTests.swift
// Hu-FacebookTests
//
// Created by Hi_Hu on 2/24/15.
// Copyright (c) 2015 hi_hu. All rights reserved.
//
import UIKit
import XCTest
class Hu_FacebookTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
AndreMuis/Algorithms | OneEditAway.playground/Contents.swift | 1 | 2464 | //
// Check if one string is one edit (insertion, removal, replacement) away from another string
//
import Foundation
func oneEditAway(first first : String, second : String) -> Bool
{
var oneAway : Bool = false
if first.characters.count == second.characters.count
{
oneAway = oneReplacementAway(string1: first, string2: second)
}
else if first.characters.count == second.characters.count + 1
{
oneAway = oneInsertAway(string1: second, string2: first)
}
else if first.characters.count + 1 == second.characters.count
{
oneAway = oneInsertAway(string1: first, string2: second)
}
return oneAway
}
func oneReplacementAway(string1 string1 : String, string2 : String) -> Bool
{
var index : String.CharacterView.Index = string1.startIndex
var nonMatchingCharactersCount = 0
while index < string1.endIndex
{
if string1[index] != string2[index]
{
nonMatchingCharactersCount += 1
}
index = index.successor()
}
return nonMatchingCharactersCount == 1
}
func oneInsertAway(string1 string1 : String, string2 : String) -> Bool
{
var index1 : String.CharacterView.Index = string1.startIndex
var index2 : String.CharacterView.Index = string2.startIndex
var oneAway : Bool = false
while index1 < string1.endIndex && index2 < string2.endIndex
{
if (string1[index1] == string2[index2])
{
index1 = index1.successor()
index2 = index2.successor()
}
else
{
if (index1 == index2)
{
oneAway = true
index2 = index2.successor()
}
else
{
oneAway = false
break
}
}
}
return oneAway
}
var first : String = "cart"
var second : String = "bart"
oneEditAway(first: first, second: second)
first = "brain"
second = "bran"
oneEditAway(first: first, second: second)
first = "favor"
second = "flavor"
oneEditAway(first: first, second: second)
first = "abcdefg"
second = "abcdefg"
oneEditAway(first: first, second: second)
first = "abcdefg"
second = "abxdefx"
oneEditAway(first: first, second: second)
first = "abcdefg"
second = "abcdefgxx"
oneEditAway(first: first, second: second)
first = "abcdefg"
second = "abcde"
oneEditAway(first: first, second: second)
| mit |
jwfriese/FrequentFlyer | FrequentFlyer/Error/Error+FrequentFlyer.swift | 1 | 137 | import protocol Foundation.LocalizedError
protocol FFError: LocalizedError, CustomStringConvertible {
var details: String { get }
}
| apache-2.0 |
Julyyq/FolioReaderKit | Example/MultipleInstances-Example/StoryboardExample/BookOneExampleFolioReaderContainer.swift | 2 | 743 | //
// BookOneExampleFolioReaderContainer.swift
// StoryboardExample
//
// Created by Panajotis Maroungas on 18/08/16.
// Copyright © 2016 FolioReader. All rights reserved.
//
import UIKit
import FolioReaderKit
class BookOneExampleFolioReaderContainer: BaseExampleFolioReaderContainer {
override var exampleReaderConfig: FolioReaderConfig {
let config = FolioReaderConfig(withIdentifier: "STORYBOARD_READER_ONE")
config.scrollDirection = .horizontalWithVerticalContent
config.shouldHideNavigationOnTap = false
return config
}
override var bookTitle: String {
return "The Silver Chair"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| bsd-3-clause |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/Client/Client_Discover.swift | 1 | 6968 | //
// Client.swift
// TheMovieDbSwiftWrapper
//
// Created by George Kye on 2016-02-05.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
extension Client {
// COMBINATION OF ALL PARAMS, MOVIES & TV
static func discover(baseURL: String, params: [DiscoverParam], completion: @escaping (ClientReturn) -> Void) {
var parameters: [String: AnyObject] = [:]
for param in params {
switch param {
case .sort_by(let sort_by):
if sort_by != nil {
parameters["sort_by"] = sort_by as AnyObject?
}
case .certification_country(let certification_country):
if certification_country != nil {
parameters["certification_country"] = certification_country as AnyObject?
}
case .certification(let certification):
if certification != nil {
parameters["certification"] = certification as AnyObject?
}
case .certification_lte(let certification_lte):
if certification_lte != nil {
parameters["certification_lte"] = certification_lte as AnyObject?
}
case . include_adult(let include_adult):
if include_adult != nil {
parameters["include_adult"] = include_adult as AnyObject?
}
case .include_video(let include_video):
if include_video != nil {
parameters["include_video"] = include_video as AnyObject?
}
case .primary_release_year(let primary_release_year):
if primary_release_year != nil {
parameters["primary_release_year"] = primary_release_year as AnyObject?
}
case .primary_release_date_gte(let primary_release_date_gte):
if primary_release_date_gte != nil {
parameters["primary_release_date.gte"] = primary_release_date_gte as AnyObject?
}
case .primary_release_date_lte(let primary_release_date_lte):
if primary_release_date_lte != nil {
parameters["primary_release_date.lte"] = primary_release_date_lte as AnyObject?
}
case .release_date_gte(let release_date_gte):
if release_date_gte != nil {
parameters["release_date.gte"] = release_date_gte as AnyObject?
}
case .release_date_lte(let release_date_lte):
if release_date_lte != nil {
parameters["release_date.lte"] = release_date_lte as AnyObject?
}
case . air_date_gte(let air_date_gte):
if air_date_gte != nil {
parameters["air_date.gte"] = air_date_gte as AnyObject?
}
case .air_date_lte(let air_date_lte):
if air_date_lte != nil {
parameters["air_date.lte"] = air_date_lte as AnyObject?
}
case .first_air_date_gte(let first_air_date_gte):
if first_air_date_gte != nil {
parameters["first_air_date.gte"] = first_air_date_gte as AnyObject?
}
case .first_air_date_lte(let first_air_date_lte):
if first_air_date_lte != nil {
parameters["first_air_date.lte"] = first_air_date_lte as AnyObject?
}
case .first_air_date_year(let first_air_date_year):
if first_air_date_year != nil {
parameters["first_air_date_year"] = first_air_date_year as AnyObject?
}
case .language(let language):
if language != nil {
parameters["language"] = language as AnyObject?
}
case .page(let page):
if page != nil {
parameters["page"] = page as AnyObject?
}
case .timezone(let timezone):
if timezone != nil {
parameters["timezone"] = timezone as AnyObject?
}
case .vote_average_gte(let vote_average_gte):
if vote_average_gte != nil {
parameters["vote_average.gte"] = vote_average_gte as AnyObject?
}
case .vote_average_lte(let vote_average_lte):
if vote_average_lte != nil {
parameters["vote_average.lte"] = vote_average_lte as AnyObject?
}
case .vote_count_gte(let vote_count_gte):
if vote_count_gte != nil {
parameters["vote_count.gte"] = vote_count_gte as AnyObject?
}
case .vote_count_lte(let vote_count_lte):
if vote_count_lte != nil {
parameters["vote_count.lte"] = vote_count_lte as AnyObject?
}
case .with_genres(let with_genres):
if with_genres != nil {
parameters["with_genres"] = with_genres as AnyObject?
}
case .with_cast(let with_cast):
if with_cast != nil {
parameters["with_cast"] = with_cast as AnyObject?
}
case .with_crew(let with_crew):
if with_crew != nil {
parameters["with_crew"] = with_crew as AnyObject?
}
case .with_companies(let with_companies):
if with_companies != nil {
parameters["with_companies"] = with_companies as AnyObject?
}
case .with_keywords(let with_keywords):
if with_keywords != nil {
parameters["with_keywords"] = with_keywords as AnyObject?
}
case .with_people(let with_people):
if with_people != nil {
parameters["with_people"] = with_people as AnyObject?
}
case . with_networks(let with_networks):
if with_networks != nil {
parameters["with_networks"] = with_networks as AnyObject?
}
case .year(let year):
if year != nil {
parameters["year"] = year as AnyObject?
}
case .certification_gte(let certification_gte):
if certification_gte != nil {
parameters["certification_gte"] = certification_gte as AnyObject?
}
}
}
let url = "https://api.themoviedb.org/3/discover/" + baseURL
networkRequest(url: url, parameters: parameters) { apiReturn in
if apiReturn.error == nil {
completion(apiReturn)
}
}
}
}
| mit |
sourcebitsllc/Asset-Generator-Mac | XCAssetGenerator/ProgressViewController.swift | 1 | 2757 | //
// ProgressController.swift
// XCAssetGenerator
//
// Created by Bader on 5/18/15.
// Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved.
//
import Foundation
import Cocoa
import ReactiveCocoa
class ProgressViewController: NSViewController {
var progressView: ProgressLineView
let viewModel: ProgressIndicationViewModel
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init?(viewModel: ProgressIndicationViewModel, width: CGFloat) {
self.viewModel = viewModel
progressView = ProgressLineView(width: width)
let lineWidth = viewModel.lineWidth // TODO: right now this is ignored.
super.init(nibName: nil, bundle: nil)
view = progressView
/// RAC3
viewModel.progress
|> observeOn(QueueScheduler.mainQueueScheduler)
|> observe(next: { progress in
self.viewModel.animating.put(true)
switch progress {
case .Ongoing(let amount):
self.progressView.animateTo(progress: amount)
case .Finished:
self.resetUI()
case .Started:
self.progressView.initiateProgress()
}
})
viewModel.color.producer
|> observeOn(QueueScheduler.mainQueueScheduler)
|> start(next: { color in
self.progressView.color = color
})
}
func resetProgress(completion: () -> Void) {
NSAnimationContext.runAnimationGroup({ (context: NSAnimationContext!) -> Void in
self.progressView.forceAnimateFullProgress()
}, completionHandler: { () -> Void in
NSAnimationContext.runAnimationGroup({ (context: NSAnimationContext!) -> Void in
self.progressView.animateFadeOut()
}, completionHandler: { () -> Void in
self.progressView.resetProgress()
completion()
})
})
}
func resetUI() {
NSAnimationContext.runAnimationGroup({ (context: NSAnimationContext!) -> Void in
self.progressView.forceAnimateFullProgress()
}, completionHandler: { () -> Void in
NSAnimationContext.runAnimationGroup({ (context: NSAnimationContext!) -> Void in
self.progressView.animateFadeOut()
}, completionHandler: { () -> Void in
self.progressView.resetProgress()
self.viewModel.animating.put(false)
})
})
}
} | mit |
moqada/swift-sandbox | tutorials/FoodTracker/FoodTracker/Meal.swift | 1 | 1748 | //
// Meal.swift
// FoodTracker
//
// Created by Masahiko Okada on 2015/10/03.
//
//
import UIKit
class Meal: NSObject, NSCoding {
// MARK: Properties
var name: String
var photo: UIImage?
var rating: Int
// MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("meals")
// MARK: Types
struct PropertyKey {
static let nameKey = "name"
static let photoKey = "photo"
static let ratingKey = "rating"
}
// MARK: Initialization
init?(name: String, photo: UIImage?, rating: Int) {
self.name = name
self.photo = photo
self.rating = rating
super.init()
// Inititialization should fail if there is no name or if the rating is negative.
if name.isEmpty || rating < 0 {
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
aCoder.encodeObject(photo, forKey: PropertyKey.photoKey)
aCoder.encodeInteger(rating, forKey: PropertyKey.ratingKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String
// Because photo is an optional property of Meal, use conditional cast.
let photo = aDecoder.decodeObjectForKey(PropertyKey.photoKey) as! UIImage
let rating = aDecoder.decodeIntegerForKey(PropertyKey.ratingKey)
// Must call designated initializer.
self.init(name: name, photo: photo, rating: rating)
}
}
| mit |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Core/Managers/SiteManager.swift | 1 | 600 | import Foundation
class SiteManager {
private var site: PXSite?
private var currency: PXCurrency!
static let shared = SiteManager()
func setSite(site: PXSite) {
self.site = site
}
func getTermsAndConditionsURL() -> String {
return site?.termsAndConditionsUrl ?? ""
}
func setCurrency(currency: PXCurrency) {
self.currency = currency
}
func getCurrency() -> PXCurrency {
return currency
}
func getSiteId() -> String {
return site?.id ?? ""
}
func getSite() -> PXSite? {
return site
}
}
| mit |
Fenrikur/ef-app_ios | Eurofurence/Modules/Event Feedback/Module/EventFeedbackModuleProvidingImpl.swift | 1 | 562 | import EurofurenceModel
import UIKit.UIViewController
struct EventFeedbackModuleProvidingImpl: EventFeedbackModuleProviding {
var presenterFactory: EventFeedbackPresenterFactory
var sceneFactory: EventFeedbackSceneFactory
func makeEventFeedbackModule(for event: EventIdentifier, delegate: EventFeedbackModuleDelegate) -> UIViewController {
let scene = sceneFactory.makeEventFeedbackScene()
presenterFactory.makeEventFeedbackPresenter(for: event, scene: scene, delegate: delegate)
return scene
}
}
| mit |
trvslhlt/games-for-impact-final | projects/WinkWink_11/WinkWink/ViewControllers/SplashViewController.swift | 1 | 930 | //
// SplashViewController.swift
// WinkWink_11
//
// Created by trvslhlt on 4/10/17.
// Copyright © 2017 travis holt. All rights reserved.
//
import UIKit
class SplashViewController: AppViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(r: 183, g: 255, b: 220, a: 255)
imageView.loadGif(name: "splash_logo")
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainMenuViewController") as! MainMenuViewController
let afterWink = {
UIView.animate(withDuration: 1, animations: {
self.imageView.alpha = 0
}, completion: { _ in
self.present(vc, animated: false, completion: nil)
})
}
delay(duration: 2.5) {
afterWink()
}
}
}
| mit |
AnRanScheme/magiGlobe | magi/magiGlobe/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift | 79 | 5000 | //
// ObservableType+Extensions.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Subscribes an event handler to an observable sequence.
- parameter on: Action to invoke for each event in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(_ on: @escaping (Event<E>) -> Void)
-> Disposable {
let observer = AnonymousObserver { e in
on(e)
}
return self.subscribeSafe(observer)
}
#if DEBUG
/**
Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is canceled by disposing subscription).
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(file: String = #file, line: UInt = #line, function: String = #function, onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
-> Disposable {
let disposable: Disposable
if let disposed = onDisposed {
disposable = Disposables.create(with: disposed)
}
else {
disposable = Disposables.create()
}
#if DEBUG
let _synchronizationTracker = SynchronizationTracker()
#endif
let observer = AnonymousObserver<E> { e in
#if DEBUG
_synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { _synchronizationTracker.unregister() }
#endif
switch e {
case .next(let value):
onNext?(value)
case .error(let e):
if let onError = onError {
onError(e)
}
else {
print("Received unhandled error: \(file):\(line):\(function) -> \(e)")
}
disposable.dispose()
case .completed:
onCompleted?()
disposable.dispose()
}
}
return Disposables.create(
self.subscribeSafe(observer),
disposable
)
}
#else
/**
Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is canceled by disposing subscription).
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
-> Disposable {
let disposable: Disposable
if let disposed = onDisposed {
disposable = Disposables.create(with: disposed)
}
else {
disposable = Disposables.create()
}
let observer = AnonymousObserver<E> { e in
switch e {
case .next(let value):
onNext?(value)
case .error(let e):
onError?(e)
disposable.dispose()
case .completed:
onCompleted?()
disposable.dispose()
}
}
return Disposables.create(
self.subscribeSafe(observer),
disposable
)
}
#endif
}
extension ObservableType {
/// All internal subscribe calls go through this method.
fileprivate func subscribeSafe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
return self.asObservable().subscribe(observer)
}
}
| mit |
jlecomte/EarthquakeTracker | EarthquakeTracker/Seismometer/SeismoModel.swift | 1 | 1984 | //
// SeismoModel.swift
// EarthquakeTracker
//
// Created by Andrew Folta on 10/11/14.
// Copyright (c) 2014 Andrew Folta. All rights reserved.
//
import UIKit
import CoreMotion
let SEISMO_UPDATE_INTERVAL = 1.0 / 20.0
@objc protocol SeismoModelDelegate {
func reportMagnitude(magnitude: Double)
func reportNoAccelerometer()
}
@objc class SeismoModel {
var delegate: SeismoModelDelegate?
init() {}
// start listening for seismic activity
func start() {
var first = true
if motionManager == nil {
motionManager = CMMotionManager()
}
if !motionManager!.accelerometerAvailable {
delegate?.reportNoAccelerometer()
return
}
motionManager!.accelerometerUpdateInterval = SEISMO_UPDATE_INTERVAL
motionManager!.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: {
(data: CMAccelerometerData?, error: NSError?) -> Void in
if error != nil {
// FUTURE -- handle error
self.motionManager!.stopAccelerometerUpdates()
}
if data != nil {
var magnitude = sqrt(
(data!.acceleration.x * data!.acceleration.x) +
(data!.acceleration.y * data!.acceleration.y) +
(data!.acceleration.z * data!.acceleration.z)
)
if first {
self.lastMagnitude = magnitude
first = false
}
dispatch_async(dispatch_get_main_queue(), {
self.delegate?.reportMagnitude(magnitude - self.lastMagnitude)
self.lastMagnitude = magnitude
})
}
})
}
// stop listening for seismic activity
func stop() {
motionManager?.stopAccelerometerUpdates()
}
private var motionManager: CMMotionManager?
private var lastMagnitude = 0.0
}
| mit |
yonaskolb/SwagGen | Specs/TestSpec/generated/Swift/Sources/Requests/UpdateWithForm.swift | 1 | 3271 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
extension TestSpec {
/** Posts a form */
public enum UpdateWithForm {
public static let service = APIService<Response>(id: "updateWithForm", tag: "", method: "POST", path: "/post-form", hasBody: true, securityRequirements: [SecurityRequirement(type: "test_auth", scopes: ["read"])])
public final class Request: APIRequest<Response> {
public struct Options {
/** Updated name of the pet */
public var name: String?
/** Updated status of the pet */
public var status: String?
public init(name: String? = nil, status: String? = nil) {
self.name = name
self.status = status
}
}
public var options: Options
public init(options: Options) {
self.options = options
super.init(service: UpdateWithForm.service)
}
/// convenience initialiser so an Option doesn't have to be created
public convenience init(name: String? = nil, status: String? = nil) {
let options = Options(name: name, status: status)
self.init(options: options)
}
public override var formParameters: [String: Any] {
var params: [String: Any] = [:]
if let name = options.name {
params["name"] = name
}
if let status = options.status {
params["status"] = status
}
return params
}
}
public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
public typealias SuccessType = Void
/** Invalid input */
case status405
public var success: Void? {
switch self {
default: return nil
}
}
public var response: Any {
switch self {
default: return ()
}
}
public var statusCode: Int {
switch self {
case .status405: return 405
}
}
public var successful: Bool {
switch self {
case .status405: return false
}
}
public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws {
switch statusCode {
case 405: self = .status405
default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data)
}
}
public var description: String {
return "\(statusCode) \(successful ? "success" : "failure")"
}
public var debugDescription: String {
var string = description
let responseString = "\(response)"
if responseString != "()" {
string += "\n\(responseString)"
}
return string
}
}
}
}
| mit |
nickynick/Visuals | Visuals/Operators.swift | 1 | 319 | //
// Operators.swift
// Visuals
//
// Created by Nick Tymchenko on 06/07/14.
// Copyright (c) 2014 Nick Tymchenko. All rights reserved.
//
import Foundation
operator prefix | {}
operator prefix |- {}
operator postfix | {}
operator postfix -| {}
operator prefix == {}
operator prefix >= {}
operator prefix <= {}
| mit |
cozkurt/coframework | COFramework/COFramework/Swift/Components/Networking/Base/TestProvider.swift | 1 | 2005 | //
// TestProvider.swift
// FuzFuz
//
// Created by Cenker Ozkurt on 10/07/19.
// Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved.
//
import Foundation
/**
TestProvider class confirms ProviderProtocol
as a new networking provider for local json mocking purposes.
*/
public class TestProvider: ProviderProtocol {
var fileName: String?
// MARK: - Init Methods
public init() {}
public init(fileName: String) {
self.fileName = fileName
}
// MARK: - Public Methods
public func request(_ urlRequest: URLRequest?, success: @escaping (String) -> Void, failure: @escaping (Error) -> Void) {
self.requestFile(urlRequest, success: success, failure: failure)
}
public var description: String {
return "Test Provider"
}
// MARK: - Private Methods
fileprivate func requestFile(_ urlRequest: URLRequest?, success: @escaping (String) -> Void, failure: (Error) -> Void) {
guard let urlRequest = urlRequest, let url = urlRequest.url else {
let error = NSError(domain: "com.coframework", code: 0, userInfo: ["error": "Invalid URL"])
failure(error as Error)
return
}
let fileName = self.fileName ?? url.deletingPathExtension().lastPathComponent.lowercased()
let bundle = Bundle(for: TestProvider.self)
if let path = bundle.path(forResource: fileName, ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: Data.ReadingOptions.alwaysMapped)
if let dataString = String(data: data, encoding: String.Encoding.utf8) {
success(dataString)
} else {
print("json string is empty/no exists")
}
} catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("Invalid filename/path.")
}
}
}
| gpl-3.0 |
tiagomartinho/swift-corelibs-xctest | Sources/XCTest/Public/XCTestCase+Performance.swift | 1 | 9812 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//
// XCTestCase+Performance.swift
// Methods on XCTestCase for testing the performance of code blocks.
//
public struct XCTPerformanceMetric : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(_ lhs: XCTPerformanceMetric, _ rhs: XCTPerformanceMetric) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
public extension XCTPerformanceMetric {
/// Records wall clock time in seconds between `startMeasuring`/`stopMeasuring`.
public static let wallClockTime = XCTPerformanceMetric(rawValue: WallClockTimeMetric.name)
}
/// The following methods are called from within a test method to carry out
/// performance testing on blocks of code.
public extension XCTestCase {
/// The names of the performance metrics to measure when invoking `measure(block:)`.
/// Returns `XCTPerformanceMetric_WallClockTime` by default. Subclasses can
/// override this to change the behavior of `measure(block:)`
class var defaultPerformanceMetrics: [XCTPerformanceMetric] {
return [.wallClockTime]
}
/// Call from a test method to measure resources (`defaultPerformanceMetrics`)
/// used by the block in the current process.
///
/// func testPerformanceOfMyFunction() {
/// measure {
/// // Do that thing you want to measure.
/// MyFunction();
/// }
/// }
///
/// - Parameter block: A block whose performance to measure.
/// - Bug: The `block` param should have no external label, but there seems
/// to be a swiftc bug that causes issues when such a parameter comes
/// after a defaulted arg. See https://bugs.swift.org/browse/SR-1483 This
/// API incompatibility with Apple XCTest can be worked around in practice
/// by using trailing closure syntax when calling this method.
/// - ToDo: The `block` param should be marked @noescape once Apple XCTest
/// has been updated to do so rdar://26224596
/// - Note: Whereas Apple XCTest determines the file and line number of
/// measurements by using symbolication, this implementation opts to take
/// `file` and `line` as parameters instead. As a result, the interface to
/// these methods are not exactly identical between these environments. To
/// ensure compatibility of tests between swift-corelibs-xctest and Apple
/// XCTest, it is not recommended to pass explicit values for `file` and `line`.
func measure(file: StaticString = #file, line: Int = #line, block: () -> Void) {
measureMetrics(type(of: self).defaultPerformanceMetrics,
automaticallyStartMeasuring: true,
file: file,
line: line,
for: block)
}
/// Call from a test method to measure resources (XCTPerformanceMetrics) used
/// by the block in the current process. Each metric will be measured across
/// calls to the block. The number of times the block will be called is undefined
/// and may change in the future. For one example of why, as long as the requested
/// performance metrics do not interfere with each other the API will measure
/// all metrics across the same calls to the block. If the performance metrics
/// may interfere the API will measure them separately.
///
/// func testMyFunction2_WallClockTime() {
/// measureMetrics(type(of: self).defaultPerformanceMetrics, automaticallyStartMeasuring: false) {
///
/// // Do setup work that needs to be done for every iteration but
/// // you don't want to measure before the call to `startMeasuring()`
/// SetupSomething();
/// self.startMeasuring()
///
/// // Do that thing you want to measure.
/// MyFunction()
/// self.stopMeasuring()
///
/// // Do teardown work that needs to be done for every iteration
/// // but you don't want to measure after the call to `stopMeasuring()`
/// TeardownSomething()
/// }
/// }
///
/// Caveats:
/// * If `true` was passed for `automaticallyStartMeasuring` and `startMeasuring()`
/// is called anyway, the test will fail.
/// * If `false` was passed for `automaticallyStartMeasuring` then `startMeasuring()`
/// must be called once and only once before the end of the block or the test will fail.
/// * If `stopMeasuring()` is called multiple times during the block the test will fail.
///
/// - Parameter metrics: An array of Strings (XCTPerformanceMetrics) to measure.
/// Providing an unrecognized string is a test failure.
/// - Parameter automaticallyStartMeasuring: If `false`, `XCTestCase` will
/// not take any measurements until -startMeasuring is called.
/// - Parameter block: A block whose performance to measure.
/// - ToDo: The `block` param should be marked @noescape once Apple XCTest
/// has been updated to do so. rdar://26224596
/// - Note: Whereas Apple XCTest determines the file and line number of
/// measurements by using symbolication, this implementation opts to take
/// `file` and `line` as parameters instead. As a result, the interface to
/// these methods are not exactly identical between these environments. To
/// ensure compatibility of tests between swift-corelibs-xctest and Apple
/// XCTest, it is not recommended to pass explicit values for `file` and `line`.
func measureMetrics(_ metrics: [XCTPerformanceMetric], automaticallyStartMeasuring: Bool, file: StaticString = #file, line: Int = #line, for block: () -> Void) {
guard _performanceMeter == nil else {
return recordAPIViolation(description: "Can only record one set of metrics per test method.", file: file, line: line)
}
PerformanceMeter.measureMetrics(metrics.map({ $0.rawValue }), delegate: self, file: file, line: line) { meter in
self._performanceMeter = meter
if automaticallyStartMeasuring {
meter.startMeasuring(file: file, line: line)
}
block()
}
}
/// Call this from within a measure block to set the beginning of the critical
/// section. Measurement of metrics will start at this point.
/// - Note: Whereas Apple XCTest determines the file and line number of
/// measurements by using symbolication, this implementation opts to take
/// `file` and `line` as parameters instead. As a result, the interface to
/// these methods are not exactly identical between these environments. To
/// ensure compatibility of tests between swift-corelibs-xctest and Apple
/// XCTest, it is not recommended to pass explicit values for `file` and `line`.
func startMeasuring(file: StaticString = #file, line: Int = #line) {
guard let performanceMeter = _performanceMeter, !performanceMeter.didFinishMeasuring else {
return recordAPIViolation(description: "Cannot start measuring. startMeasuring() is only supported from a block passed to measureMetrics(...).", file: file, line: line)
}
performanceMeter.startMeasuring(file: file, line: line)
}
/// Call this from within a measure block to set the ending of the critical
/// section. Measurement of metrics will stop at this point.
/// - Note: Whereas Apple XCTest determines the file and line number of
/// measurements by using symbolication, this implementation opts to take
/// `file` and `line` as parameters instead. As a result, the interface to
/// these methods are not exactly identical between these environments. To
/// ensure compatibility of tests between swift-corelibs-xctest and Apple
/// XCTest, it is not recommended to pass explicit values for `file` and `line`.
func stopMeasuring(file: StaticString = #file, line: Int = #line) {
guard let performanceMeter = _performanceMeter, !performanceMeter.didFinishMeasuring else {
return recordAPIViolation(description: "Cannot stop measuring. stopMeasuring() is only supported from a block passed to measureMetrics(...).", file: file, line: line)
}
performanceMeter.stopMeasuring(file: file, line: line)
}
}
extension XCTestCase: PerformanceMeterDelegate {
internal func recordAPIViolation(description: String, file: StaticString, line: Int) {
recordFailure(withDescription: "API violation - \(description)",
inFile: String(describing: file),
atLine: line,
expected: false)
}
internal func recordMeasurements(results: String, file: StaticString, line: Int) {
XCTestObservationCenter.shared.testCase(self, didMeasurePerformanceResults: results, file: file, line: line)
}
internal func recordFailure(description: String, file: StaticString, line: Int) {
recordFailure(withDescription: "failed: " + description, inFile: String(describing: file), atLine: line, expected: true)
}
}
| apache-2.0 |
darioalessandro/Theater | Pods/Nimble/Sources/Nimble/Matchers/PostNotification.swift | 6 | 4168 | import Foundation
internal class NotificationCollector {
private(set) var observedNotifications: [Notification]
private let notificationCenter: NotificationCenter
private var token: NSObjectProtocol?
required init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
self.observedNotifications = []
}
func startObserving() {
// swiftlint:disable:next line_length
self.token = self.notificationCenter.addObserver(forName: nil, object: nil, queue: nil) { [weak self] notification in
// linux-swift gets confused by .append(n)
self?.observedNotifications.append(notification)
}
}
deinit {
if let token = self.token {
self.notificationCenter.removeObserver(token)
}
}
}
private let mainThread = pthread_self()
public func postNotifications(
_ predicate: Predicate<[Notification]>,
from center: NotificationCenter = .default
) -> Predicate<Any> {
_ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center)
collector.startObserving()
var once: Bool = false
return Predicate { actualExpression in
let collectorNotificationsExpression = Expression(
memoizedExpression: { _ in
return collector.observedNotifications
},
location: actualExpression.location,
withoutCaching: true
)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let actualValue: String
if collector.observedNotifications.isEmpty {
actualValue = "no notifications"
} else {
actualValue = "<\(stringify(collector.observedNotifications))>"
}
var result = try predicate.satisfies(collectorNotificationsExpression)
result.message = result.message.replacedExpectation { message in
return .expectedCustomValueTo(message.expectedMessage, actualValue)
}
return result
}
}
@available(*, deprecated, renamed: "postNotifications(_:from:)")
public func postNotifications(
_ predicate: Predicate<[Notification]>,
fromNotificationCenter center: NotificationCenter
) -> Predicate<Any> {
return postNotifications(predicate, from: center)
}
public func postNotifications<T>(
_ notificationsMatcher: T,
from center: NotificationCenter = .default
)-> Predicate<Any> where T: Matcher, T.ValueType == [Notification] {
_ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center)
collector.startObserving()
var once: Bool = false
return Predicate { actualExpression in
let collectorNotificationsExpression = Expression(memoizedExpression: { _ in
return collector.observedNotifications
}, location: actualExpression.location, withoutCaching: true)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let failureMessage = FailureMessage()
let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage)
if collector.observedNotifications.isEmpty {
failureMessage.actualValue = "no notifications"
} else {
failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>"
}
return PredicateResult(bool: match, message: failureMessage.toExpectationMessage())
}
}
@available(*, deprecated, renamed: "postNotifications(_:from:)")
public func postNotifications<T>(
_ notificationsMatcher: T,
fromNotificationCenter center: NotificationCenter
)-> Predicate<Any> where T: Matcher, T.ValueType == [Notification] {
return postNotifications(notificationsMatcher, from: center)
}
| apache-2.0 |
dreamsxin/swift | test/IRGen/objc_properties_ios.swift | 3 | 531 | // RUN: %swift -target x86_64-apple-ios9 %S/objc_properties.swift -disable-target-os-checking -emit-ir -disable-objc-attr-requires-foundation-module | FileCheck -check-prefix=CHECK -check-prefix=CHECK-NEW %S/objc_properties.swift
// RUN: %swift -target x86_64-apple-ios8 %S/objc_properties.swift -disable-target-os-checking -emit-ir -disable-objc-attr-requires-foundation-module | FileCheck -check-prefix=CHECK -check-prefix=CHECK-OLD %S/objc_properties.swift
// REQUIRES: OS=ios
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
| apache-2.0 |
0xfeedface1993/Xs8-Safari-Block-Extension-Mac | Sex8BlockExtension/CloudFetchBot/SwiftUI/Log/LogVIew.swift | 1 | 740 | //
// LogVIew.swift
// CloudFetchBot
//
// Created by god on 2019/8/6.
// Copyright © 2019 ascp. All rights reserved.
//
import SwiftUI
struct LogVIew: View {
var items : [LogItem]
var body: some View {
List {
ForEach(self.items) { i in
HStack(alignment: .top) {
Text("[\(i.date.formartYYYYMMDDHHMMSSSSS())]: ").font(.caption).foregroundColor(.gray).opacity(0.6)
Text(i.message).lineLimit(nil).font(.caption)
}.transition(.scaleAndFade)
}
}.frame(minWidth: 400)
}
}
#if DEBUG
struct LogVIew_Previews: PreviewProvider {
static var previews: some View {
LogVIew(items: logData.logs)
}
}
#endif
| apache-2.0 |
idapgroup/IDPDesign | Tests/iOS/iOSTests/Extensions/CATransform3D+Equatable.swift | 1 | 719 | //
// CATransform3D+Equatable.swift
// iOSTests
//
// Created by Oleksa 'trimm' Korin on 10/3/17.
// Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved.
//
import UIKit
extension CATransform3D: Equatable {
public static func ==(lhs: CATransform3D, rhs: CATransform3D) -> Bool {
let getters: [(CATransform3D) -> CGFloat] = [
{ $0.m11 }, { $0.m12 }, { $0.m13 }, { $0.m14 },
{ $0.m21 }, { $0.m22 }, { $0.m23 }, { $0.m24 },
{ $0.m31 }, { $0.m32 }, { $0.m33 }, { $0.m34 },
{ $0.m41 }, { $0.m42 }, { $0.m43 }, { $0.m44 }
]
return getters
.map { $0(lhs) == $0(rhs) }
.reduce(true) { $0 && $1 }
}
}
| bsd-3-clause |
heitorgcosta/Quiver | Quiver/Validating/Default Validators/ComparatorValidator.swift | 1 | 1623 | //
// ComparatorValidator.swift
// Quiver
//
// Created by Heitor Costa on 19/09/17.
// Copyright © 2017 Heitor Costa. All rights reserved.
//
class ComparatorValidator<T>: Validator where T: Comparable {
typealias ComparationOperator = (T, T) -> Bool
private var value: T
private var operation: ComparationOperator
init(value: T, operation: @escaping ComparationOperator) {
self.value = value
self.operation = operation
}
override func validate(with object: Any?) throws -> Bool {
if object == nil {
return true
}
if let value = object {
print(value)
}
guard let value = object as? T else {
throw ValidationErrorType.typeMismatch(expected: T.self, actual: type(of: object!))
}
return operation(value, self.value)
}
}
class ComparatorEnumValidator<T>: Validator where T: RawRepresentable, T.RawValue: Equatable {
typealias ComparationOperator = (T, T) -> Bool
private var value: T
private var operation: ComparationOperator
init(value: T, operation: @escaping ComparationOperator) {
self.value = value
self.operation = operation
}
override func validate(with object: Any?) throws -> Bool {
if object == nil {
return true
}
guard let value = object! as? T else {
throw ValidationErrorType.typeMismatch(expected: T.self, actual: type(of: object!))
}
return operation(value, self.value)
}
}
| mit |
emilstahl/swift | test/decl/typealias/associated_types.swift | 10 | 483 | // RUN: %target-parse-verify-swift -parse-as-library
protocol BaseProto {
typealias AssocTy
}
var a: BaseProto.AssocTy = 4 // expected-error{{cannot use associated type 'AssocTy' outside of its protocol}}
protocol DerivedProto : BaseProto {
func associated() -> AssocTy // no-warning
func existential() -> BaseProto.AssocTy // expected-error{{cannot use associated type 'AssocTy' outside of its protocol}}
}
func generic<T: BaseProto>(assoc: T.AssocTy) {} // no-warning
| apache-2.0 |
regexident/Gestalt | GestaltDemo/Themes/UIAppearance/StepperViewTheme.swift | 1 | 500 | //
// StepperViewTheme.swift
// GestaltDemo
//
// Created by Vincent Esche on 5/15/18.
// Copyright © 2018 Vincent Esche. All rights reserved.
//
import UIKit
import Gestalt
public struct StepperTheme: Theme {
let tintColor: UIColor
init(palette: Palette) {
self.tintColor = palette.colors.dynamic.tint
}
}
extension UIStepper: Themeable {
public typealias Theme = StepperTheme
public func apply(theme: Theme) {
self.tintColor = theme.tintColor
}
}
| mpl-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/26556-swift-inflightdiagnostic-fixitreplacechars.swift | 13 | 233 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
p([{n(
class
case,
| apache-2.0 |
jrendel/SwiftKeychainWrapper | SwiftKeychainWrapperTests/KeychainWrapperDeleteTests.swift | 1 | 2178 | //
// KeychainWrapperDeleteTests.swift
// SwiftKeychainWrapper
//
// Created by Jason Rendel on 3/25/16.
// Copyright © 2016 Jason Rendel. All rights reserved.
//
import XCTest
import SwiftKeychainWrapper
class KeychainWrapperDeleteTests: XCTestCase {
let testKey = "deleteTestKey"
let testString = "This is a test"
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRemoveAllKeysDeletesSpecificKey() {
// save a value we can test delete on
let stringSaved = KeychainWrapper.standard.set(testString, forKey: testKey)
XCTAssertTrue(stringSaved, "String did not save to Keychain")
// delete all
let removeSuccessful = KeychainWrapper.standard.removeAllKeys()
XCTAssertTrue(removeSuccessful, "Failed to remove all Keys")
// confirm our test value was deleted
let retrievedValue = KeychainWrapper.standard.string(forKey: testKey)
XCTAssertNil(retrievedValue, "Test value was not deleted")
}
func testWipeKeychainDeletesSpecificKey() {
// save a value we can test delete on
let stringSaved = KeychainWrapper.standard.set(testString, forKey: testKey)
XCTAssertTrue(stringSaved, "String did not save to Keychain")
// delete all
KeychainWrapper.wipeKeychain()
// confirm our test value was deleted
let retrievedValue = KeychainWrapper.standard.string(forKey: testKey)
XCTAssertNil(retrievedValue, "Test value was not deleted")
// clean up keychain
KeychainWrapper.standard.removeObject(forKey: testKey)
}
// func testRemoveAllKeysOnlyRemovesKeysForCurrentServiceName() {
//
// }
//
// func testRemoveAllKeysOnlyRemovesKeysForCurrentAccessGroup() {
//
// }
}
| mit |
KrishMunot/swift | test/SILGen/objc_properties.swift | 6 | 7813 | // RUN: %target-swift-frontend %s -emit-silgen -emit-verbose-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import | FileCheck %s
// REQUIRES: objc_interop
import Foundation
class A {
dynamic var prop: Int
dynamic var computedProp: Int {
get {
return 5
}
set {}
}
// Regular methods go through the @objc property accessors.
// CHECK-LABEL: sil hidden @_TFC15objc_properties1A6method
// CHECK: class_method {{.*}} #A.prop
func method(_ x: Int) {
prop = x
method(prop)
}
// Initializers and destructors always directly access stored properties, even
// when they are @objc.
// CHECK-LABEL: sil hidden @_TFC15objc_properties1Ac
// CHECK-NOT: class_method {{.*}} #A.prop
init() {
prop = 5
method(prop)
prop = 6
}
// rdar://15858869 - However, direct access only applies to (implicit or
// explicit) 'self' ivar references, not ALL ivar refs.
// CHECK-LABEL: sil hidden @_TFC15objc_properties1Ac
// CHECK: bb0(%0 : $A, %1 : $Int, %2 : $A):
// CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [rootself] %2 : $A
init(other : A, x : Int) {
// CHECK: [[SELF_A:%[0-9]+]] = ref_element_addr [[SELF]] : $A, #A.prop
// CHECK: assign %1 to [[SELF_A]]
prop = x
// CHECK: class_method
// CHECK: apply
other.prop = x
}
// CHECK-LABEL: sil hidden @_TFC15objc_properties1Ad : $@convention(method) (@guaranteed A) -> @owned Builtin.NativeObject {
// CHECK-NOT: class_method {{.*}} #A.prop
// CHECK: }
deinit {
prop = 7
method(prop)
}
}
// CHECK-LABEL: sil hidden @_TF15objc_properties11testPropGet
func testPropGet(_ a: A) -> Int {
// CHECK: class_method [volatile] [[OBJ:%[0-9]+]] : $A, #A.prop!getter.1.foreign : (A) -> () -> Int , $@convention(objc_method) (A) -> Int
return a.prop
}
// CHECK-LABEL: sil hidden @_TF15objc_properties11testPropSet
func testPropSet(_ a: A, i: Int) {
// CHECK: class_method [volatile] [[OBJ:%[0-9]+]] : $A, #A.prop!setter.1.foreign : (A) -> (Int) -> () , $@convention(objc_method) (Int, A) -> ()
a.prop = i
}
// CHECK-LABEL: sil hidden @_TF15objc_properties19testComputedPropGet
func testComputedPropGet(_ a: A) -> Int {
// CHECK: class_method [volatile] [[OBJ:%[0-9]+]] : $A, #A.computedProp!getter.1.foreign : (A) -> () -> Int , $@convention(objc_method) (A) -> Int
return a.computedProp
}
// CHECK-LABEL: sil hidden @_TF15objc_properties19testComputedPropSet
func testComputedPropSet(_ a: A, i: Int) {
// CHECK: class_method [volatile] [[OBJ:%[0-9]+]] : $A, #A.computedProp!setter.1.foreign : (A) -> (Int) -> () , $@convention(objc_method) (Int, A) -> ()
a.computedProp = i
}
// 'super' property references.
class B : A {
@objc override var computedProp: Int {
// CHECK-LABEL: sil hidden @_TFC15objc_properties1Bg12computedPropSi : $@convention(method) (@guaranteed B) -> Int
get {
// CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $B, #A.computedProp!getter.1.foreign : (A) -> () -> Int , $@convention(objc_method) (A) -> Int
return super.computedProp
}
// CHECK-LABEL: sil hidden @_TFC15objc_properties1Bs12computedPropSi : $@convention(method) (Int, @guaranteed B) -> ()
set(value) {
// CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $B, #A.computedProp!setter.1.foreign : (A) -> (Int) -> () , $@convention(objc_method) (Int, A) -> ()
super.computedProp = value
}
}
}
// Test the @NSCopying attribute.
class TestNSCopying {
// CHECK-LABEL: sil hidden [transparent] @_TFC15objc_properties13TestNSCopyings8propertyCSo8NSString : $@convention(method) (@owned NSString, @guaranteed TestNSCopying) -> ()
// CHECK: bb0(%0 : $NSString, %1 : $TestNSCopying):
// CHECK: class_method [volatile] %0 : $NSString, #NSString.copy!1.foreign
@NSCopying var property : NSString
@NSCopying var optionalProperty : NSString?
@NSCopying var uncheckedOptionalProperty : NSString!
@NSCopying weak var weakProperty : NSString? = nil
// @NSCopying unowned var unownedProperty : NSString? = nil
init(s : NSString) { property = s }
}
// <rdar://problem/16663515> IBOutlet not adjusting getter/setter when making a property implicit unchecked optional
@objc
class TestComputedOutlet : NSObject {
var _disclosedView : TestComputedOutlet! = .none
@IBOutlet var disclosedView : TestComputedOutlet! {
get { return _disclosedView }
set { _disclosedView = newValue }
}
func foo() {
_disclosedView != nil ? () : self.disclosedView.foo()
}
}
class Singleton : NSObject {
// CHECK-DAG: sil hidden [transparent] @_TZFC15objc_properties9Singletong14sharedInstanceS0_ : $@convention(method) (@thick Singleton.Type) -> @owned Singleton
// CHECK-DAG: sil hidden [transparent] [thunk] @_TToZFC15objc_properties9Singletong14sharedInstanceS0_ : $@convention(objc_method) (@objc_metatype Singleton.Type) -> @autoreleased Singleton {
static let sharedInstance = Singleton()
// CHECK-DAG: sil hidden [transparent] @_TZFC15objc_properties9Singletong1iSi : $@convention(method) (@thick Singleton.Type) -> Int
// CHECK-DAG: sil hidden [transparent] [thunk] @_TToZFC15objc_properties9Singletong1iSi : $@convention(objc_method) (@objc_metatype Singleton.Type) -> Int
static let i = 2
// CHECK-DAG: sil hidden [transparent] @_TZFC15objc_properties9Singletong1jSS : $@convention(method) (@thick Singleton.Type) -> @owned String
// CHECK-DAG: sil hidden [transparent] [thunk] @_TToZFC15objc_properties9Singletong1jSS : $@convention(objc_method) (@objc_metatype Singleton.Type) -> @autoreleased NSString
// CHECK-DAG: sil hidden [transparent] @_TZFC15objc_properties9Singletons1jSS : $@convention(method) (@owned String, @thick Singleton.Type) -> ()
// CHECK-DAG: sil hidden [transparent] [thunk] @_TToZFC15objc_properties9Singletons1jSS : $@convention(objc_method) (NSString, @objc_metatype Singleton.Type) -> ()
static var j = "Hello"
// CHECK-DAG: sil hidden [thunk] @_TToZFC15objc_properties9Singletong1kSd : $@convention(objc_method) (@objc_metatype Singleton.Type) -> Double
// CHECK-DAG: sil hidden @_TZFC15objc_properties9Singletong1kSd : $@convention(method) (@thick Singleton.Type) -> Double
static var k: Double {
return 7.7
}
}
class HasUnmanaged : NSObject {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC15objc_properties12HasUnmanagedg3refGSqGVs9UnmanagedPs9AnyObject___
// CHECK: [[NATIVE:%.+]] = function_ref @_TFC15objc_properties12HasUnmanagedg3refGSqGVs9UnmanagedPs9AnyObject___
// CHECK: [[RESULT:%.+]] = apply [[NATIVE]](%0)
// CHECK-NOT: {{(retain|release)}}
// CHECK: strong_release %0 : $HasUnmanaged
// CHECK-NOT: {{(retain|release)}}
// CHECK: return [[RESULT]] : $Optional<Unmanaged<AnyObject>>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC15objc_properties12HasUnmanageds3refGSqGVs9UnmanagedPs9AnyObject___
// CHECK-NOT: {{(retain|release)}}
// CHECK: strong_retain %1 : $HasUnmanaged
// CHECK-NOT: {{(retain|release)}}
// CHECK: [[NATIVE:%.+]] = function_ref @_TFC15objc_properties12HasUnmanageds3refGSqGVs9UnmanagedPs9AnyObject___
// CHECK-NOT: {{(retain|release)}}
// CHECK: apply [[NATIVE]](%0, %1)
// CHECK-NOT: {{(retain|release)}}
// CHECK: strong_release %1 : $HasUnmanaged
// CHECK-NOT: {{(retain|release)}}
// CHECK: return
var ref: Unmanaged<AnyObject>?
}
// <rdar://problem/21544588> crash when overriding non-@objc property with @objc property.
class NonObjCBaseClass : NSObject {
@nonobjc var property: Int {
get { return 0 }
set {}
}
}
@objc class ObjCSubclass : NonObjCBaseClass {
@objc override var property: Int {
get { return 1 }
set {}
}
}
// CHECK-LABEL: sil hidden [thunk] @_TToFC15objc_properties12ObjCSubclassg8propertySi
// CHECK-LABEL: sil hidden [thunk] @_TToFC15objc_properties12ObjCSubclasss8propertySi
| apache-2.0 |
threemonkee/VCLabs | VCLabs/NavMenuVC.swift | 1 | 3436 | //
// NavMenuVC.swift
// VCLabs
//
// Created by Victor Chandra on 2/01/2016.
// Copyright © 2016 Victor. All rights reserved.
//
import UIKit
import RESideMenu
class NavMenuVC: UITableViewController, NavContentDelegate
{
let arrayMenu = [
"Navigation Bar",
"Tab Bar",
"Side Menu"
]
override func viewDidLoad() {
super.viewDidLoad()
}
// 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 arrayMenu.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = arrayMenu[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
switch arrayMenu[indexPath.row]
{
case "Navigation Bar":
openNavigationBar()
case "Tab Bar":
openTabBar()
case "Side Menu":
openSideMenu()
default:
break;
}
}
// MARK: -
func navContentClose(content: NavContentVC?, message: String?)
{
dismissViewControllerAnimated(true, completion: nil)
}
func openNavigationBar ()
{
let navContent = NavContentVC()
navContent.navigationItem.title = "Navigation Bar"
navContent.label.text = "This is Navigation Bar mechanism provided by Apple's UIKit"
navContent.delegate = self
let navMenuController = UINavigationController(rootViewController: navContent)
presentViewController(navMenuController, animated: true, completion: nil)
}
func openTabBar ()
{
let navContentLeft = NavContentVC()
navContentLeft.label.text = "Left Tab Bar. This is Tab Bar mechanism provided by Apple's UIKit"
navContentLeft.tabBarItem = UITabBarItem(tabBarSystemItem: .Favorites, tag: 0)
navContentLeft.delegate = self
let navContentRight = NavContentVC()
navContentRight.label.text = "Right Tab Bar. This is Tab Bar mechanism provided by Apple's UIKit"
navContentRight.tabBarItem = UITabBarItem(tabBarSystemItem: .Bookmarks, tag: 1)
navContentRight.delegate = self
let navMenuController = UITabBarController()
navMenuController.viewControllers = [navContentLeft, navContentRight]
presentViewController(navMenuController, animated: true, completion: nil)
}
func openSideMenu ()
{
let contentVC = SideMenuFirstVC()
let navCon = UINavigationController(rootViewController: contentVC)
let leftVC = SideMenuLeftVC()
let rightVC = SideMenuRightVC()
let reSideMenu = RESideMenu.init(contentViewController: navCon, leftMenuViewController: leftVC, rightMenuViewController: rightVC)
reSideMenu.backgroundImage = UIImage(named: "Stars")
presentViewController(reSideMenu, animated: true, completion: nil)
}
}
| gpl-2.0 |
kfix/MacPin | Sources/MacPin/WebViewController.swift | 1 | 2713 | /// MacPin WebViewController
///
/// Interlocute WebViews to general app UI
import WebKit
import WebKitPrivates
import JavaScriptCore
// https://github.com/apple/swift-evolution/blob/master/proposals/0160-objc-inference.md#re-enabling-objc-inference-within-a-class-hierarchy
@objcMembers
class WebViewController: ViewController { //, WebViewControllerScriptExports {
@objc unowned var webview: MPWebView
#if os(OSX)
override func loadView() { view = NSView() } // NIBless
#endif
let browsingReactor = AppScriptRuntime.shared
// ^ this is a simple object that can re-broadcast events from the webview and return with confirmation that those events were "handled" or not.
// this lets the controller know whether it should perform "reasonable browser-like actions" or to defer to the Reactor's business logic.
required init?(coder: NSCoder) { self.webview = MPWebView(); super.init(coder: coder); } // required by NSCoding protocol
#if os(OSX)
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { self.webview = MPWebView(); super.init(nibName:nil, bundle:nil) } //calls loadView
#endif
required init(webview: MPWebView) {
self.webview = webview
super.init(nibName: nil, bundle: nil)
webview.navigationDelegate = self // allows/denies navigation actions: see WebViewDelegates
webview._inputDelegate = self
webview._findDelegate = self
if WebKit_version >= (603, 1, 17) {
// STP 57, Safari 12
webview._iconLoadingDelegate = self
}
//webview._historyDelegate = self
#if DEBUG
//webview._diagnosticLoggingDelegate = self
#endif
webview.configuration.processPool._downloadDelegate = self
webview.configuration.processPool._setCanHandleHTTPSServerTrustEvaluation(true)
WebViewUICallbacks.subscribe(webview)
#if os(OSX)
representedObject = webview // OSX omnibox/browser uses KVC to interrogate webview
view.addSubview(webview, positioned: .below, relativeTo: nil)
// must retain the empty parent view for the inspector to co-attach to alongside the webview
#elseif os(iOS)
view = webview
#endif
}
override func viewDidLoad() {
super.viewDidLoad()
}
@objc func askToOpenCurrentURL() { askToOpenURL(webview.url as URL?) }
// sugar for delgates' opening a new tab in parent browser VC
func popup(_ webview: MPWebView) -> WebViewController {
let wvc = type(of: self).init(webview: webview)
parent?.addChild(wvc)
return wvc
}
@objc dynamic func focus() { warn("method not implemented by \(type(of: self))!") }
@objc dynamic func dismiss() { warn("method not implemented by \(type(of: self))!") }
@objc dynamic func close() { warn("method not implemented by \(type(of: self))!") }
deinit {
warn(description)
}
}
| gpl-3.0 |
divljiboy/IOSChatApp | Quick-Chat/Pods/BulletinBoard/Sources/Support/BulletinViewController.swift | 1 | 20098 | /**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* A view controller that displays a card at the bottom of the screen.
*/
final class BulletinViewController: UIViewController, UIGestureRecognizerDelegate {
/// The object managing the view controller.
weak var manager: BLTNItemManager?
// MARK: - UI Elements
/// The subview that contains the contents of the card.
let contentView = RoundedView()
/// The button that allows the users to close the bulletin.
let closeButton = BulletinCloseButton()
/**
* The stack view displaying the content of the card.
*
* - warning: You should not customize the distribution, axis and alignment of the stack, as this
* may break the layout of the card.
*/
let contentStackView = UIStackView()
/// The view covering the content. Generated in `loadBackgroundView`.
var backgroundView: BulletinBackgroundView!
/// The activity indicator.
let activityIndicator = ActivityIndicator()
// MARK: - Dismissal Support Properties
/// Indicates whether the bulletin can be dismissed by a tap outside the card.
var isDismissable: Bool = false
/// The snapshot view of the content used during dismissal.
var activeSnapshotView: UIView?
/// The active swipe interaction controller.
var swipeInteractionController: BulletinSwipeInteractionController!
// MARK: - Private Interface Elements
// Compact constraints
fileprivate var leadingConstraint: NSLayoutConstraint!
fileprivate var trailingConstraint: NSLayoutConstraint!
fileprivate var centerXConstraint: NSLayoutConstraint!
fileprivate var maxWidthConstraint: NSLayoutConstraint!
// Regular constraints
fileprivate var widthConstraint: NSLayoutConstraint!
fileprivate var centerYConstraint: NSLayoutConstraint!
// Stack view constraints
fileprivate var stackLeadingConstraint: NSLayoutConstraint!
fileprivate var stackTrailingConstraint: NSLayoutConstraint!
fileprivate var stackBottomConstraint: NSLayoutConstraint!
// Position constraints
fileprivate var minYConstraint: NSLayoutConstraint!
fileprivate var contentTopConstraint: NSLayoutConstraint!
fileprivate var contentBottomConstraint: NSLayoutConstraint!
// MARK: - Deinit
deinit {
cleanUpKeyboardLogic()
}
}
// MARK: - Lifecycle
extension BulletinViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setUpLayout(with: traitCollection)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
/// Animate status bar appearance when hiding
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
self.setNeedsStatusBarAppearanceUpdate()
})
}
override func loadView() {
super.loadView()
view.backgroundColor = .clear
let recognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
recognizer.delegate = self
recognizer.cancelsTouchesInView = false
recognizer.delaysTouchesEnded = false
view.addGestureRecognizer(recognizer)
contentView.accessibilityViewIsModal = true
contentView.translatesAutoresizingMaskIntoConstraints = false
contentStackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(contentView)
// Content View
centerXConstraint = contentView.centerXAnchor.constraint(equalTo: view.safeCenterXAnchor)
centerYConstraint = contentView.centerYAnchor.constraint(equalTo: view.safeCenterYAnchor)
centerYConstraint.constant = 2500
widthConstraint = contentView.widthAnchor.constraint(equalToConstant: 444)
widthConstraint.priority = UILayoutPriorityRequired
// Close button
contentView.addSubview(closeButton)
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12).isActive = true
closeButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -12).isActive = true
closeButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
closeButton.widthAnchor.constraint(equalToConstant: 44).isActive = true
closeButton.isUserInteractionEnabled = true
closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
// Content Stack View
contentView.addSubview(contentStackView)
stackLeadingConstraint = contentStackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
stackLeadingConstraint.isActive = true
stackTrailingConstraint = contentStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
stackTrailingConstraint.isActive = true
minYConstraint = contentView.topAnchor.constraint(greaterThanOrEqualTo: view.safeTopAnchor)
minYConstraint.isActive = true
minYConstraint.priority = UILayoutPriorityRequired
contentStackView.axis = .vertical
contentStackView.alignment = .fill
contentStackView.distribution = .fill
// Activity Indicator
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(activityIndicator)
activityIndicator.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
activityIndicator.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
activityIndicator.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
activityIndicator.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
activityIndicator.activityIndicatorViewStyle = .whiteLarge
activityIndicator.color = .black
activityIndicator.isUserInteractionEnabled = false
activityIndicator.alpha = 0
// Vertical Position
stackBottomConstraint = contentStackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
contentTopConstraint = contentView.topAnchor.constraint(equalTo: contentStackView.topAnchor)
stackBottomConstraint.isActive = true
contentTopConstraint.isActive = true
// Configuration
configureContentView()
setUpKeyboardLogic()
contentView.bringSubview(toFront: closeButton)
}
@available(iOS 11.0, *)
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
updateCornerRadius()
setUpLayout(with: traitCollection)
}
/// Configure content view with customizations.
fileprivate func configureContentView() {
guard let manager = self.manager else {
fatalError("Trying to set up the content view, but the BulletinViewController is not managed.")
}
contentView.backgroundColor = manager.backgroundColor
contentView.cornerRadius = CGFloat((manager.cardCornerRadius ?? 12).doubleValue)
closeButton.updateColors(isDarkBackground: manager.backgroundColor.needsDarkText == false)
let cardPadding = manager.edgeSpacing.rawValue
// Set left and right padding
leadingConstraint = contentView.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor,
constant: cardPadding)
trailingConstraint = contentView.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor,
constant: -cardPadding)
// Set maximum width with padding
maxWidthConstraint = contentView.widthAnchor.constraint(lessThanOrEqualTo: view.safeWidthAnchor,
constant: -(cardPadding * 2))
maxWidthConstraint.priority = UILayoutPriorityRequired
maxWidthConstraint.isActive = true
if manager.hidesHomeIndicator {
contentBottomConstraint = contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
} else {
contentBottomConstraint = contentView.bottomAnchor.constraint(equalTo: view.safeBottomAnchor)
}
contentBottomConstraint.constant = 1000
contentBottomConstraint.isActive = true
}
// MARK: - Gesture Recognizer
internal func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view?.isDescendant(of: contentView) == true {
return false
}
return true
}
}
// MARK: - Layout
extension BulletinViewController {
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { _ in
self.setUpLayout(with: newCollection)
})
}
fileprivate func setUpLayout(with traitCollection: UITraitCollection) {
switch traitCollection.horizontalSizeClass {
case .regular:
leadingConstraint.isActive = false
trailingConstraint.isActive = false
contentBottomConstraint.isActive = false
centerXConstraint.isActive = true
centerYConstraint.isActive = true
widthConstraint.isActive = true
case .compact:
leadingConstraint.isActive = true
trailingConstraint.isActive = true
contentBottomConstraint.isActive = true
centerXConstraint.isActive = false
centerYConstraint.isActive = false
widthConstraint.isActive = false
default:
break
}
switch (traitCollection.verticalSizeClass, traitCollection.horizontalSizeClass) {
case (.regular, .regular):
stackLeadingConstraint.constant = 32
stackTrailingConstraint.constant = -32
stackBottomConstraint.constant = -32
contentTopConstraint.constant = -32
contentStackView.spacing = 32
default:
stackLeadingConstraint.constant = 24
stackTrailingConstraint.constant = -24
stackBottomConstraint.constant = -24
contentTopConstraint.constant = -24
contentStackView.spacing = 24
}
}
// MARK: - Transition Adaptivity
var defaultBottomMargin: CGFloat {
return manager?.edgeSpacing.rawValue ?? 12
}
func bottomMargin() -> CGFloat {
if #available(iOS 11, *) {
if view.safeAreaInsets.bottom > 0 {
return 0
}
}
var bottomMargin: CGFloat = manager?.edgeSpacing.rawValue ?? 12
if manager?.hidesHomeIndicator == true {
bottomMargin = manager?.edgeSpacing.rawValue == 0 ? 0 : 6
}
return bottomMargin
}
/// Moves the content view to its final location on the screen. Use during presentation.
func moveIntoPlace() {
contentBottomConstraint.constant = -bottomMargin()
centerYConstraint.constant = 0
view.layoutIfNeeded()
contentView.layoutIfNeeded()
backgroundView.layoutIfNeeded()
}
// MARK: - Presentation/Dismissal
/// Dismisses the presnted BulletinViewController if `isDissmisable` is set to `true`.
@discardableResult
func dismissIfPossible() -> Bool {
guard isDismissable else {
return false
}
manager?.dismissBulletin(animated: true)
return true
}
// MARK: - Touch Events
@objc fileprivate func handleTap(recognizer: UITapGestureRecognizer) {
dismissIfPossible()
}
// MARK: - Accessibility
override func accessibilityPerformEscape() -> Bool {
return dismissIfPossible()
}
}
// MARK: - System Elements
extension BulletinViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
if let manager = manager {
switch manager.statusBarAppearance {
case .lightContent:
return .lightContent
case .automatic:
return manager.backgroundViewStyle.rawValue.isDark ? .lightContent : .default
default:
break
}
}
return .default
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return manager?.statusBarAnimation ?? .fade
}
override var prefersStatusBarHidden: Bool {
return manager?.statusBarAppearance == .hidden
}
@available(iOS 11.0, *)
override func prefersHomeIndicatorAutoHidden() -> Bool {
return manager?.hidesHomeIndicator ?? false
}
}
// MARK: - Safe Area
extension BulletinViewController {
@available(iOS 11.0, *)
fileprivate var screenHasRoundedCorners: Bool {
return view.safeAreaInsets.bottom > 0
}
fileprivate func updateCornerRadius() {
if manager?.edgeSpacing.rawValue == 0 {
contentView.cornerRadius = 0
return
}
var defaultRadius: NSNumber = 12
if #available(iOS 11.0, *) {
defaultRadius = screenHasRoundedCorners ? 36 : 12
}
contentView.cornerRadius = CGFloat((manager?.cardCornerRadius ?? defaultRadius).doubleValue)
}
}
// MARK: - Background
extension BulletinViewController {
/// Creates a new background view for the bulletin.
func loadBackgroundView() {
backgroundView = BulletinBackgroundView(style: manager?.backgroundViewStyle ?? .dimmed)
}
}
// MARK: - Activity Indicator
extension BulletinViewController {
/// Displays the activity indicator.
func displayActivityIndicator(color: UIColor) {
activityIndicator.color = color
activityIndicator.startAnimating()
let animations = {
self.activityIndicator.alpha = 1
self.contentStackView.alpha = 0
self.closeButton.alpha = 0
}
UIView.animate(withDuration: 0.25, animations: animations) { _ in
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, self.activityIndicator)
}
}
/// Hides the activity indicator.
func hideActivityIndicator() {
activityIndicator.stopAnimating()
activityIndicator.alpha = 0
let needsCloseButton = manager?.needsCloseButton == true
let animations = {
self.activityIndicator.alpha = 0
self.updateCloseButton(isRequired: needsCloseButton)
}
UIView.animate(withDuration: 0.25, animations: animations)
}
}
// MARK: - Close Button
extension BulletinViewController {
func updateCloseButton(isRequired: Bool) {
isRequired ? showCloseButton() : hideCloseButton()
}
func showCloseButton() {
closeButton.alpha = 1
}
func hideCloseButton() {
closeButton.alpha = 0
}
@objc func closeButtonTapped() {
manager?.dismissBulletin(animated: true)
}
}
// MARK: - Transitions
extension BulletinViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return BulletinPresentationAnimationController(style: manager?.backgroundViewStyle ?? .dimmed)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return BulletinDismissAnimationController()
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning)
-> UIViewControllerInteractiveTransitioning? {
guard manager?.allowsSwipeInteraction == true else {
return nil
}
let isEligible = swipeInteractionController.isInteractionInProgress
return isEligible ? swipeInteractionController : nil
}
/// Creates a new view swipe interaction controller and wires it to the content view.
func refreshSwipeInteractionController() {
guard manager?.allowsSwipeInteraction == true else {
return
}
swipeInteractionController = BulletinSwipeInteractionController()
swipeInteractionController.wire(to: self)
}
/// Prepares the view controller for dismissal.
func prepareForDismissal(displaying snapshot: UIView) {
activeSnapshotView = snapshot
}
}
// MARK: - Keyboard
extension BulletinViewController {
func setUpKeyboardLogic() {
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardHide), name: .UIKeyboardWillHide, object: nil)
}
func cleanUpKeyboardLogic() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
@objc func onKeyboardShow(_ notification: Notification) {
guard manager?.currentItem.shouldRespondToKeyboardChanges == true else {
return
}
guard let userInfo = notification.userInfo,
let keyboardFrameFinal = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
let curveInt = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? Int
else {
return
}
let animationCurve = UIViewAnimationCurve(rawValue: curveInt) ?? .linear
let animationOptions = UIViewAnimationOptions(curve: animationCurve)
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: {
var bottomSpacing = -(keyboardFrameFinal.size.height + self.defaultBottomMargin)
if #available(iOS 11.0, *) {
if self.manager?.hidesHomeIndicator == false {
bottomSpacing += self.view.safeAreaInsets.bottom
}
}
self.minYConstraint.isActive = false
self.contentBottomConstraint.constant = bottomSpacing
self.centerYConstraint.constant = -(keyboardFrameFinal.size.height + 12) / 2
self.contentView.superview?.layoutIfNeeded()
}, completion: nil)
}
@objc func onKeyboardHide(_ notification: Notification) {
guard manager?.currentItem.shouldRespondToKeyboardChanges == true else {
return
}
guard let userInfo = notification.userInfo,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
let curveInt = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? Int
else {
return
}
let animationCurve = UIViewAnimationCurve(rawValue: curveInt) ?? .linear
let animationOptions = UIViewAnimationOptions(curve: animationCurve)
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: {
self.minYConstraint.isActive = true
self.contentBottomConstraint.constant = -self.bottomMargin()
self.centerYConstraint.constant = 0
self.contentView.superview?.layoutIfNeeded()
}, completion: nil)
}
}
extension UIViewAnimationOptions {
init(curve: UIViewAnimationCurve) {
self = UIViewAnimationOptions(rawValue: UInt(curve.rawValue << 16))
}
}
// MARK: - Swift Compatibility
#if swift(>=4.0)
let UILayoutPriorityRequired = UILayoutPriority.required
let UILayoutPriorityDefaultHigh = UILayoutPriority.defaultHigh
let UILayoutPriorityDefaultLow = UILayoutPriority.defaultLow
#endif
| mit |
oneSwiftSprite/Swiftris | Swiftris/Switftris.swift | 1 | 7967 | //
// Switftris.swift
// Swiftris
//
// Created by Adriana Gustavson on 1/21/15.
// Copyright (c) 2015 Adriana Gustavson. All rights reserved.
//
// #1
let NumColumns = 10
let NumRows = 20
let StartingColumn = 4
let StartingRow = 0
let PreviewColumn = 12
let PreviewRow = 1
let PointsPerLine = 10
let LevelThreshold = 1000
protocol SwiftrisDelegate {
// invoked when the cirrent round of Swiftris ends
func gameDidEnd(swiftris: Swiftris)
// invoked immeditely after a new game has begun
func gameDidBegin(swiftris: Swiftris)
// invoked when the falling shape has become part of the game board
func gameShapeDidLand(swiftris: Swiftris)
// invoked when the falling shape has changed its location
func gameShapeDidMove(swiftris: Swiftris)
// invoked when the galling shape has changed its location after being dropped
func gameShapeDidDrop(swiftris: Swiftris)
// invoked when the game has reached a new level
func gameDidLevelUp(swiftris: Swiftris)
}
class Swiftris {
var blockArray: Array2D<Block>
var nextShape: Shape?
var fallingShape: Shape?
var delegate:SwiftrisDelegate?
var score: Int
var level: Int
init() {
score = 0
level = 1
fallingShape = nil
nextShape = nil
blockArray = Array2D<Block>(columns: NumColumns, rows: NumRows)
}
func beginGame() {
if (nextShape == nil) {
nextShape = Shape.random(PreviewColumn, startingRow: PreviewRow)
}
delegate?.gameDidBegin(self)
}
// #2
func newShape() -> (fallingShape: Shape?, nextShape: Shape?) {
fallingShape = nextShape
nextShape = Shape.random(PreviewColumn, startingRow: PreviewRow)
fallingShape?.moveTo(StartingColumn, row: StartingRow)
// #1 (playing by the rules)
if detectIllegalPlacement() {
nextShape = fallingShape
nextShape!.moveTo(PreviewColumn, row: PreviewRow)
endGame()
return (nil, nil)
}
return (fallingShape, nextShape)
}
// #2 (playing by the rulles)
func detectIllegalPlacement() -> Bool {
if let shape = fallingShape {
for block in shape.blocks {
if block.column < 0 || block.column >= NumColumns
|| block.row < 0 || block.row >= NumRows {
return true
} else if blockArray[block.column, block.row] != nil {
return true
}
}
}
return false
}
// #1 (1.3 playing by the rules)
func settleShape() {
if let shape = fallingShape {
for block in shape.blocks {
blockArray[block.column, block.row] = block
}
fallingShape = nil
delegate?.gameShapeDidLand(self)
}
}
// #2 (2.3 playing by the rules)
func detectTouch() -> Bool {
if let shape = fallingShape {
for bottomBlock in shape.bottomBlocks {
if bottomBlock.row == NumRows - 1 ||
blockArray[bottomBlock.column, bottomBlock.row + 1] != nil {
return true
}
}
}
return false
}
func endGame() {
score = 0
level = 1
delegate?.gameDidEnd(self)
}
// #1 (1.4 playing by the rules)
func removeCompletedLines() -> (linesRemoved: Array<Array<Block>>, fallenBlocks: Array<Array<Block>>) {
var removedLines = Array<Array<Block>>()
for var row = NumRows - 1; row > 0; row-- {
var rowOfBlocks = Array<Block>()
//#2 (2.4 playing by the rules)
for column in 0..<NumColumns {
if let block = blockArray[column, row] {
rowOfBlocks.append(block)
}
}
if rowOfBlocks.count == NumColumns {
removedLines.append(rowOfBlocks)
for block in rowOfBlocks {
blockArray[block.column, block.row] = nil
}
}
}
// #3 (3.4 playing by the rules)
if removedLines.count == 0 {
return ([], [])
}
let pointsEarned = removedLines.count * PointsPerLine * level
score += pointsEarned
if score >= level * LevelThreshold {
level += 1
delegate?.gameDidLevelUp(self)
}
var fallenBlocks = Array<Array<Block>>()
for column in 0..<NumColumns {
var fallenBlocksArray = Array<Block>()
// #5 (5.4 playing by the rules)
for var row = removedLines[0][0].row - 1; row > 0; row-- {
if let block = blockArray[column, row] {
var newRow = row
while (newRow < NumRows - 1 && blockArray[column, newRow + 1] == nil) {
newRow++
}
block.row = newRow
blockArray[column, row] = nil
blockArray[column, newRow] = block
fallenBlocksArray.append(block)
}
}
if fallenBlocksArray.count > 0 {
fallenBlocks.append(fallenBlocksArray)
}
}
return (removedLines, fallenBlocks)
}
func removeAllBlocks() -> Array<Array<Block>> {
var allBlocks = Array<Array<Block>>()
for row in 0..<NumRows {
var rowOfBlocks = Array<Block>()
for column in 0..<NumColumns {
if let block = blockArray[column, row] {
rowOfBlocks.append(block)
blockArray[column, row] = nil
}
}
allBlocks.append(rowOfBlocks)
}
return allBlocks
}
// #1 (#1.2 playing by the rules)
func dropShape() {
if let shape = fallingShape {
while detectIllegalPlacement() == false {
shape.lowerShapeByOneRow()
}
shape.raiseShapeByOneRow()
delegate?.gameShapeDidDrop(self)
}
}
// #2 (#2.2 playing by the rules)
func letShapeFall() {
if let shape = fallingShape {
shape.lowerShapeByOneRow()
if detectIllegalPlacement() {
shape.raiseShapeByOneRow()
if detectIllegalPlacement() {
endGame()
} else {
settleShape()
}
} else {
delegate?.gameShapeDidMove(self)
if detectTouch() {
settleShape()
}
}
}
}
// #3 (3.2 playing by the rules)
func rotateShape() {
if let shape = fallingShape {
shape.rotateClockwise()
if detectIllegalPlacement() {
shape.rotateCounterClockwise()
} else {
delegate?.gameShapeDidMove(self)
}
}
}
// #4 (4.2 playing by the rules)
func moveShapeLeft() {
if let shape = fallingShape {
shape.shiftLeftByOneColumn()
if detectIllegalPlacement() {
shape.shiftRightByOneColumn()
return
}
delegate?.gameShapeDidMove(self)
}
}
func moveShapeRight() {
if let shape = fallingShape {
shape.shiftRightByOneColumn()
if detectIllegalPlacement() {
shape.shiftLeftByOneColumn()
return
}
delegate?.gameShapeDidMove(self)
}
}
// end Swiftris class
}
| mit |
citypay/apple-pay-sdk | CityPayKit/CityPayResponse.swift | 1 | 6879 | //
// CPResponse.swift
// CityPayKit
//
// Created by Gary Feltham on 27/08/2015.
// Copyright (c) 2015 CityPay Limited. All rights reserved.
//
import UIKit
import CommonCrypto
/**
The CPResponse models the response object from the gateway for generic processing
using the **CityPay HTTP PayPOST API**.
To determine if a transaction has been accepted review the *authorised* parameter and ensure you know if you are in *test* mode or *live*
Initialisation of a CPResponse instance is provided by the API as a JSON packet which can be reinstated
using standard JSON serialization methods and
let jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error:&parseError)
if let json = jsonObject as? NSDictionary {
let response = CPResponse(json)
} else {
// error checking code.
}
*/
public class CityPayResponse: NSObject {
public let amount: Int
public let currency: String
public let authcode: String?
public let authorised: Bool
public let AvsResponse: String?
public let CscResponse: String?
public let errorcode: String
public let errormsg: String
public let expMonth: Int
public let expYear: Int
public let identifier: String
public let maskedPan: String
public let merchantId: Int
public let mode: String
public let result: Int
public let sha256: String
public let status: String
public let title: String?
public let firstname:String?
public let lastname:String?
public let email: String?
public let postcode: String?
public let transno: Int
private func b64_sha256(data : NSData) -> String {
var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA256(data.bytes, CC_LONG(data.length), &hash)
let res = NSData(bytes: hash, length: Int(CC_SHA256_DIGEST_LENGTH))
return res.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
}
func log() -> String {
return "RS:\(identifier),amount=\(amount),card=\(maskedPan),\(expMonth)\(expYear),authorised=\(authorised),mode=\(mode)"
}
/// Determines if the data provided is valid based on the sha256 value. The licence key provides a salt
/// into the hash function
public func isValid(licenceKey: String) -> Bool {
var str = authcode ?? ""
str += toString(amount) +
errorcode +
toString(merchantId) +
toString(transno) +
identifier +
licenceKey
if let data = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
let b64 = b64_sha256(data)
return b64 == sha256
}
return false
}
// Creates a rejected CPResponse from this response. This allows the object cycle to be rejected
// by workflow such as an invalid digest information.
func rejectAuth(licenceKey: String, errormsg: String) -> CityPayResponse {
NSLog("Rejecting auth \(errormsg)")
// recreate digest
let ec = "099"
var str = authcode ?? ""
str += toString(amount) +
ec +
toString(merchantId) +
toString(transno) +
identifier +
licenceKey
let data = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
let digest = b64_sha256(data)
return CityPayResponse(
amount:amount, currency:currency, authcode:authcode, authorised:false,
AvsResponse:AvsResponse, CscResponse:CscResponse, errorcode:ec, errormsg:errormsg,
expMonth:expMonth, expYear:expYear, identifier:identifier, maskedPan:maskedPan,
merchantId:merchantId, mode:mode, result:2, sha256:digest,
status:status, title:title, firstname:firstname, lastname:lastname,
email:email, postcode:postcode, transno:transno)
}
init(amount: Int, currency: String, authcode: String?, authorised: Bool,
AvsResponse: String?, CscResponse: String?, errorcode: String, errormsg: String,
expMonth: Int, expYear: Int, identifier: String, maskedPan: String,
merchantId: Int, mode: String, result: Int, sha256: String,
status: String, title: String?, firstname:String?, lastname:String?,
email: String?,postcode: String?,transno: Int) {
self.amount = amount
self.currency = currency
self.authcode = authcode
self.authorised = authorised
self.AvsResponse = AvsResponse
self.CscResponse = CscResponse
self.errorcode = errorcode
self.errormsg = errormsg
self.expMonth = expMonth
self.expYear = expYear
self.identifier = identifier
self.maskedPan = maskedPan
self.merchantId = merchantId
self.mode = mode
self.result = result
self.sha256 = sha256
self.status = status
self.title = title
self.firstname = firstname
self.lastname = lastname
self.email = email
self.postcode = postcode
self.transno = transno
}
/// only way to initialise is via a JSON packet
public init(data: NSData) {
var e: NSError?
let json = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: &e)
if let error = e {
NSLog("Error parsing JSON \(error)")
}
self.amount = json["amount"].int ?? 0
self.currency = json["currency"].stringValue
self.authcode = json["authcode"].string
self.authorised = json["authorised"].bool ?? false
self.AvsResponse = json["AVSResponse"].string
self.CscResponse = json["CSCResponse"].string
self.errorcode = json["errorcode"].string ?? "F007"
self.errormsg = json["errormessage"].string ?? "No valid response from JSON packet"
self.expMonth = json["expMonth"].int ?? 0
self.expYear = json["expYear"].int ?? 0
self.identifier = json["identifier"].string ?? "unknown"
self.maskedPan = json["maskedPan"].string ?? "n/a"
self.merchantId = json["merchantid"].int ?? 0
self.mode = json["mode"].string ?? "?"
self.result = json["result"].int ?? 20 // unknown
self.sha256 = json["sha256"].string ?? ""
self.status = json["status"].string ?? "?" // unknown
self.title = json["title"].string
self.firstname = json["firstname"].string
self.lastname = json["lastname"].string
self.email = json["email"].string
self.postcode = json["postcode"].string
self.transno = json["transno"].int ?? -1
}
}
| mit |
kansaraprateek/WebService | WebService/Classes/DocumentHandler.swift | 1 | 16975 | //
// DocumentHandler.swift
// WebService
//
// Created by Prateek Kansara on 30/05/16.
// Copyright © 2016 Prateek. All rights reserved.
//
import Foundation
import MobileCoreServices
import UIKit
extension URL {
// var typeIdentifier: String {
// guard isFileURL else { return "unknown" }
// var uniformTypeIdentifier: AnyObject?
// do {
// try getResourceValue(&uniformTypeIdentifier, forKey: URLResourceKey.typeIdentifierKey)
// return uniformTypeIdentifier as? String ?? "unknown"
// } catch let error as NSError {
// print(error.debugDescription)
// return "unknown"
// }
// }
}
private var globalFileManager : FileManager! {
if FileManager.default.fileExists(atPath: globalDestinationDocPath as String) {
do{
try FileManager.default.createDirectory(atPath: globalDestinationDocPath as String, withIntermediateDirectories: false, attributes: nil)
}
catch{
print("failed to create common doc folder")
}
}
return FileManager.default
}
private var globalPaths : NSArray! {
return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray!
}
private var globalDocumentDirectoryPath : NSString! {
return globalPaths.object(at: 0) as! NSString
}
private var globalDestinationDocPath : NSString! {
return globalDocumentDirectoryPath.appendingPathComponent("/Docs") as NSString!
}
@objc protocol DocumentHandlerDelegate : NSObjectProtocol{
func DocumentUplaodedSuccessfully(_ data : Data)
func DocumentUploadFailed(_ error : NSError)
}
private let FILEBOUNDARY = "--ARCFormBoundarym9l3512x3aexw29"
open class DocumentHandler : NSObject {
var delegate : DocumentHandlerDelegate{
set {
self.delegate = newValue
}
get{
return self.delegate
}
}
open var fileName : NSString!
open class var sharedInstance: DocumentHandler {
struct Singleton {
static let instance = DocumentHandler()
}
return Singleton.instance
}
open
func setDefaultHeaders(_ headers : NSMutableDictionary) {
let headersClass = HTTPHeaders.sharedInstance
headersClass.setDefaultDocumentHeaders(headers)
}
open var httpHeaders : NSDictionary?
open func downloadDocument(_ urlString : NSString, documentID : NSString, Progress: @escaping (_ bytesWritten : Int64, _ totalBytesWritten : Int64, _ remaining : Int64) -> Void, Success : @escaping (_ location : URL, _ taskDescription : NSString) -> Void, Error : @escaping (_ respones : HTTPURLResponse, _ error : NSError?) -> Void) {
let documetDownlaodSession : DocumentDownloader = DocumentDownloader.init(lURLString: urlString, lRequestType: "GET")
documetDownlaodSession.uniqueID = documentID
documetDownlaodSession.headerValues = httpHeaders
documetDownlaodSession.downloadDocumentWithProgress(Progress, Success: Success, Error: Error)
}
open func uploadDocumentWithURl(_ urlString : NSString, parameters : NSDictionary?, documentPath : NSArray, fieldName : String, Progress : @escaping (_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void, Success : @escaping (_ response : HTTPURLResponse, Any) -> Void, Error : @escaping (_ response : HTTPURLResponse, _ error : Any?) -> Void) {
let data : Data = createBodyWithBoundary(FILEBOUNDARY, parameters: parameters, paths: documentPath, fieldName: fieldName)
let uploadDocument : DocumentUploader = DocumentUploader()
if httpHeaders != nil {
uploadDocument.headerValues = NSMutableDictionary.init(dictionary: httpHeaders!)
}
uploadDocument.uploadDocumentWithURl(urlString, formData: data, uniqueID: self.fileName, Progress: Progress, Success: Success, Error: Error)
}
fileprivate func createBodyWithBoundary(_ boundary : String, parameters : NSDictionary?, paths : NSArray, fieldName : String) -> Data {
let httpBody : NSMutableData = NSMutableData()
parameters?.enumerateKeysAndObjects({
paramKey, paramValue, _ in
httpBody.append(String(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8)!)
httpBody.append(String(format: "Content-Disposition: form-data; name=\"%@\"\r\n\r\n", paramKey as! String).data(using: String.Encoding.utf8)!)
httpBody.append(String(format: "%@\r\n", paramValue as! String).data(using: String.Encoding.utf8)!)
})
for path in paths {
let fileName : NSString = (path as! NSString).lastPathComponent as NSString
let data : Data = try! Data(contentsOf: URL(fileURLWithPath: path as! String))
let mimeType : NSString = fileName.pathExtension as NSString
// (URL(string: path as! String)?.lastPathComponent)! as NSString
httpBody.append(String(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8)!)
httpBody.append(String(format: "Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fieldName, fileName).data(using: String.Encoding.utf8)!)
httpBody.append(String(format: "Content-Type: %@\r\n\r\n", mimeType).data(using: String.Encoding.utf8)!)
httpBody.append(data)
httpBody.append(String(format: "\r\n").data(using: String.Encoding.utf8)!)
}
httpBody.append(String(format: "--%@--\r\n", boundary).data(using: String.Encoding.utf8)!)
return httpBody as Data
}
fileprivate func mimeTypeForPath(_ path : NSString) -> NSString {
let docExtension : CFString = path.pathExtension as CFString
let UTI : CFString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, docExtension, nil) as! CFString
// assert(UTI != nil)
let mimeType = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType)!
let mimeString = convertCfTypeToString(cfValue: mimeType)
return mimeString!
}
private func convertCfTypeToString(cfValue: Unmanaged<CFString>!) -> NSString?{
/* Coded by Vandad Nahavandipoor */
let value = Unmanaged.fromOpaque(
cfValue.toOpaque()).takeUnretainedValue() as CFString
if CFGetTypeID(value) == CFStringGetTypeID(){
return value as NSString
} else {
return nil
}
}
}
extension DocumentHandler: UINavigationControllerDelegate {
}
// MARK: - Document session class
private class DocumentDownloader: NSObject {
fileprivate var uniqueID : NSString!
fileprivate var urlString : NSString!
fileprivate var requestType : NSString!
fileprivate var backgroundSession : Foundation.URLSession!
fileprivate var inProgress : ((_ bytesWritten : Int64, _ totalBytesWritten : Int64, _ remaining : Int64) -> Void)?
fileprivate var onSuccess : ((_ location : URL, _ taskDescription : NSString) -> Void)?
fileprivate var onError : ((_ response : HTTPURLResponse, _ error : NSError?) -> Void)?
fileprivate var headerValues : NSDictionary?
fileprivate var gResponse : HTTPURLResponse!
fileprivate var mutableRequest : URLRequest! {
set{
self.mutableRequest = newValue
}
get {
var lMutableRequest : URLRequest = URLRequest(url: URL(string: self.urlString as String)!)
lMutableRequest.httpMethod = "GET"
lMutableRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let httpHeaderClass = HTTPHeaders.sharedInstance
if headerValues == nil {
if httpHeaderClass.getDocumentHeaders() == nil {
headerValues = httpHeaderClass.getHTTPHeaders()
}
else{
headerValues = httpHeaderClass.getDocumentHeaders()
}
}
headerValues?.enumerateKeysAndObjects({
key, value, _ in
lMutableRequest.setValue(value as? String, forHTTPHeaderField: key as! String)
})
return lMutableRequest
}
}
fileprivate var sessionConfiguration : URLSessionConfiguration! {
set {
self.sessionConfiguration = newValue
}
get{
let sessionConfig = URLSessionConfiguration.background(withIdentifier: self.uniqueID as String)
// let additionalHeaderDictionary : NSMutableDictionary = NSMutableDictionary ()
// additionalHeaderDictionary.setValue("application/json", forKey: "Content-Type")
// sessionConfig.HTTPAdditionalHeaders = additionalHeaderDictionary
return sessionConfig
}
}
override init() {
super.init()
}
convenience init(lURLString : NSString, lRequestType : NSString) {
self.init()
requestType = lRequestType
urlString = lURLString
}
fileprivate func downloadDocumentWithProgress(_ Progress : @escaping (_ bytesWritten : Int64, _ totalBytesWritten : Int64, _ remaining : Int64) -> Void, Success: @escaping (_ location : URL, _ taskDescription : NSString) -> Void, Error : @escaping (_ response : HTTPURLResponse, _ error : NSError?) -> Void) {
onError = Error
onSuccess = Success
inProgress = Progress
backgroundSession = Foundation.URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue:OperationQueue.main)
let downloadTask = backgroundSession.downloadTask(with: mutableRequest)
downloadTask.resume()
}
}
extension DocumentDownloader: URLSessionDataDelegate{
func urlSession(_ session: Foundation.URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (Foundation.URLSession.ResponseDisposition) -> Void) {
gResponse = response as? HTTPURLResponse
completionHandler(.allow);
}
}
extension DocumentDownloader : URLSessionDownloadDelegate{
@objc func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// if gResponse.statusCode == 200{
self.onSuccess!(location, "Downloaded")
// }
// else{
// self.onError!(response: gResponse, error: nil)
// }
}
@objc func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
self.inProgress!(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
fileprivate func URLSession(_ session: Foundation.URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
self.onError!(gResponse, error)
}
}
private class DocumentUploader : NSObject {
fileprivate var gURl : NSString!
fileprivate var gRequestType : NSString!
fileprivate var uniqueID : NSString!
fileprivate var onSuccess : ((_ response : HTTPURLResponse, Any) -> Void)?
fileprivate var onError : ((_ response : HTTPURLResponse, Any?) -> Void)?
fileprivate var inProgress : ((_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void)?
fileprivate var recievedData : Data!
fileprivate var headerValues : NSMutableDictionary?
fileprivate var gResponse : HTTPURLResponse!
fileprivate var backgroundUploadSession : Foundation.URLSession!
fileprivate var mutableRequest : NSMutableURLRequest! {
set{
self.mutableRequest = newValue
}
get {
let lMutableRequest : NSMutableURLRequest = NSMutableURLRequest(url: URL(string: self.gURl as String)!)
lMutableRequest.httpMethod = gRequestType as String
let httpHeaderClass = HTTPHeaders.sharedInstance
if headerValues == nil {
if httpHeaderClass.getDocumentHeaders() == nil {
if httpHeaderClass.getHTTPHeaders() == nil {
print("Set header values")
}
else
{
headerValues = NSMutableDictionary.init(dictionary: httpHeaderClass.getHTTPHeaders()!)
}
}
else{
headerValues = NSMutableDictionary.init(dictionary: httpHeaderClass.getDocumentHeaders()!)
}
}
headerValues?.enumerateKeysAndObjects({
key, value, _ in
lMutableRequest.setValue(value as? String, forHTTPHeaderField: key as! String)
})
if gRequestType.isEqual("POST") || gRequestType.isEqual("PUT"){
let mutipartContentType = NSString(format: "multipart/form-data; boundary=%@", FILEBOUNDARY)
lMutableRequest.setValue(mutipartContentType as String, forHTTPHeaderField: "Content-Type")
}
return lMutableRequest
}
}
fileprivate func uploadDocumentWithURl(_ urlString : NSString, formData : Data, uniqueID : NSString, Progress : @escaping (_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void, Success : @escaping (_ response : HTTPURLResponse, Any) -> Void, Error : @escaping (_ response : HTTPURLResponse, _ error : Any?) -> Void) {
self.gRequestType = "POST"
self.gURl = urlString
self.uniqueID = uniqueID
inProgress = Progress
onSuccess = Success
onError = Error
let sessionConfig : URLSessionConfiguration = URLSessionConfiguration.default
backgroundUploadSession = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue:OperationQueue.main)
let uploadTask : URLSessionUploadTask = backgroundUploadSession.uploadTask(with: mutableRequest as URLRequest, from: formData)
uploadTask.resume()
}
}
extension DocumentUploader: URLSessionDataDelegate{
func urlSession(_ session: Foundation.URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (Foundation.URLSession.ResponseDisposition) -> Void) {
gResponse = response as? HTTPURLResponse
recievedData = Data()
// print("\(gResponse)")
completionHandler(.allow);
}
fileprivate func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
recievedData.append(data)
}
}
extension DocumentUploader : URLSessionTaskDelegate{
@objc func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
// print("session \(session) task : \(task) error : \(error)")
if (error == nil) {
let responseDict : Any!
do{
responseDict = try JSONSerialization.jsonObject(with: recievedData, options: .allowFragments)
// print(responseDict)
}
catch{
print("serialization failed")
let error : NSError = NSError.init(domain: "SerializationFailed", code: 0, userInfo: nil)
if gResponse!.statusCode == 200 {
if (recievedData != nil) {
onSuccess!(gResponse, recievedData)
}else{
onSuccess!(gResponse, ["message" : "success"])
}
}
else{
onError!(gResponse, error)
}
return
}
if gResponse!.statusCode == 200 {
onSuccess!(gResponse, responseDict)
}
else{
onError!(gResponse, responseDict)
}
}
else{
onError!(gResponse ?? HTTPURLResponse(), error!)
}
}
@objc func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
// print("byte send \(bytesSent) expected : \(totalBytesExpectedToSend) ")
self.inProgress!(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.