repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apple/swift-lldb | refs/heads/stable | packages/Python/lldbsuite/test/lang/swift/expression/weak_self/main.swift | apache-2.0 | 2 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
class ClosureMaker {
var a : Int
init (a : Int) {
self.a = a
}
func getClosure() -> (() -> Int) {
return { [weak self] () -> Int in
if let _self = self {
return _self.a //% self.expect("expr self", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["ClosureMaker?)", "5"])
//% self.expect("expr self!", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["ClosureMaker)", "5"])
} else {
return 0 //% self.expect("expr self", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["nil"])
}
}
}
func getGuardClosure() -> (() -> Int) {
return { [weak self] () -> Int in
guard let self = self else {
return 0 //% self.expect("expr self", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["nil"])
}
return self.a //% self.expect("expr self", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["ClosureMaker?)", "5"])
//% self.expect("expr self!", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["ClosureMaker)", "5"])
}
}
}
func use<T>(_ t: T) {}
var livemaker : ClosureMaker? = ClosureMaker(a: 5)
let liveclosure = livemaker!.getClosure()
let liveguardclosure = livemaker!.getGuardClosure()
use((liveclosure(), liveguardclosure()))
var deadmaker : ClosureMaker? = ClosureMaker(a: 3)
let deadclosure = deadmaker!.getClosure()
let deadguardclosure = deadmaker!.getGuardClosure()
deadmaker = nil
use((deadclosure(), deadguardclosure()))
| dab54c8c9a2608760e9f03abcec8b43c | 36.09434 | 125 | 0.581384 | false | false | false | false |
SwiftBond/Bond | refs/heads/master | Sources/Bond/AppKit/NSSlider.swift | mit | 2 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Tony Arnold (@tonyarnold)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if os(macOS)
import AppKit
import ReactiveKit
public extension ReactiveExtensions where Base: NSSlider {
public var minValue: Bond<Double> {
return bond { $0.minValue = $1 }
}
public var maxValue: Bond<Double> {
return bond { $0.maxValue = $1 }
}
public var altIncrementValue: Bond<Double> {
return bond { $0.altIncrementValue = $1 }
}
@available(macOS 10.12, *)
public var isVertical: Bond<Bool> {
return bond { $0.isVertical = $1 }
}
@available(macOS 10.12.2, *)
public var trackFillColor: Bond<NSColor?> {
return bond { $0.trackFillColor = $1 }
}
public var numberOfTickMarks: Bond<Int> {
return bond { $0.numberOfTickMarks = $1 }
}
public var tickMarkPosition: Bond<NSSlider.TickMarkPosition> {
return bond { $0.tickMarkPosition = $1 }
}
public var allowsTickMarkValuesOnly: Bond<Bool> {
return bond { $0.allowsTickMarkValuesOnly = $1 }
}
}
extension NSSlider {
public func bind(signal: Signal<Double, NoError>) -> Disposable {
return reactive.doubleValue.bind(signal: signal)
}
}
#endif
| df6c010fe738c83f2be8d30d3d4276c4 | 30.527027 | 81 | 0.686241 | false | false | false | false |
alltheflow/iCopyPasta | refs/heads/master | Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxDataSourceStarterKit/UISectionedViewType+RxAnimatedDataSource.swift | mit | 6 | //
// UISectionedViewType+RxAnimatedDataSource.swift
// RxExample
//
// Created by Krunoslav Zaher on 11/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
extension UITableView {
public func rx_itemsAnimatedWithDataSource<
DataSource: protocol<RxTableViewDataSourceType, UITableViewDataSource>,
S: SequenceType,
O: ObservableConvertibleType,
Section: protocol<SectionModelType, Hashable>
where
DataSource.Element == [Changeset<Section>],
O.E == S,
S.Generator.Element == Section,
Section.Item: Hashable
>
(dataSource: DataSource)
(source: O)
-> Disposable {
let differences = source.differentiateForSectionedView()
return self.rx_itemsWithDataSource(dataSource)(source: differences)
}
}
extension UICollectionView {
public func rx_itemsAnimatedWithDataSource<
DataSource: protocol<RxCollectionViewDataSourceType, UICollectionViewDataSource>,
S: SequenceType,
O: ObservableConvertibleType,
Section: protocol<SectionModelType, Hashable>
where
DataSource.Element == [Changeset<Section>],
O.E == S,
S.Generator.Element == Section,
Section.Item: Hashable
>
(dataSource: DataSource)
(source: O)
-> Disposable {
let differences = source.differentiateForSectionedView()
return self.rx_itemsWithDataSource(dataSource)(source: differences)
}
} | cea30d84114179f586371c70e3f6cade | 29.87037 | 93 | 0.642857 | false | false | false | false |
NocturneZX/TTT-Pre-Internship-Exercises | refs/heads/master | Swift/Class 11 copy/ShoppingListKai/ShoppingList/AppDelegate.swift | gpl-2.0 | 2 | //
// AppDelegate.swift
// ShoppingList
//
// Created by Oren Goldberg on 8/18/14.
// Copyright (c) 2014 TurnToTech. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> 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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.turntotech.ShoppingList" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("ShoppingList", withExtension: "momd")
return NSManagedObjectModel(contentsOfURL: modelURL!)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("ShoppingList.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| 61adf4492c7e45661485d54a737fbf19 | 54.54955 | 290 | 0.713428 | false | false | false | false |
Ricky-Choi/IUExtensions | refs/heads/master | IUExtensions/DocumentExtension.swift | mit | 1 | //
// DocumentExtension.swift
// Appetizer
//
// Created by Jaeyoung Choi on 2016. 10. 26..
// Copyright © 2016년 Appcid. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
extension UIDocument.State: CustomStringConvertible {
public var description: String {
var statusString = ""
if contains(.normal) {
statusString = "normal"
}
if contains(.closed) {
if !statusString.isEmpty {
statusString += "|"
}
statusString += "closed"
}
if contains(.inConflict) {
if !statusString.isEmpty {
statusString += "|"
}
statusString += "inConflict"
}
if contains(.savingError) {
if !statusString.isEmpty {
statusString += "|"
}
statusString += "savingError"
}
if contains(.editingDisabled) {
if !statusString.isEmpty {
statusString += "|"
}
statusString += "editingDisabled"
}
return statusString
}
}
#endif
| 7c38ce1c5a2d27a24c54dea91d25f2e8 | 24.72549 | 57 | 0.443598 | false | false | false | false |
younata/RSSClient | refs/heads/master | Tethys/Feeds/Editing Feeds/FeedDetailView.swift | mit | 1 | import UIKit
public protocol FeedDetailViewDelegate: class {
func feedDetailView(_ feedDetailView: FeedDetailView, urlDidChange url: URL)
func feedDetailView(_ feedDetailView: FeedDetailView, tagsDidChange tags: [String])
func feedDetailView(_ feedDetailView: FeedDetailView,
editTag tag: String?, completion: @escaping (String) -> Void)
}
public final class FeedDetailView: UIView {
private let mainStackView = UIStackView(forAutoLayout: ())
public let titleLabel = UILabel(forAutoLayout: ())
public let urlField = UITextField(forAutoLayout: ())
public let summaryLabel = UILabel(forAutoLayout: ())
public let addTagButton = UIButton(type: .system)
public let tagsList = ActionableTableView(forAutoLayout: ())
public var title: String { return self.titleLabel.text ?? "" }
public var url: URL? { return URL(string: self.urlField.text ?? "") }
public var summary: String { return self.summaryLabel.text ?? "" }
public fileprivate(set) var tags: [String] = [] {
didSet { self.tagsList.recalculateHeightConstraint() }
}
public var maxHeight: CGFloat {
get { return self.tagsList.maxHeight }
set { self.tagsList.maxHeight = newValue }
}
public weak var delegate: FeedDetailViewDelegate?
public func configure(title: String, url: URL, summary: String, tags: [String]) {
self.titleLabel.text = title
self.summaryLabel.text = summary
let delegate = self.delegate
self.delegate = nil
self.urlField.text = url.absoluteString
self.urlField.accessibilityValue = url.absoluteString
self.delegate = delegate
self.titleLabel.accessibilityLabel = NSLocalizedString(
"FeedViewController_Accessibility_TableHeader_Title_Label", comment: ""
)
self.titleLabel.accessibilityValue = title
self.summaryLabel.accessibilityLabel = NSLocalizedString(
"FeedViewController_Accessibility_TableHeader_Summary_Label", comment: ""
)
self.summaryLabel.accessibilityValue = summary
self.tags = tags
self.tagsList.reloadData()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.mainStackView)
self.mainStackView.axis = .vertical
self.mainStackView.spacing = 6
self.mainStackView.distribution = .equalSpacing
self.mainStackView.alignment = .center
self.mainStackView.autoPinEdge(toSuperviewEdge: .leading)
self.mainStackView.autoPinEdge(toSuperviewEdge: .trailing)
self.mainStackView.autoPinEdge(toSuperviewEdge: .top, withInset: 84)
self.mainStackView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 20, relation: .greaterThanOrEqual)
self.mainStackView.addArrangedSubview(self.titleLabel)
self.mainStackView.addArrangedSubview(self.urlField)
self.mainStackView.addArrangedSubview(UIView()) // to give a little extra space between url and summary
self.mainStackView.addArrangedSubview(self.summaryLabel)
self.mainStackView.addArrangedSubview(self.tagsList)
self.addTagButton.translatesAutoresizingMaskIntoConstraints = false
self.tagsList.setActions([UIView(), self.addTagButton])
self.urlField.delegate = self
self.tagsList.tableView.register(TableViewCell.self, forCellReuseIdentifier: "cell")
self.tagsList.tableView.delegate = self
self.tagsList.tableView.dataSource = self
self.tagsList.tableView.estimatedRowHeight = 80
self.summaryLabel.numberOfLines = 0
self.titleLabel.numberOfLines = 0
for view in ([self.titleLabel, self.summaryLabel, self.urlField] as [UIView]) {
view.autoPinEdge(toSuperviewEdge: .leading, withInset: 40)
view.autoPinEdge(toSuperviewEdge: .trailing, withInset: 40)
}
self.tagsList.autoPinEdge(toSuperviewEdge: .leading)
self.tagsList.autoPinEdge(toSuperviewEdge: .trailing)
self.addTagButton.setTitle(NSLocalizedString("FeedViewController_Actions_AddTag", comment: ""), for: .normal)
self.addTagButton.addTarget(self, action: #selector(FeedDetailView.didTapAddTarget), for: .touchUpInside)
self.urlField.textColor = UIColor.gray
[self.titleLabel, self.urlField, self.summaryLabel, self.addTagButton].forEach { view in
view.isAccessibilityElement = true
}
self.titleLabel.accessibilityTraits = [.staticText]
self.summaryLabel.accessibilityTraits = [.staticText]
self.addTagButton.accessibilityTraits = [.button]
self.addTagButton.accessibilityLabel = NSLocalizedString("FeedViewController_Actions_AddTag", comment: "")
self.urlField.accessibilityLabel = NSLocalizedString("FeedViewController_Accessibility_TableHeader_URL_Label",
comment: "")
self.applyTheme()
}
private func applyTheme() {
self.backgroundColor = Theme.backgroundColor
self.tagsList.tableView.backgroundColor = Theme.backgroundColor
self.tagsList.tableView.separatorColor = Theme.separatorColor
self.titleLabel.textColor = Theme.textColor
self.summaryLabel.textColor = Theme.textColor
self.addTagButton.setTitleColor(Theme.highlightColor, for: .normal)
}
public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
public override func layoutSubviews() {
self.titleLabel.font = UIFont.preferredFont(forTextStyle: .headline)
self.summaryLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
self.urlField.font = UIFont.preferredFont(forTextStyle: .subheadline)
super.layoutSubviews()
}
@objc private func didTapAddTarget() {
self.delegate?.feedDetailView(self, editTag: nil) { newTag in
self.tags.append(newTag)
let indexPath = IndexPath(row: self.tags.count - 1, section: 0)
self.tagsList.tableView.insertRows(at: [indexPath], with: .automatic)
self.tagsList.recalculateHeightConstraint()
self.delegate?.feedDetailView(self, tagsDidChange: self.tags)
}
}
}
extension FeedDetailView: UITextFieldDelegate {
public func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let text = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
if let url = URL(string: text), url.scheme != nil {
self.delegate?.feedDetailView(self, urlDidChange: url)
}
return true
}
}
extension FeedDetailView: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tags.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.textLabel?.text = self.tags[indexPath.row]
cell.accessibilityTraits = [.button]
cell.accessibilityLabel = NSLocalizedString("FeedViewController_Accessibility_Cell_Label", comment: "")
cell.accessibilityValue = self.tags[indexPath.row]
return cell
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true }
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {}
}
extension FeedDetailView: UITableViewDelegate {
public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt
indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteTitle = NSLocalizedString("Generic_Delete", comment: "")
let delete = UIContextualAction(style: .destructive, title: deleteTitle) { _, _, handler in
self.tags.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
self.delegate?.feedDetailView(self, tagsDidChange: self.tags)
handler(true)
}
let editTitle = NSLocalizedString("Generic_Edit", comment: "")
let edit = UIContextualAction(style: .normal, title: editTitle) { _, _, handler in
let tag = self.tags[indexPath.row]
self.delegate?.feedDetailView(self, editTag: tag) { newTag in
self.tags[indexPath.row] = newTag
tableView.reloadRows(at: [indexPath], with: .automatic)
self.delegate?.feedDetailView(self, tagsDidChange: self.tags)
handler(true)
}
}
let swipeActions = UISwipeActionsConfiguration(actions: [delete, edit])
swipeActions.performsFirstActionWithFullSwipe = true
return swipeActions
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let tag = self.tags[indexPath.row]
self.delegate?.feedDetailView(self, editTag: tag) { newTag in
self.tags[indexPath.row] = newTag
tableView.reloadRows(at: [indexPath], with: .automatic)
self.delegate?.feedDetailView(self, tagsDidChange: self.tags)
}
}
}
| 6a6f0811ec9cfe4352a5a6be30704408 | 42.790909 | 118 | 0.679676 | false | false | false | false |
steveholt55/metro | refs/heads/master | iOS/MetroTransit/Model/Route/Route+Methods.swift | mit | 1 | //
// Copyright © 2016 Brandon Jenniges. All rights reserved.
//
import UIKit
import CoreData
import Alamofire
extension Route {
// MARK: - Core Data
convenience init?(json: [String : AnyObject]) {
let entity = Route.getEntity(String(Route))
self.init(entity: entity, insertIntoManagedObjectContext: Route.getManagedObjectContext())
guard let routeNumberString = json["Route"] as? String,
let routeNumberInt = Int(routeNumberString),
let providerIdString = json["ProviderID"] as? String,
let providerIdInt = Int(providerIdString),
let routeName = json["Description"] as? String
else { return nil }
self.routeNumber = NSNumber(integer: routeNumberInt)
self.providerId = NSNumber(integer: providerIdInt)
self.name = routeName
}
// MARK: - Metro API
static func getRoutes(complete complete:(routes:[Route]) -> Void) {
let URL = NSURL(string: "http://svc.metrotransit.org/NexTrip/Routes")
HTTPClient().get(URL!, parameters: ["format":"json"]) { (json:AnyObject?, response:NSHTTPURLResponse?, error:NSError?) -> Void in
var routes = [Route]()
if let json = json as? [[String : AnyObject]] {
for item in json {
if let route = Route(json: item) {
routes.append(route)
}
}
}
complete(routes: routes)
}
}
static func getRoutesContainingName(string: String, routes:[Route]) -> [Route] {
let whitespaceSet = NSCharacterSet.whitespaceCharacterSet()
if string.stringByTrimmingCharactersInSet(whitespaceSet) == "" {
return routes
}
let lowercaseString = string.lowercaseString
return routes.filter { (route : Route) -> Bool in
return route.name!.lowercaseString.rangeOfString(lowercaseString) != nil
}
}
}
| 6d0cfe018f5663fc0c082e2df91244e2 | 33.965517 | 137 | 0.590237 | false | false | false | false |
jlainog/Messages | refs/heads/master | Messages/Messages/FireBaseService.swift | mit | 1 | //
// ChannelService.swift
// Messages
//
// Created by Gustavo Mario Londoño Correa on 3/7/17.
// Copyright © 2017 JLainoG. All rights reserved.
//
import Foundation
import Firebase
import FirebaseDatabase
typealias FirebaseListHandler = ( [FirebaseObject] ) -> Void
protocol FirebaseObject {
var id: String? { get }
init(id: String, json: NSDictionary)
func toDictionary() -> NSDictionary
}
struct FireBaseService <Object: FirebaseObject> {
var ref = FIRDatabase.database().reference()
func delete(withNodeKey nodeKey: String, object: Object) {
ref.child(nodeKey).child(object.id!).removeValue()
}
func create(withNodeKey nodeKey: String, object: Object) {
let dictionary = object.toDictionary()
ref.child(nodeKey).childByAutoId().setValue(dictionary)
}
func list(withNodeKey nodeKey: String, completionHandler: @escaping FirebaseListHandler) {
ref.child(nodeKey).observeSingleEvent(of: .value, with: { (snapshot) in
if let objects = snapshot.value as? [String : Any] {
let objectsList = objects.map { Object(id: $0, json: $1 as! NSDictionary) }
completionHandler(objectsList)
} else {
completionHandler([])
}
})
}
func listAndObserve(atNodeKey nodeKey: String, completionHandler: @escaping (FirebaseObject?) -> Void) {
ref.child(nodeKey).queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
if let object = snapshot.value as? [String : Any] {
completionHandler(Object(id: snapshot.key, json: object as NSDictionary))
} else {
completionHandler(nil)
}
})
}
func didRemoveObject(atNodeKey nodeKey: String, completionHandler: @escaping (FirebaseObject?) -> Void) {
ref.child(nodeKey).observe(.childRemoved, with: { (snapshot) in
if let object = snapshot.value as? [String : Any] {
completionHandler(Object(id: snapshot.key, json: object as NSDictionary))
} else {
completionHandler(nil)
}
})
}
func didChangeObject(atNodeKey nodeKey: String, completionHandler: @escaping (FirebaseObject?) -> Void) {
ref.child(nodeKey).observe(.childChanged, with: { (snapshot) in
if let object = snapshot.value as? [String : Any] {
completionHandler(Object(id: snapshot.key, json: object as NSDictionary))
} else {
completionHandler(nil)
}
})
}
func dismmissObservers(){
ref.removeAllObservers()
}
}
| efb9881fea25a8bb4e0518df4916983c | 32.62963 | 109 | 0.606828 | false | false | false | false |
jairoeli/Habit | refs/heads/master | Zero/Sources/Views/Cells/HabitCell.swift | mit | 1 | //
// HabitCell.swift
// Zero
//
// Created by Jairo Eli de Leon on 5/8/17.
// Copyright © 2017 Jairo Eli de León. All rights reserved.
//
import UIKit
import ReactorKit
import RxSwift
final class HabitCell: BaseTableViewCell, View {
typealias Reactor = HabitCellReactor
// MARK: - Constants
struct Constant {
static let titleLabelNumberOfLines = 0
}
struct Metric {
static let paddingTop = 24.f
static let padding = 16.f
static let valueSize = 85.f
}
struct Font {
static let titleLabel = UIFont.title2()
}
// MARK: - UI
lazy var titleLabel = UILabel() <== {
$0.font = Font.titleLabel
$0.textColor = .charcoal
$0.numberOfLines = Constant.titleLabelNumberOfLines
}
lazy var valueLabel = UILabel() <== {
$0.font = Font.titleLabel
$0.textColor = .charcoal
$0.text = "0"
$0.textAlignment = .right
}
lazy var separatorView = UIView() <== {
$0.backgroundColor = .platinumBorder
}
// MARK: - Initializing
override func initialize() {
let subviews: [UIView] = [titleLabel, valueLabel, separatorView]
self.contentView.add(subviews)
self.backgroundColor = .snow
}
// MARK: - Binding
func bind(reactor: HabitCellReactor) {
reactor.state.map { $0.title }
.distinctUntilChanged()
.bind(to: self.titleLabel.rx.text)
.disposed(by: self.disposeBag)
reactor.state.map { "\($0.value)" }
.bind(to: self.valueLabel.rx.text)
.disposed(by: self.disposeBag)
}
// MARK: - Cell Height
class func height(fits width: CGFloat, reactor: Reactor) -> CGFloat {
let height = reactor.currentState.title.height(fits: width - Metric.paddingTop * 3,
font: Font.titleLabel,
maximumNumberOfLines: Constant.titleLabelNumberOfLines)
return height + Metric.padding * 3
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
self.titleLabel.sizeToFit()
self.titleLabel.top = Metric.paddingTop
self.titleLabel.left = Metric.padding
self.titleLabel.width = self.contentView.width - 100
self.valueLabel.sizeToFit()
self.valueLabel.centerY = self.contentView.centerY
self.valueLabel.left = self.titleLabel.right - 16
self.valueLabel.width = Metric.valueSize
self.separatorView.bottom = self.contentView.bottom
self.separatorView.left = Metric.padding
self.separatorView.width = self.contentView.width - Metric.padding * 2
self.separatorView.height = 0.5 / UIScreen.main.scale
}
}
| e8affd966dfc049800aab1720404af0e | 24.5 | 106 | 0.652826 | false | false | false | false |
HarwordLiu/Ing. | refs/heads/master | Ing/Ing/Protocol/CloudKitProtocols.swift | mit | 1 | //
// CloudKitProtocols.swift
// Ing
//
// Created by 刘浩 on 2017/9/7.
// Copyright © 2017年 刘浩. All rights reserved.
//
import Foundation
import CloudKit
import CoreData
@objc protocol CloudKitRecordIDObject {
var recordID: NSData? { get set }
}
extension CloudKitRecordIDObject {
func cloudKitRecordID() -> CKRecordID? {
guard let recordID = recordID else {
return nil
}
return NSKeyedUnarchiver.unarchiveObject(with: recordID as Data) as? CKRecordID
}
}
@objc protocol CloudKitManagedObject: CloudKitRecordIDObject {
var lastUpdate: Date? { get set }
var recordName: String? { get set }
var recordType: String { get }
func managedObjectToRecord(_ record: CKRecord?) -> CKRecord
func updateWithRecord(_ record: CKRecord)
}
extension CloudKitManagedObject {
func cloudKitRecord(_ record: CKRecord?, parentRecordZoneID: CKRecordZoneID?) -> CKRecord {
if let record = record {
return record
}
var recordZoneID: CKRecordZoneID
if parentRecordZoneID != .none {
recordZoneID = parentRecordZoneID!
}
else {
guard let cloudKitZone = CloudKitZone(recordType: recordType) else {
fatalError("Attempted to create a CKRecord with an unknown zone")
}
recordZoneID = cloudKitZone.recordZoneID()
}
let uuid = UUID()
let recordName = recordType + "." + uuid.uuidString
let recordID = CKRecordID(recordName: recordName, zoneID: recordZoneID)
return CKRecord(recordType: recordType, recordID: recordID)
}
func addDeletedCloudKitObject() {
if let managedObject = self as? NSManagedObject,
let managedObjectContext = managedObject.managedObjectContext,
let recordID = recordID,
let deletedCloudKitObject = NSEntityDescription.insertNewObject(forEntityName: "DeletedCloudKitObject", into: managedObjectContext) as? DeletedCloudKitObject {
deletedCloudKitObject.recordID = recordID
deletedCloudKitObject.recordType = recordType
}
}
}
| 27555ba9e3cd023eb5beca179ac80042 | 29.791667 | 171 | 0.644565 | false | false | false | false |
hilen/TSWeChat | refs/heads/master | TSWeChat/Classes/Chat/TSChatViewController+Interaction.swift | mit | 1 | //
// TSChatViewController+Interaction.swift
// TSWeChat
//
// Created by Hilen on 12/31/15.
// Copyright © 2015 Hilen. All rights reserved.
//
import Foundation
import Photos
import MobileCoreServices
// MARK: - @protocol ChatShareMoreViewDelegate
// 分享更多里面的 Button 交互
extension TSChatViewController: ChatShareMoreViewDelegate {
//选择打开相册
func chatShareMoreViewPhotoTaped() {
// self.ts_presentImagePickerController(
// maxNumberOfSelections: 1,
// select: { (asset: PHAsset) -> Void in
// print("Selected: \(asset)")
// }, deselect: { (asset: PHAsset) -> Void in
// print("Deselected: \(asset)")
// }, cancel: { (assets: [PHAsset]) -> Void in
// print("Cancel: \(assets)")
// }, finish: {[weak self] (assets: [PHAsset]) -> Void in
// print("Finish: \(assets.get(index: 0))")
// guard let strongSelf = self else { return }
// if let image = assets.get(index: 0).getUIImage() {
// strongSelf.resizeAndSendImage(image)
// }
// }, completion: { () -> Void in
// print("completion")
// })
}
//选择打开相机
func chatShareMoreViewCameraTaped() {
let authStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if authStatus == .notDetermined {
self.checkCameraPermission()
} else if authStatus == .restricted || authStatus == .denied {
TSAlertView_show("无法访问您的相机", message: "请到设置 -> 隐私 -> 相机 ,打开访问权限" )
} else if authStatus == .authorized {
self.openCamera()
}
}
func checkCameraPermission () {
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: {granted in
if !granted {
TSAlertView_show("无法访问您的相机", message: "请到设置 -> 隐私 -> 相机 ,打开访问权限" )
}
})
}
func openCamera() {
self.imagePicker = UIImagePickerController()
self.imagePicker.delegate = self
self.imagePicker.sourceType = .camera
self.present(self.imagePicker, animated: true, completion: nil)
}
//处理图片,并且发送图片消息
func resizeAndSendImage(_ theImage: UIImage) {
let originalImage = UIImage.ts_fixImageOrientation(theImage)
let storeKey = "send_image"+String(format: "%f", Date.milliseconds)
let thumbSize = ChatConfig.getThumbImageSize(originalImage.size)
//获取缩略图失败 ,抛出异常:发送失败
guard let thumbNail = originalImage.ts_resize(thumbSize) else { return }
ImageFilesManager.storeImage(thumbNail, key: storeKey, completionHandler: { [weak self] in
guard let strongSelf = self else { return }
//发送图片消息
let sendImageModel = ChatImageModel()
sendImageModel.imageHeight = originalImage.size.height
sendImageModel.imageWidth = originalImage.size.width
sendImageModel.localStoreName = storeKey
strongSelf.chatSendImage(sendImageModel)
/**
* 异步上传原图, 然后上传成功后,把 model 值改掉
* 但因为还没有找到上传的 API,所以这个函数会返回错误 T.T
* //TODO: 原图尺寸略大,需要剪裁
*/
HttpManager.uploadSingleImage(originalImage, success: {model in
//修改 sendImageModel 的值
sendImageModel.imageHeight = model.originalHeight
sendImageModel.imageWidth = model.originalWidth
sendImageModel.thumbURL = model.thumbURL
sendImageModel.originalURL = model.originalURL
sendImageModel.imageId = String(describing: model.imageId)
//修改缩略图的名称
let tempStorePath = URL(string:ImageFilesManager.cachePathForKey(storeKey)!)
let targetStorePath = URL(string:ImageFilesManager.cachePathForKey(sendImageModel.thumbURL!)!)
ImageFilesManager.renameFile(tempStorePath!, destinationPath: targetStorePath!)
}, failure: {
})
})
}
}
// MARK: - @protocol UIImagePickerControllerDelegate
// 拍照完成,进行上传图片,并且发送的请求
extension TSChatViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// Local variable inserted by Swift 4.2 migrator.
let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
guard let mediaType = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.mediaType)] as? NSString else { return }
if mediaType.isEqual(to: kUTTypeImage as String) {
guard let image: UIImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage else { return }
if picker.sourceType == .camera {
self.resizeAndSendImage(image)
}
}
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
// MARK: - @protocol RecordAudioDelegate
// 语音录制完毕后
extension TSChatViewController: RecordAudioDelegate {
func audioRecordUpdateMetra(_ metra: Float) {
self.voiceIndicatorView.updateMetersValue(metra)
}
func audioRecordTooShort() {
self.voiceIndicatorView.messageTooShort()
}
func audioRecordFinish(_ uploadAmrData: Data, recordTime: Float, fileHash: String) {
self.voiceIndicatorView.endRecord()
//发送本地音频
let audioModel = ChatAudioModel()
audioModel.keyHash = fileHash
audioModel.audioURL = ""
audioModel.duration = recordTime
self.chatSendVoice(audioModel)
/**
* 异步上传音频文件, 然后上传成功后,把 model 值改掉
* 因为还没有上传的 API,所以这个函数会返回错误 T.T
*/
HttpManager.uploadAudio(uploadAmrData, recordTime: String(recordTime), success: {model in
audioModel.keyHash = model.keyHash
audioModel.audioURL = model.audioURL
audioModel.duration = recordTime
}, failure: {
})
}
func audioRecordFailed() {
TSAlertView_show("录音失败,请重试")
}
func audioRecordCanceled() {
}
}
// MARK: - @protocol PlayAudioDelegate
extension TSChatViewController: PlayAudioDelegate {
/**
播放完毕
*/
func audioPlayStart() {
}
/**
播放完毕
*/
func audioPlayFinished() {
self.currentVoiceCell.resetVoiceAnimation()
}
/**
播放失败
*/
func audioPlayFailed() {
self.currentVoiceCell.resetVoiceAnimation()
}
/**
播放被中断
*/
func audioPlayInterruption() {
self.currentVoiceCell.resetVoiceAnimation()
}
}
// MARK: - @protocol ChatEmotionInputViewDelegate
// 表情点击完毕后
extension TSChatViewController: ChatEmotionInputViewDelegate {
//点击表情
func chatEmoticonInputViewDidTapCell(_ cell: TSChatEmotionCell) {
self.chatActionBarView.inputTextView.insertText(cell.emotionModel!.text)
}
//点击撤退删除
func chatEmoticonInputViewDidTapBackspace(_ cell: TSChatEmotionCell) {
self.chatActionBarView.inputTextView.deleteBackward()
}
//点击发送文字,包含表情
func chatEmoticonInputViewDidTapSend() {
self.chatSendText()
}
}
// MARK: - @protocol UITextViewDelegate
extension TSChatViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
//点击发送文字,包含表情
self.chatSendText()
return false
}
return true
}
func textViewDidChange(_ textView: UITextView) {
let contentHeight = textView.contentSize.height
guard contentHeight < kChatActionBarTextViewMaxHeight else {
return
}
self.chatActionBarView.inputTextViewCurrentHeight = contentHeight + 17
self.controlExpandableInputView(showExpandable: true)
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
//设置键盘类型,响应 UIKeyboardWillShowNotification 事件
self.chatActionBarView.inputTextViewCallKeyboard()
//使 UITextView 滚动到末尾的区域
UIView.setAnimationsEnabled(false)
let range = NSMakeRange(textView.text.ts_length - 1, 1)
textView.scrollRangeToVisible(range)
UIView.setAnimationsEnabled(true)
return true
}
}
// MARK: - @protocol TSChatCellDelegate
extension TSChatViewController: TSChatCellDelegate {
/**
点击了 cell 本身
*/
func cellDidTaped(_ cell: TSChatBaseCell) {
}
/**
点击了 cell 的头像
*/
func cellDidTapedAvatarImage(_ cell: TSChatBaseCell) {
TSAlertView_show("点击了头像")
}
/**
点击了 cell 的图片
*/
func cellDidTapedImageView(_ cell: TSChatBaseCell) {
TSAlertView_show("点击了图片")
}
/**
点击了 cell 中文字的 URL
*/
func cellDidTapedLink(_ cell: TSChatBaseCell, linkString: String) {
let viewController = TSWebViewController(URLString: linkString)
self.ts_pushAndHideTabbar(viewController)
}
/**
点击了 cell 中文字的 电话
*/
func cellDidTapedPhone(_ cell: TSChatBaseCell, phoneString: String) {
TSAlertView_show("点击了电话")
}
/**
点击了声音 cell 的播放 button
*/
func cellDidTapedVoiceButton(_ cell: TSChatVoiceCell, isPlayingVoice: Bool) {
//在切换选中的语音 cell 之前把之前的动画停止掉
if self.currentVoiceCell != nil && self.currentVoiceCell != cell {
self.currentVoiceCell.resetVoiceAnimation()
}
if isPlayingVoice {
self.currentVoiceCell = cell
guard let audioModel = cell.model!.audioModel else {
AudioPlayInstance.stopPlayer()
return
}
AudioPlayInstance.startPlaying(audioModel)
} else {
AudioPlayInstance.stopPlayer()
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
| d82057c63f52e369cfa071fbe6dad014 | 31.206587 | 161 | 0.629915 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Domains/Domain registration/Views/RegisterDomainSectionHeaderView.swift | gpl-2.0 | 2 | import UIKit
class RegisterDomainSectionHeaderView: UITableViewHeaderFooterView {
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var descriptionLabel: UILabel!
static let identifier = "RegisterDomainSectionHeaderView"
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.font = WPStyleGuide.fontForTextStyle(.subheadline,
fontWeight: .semibold)
titleLabel.textColor = .textSubtle
titleLabel.numberOfLines = 0
descriptionLabel.font = WPStyleGuide.fontForTextStyle(.footnote)
descriptionLabel.textColor = .textSubtle
descriptionLabel.numberOfLines = 0
contentView.backgroundColor = .listBackground
}
func setTitle(_ title: String?) {
titleLabel.text = title
}
func setDescription(_ description: String?) {
descriptionLabel.text = description
}
}
| d5bb5473f65b8133045771b609e3a500 | 30.9 | 78 | 0.670846 | false | false | false | false |
eugeneego/utilities-ios | refs/heads/master | Sources/Common/Action.swift | mit | 1 | //
// Action
// Legacy
//
// Copyright (c) 2015 Eugene Egorov.
// License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE
//
import Foundation
@objc public protocol Action {
func perform()
}
public final class BlockAction: Action {
public let action: () -> Void
public func perform() {
action()
}
public init(action: @escaping () -> Void) {
self.action = action
}
}
public final class TargetAction<Target: AnyObject>: Action {
public private(set) weak var target: Target?
public let action: (Target) -> () -> Void
public func perform() {
if let target = target {
action(target)()
}
}
public init(target: Target, action: @escaping (Target) -> () -> Void) {
self.target = target
self.action = action
}
}
public final class TargetSenderAction<Target: AnyObject, Sender: AnyObject>: Action {
public private(set) weak var target: Target?
public private(set) weak var sender: Sender?
public let action: (Target) -> (Sender) -> Void
public func perform() {
if let target = target, let sender = sender {
action(target)(sender)
}
}
public init(target: Target, sender: Sender, action: @escaping (Target) -> (Sender) -> Void) {
self.target = target
self.sender = sender
self.action = action
}
}
| e54160581e82dd2844cd1e89d059f988 | 22.677966 | 97 | 0.606299 | false | false | false | false |
Minitour/WWDC-Collaborators | refs/heads/master | Macintosh.playground/Sources/Interface/DesktopApplication.swift | mit | 1 | import Foundation
import UIKit
public protocol DesktopAppDelegate{
/// Called when desktop application is doubled tapped.
///
/// - Parameter application: The current desktop application.
func didDoubleClick(_ application: DesktopApplication)
/// Called when application is about to start dragging.
///
/// - Parameter application: The current Desktop Application.
func willStartDragging(_ application: DesktopApplication)
/// Called when dragging is over.
///
/// - Parameter application: The current Desktop Application.
func didFinishDragging(_ application: DesktopApplication)
}
/// DesktopViewConnectionDelegate is the bridge between the MacAppDesktopView and the DesktopAppDelegate.
public protocol DesktopViewConnectionDelegate{
/// Called when desktop application is doubled tapped.
func didDoubleClick()
/// Called when application is about to start dragging.
func willStartDragging()
/// Called when dragging is over.
func didFinishDragging()
}
/// The DesktopAppDataSource is what provides the display meta data to the Desktop Application View
public protocol DesktopAppDataSource{
/// The image that will be displayed as an icon
var image: UIImage {get}
/// The title/text that will be displayed on the app
var name: String {get}
}
public class DesktopApplication{
/// This function creates an instance of Desktop Application using `MacApp` instance and `OSWindow` instance. Where the `MacApp` is used as a data source and the `OSWindow` is used as a delegate.
///
/// - Parameters:
/// - app: The app which we want to display on the desktop. Note that this MacApp must have a desktopIcon value.
/// - window: The OSWindow instance in which we are display the desktop application.
/// - Returns: The new created instance of DesktopApplication
public static func make(app: MacApp,in window: OSWindow)->DesktopApplication{
let desktopApp = DesktopApplication(with: window)
desktopApp.app = app
desktopApp.delegate = window
return desktopApp
}
/// The data source for this Desktop Application
public var app: MacApp?{
didSet{
view = MacAppDesktopView(dataSource: self)
}
}
/// The delegate for this Desktop Application
public var delegate: DesktopAppDelegate?{
didSet{
view?.delegate = self
}
}
/// The Desktop View
public var view: MacAppDesktopView!
/// A strong reference to the current window, in case the desktop application needs to make some changes to it.
var window: OSWindow!
public init(with window: OSWindow){
self.window = window
}
}
/// Conform to DesktopViewConnectionDelegate
extension DesktopApplication: DesktopViewConnectionDelegate{
public func didFinishDragging() {
delegate?.didFinishDragging(self)
}
public func willStartDragging() {
delegate?.willStartDragging(self)
}
public func didDoubleClick(){
delegate?.didDoubleClick(self)
}
}
/// Conform to DesktopAppDataSource
extension DesktopApplication: DesktopAppDataSource{
public var name: String {
return app?.windowTitle ?? ""
}
public var image: UIImage {
return app!.desktopIcon!
}
}
/// The MacAppDesktopView
public class MacAppDesktopView: UIView{
/// The data source
var dataSource: DesktopAppDataSource?
/// The delegate
var delegate: DesktopViewConnectionDelegate?
/// The icon (as image view)
var icon: UIImageView!
/// The text label
var text: UILabel!
/// The transition window frame (The border the user sees when the app is being dragged)
var transitionWindowFrame: MovingApplication?
/// The last location (A property used for dragging)
var lastLocation: CGPoint = .zero
/// The width of desktop applications
static let width: CGFloat = 65.0
/// The space between the image view and the frame
static let space: CGFloat = 3.0
/// The scale of the image relative to the width
static let imageScale: CGFloat = 0.8
/// initialization should always be done using this initailizer because a data source is needed in order to calculate the view's frame height.
///
/// - Parameter dataSource: The desktop app data source which contains an image and a string.
convenience init(dataSource: DesktopAppDataSource){
//calculate needed height
let imageHeight: CGFloat = MacAppDesktopView.imageScale * MacAppDesktopView.width
let textWidth = MacAppDesktopView.width - MacAppDesktopView.space * 2
let textHeight = Utils.heightForView(dataSource.name, font: SystemSettings.notePadFont, width: textWidth, numberOfLines: 0)
let totalHeight = textHeight + imageHeight
let rect = CGRect(origin: CGPoint.zero, size: CGSize(width: MacAppDesktopView.width, height: totalHeight))
self.init(frame: rect)
self.dataSource = dataSource
setup()
}
/// Never ussed this
///
/// - Parameter frame: The frame size of the view
override public init(frame: CGRect){
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(){
// setup image view
let imageWidth = MacAppDesktopView.imageScale * MacAppDesktopView.width
icon = UIImageView(frame: CGRect(x: (MacAppDesktopView.width - imageWidth)/2, y: 0, width: imageWidth, height: imageWidth))
icon.image = dataSource?.image
icon.contentMode = .scaleAspectFit
// setup text view
let textWidth = MacAppDesktopView.width - MacAppDesktopView.space * 2
let textHeight = Utils.heightForView(dataSource!.name, font: SystemSettings.notePadFont, width: textWidth, numberOfLines: 0)
text = UILabel(frame: CGRect(x: (MacAppDesktopView.width - textWidth)/2, y: imageWidth, width: textWidth, height: textHeight))
text.backgroundColor = .white
text.text = dataSource?.name
text.font = SystemSettings.notePadFont
text.textAlignment = .center
text.numberOfLines = 0
addSubview(icon)
addSubview(text)
// setup transition frame
transitionWindowFrame = MovingApplication(textHeight: textHeight, textWidth: textWidth, totalWidth: MacAppDesktopView.width)
transitionWindowFrame?.isHidden = true
transitionWindowFrame?.backgroundColor = .clear
addSubview(transitionWindowFrame!)
// add gesture recognizers
addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan(sender:))))
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
tapGesture.numberOfTapsRequired = 2
addGestureRecognizer(tapGesture)
}
/// Selector function, handles taps
///
/// - Parameter sender: UITapGestureRecognizer
func handleTap(sender: UITapGestureRecognizer){
delegate?.didDoubleClick()
}
/// Selector fuction, handles drag
///
/// - Parameter sender: UIPanGestureRecognizer
func handlePan(sender: UIPanGestureRecognizer){
let translation = sender.translation(in: self.superview!)
switch sender.state{
case .began:
transitionWindowFrame?.isHidden = false
transitionWindowFrame?.frame = CGRect(origin: CGPoint(x: 0 , y: 0), size: bounds.size)
transitionWindowFrame?.lastLocation = (self.transitionWindowFrame?.center)!
delegate?.willStartDragging()
break
case .ended:
transitionWindowFrame?.isHidden = true
self.center = convert(transitionWindowFrame!.center, to: superview!)
delegate?.didFinishDragging()
return
default:
break
}
let point = CGPoint(x: (transitionWindowFrame?.lastLocation.x)! + translation.x , y: (transitionWindowFrame?.lastLocation.y)! + translation.y)
transitionWindowFrame?.center = point
}
}
/// This is the class of which we create the transitioning window frame
class MovingApplication: UIView{
var lastLocation = CGPoint(x: 0, y: 0)
var width: CGFloat!
var imageSize: CGFloat!
var textHeight: CGFloat!
var textWidth: CGFloat!
convenience init(textHeight: CGFloat,textWidth: CGFloat,totalWidth: CGFloat){
self.init(frame: CGRect(x: 0, y: 0, width: textWidth, height: totalWidth * MacAppDesktopView.imageScale + textHeight))
self.textHeight = textHeight
self.textWidth = textWidth
self.width = totalWidth
self.imageSize = totalWidth * MacAppDesktopView.imageScale
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
UIColor.lightGray.setStroke()
let path = UIBezierPath()
path.move(to: CGPoint(x: (width - imageSize)/2, y: 0))
path.addLine(to: CGPoint(x: (width - imageSize)/2, y: imageSize))
path.addLine(to: CGPoint(x: 0, y: imageSize))
path.addLine(to: CGPoint(x: 0, y: textHeight + imageSize))
path.addLine(to: CGPoint(x: textWidth, y: textHeight + imageSize))
path.addLine(to: CGPoint(x: textWidth, y: imageSize))
path.addLine(to: CGPoint(x: imageSize, y: imageSize))
path.addLine(to: CGPoint(x: imageSize , y: 0))
path.close()
path.lineWidth = 1
path.stroke()
}
}
| 5dafe08b5fdd4002b047c0e1d7d19f05 | 32.817568 | 199 | 0.658841 | false | false | false | false |
wufeiyue/FYShareView | refs/heads/master | Classes/FYShareView.swift | mit | 2 | //
// FYShareView.swift
// FYShareView
//
// Created by 武飞跃 on 2017/10/18.
// Copyright © 2017年 wufeiyue.com. All rights reserved.
//
import UIKit
public typealias FYShareItemButtonAction = (_ sender: FYShareItemButton) -> Void
public struct FYShareStyle {
var offsetY: CGFloat = 0.0 //相对于顶部的偏移量 默认为0
var insetHorizontal: CGFloat = 5.0 //水平向中间方向缩进量 默认为5
var itemCount: Int = 4 //每一页显示的itemView个数
var isPagingEnabled: Bool = true //是否显示分页
var contentHeight: CGFloat = 200 //scrollView的高度
var cancelHeight: CGFloat = 38 //取消按钮的高度
var cancelMarginTop: CGFloat = 8 //取消按钮与scrollView之间浅灰色分割线高度
var titleMarginTop: CGFloat = 7 //itemView 标题与icon之间的距离
var pageControlMarginBottom: CGFloat = 10 //pageControl距离分割线的高度
}
public struct FYShareItemModel {
var normalImage: UIImage?
var highlightedImage: UIImage?
var title: String
var identifier: String = ""
public init(title:String, normal: String, highlighted: String, id: String) {
self.highlightedImage = UIImage(named: highlighted)
self.normalImage = UIImage(named: normal)
self.title = title
self.identifier = id
}
}
public protocol FYShareViewDelegate: class {
func shareView(itemDidTapped identifier: String)
}
public final class FYShareView: UIView {
public var style = FYShareStyle()
public let items: Array<FYShareItemModel>
public weak var delegate: FYShareViewDelegate?
private lazy var bgView: UIView = { [unowned self] in
let view = UIView(frame: self.bounds)
view.backgroundColor = .black
let tap = UITapGestureRecognizer(target: self, action: #selector(FYShareView.hide))
view.addGestureRecognizer(tap)
return view
}()
private lazy var containerView: FYShareContainerView = { [unowned self] in
$0.backgroundColor = UIColor.groupTableViewBackground
$0.style = self.style
$0.itemView = self.items
$0.itemAction = { [weak self] btn in
self?.delegate?.shareView(itemDidTapped: btn.identifier)
}
$0.cancelAction = { [weak self] in
self?.hide()
}
return $0
}(FYShareContainerView())
public init(frame: CGRect, items: Array<FYShareItemModel>) {
self.items = items
super.init(frame: frame)
isHidden = true
}
public func show() {
addSubviews()
guard containerView.alpha == 0 else { return }
containerView.transform = CGAffineTransform(translationX: 0, y: 40)
UIView.animate(withDuration: 0.3) {
self.containerView.alpha = 1
self.containerView.transform = CGAffineTransform(translationX: 0, y: 0)
self.bgView.alpha = 0.3
}
}
@objc public func hide() {
UIView.animate(withDuration: 0.3, animations: {
self.containerView.alpha = 0
self.containerView.transform = CGAffineTransform(translationX: 0, y: 40)
self.bgView.alpha = 0
}) { (isFinished) in
self.removeSubViews()
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func removeSubViews() {
isHidden = true
[containerView, bgView].forEach{
$0.removeFromSuperview()
}
}
private func addSubviews() {
guard subviews.isEmpty else { return }
isHidden = false
[bgView, containerView].forEach {
$0.alpha = 0
addSubview($0)
}
}
public override func layoutSubviews() {
super.layoutSubviews()
var rect = CGRect.zero
rect.size = CGSize(width: bounds.size.width, height: style.contentHeight)
containerView.bounds = rect
containerView.center.y = -style.contentHeight / 2 + bounds.size.height
containerView.center.x = bounds.midX
}
}
fileprivate final class FYShareContainerView: UIView {
lazy var cancelBtn: UIButton = { [unowned self] in
let btn = UIButton(type: .system)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
btn.setTitle("取消", for: .normal)
btn.setTitleColor(UIColor(red: 51.0/255, green: 51.0/255, blue: 51.0/255, alpha: 1), for: .normal)
btn.backgroundColor = .white
btn.addTarget(self, action: #selector(cancelBtnDidTapped), for: .touchUpInside)
return btn
}()
lazy var scrollView: UIScrollView = { [unowned self] in
let view = UIScrollView()
view.showsVerticalScrollIndicator = false
view.showsHorizontalScrollIndicator = false
view.contentOffset = .zero
view.backgroundColor = .white
view.delegate = self
return view
}()
lazy var pageControl: UIPageControl = {
let control = UIPageControl()
control.backgroundColor = UIColor.white
control.pageIndicatorTintColor = UIColor.groupTableViewBackground
control.currentPageIndicatorTintColor = UIColor.gray
control.isHidden = true
return control
}()
lazy var bgView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
return view
}()
var style: FYShareStyle!
var itemView: Array<FYShareItemModel>!
var itemAction: FYShareItemButtonAction!
var cancelAction: (() -> Void)?
init() {
super.init(frame: .zero)
[cancelBtn, scrollView, pageControl, bgView].forEach({ addSubview($0) })
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
// print("bounds:\(bounds)")
var pageControlHeight: CGFloat = 0
let isShowPageControl = style.isPagingEnabled(from: itemView.count)
scrollView.isPagingEnabled = isShowPageControl
pageControl.isHidden = !isShowPageControl
cancelBtn.frame = bounds.inset(offsetY: style.cancelHeight)
if !pageControl.isHidden{
pageControlHeight = style.pageControlMarginBottom + 8
}
scrollView.frame = bounds.inset(height: style.cancelHeight + style.cancelMarginTop + pageControlHeight)
scrollView.setupView(style: style, itemView: itemView, action: itemAction)
pageControl.numberOfPages = itemView.count / style.itemCount + 1
pageControl.frame = CGRect(x: 0, y: scrollView.frame.maxY, width: bounds.size.width, height: 8)
bgView.frame = CGRect(x: 0, y: pageControl.frame.maxY, width: bounds.size.width, height: style.pageControlMarginBottom)
}
@objc func cancelBtnDidTapped() {
cancelAction?()
}
}
extension FYShareContainerView: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageWidth = bounds.size.width
let pageFraction = scrollView.contentOffset.x / pageWidth
pageControl.currentPage = Int(pageFraction)
}
}
public protocol FYShareItemViewDelegate: class {
func setupView(style: FYShareStyle, itemView:Array<FYShareItemModel>, action: @escaping FYShareItemButtonAction)
}
extension FYShareItemViewDelegate where Self: UIScrollView {
public func setupView(style: FYShareStyle, itemView:Array<FYShareItemModel>, action: @escaping FYShareItemButtonAction) {
subviews.forEach{ $0.removeFromSuperview() }
func row(count:Int) -> Int {
let num = style.itemCount
return (count % num == 0 ? 0 : 1) + count / num
}
func createCounter(width: CGFloat) -> () -> CGFloat {
var index = 0
let offsetX = style.insetHorizontal
return {
defer { index += 1 }
return CGFloat(index) * width + offsetX + (2 * offsetX) * CGFloat(row(count: index + 1) - 1)
}
}
let size = style.originSize(from: bounds.size)
let counter = createCounter(width: size.width)
itemView.forEach { (model) in
var rect: CGRect = .zero
rect.size = size
rect.origin.y = style.offsetY
rect.origin.x = counter()
let btn = FYShareItemButton(frame: rect)
btn.setTitle(model.title, for: .normal)
btn.setTitleColor(UIColor(red: 51.0/255, green: 51.0/255, blue: 51.0/255, alpha: 1), for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
btn.setImage(model.normalImage, for: .normal)
btn.setImage(model.highlightedImage, for: .highlighted)
btn.identifier = model.identifier
btn.titleMarginTop = style.titleMarginTop
btn.addAction(action)
addSubview(btn)
}
contentSize = CGSize(width: CGFloat(row(count: itemView.count)) * bounds.size.width, height: 0)
}
}
extension UIScrollView: FYShareItemViewDelegate { }
public final class FYShareItemButton: UIButton {
var titleMarginTop: CGFloat = 5
var action: FYShareItemButtonAction?
public var identifier: String = ""
override init(frame: CGRect) {
super.init(frame: frame)
addTarget(self, action: #selector(FYShareItemButton.didPressed(_:)), for: UIControlEvents.touchUpInside)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func didPressed(_ sender: FYShareItemButton) {
action?(sender)
}
override public func layoutSubviews() {
super.layoutSubviews()
guard let titleLabel = titleLabel, let imageView = imageView else {
return
}
var newFrame = titleLabel.frame
var center = imageView.center
center.x = frame.size.width / 2
center.y = (frame.size.height - titleMarginTop - newFrame.size.height) / 2
imageView.center = center
newFrame.origin.x = 0
newFrame.origin.y = imageView.frame.maxY + titleMarginTop
newFrame.size.width = frame.size.width
titleLabel.frame = newFrame
titleLabel.textAlignment = .center
}
public func addAction(_ action: @escaping FYShareItemButtonAction) {
self.action = action
}
}
extension FYShareStyle {
fileprivate func originSize(from superview: CGSize) -> CGSize {
return CGSize(width: (superview.width - insetHorizontal * 2) / CGFloat(itemCount), height: -2 * offsetY + superview.height)
}
fileprivate func isPagingEnabled(from count: Int) -> Bool {
guard isPagingEnabled else { return false }
return itemCount < count ? true : false
}
}
extension CGRect {
fileprivate func inset(height value: CGFloat) -> CGRect {
return CGRect(x: origin.x, y: origin.y, width: size.width, height: size.height - value)
}
fileprivate func inset(offsetY value: CGFloat) -> CGRect {
return CGRect(x: origin.x, y: size.height - value, width: size.width, height: value)
}
}
| be13d702ce769c87c834020c6da35ed6 | 32.359649 | 131 | 0.621702 | false | false | false | false |
arvindhsukumar/PredicateEditor | refs/heads/master | PredicateEditor/Classes/ErrorToastView.swift | mit | 1 | //
// ErrorToastView.swift
// Pods
//
// Created by Arvindh Sukumar on 25/07/16.
//
//
import UIKit
class ErrorToastView: UIView {
let label: UILabel = {
let label = UILabel()
label.textAlignment = .Center
label.numberOfLines = 0
label.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
label.textColor = UIColor.whiteColor()
return label
}()
convenience init(message: String){
self.init(frame: CGRectZero)
label.text = message
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
addSubview(label)
label.snp_makeConstraints { (make) in
make.edges.equalTo(self).inset(10).priority(900)
}
}
}
| 97a5d36e60c76a1a091679420f68aaa0 | 22.295455 | 87 | 0.605854 | false | false | false | false |
mukeshthawani/UXMPDFKit | refs/heads/master | Pod/Classes/Renderer/PDFViewController.swift | mit | 1 | //
// PDFViewController.swift
// Pods
//
// Created by Chris Anderson on 5/7/16.
//
//
import UIKit
import SafariServices
open class PDFViewController: UIViewController {
/// A boolean value that determines whether the navigation bar and scrubber bar hide on screen tap
open var hidesBarsOnTap: Bool = true
/// A boolean value that determines if the scrubber bar should be visible
open var showsScrubber: Bool = true {
didSet {
pageScrubber.isHidden = !showsScrubber
}
}
/// A boolean value that determines if a PDF should have fillable form elements
open var allowsFormFilling: Bool = true
/// A boolean value that determines if annotations are allowed
open var allowsAnnotations: Bool = true
/// A boolean value that determines if sharing should be allowed
open var allowsSharing: Bool = true
/// A boolean value that determines if view controller is displayed as modal
open var isPresentingInModal: Bool = false
/// The scroll direction of the reader
open var scrollDirection: UICollectionViewScrollDirection = .horizontal
/// A reference to the document that is being displayed
var document: PDFDocument!
/// A reference to the share button
var shareBarButtonItem: UIBarButtonItem?
/// A closure that defines an action to take upon selecting the share button.
/// The default action brings up a UIActivityViewController
open lazy var shareBarButtonAction: () -> () = { self.showActivitySheet() }
/// A reference to the collection view handling page presentation
var collectionView: PDFSinglePageViewer!
/// A reference to the page scrubber bar
var pageScrubber: PDFPageScrubber!
lazy var formController: PDFFormViewController = PDFFormViewController(document: self.document)
lazy var annotationController: PDFAnnotationController = PDFAnnotationController(document: self.document, delegate: self)
fileprivate var showingAnnotations = false
fileprivate var showingFormFilling = true
/**
Initializes a new reader with a given document
- Parameters:
- document: The document to display
- Returns: An instance of the PDFViewController
*/
public init(document: PDFDocument) {
super.init(nibName: nil, bundle: nil)
self.document = document
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func viewDidLoad() {
super.viewDidLoad()
pageScrubber = PDFPageScrubber(frame: CGRect(x: 0, y: view.frame.size.height - bottomLayoutGuide.length, width: view.frame.size.width, height: 44.0), document: document)
pageScrubber.scrubberDelegate = self
pageScrubber.translatesAutoresizingMaskIntoConstraints = false
collectionView = PDFSinglePageViewer(frame: view.bounds, document: document)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.singlePageDelegate = self
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.scrollDirection = scrollDirection
switch scrollDirection {
case .horizontal:
collectionView.isPagingEnabled = true
pageScrubber.isHidden = !showsScrubber
case .vertical:
collectionView.isPagingEnabled = false
pageScrubber.isHidden = true
}
self.setupUI()
collectionView.reloadItems(at: [IndexPath(row: 0, section: 0)])
}
fileprivate func setupUI() {
view.addSubview(collectionView)
view.addSubview(pageScrubber)
view.addSubview(annotationController.view)
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
pageScrubber.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
pageScrubber.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
pageScrubber.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
pageScrubber.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
automaticallyAdjustsScrollViewInsets = false
pageScrubber.sizeToFit()
reloadBarButtons()
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.contentInset = UIEdgeInsetsMake(topLayoutGuide.length, 0, bottomLayoutGuide.length, 0)
collectionView.collectionViewLayout.invalidateLayout()
view.layoutSubviews()
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
self.collectionView.contentInset = UIEdgeInsetsMake(self.topLayoutGuide.length, 0, self.bottomLayoutGuide.length, 0)
self.collectionView.collectionViewLayout.invalidateLayout()
self.pageScrubber.sizeToFit()
}, completion: { (context) in
self.collectionView.displayPage(self.document.currentPage, animated: false)
})
}
//MARK: - Private helpers
fileprivate func scrollTo(page: Int) {
document.currentPage = page
collectionView.displayPage(page, animated: false)
if showsScrubber {
pageScrubber.updateScrubber()
}
}
fileprivate func reloadBarButtons() {
navigationItem.rightBarButtonItems = rightBarButtons()
if isPresentingInModal {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Done",
style: .plain,
target: self,
action: #selector(PDFViewController.dismissModal))
}
}
fileprivate func rightBarButtons() -> [UIBarButtonItem] {
var buttons: [UIBarButtonItem] = []
if allowsSharing {
let shareFormBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .action,
target: self,
action: #selector(PDFViewController.shareDocument)
)
buttons.append(shareFormBarButtonItem)
self.shareBarButtonItem = shareFormBarButtonItem
}
buttons.append(UIBarButtonItem(
image: UIImage.bundledImage("thumbs"),
style: .plain,
target: self,
action: #selector(PDFViewController.showThumbnailView)
)
)
if allowsAnnotations {
if showingAnnotations {
buttons.append(annotationController.highlighterButton)
buttons.append(annotationController.penButton)
buttons.append(annotationController.textButton)
buttons.append(annotationController.undoButton)
}
buttons.append(PDFBarButton(
image: UIImage.bundledImage("annot"),
toggled: showingAnnotations,
target: self,
action: #selector(PDFViewController.toggleAnnotations(_:))
)
)
}
return buttons
}
func toggleAnnotations(_ button: PDFBarButton) {
showingAnnotations = !showingAnnotations
reloadBarButtons()
}
func showActivitySheet() {
let renderer = PDFRenderController(document: document, controllers: [
annotationController,
formController
])
let pdf = renderer.renderOntoPDF()
let items = [pdf]
let activityVC = UIActivityViewController(activityItems: items, applicationActivities: nil)
if UIDevice.current.userInterfaceIdiom == .pad {
activityVC.modalPresentationStyle = .popover
let popController = activityVC.popoverPresentationController
popController?.barButtonItem = shareBarButtonItem
popController?.permittedArrowDirections = .up
}
present(activityVC, animated: true, completion: nil)
}
func showThumbnailView() {
let vc = PDFThumbnailViewController(document: document)
vc.delegate = self
let nvc = UINavigationController(rootViewController: vc)
nvc.modalTransitionStyle = .crossDissolve
present(nvc, animated: true, completion: nil)
}
func hideBars(state: Bool) {
navigationController?.setNavigationBarHidden(state, animated: true)
switch scrollDirection {
case .horizontal:
if showsScrubber {
pageScrubber.isHidden = state
} else {
pageScrubber.isHidden = true
}
case .vertical:
pageScrubber.isHidden = true
}
}
/// Toggles the display of the navigation bar and scrubber bar
func toggleBars() {
hideBars(state: !(navigationController?.isNavigationBarHidden ?? false))
collectionView.collectionViewLayout.invalidateLayout()
}
//MARK: - IBActions
func handleTap(_ gestureRecognizer: UIGestureRecognizer) {
self.toggleBars()
}
func shareDocument() {
self.shareBarButtonAction()
}
func dismissModal() {
dismiss(animated: true, completion: nil)
}
}
extension PDFViewController: PDFAnnotationControllerProtocol {
public func annotationWillStart(touch: UITouch) -> Int? {
let tapPoint = touch.location(in: collectionView)
guard let pageIndex = collectionView.indexPathForItem(at: tapPoint)?.row else { return nil }
return pageIndex + 1
}
}
extension PDFViewController: PDFPageScrubberDelegate {
public func scrubber(_ scrubber: PDFPageScrubber, selectedPage: Int) {
self.scrollTo(page: selectedPage)
}
}
extension PDFViewController: PDFSinglePageViewerDelegate {
public func singlePageViewer(_ collectionView: PDFSinglePageViewer, didDisplayPage page: Int) {
document.currentPage = page
if showsScrubber {
pageScrubber.updateScrubber()
}
}
public func singlePageViewer(_ collectionView: PDFSinglePageViewer, loadedContent content: PDFPageContentView) {
if allowsFormFilling {
formController.showForm(content)
}
if allowsAnnotations {
annotationController.showAnnotations(content)
}
}
public func singlePageViewer(_ collectionView: PDFSinglePageViewer, selectedAction action: PDFAction) {
if let action = action as? PDFActionURL {
let svc = SFSafariViewController(url: action.url as URL)
present(svc, animated: true, completion: nil)
} else if let action = action as? PDFActionGoTo {
collectionView.displayPage(action.pageIndex, animated: true)
}
}
public func singlePageViewer(_ collectionView: PDFSinglePageViewer, tapped recognizer: UITapGestureRecognizer) {
if hidesBarsOnTap {
handleTap(recognizer)
}
}
public func singlePageViewerDidBeginDragging() {
self.hideBars(state: true)
}
public func singlePageViewerDidEndDragging() { }
}
extension PDFViewController: PDFThumbnailViewControllerDelegate {
public func thumbnailCollection(_ collection: PDFThumbnailViewController, didSelect page: Int) {
self.scrollTo(page: page)
self.dismiss(animated: true, completion: nil)
}
}
| 4e55bb03a3dbac1a07cd164e3462c4c2 | 35.372024 | 177 | 0.64741 | false | false | false | false |
accepton/accepton-apple | refs/heads/master | Pod/Classes/AcceptOnViewController/Views/CreditCardForm/AcceptOnCreditCardFormView.swift | mit | 1 | import UIKit
import CHRTextFieldFormatterPrivate
//Notifications for all things relating to the credit card form
@objc protocol AcceptOnCreditCardFormDelegate {
optional func creditCardFormPayWasClicked()
optional func creditCardFormFieldWithName(name: String, wasUpdatedToString: String)
optional func creditCardFormFieldWithNameDidFocus(name: String)
optional func creditCardFormFocusedFieldLostFocus()
optional func creditCardFormBackWasClicked()
}
//This contains the credit-card form that is displayed if the user hits the 'credit_card' payment
//button on setup
class AcceptOnCreditCardFormView: UIView, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource
{
//-----------------------------------------------------------------------------------------------------
//Properties
//-----------------------------------------------------------------------------------------------------
//User input fields
@IBOutlet weak var cardNumField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var securityField: UITextField!
@IBOutlet weak var expMonthField: UITextField!
@IBOutlet weak var expYearField: UITextField!
lazy var nameToField: [String:UITextField] = [
"email":self.emailField,
"cardNum":self.cardNumField,
"security":self.securityField,
"expYear":self.expYearField,
"expMonth":self.expMonthField
]
lazy var fieldToName: [UITextField:String] = [
self.emailField:"email",
self.cardNumField:"cardNum",
self.securityField:"security",
self.expYearField:"expYear",
self.expMonthField:"expMonth",
]
//Picker views to show for certain input fields
lazy var expMonthPickerView = UIPickerView()
//The rounded white area of the form that contains padding
//that is animated in
@IBOutlet weak var roundFormArea: UIView!
//Container of fields, contains the validation view (surrounds) which isn't
//the user input field (see the xxField above)
@IBOutlet weak var emailValidationView: AcceptOnUICreditCardValidatableField!
@IBOutlet weak var cardNumValidationView: AcceptOnUICreditCardValidatableField!
@IBOutlet weak var securityValidationView: AcceptOnUICreditCardValidatableField!
@IBOutlet weak var expMonthValidationView: AcceptOnUICreditCardValidatableField!
@IBOutlet weak var expYearValidationView: AcceptOnUICreditCardValidatableField!
lazy var nameToValidationView: [String:AcceptOnUICreditCardValidatableField] = [
"email":self.emailValidationView,
"cardNum":self.cardNumValidationView,
"security":self.securityValidationView,
"expMonth":self.expMonthValidationView,
"expYear":self.expYearValidationView
]
//Bubble that contains credit-card brand to the right inside the cardNumValidationView
@IBOutlet weak var brandPop: AcceptOnCreditCardNumBrandPop!
//Labels above the validation fields
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var cardNumLabel: UILabel!
@IBOutlet weak var securityLabel: UILabel!
@IBOutlet weak var expYearLabel: UILabel!
@IBOutlet weak var expMonthLabel: UILabel!
//Button that says 'pay' at the bottom
@IBOutlet weak var payButton: AcceptOnRoundedButton!
//Order that things are animated in for the flashy intro
lazy var animationInOrder: [UIView] = [
self.emailLabel, self.emailValidationView,
self.cardNumLabel, self.cardNumValidationView,
self.securityLabel, self.securityValidationView,
self.expYearLabel, self.expYearValidationView,
self.expMonthLabel, self.expMonthValidationView,
self.payButton
]
//Formatting of credit-card number
var cardNumberFormatter: CHRTextFieldFormatter!
//Sends back events to a delegate
weak var delegate: AcceptOnCreditCardFormDelegate?
//AcceptOnCreditCardForm.xib root view
var nibView: UIView!
//-----------------------------------------------------------------------------------------------------
//Constructors, Initializers, and UIView lifecycle
//-----------------------------------------------------------------------------------------------------
override init(frame: CGRect) {
super.init(frame: frame)
defaultInit()
}
required init(coder: NSCoder) {
super.init(coder: coder)!
defaultInit()
}
convenience init() {
self.init(frame: CGRectZero)
}
func defaultInit() {
//Initialize AcceptOnCreditCardFormView.xib, sets the alpha to 0
let nib = UINib(nibName: "AcceptOnCreditCardFormView", bundle: AcceptOnBundle.bundle)
let nibInstance = nib.instantiateWithOwner(self, options: nil)
nibView = nibInstance[0] as! UIView
self.addSubview(nibView)
//Install a gesture recognizer that will handle dismissal of the keyboard
let gesture = UITapGestureRecognizer(target: self, action: "viewWasTapped")
gesture.delaysTouchesBegan = false
self.addGestureRecognizer(gesture)
//Set the month field to use a picker
expMonthPickerView.delegate = self
expMonthPickerView.dataSource = self
expMonthField.inputView = expMonthPickerView
//Disables touch input for the fields, they will be forwarded beginFirstResponder when necessary
//via the validation views and have no touch interaction at other times
cardNumValidationView.responderView = cardNumField
emailValidationView.responderView = emailField
expYearValidationView.responderView = expYearField
securityValidationView.responderView = securityField
expMonthValidationView.responderView = expMonthField
//Make our form area rounded
self.roundFormArea.layer.cornerRadius = 15
self.roundFormArea.clipsToBounds = true
//Setup credit-card number formatter
cardNumberFormatter = CHRTextFieldFormatter(textField: cardNumField, mask: CHRCardNumberMask())
//Hide everything until we animate in
self.alpha = 0
for e in animationInOrder { e.alpha = 0 }
}
override func layoutSubviews() {
super.layoutSubviews()
animateIn()
}
var constraintsWereUpdated = false
override func updateConstraints() {
super.updateConstraints()
//Only run custom constraints once
if (constraintsWereUpdated) { return }
constraintsWereUpdated = true
//Make XIB full-screen
nibView.snp_makeConstraints { make in
make.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0))
return
}
}
//-----------------------------------------------------------------------------------------------------
//Animation Helpers
//-----------------------------------------------------------------------------------------------------
var hasAnimatedIn = false //Have we animated in yet?
func animateIn() {
if hasAnimatedIn { return }
hasAnimatedIn = true
dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in
for (idx, elm) in self!.animationInOrder.enumerate() {
elm.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1)
UIView.animateWithDuration(1, delay: NSTimeInterval(idx)/25.0+1, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.CurveEaseOut, animations: {
elm.layer.transform = CATransform3DIdentity
elm.alpha = 1
}, completion: { res in
//Show 'unknown' for the credit-card view
if (elm == self?.cardNumValidationView) {
self?.brandPop.switchToBrandWithName("unknown")
}
})
}
self?.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1)
UIView.animateWithDuration(1, delay: 1, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
self?.layer.transform = CATransform3DIdentity
self?.alpha = 1
}, completion: { res in
})
}
}
//-----------------------------------------------------------------------------------------------------
//Signal / Action Handlers
//-----------------------------------------------------------------------------------------------------
//Dismiss keyboard
func viewWasTapped() {
//Resign all validation fields
for (_, elm) in nameToValidationView.enumerate() {
elm.1.resignFirstResponder()
}
//Notify delegate that we lost the keyboard
self.delegate?.creditCardFormFocusedFieldLostFocus?()
}
//User hit the 'pay' button
@IBAction func payWasClicked(sender: AnyObject) {
viewWasTapped()
delegate?.creditCardFormPayWasClicked?()
}
//-----------------------------------------------------------------------------------------------------
//UITextFieldDelegate Handlers
//-----------------------------------------------------------------------------------------------------
//User updated a form option
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
//We need a field name & it needs to have some value
guard let fieldName = fieldToName[textField] else { return true }
guard let currentString = textField.text as NSString? else { return true }
//Re-calculate string of field based on changes (we can't get the current string because it hasn't updated yet)
let newString = currentString.stringByReplacingCharactersInRange(range, withString: string)
//Card number formatting
if (fieldName == "cardNum") {
if !self.cardNumberFormatter.textField(textField, shouldChangeCharactersInRange: range, replacementString: string) { return false }
}
//Field length maximums, prevent further input
if (fieldName == "security" && (newString as NSString).length > 4) { return false } //Don't allow security field to be more than 4 chars
if (fieldName == "expYear" && (newString as NSString).length > 2) { return false } //Don't allow year field to be more than 2 chars
//Ensure numeric input only
if fieldName == "expYear" || fieldName == "security" {
if Int(newString) == nil { return false }
}
//Don't allow edits through input, only the pop-up
if fieldName == "expMonth" { return false }
//If we reached this point, we can accept the update
self.delegate?.creditCardFormFieldWithName?(fieldName, wasUpdatedToString: newString)
return true
}
//User began editing a text-field
func textFieldDidBeginEditing(textField: UITextField) {
if let textFieldName = fieldToName[textField] {
self.delegate?.creditCardFormFieldWithNameDidFocus?(textFieldName)
} else {
puts("Warning: textField in AcceptOnCreditCardFormView didn't have a name bound")
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
if textField == emailField {
self.cardNumValidationView.viewWasTapped()
}
return true
}
//-----------------------------------------------------------------------------------------------------
//AcceptOnCreditCardFormDelegate handlers
//-----------------------------------------------------------------------------------------------------
//Credit-card type was updated; brands include visa, amex, master_card, discover, etc.
func creditCardNumBrandWasUpdatedWithBrandName(name: String) {
//Notify the bouncy image
brandPop.switchToBrandWithName(name)
//Changes type of number input based on brand, e.g. amex has 4 6 5
(cardNumberFormatter.mask as! CHRCardNumberMask).brand = name
}
//-----------------------------------------------------------------------------------------------------
//UIPickerFieldDelegate & UIPickerFieldDataSource Handlers
//-----------------------------------------------------------------------------------------------------
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
if pickerView == expMonthPickerView {
let values = [
"01 - Jan",
"02 - Feb",
"03 - Mar",
"04 - Apr",
"05 - May",
"06 - Jun",
"07 - July",
"08 - Aug",
"09 - Sep",
"10 - Oct",
"11 - Nov",
"12 - Dec"
]
return NSAttributedString(string: values[row], attributes: nil)
} else {
return nil
}
}
//Ensure the expMonthPicker loads a default value to the UIMachine, because if we don't
//the didSelectRow is not called if the user dosen't change from the default of 01 (Jan)
var expMonthPickerViewDidSetDefault: Bool = false
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == expMonthPickerView {
if (!expMonthPickerViewDidSetDefault) {
expMonthPickerViewDidSetDefault = true
self.delegate?.creditCardFormFieldWithName?("expMonth", wasUpdatedToString: "01")
}
return 12
} else {
return -1
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
if pickerView == expMonthPickerView {
return 1
} else {
return -1
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == expMonthPickerView {
let values = [
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12"
]
let value = values[row]
self.expMonthField.text = value
self.delegate?.creditCardFormFieldWithName?("expMonth", wasUpdatedToString: value)
}
}
//-----------------------------------------------------------------------------------------------------
//External / Delegate Handlers
//-----------------------------------------------------------------------------------------------------
//Adds an error to a field
func showErrorForFieldWithName(name: String, withMessage msg: String) {
nameToValidationView[name]!.error = msg
}
//Removes an error for a field
func hideErrorForFieldWithName(name: String) {
nameToValidationView[name]!.error = nil
}
//An error was changed, or just needs to be 'emphasized' because
//there is already an error. Maybe a user hit 'pay' when a validation
//error was still in effect
func emphasizeErrorForFieldWithName(name: String, withMessage msg: String) {
nameToValidationView[name]!.error = msg
}
//Set a field value (e.g. default email)
func setInitialFieldValueWithName(name: String, withValue value: String) {
switch (name) {
case "email":
emailField.text = value
default:
puts("Unsupported credit-card form field named: \(name)")
}
}
}
| 6a802f350ba9ba388fc546a8469757eb | 41.221932 | 197 | 0.569785 | false | false | false | false |
ejeinc/MetalScope | refs/heads/master | Sources/VideoScene.swift | mit | 1 | //
// VideoScene.swift
// MetalScope
//
// Created by Jun Tanaka on 2017/01/19.
// Copyright © 2017 eje Inc. All rights reserved.
//
#if (arch(arm) || arch(arm64)) && os(iOS)
import SceneKit
import AVFoundation
public protocol VideoScene: class {
var renderer: PlayerRenderer { get }
init(renderer: PlayerRenderer)
}
extension VideoScene {
public var player: AVPlayer? {
get {
return renderer.player
}
set(value) {
renderer.player = value
}
}
public init(device: MTLDevice) {
let renderer = PlayerRenderer(device: device)
self.init(renderer: renderer)
}
public init(device: MTLDevice, outputSettings: [String: Any]) throws {
let renderer = try PlayerRenderer(device: device, outputSettings: outputSettings)
self.init(renderer: renderer)
}
fileprivate var preferredPixelFormat: MTLPixelFormat {
if #available(iOS 10, *) {
return .bgra8Unorm_srgb
} else {
return .bgra8Unorm
}
}
}
public final class MonoSphericalVideoScene: MonoSphericalMediaScene, VideoScene {
private var playerTexture: MTLTexture? {
didSet {
mediaSphereNode.mediaContents = playerTexture
}
}
private lazy var renderLoop: RenderLoop = {
return RenderLoop { [weak self] time in
self?.renderVideo(atTime: time)
}
}()
private let commandQueue: MTLCommandQueue
public let renderer: PlayerRenderer
public override var isPaused: Bool {
didSet {
if isPaused {
renderLoop.pause()
} else {
renderLoop.resume()
}
}
}
public init(renderer: PlayerRenderer) {
self.renderer = renderer
commandQueue = renderer.device.makeCommandQueue()
super.init()
renderLoop.resume()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateTextureIfNeeded() {
guard let videoSize = renderer.itemRenderer.playerItem?.presentationSize, videoSize != .zero else {
return
}
let width = Int(videoSize.width)
let height = Int(videoSize.height)
if let texture = playerTexture, texture.width == width, texture.height == height {
return
}
let device = renderer.device
let pixelFormat = preferredPixelFormat
let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: width, height: height, mipmapped: true)
playerTexture = device.makeTexture(descriptor: descriptor)
}
public func renderVideo(atTime time: TimeInterval, commandQueue: MTLCommandQueue? = nil) {
guard renderer.hasNewPixelBuffer(atHostTime: time) else {
return
}
updateTextureIfNeeded()
guard let texture = playerTexture else {
return
}
do {
let commandBuffer = (commandQueue ?? self.commandQueue).makeCommandBuffer()
try renderer.render(atHostTime: time, to: texture, commandBuffer: commandBuffer)
commandBuffer.commit()
} catch let error as CVError {
debugPrint("[MonoSphericalVideoScene] failed to render video with error: \(error)")
} catch {
fatalError(error.localizedDescription)
}
}
}
public final class StereoSphericalVideoScene: StereoSphericalMediaScene, VideoScene {
private var playerTexture: MTLTexture?
private var leftSphereTexture: MTLTexture? {
didSet {
leftMediaSphereNode.mediaContents = leftSphereTexture
}
}
private var rightSphereTexture: MTLTexture? {
didSet {
rightMediaSphereNode.mediaContents = rightSphereTexture
}
}
private lazy var renderLoop: RenderLoop = {
return RenderLoop { [weak self] time in
self?.renderVideo(atTime: time)
}
}()
private let commandQueue: MTLCommandQueue
public let renderer: PlayerRenderer
public override var isPaused: Bool {
didSet {
if isPaused {
renderLoop.pause()
} else {
renderLoop.resume()
}
}
}
public init(renderer: PlayerRenderer) {
self.renderer = renderer
commandQueue = renderer.device.makeCommandQueue()
super.init()
renderLoop.resume()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateTexturesIfNeeded() {
guard let videoSize = renderer.itemRenderer.playerItem?.presentationSize, videoSize != .zero else {
return
}
let width = Int(videoSize.width)
let height = Int(videoSize.height)
if let texture = playerTexture, texture.width == width, texture.height == height {
return
}
let device = renderer.device
let pixelFormat = preferredPixelFormat
let playerTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: width, height: height, mipmapped: true)
playerTexture = device.makeTexture(descriptor: playerTextureDescriptor)
let sphereTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: width, height: height / 2, mipmapped: true)
leftSphereTexture = device.makeTexture(descriptor: sphereTextureDescriptor)
rightSphereTexture = device.makeTexture(descriptor: sphereTextureDescriptor)
}
public func renderVideo(atTime time: TimeInterval, commandQueue: MTLCommandQueue? = nil) {
guard renderer.hasNewPixelBuffer(atHostTime: time) else {
return
}
updateTexturesIfNeeded()
guard let playerTexture = playerTexture else {
return
}
let commandBuffer = (commandQueue ?? self.commandQueue).makeCommandBuffer()
do {
try renderer.render(atHostTime: time, to: playerTexture, commandBuffer: commandBuffer)
func copyPlayerTexture(region: MTLRegion, to sphereTexture: MTLTexture) {
let blitCommandEncoder = commandBuffer.makeBlitCommandEncoder()
blitCommandEncoder.copy(
from: playerTexture,
sourceSlice: 0,
sourceLevel: 0,
sourceOrigin: region.origin,
sourceSize: region.size,
to: sphereTexture,
destinationSlice: 0,
destinationLevel: 0,
destinationOrigin: MTLOrigin(x: 0, y: 0, z: 0)
)
blitCommandEncoder.endEncoding()
}
let halfHeight = playerTexture.height / 2
if let leftTexture = leftSphereTexture {
let leftSphereRegion = MTLRegionMake2D(0, 0, playerTexture.width, halfHeight)
copyPlayerTexture(region: leftSphereRegion, to: leftTexture)
}
if let rightTexture = rightSphereTexture {
let rightSphereRegion = MTLRegionMake2D(0, halfHeight, playerTexture.width, halfHeight)
copyPlayerTexture(region: rightSphereRegion, to: rightTexture)
}
commandBuffer.commit()
} catch let error as CVError {
debugPrint("[StereoSphericalVideoScene] failed to render video with error: \(error)")
} catch {
fatalError(error.localizedDescription)
}
}
}
#endif
| 560c53f5ce928f74f7e4e7560b0d5317 | 29.804781 | 155 | 0.618857 | false | false | false | false |
LipliStyle/Liplis-iOS | refs/heads/master | Liplis/LiplisWidget.swift | mit | 1 | //
// LiplisWidget.swift
// Liplis
//
// ウィジェットのインスタンス
// ウィジェットの立ち絵、ウインドウ、アイコン等の像イメージを管理し、
// 文字の送り制御、立ち絵の切り替え制御まで行う。
//
//アップデート履歴
// 2015/04/11 ver0.1.0 作成
// 2015/05/09 ver1.0.0 リリース
// 2015/05/12 ver1.1.0 リファクタリング
// 2015/05/19 ver1.4.0 Swift1.2対応
// 2015/05/19 ver1.4.1 会話中にすぐに通常おしゃべりに戻るバグ修正
// 2015/12/18 ver1.5.0 Swift2.0対応
//
// Created by sachin on 2015/04/11.
// Copyright (c) 2015年 sachin. All rights reserved.
//
import UIKit
import Foundation
class LiplisWidget : NSObject {
//=================================
//画面要素
internal var lblLpsTalkLabel: UILabel!
internal var imgWindow: UIImageView! //ウインドウ
internal var imgBody: UIImageView! //本体画像
internal var icoSleep : UIButton! //おやすみアイコン
internal var icoLog : UIButton! //回想アイコン
internal var icoSetting : UIButton! //設定アイコン
internal var icoChat : UIButton! //会話アイコン
internal var icoClock : UIButton! //時計アイコン
internal var icoBattery : UIButton! //バッテリーアイコン
internal var imgClockBase: UIImageView! //時計本体画像
internal var imgClockLongHand: UIImageView! //時計長針
internal var imgClockShortHand: UIImageView! //時計短針
internal var frame : CGRect! //ウィジェットのレクトアングル
//=================================
//XMLオブジェクト
internal var lpsSkinData : LiplisSkinData!
internal var lpsBody : ObjLiplisBody!
internal var lpsChat : ObjLiplisChat!
internal var lpsIcon : ObjLiplisIcon!
internal var lpsSkin : ObjLiplisSkin!
internal var lpsTouch : ObjLiplisTouch!
internal var lpsVer : ObjLiplisVersion!
//=================================
//ロードボディオブジェクト
internal var ob : ObjBody!
//=================================
//キャラクター設定
internal var os : ObjPreference!
//=================================
//デスクトップインスタンス
internal var desk:ViewDeskTop!
//=================================
//ニュースインスタンス
internal var lpsNews : LiplisNews!
internal var lpsBattery : ObjBattery!
internal var lpsChatTalk : LiplisApiChat!
//=================================
//タイマー
internal var updateTimer : NSTimer!
internal var nextTimer : NSTimer!
internal var startMoveTimer : NSTimer!
internal var flgAlarm : Int! = 0
//=================================
//制御プロパティ
internal var liplisNowTopic : MsgShortNews! //現在ロードおしゃべりデータ
internal var liplisNowWord : String = "" //ロード中の単語
internal var liplisChatText : String = "" //テキストバッファ
internal var liplisUrl : String = "" //現在ロード中の記事のURL
internal var cntLct : Int! = 0 //チャットテキストカウント
internal var cntLnw : Int! = 0 //ナウワードカウント
internal var nowPoint : Int! = 0 //現在感情レベル
internal var nowPos : Int! = 0 //現在品詞
internal var nowEmotion : Int! = 0 //現在感情
internal var prvEmotion : Int! = 0 //前回感情
internal var cntMouth : Int! = 0 //口パクカウント
internal var cntBlink : Int! = 0 //まばたきカウント
internal var nowBlink : Int! = 0 //現在目のオープン状態
internal var prvBlink : Int! = 0 //1つ前の目のオープン状態
internal var nowDirection : Int! = 0 //現在の方向
internal var prvDirection : Int = 0 //1つ前の方向
internal var cntSlow : Int! = 0 //スローカウント
//=================================
//制御フラグ
internal var flgConnect : Bool = false //接続フラグ
internal var flgBodyChencge : Bool = false //ボディ変更フラグ
internal var flgChatting : Bool = false //おしゃべり中フラグ
internal var flgSkip : Bool = false //スキップフラグ
internal var flgSkipping : Bool = false //スキップ中フラグ
internal var flgSitdown : Bool = false //おすわり中フラグ
internal var flgThinking : Bool = false //考え中フラグ
internal var flgEnd : Bool = false //おしゃべり終了フラグ
internal var flgTag : Bool = false //タグチェック
internal var flgChatTalk : Bool = false //
internal var flgDebug : Bool = false //
internal var flgOutputDemo : Bool = false //
///=====================================
/// 設定値
//NOTE : liplisRefreshRate * liplisRate = 更新間隔 (updateCntに関連)
internal var liplisInterval : Int! = 100; //インターバル
internal var liplisRefresh : Int! = 10; //リフレッシュレート
///=====================================
/// 時報制御
internal var prvHour : Int = 0
//============================================================
//
//初期化処理
//
//============================================================
/**
デフォルトイニシャライザ
*/
internal init(desk:ViewDeskTop!, os : ObjPreference, lpsSkinData : LiplisSkinData!)
{
//スーパーイニット
super.init()
//設定データ
self.os = os
//デスクトップクラス取得
self.desk = desk
//スキンデータ取得
self.lpsSkinData = lpsSkinData
//XMLの読み込み
self.initXml()
//クラスの初期化
self.initClass()
//ビューの初期化
self.initView()
//あいさつ
self.greet()
}
/*
画面要素の初期化
*/
internal func initView()
{
// UIImageViewを作成する.
self.lblLpsTalkLabel = UILabel(frame: CGRectMake(0, 0, 140, 60))
self.imgWindow = UIImageView(frame: CGRectMake(0,0,150,60))
self.imgBody = UIImageView(frame: CGRectMake(0,0,self.lpsBody.widthReal,self.lpsBody.heightReal))
self.icoSleep = UIButton(frame: CGRectMake(0,0,32,32))
self.icoLog = UIButton(frame: CGRectMake(0,0,32,32))
self.icoSetting = UIButton(frame: CGRectMake(0,0,32,32))
self.icoChat = UIButton(frame: CGRectMake(0,0,32,32))
self.icoClock = UIButton(frame: CGRectMake(0,0,32,32))
self.icoBattery = UIButton(frame: CGRectMake(0,0,32,32))
self.imgClockBase = UIImageView(frame: CGRectMake(0,0,32,32))
self.imgClockLongHand = UIImageView(frame: CGRectMake(0,0,32,32))
self.imgClockShortHand = UIImageView(frame: CGRectMake(0,0,32,32))
// 画像をUIImageViewに設定する.
self.imgBody.image = UIImage(named: lpsBody.normalList[0].eye_1_c)
self.icoSleep.setImage(lpsIcon.imgSleep,forState : UIControlState.Normal)
self.icoLog.setImage(lpsIcon.imgLog, forState: UIControlState.Normal)
self.icoSetting.setImage(lpsIcon.imgSetting, forState: UIControlState.Normal)
self.icoChat.setImage(lpsIcon.imgIntro, forState: UIControlState.Normal)
self.icoClock.setImage(lpsIcon.imgBack, forState: UIControlState.Normal)
self.icoBattery.setImage(lpsIcon.imgBattery_100, forState: UIControlState.Normal)
self.imgClockBase.image = desk.imgClockBase
self.imgClockLongHand.image = desk.imgClockLongHand
self.imgClockShortHand.image = desk.imgClockShortHand
//ウインドウイメージのセット
self.setWindow()
//ラベル設定
self.lblLpsTalkLabel.text = "" //初期テキスト 空
self.lblLpsTalkLabel.font = UIFont.systemFontOfSize(10) //フォントサイズ
self.lblLpsTalkLabel.numberOfLines = 6 //行数 6
// 画像の表示する座標を指定する. 初期表示 暫定中央
self.imgBody.layer.position = CGPoint(x: os.locationX, y: os.locationY)
self.setWidgetLocation(-10, windowOffsetY: 5)
//イベントハンドラマッピング
self.icoSleep.addTarget(self, action: "onDownIcoSleep:", forControlEvents: .TouchDown)
self.icoSleep.addTarget(self, action: "onUpIcoSleep:", forControlEvents: [.TouchUpInside, .TouchUpOutside])
self.icoLog.addTarget(self, action: "onDownIcoLog:", forControlEvents: .TouchDown)
self.icoLog.addTarget(self, action: "onUpIcoLog:", forControlEvents: [.TouchUpInside, .TouchUpOutside])
self.icoSetting.addTarget(self, action: "onDownIcoSetting:", forControlEvents: .TouchDown)
self.icoSetting.addTarget(self, action: "onUpIcoSetting:", forControlEvents: [.TouchUpInside, .TouchUpOutside])
self.icoChat.addTarget(self, action: "onDownIcoChat:", forControlEvents: .TouchDown)
self.icoChat.addTarget(self, action: "onUpIcoChat:", forControlEvents: [.TouchUpInside, .TouchUpOutside])
self.icoClock.addTarget(self, action: "onDownIoClock:", forControlEvents: .TouchDown)
self.icoClock.addTarget(self, action: "onUpIoClock:", forControlEvents: [.TouchUpInside, .TouchUpOutside])
self.icoBattery.addTarget(self, action: "onDownIcoBattery:", forControlEvents: .TouchDown)
self.icoBattery.addTarget(self, action: "onUpIcoBattery:", forControlEvents: [.TouchUpInside, .TouchUpOutside])
//要素の登録はデスクトップで行う
self.desk.registWidget(self)
//時計設定
self.setClock()
}
/*
XML読み込み
オーバーライドが必要
*/
internal func initXml()
{
//ボディインスタンス
self.lpsSkin = self.lpsSkinData.lpsSkin
self.lpsChat = ObjLiplisChat(url:self.lpsSkinData.xmlChat)
self.lpsBody = ObjLiplisBody(url:self.lpsSkinData.xmlBody, bodyPath: self.lpsSkinData.pathBody)
self.lpsTouch = ObjLiplisTouch(url:self.lpsSkinData.xmlTouch)
self.lpsVer = ObjLiplisVersion(url:self.lpsSkinData.xmlVersion)
self.lpsIcon = ObjLiplisIcon(windowPath: self.lpsSkinData.pathWindow)
}
/*
クラスの初期化
*/
internal func initClass()
{
//デフォルトボディロード
self.ob = lpsBody.getDefaultBody()
//ニュースの初期化
self.lpsNews = LiplisNews()
//話題収集の実行
self.onCheckNewsQueue()
//バッテリーオブジェクトの初期化
self.lpsBattery = ObjBattery()
//チャットAPIインスタンス
self.lpsChatTalk = LiplisApiChat()
}
/*
チャット情報の初期化
*/
internal func initChatInfo()
{
//チャットテキストの初期化
self.liplisChatText = ""
//なうワードの初期化
self.liplisNowWord = ""
//ナウ文字インデックスの初期化
self.cntLct = 0
//ナウワードインデックスの初期化
self.cntLnw = 0
}
/*
ウインドウのセット
オーバーライドが必要
*/
internal func setWindow()
{
//スキンのウインドウファイルにアクセス
self.imgWindow.image = UIImage(contentsOfFile: self.lpsSkinData.pathWindow + "/" + os.lpsWindowColor)
}
/*
時計のセット
*/
internal func setClock()
{
//現在日時取得
let date : LiplisDate = LiplisDate()
//時計イメージ取得
self.imgClockLongHand.image = self.desk.imgClockLongHand
self.imgClockShortHand.image = self.desk.imgClockShortHand
//現在分の計算
let dblkeikaMin : Double = Double(60 * date.hour! + date.minute!)
let dblMin : Double = Double(date.minute!)
//角度の計算
let argHour = CGFloat((2 * M_PI * dblkeikaMin) / (60 * 12))
let argMin = CGFloat((2 * M_PI * dblMin)/60)
//時計セット
self.imgClockShortHand.transform = CGAffineTransformMakeRotation(argHour)
self.imgClockLongHand.transform = CGAffineTransformMakeRotation(argMin)
}
//============================================================
//
//終了処理
//
//============================================================
deinit
{
dispose()
}
/*
破棄
*/
internal func dispose()
{
//プリファレンスの破棄
self.os.delPreference()
//タイマー停止
self.stopNextTimer()
self.stopUpdateTimer()
//イメージの破棄
if self.imgWindow != nil {self.imgWindow.image = nil}
if self.imgBody != nil {self.imgBody.image = nil}
if self.icoSleep != nil {self.icoSleep.setImage(nil,forState : UIControlState.Normal)}
if self.icoLog != nil {self.icoLog.setImage(nil ,forState: UIControlState.Normal)}
if self.icoSetting != nil {self.icoSetting.setImage(nil, forState: UIControlState.Normal)}
if self.icoChat != nil {self.icoChat.setImage(nil, forState: UIControlState.Normal)}
if self.icoClock != nil {self.icoClock.setImage(nil, forState: UIControlState.Normal)}
if self.icoBattery != nil {self.icoBattery.setImage(nil, forState: UIControlState.Normal)}
if self.imgClockBase != nil {self.imgClockBase.image = nil}
if self.imgClockLongHand != nil {self.imgClockLongHand.image = nil}
if self.imgClockShortHand != nil {self.imgClockShortHand.image = nil}
//要素の破棄
self.lblLpsTalkLabel = nil
self.imgWindow = nil
self.imgBody = nil
self.icoSleep = nil
self.icoClock = nil
self.icoLog = nil
self.icoSetting = nil
self.icoChat = nil
self.icoBattery = nil
self.imgClockBase = nil
self.imgClockLongHand = nil
self.imgClockShortHand = nil
//タイマーの破棄
self.nextTimer = nil
self.updateTimer = nil
}
//============================================================
//
//タイマー処理
//
//============================================================
/*
アップデートタイマースタート
*/
internal func startUpdateTimer()
{
//すでに動作中なら破棄しておく
self.stopUpdateTimer()
//タイマースタート
self.updateTimer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: "onUpdate:", userInfo: nil, repeats: true)
}
internal func stopUpdateTimer()
{
//すでに起動していたら破棄する
if self.updateTimer != nil && self.updateTimer.valid
{
self.updateTimer.invalidate()
}
}
/*
ネクストタイマースタート
*/
internal func startNextTimer(pInterval : Double)
{
//すでに動作中なら破棄しておく
self.stopNextTimer()
//タイマースタート
self.nextTimer = NSTimer.scheduledTimerWithTimeInterval(pInterval, target: self, selector : "onNext:", userInfo: nil, repeats: true)
}
internal func stopNextTimer()
{
//すでに起動していたら破棄する
if self.nextTimer != nil && self.nextTimer.valid
{
self.nextTimer.invalidate()
}
}
/*
ドラッグ移動開始タイマー
*/
internal func startStartMoveTimer()
{
//すでに動作中なら破棄しておく
self.stopStartMoveTimer()
//タイマースタート
self.startMoveTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector : "onstartMove:", userInfo: nil, repeats: true)
}
internal func stopStartMoveTimer()
{
//すでに起動していたら破棄する
if self.startMoveTimer != nil && self.startMoveTimer.valid
{
self.startMoveTimer.invalidate()
}
}
/*
おしゃべりタイマー
10秒間隔で実行
おしゃべり中は停止する
*/
internal func onNext(timer : NSTimer)
{
//アイコン表示オフなら、アイコンを消去する
if self.os.lpsDisplayIcon == 0
{
self.iconOff()
}
//次の話題
self.nextLiplis()
}
/*
おしゃべりタイマー
0.1間隔で実行
*/
internal func onUpdate(timer : NSTimer)
{
//おしゃべり中なら、Liplisアップデート
if(self.flgAlarm == 12)
{
self.updateLiplis()
}
}
/*
アップデートカウントのリセット
*/
func reSetUpdateCount()
{
//無口の場合はタイマーを更新しない
if self.os.lpsMode == 3
{
//すでに動作中なら破棄しておく
self.stopNextTimer()
return
}
//チャットトーク時は、60秒のインターバルを設定
if !self.flgChatTalk
{
self.startNextTimer(self.os.lpsInterval)
}
else
{
self.startNextTimer(60.0)
}
}
/*
ドラッグ移動開始タイマー
タップしてから3秒後に実行
*/
internal func onstartMove(timer : NSTimer)
{
//移動可能にする
self.startMove()
//移動開始タイマーを破棄
self.stopStartMoveTimer()
}
//============================================================
//
//イベントハンドラ
//
//============================================================
/*
タッチ開始イベント
*/
internal func touchesBegan(touches: NSSet)->Bool {
//フレーム取得
let frameImgBody: CGRect = self.imgBody.frame
// タッチイベントを取得.
let aTouch = touches.anyObject() as! UITouch
// タッチ位置の取得
let location = aTouch.locationInView(self.imgBody)
//範囲チェック
if((location.x >= 0 && location.x <= frameImgBody.width) && (location.y >= 0 && location.y <= frameImgBody.height))
{
//アニメーション
UIView.animateWithDuration(0.06,
// アニメーション中の処理(縮小)
animations: { () -> Void in
self.imgBody.transform = CGAffineTransformMakeScale(0.9, 0.9)
})
{ (Bool) -> Void in}
//移動制御タイマー開始
self.startStartMoveTimer()
return true
}
//ウインドウフレーム取得
let frameImgWindow : CGRect = imgWindow.frame
//ウインドウクリックモードチェック
//down時はアニメーションのみ
if(self.desk.baseSetting.lpsTalkWindowClickMode == 1)
{
//ウインドウタッチ位置の取得
let locationWindow = aTouch.locationInView(imgWindow)
//ウインドウタッチ位置チェック
if((locationWindow.x >= 0 && locationWindow.x <= frameImgWindow.width) && (locationWindow.y >= 0 && locationWindow.y <= frameImgWindow.height))
{
UIView.animateWithDuration(0.06,
animations: { () -> Void in
self.imgWindow.transform = CGAffineTransformMakeScale(0.9, 0.9)
})
return true
}
}
return false
}
/*
ドラッグイベント
*/
internal func touchesMoved(touches: NSSet)->Bool {
if(desk.flgMoving)
{
// タッチイベントを取得.
let aTouch = touches.anyObject() as! UITouch
//ボディフレーム
let frameImgBody : CGRect = imgBody.frame
// 移動した先の座標を取得.
let location = aTouch.locationInView(imgBody)
if((location.x >= 0 && location.x <= frameImgBody.width) && (location.y >= 0 && location.y <= frameImgBody.height))
{
//移動する前の座標を取得.
let prevLocation = aTouch.previousLocationInView(imgBody)
//移動量計算
let deltaX: CGFloat = location.x - prevLocation.x
let deltaY: CGFloat = location.y - prevLocation.y
// 移動した分の距離をmyFrameの座標にプラスする.
self.imgBody.frame.origin.x += deltaX
self.imgBody.frame.origin.y += deltaY
//ほかパーツの追随
self.setWidgetLocation(0,windowOffsetY : 0)
return true
}
}
return false
}
/*
タッチ終了イベント
*/
internal func touchesEnded(touches: NSSet)->Bool {
//フレーム取得
let frameImgBody : CGRect = imgBody.frame
//タッチイベントを取得.
let aTouch = touches.anyObject() as! UITouch
//タッチ位置取得
let location = aTouch.locationInView(imgBody)
//タッチ範囲チェック
if(location.x >= 0 && location.x <= frameImgBody.width) && (location.y >= 0 && location.y <= frameImgBody.height)
{
//タッチ位置保存
self.saveLocation()
//アニメーション.
UIView.animateWithDuration(0.1,
// アニメーション中の処理(縮小して拡大)
animations: { () -> Void in
self.imgBody.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.imgBody.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
//クリックイベント
self.onClickBody()
//レスキュー
if self.desk.baseSetting.lpsAutoRescue == 1
{
rescue(40)
}
//移動終了
self.desk.flgMoving = false
//移動制御タイマーを破棄しておく
self.stopStartMoveTimer()
return true
}
//ウインドウフレーム取得
let frameImgWindow : CGRect = imgWindow.frame
//ウインドウクリック設定が有効なら、ウインドウ範囲チェックを行う
if(self.desk.baseSetting.lpsTalkWindowClickMode == 1)
{
//タッチ位置の表示
let locationWindow = aTouch.locationInView(imgWindow)
//ウインドウ範囲チェック
if((locationWindow.x >= 0 && locationWindow.x <= frameImgWindow.width) && (locationWindow.y >= 0 && locationWindow.y <= frameImgWindow.height))
{
UIView.animateWithDuration(0.06,
animations: { () -> Void in
self.imgWindow.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.imgWindow.transform = CGAffineTransformMakeScale(1.0, 1.0)
self.onClickWindow()
})
return true
}
}
return false
}
/*
各パーツをボディに追随させる
*/
internal func setWidgetLocation(offsetY : CGFloat, windowOffsetY : CGFloat)
{
//ボディフレーム
let frameImgBody : CGRect = imgBody.frame
var frameImgWindow : CGRect = imgWindow.frame
var frameLblTalkLabel : CGRect = lblLpsTalkLabel.frame
var frameIcoSleep: CGRect = icoSleep.frame
var frameIcoLog: CGRect = icoLog.frame
var frameIcoSetting: CGRect = icoSetting.frame
var frameIcoChat: CGRect = icoChat.frame
var frameIcoClock: CGRect = icoClock.frame
var frameIcoBattery: CGRect = icoBattery.frame
frameImgWindow.origin.x = frameImgBody.origin.x - frameImgWindow.width/2 + frameImgBody.width/2
frameImgWindow.origin.y = frameImgBody.origin.y - 45 + windowOffsetY
frameLblTalkLabel.origin.x = frameImgBody.origin.x - frameImgWindow.width/2 + frameImgBody.width/2 + 5
frameLblTalkLabel.origin.y = frameImgBody.origin.y - 45 + windowOffsetY
frameIcoSleep.origin.x = frameImgWindow.origin.x
frameIcoSleep.origin.y = frameImgBody.origin.y + frameImgBody.height - 112 + offsetY
frameIcoLog.origin.x = frameImgWindow.origin.x
frameIcoLog.origin.y = frameImgBody.origin.y + frameImgBody.height - 72 + offsetY
frameIcoSetting.origin.x = frameImgWindow.origin.x
frameIcoSetting.origin.y = frameImgBody.origin.y + frameImgBody.height - 32 + offsetY
frameIcoChat.origin.x = frameImgWindow.origin.x + frameImgWindow.width-32
frameIcoChat.origin.y = frameImgBody.origin.y + frameImgBody.height - 112 + offsetY
frameIcoClock.origin.x = frameImgWindow.origin.x + frameImgWindow.width-32
frameIcoClock.origin.y = frameImgBody.origin.y + frameImgBody.height-72 + offsetY
frameIcoBattery.origin.x = frameImgWindow.origin.x + frameImgWindow.width-32
frameIcoBattery.origin.y = frameImgBody.origin.y + frameImgBody.height - 32 + offsetY
//移動したフレーム値を反映
self.imgWindow.frame = frameImgWindow
self.lblLpsTalkLabel.frame = frameLblTalkLabel
self.imgClockBase.frame = frameIcoClock
self.imgClockLongHand.frame = frameIcoClock
self.imgClockShortHand.frame = frameIcoClock
self.icoSleep.frame = frameIcoSleep
self.icoLog.frame = frameIcoLog
self.icoSetting.frame = frameIcoSetting
self.icoChat.frame = frameIcoChat
self.icoClock.frame = frameIcoClock
self.icoBattery.frame = frameIcoBattery
//レクトの設定
self.frame = CGRect(x: frameImgWindow.origin.x, y: frameImgWindow.origin.y, width: frameImgWindow.width, height: frameIcoSetting.origin.y + frameIcoSetting.height - frameImgWindow.origin.y)
}
/*
移動開始処理
*/
internal func startMove()
{
//アニメーション
UIView.animateWithDuration(0.06,
animations: { () -> Void in
self.imgBody.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.imgBody.transform = CGAffineTransformMakeScale(1.0, 1.0)
self.imgBody.transform = CGAffineTransformMakeScale(0.9, 0.9)
})
//ウィジェットを最前面に移動する
self.goToTheFront()
//移動開始
self.self.desk.flgMoving = true
desk.onDragTrashBegin()
}
/*
ボディクリック時処理
*/
internal func onClickBody()
{
//チャット中チェック
if(!self.flgChatting)
{
//チャット中でなければ、次の話題おしゃべり
self.nextLiplis()
}
else
{
//チャット中ならスキップする
self.flgSkip = true
}
//アイコンを有効にする
self.iconOn()
//時計合わせ
self.setClock()
}
/*
ウインドウクリック時処理
*/
internal func onClickWindow()
{
if(self.liplisUrl != "")
{
if self.desk.baseSetting.lpsBrowserMode == 0
{
//URL設定
self.desk.app.activityWeb.url = NSURL(string: self.liplisUrl)!
//タブ移動
self.desk.tabBarController?.selectedIndex=4
}
else if self.desk.baseSetting.lpsBrowserMode == 1
{
let nurl = NSURL(string: liplisUrl)
if UIApplication.sharedApplication().canOpenURL(nurl!){
UIApplication.sharedApplication().openURL(nurl!)
}
}
else if desk.baseSetting.lpsBrowserMode == 2
{
//URL設定
self.desk.desktopWebSetUrl(self.liplisUrl)
}
}
}
/*
おやすみボタン押下時処理
*/
internal func onClickSleep()
{
//おやすみチェック
if self.flgSitdown
{
//おやすみ中なら、起こす
self.wakeup()
}
else
{
//通常なら、おやすみ
self.sleep()
}
}
/*
ウィジェットをデスクトップ内に復帰させる
*/
internal func rescue(offset : Int)
{
//X軸範囲チェック
if self.frame.origin.x < CGFloat(offset * -1) //-40
{
self.imgBody.frame.origin.x = 10 + (self.imgWindow.frame.width/2 - self.imgBody.frame.width/2)
}
else if self.frame.origin.x >= self.desk.view.frame.width - self.frame.width + CGFloat(offset) //40
{
self.imgBody.frame.origin.x = self.desk.view.frame.width - self.frame.width + (self.imgWindow.frame.width/2 - self.imgBody.frame.width/2) - 10
}
//Y軸範囲チェック
if self.frame.origin.y < CGFloat(offset * -1) //-40
{
self.imgBody.frame.origin.y = 50
}
else if self.frame.origin.y > self.desk.view.frame.height - self.frame.height + CGFloat(offset/2) //20
{
self.imgBody.frame.origin.y = self.desk.view.frame.height - self.frame.height - 80
}
//パーツの位置調整
self.setWidgetLocation(-10, windowOffsetY: 5)
//座標セーブ
self.saveLocation()
}
/*
座標をセーブルする
*/
internal func saveLocation()
{
self.os.locationX = Int(self.imgBody.layer.position.x)
self.os.locationY = Int(self.imgBody.layer.position.y)
self.os.saveSetting()
}
//============================================================
//
//ボタンイベント
//
//============================================================
/*
スリープボタンイベント
*/
internal func onDownIcoSleep(sender: UIButton){
UIView.animateWithDuration(0.06,animations: { () -> Void in
self.icoSleep.transform = CGAffineTransformMakeScale(0.9, 0.9)
})
onClickSleep()
}
internal func onUpIcoSleep(sender: UIButton){
UIView.animateWithDuration(0.1,animations: { () -> Void in
self.icoSleep.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.icoSleep.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
}
/*
ログボタンイベント
*/
internal func onDownIcoLog(sender: UIButton){
UIView.animateWithDuration(0.06,animations: { () -> Void in
self.icoLog.transform = CGAffineTransformMakeScale(0.9, 0.9)
})
}
internal func onUpIcoLog(sender: UIButton){
UIView.animateWithDuration(0.1,animations: { () -> Void in
self.icoLog.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.icoLog.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
//タブ移動 ログ画面
self.desk.tabBarController?.selectedIndex=3
}
/*
設定ボタンイベント
*/
internal func onDownIcoSetting(sender: UIButton){
UIView.animateWithDuration(0.06,animations: { () -> Void in
self.icoSetting.transform = CGAffineTransformMakeScale(0.9, 0.9)
})
}
internal func onUpIcoSetting(sender: UIButton){
UIView.animateWithDuration(0.1,animations: { () -> Void in
self.icoSetting.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.icoSetting.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
//ウィジェット設定メニュー呼び出し
self.callWidgetSetting()
}
/*
チャットボタンイベント
*/
internal func onDownIcoChat(sender: UIButton){
UIView.animateWithDuration(0.06,animations: { () -> Void in
self.icoChat.transform = CGAffineTransformMakeScale(0.9, 0.9)
})
}
internal func onUpIcoChat(sender: UIButton){
UIView.animateWithDuration(0.1,animations: { () -> Void in
self.icoChat.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.icoChat.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
//おしゃべり画面呼び出し
self.callChat()
}
/*
クロックボタンイベント
*/
internal func onDownIoClock(sender: UIButton){
UIView.animateWithDuration(0.06,animations: { () -> Void in
self.icoClock.transform = CGAffineTransformMakeScale(0.9, 0.9)
})
//時刻おしゃべり
self.clockInfo()
}
internal func onUpIoClock(sender: UIButton){
UIView.animateWithDuration(0.1,animations: { () -> Void in
self.icoClock.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.icoClock.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
}
/*
バッテリーボタンイベント
*/
internal func onDownIcoBattery(sender: UIButton){
UIView.animateWithDuration(0.06,animations: { () -> Void in
self.icoBattery.transform = CGAffineTransformMakeScale(0.9, 0.9)
})
//バッテリー情報おしゃべり
self.batteryInfo()
}
internal func onUpIcoBattery(sender: UIButton){
UIView.animateWithDuration(0.1,animations: { () -> Void in
self.icoBattery.transform = CGAffineTransformMakeScale(0.4, 0.4)
self.icoBattery.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
}
//============================================================
//
//定型おしゃべり
//
//============================================================
/*
挨拶
*/
internal func greet()
{
self.liplisNowTopic = self.lpsChat.getGreet()
if self.liplisNowTopic.getMessage() == ""
{
self.liplisNowTopic = MsgShortNews(name: "なうろーでぃんぐ♪",emotion: 0,point: 0)
}
//チャット情報の初期化
self.initChatInfo()
//チャットスタート
self.chatStart()
}
/*
バッテリー情報おしゃべり
*/
internal func batteryInfo()
{
//座り中なら回避
if(self.flgSitdown){return}
//挨拶の選定
self.liplisNowTopic = self.lpsChat.getBatteryInfo(Int(self.lpsBattery.batteryNowLevel * 100))
//チャット情報の初期化
self.initChatInfo()
//チャットスタート
self.chatStart()
}
/*
時刻情報おしゃべり
*/
internal func clockInfo()
{
//座り中なら回避
if(self.flgSitdown){return}
//挨拶の選定
self.liplisNowTopic = self.lpsChat.getClockInfo()
//チャット情報の初期化
self.initChatInfo()
//チャットスタート
self.chatStart()
}
/*
時報チェック
*/
internal func onTimeSignal()->Bool
{
var result : Bool = false
//現在時間取得
let nowHour : Int = self.getHour()
if(nowHour != self.prvHour)
{
//座り中なら回避
if(self.flgSitdown){return false}
//時報取得
self.liplisNowTopic = self.lpsChat.getTimeSignal(nowHour)
//時報データが無い場合は時報をおしゃべりしない
if self.liplisNowTopic == nil
{
self.prvHour = self.getHour()
return false
}
//チャット情報の初期化
self.initchatInfo()
//おしゃべりスタート
self.chatStart()
result = true
}
//前回時刻のセット
self.prvHour = self.getHour()
return result
}
/*
時刻取得
*/
internal func getHour()->Int{
let date : LiplisDate = LiplisDate()
return date.hour!
}
/*
話しかけ取得
*/
internal func chatTalkRecive(chatText : String)
{
//座り中なら回避
if(self.flgSitdown){return}
self.flgChatTalk = true
//挨拶の選定
self.liplisNowTopic = lpsChatTalk.apiPost(self.desk.baseSetting.lpsUid, toneUrl: self.lpsSkin.tone,version: "I" + LiplisUtil.getAppVersion(),sentence: chatText)
//チャット情報の初期化
self.initChatInfo()
//チャットスタート
self.chatStart()
}
//============================================================
//
//おしゃべり準備処理
//
//============================================================
/*
チャット情報の初期化
*/
internal func initchatInfo()
{
//チャットテキストの初期化
self.liplisChatText = ""
//ナウワードの初期化
self.liplisNowWord = ""
//ナウ文字インデックスの初期化
self.cntLct = 0
//なうワードインデックスの初期化
self.cntLnw = 0
}
/*
話題残量チェック
*/
internal func checkRunout()->Bool
{
return (self.os.lpsNewsRunOut == 1) && self.lpsNews.checkNewsQueueCount(self.getPostDataForLiplisNewsList())
}
//============================================================
//
//おしゃべり処理
//
//============================================================
/*
次の話題
*/
internal func nextLiplis()
{
self.flgAlarm = 0
//バッテリーチェック
self.icoBattery.setImage(self.lpsIcon.getBatteryIcon(self.lpsBattery.getBatteryRatel()), forState: UIControlState.Normal)
//おすわりチェック
if(self.flgSitdown){
self.stopNextTimer()
self.stopUpdateTimer()
return
}
//URLの初期化
self.liplisUrl = ""
//モードチェック
if(self.os.lpsMode == 0 || self.os.lpsMode == 1 || self.os.lpsMode == 2)
{
//時報チェック
if(self.onTimeSignal())
{
return
}
//話題がつきたかチェック
if(self.checkRunout())
{
//再カウント
reSetUpdateCount()
return
}
//次の話題おしゃべり
self.runLiplis()
}
else if(self.os.lpsMode == 3)
{
self.runLiplis()
}
else if(self.os.lpsMode == 4)
{
//時計&バッテリー(ios版ではなし)
}
}
/*
次の話題スタート
*/
internal func runLiplis()
{
//チャット中なら終了する
if(self.flgChatting){self.chatStop();return}
//座り中なら回避
if(self.flgSitdown){self.chatStop();return}
//ウインドウチェック ウインドウが消える仕様は保留する
//windowsOn()
//クロックチェック
//ios版では時計表示なし
//アイコンカウント
//iconCloseCheck()
//立ち絵をデフォルトに戻す
self.setObjectBodyNeutral()
//トピックを取得する
self.getTopic()
//チャット情報の初期化
self.initChatInfo()
//チャットスタート
self.chatStart()
}
/*
リプリスの更新
*/
internal func updateLiplis()
{
//設定速度に応じて動作をウェイトさせる
switch(self.os.lpsSpeed)
{
case 0 : //最速 常に実行
if(self.flgAlarm != 0){self.refreshLiplis()}
break
case 1 : //普通 1回休む
if(self.cntSlow >= 1)
{
self.refreshLiplis()
self.cntSlow = 0
}
else
{
self.cntSlow = self.cntSlow + 1
}
break
case 2 : //おそい 2回休む
if(self.cntSlow >= 2)
{
refreshLiplis()
self.cntSlow = 0
}
else
{
self.cntSlow = self.cntSlow + 1
}
break
case 3 : //瞬間表示
self.immediateRefresh()
break
default : //ほかの値が設定された場合は瞬間表示とする
self.immediateRefresh()
break
}
}
/*
リフレッシュ
*/
internal func refreshLiplis()
{
//キャンセルフェーズ
if self.checkMsg(){return}
//おすわりチェック
if self.checkSitdown(){return}
//タグチェック ひとまず保留
//if checkTag(){}
//スキップチェック
if self.checkSkip()
{
self.updateText()
}
//ナウワード取得、ナウテキスト設定
if(self.setText()){return}
//テキストの設定
self.updateText()
//ボディの更新
self.updateBody()
}
/*
瞬時リフレッシュ
*/
internal func immediateRefresh()
{
//キャンセルフェーズ
if self.checkMsg(){return}
//スキップ
self.skipLiplis()
//テキストの設定
self.updateText()
//ボディの更新
self.updateBody()
//終了
self.checkEnd()
}
/*
メッセージチェック
*/
internal func checkMsg()->Bool
{
//現在の話題が破棄されていれば、アップデートカウントをリセットする
if self.liplisNowTopic == nil
{
self.reSetUpdateCount()
return true
}
return false
}
/*
スキップチェック
*/
internal func checkSkip()->Bool
{
var result : Bool = false
//スキップチェック
if self.flgSkip{
//スキップ処理中有効
self.flgSkipping = true
//チャット停止
self.chatStop()
//スキップ処理
result = self.skipLiplis()
//スキップ処理中終了
self.flgSkipping = false
}
return result
}
/*
スキップ
*/
internal func skipLiplis()->Bool
{
self.liplisChatText = ""
if self.liplisNowTopic != nil
{
for var idx = 0, n = self.liplisNowTopic.nameList.count; idx<n; idx++
{
if idx != 0
{
//ナウワードの初期化
self.liplisNowWord = self.liplisNowTopic.nameList[idx]
//プレブエモーションセット
self.prvEmotion = self.nowEmotion
//なうエモーションの取得
self.nowEmotion = self.liplisNowTopic.emotionList[idx]
//なうポイントの取得
self.nowPoint = self.liplisNowTopic.pointList[0]
}
//初回ワードチェック
else if(idx == 0)
{
self.liplisNowWord = self.liplisNowTopic.nameList[idx]
//空だったら、空じゃなくなるまで繰り返す
if(self.liplisNowWord != "")
{
repeat
{
//次ワード遷移
idx++
//終了チェック
if(self.liplisNowTopic.nameList.count < idx)
{
if(idx > self.liplisNowTopic.nameList[idx].utf16.count){break}
//ナウワードの初期化
self.liplisNowWord = self.liplisNowTopic.nameList[idx]
}
}
while(self.liplisNowWord == "")
}
}
//おしゃべり中は何もしない
else
{
}
for(var kdx : Int = 0, n = self.liplisNowWord.utf16.count; kdx<n; kdx++)
{
self.liplisChatText = self.liplisChatText + (self.liplisNowWord as NSString).substringWithRange(NSRange(location : kdx,length : 1))
}
self.cntLnw = self.liplisNowTopic.nameList.count
self.cntLct = self.liplisNowWord.utf16.count
}
return true
}
else
{
return false
}
}
/*
座りチェック
*/
internal func checkSitdown()->Bool
{
if self.flgSitdown
{
self.liplisNowTopic = nil
self.updateBodySitDown()
return true
}
return false
}
/*
終了チェック
*/
internal func checkEnd()->Bool
{
if(self.cntLnw>=self.liplisNowTopic.nameList.count)
{
self.desk.lpsLog.append(self.liplisChatText, url: self.liplisNowTopic.url)
self.chatStop()
self.herfEyeCheck()
self.liplisNowTopic = nil
return true
}
return false
}
/*
テキストの更新
*/
internal func setText()->Bool
{
//送りワード文字数チェック
if(self.cntLnw != 0)
{
if(self.cntLct >= self.liplisNowWord.utf16.count)
{
//終了チェック
if(self.checkEnd()){return true}
//チャットテキストカウントの初期化
self.cntLct = 0
//なうワードの初期化
self.liplisNowWord = self.liplisNowTopic.nameList[cntLnw]
//プレブエモーションセット
self.prvEmotion = self.nowEmotion
//なうエモーションの取得
self.nowEmotion = self.liplisNowTopic.emotionList[self.cntLnw]
//なうポイントの取得
self.nowPoint = self.liplisNowTopic.pointList[self.cntLnw]
//インデックスインクリメント
self.cntLnw = self.cntLnw + 1
}
}
else if(self.cntLnw == 0)
{
//チャットテキストカウントの初期化
self.cntLct = 0
//空チェック
if self.liplisNowTopic.nameList.count == 0
{
self.checkEnd()
return true
}
//なうワードの初期化
self.liplisNowWord = self.liplisNowTopic.nameList[self.cntLnw]
//次ワード遷移
self.cntLnw = self.cntLnw + 1
//空だったら、空じゃなくなるまで繰り返す
if(self.liplisNowWord == "")
{
repeat
{
//チェックエンド
checkEnd()
//終了チェック
if(self.cntLnw > self.liplisNowTopic.nameList[cntLnw].utf16.count){break}
//ナウワードの初期化
self.liplisNowWord = self.liplisNowTopic.nameList[self.cntLnw]
//次ワード遷移
self.cntLnw = self.cntLnw + 1
}
while(self.liplisNowWord == "")
}
}
else
{
}
//おしゃべり
self.liplisChatText = self.liplisChatText + (self.liplisNowWord as NSString).substringWithRange(NSRange(location : self.cntLct,length : 1))
self.cntLct = self.cntLct + 1
return false
}
/*
テキストビューの更新
*/
internal func updateText()
{
self.lblLpsTalkLabel.text = self.liplisChatText
}
/*
ボディの更新
*/
internal func updateBody()->Bool
{
//感情変化セット
self.setObjectBody()
//口パクカウント
if(self.flgChatting)
{
if(self.cntMouth == 1){self.cntMouth = 2}
else {self.cntMouth = 1}
}
else
{
self.cntMouth = 1
}
//めぱちカウント
if(self.cntBlink == 0){self.cntBlink = self.getBlincCnt()}
else {self.cntBlink = self.cntBlink - 1}
autoreleasepool { () -> () in
self.imgBody.image = nil
self.imgBody.image = self.ob.getLiplisBodyImgIdIns(self.getBlinkState(),mouthState: self.cntMouth)
self.imgBody.setNeedsDisplay()
}
return true
}
/*
ボディの更新
*/
internal func updateBodySitDown()
{
self.imgBody.image = nil
self.imgBody.image = self.lpsBody.sleep
}
//============================================================
//
//ボディ制御
//
//============================================================
/*
ボディの取得
*/
internal func setObjectBody()->Bool
{
if(self.nowEmotion != self.prvEmotion && self.flgChatting)
{
//バッテリーレベルによる容姿変化の処理はここに入れる
//現在の感情値、感情レベルからボディを一つ取得
self.ob = lpsBody.getLiplisBody(nowEmotion, point: nowPoint)
return true
}
return false
}
/*
ボディを初期状態に戻す
*/
internal func setObjectBodyNeutral()->Bool
{
self.cntMouth = 1
self.cntBlink = 0
self.nowEmotion = 0
self.nowPoint = 0
if self.os.lpsHealth == 1 && self.lpsBattery.batteryNowLevel > 75
{
//ヘルス設定ONでバッテリー残量が75%以下なら小破以下の画像取得
self.ob = self.lpsBody.getLiplisBodyHelth(Int(self.lpsBattery.batteryNowLevel), emotion: self.nowEmotion, point: self.nowPoint)
}
else
{
self.ob = self.lpsBody.getLiplisBody(self.nowEmotion, point : self.nowPoint)
}
//reqReflesh()
return true
}
/*
まばたきカウント
*/
internal func getBlincCnt()->Int{
return LiplisUtil.getRandormNumber(Min: 30,Max: 50)
}
/*
まばたき状態の取得
*/
internal func getBlinkState()->Int
{
switch(self.cntBlink)
{
case 0:
return 1
case 1:
return 2
case 2:
return 3
case 3:
return 2
default:
return 1
}
}
/*
半目チェック
*/
internal func herfEyeCheck()
{
if(self.cntBlink == 1 || self.cntBlink == 3)
{
self.cntBlink = 0
self.updateBody()
}
}
//============================================================
//
//チャット制御
//
//============================================================
/*
チャットスタート
*/
internal func chatStart()
{
self.flgChatting = true
//瞬時表示チェック
if self.os.lpsSpeed == 3
{
self.immediateRefresh()
}
else
{
//実行モードを12に設定する
self.flgAlarm = 12
//更新タイマーをONする
self.startUpdateTimer()
}
}
/*
チャットストップ
*/
internal func chatStop()
{
self.flgAlarm = 0
self.reSetUpdateCount()
self.flgChatting = false
self.flgSkip = false
}
//============================================================
//
//話題管理
//
//============================================================
/*
1件のトピックを取得する
*/
internal func getTopic()
{
self.flgChatTalk = false
self.flgThinking = true
self.getShortNews()
self.flgThinking = false
}
/*
ニュースキューチェック
*/
internal func onCheckNewsQueue()
{
if(!self.flgSitdown)
{
self.lpsNews.checkNewsQueue(self.getPostDataForLiplisNewsList())
}
}
/*
ニュースを取得する
*/
internal func getShortNews()
{
self.liplisNowTopic = self.lpsNews.getShortNews(self.getPostDataForLiplisNews())
//取得失敗メッセージ
if self.liplisNowTopic == nil
{
self.self.liplisNowTopic = FctLiplisMsg.createMsgMassageDlFaild()
liplisUrl = ""
}
else
{
self.liplisUrl = self.liplisNowTopic.url
}
}
/*
ポストパラメーターの作成(ニュース単体向け)
*/
internal func getPostDataForLiplisNews()->NSData
{
let nameValuePair : NameValuePair = NameValuePair()
nameValuePair.add(BasicNameValuePair(key: "tone", value: self.lpsSkin.tone))
nameValuePair.add(BasicNameValuePair(key: "newsFlg", value: self.os.getNewsFlg()))
nameValuePair.add(BasicNameValuePair(key: "randomkey", value: LiplisDate().getTimeStr())) //キャッシュ防止
return nameValuePair.getPostData()
}
/*
ポストパラメーターの作成(ニュースリスト向け)
*/
internal func getPostDataForLiplisNewsList()->NSData
{
let nameValuePair : NameValuePair = NameValuePair()
nameValuePair.add(BasicNameValuePair(key: "userid", value: self.desk.baseSetting.lpsUid))
nameValuePair.add(BasicNameValuePair(key : "tone", value: self.lpsSkin.tone))
nameValuePair.add(BasicNameValuePair(key: "newsFlg", value: self.os.getNewsFlg()))
nameValuePair.add(BasicNameValuePair(key : "num", value: "20"))
nameValuePair.add(BasicNameValuePair(key: "hour", value: self.os.getLpsNewsRangeStr()))
nameValuePair.add(BasicNameValuePair(key: "already", value: String(self.os.lpsNewsAlready)))
nameValuePair.add(BasicNameValuePair(key: "twitterMode", value: String(self.os.lpsTopicTwitterMode)))
nameValuePair.add(BasicNameValuePair(key: "runout", value: String(self.os.lpsNewsRunOut)))
nameValuePair.add(BasicNameValuePair(key: "randomkey", value: LiplisDate().getTimeStr())) //キャッシュ防止
return nameValuePair.getPostData()
}
//============================================================
//
//状態制御
//
//============================================================
/*
おはよう
*/
internal func wakeup()
{
//おやすみ状態の場合、ウェイクアップ
self.flgSitdown = false
//アイコン変更
self.icoSleep.setImage(self.lpsIcon.imgSleep,forState : UIControlState.Normal)
//あいさつ
self.greet()
}
/*
おやすみ
*/
internal func sleep()
{
//ウェイクアップ状態の場合、おやすみ
self.flgSitdown = true
//アイコン変更
self.icoSleep.setImage(self.lpsIcon.imgWakeup,forState : UIControlState.Normal)
//表示テキスト変更
self.lblLpsTalkLabel.text = "zzz"
//おやすみの立ち絵に変更
self.updateBodySitDown()
}
/*
アイコン表示
*/
internal func iconOn()
{
self.icoSleep.hidden = false
self.icoLog.hidden = false
self.icoSetting.hidden = false
self.icoChat.hidden = false
self.icoClock.hidden = false
self.icoBattery.hidden = false
}
/*
アイコン非表示
*/
internal func iconOff()
{
self.icoSleep.hidden = true
self.icoLog.hidden = true
self.icoSetting.hidden = true
self.icoChat.hidden = true
self.icoClock.hidden = true
self.icoBattery.hidden = true
}
/*
最前面に移動する
*/
internal func goToTheFront()
{
self.desk.view.bringSubviewToFront(self.imgWindow)
self.desk.view.bringSubviewToFront(self.lblLpsTalkLabel)
self.desk.view.bringSubviewToFront(self.imgBody)
self.desk.view.bringSubviewToFront(self.icoSleep)
self.desk.view.bringSubviewToFront(self.icoLog)
self.desk.view.bringSubviewToFront(self.icoSetting)
self.desk.view.bringSubviewToFront(self.icoChat)
self.desk.view.bringSubviewToFront(self.icoClock)
self.desk.view.bringSubviewToFront(self.icoBattery)
self.desk.view.bringSubviewToFront(self.imgClockBase)
self.desk.view.bringSubviewToFront(self.imgClockLongHand)
self.desk.view.bringSubviewToFront(self.imgClockShortHand)
}
//============================================================
//
//ほか画面呼び出し
//
//============================================================
/*
ウィジェット設定画面を呼び出す
*/
internal func callWidgetSetting()
{
let modalView : ViewWidgetMenu = ViewWidgetMenu(widget: self)
modalView.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
self.desk.presentViewController(modalView, animated: true, completion: nil)
}
/*
チャット画面を呼び出す
*/
internal func callChat()
{
let modalView : ViewChat = ViewChat(widget : self)
modalView.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
modalView.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
self.desk.presentViewController(modalView, animated: true, completion: nil)
}
}
| 4c63c29708c44a1bcf31bc985cd1273c | 27.309698 | 197 | 0.511676 | false | false | false | false |
pakLebah/simpleWeb | refs/heads/master | webtest.swift | mit | 1 | /**
SimpleWeb Swift Demo
v.1.0 - Oct, 2016
© pak.lebah
*/
import Foundation
import SimpleWeb
/* --- CUSTOM METHODS --- */
func p() { webWrite("<p>", width: 0) } // start a html paragraph
func bold(_ s: String) -> String { return "<b>\(s)</b>" }
func italic(_ s: String) -> String { return "<i>\(s)</i>" }
func underline(_ s: String) -> String { return "<u>\(s)</u>" }
func strike(_ s: String) -> String { return "<s>\(s)</s>" }
func sub(_ s: String) -> String { return "<sub>\(s)</sub>" }
func sup(_ s: String) -> String { return "<sup>\(s)</sup>" }
func big(_ s: String) -> String { return "<big>\(s)</big>" }
func small(_ s: String) -> String { return "<small>\(s)</small>" }
/* --- MAIN WEB PROGRAM --- */
let leftWidth = -1 // left alignment is from css
openHTML(title: "Test")
webPageHeader("Hello World from Swift on Linux!", level:2)
webWriteln(bold("Read input:"))
p()
webWrite("String: ", width: leftWidth)
let str = webRead("")
let btn = webReadButton(" ► ")
webWrite("Integer: ")
let int = webReadln(0)
webWrite("Double: ")
let float = webReadln(0.0)
webWrite("Boolean: ")
let bool = webReadln(true, label: "boolean")
webWrite("Option: ")
let options = ["option 1","option 2","option 3"]
let opt = webReadOption(labels: options)
webWrite("Select: ")
let sel = webReadSelect(-1, items: ["item 1","item 2","item 3"])
webWriteln("Text: ")
let txt = webReadMemo("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
webWrite("Output: ", width: leftWidth)
let out = webReadOption(0, labels: ["table","list"], newLine: false)
webWriteln()
if webHasInput {
p()
webWriteln(bold("Write output:"))
switch (out == 0) {
case true: // table
webOpenTable(["Type", "Value"])
webTableRow(["Button", btn ? "[clicked]" : "[not clicked]"])
webTableRow(["String", str.isEmpty ? "[empty]" : str])
webTableRow(["Integer","\(int)"])
webTableRow(["Double", "\(float)"])
webTableRow(["Boolean","\(bool)"])
webTableRow(["Option", opt < 0 ? "[none]" : "\(options[opt])"])
webTableRow(["Select", sel < 0 ? "[none]" : "\(sel)"])
webTableRow(["Text", txt.isEmpty ? "[empty]" : txt])
webCloseTable()
case false: // list
webOpenList(ordered: false)
webListItem("Button: \(btn ? "[clicked]" : "[not clicked]")")
webListItem("String: \(str.isEmpty ? "[empty]" : str)")
webListItem("Integer: \(int)")
webListItem("Double: \(float)")
webListItem("Boolean: \(bool)")
webListItem("Option: \(opt < 0 ? "[none]" : "\(options[opt])")")
webListItem("Select: \(sel < 0 ? "[none]" : "\(sel)")")
webListItem("Text: \(txt.isEmpty ? "[empty]" : "")")
if !txt.isEmpty { webWriteBlock(txt) }
webCloseList()
}
let linkMod = webGetLink("viewcode.cgi?file=SimpleWeb.swift", caption: "here")
let linkDemo = webGetLink("viewcode.cgi?file=webtest.swift", caption: "here")
webWriteln("<p>Source code of the module is \(linkMod) and the demo is \(linkDemo).")
}
closeHTML()
/* --- END OF PROGRAM --- */
| 69b9550a439111ca7e62becc4a0fdf8d | 34.344828 | 87 | 0.59252 | false | false | false | false |
binarylevel/Riseset | refs/heads/master | Riseset/View Controllers/RSWeatherViewController.swift | mit | 1 | // RSWeatherViewController.swift
//
// Copyright (c) 2016 Riseset ()
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreLocation
import RxSwift
import RxCocoa
import RxBlocking
import PureLayout
import RealmSwift
class RSWeatherViewController: UIViewController {
var didSetupContraints = false
func bindSourceToLabel(source: PublishSubject<String?>, label: UILabel) {
source
.subscribeNext { text in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
label.text = text
})
}
.addDisposableTo(rx_disposeBag)
}
let locationController = RSLocationController()
let geocodeController = RSGeocodeController()
let forecastController = RSForecastController()
let weatherController = RSWeatherController()
var viewModel = RSForecastViewModel()
var dayViews:NSMutableArray?
let timeLabel:UILabel = {
let timeLabel = UILabel.newAutoLayoutView()
if #available(iOS 8.2, *) {
timeLabel.font = UIFont.systemFontOfSize(20.0, weight: UIFontWeightRegular)
} else {
timeLabel.font = UIFont.systemFontOfSize(20.0)
}
timeLabel.textColor = UIColor(red: 57.0 / 255.0, green: 70.0 / 255.0, blue: 89.0 / 255.0, alpha: 1.0)
return timeLabel
}()
let summaryLabel:UILabel = {
let summaryLabel = UILabel.newAutoLayoutView()
if #available(iOS 8.2, *) {
summaryLabel.font = UIFont.systemFontOfSize(24.0, weight: UIFontWeightRegular)
} else {
summaryLabel.font = UIFont.systemFontOfSize(24.0)
}
summaryLabel.textColor = UIColor(red: 57.0 / 255.0, green: 70.0 / 255.0, blue: 89.0 / 255.0, alpha: 1.0)
return summaryLabel
}()
let temperatureLabel:UILabel = {
let temperatureLabel = UILabel.newAutoLayoutView()
if #available(iOS 8.2, *) {
temperatureLabel.font = UIFont.systemFontOfSize(160.0, weight: UIFontWeightLight)
} else {
temperatureLabel.font = UIFont.systemFontOfSize(160.0)
}
temperatureLabel.textColor = UIColor(red: 57.0 / 255.0, green: 70.0 / 255.0, blue: 89.0 / 255.0, alpha: 1.0)
return temperatureLabel
}()
let locationLabel:UILabel = {
let locationLabel = UILabel(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 44))
if #available(iOS 8.2, *) {
locationLabel.font = UIFont.systemFontOfSize(22.0, weight: UIFontWeightRegular)
} else {
locationLabel.font = UIFont.systemFontOfSize(22.0)
}
locationLabel.textAlignment = .Center
locationLabel.textColor = UIColor(red: 57.0 / 255.0, green: 70.0 / 255.0, blue: 89.0 / 255.0, alpha: 1.0)
return locationLabel
}()
lazy var verticalLine1:UIView = {
let verticalLine1 = UIView.newAutoLayoutView()
verticalLine1.backgroundColor = UIColor(red: 57.0 / 255.0, green: 70.0 / 255.0, blue: 89.0 / 255.0, alpha: 0.2)
return verticalLine1
}()
lazy var verticalLine2:UIView = {
let verticalLine2 = UIView.newAutoLayoutView()
verticalLine2.backgroundColor = UIColor(red: 57.0 / 255.0, green: 70.0 / 255.0, blue: 89.0 / 255.0, alpha: 0.2)
return verticalLine2
}()
lazy var horizontalLine:UIView = {
let horizontalLine = UIView.newAutoLayoutView()
horizontalLine.backgroundColor = UIColor(red: 57.0 / 255.0, green: 70.0 / 255.0, blue: 89.0 / 255.0, alpha: 0.2)
return horizontalLine
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = locationLabel
automaticallyAdjustsScrollViewInsets = false
view.backgroundColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.translucent = true
navigationController?.view.backgroundColor = UIColor.clearColor()
bindSourceToLabel(weatherController.viewModel.publishTime, label: timeLabel)
weatherController.viewModel.publishHumidity
.subscribeNext { value in
print("value \(value!)")
}.addDisposableTo(rx_disposeBag)
Realm.rx_objects(RSForecast)
.debugOnlyInDebugMode("fetch realm objects")
.subscribeNext { [weak self] items in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let currently = items.first?.currently {
self?.timeLabel.text = currently.currentTime
self?.temperatureLabel.text = "\(currently.currentTemperature.fahrenheitValue!)°"
self?.summaryLabel.text = currently.summary
}
if let dailyData = items.first?.daily?.data {
let sliced = dailyData[1...3]
let newArray = Array(sliced)
self?.dayViews!.enumerateObjectsUsingBlock({ view, index, stop in
let forecastDayView = view as! RSForecastDayView
forecastDayView.dataPoint = newArray[index]
})
}
})
}.addDisposableTo(self.rx_disposeBag)
weatherController.viewModel.items
.debugOnlyInDebugMode("refresh model")
.subscribeNext { [weak self] items in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let currently = items.first?.currently {
self?.temperatureLabel.text = "\(currently.currentTemperature.fahrenheitValue!)°"
self?.summaryLabel.text = currently.summary
}
if let dailyData = items.first?.daily?.data {
let sliced = dailyData[1...3]
let newArray = Array(sliced)
self?.dayViews!.enumerateObjectsUsingBlock({ view, index, stop in
let forecastDayView = view as! RSForecastDayView
forecastDayView.dataPoint = newArray[index]
})
}
})
}.addDisposableTo(rx_disposeBag)
weatherController.viewModel.locationName
.startWith("updating weather...")
.subscribeNext { [weak self] text in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self?.locationLabel.text = text
})
}.addDisposableTo(rx_disposeBag)
NSNotificationCenter.defaultCenter().rx_notification(UIApplicationWillEnterForegroundNotification).subscribeNext { [weak self] _ in
self?.weatherController.updateActions().subscribeNext { location in
self?.viewModel.updateViewModel()
}.addDisposableTo(self!.rx_disposeBag)
}.addDisposableTo(rx_disposeBag)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
viewModel.updateViewModel()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
weatherController.updateActions().subscribeNext { location in
}.addDisposableTo(rx_disposeBag)
}
override func loadView() {
view = UIView()
view.backgroundColor = UIColor.whiteColor()
dayViews = NSMutableArray()
for _ in 0...2 {
let forecastDayView = RSForecastDayView.newAutoLayoutView()
view.addSubview(forecastDayView)
dayViews?.addObject(forecastDayView)
}
view.addSubview(verticalLine1)
view.addSubview(verticalLine2)
view.addSubview(horizontalLine)
view.addSubview(temperatureLabel)
view.addSubview(timeLabel)
view.addSubview(summaryLabel)
view.setNeedsUpdateConstraints()
}
override func updateViewConstraints() {
let width:CGFloat = UIScreen.mainScreen().bounds.size.width / 3.0
let height:CGFloat = 160.0
if !didSetupContraints {
timeLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: 74.0)
timeLabel.autoAlignAxisToSuperviewAxis(.Vertical)
temperatureLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: timeLabel)
temperatureLabel.autoAlignAxisToSuperviewAxis(.Vertical)
summaryLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: temperatureLabel)
summaryLabel.autoAlignAxisToSuperviewAxis(.Vertical)
dayViews?.autoSetViewsDimensionsToSize(CGSizeMake(width, height))
dayViews?.autoMatchViewsDimension(.Width)
dayViews?.firstObject?.autoPinEdgeToSuperviewEdge(.Left)
dayViews?.firstObject?.autoPinEdgeToSuperviewEdge(.Bottom)
var previousView: UIView?
for view in dayViews! {
if let previousView = previousView {
view.autoPinEdge(.Left, toEdge: .Right, ofView: previousView)
view.autoPinEdgeToSuperviewEdge(.Bottom)
}
previousView = view as? UIView
}
dayViews?.lastObject?.autoPinEdgeToSuperviewEdge(.Right)
horizontalLine.autoMatchDimension(.Width, toDimension: .Width, ofView: view)
horizontalLine.autoSetDimension(.Height, toSize: 1.0)
horizontalLine.autoPinEdge(.Bottom, toEdge: .Top, ofView: dayViews?.firstObject as! UIView)
verticalLine1.autoSetDimensionsToSize(CGSizeMake(1.0, height))
verticalLine1.autoPinEdge(.Left, toEdge: .Right, ofView: dayViews?.firstObject as! UIView)
verticalLine1.autoPinEdgeToSuperviewEdge(.Bottom)
verticalLine2.autoSetDimensionsToSize(CGSizeMake(1.0, height))
verticalLine2.autoPinEdge(.Left, toEdge: .Right, ofView: dayViews?.objectAtIndex(1) as! UIView)
verticalLine2.autoPinEdgeToSuperviewEdge(.Bottom)
didSetupContraints = true
}
super.updateViewConstraints()
}
}
| 7c01f0e06c8346f9833285f5481c91ef | 40.327526 | 139 | 0.607959 | false | false | false | false |
tzongw/ReactiveCocoa | refs/heads/master | ReactiveCocoa/Swift/Signal.swift | mit | 1 | import Foundation
import Result
/// A push-driven stream that sends Events over time, parameterized by the type
/// of values being sent (`Value`) and the type of failure that can occur (`Error`).
/// If no failures should be possible, NoError can be specified for `Error`.
///
/// An observer of a Signal will see the exact same sequence of events as all
/// other observers. In other words, events will be sent to all observers at the
/// same time.
///
/// Signals are generally used to represent event streams that are already “in
/// progress,” like notifications, user input, etc. To represent streams that
/// must first be _started_, see the SignalProducer type.
///
/// Signals do not need to be retained. A Signal will be automatically kept
/// alive until the event stream has terminated.
public final class Signal<Value, Error: ErrorType> {
public typealias Observer = ReactiveCocoa.Observer<Value, Error>
private let atomicObservers: Atomic<Bag<Observer>?> = Atomic(Bag())
/// Initializes a Signal that will immediately invoke the given generator,
/// then forward events sent to the given observer.
///
/// The disposable returned from the closure will be automatically disposed
/// if a terminating event is sent to the observer. The Signal itself will
/// remain alive until the observer is released.
public init(@noescape _ generator: Observer -> Disposable?) {
/// Used to ensure that events are serialized during delivery to observers.
let sendLock = NSLock()
sendLock.name = "org.reactivecocoa.ReactiveCocoa.Signal"
let generatorDisposable = SerialDisposable()
/// When set to `true`, the Signal should interrupt as soon as possible.
let interrupted = Atomic(false)
let observer = Observer { event in
if case .Interrupted = event {
// Normally we disallow recursive events, but
// Interrupted is kind of a special snowflake, since it
// can inadvertently be sent by downstream consumers.
//
// So we'll flag Interrupted events specially, and if it
// happened to occur while we're sending something else,
// we'll wait to deliver it.
interrupted.value = true
if sendLock.tryLock() {
self.interrupt()
sendLock.unlock()
generatorDisposable.dispose()
}
} else {
if let observers = (event.isTerminating ? self.atomicObservers.swap(nil) : self.atomicObservers.value) {
sendLock.lock()
for observer in observers {
observer.action(event)
}
let shouldInterrupt = !event.isTerminating && interrupted.value
if shouldInterrupt {
self.interrupt()
}
sendLock.unlock()
if event.isTerminating || shouldInterrupt {
// Dispose only after notifying observers, so disposal logic
// is consistently the last thing to run.
generatorDisposable.dispose()
}
}
}
}
generatorDisposable.innerDisposable = generator(observer)
}
/// A Signal that never sends any events to its observers.
public static var never: Signal {
return self.init { _ in nil }
}
/// A Signal that completes immediately without emitting any value.
public static var empty: Signal {
return self.init { observer in
observer.sendCompleted()
return nil
}
}
/// Creates a Signal that will be controlled by sending events to the given
/// observer.
///
/// The Signal will remain alive until a terminating event is sent to the
/// observer.
public static func pipe() -> (Signal, Observer) {
var observer: Observer!
let signal = self.init { innerObserver in
observer = innerObserver
return nil
}
return (signal, observer)
}
/// Interrupts all observers and terminates the stream.
private func interrupt() {
if let observers = self.atomicObservers.swap(nil) {
for observer in observers {
observer.sendInterrupted()
}
}
}
/// Observes the Signal by sending any future events to the given observer. If
/// the Signal has already terminated, the observer will immediately receive an
/// `Interrupted` event.
///
/// Returns a Disposable which can be used to disconnect the observer. Disposing
/// of the Disposable will have no effect on the Signal itself.
public func observe(observer: Observer) -> Disposable? {
var token: RemovalToken?
atomicObservers.modify { observers in
guard var observers = observers else {
return nil
}
token = observers.insert(observer)
return observers
}
if let token = token {
return ActionDisposable { [weak self] in
self?.atomicObservers.modify { observers in
guard var observers = observers else {
return nil
}
observers.removeValueForToken(token)
return observers
}
}
} else {
observer.sendInterrupted()
return nil
}
}
}
public protocol SignalType {
/// The type of values being sent on the signal.
associatedtype Value
/// The type of error that can occur on the signal. If errors aren't possible
/// then `NoError` can be used.
associatedtype Error: ErrorType
/// Extracts a signal from the receiver.
var signal: Signal<Value, Error> { get }
/// Observes the Signal by sending any future events to the given observer.
func observe(observer: Signal<Value, Error>.Observer) -> Disposable?
}
extension Signal: SignalType {
public var signal: Signal {
return self
}
}
extension SignalType {
/// Convenience override for observe(_:) to allow trailing-closure style
/// invocations.
public func observe(action: Signal<Value, Error>.Observer.Action) -> Disposable? {
return observe(Observer(action))
}
/// Observes the Signal by invoking the given callback when `next` events are
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callbacks. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeNext(next: Value -> Void) -> Disposable? {
return observe(Observer(next: next))
}
/// Observes the Signal by invoking the given callback when a `completed` event is
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeCompleted(completed: () -> Void) -> Disposable? {
return observe(Observer(completed: completed))
}
/// Observes the Signal by invoking the given callback when a `failed` event is
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeFailed(error: Error -> Void) -> Disposable? {
return observe(Observer(failed: error))
}
/// Observes the Signal by invoking the given callback when an `interrupted` event is
/// received. If the Signal has already terminated, the callback will be invoked
/// immediately.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeInterrupted(interrupted: () -> Void) -> Disposable? {
return observe(Observer(interrupted: interrupted))
}
/// Maps each value in the signal to a new value.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func map<U>(transform: Value -> U) -> Signal<U, Error> {
return Signal { observer in
return self.observe { event in
observer.action(event.map(transform))
}
}
}
/// Maps errors in the signal to a new error.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func mapError<F>(transform: Error -> F) -> Signal<Value, F> {
return Signal { observer in
return self.observe { event in
observer.action(event.mapError(transform))
}
}
}
/// Preserves only the values of the signal that pass the given predicate.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func filter(predicate: Value -> Bool) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { (event: Event<Value, Error>) -> Void in
if case let .Next(value) = event {
if predicate(value) {
observer.sendNext(value)
}
} else {
observer.action(event)
}
}
}
}
}
extension SignalType where Value: OptionalType {
/// Unwraps non-`nil` values and forwards them on the returned signal, `nil`
/// values are dropped.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func ignoreNil() -> Signal<Value.Wrapped, Error> {
return filter { $0.optional != nil }.map { $0.optional! }
}
}
extension SignalType {
/// Returns a signal that will yield the first `count` values from `self`
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func take(count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
return Signal { observer in
if count == 0 {
observer.sendCompleted()
return nil
}
var taken = 0
return self.observe { event in
if case let .Next(value) = event {
if taken < count {
taken += 1
observer.sendNext(value)
}
if taken == count {
observer.sendCompleted()
}
} else {
observer.action(event)
}
}
}
}
}
/// A reference type which wraps an array to auxiliate the collection of values
/// for `collect` operator.
private final class CollectState<Value> {
var values: [Value] = []
/// Collects a new value.
func append(value: Value) {
values.append(value)
}
/// Check if there are any items remaining.
///
/// - Note: This method also checks if there weren't collected any values
/// and, in that case, it means an empty array should be sent as the result
/// of collect.
var isEmpty: Bool {
/// We use capacity being zero to determine if we haven't collected any
/// value since we're keeping the capacity of the array to avoid
/// unnecessary and expensive allocations). This also guarantees
/// retro-compatibility around the original `collect()` operator.
return values.isEmpty && values.capacity > 0
}
/// Removes all values previously collected if any.
func flush() {
// Minor optimization to avoid consecutive allocations. Can
// be useful for sequences of regular or similar size and to
// track if any value was ever collected.
values.removeAll(keepCapacity: true)
}
}
extension SignalType {
/// Returns a signal that will yield an array of values when `self` completes.
///
/// - Note: When `self` completes without collecting any value, it will sent
/// an empty array of values.
///
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func collect() -> Signal<[Value], Error> {
return collect { _,_ in false }
}
/// Returns a signal that will yield an array of values until it reaches a
/// certain count.
///
/// When the count is reached the array is sent and the signal starts over
/// yielding a new array of values.
///
/// - Precondition: `count` should be greater than zero.
///
/// - Note: When `self` completes any remaining values will be sent, the last
/// array may not have `count` values. Alternatively, if were not collected
/// any values will sent an empty array of values.
///
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func collect(count count: Int) -> Signal<[Value], Error> {
precondition(count > 0)
return collect { values in values.count == count }
}
/// Returns a signal that will yield an array of values based on a predicate
/// which matches the values collected.
///
/// - parameter predicate: Predicate to match when values should be sent
/// (returning `true`) or alternatively when they should be collected (where
/// it should return `false`). The most recent value (`next`) is included in
/// `values` and will be the end of the current array of values if the
/// predicate returns `true`.
///
/// - Note: When `self` completes any remaining values will be sent, the last
/// array may not match `predicate`. Alternatively, if were not collected any
/// values will sent an empty array of values.
///
/// #### Example
///
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .observeNext { print($0) }
///
/// observer.sendNext(1)
/// observer.sendNext(3)
/// observer.sendNext(4)
/// observer.sendNext(7)
/// observer.sendNext(1)
/// observer.sendNext(5)
/// observer.sendNext(6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 3, 4]
/// // [7, 1]
/// // [5, 6]
///
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func collect(predicate: (values: [Value]) -> Bool) -> Signal<[Value], Error> {
return Signal { observer in
let state = CollectState<Value>()
return self.observe { event in
switch event {
case let .Next(value):
state.append(value)
if predicate(values: state.values) {
observer.sendNext(state.values)
state.flush()
}
case .Completed:
if !state.isEmpty {
observer.sendNext(state.values)
}
observer.sendCompleted()
case let .Failed(error):
observer.sendFailed(error)
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Returns a signal that will yield an array of values based on a predicate
/// which matches the values collected and the next value.
///
/// - parameter predicate: Predicate to match when values should be sent
/// (returning `true`) or alternatively when they should be collected (where
/// it should return `false`). The most recent value (`next`) is not included
/// in `values` and will be the start of the next array of values if the
/// predicate returns `true`.
///
/// - Note: When `self` completes any remaining values will be sent, the last
/// array may not match `predicate`. Alternatively, if were not collected any
/// values will sent an empty array of values.
///
/// #### Example
///
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values, next in next == 7 }
/// .observeNext { print($0) }
///
/// observer.sendNext(1)
/// observer.sendNext(1)
/// observer.sendNext(7)
/// observer.sendNext(7)
/// observer.sendNext(5)
/// observer.sendNext(6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 1]
/// // [7]
/// // [7, 5, 6]
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func collect(predicate: (values: [Value], next: Value) -> Bool) -> Signal<[Value], Error> {
return Signal { observer in
let state = CollectState<Value>()
return self.observe { event in
switch event {
case let .Next(value):
if predicate(values: state.values, next: value) {
observer.sendNext(state.values)
state.flush()
}
state.append(value)
case .Completed:
if !state.isEmpty {
observer.sendNext(state.values)
}
observer.sendCompleted()
case let .Failed(error):
observer.sendFailed(error)
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forwards all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
public func observeOn(scheduler: SchedulerType) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { event in
scheduler.schedule {
observer.action(event)
}
}
}
}
}
private final class CombineLatestState<Value> {
var latestValue: Value?
var completed = false
}
extension SignalType {
private func observeWithStates<U>(signalState: CombineLatestState<Value>, _ otherState: CombineLatestState<U>, _ lock: NSLock, _ onBothNext: () -> Void, _ onFailed: Error -> Void, _ onBothCompleted: () -> Void, _ onInterrupted: () -> Void) -> Disposable? {
return self.observe { event in
switch event {
case let .Next(value):
lock.lock()
signalState.latestValue = value
if otherState.latestValue != nil {
onBothNext()
}
lock.unlock()
case let .Failed(error):
onFailed(error)
case .Completed:
lock.lock()
signalState.completed = true
if otherState.completed {
onBothCompleted()
}
lock.unlock()
case .Interrupted:
onInterrupted()
}
}
}
/// Combines the latest value of the receiver with the latest value from
/// the given signal.
///
/// The returned signal will not send a value until both inputs have sent
/// at least one value each. If either signal is interrupted, the returned signal
/// will also be interrupted.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatestWith<U>(otherSignal: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let lock = NSLock()
lock.name = "org.reactivecocoa.ReactiveCocoa.combineLatestWith"
let signalState = CombineLatestState<Value>()
let otherState = CombineLatestState<U>()
let onBothNext = {
observer.sendNext((signalState.latestValue!, otherState.latestValue!))
}
let onFailed = observer.sendFailed
let onBothCompleted = observer.sendCompleted
let onInterrupted = observer.sendInterrupted
let disposable = CompositeDisposable()
disposable += self.observeWithStates(signalState, otherState, lock, onBothNext, onFailed, onBothCompleted, onInterrupted)
disposable += otherSignal.observeWithStates(otherState, signalState, lock, onBothNext, onFailed, onBothCompleted, onInterrupted)
return disposable
}
}
/// Delays `Next` and `Completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// `Failed` and `Interrupted` events are always scheduled immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func delay(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
return self.observe { event in
switch event {
case .Failed, .Interrupted:
scheduler.schedule {
observer.action(event)
}
case .Next, .Completed:
let date = scheduler.currentDate.dateByAddingTimeInterval(interval)
scheduler.scheduleAfter(date) {
observer.action(event)
}
}
}
}
}
/// Returns a signal that will skip the first `count` values, then forward
/// everything afterward.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skip(count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
if count == 0 {
return signal
}
return Signal { observer in
var skipped = 0
return self.observe { event in
if case .Next = event where skipped < count {
skipped += 1
} else {
observer.action(event)
}
}
}
}
/// Treats all Events from `self` as plain values, allowing them to be manipulated
/// just like any other value.
///
/// In other words, this brings Events “into the monad.”
///
/// When a Completed or Failed event is received, the resulting signal will send
/// the Event itself and then complete. When an Interrupted event is received,
/// the resulting signal will send the Event itself and then interrupt.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func materialize() -> Signal<Event<Value, Error>, NoError> {
return Signal { observer in
return self.observe { event in
observer.sendNext(event)
switch event {
case .Interrupted:
observer.sendInterrupted()
case .Completed, .Failed:
observer.sendCompleted()
case .Next:
break
}
}
}
}
}
extension SignalType where Value: EventType, Error == NoError {
/// The inverse of materialize(), this will translate a signal of `Event`
/// _values_ into a signal of those events themselves.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func dematerialize() -> Signal<Value.Value, Value.Error> {
return Signal<Value.Value, Value.Error> { observer in
return self.observe { event in
switch event {
case let .Next(innerEvent):
observer.action(innerEvent.event)
case .Failed:
fatalError("NoError is impossible to construct")
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
}
extension SignalType {
/// Injects side effects to be performed upon the specified signal events.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func on(event event: (Event<Value, Error> -> Void)? = nil, failed: (Error -> Void)? = nil, completed: (() -> Void)? = nil, interrupted: (() -> Void)? = nil, terminated: (() -> Void)? = nil, disposed: (() -> Void)? = nil, next: (Value -> Void)? = nil) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
_ = disposed.map(disposable.addDisposable)
disposable += signal.observe { receivedEvent in
event?(receivedEvent)
switch receivedEvent {
case let .Next(value):
next?(value)
case let .Failed(error):
failed?(error)
case .Completed:
completed?()
case .Interrupted:
interrupted?()
}
if receivedEvent.isTerminating {
terminated?()
}
observer.action(receivedEvent)
}
return disposable
}
}
}
private struct SampleState<Value> {
var latestValue: Value? = nil
var signalCompleted: Bool = false
var samplerCompleted: Bool = false
}
extension SignalType {
/// Forwards the latest value from `self` with the value from `sampler` as a tuple,
/// only when`sampler` sends a Next event.
///
/// If `sampler` fires before a value has been observed on `self`, nothing
/// happens.
///
/// Returns a signal that will send values from `self` and `sampler`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input signals have
/// completed, or interrupt if either input signal is interrupted.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func sampleWith<T>(sampler: Signal<T, NoError>) -> Signal<(Value, T), Error> {
return Signal { observer in
let state = Atomic(SampleState<Value>())
let disposable = CompositeDisposable()
disposable += self.observe { event in
switch event {
case let .Next(value):
state.modify { st in
var st = st
st.latestValue = value
return st
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
let oldState = state.modify { st in
var st = st
st.signalCompleted = true
return st
}
if oldState.samplerCompleted {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
}
}
disposable += sampler.observe { event in
switch event {
case .Next(let samplerValue):
if let value = state.value.latestValue {
observer.sendNext((value, samplerValue))
}
case .Completed:
let oldState = state.modify { st in
var st = st
st.samplerCompleted = true
return st
}
if oldState.signalCompleted {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
case .Failed:
break
}
}
return disposable
}
}
/// Forwards the latest value from `self` whenever `sampler` sends a Next
/// event.
///
/// If `sampler` fires before a value has been observed on `self`, nothing
/// happens.
///
/// Returns a signal that will send values from `self`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input signals have
/// completed, or interrupt if either input signal is interrupted.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func sampleOn(sampler: Signal<(), NoError>) -> Signal<Value, Error> {
return sampleWith(sampler)
.map { $0.0 }
}
/// Forwards events from `self` until `trigger` sends a Next or Completed
/// event, at which point the returned signal will complete.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeUntil(trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
disposable += self.observe(observer)
disposable += trigger.observe { event in
switch event {
case .Next, .Completed:
observer.sendCompleted()
case .Failed, .Interrupted:
break
}
}
return disposable
}
}
/// Does not forward any values from `self` until `trigger` sends a Next or
/// Completed event, at which point the returned signal behaves exactly like
/// `signal`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipUntil(trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = SerialDisposable()
disposable.innerDisposable = trigger.observe { event in
switch event {
case .Next, .Completed:
disposable.innerDisposable = self.observe(observer)
case .Failed, .Interrupted:
break
}
}
return disposable
}
}
/// Forwards events from `self` with history: values of the returned signal
/// are a tuple whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `self`
/// sends its first value.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combinePrevious(initial: Value) -> Signal<(Value, Value), Error> {
return scan((initial, initial)) { previousCombinedValues, newValue in
return (previousCombinedValues.1, newValue)
}
}
/// Like `scan`, but sends only the final value and then immediately completes.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func reduce<U>(initial: U, _ combine: (U, Value) -> U) -> Signal<U, Error> {
// We need to handle the special case in which `signal` sends no values.
// We'll do that by sending `initial` on the output signal (before taking
// the last value).
let (scannedSignalWithInitialValue, outputSignalObserver) = Signal<U, Error>.pipe()
let outputSignal = scannedSignalWithInitialValue.takeLast(1)
// Now that we've got takeLast() listening to the piped signal, send that initial value.
outputSignalObserver.sendNext(initial)
// Pipe the scanned input signal into the output signal.
scan(initial, combine).observe(outputSignalObserver)
return outputSignal
}
/// Aggregates `selfs`'s values into a single combined value. When `self` emits
/// its first value, `combine` is invoked with `initial` as the first argument and
/// that emitted value as the second argument. The result is emitted from the
/// signal returned from `scan`. That result is then passed to `combine` as the
/// first argument when the next value is emitted, and so on.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func scan<U>(initial: U, _ combine: (U, Value) -> U) -> Signal<U, Error> {
return Signal { observer in
var accumulator = initial
return self.observe { event in
observer.action(event.map { value in
accumulator = combine(accumulator, value)
return accumulator
})
}
}
}
}
extension SignalType where Value: Equatable {
/// Forwards only those values from `self` which are not duplicates of the
/// immedately preceding value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipRepeats() -> Signal<Value, Error> {
return skipRepeats(==)
}
}
extension SignalType {
/// Forwards only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipRepeats(isRepeat: (Value, Value) -> Bool) -> Signal<Value, Error> {
return self
.scan((nil, false)) { (accumulated: (Value?, Bool), next: Value) -> (value: Value?, repeated: Bool) in
switch accumulated.0 {
case nil:
return (next, false)
case let prev? where isRepeat(prev, next):
return (prev, true)
case _?:
return (Optional(next), false)
}
}
.filter { !$0.repeated }
.map { $0.value }
.ignoreNil()
}
/// Does not forward any values from `self` until `predicate` returns false,
/// at which point the returned signal behaves exactly like `signal`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipWhile(predicate: Value -> Bool) -> Signal<Value, Error> {
return Signal { observer in
var shouldSkip = true
return self.observe { event in
switch event {
case let .Next(value):
shouldSkip = shouldSkip && predicate(value)
if !shouldSkip {
fallthrough
}
case .Failed, .Completed, .Interrupted:
observer.action(event)
}
}
}
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// Returns a signal which passes through `Next`, `Failed`, and `Interrupted`
/// events from `signal` until `replacement` sends an event, at which point the
/// returned signal will send that event and switch to passing through events
/// from `replacement` instead, regardless of whether `self` has sent events
/// already.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeUntilReplacement(replacement: Signal<Value, Error>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
let signalDisposable = self.observe { event in
switch event {
case .Completed:
break
case .Next, .Failed, .Interrupted:
observer.action(event)
}
}
disposable += signalDisposable
disposable += replacement.observe { event in
signalDisposable?.dispose()
observer.action(event)
}
return disposable
}
}
/// Waits until `self` completes and then forwards the final `count` values
/// on the returned signal.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeLast(count: Int) -> Signal<Value, Error> {
return Signal { observer in
var buffer: [Value] = []
buffer.reserveCapacity(count)
return self.observe { event in
switch event {
case let .Next(value):
// To avoid exceeding the reserved capacity of the buffer, we remove then add.
// Remove elements until we have room to add one more.
while (buffer.count + 1) > count {
buffer.removeAtIndex(0)
}
buffer.append(value)
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
buffer.forEach(observer.sendNext)
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forwards any values from `self` until `predicate` returns false,
/// at which point the returned signal will complete.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeWhile(predicate: Value -> Bool) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { event in
if case let .Next(value) = event where !predicate(value) {
observer.sendCompleted()
} else {
observer.action(event)
}
}
}
}
}
private struct ZipState<Left, Right> {
var values: (left: [Left], right: [Right]) = ([], [])
var completed: (left: Bool, right: Bool) = (false, false)
var isFinished: Bool {
return (completed.left && values.left.isEmpty) || (completed.right && values.right.isEmpty)
}
}
extension SignalType {
/// Zips elements of two signals into pairs. The elements of any Nth pair
/// are the Nth elements of the two input signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zipWith<U>(otherSignal: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let state = Atomic(ZipState<Value, U>())
let disposable = CompositeDisposable()
let flush = {
var tuple: (Value, U)?
var isFinished = false
state.modify { state in
var state = state
guard !state.values.left.isEmpty && !state.values.right.isEmpty else {
return state
}
tuple = (state.values.left.removeFirst(), state.values.right.removeFirst())
isFinished = state.isFinished
return state
}
if let tuple = tuple {
observer.sendNext(tuple)
}
if isFinished {
observer.sendCompleted()
}
}
let onFailed = observer.sendFailed
let onInterrupted = observer.sendInterrupted
disposable += self.observe { event in
switch event {
case let .Next(value):
state.modify { state in
var state = state
state.values.left.append(value)
return state
}
flush()
case let .Failed(error):
onFailed(error)
case .Completed:
state.modify { state in
var state = state
state.completed.left = true
return state
}
flush()
case .Interrupted:
onInterrupted()
}
}
disposable += otherSignal.observe { event in
switch event {
case let .Next(value):
state.modify { state in
var state = state
state.values.right.append(value)
return state
}
flush()
case let .Failed(error):
onFailed(error)
case .Completed:
state.modify { state in
var state = state
state.completed.right = true
return state
}
flush()
case .Interrupted:
onInterrupted()
}
}
return disposable
}
}
/// Applies `operation` to values from `self` with `Success`ful results
/// forwarded on the returned signal and `Failure`s sent as `Failed` events.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func attempt(operation: Value -> Result<(), Error>) -> Signal<Value, Error> {
return attemptMap { value in
return operation(value).map {
return value
}
}
}
/// Applies `operation` to values from `self` with `Success`ful results mapped
/// on the returned signal and `Failure`s sent as `Failed` events.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func attemptMap<U>(operation: Value -> Result<U, Error>) -> Signal<U, Error> {
return Signal { observer in
self.observe { event in
switch event {
case let .Next(value):
operation(value).analysis(
ifSuccess: observer.sendNext,
ifFailure: observer.sendFailed
)
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Throttle values sent by the receiver, so that at least `interval`
/// seconds pass between each, then forwards them on the given scheduler.
///
/// If multiple values are received before the interval has elapsed, the
/// latest value is the one that will be passed on.
///
/// If the input signal terminates while a value is being throttled, that value
/// will be discarded and the returned signal will terminate immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func throttle(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
let state: Atomic<ThrottleState<Value>> = Atomic(ThrottleState())
let schedulerDisposable = SerialDisposable()
let disposable = CompositeDisposable()
disposable.addDisposable(schedulerDisposable)
disposable += self.observe { event in
if case let .Next(value) = event {
var scheduleDate: NSDate!
state.modify { state in
var state = state
state.pendingValue = value
let proposedScheduleDate = state.previousDate?.dateByAddingTimeInterval(interval) ?? scheduler.currentDate
scheduleDate = proposedScheduleDate.laterDate(scheduler.currentDate)
return state
}
schedulerDisposable.innerDisposable = scheduler.scheduleAfter(scheduleDate) {
let previousState = state.modify { state in
var state = state
if state.pendingValue != nil {
state.pendingValue = nil
state.previousDate = scheduleDate
}
return state
}
if let pendingValue = previousState.pendingValue {
observer.sendNext(pendingValue)
}
}
} else {
schedulerDisposable.innerDisposable = scheduler.schedule {
observer.action(event)
}
}
}
return disposable
}
}
}
extension SignalType {
/// Forwards only those values from `self` that have unique identities across the set of
/// all values that have been seen.
///
/// Note: This causes the identities to be retained to check for uniqueness.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func uniqueValues<Identity: Hashable>(transform: Value -> Identity) -> Signal<Value, Error> {
return Signal { observer in
var seenValues: Set<Identity> = []
return self
.observe { event in
switch event {
case let .Next(value):
let identity = transform(value)
if !seenValues.contains(identity) {
seenValues.insert(identity)
fallthrough
}
case .Failed, .Completed, .Interrupted:
observer.action(event)
}
}
}
}
}
extension SignalType where Value: Hashable {
/// Forwards only those values from `self` that are unique across the set of
/// all values that have been seen.
///
/// Note: This causes the values to be retained to check for uniqueness. Providing
/// a function that returns a unique value for each sent value can help you reduce
/// the memory footprint.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func uniqueValues() -> Signal<Value, Error> {
return uniqueValues { $0 }
}
}
private struct ThrottleState<Value> {
var previousDate: NSDate? = nil
var pendingValue: Value? = nil
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>) -> Signal<(A, B), Error> {
return a.combineLatestWith(b)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(A, B, C), Error> {
return combineLatest(a, b)
.combineLatestWith(c)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> {
return combineLatest(a, b, c)
.combineLatestWith(d)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> {
return combineLatest(a, b, c, d)
.combineLatestWith(e)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> {
return combineLatest(a, b, c, d, e)
.combineLatestWith(f)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> {
return combineLatest(a, b, c, d, e, f)
.combineLatestWith(g)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> {
return combineLatest(a, b, c, d, e, f, g)
.combineLatestWith(h)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> {
return combineLatest(a, b, c, d, e, f, g, h)
.combineLatestWith(i)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> {
return combineLatest(a, b, c, d, e, f, g, h, i)
.combineLatestWith(j)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`. No events will be sent if the sequence is empty.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<S: SequenceType, Value, Error where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<[Value], Error> {
var generator = signals.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { signal, next in
signal.combineLatestWith(next).map { $0.0 + [$0.1] }
}
}
return .never
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>) -> Signal<(A, B), Error> {
return a.zipWith(b)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(A, B, C), Error> {
return zip(a, b)
.zipWith(c)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> {
return zip(a, b, c)
.zipWith(d)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> {
return zip(a, b, c, d)
.zipWith(e)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> {
return zip(a, b, c, d, e)
.zipWith(f)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> {
return zip(a, b, c, d, e, f)
.zipWith(g)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> {
return zip(a, b, c, d, e, f, g)
.zipWith(h)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> {
return zip(a, b, c, d, e, f, g, h)
.zipWith(i)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> {
return zip(a, b, c, d, e, f, g, h, i)
.zipWith(j)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`. No events will be sent if the sequence is empty.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<S: SequenceType, Value, Error where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<[Value], Error> {
var generator = signals.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { signal, next in
signal.zipWith(next).map { $0.0 + [$0.1] }
}
}
return .never
}
extension SignalType {
/// Forwards events from `self` until `interval`. Then if signal isn't completed yet,
/// fails with `error` on `scheduler`.
///
/// If the interval is 0, the timeout will be scheduled immediately. The signal
/// must complete synchronously (or on a faster scheduler) to avoid the timeout.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func timeoutWithError(error: Error, afterInterval interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
let disposable = CompositeDisposable()
let date = scheduler.currentDate.dateByAddingTimeInterval(interval)
disposable += scheduler.scheduleAfter(date) {
observer.sendFailed(error)
}
disposable += self.observe(observer)
return disposable
}
}
}
extension SignalType where Error == NoError {
/// Promotes a signal that does not generate failures into one that can.
///
/// This does not actually cause failures to be generated for the given signal,
/// but makes it easier to combine with other signals that may fail; for
/// example, with operators like `combineLatestWith`, `zipWith`, `flatten`, etc.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func promoteErrors<F: ErrorType>(_: F.Type) -> Signal<Value, F> {
return Signal { observer in
return self.observe { event in
switch event {
case let .Next(value):
observer.sendNext(value)
case .Failed:
fatalError("NoError is impossible to construct")
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
}
| b4d7b7c9753d8ba0219e2457deae15da | 32.306 | 341 | 0.67131 | false | false | false | false |
Agarunov/FetchKit | refs/heads/master | Tests/FetchKitTests.swift | bsd-2-clause | 1 | //
// FetchKitTests.swift
// FetchKit
//
// Created by Anton Agarunov on 25.04.17.
//
//
import CoreData
@testable import FetchKit
import XCTest
// swiftlint:disable force_cast force_try implicitly_unwrapped_optional no_grouping_extension
@objc(User)
internal class User: NSManagedObject {
@NSManaged var id: Int64
@NSManaged var firstName: String?
@NSManaged var lastName: String?
@NSManaged var salary: Int64
}
extension User: QueryProtocol { }
internal class FetchKitTests: XCTestCase {
var model: NSManagedObjectModel!
var context: NSManagedObjectContext!
var persistentStore: NSPersistentStore!
var persistentStoreCoordinator: NSPersistentStoreCoordinator!
override func setUp() {
super.setUp()
setupModel()
setupPersistentStoreCoordinator()
populateDatabase()
}
override func tearDown() {
super.tearDown()
// Core Data tear down
try! persistentStoreCoordinator.remove(persistentStore)
}
private func setupModel() {
let userEntity = NSEntityDescription()
userEntity.name = "User"
userEntity.managedObjectClassName = "User"
let idAttribute = NSAttributeDescription()
idAttribute.name = "id"
idAttribute.isOptional = false
idAttribute.attributeType = .integer64AttributeType
let firstNameAttribute = NSAttributeDescription()
firstNameAttribute.name = "firstName"
firstNameAttribute.isOptional = true
firstNameAttribute.attributeType = .stringAttributeType
let lastNameAttribute = NSAttributeDescription()
lastNameAttribute.name = "lastName"
lastNameAttribute.isOptional = true
lastNameAttribute.attributeType = .stringAttributeType
let salaryAttribute = NSAttributeDescription()
salaryAttribute.name = "salary"
salaryAttribute.isOptional = false
salaryAttribute.attributeType = .integer64AttributeType
userEntity.properties = [idAttribute, firstNameAttribute, lastNameAttribute, salaryAttribute]
model = NSManagedObjectModel()
model.entities = [userEntity]
}
private func setupPersistentStoreCoordinator() {
persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
let tmpDirUrl = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent("test.sqlite")
if FileManager.default.fileExists(atPath: tmpDirUrl.path) {
try! FileManager.default.removeItem(at: tmpDirUrl)
}
FileManager.default.createFile(atPath: tmpDirUrl.path, contents: nil, attributes: nil)
persistentStore = try! persistentStoreCoordinator.addPersistentStore(
ofType: NSSQLiteStoreType,
configurationName: nil,
at: tmpDirUrl,
options: nil
)
context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.persistentStoreCoordinator = persistentStoreCoordinator
}
private func populateDatabase() {
let data: [(String, String, Int64)] =
[("Ivan", "Ivanov", 10_000), ("John", "Williams", 12_000),
("Joe", "Cole", 10_000), ("Alex", "Finch", 23_000), ("John", "Donn", 22_000)]
for (idx, name) in data.enumerated() {
let user = NSEntityDescription.insertNewObject(
forEntityName: User.fk_entityName,
into: context) as! User
user.id = Int64(idx)
user.firstName = name.0
user.lastName = name.1
user.salary = name.2
}
try! context.save()
}
}
| 9c7f6935118cc90e00556d8e33ff84fe | 31.347458 | 101 | 0.647629 | false | true | false | false |
visualitysoftware/swift-sdk | refs/heads/master | CloudBoostTests/CloudQueueTest.swift | mit | 1 | //
// CloudQueueTest.swift
// CloudBoost
//
// Created by Randhir Singh on 19/04/16.
// Copyright © 2016 Randhir Singh. All rights reserved.
//
import XCTest
@testable import CloudBoost
class CloudQueueTest: XCTestCase {
override func setUp() {
super.setUp()
let app = CloudApp.init(appID: "xckzjbmtsbfb", appKey: "345f3324-c73c-4b15-94b5-9e89356c1b4e")
app.setIsLogging(true)
app.setMasterKey("f5cc5cb3-ba0d-446d-9e51-e09be23c540d")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// Should return no queue objects when there are no queues inthe database
func testGetAllWithNoQueueInDatabase(){
let exp = expectationWithDescription("return no queue on an empty database")
CloudQueue.getAll({
response in
response.log()
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should get the message when expires is set to future date.
func testGetMessageExpireSetToFuture(){
let exp = expectationWithDescription("get message when expire set to future date")
let today = NSDate()
let tomorrow = NSDate(timeIntervalSinceReferenceDate: today.timeIntervalSinceReferenceDate + 60*60*24)
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let queueMessage = QueueMessage()
queueMessage.setExpires(tomorrow)
queueMessage.setMessage("data")
queue.addMessage(queueMessage, callback: {
response in
response.log()
if response.success {
queue.getMessage(1, callback: {
response in
response.log()
XCTAssert(response.success)
exp.fulfill()
})
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should add data into the Queue
func testAddDataInQueue(){
let exp = expectationWithDescription("add data into the queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
queue.addMessage("Randhir", callback: {
response in
response.log()
if let res = response.object as? NSMutableDictionary {
let queMessage = QueueMessage()
queMessage.setDocument(res)
if queMessage.getMessage()! == "Randhir" {
print("Data matches")
}else{
XCTAssert(false)
}
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// create and delete a queue
func testCreateDeleteQueue(){
let exp = expectationWithDescription("create and delete queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
try! queue.create({
response in
if response.success {
queue.delete({
response in
XCTAssert(response.success)
exp.fulfill()
})
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should add expires into the queue message.
func testAddExpiresToData(){
let exp = expectationWithDescription("add expires field to queue messages")
let today = NSDate()
let tomorrow = NSDate(timeIntervalSinceReferenceDate: today.timeIntervalSinceReferenceDate + 60*60*24)
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let queueMessage = QueueMessage()
queueMessage.setExpires(tomorrow)
queueMessage.setMessage("data")
queue.addMessage(queueMessage, callback: {
response in
response.log()
XCTAssert(response.success)
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should add current time as expires into the queue
func testAddCurrentTimeExpires(){
let exp = expectationWithDescription("add current time as expires in queue messages")
let today = NSDate()
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let queueMessage = QueueMessage()
queueMessage.setExpires(today)
queueMessage.setMessage("data")
queue.addMessage(queueMessage, callback: {
response in
response.log()
XCTAssert(response.success)
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should add multiple messages and get all messages
func testAddMultipleMessages(){
let exp = expectationWithDescription("add multiple messages in a queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
// Addding first message
queue.addMessage("sample", callback: {
response in
response.log()
if let res = response.object as? QueueMessage {
if res.getMessage()! == "sample" {
// Add the second message
queue.addMessage("sample1", callback: {
response in
if let res = response.object as? QueueMessage {
if res.getMessage()! == "sample1" {
// now get the entire queue
queue.getAllMessages({
response in
response.log()
if let queueMessages = response.object as? [QueueMessage] {
if queueMessages.count == 2 {
XCTAssert(true)
}else{
XCTAssert(false)
}
}
exp.fulfill()
})
}else{
XCTAssert(false)
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should update data into the Queue
func testUpdateData(){
let exp = expectationWithDescription("update data in queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
// Addding message
let message = "sample"
queue.addMessage(message, callback: {
response in
response.log()
if let res = response.object as? NSMutableDictionary {
let queMessage = QueueMessage()
queMessage.setDocument(res)
if queMessage.getMessage()! == message {
// Update the message
let message2 = "Sample2"
queMessage.setMessage(message2)
try! queue.updateMessage([queMessage], callback: {
response in
if let res = response.object as? NSMutableDictionary {
let queMessage = QueueMessage()
queMessage.setDocument(res)
if queMessage.getMessage()! == message2 {
XCTAssert(true)
}else{
XCTAssert(false)
}
exp.fulfill()
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should not update data in the queue which is not saved
func testUpdateUnsavedData(){
let exp = expectationWithDescription("should not update unsaved data")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("Sample")
do{
try queue.updateMessage([message], callback: {
response in
response.log()
XCTAssert(false)
exp.fulfill()
})
} catch {
print("Error in arguments")
XCTAssert(true)
exp.fulfill()
}
waitForExpectationsWithTimeout(30, handler: nil)
}
// should create the queue
func testCreateQueue(){
let exp = expectationWithDescription("should create the queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
try! queue.create({
response in
if queue.getCreatedAt() != nil && queue.getUpdatedAt() != nil {
print("Queue created successfully")
}else{
XCTAssert(response.success)
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should add an array into the queue
func testAddArrayInQueue(){
let exp = expectationWithDescription("add an array to queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
queue.addMessage(["sample","sample2"], callback: {
response in
let queueArr = response.object as! [QueueMessage]
if queueArr.count == 2{
XCTAssert(true)
}else{
XCTAssert(false)
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// can add multiple messages in the same queue
func testAddMultipleMessagesSameQueue(){
let exp = expectationWithDescription("add multiple messages in the same queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
// Addding message
queue.addMessage(["sample","sample1"], callback: {
response in
response.log()
if let res = response.object as? [QueueMessage] {
if res.count == 2 {
queue.addMessage(["sample3","sample4"], callback: {
response in
if let res = response.object as? [QueueMessage] {
if res.count == 2 {
queue.getAllMessages({
response in
if let res = response.object as? [QueueMessage] {
if res.count == 4 {
XCTAssert(true)
}else{
XCTAssert(false)
}
exp.fulfill()
}else{
XCTAssert(false)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should not add null data into the Queue
func testShouldNotAddNullData(){
let exp = expectationWithDescription("should not add null data into the queue")
let qName = Util.makeString(5)
let q = CloudQueue(queueName: qName, queueType: nil)
q.addMessage("", callback: {
response in
response.log()
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
//should not create queue with an empty name
func testCreateQueueEmptyName(){
let exp = expectationWithDescription("should not create a queue with an empty name")
let queue = CloudQueue(queueName: nil, queueType: nil)
do {
try queue.create({
response in
response.log()
XCTAssert(response.success)
exp.fulfill()
})
} catch {
print("stopped due to passing nil as queue name")
exp.fulfill()
}
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should add and get data from the queue
func testAddAndGetData(){
let exp = expectationWithDescription("add and get data from the queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
// Addding message
queue.addMessage("sample", callback: {
response in
response.log()
if let res = response.object as? QueueMessage {
if res.getMessage()! == "sample" {
queue.getAllMessages({
response in
if let res = response.object as? [QueueMessage] {
if res.count == 1 && res[0].getMessage()! == "sample"{
XCTAssert(true)
}else{
XCTAssert(false)
}
}else{
XCTAssert(false)
exp.fulfill()
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should peek
func testShouldPeek(){
let exp = expectationWithDescription("should peek")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("data")
queue.addMessage(message, callback: {
response in
let mes = response.object as! QueueMessage
if mes.getMessage()! == "data" {
queue.peekMessage(1, callback: {
response in
let mess = response.object as! QueueMessage
if mess.getMessage()! == "data" {
XCTAssert(true)
}else{
XCTAssert(false)
}
exp.fulfill()
})
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should get the messages in FIFO
func testGetMessageInFIFO(){
let exp = expectationWithDescription("get message in FIFO fashion")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
// Addding first message
queue.addMessage("sample", callback: {
response in
response.log()
if let res = response.object as? QueueMessage {
if res.getMessage()! == "sample" {
// Add the second message
queue.addMessage("sample1", callback: {
response in
if let res = response.object as? QueueMessage {
if res.getMessage()! == "sample1" {
// now get the entire queue
queue.getMessage(nil,callback: {
response in
let mess = response.object as! QueueMessage
if mess.getMessage()! == "sample" {
queue.getMessage(nil, callback: {
response in
let mess = response.object as! QueueMessage
if mess.getMessage()! == "sample1" {
print("data matches")
XCTAssert(true)
}
else{
XCTAssert(false)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(60, handler: nil)
}
// Should peek 2 messages at the same time
func testPeekTwoMessages(){
let exp = expectationWithDescription("peek two messages at the same time")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
// Addding first message
queue.addMessage("sample", callback: {
response in
response.log()
if let res = response.object as? QueueMessage {
if res.getMessage()! == "sample" {
// Add the second message
queue.addMessage("sample1", callback: {
response in
if let res = response.object as? QueueMessage {
if res.getMessage()! == "sample1" {
// now get the entire queue
queue.peekMessage(2, callback: {
response in
let messArr = response.object as! [QueueMessage]
if messArr.count == 2 {
print("count matches")
XCTAssert(true)
}else{
XCTAssert(false)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(60, handler: nil)
}
// Should get 2 messages at the same time
func testGetTwoMessages(){
let exp = expectationWithDescription("get two messages at the same time")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
// Addding first message
queue.addMessage("sample", callback: {
response in
response.log()
if let res = response.object as? QueueMessage {
if res.getMessage()! == "sample" {
// Add the second message
queue.addMessage("sample1", callback: {
response in
if let res = response.object as? QueueMessage {
if res.getMessage()! == "sample1" {
// now get the entire queue
queue.getMessage(2, callback: {
response in
let messArr = response.object as! [QueueMessage]
if messArr.count == 2 {
print("count matches")
XCTAssert(true)
}else{
XCTAssert(false)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(60, handler: nil)
}
// Should not getMessage message with the delay
func testNoMessageWithDelay(){
let exp = expectationWithDescription("should not get message with delay")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("Anurag")
message.setDelay(3000)
// Addding first message
queue.addMessage(message, callback: {
response in
if let res = response.object as? QueueMessage {
if res.getMessage()! == "Anurag" {
queue.getMessage(nil, callback: {
response in
if let _ = response.object as? QueueMessage {
XCTAssert(false)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// should give an error if queue doesnot exists.
func testEmptyQueue(){
let exp = expectationWithDescription("should try getmessages on an empty queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
queue.getMessage(1, callback: {
response in
if let _ = response.object as? QueueMessage {
XCTAssert(false)
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// should not get the same message twice
func testGetMessageTwice(){
let exp = expectationWithDescription("should not get message with delay")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("Anurag")
queue.addMessage(message, callback: {
response in
if let res = response.object as? QueueMessage {
if res.getMessage()! == "Anurag" {
queue.getMessage(nil, callback: {
response in
if let mess = response.object as? QueueMessage {
if mess.getMessage()! == "Anurag" {
queue.getMessage(nil, callback: {
response in
if let _ = response.object as? QueueMessage {
XCTAssert(false)
}else{
print("not retrieved twice")
XCTAssert(true)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should be able to get messages after the delay
func testGetMessageAfterDelay(){
let exp = expectationWithDescription("should get message after delay")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("Anurag")
message.setDelay(1)
// Addding first message
queue.addMessage(message, callback: {
response in
if let res = response.object as? QueueMessage {
if res.getMessage()! == "Anurag" {
queue.getMessage(nil, callback: {
response in
if let _ = response.object as? QueueMessage {
XCTAssert(true)
}else{
XCTAssert(false)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should be able to get message with an id
func testGetMessageWithID(){
let exp = expectationWithDescription("should get message with ID")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("Anurag")
// Addding first message
queue.addMessage(message, callback: {
response in
if let res = response.object as? QueueMessage {
queue.getMessageById(res.getId()!, callback: {
response in
if let resp = response.object as? QueueMessage {
if resp.getMessage() == "Anurag"{
print("Matching data")
XCTAssert(true)
}else{
XCTAssert(false)
}
}else{
XCTAssert(false)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should get null when invalid message id is requested
func testGetMessageWithInvalidID(){
let exp = expectationWithDescription("should not message with invalid ID")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("Anurag")
// Addding first message
queue.addMessage(message, callback: {
response in
if let _ = response.object as? QueueMessage {
queue.getMessageById(Util.makeString(5), callback: {
response in
if let _ = response.object as? QueueMessage {
XCTAssert(false)
}else{
print("nothing retrieved")
XCTAssert(true)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should delete message with message id
func testDeleteItemWithMessageID(){
let exp = expectationWithDescription("should delete message with ID")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("Anurag")
// Addding first message
queue.addMessage(message, callback: {
response in
if let res = response.object as? QueueMessage {
queue.deleteMessage(res.getId()!, callback: {
response in
if let resp = response.object as? QueueMessage {
if resp.getId()! == res.getId()!{
print("Matching IDs, data deleted")
XCTAssert(true)
}else{
XCTAssert(false)
}
}else{
XCTAssert(false)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should delete message by passing queueMessage to the function
func testDeleteItemWithMessageObject(){
let exp = expectationWithDescription("should delete message with queueMessage Object")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("Anurag")
// Addding first message
queue.addMessage(message, callback: {
response in
if let res = response.object as? QueueMessage {
queue.deleteMessage(res, callback: {
response in
if let resp = response.object as? QueueMessage {
if resp.getId()! == res.getId()!{
print("Matching IDs, data deleted")
XCTAssert(true)
}else{
XCTAssert(false)
}
}else{
XCTAssert(false)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should not get the message after it was deleted
func testGettingDeletedMessage(){
let exp = expectationWithDescription("should not get message that have been deleted")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
let message = QueueMessage()
message.setMessage("Anurag")
// Addding first message
queue.addMessage(message, callback: {
response in
if let res = response.object as? QueueMessage {
queue.deleteMessage(res, callback: {
response in
if let resp = response.object as? QueueMessage {
queue.getMessageById(resp.getId()!, callback: {
response in
if let _ = response.object as? QueueMessage {
XCTAssert(false)
}else{
print("nothing retrieved")
XCTAssert(true)
}
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should add subscriber to the queue
func testAddSubscriber(){
let exp = expectationWithDescription("Should add subscriber to the queue")
let qName = Util.makeString(5)
let queue = CloudQueue(queueName: qName, queueType: nil)
let url = "http://sample.sample.com"
queue.addSubscriber(url, callback: {
response in
let subs = queue.getSubscribers()!
if subs.indexOf(url) != nil {
print("Element exists")
}else{
XCTAssert(false)
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should multiple subscribers to the queue
func testAddMultipleSubscriber(){
let exp = expectationWithDescription("Should add multiple subscriber to the queue")
let qName = Util.makeString(5)
let queue = CloudQueue(queueName: qName, queueType: nil)
let url = ["http://sample.sample.com", "http://sample1.cloudapp.net"]
queue.addSubscriber(url, callback: {
response in
let subs = queue.getSubscribers()!
if subs.indexOf(url[0]) != nil && subs.indexOf(url[1]) != nil {
print("Element exists")
}else{
XCTAssert(false)
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should remove subscriber from the queue
func testRemoveSubscriber(){
let exp = expectationWithDescription("Should remove subscriber from the queue")
let qName = Util.makeString(5)
let queue = CloudQueue(queueName: qName, queueType: nil)
let url = "http://sample.sample.com"
queue.removeSubscriber(url, callback: {
response in
let subs = queue.getSubscribers()!
if subs.indexOf(url) != nil {
print("Element exists, fail")
XCTAssert(false)
}else{
XCTAssert(true)
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should remove multiple subscriber from the queue
func testRemoveMultipleSubscriber(){
let exp = expectationWithDescription("Should remove multiple subscriber from the queue")
let qName = Util.makeString(5)
let queue = CloudQueue(queueName: qName, queueType: nil)
let url = ["http://sample.sample.com", "http://sample1.cloudapp.net"]
queue.removeSubscriber(url, callback: {
response in
let subs = queue.getSubscribers()!
if subs.indexOf(url[0]) != nil && subs.indexOf(url[1]) != nil {
print("Element exists, fail")
XCTAssert(false)
}else{
XCTAssert(true)
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should not add subscriber with invalid URL
func testAddInvalidSubscriber(){
let exp = expectationWithDescription("Should add subscriber to the queue")
let qName = Util.makeString(5)
let queue = CloudQueue(queueName: qName, queueType: nil)
let url = "sample,sample"
queue.addSubscriber(url, callback: {
response in
let subs = queue.getSubscribers()!
if subs.indexOf(url) != nil {
print("Element added, fail")
XCTAssert(false)
}else{
XCTAssert(true)
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should add a subscriber and then remove a subscriber from the queue
func testAddRemoveSubscriber(){
let exp = expectationWithDescription("Should add subscriber to the queue")
let qName = Util.makeString(5)
let queue = CloudQueue(queueName: qName, queueType: nil)
let url = "http://sample.sample.com"
queue.addSubscriber(url, callback: {
response in
let subs = queue.getSubscribers()!
if subs.indexOf(url) != nil {
queue.removeSubscriber(url, callback: {
response in
if let subs = queue.getSubscribers() {
if subs.indexOf(url) != nil {
XCTAssert(false)
}else{
print("Removed subscriber!!")
}
exp.fulfill()
}else{
XCTAssert(false)
exp.fulfill()
}
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should delete the queue
func testDeleteQueue(){
let exp = expectationWithDescription("should delete queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
queue.addMessage("sample", callback: {
response in
let qmess = response.object as! QueueMessage
if qmess.getMessage()! == "sample"{
queue.delete({
response in
XCTAssert(response.success)
queue.getMessage(1, callback: {
response in
if let _ = response.object as? QueueMessage {
XCTAssert(false)
}else{
print("nothing found in queue")
XCTAssert(true)
}
exp.fulfill()
})
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// should clear queue
func testClearQueue(){
let exp = expectationWithDescription("should clear queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
queue.addMessage("sample", callback: {
response in
let qmess = response.object as! QueueMessage
if qmess.getMessage()! == "sample"{
queue.clear({
response in
XCTAssert(response.success)
queue.getMessage(1, callback: {
response in
if let _ = response.object as? QueueMessage {
XCTAssert(false)
}else{
print("nothing found in queue")
XCTAssert(true)
}
exp.fulfill()
})
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should get the queue
func testShouldGetQueue(){
let exp = expectationWithDescription("should get the queue")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
queue.addMessage("sample", callback: {
response in
let qmess = response.object as! QueueMessage
if qmess.getMessage()! == "sample"{
CloudQueue.get(queueName,callback: {
response in
XCTAssert(response.success)
response.log()
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should not get the queue with null name
func testGetQueueWithNullName(){
let exp = expectationWithDescription("should not get the queue with invalid name")
let queueName = Util.makeString(5)
let queue = CloudQueue(queueName: queueName, queueType: nil)
queue.addMessage("sample", callback: {
response in
let qmess = response.object as! QueueMessage
if qmess.getMessage()! == "sample"{
CloudQueue.get("null",callback: {
response in
if response.success {
XCTAssert(false)
}else{
XCTAssert(true)
}
response.log()
exp.fulfill()
})
}else{
XCTAssert(false)
exp.fulfill()
}
})
waitForExpectationsWithTimeout(30, handler: nil)
}
// Should get All Queues
func testGetAllQueues(){
let exp = expectationWithDescription("should get all queues")
CloudQueue.getAll({
response in
if let queues = response.object as? [CloudQueue] {
print("Number of queues: \(queues.count)")
}else{
XCTAssert(false)
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
func testGetParameters() {
let exp = expectationWithDescription("askj")
let msg = QueueMessage()
msg.setMessage("Sample")
msg.setExpires(NSDate().dateByAddingTimeInterval(NSTimeInterval.abs(10000)))
let queue = CloudQueue(queueName: "asd", queueType: nil)
queue.addMessage(msg, callback: { response in
response.log()
})
let query = CloudQuery(tableName: "Student")
let geoPoint = try! CloudGeoPoint(latitude: 17, longitude: 80)
query.include("courses")
query.near("location", geoPoint: geoPoint, maxDistance: 55, minDistance: 10)
try! query.find({ res in
if let list = res.object as? [NSMutableDictionary] {
if list.count > 0 {
}
}
exp.fulfill()
})
waitForExpectationsWithTimeout(30, handler: nil)
}
}
| 19a30a2e281e5e98bcc47f5f025ed7e8 | 36.567747 | 111 | 0.462938 | false | false | false | false |
JohnEstropia/CoreStore | refs/heads/develop | CoreStoreTests/StorageInterfaceTests.swift | mit | 1 | //
// StorageInterfaceTests.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
import XCTest
@testable
import CoreStore
//MARK: - StorageInterfaceTests
final class StorageInterfaceTests: XCTestCase {
@objc
dynamic func test_ThatDefaultInMemoryStores_ConfigureCorrectly() {
let store = InMemoryStore()
XCTAssertEqual(type(of: store).storeType, NSInMemoryStoreType)
XCTAssertNil(store.configuration)
XCTAssertNil(store.storeOptions)
}
@objc
dynamic func test_ThatCustomInMemoryStores_ConfigureCorrectly() {
let store = InMemoryStore(configuration: "config1")
XCTAssertEqual(type(of: store).storeType, NSInMemoryStoreType)
XCTAssertEqual(store.configuration, "config1")
XCTAssertNil(store.storeOptions)
}
@objc
dynamic func test_ThatSQLiteStoreDefaultDirectories_AreCorrect() {
#if os(tvOS)
let systemDirectorySearchPath = FileManager.SearchPathDirectory.cachesDirectory
#else
let systemDirectorySearchPath = FileManager.SearchPathDirectory.applicationSupportDirectory
#endif
let defaultSystemDirectory = FileManager.default
.urls(for: systemDirectorySearchPath, in: .userDomainMask).first!
let defaultRootDirectory = defaultSystemDirectory.appendingPathComponent(
Bundle.main.bundleIdentifier ?? "com.CoreStore.DataStack",
isDirectory: true
)
let applicationName = (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? "CoreData"
let defaultFileURL = defaultRootDirectory
.appendingPathComponent(applicationName, isDirectory: false)
.appendingPathExtension("sqlite")
XCTAssertEqual(SQLiteStore.defaultRootDirectory, defaultRootDirectory)
XCTAssertEqual(SQLiteStore.defaultFileURL, defaultFileURL)
}
@objc
dynamic func test_ThatDefaultSQLiteStores_ConfigureCorrectly() {
let store = SQLiteStore()
XCTAssertEqual(type(of: store).storeType, NSSQLiteStoreType)
XCTAssertNil(store.configuration)
XCTAssertEqual(
store.storeOptions as NSDictionary?,
[NSSQLitePragmasOption: ["journal_mode": "WAL"],
NSBinaryStoreInsecureDecodingCompatibilityOption: true] as NSDictionary
)
XCTAssertEqual(store.fileURL, SQLiteStore.defaultFileURL)
XCTAssertTrue(store.migrationMappingProviders.isEmpty)
XCTAssertEqual(store.localStorageOptions, .none)
}
@objc
dynamic func test_ThatFileURLSQLiteStores_ConfigureCorrectly() {
let fileURL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString, isDirectory: false)
.appendingPathExtension("db")
let mappingProvider = XcodeSchemaMappingProvider(
from: "V1", to: "V2",
mappingModelBundle: Bundle.module
)
let store = SQLiteStore(
fileURL: fileURL,
configuration: "config1",
migrationMappingProviders: [mappingProvider],
localStorageOptions: .recreateStoreOnModelMismatch
)
XCTAssertEqual(type(of: store).storeType, NSSQLiteStoreType)
XCTAssertEqual(store.configuration, "config1")
XCTAssertEqual(
store.storeOptions as NSDictionary?,
[NSSQLitePragmasOption: ["journal_mode": "WAL"],
NSBinaryStoreInsecureDecodingCompatibilityOption: true] as NSDictionary
)
XCTAssertEqual(store.fileURL, fileURL)
XCTAssertEqual(store.migrationMappingProviders as! [XcodeSchemaMappingProvider], [mappingProvider])
XCTAssertEqual(store.localStorageOptions, [.recreateStoreOnModelMismatch])
}
@objc
dynamic func test_ThatFileNameSQLiteStores_ConfigureCorrectly() {
let fileName = UUID().uuidString + ".db"
let mappingProvider = XcodeSchemaMappingProvider(
from: "V1", to: "V2",
mappingModelBundle: Bundle.module
)
let store = SQLiteStore(
fileName: fileName,
configuration: "config1",
migrationMappingProviders: [mappingProvider],
localStorageOptions: .recreateStoreOnModelMismatch
)
XCTAssertEqual(type(of: store).storeType, NSSQLiteStoreType)
XCTAssertEqual(store.configuration, "config1")
XCTAssertEqual(
store.storeOptions as NSDictionary?,
[NSSQLitePragmasOption: ["journal_mode": "WAL"],
NSBinaryStoreInsecureDecodingCompatibilityOption: true] as NSDictionary
)
XCTAssertEqual(store.fileURL.deletingLastPathComponent(), SQLiteStore.defaultRootDirectory)
XCTAssertEqual(store.fileURL.lastPathComponent, fileName)
XCTAssertEqual(store.migrationMappingProviders as! [XcodeSchemaMappingProvider], [mappingProvider])
XCTAssertEqual(store.localStorageOptions, [.recreateStoreOnModelMismatch])
}
@objc
dynamic func test_ThatLegacySQLiteStoreDefaultDirectories_AreCorrect() {
#if os(tvOS)
let systemDirectorySearchPath = FileManager.SearchPathDirectory.cachesDirectory
#else
let systemDirectorySearchPath = FileManager.SearchPathDirectory.applicationSupportDirectory
#endif
let legacyDefaultRootDirectory = FileManager.default.urls(
for: systemDirectorySearchPath,
in: .userDomainMask).first!
let legacyDefaultFileURL = legacyDefaultRootDirectory
.appendingPathComponent(DataStack.applicationName, isDirectory: false)
.appendingPathExtension("sqlite")
XCTAssertEqual(SQLiteStore.legacyDefaultRootDirectory, legacyDefaultRootDirectory)
XCTAssertEqual(SQLiteStore.legacyDefaultFileURL, legacyDefaultFileURL)
}
@objc
dynamic func test_ThatDefaultLegacySQLiteStores_ConfigureCorrectly() {
let store = SQLiteStore.legacy()
XCTAssertEqual(type(of: store).storeType, NSSQLiteStoreType)
XCTAssertNil(store.configuration)
XCTAssertEqual(
store.storeOptions as NSDictionary?,
[NSSQLitePragmasOption: ["journal_mode": "WAL"],
NSBinaryStoreInsecureDecodingCompatibilityOption: true] as NSDictionary
)
XCTAssertEqual(store.fileURL, SQLiteStore.legacyDefaultFileURL)
XCTAssertTrue(store.migrationMappingProviders.isEmpty)
XCTAssertEqual(store.localStorageOptions, .none)
}
@objc
dynamic func test_ThatFileNameLegacySQLiteStores_ConfigureCorrectly() {
let fileName = UUID().uuidString + ".db"
let mappingProvider = XcodeSchemaMappingProvider(
from: "V1", to: "V2",
mappingModelBundle: Bundle.module
)
let store = SQLiteStore.legacy(
fileName: fileName,
configuration: "config1",
migrationMappingProviders: [mappingProvider],
localStorageOptions: .recreateStoreOnModelMismatch
)
XCTAssertEqual(type(of: store).storeType, NSSQLiteStoreType)
XCTAssertEqual(store.configuration, "config1")
XCTAssertEqual(
store.storeOptions as NSDictionary?,
[NSSQLitePragmasOption: ["journal_mode": "WAL"],
NSBinaryStoreInsecureDecodingCompatibilityOption: true] as NSDictionary
)
XCTAssertEqual(store.fileURL.deletingLastPathComponent(), SQLiteStore.legacyDefaultRootDirectory)
XCTAssertEqual(store.fileURL.lastPathComponent, fileName)
XCTAssertEqual(store.migrationMappingProviders as! [XcodeSchemaMappingProvider], [mappingProvider])
XCTAssertEqual(store.localStorageOptions, [.recreateStoreOnModelMismatch])
}
}
| c897dcfc2cd7613b94520c246b49f79e | 40.271493 | 113 | 0.686657 | false | true | false | false |
NestedWorld/NestedWorld-iOS | refs/heads/develop | nestedworld/nestedworldTests/UserNotNilTests.swift | mit | 1 | //
// UserTests.swift
// nestedworld
//
// Created by Jean-Antoine Dupont on 26/04/2016.
// Copyright © 2016 NestedWorld. All rights reserved.
//
import XCTest
class UserNotNilTests: UserTestsProtocol
{
private var errorMessageRoot: String
private let email: String = "[email protected]"
private let nickname: String = "test"
private let gender: String = "male"
private let birthDate:String = "1942-08-09T12:42:42.6789+00:00"
private let city: String = "Paris"
private let background: String = "http://background-test.nestedworld.com"
private let avatar: String = "http://avatar-test.nestedworld.com"
private let registerDate: String = "2010-01-27T17:42:42.1234+00:00"
private let isActive: Bool = true
init(errorMsgRoot: String)
{
self.errorMessageRoot = errorMsgRoot + "[NOT NIL]: "
}
func testAll()
{
self.testEverythingIsOk()
self.testEmail()
self.testNickname()
self.testGender()
self.testBirthDate()
self.testCity()
self.testBackground()
self.testAvatar()
self.testRegisterDate()
self.testIsActive()
}
func testEverythingIsOk()
{
let test = User(email: self.email, nickname: self.nickname,
gender: self.gender, birthDate: self.birthDate, city: self.city,
background: self.background, avatar: self.avatar,
registerDate: self.registerDate, isActive: self.isActive)
XCTAssertNotNil(test, self.errorMessageRoot + "..")
}
func testEmail()
{
}
func testNickname()
{
}
func testGender()
{
let testCases: [AnyObject?] = [
"", // Empty
"male", // Valid
"Pirate", // Not existing
"FEmaLE", // With upper case
nil // Nil
]
for value in testCases {
let test = User(email: self.email, nickname: self.nickname,
gender: value as? String, birthDate: self.birthDate, city: self.city,
background: self.background, avatar: self.avatar,
registerDate: self.registerDate, isActive: self.isActive)
XCTAssertNotNil(test, self.errorMessageRoot + "[GENDER]: Test has failed with value: \"\(value)\"")
}
}
func testBirthDate()
{
let testCases: [AnyObject?] = [
"", // Empty
"2170-08-09T12:42:42.6789+00:00", // Not happened
"coucou", // Bad
nil // Nil
]
for value in testCases {
let test = User(email: self.email, nickname: self.nickname,
gender: self.gender, birthDate: value as? String, city: self.city,
background: self.background, avatar: self.avatar,
registerDate: self.registerDate, isActive: self.isActive)
XCTAssertNotNil(test, self.errorMessageRoot + "[BIRTHDATE]: Test has failed with value: \"\(value)\"")
}
}
func testCity()
{
let testCases: [AnyObject?] = [
"", // Empty
"Lille", // Existing
"EIPCity", // Not existing
nil // Nil
]
for value in testCases {
let test = User(email: self.email, nickname: self.nickname,
gender: self.gender, birthDate: self.birthDate, city: value as? String,
background: self.background, avatar: self.avatar,
registerDate: self.registerDate, isActive: self.isActive)
XCTAssertNotNil(test, self.errorMessageRoot + "[CITY]: Test has failed with value: \"\(value)\"")
}
}
func testBackground()
{
let testCases: [AnyObject?] = [
"", // Empty
"http://image-test-background.nestedworld.com", // Existing
"http://fake.xxfake-backgroundxx.fake", // Not existing
nil // Nil
]
for value in testCases {
let test = User(email: self.email, nickname: self.nickname,
gender: self.gender, birthDate: self.birthDate, city: self.city,
background: value as? String, avatar: self.avatar,
registerDate: self.registerDate, isActive: self.isActive)
XCTAssertNotNil(test, self.errorMessageRoot + "[BACKGROUND]: Test has failed with value: \"\(value)\"")
}
}
func testAvatar()
{
let testCases: [AnyObject?] = [
"", // Empty
"http://image-test-avatar.nestedworld.com", // Existing
"http://fake.xxfake-avatarxx.fake", // Not existing
nil // Nil
]
for value in testCases {
let test = User(email: self.email, nickname: self.nickname,
gender: self.gender, birthDate: self.birthDate, city: self.city,
background: self.background, avatar: value as? String,
registerDate: self.registerDate, isActive: self.isActive)
XCTAssertNotNil(test, self.errorMessageRoot + "[AVATAR]: Test has failed with value: \"\(value)\"")
}
}
func testRegisterDate()
{
}
func testIsActive()
{
}
} | 682e33bf9d47579d076fe637e741ce7e | 34.308176 | 115 | 0.530732 | false | true | false | false |
Authman2/Pix | refs/heads/master | Pods/Eureka/Source/Rows/CheckRow.swift | apache-2.0 | 4 | // CheckRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: CheckCell
public final class CheckCell : Cell<Bool>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func update() {
super.update()
accessoryType = row.value == true ? .checkmark : .none
editingAccessoryType = accessoryType
selectionStyle = .default
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
if row.isDisabled {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 0.3)
selectionStyle = .none
}
else {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
}
}
open override func setup() {
super.setup()
accessoryType = .checkmark
editingAccessoryType = accessoryType
}
open override func didSelect() {
row.value = row.value ?? false ? false : true
row.deselect()
row.updateCell()
}
}
// MARK: CheckRow
open class _CheckRow: Row<CheckCell> {
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
}
///// Boolean row that has a checkmark as accessoryType
public final class CheckRow: _CheckRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| d00b7b4e23299627a411523342cca21c | 32.988235 | 87 | 0.664244 | false | false | false | false |
cactuslab/Succulent | refs/heads/develop | Succulent/Classes/Router.swift | mit | 1 | //
// Router.swift
// Succulent
//
// Created by Karl von Randow on 15/01/17.
// Copyright © 2017 Cactuslab. All rights reserved.
//
import Foundation
public typealias RoutingResultBLock = (RoutingResult) -> ()
/// The result of routing
public enum RoutingResult {
case response(_: Response)
case error(_: Error)
case noRoute
}
public class Router {
private var routes = [Route]()
public init() {
}
public func add(_ path: String) -> Route {
let route = Route(path)
routes.append(route)
return route
}
public func handle(request: Request, resultBlock: @escaping RoutingResultBLock) {
var bestScore = -1
var bestRoute: Route?
for route in routes {
if let score = route.match(request: request) {
if score >= bestScore {
bestScore = score
bestRoute = route
}
}
}
if let route = bestRoute {
route.handle(request: request, resultBlock: resultBlock)
} else {
resultBlock(.noRoute)
}
}
public func handleSync(request: Request) -> RoutingResult {
var result: RoutingResult?
let semaphore = DispatchSemaphore(value: 0)
handle(request: request) { theResult in
result = theResult
semaphore.signal()
}
semaphore.wait()
return result!
}
}
/// The status code of a response
public enum ResponseStatus: Equatable, CustomStringConvertible {
public static func ==(lhs: ResponseStatus, rhs: ResponseStatus) -> Bool {
return lhs.code == rhs.code
}
case notFound
case ok
case notModified
case internalServerError
case other(code: Int)
public var code: Int {
switch self {
case .notFound: return 404
case .ok: return 200
case .notModified: return 304
case .internalServerError: return 500
case .other(let code): return code
}
}
public var message: String {
return HTTPURLResponse.localizedString(forStatusCode: code)
}
public var description: String {
return "\(self.code) \(self.message)"
}
}
/// The mime-type part of a content type
public enum ContentType {
case TextJSON
case TextPlain
case TextHTML
case Other(type: String)
func type() -> String {
switch self {
case .TextJSON:
return "text/json"
case .TextPlain:
return "text/plain"
case .TextHTML:
return "text/html"
case .Other(let aType):
return aType
}
}
static func forExtension(ext: String) -> ContentType? {
switch ext.lowercased() {
case "json":
return .TextJSON
case "txt":
return .TextPlain
case "html", "htm":
return .TextHTML
default:
return nil
}
}
static func forContentType(contentType: String) -> ContentType? {
let components = contentType.components(separatedBy: ";")
guard components.count > 0 else {
return nil
}
let mimeType = components[0].trimmingCharacters(in: .whitespacesAndNewlines)
switch mimeType.lowercased() {
case "text/json":
return .TextJSON
case "text/plain":
return .TextPlain
case "text/html":
return .TextHTML
default:
return .Other(type: mimeType)
}
}
}
public class Route {
public typealias ThenBlock = () -> ()
private let path: String
private var params = [String: String]()
private var allowOtherParams = false
private var headers = [String: String]()
private var responder: Responder?
private var thenBlock: ThenBlock?
public init(_ path: String) {
self.path = path
}
@discardableResult public func param(_ name: String, _ value: String) -> Route {
params[name] = value
return self
}
@discardableResult public func anyParams() -> Route {
allowOtherParams = true
return self
}
@discardableResult public func header(_ name: String, _ value: String) -> Route {
headers[name] = value
return self
}
@discardableResult public func respond(_ responder: Responder) -> Route {
return self
}
@discardableResult public func status(_ status: ResponseStatus) -> Route {
responder = StatusResponder(status: status)
return self
}
@discardableResult public func resource(_ url: URL) -> Route {
return self
}
@discardableResult public func resource(_ resource: String) throws -> Route {
return self
}
@discardableResult public func resource(bundle: Bundle, resource: String) throws -> Route {
return self
}
@discardableResult public func content(_ string: String, _ type: ContentType) -> Route {
responder = ContentResponder(string: string, contentType: type, encoding: .utf8)
return self
}
@discardableResult public func content(_ data: Data, _ type: ContentType) -> Route {
responder = ContentResponder(data: data, contentType: type)
return self
}
@discardableResult public func block(_ block: @escaping BlockResponder.BlockResponderBlock) -> Route {
responder = BlockResponder(block: block)
return self
}
@discardableResult public func json(_ value: Any) throws -> Route {
let data = try JSONSerialization.data(withJSONObject: value)
return content(data, .TextJSON)
}
@discardableResult public func then(_ block: @escaping ThenBlock) -> Route {
self.thenBlock = block
return self
}
fileprivate func match(request: Request) -> Int? {
guard match(path: request.path) else {
return nil
}
guard let paramsScore = match(queryString: request.queryString) else {
return nil
}
return paramsScore
}
private func match(path: String) -> Bool {
guard let r = path.range(of: self.path, options: [.regularExpression, .anchored]) else {
return false
}
/* Check anchoring at the end of the string, so our regex is a full match */
if r.upperBound != path.endIndex {
return false
}
return true
}
private func match(queryString: String?) -> Int? {
var score = 0
if let params = Route.parse(queryString: queryString) {
var remainingToMatch = self.params
for (key, value) in params {
if let requiredMatch = self.params[key] {
if let r = value.range(of: requiredMatch, options: [.regularExpression, .anchored]) {
/* Check anchoring at the end of the string, so our regex is a full match */
if r.upperBound != value.endIndex {
return nil
}
score += 1
remainingToMatch.removeValue(forKey: key)
} else {
return nil
}
} else if !allowOtherParams {
return nil
}
}
guard remainingToMatch.count == 0 else {
return nil
}
} else if self.params.count != 0 {
return nil
}
return score
}
public static func parse(queryString: String?) -> [(String, String)]? {
guard let queryString = queryString else {
return nil
}
var result = [(String, String)]()
for pair in queryString.components(separatedBy: "&") {
let pairTuple = pair.components(separatedBy: "=")
if pairTuple.count == 2 {
result.append((pairTuple[0], pairTuple[1]))
} else {
result.append((pairTuple[0], ""))
}
}
return result
}
fileprivate func handle(request: Request, resultBlock: @escaping RoutingResultBLock) {
if let responder = responder {
responder.respond(request: request) { (result) in
resultBlock(result)
if let thenBlock = self.thenBlock {
thenBlock()
}
}
} else {
resultBlock(.response(Response(status: .notFound)))
if let thenBlock = thenBlock {
thenBlock()
}
}
}
}
/// Request methods
public enum RequestMethod: String {
case GET
case HEAD
case POST
case PUT
case DELETE
}
public let DefaultHTTPVersion = "HTTP/1.1"
/// Model for an HTTP request
public struct Request {
public var version: String
public var method: String
public var path: String
public var queryString: String?
public var headers: [(String, String)]?
public var body: Data?
public var contentType: ContentType? {
if let contentType = header("Content-Type") {
return ContentType.forContentType(contentType: contentType)
} else {
return nil
}
}
public var file: String {
if let queryString = queryString {
return "\(path)?\(queryString)"
} else {
return path
}
}
public init(method: String = RequestMethod.GET.rawValue, version: String = DefaultHTTPVersion, path: String) {
self.method = method
self.path = path
self.version = version
}
public init(method: String = RequestMethod.GET.rawValue, version: String = DefaultHTTPVersion, path: String, queryString: String?) {
self.method = method
self.path = path
self.version = version
self.queryString = queryString
}
public init(method: String = RequestMethod.GET.rawValue, version: String = DefaultHTTPVersion, path: String, queryString: String?, headers: [(String, String)]?) {
self.method = method
self.path = path
self.version = version
self.queryString = queryString
self.headers = headers
}
public func header(_ needle: String) -> String? {
guard let headers = headers else {
return nil
}
for (key, value) in headers {
if key.lowercased().replacingOccurrences(of: "-", with: "_") == needle.lowercased().replacingOccurrences(of: "-", with: "_") {
return value
}
}
return nil
}
}
/// Model for an HTTP response
public struct Response {
public var status: ResponseStatus
public var headers: [(String, String)]?
public var data: Data?
public var contentType: ContentType?
public init(status: ResponseStatus) {
self.status = status
}
public init(status: ResponseStatus, data: Data?, contentType: ContentType?) {
self.status = status
self.data = data
self.contentType = contentType
}
public func containsHeader(_ needle: String) -> Bool {
guard let headers = headers else {
return false
}
for (key, _) in headers {
if key.lowercased() == needle.lowercased() {
return true
}
}
return false
}
}
public enum ResponderError: Error {
case ResourceNotFound(bundle: Bundle, resource: String)
}
/// Protocol for objects that produce responses to requests
public protocol Responder {
func respond(request: Request, resultBlock: @escaping RoutingResultBLock)
}
/// Responder that produces a response with a given bundle resource
public class ResourceResponder: Responder {
private let url: URL
public init(url: URL) {
self.url = url
}
public init(bundle: Bundle, resource: String) throws {
if let url = bundle.url(forResource: resource, withExtension: nil) {
self.url = url
} else {
throw ResponderError.ResourceNotFound(bundle: bundle, resource: resource)
}
}
public func respond(request: Request, resultBlock: @escaping RoutingResultBLock) {
do {
let data = try Data.init(contentsOf: url)
resultBlock(.response(Response(status: .ok, data: data, contentType: .TextPlain))) //TODO contentType
} catch {
resultBlock(.error(error))
}
}
}
/// Responder that produces a response with the given content
public class ContentResponder: Responder {
private let data: Data
private let contentType: ContentType
public init(string: String, contentType: ContentType, encoding: String.Encoding) {
self.data = string.data(using: encoding)!
self.contentType = contentType
}
public init(data: Data, contentType: ContentType) {
self.data = data
self.contentType = contentType
}
public func respond(request: Request, resultBlock: @escaping RoutingResultBLock) {
resultBlock(.response(Response(status: .ok, data: data, contentType: contentType)))
}
}
/// Responder that takes a block that itself produces a response given a request
public class BlockResponder: Responder {
public typealias BlockResponderBlock = (Request, @escaping RoutingResultBLock) -> ()
private let block: BlockResponderBlock
public init(block: @escaping BlockResponderBlock) {
self.block = block
}
public func respond(request: Request, resultBlock: @escaping RoutingResultBLock) {
block(request, resultBlock)
}
}
/// Responder that simply responds with the given response status
public class StatusResponder: Responder {
private let status: ResponseStatus
public init(status: ResponseStatus) {
self.status = status
}
public func respond(request: Request, resultBlock: @escaping RoutingResultBLock) {
resultBlock(.response(Response(status: status)))
}
}
| c0b21ea0e6eddb5ccdac470503a353cd | 26.179924 | 166 | 0.581771 | false | false | false | false |
sammyd/SwiftJSONShootout | refs/heads/master | JSONShootOut_Swifty.playground/section-1.swift | apache-2.0 | 1 |
import Foundation
import SwiftyJSON
/* Import the JSON from a file */
let jsonURL = NSBundle.mainBundle().pathForResource("sams_repos", ofType: "json")
let rawJSON = NSData(contentsOfFile: jsonURL!)
//-------------//
// MARK:- Model
//-------------//
struct Repo {
let id: Int
let name: String
let desc: String?
let url: NSURL
let homepage: NSURL?
let fork: Bool
}
extension Repo: Printable {
var description : String {
return "\(name) (\(id)) {\(desc) :: \(homepage)}"
}
}
//-------------------//
// MARK:- SwiftyJSON
//-------------------//
let json = JSON(data: rawJSON!, options: .allZeros, error: nil)
var repos = [Repo]()
for (index: String, subJson: JSON) in json {
if let id = subJson["id"].int,
let name = subJson["name"].string,
let url = subJson["url"].string,
let fork = subJson["fork"].bool {
var homepage: NSURL? = .None
if let homepage_raw = subJson["homepage"].string {
homepage = NSURL(string: homepage_raw)
}
let url_url = NSURL(string: url)!
repos += [Repo(id: id, name: name, desc: subJson["description"].string,
url: url_url, homepage: homepage, fork: fork)]
}
}
repos
| 7939ff2163ef17a3dcfdd228a072c114 | 21.259259 | 81 | 0.579035 | false | false | false | false |
El-Fitz/ImageSlideshow | refs/heads/master | Pod/Classes/InputSources/AFURLSource.swift | mit | 1 | //
// AFURLSource.swift
// ImageSlideshow
//
// Created by Petr Zvoníček on 30.07.15.
//
import AFNetworking
public class AFURLSource: NSObject, InputSource {
var url: URL
var placeholder: UIImage?
public init(url: URL) {
self.url = url
super.init()
}
public init(url: URL, placeholder: UIImage) {
self.url = url
self.placeholder = placeholder
super.init()
}
public init?(urlString: String) {
if let validUrl = URL(string: urlString) {
self.url = validUrl
super.init()
} else {
return nil
}
}
public func load(to imageView: UIImageView, with callback: @escaping (UIImage) -> ()) {
imageView.setImageWith(URLRequest(url: url), placeholderImage: self.placeholder, success: { (_, _, image: UIImage) in
imageView.image = image
callback(image)
}, failure: nil)
}
}
| 86409f7d9b9579cf22e76067131c113d | 23.125 | 125 | 0.568912 | false | false | false | false |
groue/GRDB.swift | refs/heads/master | GRDB/Core/StatementAuthorizer.swift | mit | 1 | #if os(Linux)
import Glibc
#endif
/// `StatementAuthorizer` provides information about compiled database
/// statements, and prevents the truncate optimization when row deletions are
/// observed by transaction observers.
///
/// <https://www.sqlite.org/c3ref/set_authorizer.html>
/// <https://www.sqlite.org/lang_delete.html#the_truncate_optimization>
final class StatementAuthorizer {
private unowned var database: Database
/// What a statement reads.
var selectedRegion = DatabaseRegion()
/// What a statement writes.
var databaseEventKinds: [DatabaseEventKind] = []
/// True if a statement alters the schema in a way that requires
/// invalidation of the schema cache. For example, adding a column to a
/// table invalidates the schema cache.
var invalidatesDatabaseSchemaCache = false
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
/// savepoint statement.
var transactionEffect: Statement.TransactionEffect?
private var isDropStatement = false
init(_ database: Database) {
self.database = database
}
/// Registers the authorizer with `sqlite3_set_authorizer`.
func register() {
let authorizerP = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(
database.sqliteConnection,
{ (authorizerP, actionCode, cString1, cString2, cString3, cString4) in
Unmanaged<StatementAuthorizer>
.fromOpaque(authorizerP.unsafelyUnwrapped)
.takeUnretainedValue()
.authorize(actionCode, cString1, cString2, cString3, cString4)
},
authorizerP)
}
/// Reset before compiling a new statement
func reset() {
selectedRegion = DatabaseRegion()
databaseEventKinds = []
invalidatesDatabaseSchemaCache = false
transactionEffect = nil
isDropStatement = false
}
private func authorize(
_ actionCode: CInt,
_ cString1: UnsafePointer<Int8>?,
_ cString2: UnsafePointer<Int8>?,
_ cString3: UnsafePointer<Int8>?,
_ cString4: UnsafePointer<Int8>?)
-> CInt
{
// Uncomment when debugging
// print("""
// StatementAuthorizer: \
// \(AuthorizerActionCode(rawValue: actionCode)) \
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }.joined(separator: ", "))
// """)
switch actionCode {
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE,
SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX,
SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW,
SQLITE_DROP_TRIGGER, SQLITE_DROP_TEMP_TRIGGER:
isDropStatement = true
invalidatesDatabaseSchemaCache = true
return SQLITE_OK
case SQLITE_ATTACH, SQLITE_DETACH, SQLITE_ALTER_TABLE,
SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE,
SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE,
SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW,
SQLITE_CREATE_TRIGGER, SQLITE_CREATE_VIEW,
SQLITE_CREATE_VTABLE:
invalidatesDatabaseSchemaCache = true
return SQLITE_OK
case SQLITE_READ:
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
selectedRegion.formUnion(DatabaseRegion(table: tableName))
} else {
// SELECT column FROM table
selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
}
return SQLITE_OK
case SQLITE_INSERT:
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
databaseEventKinds.append(.insert(tableName: tableName))
return SQLITE_OK
case SQLITE_DELETE:
if isDropStatement { return SQLITE_OK }
guard let cString1 = cString1 else { return SQLITE_OK }
// Deletions from sqlite_master and sqlite_temp_master are not like
// other deletions: `sqlite3_update_hook` does not notify them, and
// they are prevented when the truncate optimization is disabled.
// Let's always authorize such deletions by returning SQLITE_OK:
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
let tableName = String(cString: cString1)
databaseEventKinds.append(.delete(tableName: tableName))
if let observationBroker = database.observationBroker,
observationBroker.observesDeletions(on: tableName)
{
// Prevent the truncate optimization so that
// `sqlite3_update_hook` notifies individual row deletions to
// transaction observers.
return SQLITE_IGNORE
} else {
return SQLITE_OK
}
case SQLITE_UPDATE:
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
insertUpdateEventKind(tableName: tableName, columnName: columnName)
return SQLITE_OK
case SQLITE_TRANSACTION:
guard let cString1 = cString1 else { return SQLITE_OK }
if strcmp(cString1, "BEGIN") == 0 {
transactionEffect = .beginTransaction
} else if strcmp(cString1, "COMMIT") == 0 {
transactionEffect = .commitTransaction
} else if strcmp(cString1, "ROLLBACK") == 0 {
transactionEffect = .rollbackTransaction
}
return SQLITE_OK
case SQLITE_SAVEPOINT:
guard let cString1 = cString1 else { return SQLITE_OK }
guard let name = cString2.map(String.init) else { return SQLITE_OK }
if strcmp(cString1, "BEGIN") == 0 {
transactionEffect = .beginSavepoint(name)
} else if strcmp(cString1, "RELEASE") == 0 {
transactionEffect = .releaseSavepoint(name)
} else if strcmp(cString1, "ROLLBACK") == 0 {
transactionEffect = .rollbackSavepoint(name)
}
return SQLITE_OK
case SQLITE_FUNCTION:
// SQLite 3.37.2 does not report ALTER TABLE DROP COLUMN with the
// SQLITE_ALTER_TABLE action code. SQLite 3.38 does.
//
// Until SQLite 3.38, we need to find another way to set the
// `invalidatesDatabaseSchemaCache` flag for such
// statement, and it is SQLITE_FUNCTION sqlite_drop_column.
//
// See <https://github.com/groue/GRDB.swift/pull/1144#issuecomment-1015155717>
// See <https://sqlite.org/forum/forumpost/bd47580ec2>
if sqlite3_libversion_number() < 3038000,
let cString2,
strcmp(cString2, "sqlite_drop_column") == 0
{
invalidatesDatabaseSchemaCache = true
}
return SQLITE_OK
default:
return SQLITE_OK
}
}
private func insertUpdateEventKind(tableName: String, columnName: String) {
for (index, eventKind) in databaseEventKinds.enumerated() {
if case .update(let t, let columnNames) = eventKind, t == tableName {
var columnNames = columnNames
columnNames.insert(columnName)
databaseEventKinds[index] = .update(tableName: tableName, columnNames: columnNames)
return
}
}
databaseEventKinds.append(.update(tableName: tableName, columnNames: [columnName]))
}
}
private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible {
let rawValue: CInt
var description: String {
switch rawValue {
case 1: return "SQLITE_CREATE_INDEX"
case 2: return "SQLITE_CREATE_TABLE"
case 3: return "SQLITE_CREATE_TEMP_INDEX"
case 4: return "SQLITE_CREATE_TEMP_TABLE"
case 5: return "SQLITE_CREATE_TEMP_TRIGGER"
case 6: return "SQLITE_CREATE_TEMP_VIEW"
case 7: return "SQLITE_CREATE_TRIGGER"
case 8: return "SQLITE_CREATE_VIEW"
case 9: return "SQLITE_DELETE"
case 10: return "SQLITE_DROP_INDEX"
case 11: return "SQLITE_DROP_TABLE"
case 12: return "SQLITE_DROP_TEMP_INDEX"
case 13: return "SQLITE_DROP_TEMP_TABLE"
case 14: return "SQLITE_DROP_TEMP_TRIGGER"
case 15: return "SQLITE_DROP_TEMP_VIEW"
case 16: return "SQLITE_DROP_TRIGGER"
case 17: return "SQLITE_DROP_VIEW"
case 18: return "SQLITE_INSERT"
case 19: return "SQLITE_PRAGMA"
case 20: return "SQLITE_READ"
case 21: return "SQLITE_SELECT"
case 22: return "SQLITE_TRANSACTION"
case 23: return "SQLITE_UPDATE"
case 24: return "SQLITE_ATTACH"
case 25: return "SQLITE_DETACH"
case 26: return "SQLITE_ALTER_TABLE"
case 27: return "SQLITE_REINDEX"
case 28: return "SQLITE_ANALYZE"
case 29: return "SQLITE_CREATE_VTABLE"
case 30: return "SQLITE_DROP_VTABLE"
case 31: return "SQLITE_FUNCTION"
case 32: return "SQLITE_SAVEPOINT"
case 0: return "SQLITE_COPY"
case 33: return "SQLITE_RECURSIVE"
default: return "\(rawValue)"
}
}
}
| 1d2340ee8c64e4fe43a8c8d3a5fa0623 | 40.666667 | 117 | 0.5979 | false | false | false | false |
GetZero/Give-Me-One | refs/heads/master | MyOne/首页/ViewController/HomeViewController.swift | apache-2.0 | 1 | //
// HomeViewController.swift
// MyOne
//
// Created by 韦曲凌 on 16/8/24.
// Copyright © 2016年 Wake GetZero. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
// MARK: Life circle and property
var homeModels: HomeModel = HomeModel()
var day: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
initWithUserInterface()
addObservers()
startNetwork()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
TopWindow.showTopWindow()
}
deinit {
homeModels.removeObserver(self, forKeyPath: homeModels.resultKeyPath())
}
func initWithUserInterface() {
view.addSubview(homeCollectionView)
view.addSubview(juhuaActivity)
view.addSubview(circleView)
view.addSubview(networkWarningLabel)
UIView.animateWithDuration(1, animations: {
self.circleView.transform = CGAffineTransformScale(self.circleView.transform, 0.0001, 0.0001)
}) { (_) in
self.circleView.removeFromSuperview()
}
}
// MARK: Observer and network
func addObservers() {
homeModels.addObserver(self, forKeyPath: homeModels.resultKeyPath(), options: NSKeyValueObservingOptions.New, context: nil)
}
func startNetwork() {
juhuaActivity.startAnimating()
homeModels.startNetwork(day)
day -= 1
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if object!.isKindOfClass(HomeModel) && keyPath! == homeModels.resultKeyPath() {
if change!["new"]! as! String == "Success" {
homeCollectionView.reloadData()
networkWarningLabel.hidden = true
} else {
let _: UIAlertController = UIAlertController.networkErrorAlert(self)
networkWarningLabel.hidden = false
juhuaActivity.stopAnimating()
}
}
}
// MARK: Delegate and datasource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
homeModels.homeDatas.count == 0 ? juhuaActivity.startAnimating() : juhuaActivity.stopAnimating()
return homeModels.homeDatas.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: HomeCell = collectionView.dequeueReusableCellWithReuseIdentifier("HomeCell", forIndexPath: indexPath) as! HomeCell
cell.setModel(homeModels.homeDatas[indexPath.item])
return cell
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if indexPath.item == homeModels.homeDatas.count - 1 {
startNetwork()
}
}
// MARK: Lazy load
private lazy var homeCollectionView: UICollectionView = {
let view: UICollectionView = UICollectionView.standardCollectionView("HomeCell")
view.delegate = self
view.dataSource = self
return view
}()
private lazy var juhuaActivity: UIActivityIndicatorView = UIActivityIndicatorView.juhuaActivityView(self.view)
private lazy var circleView: UIView = UIView.circleView(self.view)
private lazy var networkWarningLabel: UILabel = UILabel.networkErrorWarning(self.view)
}
| 67682bd6592f8a12f4ea0fbd8345fd7f | 34.254717 | 157 | 0.663902 | false | false | false | false |
CodaFi/Basis | refs/heads/master | Basis/Unique.swift | mit | 2 | //
// Unique.swift
// Basis
//
// Created by Robert Widmann on 9/13/14.
// Copyright (c) 2014 TypeLift. All rights reserved.
// Released under the MIT license.
//
/// Abstract Unique objects. Objects of type Unique may be compared for equality and ordering and
/// hashed.
public class Unique : K0, Equatable, Hashable, Comparable {
private let val : Int
public var hashValue: Int {
get {
return self.val
}
}
public init(_ x : Int) {
self.val = x
}
}
/// Creates a new object of type Unique. The value returned will not compare equal to any other
/// value of type Unique returned by previous calls to newUnique. There is no limit on the number of
/// times newUnique may be called.
public func newUnique() -> IO<Unique> {
return do_({ () -> Unique in
let r = !(modifyIORef(innerSource)({ $0 + 1 }) >> readIORef(innerSource))
return Unique(r)
})
}
public func <=(lhs: Unique, rhs: Unique) -> Bool {
return lhs.val <= rhs.val
}
public func >=(lhs: Unique, rhs: Unique) -> Bool {
return lhs.val >= rhs.val
}
public func >(lhs: Unique, rhs: Unique) -> Bool {
return lhs.val > rhs.val
}
public func <(lhs: Unique, rhs: Unique) -> Bool {
return lhs.val < rhs.val
}
public func ==(lhs: Unique, rhs: Unique) -> Bool {
return lhs.val == rhs.val
}
private let innerSource : IORef<Int> = !newIORef(0)
| 6a79cb40bb7a2d318410840a393248c3 | 22.892857 | 100 | 0.660688 | false | false | false | false |
victorchee/Live | refs/heads/master | Live/Live/LivePublishClient.swift | mit | 1 | //
// LivePublishClient.swift
// Live
//
// Created by VictorChee on 2016/12/22.
// Copyright © 2016年 VictorChee. All rights reserved.
//
import UIKit
import AVFoundation
import RTMP
import Capture
class LivePublishClient: NSObject {
fileprivate let publishClientQueue = DispatchQueue(label: "LivePublishClientQueue")
fileprivate var isPublishReady = false
fileprivate let captureSession = AVCaptureSession()
fileprivate let videoCapture = VideoCapture()
fileprivate let audioCapture = AudioCapture()
fileprivate let videoEncoder = AVCEncoder()
fileprivate let audioEncoder = AACEncoder()
fileprivate var muxer = RTMPMuxer()
fileprivate var rtmpPublisher = RTMPPublishClient()
public var videoPreviewView: VideoPreviewView {
return videoCapture.videoPreviewView
}
fileprivate var videoOrientation = AVCaptureVideoOrientation.portrait {
didSet {
if videoOrientation != oldValue {
videoCapture.videoOrientation = videoOrientation
videoEncoder.videoOrientation = videoOrientation
}
}
}
public var videoEncoderSettings: [String: Any] {
get {
return videoEncoder.dictionaryWithValues(forKeys: AVCEncoder.supportedSettingsKeys)
}
set {
videoEncoder.setValuesForKeys(newValue)
}
}
public var audioEncoderSettings: [String: Any] {
get {
return audioEncoder.dictionaryWithValues(forKeys: AACEncoder.supportedSettingsKeys)
}
set {
audioEncoder.setValuesForKeys(newValue)
}
}
public override init() {
super.init()
setupRTMP()
setupCapture()
setupEncode()
}
public func startPublish(toUrl rtmpUrl: String) {
if isPublishReady { return }
publishClientQueue.async {
self.captureSession.startRunning()
self.rtmpPublisher.setMediaMetaData(self.audioEncoder.metaData)
self.rtmpPublisher.setMediaMetaData(self.videoEncoder.metaData)
self.rtmpPublisher.connect(rtmpUrl: rtmpUrl)
self.videoEncoder.run()
self.audioEncoder.run()
}
}
private func setupRTMP() {
rtmpPublisher.delegate = self
muxer.delegate = self
}
private func setupCapture() {
listenOrientationDidChangeNotification()
audioCapture.session = captureSession
audioCapture.output { (sampleBuffer) in
self.handleAudioCaptureBuffer(sampleBuffer)
}
audioCapture.attachMicrophone()
videoCapture.session = captureSession
videoCapture.output { (sampleBuffer) in
self.handleVideoCaptureBuffer(sampleBuffer)
}
videoCapture.attachCamera()
}
private func setupEncode() {
audioEncoder.delegate = self
videoEncoder.delegate = self
}
private func handleAudioCaptureBuffer(_ sampleBuffer: CMSampleBuffer) {
guard isPublishReady else { return }
audioEncoder.encode(sampleBuffer: sampleBuffer)
}
private func handleVideoCaptureBuffer(_ sampleBuffer: CMSampleBuffer) {
guard isPublishReady else { return }
videoEncoder.encode(sampleBuffer: sampleBuffer)
}
public func stop() {
guard isPublishReady else { return }
publishClientQueue.async {
self.captureSession.stopRunning()
self.videoEncoder.stop()
self.audioEncoder.stop()
self.rtmpPublisher.stop()
self.isPublishReady = false
}
}
}
extension LivePublishClient: RTMPPublisherDelegate {
func publishStreamHasDone() {
isPublishReady = true
}
}
extension LivePublishClient: AVCEncoderDelegate {
func didGetAVCFormatDescription(_ formatDescription: CMFormatDescription?) {
muxer.muxAVCFormatDescription(formatDescription: formatDescription)
}
func didGetAVCSampleBuffer(_ sampleBuffer: CMSampleBuffer) {
muxer.muxAVCSampleBuffer(sampleBuffer: sampleBuffer)
}
}
extension LivePublishClient: AACEncoderDelegate {
func didGetAACFormatDescription(_ formatDescription: CMFormatDescription?) {
muxer.muxAACFormatDescription(formatDescription: formatDescription)
}
func didGetAACSampleBuffer(_ sampleBuffer: CMSampleBuffer?) {
muxer.muxAACSampleBuffer(sampleBuffer: sampleBuffer)
}
}
extension LivePublishClient: RTMPMuxerDelegate {
func sampleOutput(audio buffer: Data, timestamp: Double) {
rtmpPublisher.publishAudio([UInt8](buffer), timestamp: UInt32(timestamp))
}
func sampleOutput(video buffer: Data, timestamp: Double) {
rtmpPublisher.publishVideo([UInt8](buffer), timestamp: UInt32(timestamp))
}
}
extension LivePublishClient {
fileprivate func listenOrientationDidChangeNotification() {
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIDeviceOrientationDidChange, object: nil, queue: OperationQueue.main) { (notification) in
var deviceOrientation = UIDeviceOrientation.unknown
if let device = notification.object as? UIDevice {
deviceOrientation = device.orientation
}
func getAVCaptureVideoOrientation(_ orientaion: UIDeviceOrientation) -> AVCaptureVideoOrientation? {
switch orientaion {
case .portrait:
return .portrait
case .portraitUpsideDown:
return .portraitUpsideDown
case .landscapeLeft:
return .landscapeRight
case .landscapeRight:
return .landscapeLeft
default:
return nil
}
}
if let orientation = getAVCaptureVideoOrientation(deviceOrientation), orientation != self.videoOrientation {
self.videoOrientation = orientation
}
}
}
}
| d77a351f762a48fbf65cfe770b7a60e7 | 32.36612 | 166 | 0.652309 | false | false | false | false |
FulcrumTechnologies/SQLite.swift | refs/heads/master | Source/Typed/Query.swift | mit | 2 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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 QueryType : Expressible {
var clauses: QueryClauses { get set }
init(_ name: String, database: String?)
}
public protocol SchemaType : QueryType {
static var identifier: String { get }
}
extension SchemaType {
/// Builds a copy of the query with the `SELECT` clause applied.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let email = Expression<String>("email")
///
/// users.select(id, email)
/// // SELECT "id", "email" FROM "users"
///
/// - Parameter all: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT` clause applied.
public func select(column1: Expressible, _ column2: Expressible, _ more: Expressible...) -> Self {
return select(false, [column1, column2] + more)
}
/// Builds a copy of the query with the `SELECT DISTINCT` clause applied.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.select(distinct: email)
/// // SELECT DISTINCT "email" FROM "users"
///
/// - Parameter columns: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT DISTINCT` clause applied.
public func select(distinct column1: Expressible, _ column2: Expressible, _ more: Expressible...) -> Self {
return select(true, [column1, column2] + more)
}
/// Builds a copy of the query with the `SELECT` clause applied.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let email = Expression<String>("email")
///
/// users.select([id, email])
/// // SELECT "id", "email" FROM "users"
///
/// - Parameter all: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT` clause applied.
public func select(all: [Expressible]) -> Self {
return select(false, all)
}
/// Builds a copy of the query with the `SELECT DISTINCT` clause applied.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.select(distinct: [email])
/// // SELECT DISTINCT "email" FROM "users"
///
/// - Parameter columns: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT DISTINCT` clause applied.
public func select(distinct columns: [Expressible]) -> Self {
return select(true, columns)
}
/// Builds a copy of the query with the `SELECT *` clause applied.
///
/// let users = Table("users")
///
/// users.select(*)
/// // SELECT * FROM "users"
///
/// - Parameter star: A star literal.
///
/// - Returns: A query with the given `SELECT *` clause applied.
public func select(star: Star) -> Self {
return select([star(nil, nil)])
}
/// Builds a copy of the query with the `SELECT DISTINCT *` clause applied.
///
/// let users = Table("users")
///
/// users.select(distinct: *)
/// // SELECT DISTINCT * FROM "users"
///
/// - Parameter star: A star literal.
///
/// - Returns: A query with the given `SELECT DISTINCT *` clause applied.
public func select(distinct star: Star) -> Self {
return select(distinct: [star(nil, nil)])
}
/// Builds a scalar copy of the query with the `SELECT` clause applied.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
///
/// users.select(id)
/// // SELECT "id" FROM "users"
///
/// - Parameter all: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT` clause applied.
public func select<V : Value>(column: Expression<V>) -> ScalarQuery<V> {
return select(false, [column])
}
public func select<V : Value>(column: Expression<V?>) -> ScalarQuery<V?> {
return select(false, [column])
}
/// Builds a scalar copy of the query with the `SELECT DISTINCT` clause
/// applied.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
///
/// users.select(distinct: email)
/// // SELECT DISTINCT "email" FROM "users"
///
/// - Parameter column: A list of expressions to select.
///
/// - Returns: A query with the given `SELECT DISTINCT` clause applied.
public func select<V : Value>(distinct column: Expression<V>) -> ScalarQuery<V> {
return select(true, [column])
}
public func select<V : Value>(distinct column: Expression<V?>) -> ScalarQuery<V?> {
return select(true, [column])
}
public var count: ScalarQuery<Int> {
return select(Expression.count(*))
}
}
extension QueryType {
private func select<Q : QueryType>(distinct: Bool, _ columns: [Expressible]) -> Q {
var query = Q.init(clauses.from.name, database: clauses.from.database)
query.clauses = clauses
query.clauses.select = (distinct, columns)
return query
}
// MARK: JOIN
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64>("user_id")
///
/// users.join(posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(table: QueryType, on condition: Expression<Bool>) -> Self {
return join(table, on: Expression<Bool?>(condition))
}
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64?>("user_id")
///
/// users.join(posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(table: QueryType, on condition: Expression<Bool?>) -> Self {
return join(.Inner, table, on: condition)
}
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64>("user_id")
///
/// users.join(.LeftOuter, posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - type: The `JOIN` operator.
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(type: JoinType, _ table: QueryType, on condition: Expression<Bool>) -> Self {
return join(type, table, on: Expression<Bool?>(condition))
}
/// Adds a `JOIN` clause to the query.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
/// let posts = Table("posts")
/// let userId = Expression<Int64?>("user_id")
///
/// users.join(.LeftOuter, posts, on: posts[userId] == users[id])
/// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id")
///
/// - Parameters:
///
/// - type: The `JOIN` operator.
///
/// - table: A query representing the other table.
///
/// - condition: A boolean expression describing the join condition.
///
/// - Returns: A query with the given `JOIN` clause applied.
public func join(type: JoinType, _ table: QueryType, on condition: Expression<Bool?>) -> Self {
var query = self
query.clauses.join.append((type: type, query: table, condition: table.clauses.filters.map { condition && $0 } ?? condition as Expressible))
return query
}
// MARK: WHERE
/// Adds a condition to the query’s `WHERE` clause.
///
/// let users = Table("users")
/// let id = Expression<Int64>("id")
///
/// users.filter(id == 1)
/// // SELECT * FROM "users" WHERE ("id" = 1)
///
/// - Parameter condition: A boolean expression to filter on.
///
/// - Returns: A query with the given `WHERE` clause applied.
public func filter(predicate: Expression<Bool>) -> Self {
return filter(Expression<Bool?>(predicate))
}
/// Adds a condition to the query’s `WHERE` clause.
///
/// let users = Table("users")
/// let age = Expression<Int?>("age")
///
/// users.filter(age >= 35)
/// // SELECT * FROM "users" WHERE ("age" >= 35)
///
/// - Parameter condition: A boolean expression to filter on.
///
/// - Returns: A query with the given `WHERE` clause applied.
public func filter(predicate: Expression<Bool?>) -> Self {
var query = self
query.clauses.filters = query.clauses.filters.map { $0 && predicate } ?? predicate
return query
}
// MARK: GROUP BY
/// Sets a `GROUP BY` clause on the query.
///
/// - Parameter by: A list of columns to group by.
///
/// - Returns: A query with the given `GROUP BY` clause applied.
public func group(by: Expressible...) -> Self {
return group(by)
}
/// Sets a `GROUP BY` clause on the query.
///
/// - Parameter by: A list of columns to group by.
///
/// - Returns: A query with the given `GROUP BY` clause applied.
public func group(by: [Expressible]) -> Self {
return group(by, nil)
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A column to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(by: Expressible, having: Expression<Bool>) -> Self {
return group([by], having: having)
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A column to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(by: Expressible, having: Expression<Bool?>) -> Self {
return group([by], having: having)
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A list of columns to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(by: [Expressible], having: Expression<Bool>) -> Self {
return group(by, Expression<Bool?>(having))
}
/// Sets a `GROUP BY`-`HAVING` clause on the query.
///
/// - Parameters:
///
/// - by: A list of columns to group by.
///
/// - having: A condition determining which groups are returned.
///
/// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied.
public func group(by: [Expressible], having: Expression<Bool?>) -> Self {
return group(by, having)
}
private func group(by: [Expressible], _ having: Expression<Bool?>?) -> Self {
var query = self
query.clauses.group = (by, having)
return query
}
// MARK: ORDER BY
/// Sets an `ORDER BY` clause on the query.
///
/// let users = Table("users")
/// let email = Expression<String>("email")
/// let email = Expression<String?>("name")
///
/// users.order(email.desc, name.asc)
/// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC
///
/// - Parameter by: An ordered list of columns and directions to sort by.
///
/// - Returns: A query with the given `ORDER BY` clause applied.
public func order(by: Expressible...) -> Self {
var query = self
query.clauses.order = by
return query
}
// MARK: LIMIT/OFFSET
/// Sets the LIMIT clause (and resets any OFFSET clause) on the query.
///
/// let users = Table("users")
///
/// users.limit(20)
/// // SELECT * FROM "users" LIMIT 20
///
/// - Parameter length: The maximum number of rows to return (or `nil` to
/// return unlimited rows).
///
/// - Returns: A query with the given LIMIT clause applied.
public func limit(length: Int?) -> Self {
return limit(length, nil)
}
/// Sets LIMIT and OFFSET clauses on the query.
///
/// let users = Table("users")
///
/// users.limit(20, offset: 20)
/// // SELECT * FROM "users" LIMIT 20 OFFSET 20
///
/// - Parameters:
///
/// - length: The maximum number of rows to return.
///
/// - offset: The number of rows to skip.
///
/// - Returns: A query with the given LIMIT and OFFSET clauses applied.
public func limit(length: Int, offset: Int) -> Self {
return limit(length, offset)
}
// prevents limit(nil, offset: 5)
private func limit(length: Int?, _ offset: Int?) -> Self {
var query = self
query.clauses.limit = length.map { ($0, offset) }
return query
}
// MARK: - Clauses
//
// MARK: SELECT
// MARK: -
private var selectClause: Expressible {
return " ".join([
Expression<Void>(literal: clauses.select.distinct ? "SELECT DISTINCT" : "SELECT"),
", ".join(clauses.select.columns),
Expression<Void>(literal: "FROM"),
tableName(alias: true)
])
}
private var joinClause: Expressible? {
guard !clauses.join.isEmpty else {
return nil
}
return " ".join(clauses.join.map { type, query, condition in
" ".join([
Expression<Void>(literal: "\(type.rawValue) JOIN"),
query.tableName(alias: true),
Expression<Void>(literal: "ON"),
condition
])
})
}
private var whereClause: Expressible? {
guard let filters = clauses.filters else {
return nil
}
return " ".join([
Expression<Void>(literal: "WHERE"),
filters
])
}
private var groupByClause: Expressible? {
guard let group = clauses.group else {
return nil
}
let groupByClause = " ".join([
Expression<Void>(literal: "GROUP BY"),
", ".join(group.by)
])
guard let having = group.having else {
return groupByClause
}
return " ".join([
groupByClause,
" ".join([
Expression<Void>(literal: "HAVING"),
having
])
])
}
private var orderClause: Expressible? {
guard !clauses.order.isEmpty else {
return nil
}
return " ".join([
Expression<Void>(literal: "ORDER BY"),
", ".join(clauses.order)
])
}
private var limitOffsetClause: Expressible? {
guard let limit = clauses.limit else {
return nil
}
let limitClause = Expression<Void>(literal: "LIMIT \(limit.length)")
guard let offset = limit.offset else {
return limitClause
}
return " ".join([
limitClause,
Expression<Void>(literal: "OFFSET \(offset)")
])
}
// MARK: -
public func alias(aliasName: String) -> Self {
var query = self
query.clauses.from = (clauses.from.name, aliasName, clauses.from.database)
return query
}
// MARK: - Operations
//
// MARK: INSERT
public func insert(value: Setter, _ more: Setter...) -> Insert {
return insert([value] + more)
}
public func insert(values: [Setter]) -> Insert {
return insert(nil, values)
}
public func insert(or onConflict: OnConflict, _ values: Setter...) -> Insert {
return insert(or: onConflict, values)
}
public func insert(or onConflict: OnConflict, _ values: [Setter]) -> Insert {
return insert(onConflict, values)
}
private func insert(or: OnConflict?, _ values: [Setter]) -> Insert {
let insert = values.reduce((columns: [Expressible](), values: [Expressible]())) { insert, setter in
(insert.columns + [setter.column], insert.values + [setter.value])
}
let clauses: [Expressible?] = [
Expression<Void>(literal: "INSERT"),
or.map { Expression<Void>(literal: "OR \($0.rawValue)") },
Expression<Void>(literal: "INTO"),
tableName(),
"".wrap(insert.columns) as Expression<Void>,
Expression<Void>(literal: "VALUES"),
"".wrap(insert.values) as Expression<Void>,
whereClause
]
return Insert(" ".join(clauses.flatMap { $0 }).expression)
}
/// Runs an `INSERT` statement against the query with `DEFAULT VALUES`.
public func insert() -> Insert {
return Insert(" ".join([
Expression<Void>(literal: "INSERT INTO"),
tableName(),
Expression<Void>(literal: "DEFAULT VALUES")
]).expression)
}
/// Runs an `INSERT` statement against the query with the results of another
/// query.
///
/// - Parameter query: A query to `SELECT` results from.
///
/// - Returns: The number of updated rows and statement.
public func insert(query: QueryType) -> Update {
return Update(" ".join([
Expression<Void>(literal: "INSERT INTO"),
tableName(),
query.expression
]).expression)
}
// MARK: UPDATE
public func update(values: Setter...) -> Update {
return update(values)
}
public func update(values: [Setter]) -> Update {
let clauses: [Expressible?] = [
Expression<Void>(literal: "UPDATE"),
tableName(),
Expression<Void>(literal: "SET"),
", ".join(values.map { " = ".join([$0.column, $0.value]) }),
whereClause
]
return Update(" ".join(clauses.flatMap { $0 }).expression)
}
// MARK: DELETE
public func delete() -> Delete {
let clauses: [Expressible?] = [
Expression<Void>(literal: "DELETE FROM"),
tableName(),
whereClause
]
return Delete(" ".join(clauses.flatMap { $0 }).expression)
}
// MARK: EXISTS
public var exists: Select<Bool> {
return Select(" ".join([
Expression<Void>(literal: "SELECT EXISTS"),
"".wrap(expression) as Expression<Void>
]).expression)
}
// MARK: -
/// Prefixes a column expression with the query’s table name or alias.
///
/// - Parameter column: A column expression.
///
/// - Returns: A column expression namespaced with the query’s table name or
/// alias.
public func namespace<V>(column: Expression<V>) -> Expression<V> {
return Expression(".".join([tableName(), column]).expression)
}
// FIXME: rdar://problem/18673897 // subscript<T>…
public subscript(column: Expression<Blob>) -> Expression<Blob> {
return namespace(column)
}
public subscript(column: Expression<Blob?>) -> Expression<Blob?> {
return namespace(column)
}
public subscript(column: Expression<Bool>) -> Expression<Bool> {
return namespace(column)
}
public subscript(column: Expression<Bool?>) -> Expression<Bool?> {
return namespace(column)
}
public subscript(column: Expression<Double>) -> Expression<Double> {
return namespace(column)
}
public subscript(column: Expression<Double?>) -> Expression<Double?> {
return namespace(column)
}
public subscript(column: Expression<Int>) -> Expression<Int> {
return namespace(column)
}
public subscript(column: Expression<Int?>) -> Expression<Int?> {
return namespace(column)
}
public subscript(column: Expression<Int64>) -> Expression<Int64> {
return namespace(column)
}
public subscript(column: Expression<Int64?>) -> Expression<Int64?> {
return namespace(column)
}
public subscript(column: Expression<String>) -> Expression<String> {
return namespace(column)
}
public subscript(column: Expression<String?>) -> Expression<String?> {
return namespace(column)
}
/// Prefixes a star with the query’s table name or alias.
///
/// - Parameter star: A literal `*`.
///
/// - Returns: A `*` expression namespaced with the query’s table name or
/// alias.
public subscript(star: Star) -> Expression<Void> {
return namespace(star(nil, nil))
}
// MARK: -
// TODO: alias support
func tableName(alias aliased: Bool = false) -> Expressible {
guard let alias = clauses.from.alias where aliased else {
return database(namespace: clauses.from.alias ?? clauses.from.name)
}
return " ".join([
database(namespace: clauses.from.name),
Expression<Void>(literal: "AS"),
Expression<Void>(alias)
])
}
func database(namespace name: String) -> Expressible {
let name = Expression<Void>(name)
guard let database = clauses.from.database else {
return name
}
return ".".join([Expression<Void>(database), name])
}
public var expression: Expression<Void> {
let clauses: [Expressible?] = [
selectClause,
joinClause,
whereClause,
groupByClause,
orderClause,
limitOffsetClause
]
return " ".join(clauses.flatMap { $0 }).expression
}
}
// TODO: decide: simplify the below with a boxed type instead
/// Queries a collection of chainable helper functions and expressions to build
/// executable SQL statements.
public struct Table : SchemaType {
public static let identifier = "TABLE"
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
public struct View : SchemaType {
public static let identifier = "VIEW"
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
public struct VirtualTable : SchemaType {
public static let identifier = "VIRTUAL TABLE"
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
// TODO: make `ScalarQuery` work in `QueryType.select()`, `.filter()`, etc.
public struct ScalarQuery<V> : QueryType {
public var clauses: QueryClauses
public init(_ name: String, database: String? = nil) {
clauses = QueryClauses(name, alias: nil, database: database)
}
}
// TODO: decide: simplify the below with a boxed type instead
public struct Select<T> : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct Insert : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct Update : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
public struct Delete : ExpressionType {
public var template: String
public var bindings: [Binding?]
public init(_ template: String, _ bindings: [Binding?]) {
self.template = template
self.bindings = bindings
}
}
extension Connection {
public func prepare(query: QueryType) -> AnySequence<Row> {
let expression = query.expression
let statement = prepare(expression.template, expression.bindings)
let columnNames: [String: Int] = {
var (columnNames, idx) = ([String: Int](), 0)
column: for each in query.clauses.select.columns ?? [Expression<Void>(literal: "*")] {
var names = each.expression.template.characters.split { $0 == "." }.map(String.init)
let column = names.removeLast()
let namespace = names.joinWithSeparator(".")
func expandGlob(namespace: Bool) -> QueryType -> Void {
return { query in
var q = query.dynamicType.init(query.clauses.from.name, database: query.clauses.from.database)
q.clauses.select = query.clauses.select
let e = q.expression
var names = self.prepare(e.template, e.bindings).columnNames.map { $0.quote() }
if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } }
for name in names { columnNames[name] = idx++ }
}
}
if column == "*" {
var select = query
select.clauses.select = (false, [Expression<Void>(literal: "*") as Expressible])
let queries = [select] + query.clauses.join.map { $0.query }
if !namespace.isEmpty {
for q in queries {
if q.tableName().expression.template == namespace {
expandGlob(true)(q)
continue column
}
}
fatalError("no such table: \(namespace)")
}
for q in queries {
expandGlob(query.clauses.join.count > 0)(q)
}
continue
}
columnNames[each.expression.template] = idx++
}
return columnNames
}()
return AnySequence {
anyGenerator { statement.next().map { Row(columnNames, $0) } }
}
}
public func scalar<V : Value>(query: ScalarQuery<V>) -> V {
let expression = query.expression
return value(scalar(expression.template, expression.bindings))
}
public func scalar<V : Value>(query: ScalarQuery<V?>) -> V.ValueType? {
let expression = query.expression
guard let value = scalar(expression.template, expression.bindings) as? V.Datatype else { return nil }
return V.fromDatatypeValue(value)
}
public func scalar<V : Value>(query: Select<V>) -> V {
let expression = query.expression
return value(scalar(expression.template, expression.bindings))
}
public func scalar<V : Value>(query: Select<V?>) -> V.ValueType? {
let expression = query.expression
guard let value = scalar(expression.template, expression.bindings) as? V.Datatype else { return nil }
return V.fromDatatypeValue(value)
}
public func pluck(query: QueryType) -> Row? {
return prepare(query.limit(1, query.clauses.limit?.offset)).generate().next()
}
/// Runs an `Insert` query.
///
/// - SeeAlso: `QueryType.insert(value:_:)`
/// - SeeAlso: `QueryType.insert(values:)`
/// - SeeAlso: `QueryType.insert(or:_:)`
/// - SeeAlso: `QueryType.insert()`
///
/// - Parameter query: An insert query.
///
/// - Returns: The insert’s rowid.
public func run(query: Insert) throws -> Int64 {
let expression = query.expression
return try sync {
try self.run(expression.template, expression.bindings)
return self.lastInsertRowid!
}
}
/// Runs an `Update` query.
///
/// - SeeAlso: `QueryType.insert(query:)`
/// - SeeAlso: `QueryType.update(values:)`
///
/// - Parameter query: An update query.
///
/// - Returns: The number of updated rows.
public func run(query: Update) throws -> Int {
let expression = query.expression
return try sync {
try self.run(expression.template, expression.bindings)
return self.changes
}
}
/// Runs a `Delete` query.
///
/// - SeeAlso: `QueryType.delete()`
///
/// - Parameter query: A delete query.
///
/// - Returns: The number of deleted rows.
public func run(query: Delete) throws -> Int {
let expression = query.expression
return try sync {
try self.run(expression.template, expression.bindings)
return self.changes
}
}
}
public struct Row {
private let columnNames: [String: Int]
private let values: [Binding?]
private init(_ columnNames: [String: Int], _ values: [Binding?]) {
self.columnNames = columnNames
self.values = values
}
/// Returns a row’s value for the given column.
///
/// - Parameter column: An expression representing a column selected in a Query.
///
/// - Returns: The value for the given column.
public func get<V: Value>(column: Expression<V>) -> V {
return get(Expression<V?>(column))!
}
public func get<V: Value>(column: Expression<V?>) -> V? {
func valueAtIndex(idx: Int) -> V? {
guard let value = values[idx] as? V.Datatype else { return nil }
return (V.fromDatatypeValue(value) as? V)!
}
guard let idx = columnNames[column.template] else {
let similar = Array(columnNames.keys).filter { $0.hasSuffix(".\(column.template)") }
switch similar.count {
case 0:
fatalError("no such column '\(column.template)' in columns: \(columnNames.keys.sort())")
case 1:
return valueAtIndex(columnNames[similar[0]]!)
default:
fatalError("ambiguous column '\(column.template)' (please disambiguate: \(similar))")
}
}
return valueAtIndex(idx)
}
// FIXME: rdar://problem/18673897 // subscript<T>…
public subscript(column: Expression<Blob>) -> Blob {
return get(column)
}
public subscript(column: Expression<Blob?>) -> Blob? {
return get(column)
}
public subscript(column: Expression<Bool>) -> Bool {
return get(column)
}
public subscript(column: Expression<Bool?>) -> Bool? {
return get(column)
}
public subscript(column: Expression<Double>) -> Double {
return get(column)
}
public subscript(column: Expression<Double?>) -> Double? {
return get(column)
}
public subscript(column: Expression<Int>) -> Int {
return get(column)
}
public subscript(column: Expression<Int?>) -> Int? {
return get(column)
}
public subscript(column: Expression<Int64>) -> Int64 {
return get(column)
}
public subscript(column: Expression<Int64?>) -> Int64? {
return get(column)
}
public subscript(column: Expression<String>) -> String {
return get(column)
}
public subscript(column: Expression<String?>) -> String? {
return get(column)
}
}
/// Determines the join operator for a query’s `JOIN` clause.
public enum JoinType : String {
/// A `CROSS` join.
case Cross = "CROSS"
/// An `INNER` join.
case Inner = "INNER"
/// A `LEFT OUTER` join.
case LeftOuter = "LEFT OUTER"
}
/// ON CONFLICT resolutions.
public enum OnConflict: String {
case Replace = "REPLACE"
case Rollback = "ROLLBACK"
case Abort = "ABORT"
case Fail = "FAIL"
case Ignore = "IGNORE"
}
// MARK: - Private
public struct QueryClauses {
var select = (distinct: false, columns: [Expression<Void>(literal: "*") as Expressible])
var from: (name: String, alias: String?, database: String?)
var join = [(type: JoinType, query: QueryType, condition: Expressible)]()
var filters: Expression<Bool?>?
var group: (by: [Expressible], having: Expression<Bool?>?)?
var order = [Expressible]()
var limit: (length: Int, offset: Int?)?
private init(_ name: String, alias: String?, database: String?) {
self.from = (name, alias, database)
}
}
| 6443fb3a650394bfe6aae9034210f470 | 29.970693 | 147 | 0.572162 | false | false | false | false |
Antuaaan/ECWeather | refs/heads/master | Calendouer/Pods/Spring/Spring/SoundPlayer.swift | apache-2.0 | 17 | // The MIT License (MIT)
//
// Copyright (c) 2015 James Tang ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import AudioToolbox
struct SoundPlayer {
static var filename : String?
static var enabled : Bool = true
private struct Internal {
static var cache = [URL:SystemSoundID]()
}
static func playSound(soundFile: String) {
if !enabled {
return
}
if let url = Bundle.main.url(forResource: soundFile, withExtension: nil) {
var soundID : SystemSoundID = Internal.cache[url] ?? 0
if soundID == 0 {
AudioServicesCreateSystemSoundID(url as CFURL, &soundID)
Internal.cache[url] = soundID
}
AudioServicesPlaySystemSound(soundID)
} else {
print("Could not find sound file name `\(soundFile)`")
}
}
static func play(file: String) {
self.playSound(soundFile: file)
}
}
| 02d11b0415e6e8e22e6b4bfbca886c25 | 34.016667 | 82 | 0.655402 | false | false | false | false |
Torsten2217/PathDynamicModal | refs/heads/master | PathDynamicModal-Demo/ModalView.swift | mit | 1 | //
// ModalView.swift
// PathDynamicModal-Demo
//
// Created by Ryo Aoyama on 2/11/15.
// Copyright (c) 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
class ModalView: UIView {
var bottomButtonHandler: (() -> Void)?
var closeButtonHandler: (() -> Void)?
@IBOutlet weak var contentView: UIView!
@IBOutlet private weak var bottomButton: UIButton!
@IBOutlet weak var closeButton: UIButton!
class func instantiateFromNib() -> ModalView {
let view = UINib(nibName: "ModalView", bundle: nil).instantiateWithOwner(nil, options: nil).first as ModalView
return view
}
override func awakeFromNib() {
super.awakeFromNib()
self.configure()
}
private func configure() {
self.contentView.layer.cornerRadius = 5.0
self.closeButton.layer.cornerRadius = CGRectGetHeight(self.closeButton.bounds) / 2.0
self.closeButton.layer.shadowColor = UIColor.blackColor().CGColor
self.closeButton.layer.shadowOffset = CGSizeZero
self.closeButton.layer.shadowOpacity = 0.3
self.closeButton.layer.shadowRadius = 2.0
}
@IBAction func handleBottomButton(sender: UIButton) {
self.bottomButtonHandler?()
}
@IBAction func handleCloseButton(sender: UIButton) {
self.closeButtonHandler?()
}
} | a2cdee4eadb1e039d4040a07ff7c2d5c | 29.155556 | 118 | 0.661504 | false | false | false | false |
RemyDCF/tpg-offline | refs/heads/master | tpg offline watchOS Extension/Departures/ReminderInterfaceController.swift | mit | 1 | //
// ReminderInterfaceController.swift
// tpg offline watchOS Extension
//
// Created by Rémy Da Costa Faro on 06/04/2018.
// Copyright © 2018 Rémy Da Costa Faro. All rights reserved.
//
import WatchKit
import Foundation
import Alamofire
import UserNotifications
class ReminderInterfaceController: WKInterfaceController, WKCrownDelegate {
@IBOutlet weak var beforeTimeImageView: WKInterfaceImage!
var minutesBeforeDeparture = 10
let expectedMoveDelta = 0.2617995
var crownRotationalDelta = 0.0
var departure: Departure?
var maximum = 60
override func awake(withContext context: Any?) {
super.awake(withContext: context)
guard let option = context as? Departure else {
print("Context is not in a valid format")
return
}
departure = option
if Int(departure?.leftTime ?? "") ?? 0 < 60 {
maximum = Int(departure?.leftTime ?? "") ?? 0
}
if let leftTime = departure?.leftTime, Int(leftTime) ?? 0 < 10 {
beforeTimeImageView.setImageNamed("reminderCircle-\(leftTime)")
}
crownSequencer.delegate = self
crownSequencer.focus()
}
override func willActivate() {
super.willActivate()
crownSequencer.focus()
}
func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) {
crownRotationalDelta += rotationalDelta
if crownRotationalDelta > expectedMoveDelta {
let newValue = minutesBeforeDeparture + 1
if newValue < 0 {
minutesBeforeDeparture = 0
} else if newValue > maximum {
minutesBeforeDeparture = maximum
} else {
minutesBeforeDeparture = newValue
}
beforeTimeImageView.setImageNamed("reminderCircle-\(minutesBeforeDeparture)")
crownRotationalDelta = 0.0
} else if crownRotationalDelta < -expectedMoveDelta {
let newValue = minutesBeforeDeparture - 1
if newValue < 0 {
minutesBeforeDeparture = 0
} else if newValue > maximum {
minutesBeforeDeparture = maximum
} else {
minutesBeforeDeparture = newValue
}
beforeTimeImageView.setImageNamed("reminderCircle-\(minutesBeforeDeparture)")
crownRotationalDelta = 0.0
}
}
@IBAction func setReminder() {
guard let departure = self.departure else { return }
setAlert(with: minutesBeforeDeparture, departure: departure)
}
func setAlert(with timeBefore: Int,
departure: Departure,
forceDisableSmartReminders: Bool = false) {
var departure = departure
departure.calculateLeftTime()
let date = departure.dateCompenents?.date?
.addingTimeInterval(TimeInterval(timeBefore * -60))
let components = Calendar.current.dateComponents([.hour,
.minute,
.day,
.month,
.year],
from: date ?? Date())
let trigger = UNCalendarNotificationTrigger(dateMatching: components,
repeats: false)
let content = UNMutableNotificationContent()
content.title = timeBefore == 0 ?
Text.busIsCommingNow : Text.minutesLeft(timeBefore)
content.body = Text.take(line: departure.line.code,
to: departure.line.destination)
content.sound = UNNotificationSound.default
let request =
UNNotificationRequest(identifier:
"departureNotification-\(String.random(30))",
content: content,
trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
let action = WKAlertAction(title: Text.ok, style: .default, handler: {})
self.presentAlert(withTitle: Text.error,
message: Text.sorryError,
preferredStyle: .alert, actions: [action])
} else {
let action = WKAlertAction(title: Text.ok, style: .default, handler: {
self.dismiss()
})
self.presentAlert(
withTitle: Text.youWillBeReminded,
message: Text.notificationWillBeSend(minutes: timeBefore),
preferredStyle: .alert,
actions: [action])
}
}
}
}
| 7d77f6b151d0f94e42b539794a2177d2 | 34.580645 | 85 | 0.616727 | false | false | false | false |
MounikaAnkam/DrawingAssignment | refs/heads/master | Drawing Assignment/hillsView.swift | mit | 1 | //
// hillsView.swift
// Drawing Assignment
//
// Created by Mounika Ankamon 4/3/15.
// Copyright (c) 2015 Mounika Ankam. All rights reserved.
//
import UIKit
class hillsView: UIView {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
var bPath = UIBezierPath()
bPath.moveToPoint(CGPoint(x: 0, y: 300))
var count = 250
for J in 1...6 {
bPath.addLineToPoint(CGPoint(x: J*62, y: count))
if count == 250 {
count = count + 50
}else{
count = 250
}
}
bPath.lineWidth = 6.0
bPath.stroke()
}
}
| 493d0886d52fd92a1dcf74f301a7cc45 | 22.157895 | 78 | 0.494318 | false | false | false | false |
hsusmita/SwiftResponsiveLabel | refs/heads/master | SwiftResponsiveLabel/Source/TouchHandler.swift | mit | 1 | //
// TouchHandler.swift
// SwiftResponsiveLabel
//
// Created by Susmita Horrow on 01/03/16.
// Copyright © 2016 hsusmita.com. All rights reserved.
//
import Foundation
import UIKit.UIGestureRecognizerSubclass
class TouchGestureRecognizer: UIGestureRecognizer {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
self.state = .began
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesCancelled(touches, with: event)
self.state = .cancelled
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
self.state = .ended
}
}
class TouchHandler: NSObject {
fileprivate var responsiveLabel: SwiftResponsiveLabel?
var touchIndex: Int?
var selectedRange: NSRange?
fileprivate var defaultAttributes: AttributesDictionary?
fileprivate var highlightAttributes: AttributesDictionary?
init(responsiveLabel: SwiftResponsiveLabel) {
super.init()
self.responsiveLabel = responsiveLabel
let gestureRecognizer = TouchGestureRecognizer(target: self, action: #selector(TouchHandler.handleTouch(_:)))
self.responsiveLabel?.addGestureRecognizer(gestureRecognizer)
gestureRecognizer.delegate = self
}
@objc fileprivate func handleTouch(_ gesture: UIGestureRecognizer) {
let touchLocation = gesture.location(in: self.responsiveLabel)
let index = self.responsiveLabel?.textKitStack.characterIndexAtLocation(touchLocation)
self.touchIndex = index
switch gesture.state {
case .began:
self.beginSession()
case .cancelled:
self.cancelSession()
case .ended:
self.endSession()
default:
return
}
}
fileprivate func beginSession() {
guard let textkitStack = self.responsiveLabel?.textKitStack,
let touchIndex = self.touchIndex, self.touchIndex! < textkitStack.textStorageLength else { return }
var rangeOfTappedText = NSRange()
let highlightAttributeInfo = textkitStack.rangeAttributeForKey(NSAttributedString.Key.RLHighlightedAttributesDictionary, atIndex: touchIndex)
rangeOfTappedText = highlightAttributeInfo.range
self.highlightAttributes = highlightAttributeInfo.attribute as? AttributesDictionary
if let attributes = self.highlightAttributes {
self.selectedRange = rangeOfTappedText
self.defaultAttributes = [NSAttributedString.Key : Any]()
for (key, value) in attributes {
self.defaultAttributes![key] = textkitStack.rangeAttributeForKey(key, atIndex: touchIndex).attribute
textkitStack.addAttribute(value, forkey: key, atRange: rangeOfTappedText)
}
self.responsiveLabel?.setNeedsDisplay()
}
if self.selectedRange == nil {
if let _ = textkitStack.rangeAttributeForKey(NSAttributedString.Key.RLTapResponder, atIndex: touchIndex).attribute as? PatternTapResponder {
self.selectedRange = rangeOfTappedText
}
}
}
fileprivate func cancelSession() {
self.removeHighlight()
}
fileprivate func endSession() {
self.performActionOnSelection()
self.removeHighlight()
}
fileprivate func removeHighlight() {
guard let textkitStack = self.responsiveLabel?.textKitStack,
let selectedRange = self.selectedRange,
let highlightAttributes = self.highlightAttributes,
let defaultAttributes = self.defaultAttributes else {
self.resetGlobalVariables()
return
}
for (key, _) in highlightAttributes {
textkitStack.removeAttribute(forkey: key, atRange: selectedRange)
if let defaultValue = defaultAttributes[key] {
textkitStack.addAttribute(defaultValue, forkey: key, atRange: selectedRange)
}
}
self.responsiveLabel?.setNeedsDisplay()
self.resetGlobalVariables()
}
private func resetGlobalVariables() {
self.selectedRange = nil
self.defaultAttributes = nil
self.highlightAttributes = nil
}
fileprivate func performActionOnSelection() {
guard let textkitStack = self.responsiveLabel?.textKitStack, let selectedRange = self.selectedRange else { return }
if let tapResponder = textkitStack.rangeAttributeForKey(NSAttributedString.Key.RLTapResponder, atIndex: selectedRange.location).attribute as? PatternTapResponder {
let tappedString = textkitStack.substringForRange(selectedRange)
tapResponder.perform(tappedString)
}
}
}
extension TouchHandler : UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let touchLocation = touch.location(in: self.responsiveLabel)
guard let textkitStack = self.responsiveLabel?.textKitStack,
let index = self.responsiveLabel?.textKitStack.characterIndexAtLocation(touchLocation), index < textkitStack.textStorageLength
else {
return false
}
let keys = textkitStack.rangeAttributesAtIndex(index).map { $0.key }
return keys.contains(NSAttributedString.Key.RLHighlightedAttributesDictionary) || keys.contains(NSAttributedString.Key.RLTapResponder)
}
}
| f2d68232fcfb9846d0aa14d6d7b7698a | 34.493056 | 165 | 0.7793 | false | false | false | false |
hellogaojun/Swift-coding | refs/heads/master | swift学习教材案例/GuidedTour-1.2.playground/section-27.swift | apache-2.0 | 1 | var n = 2
while n < 100 {
n = n * 2
}
n
var m = 2
//do {
// m = m * 2
//} while m < 100
repeat {
m = m * 2
} while m < 100
m
| ca3f370d9f2100cd80b952b071e4fa19 | 8.785714 | 17 | 0.408759 | false | false | false | false |
someoneAnyone/Nightscouter | refs/heads/dev | NightscouterNow Extension/ExtensionDelegate.swift | mit | 1 | //
// ExtensionDelegate.swift
// NightscouterNow Extension
//
// Created by Peter Ina on 10/4/15.
// Copyright © 2015 Peter Ina. All rights reserved.
//
import WatchKit
import NightscouterWatchOSKit
import WatchConnectivity
class ExtensionDelegate: NSObject, WKExtensionDelegate {
private var wcBackgroundTasks = [WKWatchConnectivityRefreshBackgroundTask]()
override init() {
super.init()
#if DEBUG
print(">>> Entering \(#function) <<<")
print(">>> ExtensionDelegate <<<")
#endif
// WKWatchConnectivityRefreshBackgroundTask should be completed – Otherwise they will keep consuming
// the background executing time and eventually causes an app crash.
// The timing to complete the tasks is when the current WCSession turns to not .activated or
// hasContentPending flipped to false (see completeBackgroundTasks), so KVO is set up here to observe
// the changes if the two properties.
//
WCSession.default.addObserver(self, forKeyPath: "activationState", options: [], context: nil)
WCSession.default.addObserver(self, forKeyPath: "hasContentPending", options: [], context: nil)
// Create the session coordinator to activate the session asynchronously as early as possible.
// In the case of being background launched with a task, this may save some background runtime budget.
//
_ = SitesDataSource.sharedInstance
}
// When the WCSession's activationState and hasContentPending flips, complete the background tasks.
//
override func observeValue(forKeyPath keyPath: String?, of object: Any?,
change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
DispatchQueue.main.async {
self.completeBackgroundTasks()
}
}
// Compelete the background tasks, and schedule a snapshot refresh.
//
func completeBackgroundTasks() {
guard !wcBackgroundTasks.isEmpty else { return }
let session = WCSession.default
guard session.activationState == .activated && !session.hasContentPending else { return }
wcBackgroundTasks.forEach { $0.setTaskCompleted() }
if (WKExtension.shared().applicationState == .background) {
SitesDataSource.sharedInstance.appIsInBackground = true
for site in SitesDataSource.sharedInstance.sites {
site.fetchDataFromNetwork(useBackground: true, completion: { (updatedSite, error) in
SitesDataSource.sharedInstance.updateSite(updatedSite)
})
}
}
// Use FileLogger to log the tasks for debug purpose. A real app may remove the log
// to save the precious background time.
//
// FileLogger.shared.append(line: "\(#function):\(wcBackgroundTasks) was completed!")
// Schedule a snapshot refresh if the UI is updated by background tasks.
//
let date = Date(timeIntervalSinceNow: 1)
WKExtension.shared().scheduleSnapshotRefresh(withPreferredDate: date, userInfo: nil) { error in
if let error = error {
print("scheduleSnapshotRefresh error: \(error)!")
}
}
WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: Date(timeIntervalSinceNow: TimeInterval.OneHour), userInfo: nil) { (error: Error?) in
if let error = error {
print("Error occured while scheduling background refresh: \(error.localizedDescription)")
}
}
wcBackgroundTasks.removeAll()
}
func applicationDidFinishLaunching() {
#if DEBUG
print(">>> Entering \(#function) <<<")
#endif
}
func applicationDidBecomeActive() {
#if DEBUG
print(">>> Entering \(#function) <<<")
#endif
}
func applicationWillResignActive() {
#if DEBUG
print(">>> Entering \(#function) <<<")
#endif
}
// Be sure to complete all the tasks - otherwise they will keep consuming the background executing
// time until the time is out of budget and the app is killed.
//
// WKWatchConnectivityRefreshBackgroundTask should be completed after the pending data is received
// so retain the tasks first. The retained tasks will be completed at the following cases:
// 1. hasContentPending flips to false, meaning all the pending data is received. Pending data means
// the data received by the device prior to the WCSession getting activated.
// More data might arrive, but it isn't pending when the session activated.
// 2. The end of the handle method.
// This happens when hasContentPending can flip to false before the tasks are retained.
//
// If the tasks are completed before the WCSessionDelegate methods are called, the data will be delivered
// the app is running next time, so no data lost.
//
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
for task in backgroundTasks {
// Use FileLogger to log the tasks for debug purpose. A real app may remove the log
// to save the precious background time.
//
if let wcTask = task as? WKWatchConnectivityRefreshBackgroundTask {
wcBackgroundTasks.append(wcTask)
// FileLogger.shared.append(line: "\(#function):\(wcTask.description) was appended!")
}
else {
task.setTaskCompleted()
// FileLogger.shared.append(line: "\(#function):\(task.description) was completed!")
}
}
completeBackgroundTasks()
}
}
| 3e93e79bab90f55e714ce731b562cb45 | 40.013889 | 159 | 0.630376 | false | false | false | false |
relayr/apple-sdk | refs/heads/master | Sources/common/services/API/APIRules.swift | mit | 1 | import Result
import ReactiveSwift
import Foundation
internal extension API {
/// Rule related types coming from the API.
struct Rule {
/// Describes (at high-level) a rule template.
struct Template {
let identifier: String
let projectIdentifier: String
var title: String
var description: String?
var timestamp: (creation: Date, update: Date?)
/// Describes a specific version of a *rules-engine* template.
struct Version {
let identifier: String
let versionNumber: Int
let templateIdentifier: String
var configurations: [Configuration]
var timestamp: (creation: Date?, update: Date?)
struct Configuration {
var name: String
var description: String?
var type: String
var label: String?
var validation: [String:Any]?
}
}
/// Describes a specific template installation.
struct Installation {
let identifier: String
let userIdentifier: String
let projectIdentifier: String
let templateIdentifier: String
let templateVersionIdentifier: String
var active: Bool
var name: String?
var description: String?
var parameters: [String:Any]
var timestamp: (creation: Date, update: Date?)
}
}
}
}
// HTTP APIs for *rules-engine* related endpoints.
internal extension API {
/// Retrieves a list of templates under the given project.
/// - parameter projectID: Project targeted for *rules-engine* templates.
func templatesFromProject(withID projectID: String) -> SignalProducer<[API.Rule.Template],API.Error> {
let url = Addresses.build(withHostURL: urls.root, relativeURL: "projects/\(projectID)/templates")
return sessionForRequests.request(withAbsoluteURL: url, method: .Get).flatMap(.latest) { (code, data) -> SignalProducer<[API.Rule.Template],API.Error> in
guard code != 404 else { return SignalProducer(value: []) }
guard code == 200 else { return SignalProducer(error: .invalidResponseCode(code: code)) }
guard let response = data,
let json = (try? Parser.toJSON(fromData: response)) as? [[String:Any]] else { return SignalProducer(error: .invalidResponseBody(body: data)) }
let result = json.flatMap { try? API.Rule.Template(fromJSON: $0, projectID: projectID) }
return SignalProducer(value: result)
}
}
/// Retrieves a *rules-engine* targeted template and its latest version.
/// - parameter templateID: Template identifier targeting a specific *rules-engine* template.
/// - parameter projectID: Project targeted for *rules-engine* templates.
func templateInfo(withID templateID: String, fromProjectWithID projectID: String) -> SignalProducer<(API.Rule.Template,API.Rule.Template.Version),API.Error> {
let url = Addresses.build(withHostURL: urls.root, relativeURL: "projects/\(projectID)/templates/\(templateID)")
return sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, expectedCodes: [200]).attemptMap { (json: [String:Any]) in
Result {
guard let versionJSON = json["latestVersion"] as? [String:Any] else { throw API.Error.invalidResponseBody(body: json) }
let template = try API.Rule.Template(fromJSON: json, projectID: projectID)
let version = try API.Rule.Template.Version(fromJSON: versionJSON)
return (template, version)
}
}
}
/// Retrieves all versions of a specific template.
/// - parameter templateID: Unique identifier for the targeted template.
/// - parameter projectID: The project listing the targeted template.
func templateVersions(withID templateID: String, fromProjectWithID projectID: String) -> SignalProducer<[API.Rule.Template.Version],API.Error> {
let url = Addresses.build(withHostURL: urls.root, relativeURL: "projects/\(projectID)/templates/\(templateID)/versions")
return sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, expectedCodes: [200]).map { (json: [[String:Any]]) in
json.flatMap { try? API.Rule.Template.Version(fromJSON: $0) }
}
}
/// Retrieves a *rules-engine* targeted template version.
/// - parameter versionID: A specific version identifier for the previously defined template.
/// - parameter templateID: Template identifier targeting a specific *rules-engine* template.
/// - parameter projectID: Project targeted for *rules-engine* templates.
func templateVersionInfo(withID versionID: String, fromTemplateID templateID: String, projectID: String) -> SignalProducer<API.Rule.Template.Version,API.Error> {
let url = Addresses.build(withHostURL: urls.root, relativeURL: "projects/\(projectID)/templates/\(templateID)/versions/\(versionID)")
return sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, expectedCodes: [200]).attemptMap { (json: [String:Any]) in
Result { try API.Rule.Template.Version(fromJSON: json) }
}
}
/// Applies a given body to a specific *rules-engine*
func installTemplate(withID templateID: String, versionID: String, ofProjectID projectID: String, withName name: String, activityStatus isActive: Bool, parameters: [String:Any]) -> SignalProducer<API.Rule.Template.Installation,API.Error> {
let url = Addresses.build(withHostURL: urls.root, relativeURL: "projects/\(projectID)/templates/\(templateID)/versions/\(versionID)/apply")
let body: [String:Any] = [
"name": name,
"templateVersionId": versionID,
"active": isActive, //NSNumber(bool: isActive),
"description": "",
"parameters": parameters
]
return sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Post, token: token, contentType: .JSON, body: body, expectedCodes: [200]).attemptMap { (json: [String:Any]) in
Result { try API.Rule.Template.Installation(fromJSON: json) }
}
}
/// Removes an installed rule from the cloud platform.
func uninstallTemplate(withID installationID: String, fromUserWithID userID: String) -> SignalProducer<(),API.Error> {
let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)/ruletemplateinstallations/\(installationID)")
return sessionForRequests.request(withAbsoluteURL: url, method: .Delete, token: token, expectedCodes: [204,404]).map { _ in () }
}
/// Installed templates on the user account.
func installedTemplatesForUser(withID userID: String) -> SignalProducer<[API.Rule.Template.Installation],API.Error> {
let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)/ruletemplateinstallations")
return sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).map { (json: [[String:Any]]) in
json.flatMap { try? API.Rule.Template.Installation(fromJSON: $0) }
}
}
/// Retrieves a specific installation template (indicated by the given identifier).
func installedTemplateInfo(withID installationID: String, forUserWithID userID: String) -> SignalProducer<API.Rule.Template.Installation,API.Error> {
let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)/ruletemplateinstallations/\(installationID)")
return sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).attemptMap { (json: [String:Any]) in
Result { try API.Rule.Template.Installation(fromJSON: json) }
}
}
/// Sets the name, activity flag, or template version for the installed rule.
func setInstalledTemplate(withID installationID: String, name: String?=nil, active: Bool?=nil, templateVersionIdentifier: String?=nil, parameters: [String:Any]?=nil, forUserWithID userID: String) -> SignalProducer<API.Rule.Template.Installation,API.Error> {
let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)/ruletemplateinstallations/\(installationID)")
var body: [String:Any] = [:]
if let active = active { body["active"] = NSNumber(value: active) }
if let name = name { body["name"] = name }
if let version = templateVersionIdentifier { body["templateVersionId"] = version }
if let parameters = parameters { body["parameters"] = parameters }
guard !body.isEmpty else {
return SignalProducer(error: .insufficientInformation)
}
return sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Patch, token: token, contentType: .JSON, body: body, expectedCodes: [200]).attemptMap { (json: [String:Any]) in
Result { try API.Rule.Template.Installation(fromJSON: json) }
}
}
}
internal extension API.Rule.Template {
typealias JSONType = [String:Any]
fileprivate init(fromJSON json: JSONType, projectID: String) throws {
guard let identifier = json["id"] as? String,
let title = json["title"] as? String,
let description = json["description"] as? String,
let creationDate = (json["createdAt"] as? String).flatMap(API.dateFormatter.date) else {
throw API.Error.invalidResponseBody(body: json)
}
self.identifier = identifier
self.projectIdentifier = projectID
self.title = title
self.description = description
self.timestamp = (creationDate, (json["updateAt"] as? String).flatMap(API.dateFormatter.date))
}
}
internal extension API.Rule.Template.Version {
typealias JSONType = [String:Any]
fileprivate init(fromJSON json: JSONType) throws {
guard let identifier = json["id"] as? String,
let version = json["versionNumber"] as? Int,
let templateIdentifier = json["templateId"] as? String else {
throw API.Error.invalidResponseBody(body: json)
}
self.identifier = identifier
self.versionNumber = version
self.templateIdentifier = templateIdentifier
self.timestamp = ((json["createdAt"] as? String).flatMap(API.dateFormatter.date), (json["updateAt"] as? String).flatMap(API.dateFormatter.date))
let config = try (json["configuration"] as? [Configuration.JSONType])?.flatMap {
try API.Rule.Template.Version.Configuration(fromJSON: $0)
}
self.configurations = config ?? []
}
}
internal extension API.Rule.Template.Version.Configuration {
typealias JSONType = [String:Any]
fileprivate init(fromJSON json: JSONType) throws {
guard let name = json["name"] as? String,
let type = json["type"] as? String else {
throw API.Error.invalidResponseBody(body: json)
}
self.name = name
self.description = json["description"] as? String
self.type = type
self.label = json["label"] as? String
self.validation = json["validation"] as? [String:Any]
}
}
internal extension API.Rule.Template.Installation {
typealias JSONType = [String:Any]
fileprivate init(fromJSON json: JSONType) throws {
guard let identifier = json["id"] as? String,
let userID = json["userId"] as? String,
let projectID = json["projectId"] as? String,
let templateIdentifier = json["templateId"] as? String,
let templateVersion = json["templateVersionId"] as? String,
let active = (json["active"] as? NSNumber)?.boolValue,
let creationDate = (json["createdAt"] as? String).flatMap(API.dateFormatter.date) else {
throw API.Error.invalidResponseBody(body: json)
}
self.identifier = identifier
self.userIdentifier = userID
self.projectIdentifier = projectID
self.templateIdentifier = templateIdentifier
self.templateVersionIdentifier = templateVersion
self.active = active
self.name = json["name"] as? String
self.description = json["description"] as? String
self.parameters = json["parameters"] as? [String:Any] ?? [:]
self.timestamp = (creationDate, (json["updateAt"] as? String).flatMap(API.dateFormatter.date))
}
}
| 11a2d38e8a9c307b428254c8701437a3 | 51.412245 | 261 | 0.645744 | false | false | false | false |
suragch/Chimee-iOS | refs/heads/master | Chimee/UIMongolLabel.swift | mit | 1 | import UIKit
@IBDesignable class UIMongolLabel: UIView {
// TODO: make view resize to label length
// MARK:- Unique to Label
// ********* Unique to Label *********
fileprivate let view = UILabel()
fileprivate let rotationView = UIView()
fileprivate var userInteractionEnabledForSubviews = true
let mongolFontName = "ChimeeWhiteMirrored"
let defaultFontSize: CGFloat = 17
@IBInspectable var text: String {
get {
return view.text ?? ""
}
set {
view.text = newValue
view.invalidateIntrinsicContentSize()
}
}
@IBInspectable var fontSize: CGFloat {
get {
if let font = view.font {
return font.pointSize
} else {
return 0.0
}
}
set {
view.font = UIFont(name: mongolFontName, size: newValue)
view.invalidateIntrinsicContentSize()
}
}
@IBInspectable var textColor: UIColor {
get {
return view.textColor
}
set {
view.textColor = newValue
}
}
@IBInspectable var centerText: Bool {
get {
return view.textAlignment == NSTextAlignment.center
}
set {
if newValue {
view.textAlignment = NSTextAlignment.center
}
}
}
@IBInspectable var lines: Int {
get {
return view.numberOfLines
}
set {
view.numberOfLines = newValue
}
}
var textAlignment: NSTextAlignment {
get {
return view.textAlignment
}
set {
view.textAlignment = newValue
}
}
var font: UIFont {
get {
return view.font
}
set {
view.font = newValue
}
}
var adjustsFontSizeToFitWidth: Bool {
get {
return view.adjustsFontSizeToFitWidth
}
set {
view.adjustsFontSizeToFitWidth = newValue
}
}
var minimumScaleFactor: CGFloat {
get {
return view.minimumScaleFactor
}
set {
view.minimumScaleFactor = newValue
}
}
override var intrinsicContentSize : CGSize {
return CGSize(width: view.frame.height, height: view.frame.width)
}
func setup() {
self.addSubview(rotationView)
rotationView.addSubview(view)
// set font if user didn't specify size in IB
if self.view.font.fontName != mongolFontName {
view.font = UIFont(name: mongolFontName, size: defaultFontSize)
}
}
// MARK:- General code for Mongol views
// *******************************************
// ****** General code for Mongol views ******
// *******************************************
// This method gets called if you create the view in the Interface Builder
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// This method gets called if you create the view in code
override init(frame: CGRect){
super.init(frame: frame)
self.setup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
rotationView.transform = CGAffineTransform.identity
rotationView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.height, height: self.bounds.width))
rotationView.transform = translateRotateFlip()
view.frame = rotationView.bounds
}
func translateRotateFlip() -> CGAffineTransform {
var transform = CGAffineTransform.identity
// translate to new center
transform = transform.translatedBy(x: (self.bounds.width / 2)-(self.bounds.height / 2), y: (self.bounds.height / 2)-(self.bounds.width / 2))
// rotate counterclockwise around center
transform = transform.rotated(by: CGFloat(-M_PI_2))
// flip vertically
transform = transform.scaledBy(x: -1, y: 1)
return transform
}
}
| 62ad351be784277d468d6a8e0f787345 | 24.664706 | 148 | 0.530827 | false | false | false | false |
LeeKahSeng/KSImageCarousel | refs/heads/master | KSImageCarousel/KSImageCarousel/Sources/KSICImageView.swift | mit | 1 | //
// KSICImageView.swift
// KSImageCarousel
//
// Created by Lee Kah Seng on 22/07/2017.
// Copyright © 2017 Lee Kah Seng. All rights reserved. (https://github.com/LeeKahSeng/KSImageCarousel)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
import UIKit
/// UIImageView subclass that have UIActivityIndicatorView as subview. This allow activity indicator to be shown at the center of the imageView while waiting for image to be downloaded
class KSICImageView: UIImageView {
lazy var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
commonInit()
}
override init(image: UIImage?) {
super.init(image: image)
commonInit()
}
private func commonInit() {
activityIndicator.style = .gray
activityIndicator.hidesWhenStopped = true
activityIndicator.startAnimating()
addSubview(activityIndicator)
// Make activity indicator center
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
let centerX = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: activityIndicator, attribute: .centerX, multiplier: 1, constant:0)
let centerY = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: activityIndicator, attribute: .centerY, multiplier: 1, constant:0)
addConstraints([centerX , centerY])
}
/// Start animating activity indicator
func startLoading() {
activityIndicator.startAnimating()
}
/// Stop animating activity indicator
func stopLoading() {
activityIndicator.stopAnimating()
}
}
| 3ebba9aeed79b90c27e9c544a95cbc01 | 38.647887 | 184 | 0.714032 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | refs/heads/main | WhiteBoardCodingChallenges/Challenges/HackerRank/MissingNumbers/MissingNumbers.swift | mit | 1 | //
// MissingNumbers.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 12/07/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
//https://www.hackerrank.com/challenges/missing-numbers/problem
class MissingNumbers: NSObject {
// MARK: Missing
class func missingNumbers(complete: [Int], incomplete: [Int]) -> [Int] {
var occurrences = [Int: Int]()
for i in 0..<complete.count {
let completeValue = complete[i]
if let existingCount = occurrences[completeValue] {
occurrences[completeValue] = existingCount+1
} else {
occurrences[completeValue] = 1
}
if i < incomplete.count {
let incompleteValue = incomplete[i]
if let existingCount = occurrences[incompleteValue] {
occurrences[incompleteValue] = existingCount-1
} else {
occurrences[incompleteValue] = -1
}
}
}
var missing = [Int]()
for key in occurrences.keys {
if occurrences[key] != 0 {
missing.append(key)
}
}
return missing.sorted(by: { (a, b) -> Bool in
return b > a
})
}
}
| 540c574260d5993cccfb4af478dafd60 | 27.229167 | 76 | 0.519557 | false | false | false | false |
jamalping/XPUtil | refs/heads/master | XPUtilExample/Test/ImageScaleVC.swift | mit | 1 | //
// ImageScaleVC.swift
// XPUtilExample
//
// Created by Apple on 2019/4/17.
// Copyright © 2019年 xyj. All rights reserved.
//
import UIKit
// MARK: - ImageView自适应图片
class ImageScaleVC: UIViewController {
lazy var imageView = UIImageView()
// .init(frame: CGRect.init(x: 10, y: 100, width: 400, height: 500))
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(imageView)
// guard let image = ct_imageFromImage(image: UIImage.init(named: "r")!, rect: imageView.frame) else { return }
// if image.size.height > image.size.width {
// }
guard let image = UIImage.init(named: "t") else { return }
guard let imageData = image.toImageJPEGData else { return }
imageData.forEach { (bety) in
// print(bety)
}
let w = pngImageSizeWithHeaderData(imgdata: imageData)
let scale = image.size.height/image.size.width
imageView.size = CGSize.init(width: 300, height: 300)
imageView.image = image
imageView.backgroundColor = .red
imageView.origin = CGPoint.init(x: 100, y: 100)
imageView.contentMode = .scaleAspectFill
let url = URL.init(string: "http://kuaiqiav2.oss-cn-shenzhen.aliyuncs.com/photo/20190417/2_20190417141209545.jpg?x-oss-process=image/info")!
let request = URLRequest.init(url: url)
guard let data = try? Data.init(contentsOf: url) else { return }
let dataString = String.init(data: data, encoding: String.Encoding.utf8)
print(dataString)
}
func config() {
layout()
}
func layout() {
}
}
func pngImageSizeWithHeaderData(imgdata: Data) -> CGSize
{
var w1 = 0.0
var w2 = 0.0
var w3 = 0.0
var w4 = 0.0
let index0 = imgdata.index(imgdata.startIndex, offsetBy: 1)
let index1 = imgdata.index(index0, offsetBy: 1)
let index2 = imgdata.index(index1, offsetBy: 1)
let index3 = imgdata.index(index2, offsetBy: 1)
var w: CGFloat = 0
var h: CGFloat = 0
imgdata.enumerated().forEach { (index, element) in
if index <= 3 {
w += CGFloat(element << ((3-index)*8))
}else if index <= 7 {
h += CGFloat(element << ((7-index)*8))
}
}
return CGSize.init(width: w, height: h)
// imgdata.copyBytes(to: w1, from: imgdata.index(0, offsetBy: 1))
// imgdata.copyBytes(to: &w1, from: imgdata.index(0, offsetBy: 1))
// [data getBytes:&w1 range:NSMakeRange(0, 1)];
// [data getBytes:&w2 range:NSMakeRange(1, 1)];
// [data getBytes:&w3 range:NSMakeRange(2, 1)];
// [data getBytes:&w4 range:NSMakeRange(3, 1)];
// int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
//
// int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
// [data getBytes:&h1 range:NSMakeRange(4, 1)];
// [data getBytes:&h2 range:NSMakeRange(5, 1)];
// [data getBytes:&h3 range:NSMakeRange(6, 1)];
// [data getBytes:&h4 range:NSMakeRange(7, 1)];
// int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
//
// return CGSizeMake(w, h);
}
func ct_imageFromImage(image: UIImage, rect: CGRect) -> UIImage? {
let size = image.size
let a = rect.size.width/rect.size.height
var X: CGFloat = 0.0
var Y: CGFloat = 0.0
var W: CGFloat = 0.0
var H: CGFloat = 0.0
if size.width > size.height {
H = size.height
W = H*a
Y = 0
X = (size.width - W)/2
if (size.width - size.height*a)/2<0 {
W = size.width
H = size.width/a
Y = (size.height-H)/2
X = 0
}
}else{
W = size.width
H = W/a
X = 0
Y = (size.height - H)/2
if (size.height - size.width/a)/2<0 {
H = size.height
W = size.height*a
X = (size.width-W)/2
Y = 0
}
}
//把像 素rect 转化为 点rect(如无转化则按原图像素取部分图片)
// CGFloat scale = [UIScreen mainScreen].scale;
let dianRect = CGRect.init(x: X, y: Y, width: W, height: H)//CGRectMake(x, y, w, h);
// CGImageCreateWithImageInRect
guard let imageRef = image.cgImage?.cropping(to: dianRect) else { return nil }
return UIImage.init(cgImage: imageRef, scale: UIScreen.main.scale, orientation: UIImage.Orientation.up)
//截取部分图片并生成新图片
//
// CGImageRef sourceImageRef = [image CGImage];
// CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, dianRect);
// UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
//
// CGImageRelease(sourceImageRef);
//
//
// return newImage;
}
//-(UIImage *)ct_imageFromImage:(UIImage *)image inRect:(CGRect)rect{
//
// CGSize size=image.size;
//
//
// if (size.width>size.height) {
//
// H= size.height;
// W= H*a;
// Y=0;
// X= (size.width - W)/2;
//
// if ((size.width - size.height*a)/2<0) {
//
// W = size.width;
// H = size.width/a;
// Y= (size.height-H)/2;
// X=0;
// }
//
// }else{
//
// W= size.width;
// H= W/a;
// X=0;
// Y= (size.height - H)/2;
//
// if ((size.height - size.width/a)/2<0) {
//
// H= size.height;
// W = size.height*a;
// X= (size.width-W)/2;
// Y=0;
// }
//
// }
//
// //把像 素rect 转化为 点rect(如无转化则按原图像素取部分图片)
// // CGFloat scale = [UIScreen mainScreen].scale;
// CGRect dianRect = CGRectMake(X, Y, W, H);//CGRectMake(x, y, w, h);
//
// //截取部分图片并生成新图片
// CGImageRef sourceImageRef = [image CGImage];
// CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, dianRect);
// UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
//
// CGImageRelease(sourceImageRef);
//
//
// return newImage;
// ---------------------
// 作者:YoYo____u
// 来源:CSDN
// 原文:https://blog.csdn.net/youyou_56/article/details/82968475
//版权声明:本文为博主原创文章,转载请附上博文链接!
| 76a8189044962a0cf0b1c4b4efe8eb9d | 29.648515 | 148 | 0.564368 | false | false | false | false |
codingTheHole/BuildingAppleWatchProjectsBook | refs/heads/master | Xcode Projects by Chapter/5086_Code_Ch07_PlotBuddy/Plot Buddy/Plot Buddy WatchKit Extension/InterfaceController.swift | cc0-1.0 | 1 | //
// InterfaceController.swift
// Plot Buddy WatchKit Extension
//
// Created by Stuart Grimshaw on 23/11/15.
// Copyright © 2015 Stuart Grimshaw. All rights reserved.
//
import WatchKit
let kStartPlotting = "Start\nPlotting"
let kStopPlotting = "Stop\nPlotting"
let kStoreCoordinates = "Add Current\nCoordinates"
let kFetching = "Fetching Location..."
let kLocationFailed = "Location Failed"
class InterfaceController: WKInterfaceController, PBLocationManagerDelegate {
var locationManager: PBLocationManager!
var isRecording = false
@IBOutlet var startStopGroup: WKInterfaceGroup!
@IBOutlet var addPlotGroup: WKInterfaceGroup!
@IBOutlet var showPlotsGroup: WKInterfaceGroup!
@IBOutlet var showPlotsButton: WKInterfaceButton!
@IBOutlet var infoLable: WKInterfaceLabel!
@IBOutlet var startStopButton: WKInterfaceButton!
@IBOutlet var addPlotButton: WKInterfaceButton!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
locationManager = PBLocationManager(delegate: self)
updateUI(running: false)
}
@IBAction func startStopButtonPressed() {
toggleRecording()
}
@IBAction func addPlotButtonPressed() {
fetchLocation()
}
@IBAction func showPlotsButtonTapped() {
pushControllerWithName("PlotsScene", context: locationManager.currentLocations)
}
@IBAction func sendPlotsButtonTapped() {
WatchConnectivityManager.sharedManager.sendDataToWatch(
locationManager.currentLocations)
}
func toggleRecording() {
isRecording = !isRecording
if isRecording {
locationManager.clearLocations()
}
updateUI(running: isRecording)
}
func fetchLocation() {
updateUI(fetching: true)
locationManager.requestLocation()
}
func handleNewLocation(newLocation: CLLocation) {
addPlotButton.setTitle(kStoreCoordinates)
infoLable.setText("Lat:\n" + "\(newLocation.coordinate.latitude)" + "\nLong:\n" + "\(newLocation.coordinate.longitude)")
updateUI(fetching: false)
}
func handleLocationFailure(error: NSError) {
infoLable.setText(kLocationFailed)
updateUI(fetching: false)
}
func updateUI(running running: Bool) {
infoLable.setText("")
infoLable.setHidden(!running)
startStopButton.setTitle(isRecording ? kStopPlotting : kStartPlotting)
showPlotsGroup.setHidden(running)
showPlotsButton.setEnabled(locationManager.currentLocations.count > 0)
showPlotsGroup.setBackgroundColor(locationManager.currentLocations.count > 0 ? UIColor.blueColor() : UIColor.clearColor())
addPlotGroup.setHidden(!isRecording)
}
func updateUI(fetching fetching: Bool) {
infoLable.setHidden(fetching)
startStopButton.setEnabled(!fetching)
startStopGroup.setBackgroundColor(fetching ? UIColor.clearColor() : UIColor.blueColor())
addPlotButton.setEnabled(!fetching)
addPlotGroup.setBackgroundColor(fetching ? UIColor.clearColor() : UIColor.blueColor())
addPlotButton.setTitle(fetching ? kFetching : kStoreCoordinates)
}
}
| 443c12082ba4da89d2c006a6ab3067d4 | 32.08 | 130 | 0.691657 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/TypeDecoder/reference_storage.swift | apache-2.0 | 32 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-executable %s -g -o %t/reference_storage -emit-module
// RUN: sed -ne '/\/\/ *DEMANGLE: /s/\/\/ *DEMANGLE: *//p' < %s > %t/input
// RUN: %lldb-moduleimport-test %t/reference_storage -type-from-mangled=%t/input | %FileCheck %s
func blackHole(_: Any...) {}
class Class {}
let c = Class()
weak var weakVar: Class? = c
unowned let unownedVar: Class = c
unowned(unsafe) let unmanagedVar: Class = c
blackHole(weakVar, unownedVar, unmanagedVar)
// DEMANGLE: $s17reference_storage5ClassCSgXwD
// DEMANGLE: $s17reference_storage5ClassCXoD
// DEMANGLE: $s17reference_storage5ClassCXuD
// CHECK: @sil_weak Optional<Class>
// CHECK: @sil_unowned Class
// CHECK: @sil_unmanaged Class | 017321376bcd8456f3b0682003df6327 | 27.576923 | 96 | 0.698113 | false | false | false | false |
angelcstt/DouYuZB | refs/heads/master | DYZB/DYZB/Classes/Main/View/PageTitleView.swift | mit | 1 | //
// PageTitleView.swift
// DYZB
//
// Created by macosx on 2017/9/2.
// Copyright © 2017年 angelcstt. All rights reserved.
//
import UIKit
//定义代理协议
protocol PageTitleViewDelegate : class {
func pageTitleView (titleView : PageTitleView, selectedIndex index: Int)
}
//定义常量
private let kScrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85)
private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0)
class PageTitleView: UIView {
//定义属性
public var currentIndex : Int = 0
public var titles : [String]
weak var delegate : PageTitleViewDelegate?
// MARK: -懒加载属性
public lazy var titleLabels : [UILabel] = [UILabel]()
public lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
public lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
//自定义构造函数
init(frame: CGRect,titles : [String]) {
self.titles = titles
super.init(frame: frame)
//设置UI界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// mark: - 设置UI界面
extension PageTitleView{
public func setupUI(){
//添加UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
//添加title对应的label
setTitleLabels()
//添加底线和title下面滚动line
setupBottomMenuAndScrollLine()
}
private func setTitleLabels(){
for (index,title) in titles.enumerated(){
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labeiH : CGFloat = frame.height - kScrollLineH
let labelY : CGFloat = 0
//创建UILabel
let label = UILabel()
//设置UILabel的属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor.darkGray
label.textAlignment = .center
//设置Label的Frame
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labeiH)
//将Label添加到scrollview中
scrollView.addSubview(label)
titleLabels.append(label)
//给label添加手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupBottomMenuAndScrollLine(){
//添加底线
let buttomLine = UIView()
buttomLine.backgroundColor = UIColor.lightGray
let lineH :CGFloat = 0.5
buttomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(buttomLine)
//添加scrollLine
guard let firstLabel = titleLabels.first else { return }
firstLabel.textColor = UIColor.orange
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH)
}
}
//监听label点击
extension PageTitleView{
//事件监听一定要在定义方法前加上@objc
@objc public func titleLabelClick(tapGes : UITapGestureRecognizer){
//print("葵花点穴手!")
//获取当前label下标值
guard let currentLabel = tapGes.view as? UILabel else { return }
//获取之前的label下标
let oldLabel = titleLabels[currentIndex]
//切换文字颜色
currentLabel.textColor = UIColor.orange
oldLabel.textColor = UIColor.darkGray
//保存最新label的下标值
currentIndex = currentLabel.tag
//滚动条位置发生改变
let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width
UIView.animate(withDuration: 0.01) {
self.scrollLine.frame.origin.x = scrollLineX
}
//通知代理
delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex)
}
}
//暴露的方法
extension PageTitleView{
func setTitleWithProgress(progress : CGFloat,sourceIndex : Int,targetIndex : Int) {
//取出sourcelabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
//处理滑块逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
//处理颜色渐变
}
}
| 4b58b3c90e7c7644c84ecbe48dceb681 | 24.071429 | 148 | 0.57284 | false | false | false | false |
wireapp/wire-ios-sync-engine | refs/heads/develop | Tests/Source/RecordingMockTransportSession.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
@objcMembers
class RecordingMockTransportSession: NSObject, TransportSessionType {
var pushChannel: ZMPushChannel
var cookieStorage: ZMPersistentCookieStorage
var requestLoopDetectionCallback: ((String) -> Void)?
let mockReachability = MockReachability()
var reachability: ReachabilityProvider & TearDownCapable {
return mockReachability
}
init(cookieStorage: ZMPersistentCookieStorage, pushChannel: ZMPushChannel) {
self.pushChannel = pushChannel
self.cookieStorage = cookieStorage
super.init()
}
func tearDown() { }
var didCallEnterBackground = false
func enterBackground() {
didCallEnterBackground = true
}
var didCallEnterForeground = false
func enterForeground() {
didCallEnterForeground = true
}
func prepareForSuspendedState() { }
func cancelTask(with taskIdentifier: ZMTaskIdentifier) { }
var lastEnqueuedRequest: ZMTransportRequest?
func enqueueOneTime(_ request: ZMTransportRequest) {
lastEnqueuedRequest = request
}
func attemptToEnqueueSyncRequest(generator: () -> ZMTransportRequest?) -> ZMTransportEnqueueResult {
guard let request = generator() else {
return ZMTransportEnqueueResult(didHaveLessRequestsThanMax: true, didGenerateNonNullRequest: false)
}
lastEnqueuedRequest = request
return ZMTransportEnqueueResult(didHaveLessRequestsThanMax: true, didGenerateNonNullRequest: true)
}
func setAccessTokenRenewalFailureHandler(handler: @escaping ZMCompletionHandlerBlock) { }
var didCallSetNetworkStateDelegate: Bool = false
func setNetworkStateDelegate(_ delegate: ZMNetworkStateDelegate?) {
didCallSetNetworkStateDelegate = true
}
func addCompletionHandlerForBackgroundSession(identifier: String, handler: @escaping () -> Void) { }
var didCallConfigurePushChannel = false
func configurePushChannel(consumer: ZMPushChannelConsumer, groupQueue: ZMSGroupQueue) {
didCallConfigurePushChannel = true
}
}
| c2304b5c526a5d5684edf0abc19169e9 | 31.776471 | 111 | 0.734745 | false | false | false | false |
vazteam/ProperMediaView | refs/heads/master | Example/ProperMediaViewDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// ProperMediaViewDemo
//
// Created by Murawaki on 2017/03/30.
// Copyright © 2017年 Murawaki. All rights reserved.
//
import UIKit
import ProperMediaView
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/*Debug
let webImageCache = SDImageCache.shared()
webImageCache.clearMemory()
webImageCache.clearDisk {}*/
//Image
let imageMedia = ProperImage(thumbnailUrl: URL(string: "https://i.gyazo.com/f4f9410028b33650b7f2f0c76e3e82ff.png")!,
originalImageUrl: URL(string: "https://i.gyazo.com/f32151613b826dec8faab456f1d6e8b6.png")!)
let imageMediaView = ProperMediaView(frame: CGRect(x: 0, y: 0, width: 200, height: 200), media: imageMedia, isNeedsDownloadOriginalImage: true)
imageMediaView.setEnableFullScreen(fromViewController: self)
//Movie
let movieMedia = ProperMovie(thumbnailUrlStr: "https://i.gyazo.com/f4f9410028b33650b7f2f0c76e3e82ff.png",
movieUrlStr: "http://img.profring.com/medias/4813cacbc19667eacb05c8705d9db7a5120832mnKcTmYOH8XiszVsaTMuohH8ovnCXSsH.mp4")
let movieMediaView = ProperMediaView(frame: CGRect(x: 0, y: 0, width: 200, height: 200), media: movieMedia)
movieMediaView.setEnableFullScreen(fromViewController: self)
imageMediaView.center = view.center
imageMediaView.center.y -= 150
movieMediaView.center = view.center
movieMediaView.center.y += 150
view.addSubview(imageMediaView)
view.addSubview(movieMediaView)
//再生が開始されてからDLが始まる
movieMediaView.play()
}
}
| 263fdaa062c3a05ee12ab4194387332b | 35.791667 | 158 | 0.660815 | false | false | false | false |
connienguyen/volunteers-iOS | refs/heads/development | VOLA/VOLA/Model/Location.swift | gpl-2.0 | 1 | //
// Location.swift
// VOLA
//
// Created by Connie Nguyen on 6/13/17.
// Copyright © 2017 Systers-Opensource. All rights reserved.
//
import Foundation
import ObjectMapper
/**
Enum to organize mappable fields on Location from JSON
*/
enum LocationMappable: String {
case name
case address1
case address2
case city
case postCode
case country
case phone
case latitude
case longitude
/// JSON key to map from
var mapping: String {
return self.rawValue.lowercased()
}
}
/// Model for Location data within an Event
class Location {
var name: String = ""
var address1: String = ""
var address2: String = ""
var city: String = ""
var postCode: String = ""
var country: String = ""
var phone: String = ""
var latitude: Double = 0.0
var longitude: Double = 0.0
/// Full address as one string, separated by newlines
var addressString: String {
let mainAddressArray: [String] = [name, address1, address2, city].filter({ !$0.trimmed.isEmpty})
return mainAddressArray.joined(separator: "\n").trimmed
}
/// Shortened address as one string, separated by newlines
var shortAddressString: String {
let shortAddressArray: [String] = [name, address1, address2].filter({ !$0.trimmed.isEmpty })
return shortAddressArray.joined(separator: "\n").trimmed
}
var isDefaultCoords: Bool {
return latitude == 0.0 && longitude == 0.0
}
required init?(map: Map) {
// Required to conform to protocol
}
/// Used to initialize Location object with default values (e.g. in Event)
init() { /* intentionally empty */ }
}
// MARK: - Conform to protocol for Mappable
extension Location: Mappable {
func mapping(map: Map) {
name <- map[LocationMappable.name.mapping]
address1 <- map[LocationMappable.address1.mapping]
address2 <- map[LocationMappable.address2.mapping]
city <- map[LocationMappable.city.mapping]
postCode <- map[LocationMappable.postCode.mapping]
country <- map[LocationMappable.country.mapping]
phone <- map[LocationMappable.phone.mapping]
latitude <- map[LocationMappable.latitude.mapping]
longitude <- map[LocationMappable.longitude.mapping]
}
}
| 226b6314e33493e75988ddd5c541dfcc | 27.987654 | 104 | 0.644378 | false | false | false | false |
RiBj1993/CodeRoute | refs/heads/master | Pods/SwiftyGif/SwiftyGif/UIImage+SwiftyGif.swift | apache-2.0 | 1 | //
// UIImage+SwiftyGif.swift
//
import ImageIO
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l <= r
default:
return !(rhs < lhs)
}
}
let _imageSourceKey = malloc(4)
let _displayRefreshFactorKey = malloc(4)
let _imageCountKey = malloc(4)
let _displayOrderKey = malloc(4)
let _imageSizeKey = malloc(4)
let _imageDataKey = malloc(4)
let defaultLevelOfIntegrity: Float = 0.8
fileprivate enum GifParseError:Error {
case noProperties
case noGifDictionary
case noTimingInfo
}
public extension UIImage{
// MARK: Inits
/**
Convenience initializer. Creates a gif with its backing data. Defaulted level of integrity.
- Parameter gifData: The actual gif data
*/
public convenience init(gifData:Data) {
self.init()
setGifFromData(gifData,levelOfIntegrity: defaultLevelOfIntegrity)
}
/**
Convenience initializer. Creates a gif with its backing data.
- Parameter gifData: The actual gif data
- Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping
*/
public convenience init(gifData:Data, levelOfIntegrity:Float) {
self.init()
setGifFromData(gifData,levelOfIntegrity: levelOfIntegrity)
}
/**
Convenience initializer. Creates a gif with its backing data. Defaulted level of integrity.
- Parameter gifName: Filename
*/
public convenience init(gifName: String) {
self.init()
setGif(gifName, levelOfIntegrity: defaultLevelOfIntegrity)
}
/**
Convenience initializer. Creates a gif with its backing data.
- Parameter gifName: Filename
- Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping
*/
public convenience init(gifName: String, levelOfIntegrity: Float) {
self.init()
setGif(gifName, levelOfIntegrity: levelOfIntegrity)
}
/**
Set backing data for this gif. Overwrites any existing data.
- Parameter data: The actual gif data
- Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping
*/
public func setGifFromData(_ data:Data,levelOfIntegrity:Float) {
guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else { return }
self.imageSource = imageSource
self.imageData = data
do {
calculateFrameDelay(try delayTimes(imageSource), levelOfIntegrity: levelOfIntegrity)
} catch {
print("Could not determine delay times for GIF.")
return
}
calculateFrameSize()
}
/**
Set backing data for this gif. Overwrites any existing data.
- Parameter name: Filename
*/
public func setGif(_ name: String) {
setGif(name, levelOfIntegrity: defaultLevelOfIntegrity)
}
/**
Check the number of frame for this gif
- Return number of frames
*/
public func framesCount() -> Int{
if let orders = self.displayOrder{
return orders.count
}
return 0
}
/**
Set backing data for this gif. Overwrites any existing data.
- Parameter name: Filename
- Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping
*/
public func setGif(_ name: String, levelOfIntegrity: Float) {
if let url = Bundle.main.url(forResource: name,
withExtension: name.getPathExtension() == "gif" ? "" : "gif") {
if let data = try? Data(contentsOf: url) {
setGifFromData(data,levelOfIntegrity: levelOfIntegrity)
} else {
print("Error : Invalid GIF data for \(name).gif")
}
} else {
print("Error : Gif file \(name).gif not found")
}
}
// MARK: Logic
fileprivate func convertToDelay(_ pointer:UnsafeRawPointer?) -> Float? {
if pointer == nil {
return nil
}
let value = unsafeBitCast(pointer, to:AnyObject.self)
return value.floatValue
}
/**
Get delay times for each frames
- Parameter imageSource: reference to the gif image source
- Returns array of delays
*/
fileprivate func delayTimes(_ imageSource:CGImageSource) throws ->[Float] {
let imageCount = CGImageSourceGetCount(imageSource)
var imageProperties = [CFDictionary]()
for i in 0..<imageCount{
if let dict = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) {
imageProperties.append(dict)
} else {
throw GifParseError.noProperties
}
}
let frameProperties = try imageProperties.map(){
(dict:CFDictionary)->CFDictionary in
let key = Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()
let value = CFDictionaryGetValue(dict, key)
if value == nil {
throw GifParseError.noGifDictionary
}
return unsafeBitCast(value, to:CFDictionary.self)
}
let EPS:Float = 1e-6
let frameDelays:[Float] = try frameProperties.map(){
let unclampedKey = Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()
let unclampedPointer:UnsafeRawPointer? = CFDictionaryGetValue($0, unclampedKey)
if let value = convertToDelay(unclampedPointer), value >= EPS {
return value
}
let clampedKey = Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()
let clampedPointer:UnsafeRawPointer? = CFDictionaryGetValue($0, clampedKey)
if let value = convertToDelay(clampedPointer) {
return value
}
throw GifParseError.noTimingInfo
}
return frameDelays
}
/**
Compute backing data for this gif
- Parameter delaysArray: decoded delay times for this gif
- Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping
*/
fileprivate func calculateFrameDelay(_ delaysArray:[Float],levelOfIntegrity:Float){
var delays = delaysArray
//Factors send to CADisplayLink.frameInterval
let displayRefreshFactors = [60,30,20,15,12,10,6,5,4,3,2,1]
//maxFramePerSecond,default is 60
let maxFramePerSecond = displayRefreshFactors.first
//frame numbers per second
let displayRefreshRates = displayRefreshFactors.map{maxFramePerSecond!/$0}
//time interval per frame
let displayRefreshDelayTime = displayRefreshRates.map{1.0/Float($0)}
//caclulate the time when each frame should be displayed at(start at 0)
for i in 1..<delays.count{ delays[i] += delays[i-1] }
//find the appropriate Factors then BREAK
for i in 0..<displayRefreshDelayTime.count{
let displayPosition = delays.map{Int($0/displayRefreshDelayTime[i])}
var framelosecount: Float = 0
for j in 1..<displayPosition.count{
if displayPosition[j] == displayPosition[j-1] {
framelosecount += 1
}
}
if(displayPosition[0] == 0){
framelosecount += 1
}
if framelosecount <= Float(displayPosition.count) * (1.0 - levelOfIntegrity) ||
i == displayRefreshDelayTime.count-1 {
self.imageCount = displayPosition.last!
self.displayRefreshFactor = displayRefreshFactors[i]
self.displayOrder = [Int]()
var indexOfold = 0
var indexOfnew = 1
while indexOfnew <= imageCount {
if indexOfnew <= displayPosition[indexOfold] {
self.displayOrder!.append(indexOfold)
indexOfnew += 1
}else{
indexOfold += 1
}
}
break
}
}
}
/**
Compute frame size for this gif
*/
fileprivate func calculateFrameSize(){
guard let imageSource = imageSource else {
return
}
guard let imageCount = imageCount else {
return
}
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource,0,nil) else {
return
}
let image = UIImage(cgImage:cgImage)
self.imageSize = Int(image.size.height*image.size.width*4)*imageCount/1000000
}
// MARK: get / set associated values
public var imageSource: CGImageSource? {
get {
let result = objc_getAssociatedObject(self, _imageSourceKey)
if result == nil {
return nil
}
return (result as! CGImageSource)
}
set {
objc_setAssociatedObject(self, _imageSourceKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN);
}
}
public var displayRefreshFactor: Int?{
get {
return objc_getAssociatedObject(self, _displayRefreshFactorKey) as? Int
}
set {
objc_setAssociatedObject(self, _displayRefreshFactorKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN);
}
}
public var imageSize: Int?{
get {
return objc_getAssociatedObject(self, _imageSizeKey) as? Int
}
set {
objc_setAssociatedObject(self, _imageSizeKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN);
}
}
public var imageCount: Int?{
get {
return objc_getAssociatedObject(self, _imageCountKey) as? Int
}
set {
objc_setAssociatedObject(self, _imageCountKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN);
}
}
public var displayOrder: [Int]?{
get {
return objc_getAssociatedObject(self, _displayOrderKey) as? [Int]
}
set {
objc_setAssociatedObject(self, _displayOrderKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN);
}
}
public var imageData:Data? {
get {
let result = objc_getAssociatedObject(self, _imageDataKey)
if result == nil {
return nil
}
return (result as! Data)
}
set {
objc_setAssociatedObject(self, _imageDataKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN);
}
}
}
extension String {
func getPathExtension() -> String {
return (self as NSString).pathExtension
}
}
| 538a9e8e5c9f1490a8f940ff4d11aed1 | 31.325581 | 127 | 0.589029 | false | false | false | false |
OfficeDev/O365-iOS-Microsoft-Graph-Connect-Swift | refs/heads/master | O365-iOS-Microsoft-Graph-Connect-Swift/AuthenticationConstants.swift | mit | 1 | /*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See LICENSE in the project root for license information.
*/
import Foundation
// You'll set your application's ClientId and RedirectURI here. These values are provided by your Microsoft Azure app
//registration. See README.MD for more details.
struct ApplicationConstants {
static let ResourceId = "https://graph.microsoft.com"
static let kAuthority = "https://login.microsoftonline.com/common"
static let kGraphURI = "https://graph.microsoft.com/v1.0/me/"
static let kScopes = ["https://graph.microsoft.com/Mail.ReadWrite",
"https://graph.microsoft.com/Mail.Send",
"https://graph.microsoft.com/Files.ReadWrite",
"https://graph.microsoft.com/User.ReadBasic.All"]
/*
To enable brokered auth, redirect uri must be in the form of "msauth.<your-bundle-id-here>://auth".
The redirect uri needs to be registered for your app in Azure Portal
The scheme, i.e. "msauth.<your-bundle-id-here>" needs to be registered in the info.plist of the project
*/
static let kRedirectUri = "msauth.com.microsoft.O365-iOS-Microsoft-Graph-Connect-Swift-REST://auth"
// Put your client id here
static let kClientId = "<your-client-id>"
/**
Simple construct to encapsulate NSError. This could be expanded for more types of graph errors in future.
*/
enum MSGraphError: Error {
case nsErrorType(error: NSError)
}
}
| b2b501ccbc1e2052cb7f7c7211779d30 | 43.628571 | 117 | 0.671575 | false | false | false | false |
JoeLago/MHGDB-iOS | refs/heads/master | Pods/GRDB.swift/GRDB/QueryInterface/TableDefinition.swift | mit | 1 | extension Database {
// MARK: - Database Schema
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates a database table.
///
/// try db.create(table: "pointOfInterests") { t in
/// t.column("id", .integer).primaryKey()
/// t.column("title", .text)
/// t.column("favorite", .boolean).notNull().default(false)
/// t.column("longitude", .double).notNull()
/// t.column("latitude", .double).notNull()
/// }
///
/// See https://www.sqlite.org/lang_createtable.html and
/// https://www.sqlite.org/withoutrowid.html
///
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (TableDefinition) -> Void) throws {
let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID)
body(definition)
let sql = try definition.sql(self)
try execute(sql)
}
#else
/// Creates a database table.
///
/// try db.create(table: "pointOfInterests") { t in
/// t.column("id", .integer).primaryKey()
/// t.column("title", .text)
/// t.column("favorite", .boolean).notNull().default(false)
/// t.column("longitude", .double).notNull()
/// t.column("latitude", .double).notNull()
/// }
///
/// See https://www.sqlite.org/lang_createtable.html and
/// https://www.sqlite.org/withoutrowid.html
///
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@available(iOS 8.2, OSX 10.10, *)
public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool, body: (TableDefinition) -> Void) throws {
// WITHOUT ROWID was added in SQLite 3.8.2 http://www.sqlite.org/changes.html#version_3_8_2
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID)
body(definition)
let sql = try definition.sql(self)
try execute(sql)
}
/// Creates a database table.
///
/// try db.create(table: "pointOfInterests") { t in
/// t.column("id", .integer).primaryKey()
/// t.column("title", .text)
/// t.column("favorite", .boolean).notNull().default(false)
/// t.column("longitude", .double).notNull()
/// t.column("latitude", .double).notNull()
/// }
///
/// See https://www.sqlite.org/lang_createtable.html
///
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (TableDefinition) -> Void) throws {
let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: false)
body(definition)
let sql = try definition.sql(self)
try execute(sql)
}
#endif
/// Renames a database table.
///
/// See https://www.sqlite.org/lang_altertable.html
///
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func rename(table name: String, to newName: String) throws {
try execute("ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)")
}
/// Modifies a database table.
///
/// try db.alter(table: "players") { t in
/// t.add(column: "url", .text)
/// }
///
/// See https://www.sqlite.org/lang_altertable.html
///
/// - parameters:
/// - name: The table name.
/// - body: A closure that defines table alterations.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func alter(table name: String, body: (TableAlteration) -> Void) throws {
let alteration = TableAlteration(name: name)
body(alteration)
let sql = try alteration.sql(self)
try execute(sql)
}
/// Deletes a database table.
///
/// See https://www.sqlite.org/lang_droptable.html
///
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func drop(table name: String) throws {
try execute("DROP TABLE \(name.quotedDatabaseIdentifier)")
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates an index.
///
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
///
/// SQLite can also index expressions (https://www.sqlite.org/expridx.html)
/// and use specific collations. To create such an index, use a raw SQL
/// query.
///
/// try db.execute("CREATE INDEX ...")
///
/// See https://www.sqlite.org/lang_createindex.html
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - unique: If true, creates a unique index.
/// - ifNotExists: If false, no error is thrown if index already exists.
/// - condition: If not nil, creates a partial index
/// (see https://www.sqlite.org/partialindex.html).
public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible? = nil) throws {
// Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression)
let sql = definition.sql()
try execute(sql)
}
#else
/// Creates an index.
///
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
///
/// SQLite can also index expressions (https://www.sqlite.org/expridx.html)
/// and use specific collations. To create such an index, use a raw SQL
/// query.
///
/// try db.execute("CREATE INDEX ...")
///
/// See https://www.sqlite.org/lang_createindex.html
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - unique: If true, creates a unique index.
/// - ifNotExists: If false, no error is thrown if index already exists.
public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false) throws {
// Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: nil)
let sql = definition.sql()
try execute(sql)
}
/// Creates a partial index.
///
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"], condition: Column("email") != nil)
///
/// See https://www.sqlite.org/lang_createindex.html, and
/// https://www.sqlite.org/partialindex.html
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - unique: If true, creates a unique index.
/// - ifNotExists: If false, no error is thrown if index already exists.
/// - condition: The condition that indexed rows must verify.
@available(iOS 8.2, OSX 10.10, *)
public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible) throws {
// Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition.sqlExpression)
let sql = definition.sql()
try execute(sql)
}
#endif
/// Deletes a database index.
///
/// See https://www.sqlite.org/lang_dropindex.html
///
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func drop(index name: String) throws {
try execute("DROP INDEX \(name.quotedDatabaseIdentifier)")
}
}
/// The TableDefinition class lets you define table columns and constraints.
///
/// You don't create instances of this class. Instead, you use the Database
/// `create(table:)` method:
///
/// try db.create(table: "players") { t in // t is TableDefinition
/// t.column(...)
/// }
///
/// See https://www.sqlite.org/lang_createtable.html
public final class TableDefinition {
private typealias KeyConstraint = (columns: [String], conflictResolution: Database.ConflictResolution?)
private let name: String
private let temporary: Bool
private let ifNotExists: Bool
private let withoutRowID: Bool
private var columns: [ColumnDefinition] = []
private var primaryKeyConstraint: KeyConstraint?
private var uniqueKeyConstraints: [KeyConstraint] = []
private var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = []
private var checkConstraints: [SQLExpression] = []
init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) {
self.name = name
self.temporary = temporary
self.ifNotExists = ifNotExists
self.withoutRowID = withoutRowID
}
/// Appends a table column.
///
/// try db.create(table: "players") { t in
/// t.column("name", .text)
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#tablecoldef
///
/// - parameter name: the column name.
/// - parameter type: the eventual column type.
/// - returns: An ColumnDefinition that allows you to refine the
/// column definition.
@discardableResult
public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
let column = ColumnDefinition(name: name, type: type)
columns.append(column)
return column
}
/// Defines the table primary key.
///
/// try db.create(table: "citizenships") { t in
/// t.column("citizenID", .integer)
/// t.column("countryCode", .text)
/// t.primaryKey(["citizenID", "countryCode"])
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#primkeyconst and
/// https://www.sqlite.org/lang_createtable.html#rowid
///
/// - parameter columns: The primary key columns.
/// - parameter conflitResolution: An optional conflict resolution
/// (see https://www.sqlite.org/lang_conflict.html).
public func primaryKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) {
guard primaryKeyConstraint == nil else {
// Programmer error
fatalError("can't define several primary keys")
}
primaryKeyConstraint = (columns: columns, conflictResolution: conflictResolution)
}
/// Adds a unique key.
///
/// try db.create(table: "pointOfInterests") { t in
/// t.column("latitude", .double)
/// t.column("longitude", .double)
/// t.uniqueKey(["latitude", "longitude"])
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#uniqueconst
///
/// - parameter columns: The unique key columns.
/// - parameter conflitResolution: An optional conflict resolution
/// (see https://www.sqlite.org/lang_conflict.html).
public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) {
uniqueKeyConstraints.append((columns: columns, conflictResolution: conflictResolution))
}
/// Adds a foreign key.
///
/// try db.create(table: "passport") { t in
/// t.column("issueDate", .date)
/// t.column("citizenID", .integer)
/// t.column("countryCode", .text)
/// t.foreignKey(["citizenID", "countryCode"], references: "citizenships", onDelete: .cascade)
/// }
///
/// See https://www.sqlite.org/foreignkeys.html
///
/// - parameters:
/// - columns: The foreign key columns.
/// - table: The referenced table.
/// - destinationColumns: The columns in the referenced table. If not
/// specified, the columns of the primary key of the referenced table
/// are used.
/// - deleteAction: Optional action when the referenced row is deleted.
/// - updateAction: Optional action when the referenced row is updated.
/// - deferred: If true, defines a deferred foreign key constraint.
/// See https://www.sqlite.org/foreignkeys.html#fk_deferred.
public func foreignKey(_ columns: [String], references table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) {
foreignKeyConstraints.append((columns: columns, table: table, destinationColumns: destinationColumns, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred))
}
/// Adds a CHECK constraint.
///
/// try db.create(table: "players") { t in
/// t.column("personalPhone", .text)
/// t.column("workPhone", .text)
/// let personalPhone = Column("personalPhone")
/// let workPhone = Column("workPhone")
/// t.check(personalPhone != nil || workPhone != nil)
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#ckconst
///
/// - parameter condition: The checked condition
public func check(_ condition: SQLExpressible) {
checkConstraints.append(condition.sqlExpression)
}
/// Adds a CHECK constraint.
///
/// try db.create(table: "players") { t in
/// t.column("personalPhone", .text)
/// t.column("workPhone", .text)
/// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#ckconst
///
/// - parameter sql: An SQL snippet
public func check(sql: String) {
checkConstraints.append(SQLExpressionLiteral(sql))
}
fileprivate func sql(_ db: Database) throws -> String {
var statements: [String] = []
do {
var chunks: [String] = []
chunks.append("CREATE")
if temporary {
chunks.append("TEMPORARY")
}
chunks.append("TABLE")
if ifNotExists {
chunks.append("IF NOT EXISTS")
}
chunks.append(name.quotedDatabaseIdentifier)
let primaryKeyColumns: [String]
if let (columns, _) = primaryKeyConstraint {
primaryKeyColumns = columns
} else if let index = columns.index(where: { $0.primaryKey != nil }) {
primaryKeyColumns = [columns[index].name]
} else {
// WITHOUT ROWID optimization requires a primary key. If the
// user sets withoutRowID, but does not define a primary key,
// this is undefined behavior.
//
// We thus can use the rowId column even when the withoutRowID
// flag is set ;-)
primaryKeyColumns = [Column.rowID.name]
}
do {
var items: [String] = []
try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) })
if let (columns, conflictResolution) = primaryKeyConstraint {
var chunks: [String] = []
chunks.append("PRIMARY KEY")
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
if let conflictResolution = conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
items.append(chunks.joined(separator: " "))
}
for (columns, conflictResolution) in uniqueKeyConstraints {
var chunks: [String] = []
chunks.append("UNIQUE")
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
if let conflictResolution = conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
items.append(chunks.joined(separator: " "))
}
for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints {
var chunks: [String] = []
chunks.append("FOREIGN KEY")
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
chunks.append("REFERENCES")
if let destinationColumns = destinationColumns {
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
} else if table == name {
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
} else {
let primaryKey = try db.primaryKey(table)
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
}
if let deleteAction = deleteAction {
chunks.append("ON DELETE")
chunks.append(deleteAction.rawValue)
}
if let updateAction = updateAction {
chunks.append("ON UPDATE")
chunks.append(updateAction.rawValue)
}
if deferred {
chunks.append("DEFERRABLE INITIALLY DEFERRED")
}
items.append(chunks.joined(separator: " "))
}
for checkExpression in checkConstraints {
var chunks: [String] = []
chunks.append("CHECK")
chunks.append("(" + checkExpression.sql + ")")
items.append(chunks.joined(separator: " "))
}
chunks.append("(\(items.joined(separator: ", ")))")
}
if withoutRowID {
chunks.append("WITHOUT ROWID")
}
statements.append(chunks.joined(separator: " "))
}
let indexStatements = columns
.compactMap { $0.indexDefinition(in: name) }
.map { $0.sql() }
statements.append(contentsOf: indexStatements)
return statements.joined(separator: "; ")
}
}
/// The TableAlteration class lets you alter database tables.
///
/// You don't create instances of this class. Instead, you use the Database
/// `alter(table:)` method:
///
/// try db.alter(table: "players") { t in // t is TableAlteration
/// t.add(column: ...)
/// }
///
/// See https://www.sqlite.org/lang_altertable.html
public final class TableAlteration {
private let name: String
private var addedColumns: [ColumnDefinition] = []
init(name: String) {
self.name = name
}
/// Appends a column to the table.
///
/// try db.alter(table: "players") { t in
/// t.add(column: "url", .text)
/// }
///
/// See https://www.sqlite.org/lang_altertable.html
///
/// - parameter name: the column name.
/// - parameter type: the column type.
/// - returns: An ColumnDefinition that allows you to refine the
/// column definition.
@discardableResult
public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
let column = ColumnDefinition(name: name, type: type)
addedColumns.append(column)
return column
}
fileprivate func sql(_ db: Database) throws -> String {
var statements: [String] = []
for column in addedColumns {
var chunks: [String] = []
chunks.append("ALTER TABLE")
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("ADD COLUMN")
try chunks.append(column.sql(db, tableName: name, primaryKeyColumns: nil))
let statement = chunks.joined(separator: " ")
statements.append(statement)
if let indexDefinition = column.indexDefinition(in: name) {
statements.append(indexDefinition.sql())
}
}
return statements.joined(separator: "; ")
}
}
/// The ColumnDefinition class lets you refine a table column.
///
/// You get instances of this class when you create or alter a database table:
///
/// try db.create(table: "players") { t in
/// t.column(...) // ColumnDefinition
/// }
///
/// try db.alter(table: "players") { t in
/// t.add(column: ...) // ColumnDefinition
/// }
///
/// See https://www.sqlite.org/lang_createtable.html and
/// https://www.sqlite.org/lang_altertable.html
public final class ColumnDefinition {
enum Index {
case none
case index
case unique(Database.ConflictResolution)
}
fileprivate let name: String
private let type: Database.ColumnType?
fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)?
private var index: Index = .none
private var notNullConflictResolution: Database.ConflictResolution?
private var checkConstraints: [SQLExpression] = []
private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = []
private var defaultExpression: SQLExpression?
private var collationName: String?
init(name: String, type: Database.ColumnType?) {
self.name = name
self.type = type
}
/// Adds a primary key constraint on the column.
///
/// try db.create(table: "players") { t in
/// t.column("id", .integer).primaryKey()
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#primkeyconst and
/// https://www.sqlite.org/lang_createtable.html#rowid
///
/// - parameters:
/// - conflitResolution: An optional conflict resolution
/// (see https://www.sqlite.org/lang_conflict.html).
/// - autoincrement: If true, the primary key is autoincremented.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self {
primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement)
return self
}
/// Adds a NOT NULL constraint on the column.
///
/// try db.create(table: "players") { t in
/// t.column("name", .text).notNull()
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#notnullconst
///
/// - parameter conflitResolution: An optional conflict resolution
/// (see https://www.sqlite.org/lang_conflict.html).
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
notNullConflictResolution = conflictResolution ?? .abort
return self
}
/// Adds a UNIQUE constraint on the column.
///
/// try db.create(table: "players") { t in
/// t.column("email", .text).unique()
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#uniqueconst
///
/// - parameter conflitResolution: An optional conflict resolution
/// (see https://www.sqlite.org/lang_conflict.html).
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
index = .unique(conflictResolution ?? .abort)
return self
}
/// Adds an index of the column.
///
/// try db.create(table: "players") { t in
/// t.column("email", .text).indexed()
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#uniqueconst
///
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func indexed() -> Self {
if case .none = index {
self.index = .index
}
return self
}
/// Adds a CHECK constraint on the column.
///
/// try db.create(table: "players") { t in
/// t.column("name", .text).check { length($0) > 0 }
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#ckconst
///
/// - parameter condition: A closure whose argument is an Column that
/// represents the defined column, and returns the expression to check.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func check(_ condition: (Column) -> SQLExpressible) -> Self {
checkConstraints.append(condition(Column(name)).sqlExpression)
return self
}
/// Adds a CHECK constraint on the column.
///
/// try db.create(table: "players") { t in
/// t.column("name", .text).check(sql: "LENGTH(name) > 0")
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#ckconst
///
/// - parameter sql: An SQL snippet.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func check(sql: String) -> Self {
checkConstraints.append(SQLExpressionLiteral(sql))
return self
}
/// Defines the default column value.
///
/// try db.create(table: "players") { t in
/// t.column("name", .text).defaults(to: "Anonymous")
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#dfltval
///
/// - parameter value: A DatabaseValueConvertible value.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func defaults(to value: DatabaseValueConvertible) -> Self {
defaultExpression = value.sqlExpression
return self
}
/// Defines the default column value.
///
/// try db.create(table: "players") { t in
/// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP")
/// }
///
/// See https://www.sqlite.org/lang_createtable.html#dfltval
///
/// - parameter sql: An SQL snippet.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func defaults(sql: String) -> Self {
defaultExpression = SQLExpressionLiteral(sql)
return self
}
// Defines the default column collation.
///
/// try db.create(table: "players") { t in
/// t.column("email", .text).collate(.nocase)
/// }
///
/// See https://www.sqlite.org/datatype3.html#collation
///
/// - parameter collation: An Database.CollationName.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func collate(_ collation: Database.CollationName) -> Self {
collationName = collation.rawValue
return self
}
// Defines the default column collation.
///
/// try db.create(table: "players") { t in
/// t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
/// }
///
/// See https://www.sqlite.org/datatype3.html#collation
///
/// - parameter collation: A custom DatabaseCollation.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func collate(_ collation: DatabaseCollation) -> Self {
collationName = collation.name
return self
}
/// Defines a foreign key.
///
/// try db.create(table: "books") { t in
/// t.column("authorId", .integer).references("authors", onDelete: .cascade)
/// }
///
/// See https://www.sqlite.org/foreignkeys.html
///
/// - parameters
/// - table: The referenced table.
/// - column: The column in the referenced table. If not specified, the
/// column of the primary key of the referenced table is used.
/// - deleteAction: Optional action when the referenced row is deleted.
/// - updateAction: Optional action when the referenced row is updated.
/// - deferred: If true, defines a deferred foreign key constraint.
/// See https://www.sqlite.org/foreignkeys.html#fk_deferred.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self {
foreignKeyConstraints.append((table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred))
return self
}
fileprivate func sql(_ db: Database, tableName: String, primaryKeyColumns: [String]?) throws -> String {
var chunks: [String] = []
chunks.append(name.quotedDatabaseIdentifier)
if let type = type {
chunks.append(type.rawValue)
}
if let (conflictResolution, autoincrement) = primaryKey {
chunks.append("PRIMARY KEY")
if let conflictResolution = conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
if autoincrement {
chunks.append("AUTOINCREMENT")
}
}
switch notNullConflictResolution {
case .none:
break
case .abort?:
chunks.append("NOT NULL")
case let conflictResolution?:
chunks.append("NOT NULL ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
switch index {
case .none:
break
case .unique(let conflictResolution):
switch conflictResolution {
case .abort:
chunks.append("UNIQUE")
default:
chunks.append("UNIQUE ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
case .index:
break
}
for checkConstraint in checkConstraints {
chunks.append("CHECK")
chunks.append("(" + checkConstraint.sql + ")")
}
if let defaultExpression = defaultExpression {
chunks.append("DEFAULT")
chunks.append(defaultExpression.sql)
}
if let collationName = collationName {
chunks.append("COLLATE")
chunks.append(collationName)
}
for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints {
chunks.append("REFERENCES")
if let column = column {
// explicit reference
chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))")
} else if table.lowercased() == tableName.lowercased() {
// implicit autoreference
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table).columns
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
} else {
// implicit external reference
let primaryKeyColumns = try db.primaryKey(table).columns
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
}
if let deleteAction = deleteAction {
chunks.append("ON DELETE")
chunks.append(deleteAction.rawValue)
}
if let updateAction = updateAction {
chunks.append("ON UPDATE")
chunks.append(updateAction.rawValue)
}
if deferred {
chunks.append("DEFERRABLE INITIALLY DEFERRED")
}
}
return chunks.joined(separator: " ")
}
fileprivate func indexDefinition(in table: String) -> IndexDefinition? {
switch index {
case .none: return nil
case .unique: return nil
case .index:
return IndexDefinition(
name: "\(table)_on_\(name)",
table: table,
columns: [name],
unique: false,
ifNotExists: false,
condition: nil)
}
}
}
private struct IndexDefinition {
let name: String
let table: String
let columns: [String]
let unique: Bool
let ifNotExists: Bool
let condition: SQLExpression?
func sql() -> String {
var chunks: [String] = []
chunks.append("CREATE")
if unique {
chunks.append("UNIQUE")
}
chunks.append("INDEX")
if ifNotExists {
chunks.append("IF NOT EXISTS")
}
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("ON")
chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
if let condition = condition {
chunks.append("WHERE")
chunks.append(condition.sql)
}
return chunks.joined(separator: " ")
}
}
| b48bc26071786c75cfa57af33a34aa59 | 41.002252 | 258 | 0.588825 | false | false | false | false |
PureSwift/Bluetooth | refs/heads/master | Sources/BluetoothHCI/LowEnergyPacketPayload.swift | mit | 1 | //
// LowEnergyPacketPayload.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
/// Bluetooth LE Packet Payload format
@frozen
public enum LowEnergyPacketPayload: UInt8 { // Packet_Payload
case prb29Sequence = 0x00
case repeated11110000 = 0x01
case repeated10101010 = 0x02
case prbs15Sequence = 0x03
case repeated11111111 = 0x04
case repeated00000000 = 0x05
case repeated00001111 = 0x06
case repeated01010101 = 0x07
}
| f57ab2553131c39855598d3f908ae80c | 25.761905 | 61 | 0.679715 | false | false | false | false |
bukoli/bukoli-ios | refs/heads/master | Bukoli/Classes/Controllers/BukoliPhoneDialog.swift | mit | 1 | //
// BukoliPhoneDialog.swift
// Pods
//
// Created by Utku Yıldırım on 03/10/2016.
//
//
import UIKit
class BukoliPhoneDialog: UIViewController, UITextFieldDelegate {
@IBOutlet weak var phoneNumberLabel: UITextField!
@IBOutlet weak var centerYConstraint: NSLayoutConstraint!
var bukoliMapViewController: BukoliMapViewController!
// MARK: - Actions
@IBAction func save(_ sender: AnyObject) {
// Validate Phone Number
var phoneNumber = String(phoneNumberLabel.text!.characters.filter {
return String($0).rangeOfCharacter(from: CharacterSet(charactersIn: "0123456789")) != nil
})
if (phoneNumber.characters.count < 11) {
// Error
let alert = UIAlertController(title: "Hata", message: "Girdiğiniz telefon numarası hatalıdır.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Tamam", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
// Remove first 0
phoneNumber.characters.removeFirst()
Bukoli.sharedInstance.phoneNumber = phoneNumber
self.dismiss(animated: true) {
self.bukoliMapViewController.close(sender)
}
}
@IBAction func close(_ sender: AnyObject) {
bukoliMapViewController.definesPresentationContext = true
view.endEditing(true)
dismiss(animated: true, completion: nil)
}
// MARK: - UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// TODO: Reimplement Phone Formatting
let length = textField.text!.characters.count
// Remove Char
if (range.length == 1) {
if length > range.location {
let newPosition = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
}
return true
}
if (length >= 17) {
return false
}
if range.location >= 17 {
return false
} else if range.location == 0 {
textField.insertText("0 (")
if (string == "0") {
return false
}
} else if range.location == 1 {
textField.insertText(" (")
} else if range.location == 2 {
textField.insertText("(")
} else if range.location == 6 {
textField.insertText(") ")
} else if range.location == 7 {
textField.insertText(" ")
} else if range.location == 11 {
textField.insertText(" ")
} else if range.location == 14 {
textField.insertText(" ")
}
return true
}
// MARK: - Keyboard
func keyboardWillShow(_ notification: Notification) {
if let userInfo = notification.userInfo {
let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
self.centerYConstraint.constant = -endFrame!.size.height / 2;
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
func keyboardWillHide(_ notification: Notification) {
if let userInfo = notification.userInfo {
let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
self.centerYConstraint.constant = 0;
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
}
| 94b49e46342ce146969917bce3240401 | 38.534247 | 159 | 0.608281 | false | false | false | false |
domenicosolazzo/practice-swift | refs/heads/master | CoreMotion/Retrieving Accelerometer Data/Retrieving Accelerometer Data/ViewController.swift | mit | 1 | //
// ViewController.swift
// Retrieving Accelerometer Data
//
// Created by Domenico on 21/05/15.
// License MIT
//
import UIKit
import CoreMotion
class ViewController: UIViewController {
lazy var motionManager = CMMotionManager()
override func viewDidLoad() {
super.viewDidLoad()
if motionManager.isAccelerometerAvailable{
_ = OperationQueue()
motionManager.startAccelerometerUpdates(to: OperationQueue.main) { [weak self] (data: CMAccelerometerData?, error: Error?) in
print("X = \(data?.acceleration.x)")
print("Y = \(data?.acceleration.y)")
print("Z = \(data?.acceleration.z)")
}
} else {
print("Accelerometer is not available")
}
}
}
| 533c1f8078a2350dcf461e10c815bf52 | 24.558824 | 137 | 0.547756 | false | false | false | false |
DarrenKong/firefox-ios | refs/heads/master | Client/Frontend/Browser/BrowserViewController.swift | mpl-2.0 | 1 | /* 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 Photos
import UIKit
import WebKit
import Shared
import Storage
import SnapKit
import XCGLogger
import Alamofire
import Account
import ReadingList
import MobileCoreServices
import SDWebImage
import SwiftyJSON
import Telemetry
import Sentry
private let KVOs: [KVOConstants] = [
.estimatedProgress,
.loading,
.canGoBack,
.canGoForward,
.URL,
.title,
]
private let ActionSheetTitleMaxLength = 120
private struct BrowserViewControllerUX {
fileprivate static let BackgroundColor = UIConstants.AppBackgroundColor
fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32
fileprivate static let BookmarkStarAnimationDuration: Double = 0.5
fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80
}
class BrowserViewController: UIViewController {
var homePanelController: HomePanelViewController?
var webViewContainer: UIView!
var urlBar: URLBarView!
var clipboardBarDisplayHandler: ClipboardBarDisplayHandler?
var readerModeBar: ReaderModeBarView?
var readerModeCache: ReaderModeCache
let webViewContainerToolbar = UIView()
var statusBarOverlay: UIView!
fileprivate(set) var toolbar: TabToolbar?
fileprivate var searchController: SearchViewController?
fileprivate var screenshotHelper: ScreenshotHelper!
fileprivate var homePanelIsInline = false
fileprivate var searchLoader: SearchLoader?
fileprivate let alertStackView = UIStackView() // All content that appears above the footer should be added to this view. (Find In Page/SnackBars)
fileprivate var findInPageBar: FindInPageBar?
lazy var mailtoLinkHandler: MailtoLinkHandler = MailtoLinkHandler()
lazy fileprivate var customSearchEngineButton: UIButton = {
let searchButton = UIButton()
searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: [])
searchButton.addTarget(self, action: #selector(addCustomSearchEngineForFocusedElement), for: .touchUpInside)
searchButton.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton"
return searchButton
}()
fileprivate var customSearchBarButton: UIBarButtonItem?
// popover rotation handling
fileprivate var displayedPopoverController: UIViewController?
fileprivate var updateDisplayedPopoverProperties: (() -> Void)?
var openInHelper: OpenInHelper?
// location label actions
fileprivate var pasteGoAction: AccessibleAction!
fileprivate var pasteAction: AccessibleAction!
fileprivate var copyAddressAction: AccessibleAction!
fileprivate weak var tabTrayController: TabTrayController!
let profile: Profile
let tabManager: TabManager
// These views wrap the urlbar and toolbar to provide background effects on them
var header: UIView!
var footer: UIView!
fileprivate var topTouchArea: UIButton!
let urlBarTopTabsContainer = UIView(frame: CGRect.zero)
var topTabsVisible: Bool {
return topTabsViewController != nil
}
// Backdrop used for displaying greyed background for private tabs
var webViewContainerBackdrop: UIView!
var scrollController = TabScrollingController()
fileprivate var keyboardState: KeyboardState?
var pendingToast: ButtonToast? // A toast that might be waiting for BVC to appear before displaying
// Tracking navigation items to record history types.
// TODO: weak references?
var ignoredNavigation = Set<WKNavigation>()
var typedNavigation = [WKNavigation: VisitType]()
var navigationToolbar: TabToolbarProtocol {
return toolbar ?? urlBar
}
var topTabsViewController: TopTabsViewController?
let topTabsContainer = UIView()
init(profile: Profile, tabManager: TabManager) {
self.profile = profile
self.tabManager = tabManager
self.readerModeCache = DiskReaderModeCache.sharedInstance
super.init(nibName: nil, bundle: nil)
didInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
displayedPopoverController?.dismiss(animated: true) {
self.displayedPopoverController = nil
}
if let _ = self.presentedViewController as? PhotonActionSheet {
self.presentedViewController?.dismiss(animated: true, completion: nil)
}
coordinator.animate(alongsideTransition: { context in
self.scrollController.updateMinimumZoom()
self.topTabsViewController?.scrollToCurrentTab(false, centerCell: false)
if let popover = self.displayedPopoverController {
self.updateDisplayedPopoverProperties?()
self.present(popover, animated: true, completion: nil)
}
}, completion: { _ in
self.scrollController.setMinimumZoom()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
fileprivate func didInit() {
screenshotHelper = ScreenshotHelper(controller: self)
tabManager.addDelegate(self)
tabManager.addNavigationDelegate(self)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
let isIpad = shouldShowTopTabsForTraitCollection(traitCollection)
return (isPrivate || isIpad) ? .lightContent : .default
}
func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool {
return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular
}
func shouldShowTopTabsForTraitCollection(_ newTraitCollection: UITraitCollection) -> Bool {
return newTraitCollection.verticalSizeClass == .regular && newTraitCollection.horizontalSizeClass == .regular
}
func toggleSnackBarVisibility(show: Bool) {
if show {
UIView.animate(withDuration: 0.1, animations: { self.alertStackView.isHidden = false })
} else {
alertStackView.isHidden = true
}
}
fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) {
let showToolbar = shouldShowFooterForTraitCollection(newCollection)
let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection)
urlBar.topTabsIsShowing = showTopTabs
urlBar.setShowToolbar(!showToolbar)
toolbar?.removeFromSuperview()
toolbar?.tabToolbarDelegate = nil
toolbar = nil
if showToolbar {
toolbar = TabToolbar()
footer.addSubview(toolbar!)
toolbar?.tabToolbarDelegate = self
let theme = (tabManager.selectedTab?.isPrivate ?? false) ? Theme.Private : Theme.Normal
toolbar?.applyTheme(theme)
updateTabCountUsingTabManager(self.tabManager)
}
if showTopTabs {
if topTabsViewController == nil {
let topTabsViewController = TopTabsViewController(tabManager: tabManager)
topTabsViewController.delegate = self
addChildViewController(topTabsViewController)
topTabsViewController.view.frame = topTabsContainer.frame
topTabsContainer.addSubview(topTabsViewController.view)
topTabsViewController.view.snp.makeConstraints { make in
make.edges.equalTo(topTabsContainer)
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
self.topTabsViewController = topTabsViewController
}
topTabsContainer.snp.updateConstraints { make in
make.height.equalTo(TopTabsUX.TopTabsViewHeight)
}
} else {
topTabsContainer.snp.updateConstraints { make in
make.height.equalTo(0)
}
topTabsViewController?.view.removeFromSuperview()
topTabsViewController?.removeFromParentViewController()
topTabsViewController = nil
}
view.setNeedsUpdateConstraints()
if let home = homePanelController {
home.view.setNeedsUpdateConstraints()
}
if let tab = tabManager.selectedTab,
let webView = tab.webView {
updateURLBarDisplayURL(tab)
navigationToolbar.updateBackStatus(webView.canGoBack)
navigationToolbar.updateForwardStatus(webView.canGoForward)
navigationToolbar.updateReloadStatus(tab.loading)
}
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
// During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to
// set things up. Make sure to only update the toolbar state if the view is ready for it.
if isViewLoaded {
updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator)
}
displayedPopoverController?.dismiss(animated: true, completion: nil)
coordinator.animate(alongsideTransition: { context in
self.scrollController.showToolbars(animated: false)
if self.isViewLoaded {
self.statusBarOverlay.backgroundColor = self.shouldShowTopTabsForTraitCollection(self.traitCollection) ? UIColor.Defaults.Grey80 : self.urlBar.backgroundColor
self.setNeedsStatusBarAppearanceUpdate()
}
}, completion: nil)
}
func SELappDidEnterBackgroundNotification() {
displayedPopoverController?.dismiss(animated: false) {
self.displayedPopoverController = nil
}
}
func SELtappedTopArea() {
scrollController.showToolbars(animated: true)
}
func SELappWillResignActiveNotification() {
// Dismiss any popovers that might be visible
displayedPopoverController?.dismiss(animated: false) {
self.displayedPopoverController = nil
}
// If we are displying a private tab, hide any elements in the tab that we wouldn't want shown
// when the app is in the home switcher
guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else {
return
}
webViewContainerBackdrop.alpha = 1
webViewContainer.alpha = 0
urlBar.locationContainer.alpha = 0
topTabsViewController?.switchForegroundStatus(isInForeground: false)
presentedViewController?.popoverPresentationController?.containerView?.alpha = 0
presentedViewController?.view.alpha = 0
}
func SELappDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
self.webViewContainer.alpha = 1
self.urlBar.locationContainer.alpha = 1
self.topTabsViewController?.switchForegroundStatus(isInForeground: true)
self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1
self.presentedViewController?.view.alpha = 1
self.view.backgroundColor = UIColor.clear
}, completion: { _ in
self.webViewContainerBackdrop.alpha = 0
})
// Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background)
scrollController.showToolbars(animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(SELappWillResignActiveNotification), name: .UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SELappDidBecomeActiveNotification), name: .UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SELappDidEnterBackgroundNotification), name: .UIApplicationDidEnterBackground, object: nil)
KeyboardHelper.defaultHelper.addDelegate(self)
webViewContainerBackdrop = UIView()
webViewContainerBackdrop.backgroundColor = UIColor.gray
webViewContainerBackdrop.alpha = 0
view.addSubview(webViewContainerBackdrop)
webViewContainer = UIView()
webViewContainer.addSubview(webViewContainerToolbar)
view.addSubview(webViewContainer)
// Temporary work around for covering the non-clipped web view content
statusBarOverlay = UIView()
view.addSubview(statusBarOverlay)
topTouchArea = UIButton()
topTouchArea.isAccessibilityElement = false
topTouchArea.addTarget(self, action: #selector(SELtappedTopArea), for: .touchUpInside)
view.addSubview(topTouchArea)
// Setup the URL bar, wrapped in a view to get transparency effect
urlBar = URLBarView()
urlBar.translatesAutoresizingMaskIntoConstraints = false
urlBar.delegate = self
urlBar.tabToolbarDelegate = self
header = urlBarTopTabsContainer
urlBarTopTabsContainer.addSubview(urlBar)
urlBarTopTabsContainer.addSubview(topTabsContainer)
view.addSubview(header)
// UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC
pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.general.string {
self.urlBar(self.urlBar, didSubmitText: pasteboardContents)
return true
}
return false
})
pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.general.string {
// Enter overlay mode and make the search controller appear.
self.urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true)
return true
}
return false
})
copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in
if let url = self.urlBar.currentURL {
UIPasteboard.general.url = url as URL
}
return true
})
view.addSubview(alertStackView)
footer = UIView()
view.addSubview(footer)
alertStackView.axis = .vertical
alertStackView.alignment = .center
if AppConstants.MOZ_CLIPBOARD_BAR {
clipboardBarDisplayHandler = ClipboardBarDisplayHandler(prefs: profile.prefs, tabManager: tabManager)
clipboardBarDisplayHandler?.delegate = self
}
scrollController.urlBar = urlBar
scrollController.header = header
scrollController.footer = footer
scrollController.snackBars = alertStackView
scrollController.webViewContainerToolbar = webViewContainerToolbar
self.updateToolbarStateForTraitCollection(self.traitCollection)
setupConstraints()
// Setup UIDropInteraction to handle dragging and dropping
// links into the view from other apps.
if #available(iOS 11, *) {
let dropInteraction = UIDropInteraction(delegate: self)
view.addInteraction(dropInteraction)
}
}
fileprivate func setupConstraints() {
topTabsContainer.snp.makeConstraints { make in
make.leading.trailing.equalTo(self.header)
make.top.equalTo(urlBarTopTabsContainer)
}
urlBar.snp.makeConstraints { make in
make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer)
make.height.equalTo(UIConstants.TopToolbarHeight)
make.top.equalTo(topTabsContainer.snp.bottom)
}
header.snp.makeConstraints { make in
scrollController.headerTopConstraint = make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint
make.left.right.equalTo(self.view)
}
webViewContainerBackdrop.snp.makeConstraints { make in
make.edges.equalTo(webViewContainer)
}
webViewContainerToolbar.snp.makeConstraints { make in
make.left.right.top.equalTo(webViewContainer)
make.height.equalTo(0)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
statusBarOverlay.snp.remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(self.topLayoutGuide.length)
}
}
override var canBecomeFirstResponder: Bool {
return true
}
override func becomeFirstResponder() -> Bool {
// Make the web view the first responder so that it can show the selection menu.
return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false
}
func loadQueuedTabs(receivedURLs: [URL]? = nil) {
// Chain off of a trivial deferred in order to run on the background queue.
succeed().upon() { res in
self.dequeueQueuedTabs(receivedURLs: receivedURLs ?? [])
}
}
fileprivate func dequeueQueuedTabs(receivedURLs: [URL]) {
assert(!Thread.current.isMainThread, "This must be called in the background.")
self.profile.queue.getQueuedTabs() >>== { cursor in
// This assumes that the DB returns rows in some kind of sane order.
// It does in practice, so WFM.
if cursor.count > 0 {
// Filter out any tabs received by a push notification to prevent dupes.
let urls = cursor.flatMap { $0?.url.asURL }.filter { !receivedURLs.contains($0) }
if !urls.isEmpty {
DispatchQueue.main.async {
self.tabManager.addTabsForURLs(urls, zombie: false)
}
}
// Clear *after* making an attempt to open. We're making a bet that
// it's better to run the risk of perhaps opening twice on a crash,
// rather than losing data.
self.profile.queue.clearQueuedTabs()
}
// Then, open any received URLs from push notifications.
if !receivedURLs.isEmpty {
DispatchQueue.main.async {
let unopenedReceivedURLs = receivedURLs.filter { self.tabManager.getTabForURL($0) == nil }
self.tabManager.addTabsForURLs(unopenedReceivedURLs, zombie: false)
if let lastURL = receivedURLs.last, let tab = self.tabManager.getTabForURL(lastURL) {
self.tabManager.selectTab(tab)
}
}
}
}
}
// Because crashedLastLaunch is sticky, it does not get reset, we need to remember its
// value so that we do not keep asking the user to restore their tabs.
var displayedRestoreTabsAlert = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does
// not flash before we present. This change of alpha also participates in the animation when
// the intro view is dismissed.
if UIDevice.current.userInterfaceIdiom == .phone {
self.view.alpha = (profile.prefs.intForKey(PrefsKeys.IntroSeen) != nil) ? 1.0 : 0.0
}
if !displayedRestoreTabsAlert && !cleanlyBackgrounded() && crashedLastLaunch() {
displayedRestoreTabsAlert = true
showRestoreTabsAlert()
} else {
tabManager.restoreTabs()
}
updateTabCountUsingTabManager(tabManager, animated: false)
clipboardBarDisplayHandler?.checkIfShouldDisplayBar()
}
fileprivate func crashedLastLaunch() -> Bool {
return Sentry.crashedLastLaunch
}
fileprivate func cleanlyBackgrounded() -> Bool {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return false
}
return appDelegate.applicationCleanlyBackgrounded
}
fileprivate func showRestoreTabsAlert() {
guard canRestoreTabs() else {
self.tabManager.addTabAndSelect()
return
}
let alert = UIAlertController.restoreTabsAlert(
okayCallback: { _ in
self.tabManager.restoreTabs()
},
noCallback: { _ in
self.tabManager.addTabAndSelect()
}
)
self.present(alert, animated: true, completion: nil)
}
fileprivate func canRestoreTabs() -> Bool {
guard let tabsToRestore = TabManager.tabsToRestore() else { return false }
return !tabsToRestore.isEmpty
}
override func viewDidAppear(_ animated: Bool) {
presentIntroViewController()
self.webViewContainerToolbar.isHidden = false
screenshotHelper.viewIsVisible = true
screenshotHelper.takePendingScreenshots(tabManager.tabs)
super.viewDidAppear(animated)
if shouldShowWhatsNewTab() {
// Only display if the SUMO topic has been configured in the Info.plist (present and not empty)
if let whatsNewTopic = AppInfo.whatsNewTopic, whatsNewTopic != "" {
if let whatsNewURL = SupportUtils.URLForTopic(whatsNewTopic) {
self.openURLInNewTab(whatsNewURL, isPrivileged: false)
profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey)
}
}
}
if let toast = self.pendingToast {
self.pendingToast = nil
show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay)
}
showQueuedAlertIfAvailable()
}
// THe logic for shouldShowWhatsNewTab is as follows: If we do not have the LatestAppVersionProfileKey in
// the profile, that means that this is a fresh install and we do not show the What's New. If we do have
// that value, we compare it to the major version of the running app. If it is different then this is an
// upgrade, downgrades are not possible, so we can show the What's New page.
fileprivate func shouldShowWhatsNewTab() -> Bool {
guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else {
return false // Clean install, never show What's New
}
return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity()
}
fileprivate func showQueuedAlertIfAvailable() {
if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() {
let alertController = queuedAlertInfo.alertController()
alertController.delegate = self
present(alertController, animated: true, completion: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
screenshotHelper.viewIsVisible = false
super.viewWillDisappear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
func resetBrowserChrome() {
// animate and reset transform for tab chrome
urlBar.updateAlphaForSubviews(1)
footer.alpha = 1
[header, footer, readerModeBar].forEach { view in
view?.transform = .identity
}
statusBarOverlay.isHidden = false
}
override func updateViewConstraints() {
super.updateViewConstraints()
topTouchArea.snp.remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight)
}
readerModeBar?.snp.remakeConstraints { make in
make.top.equalTo(self.header.snp.bottom)
make.height.equalTo(UIConstants.ToolbarHeight)
make.leading.trailing.equalTo(self.view)
}
webViewContainer.snp.remakeConstraints { make in
make.left.right.equalTo(self.view)
if let readerModeBarBottom = readerModeBar?.snp.bottom {
make.top.equalTo(readerModeBarBottom)
} else {
make.top.equalTo(self.header.snp.bottom)
}
let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight
if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight)
} else {
make.bottom.equalTo(self.view).offset(-findInPageHeight)
}
}
// Setup the bottom toolbar
toolbar?.snp.remakeConstraints { make in
make.edges.equalTo(self.footer)
make.height.equalTo(UIConstants.BottomToolbarHeight)
}
footer.snp.remakeConstraints { make in
scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint
make.leading.trailing.equalTo(self.view)
}
urlBar.setNeedsUpdateConstraints()
// Remake constraints even if we're already showing the home controller.
// The home controller may change sizes if we tap the URL bar while on about:home.
homePanelController?.view.snp.remakeConstraints { make in
make.top.equalTo(self.urlBar.snp.bottom)
make.left.right.equalTo(self.view)
if self.homePanelIsInline {
make.bottom.equalTo(self.toolbar?.snp.top ?? self.view.snp.bottom)
} else {
make.bottom.equalTo(self.view.snp.bottom)
}
}
alertStackView.snp.remakeConstraints { make in
make.centerX.equalTo(self.view)
make.width.equalTo(self.view.snp.width)
if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 {
make.bottom.equalTo(self.view).offset(-keyboardHeight)
} else if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp.top)
} else {
make.bottom.equalTo(self.view)
}
}
}
fileprivate func showHomePanelController(inline: Bool) {
homePanelIsInline = inline
if homePanelController == nil {
let homePanelController = HomePanelViewController()
homePanelController.profile = profile
homePanelController.delegate = self
homePanelController.url = tabManager.selectedTab?.url?.displayURL
homePanelController.view.alpha = 0
self.homePanelController = homePanelController
addChildViewController(homePanelController)
view.addSubview(homePanelController.view)
homePanelController.didMove(toParentViewController: self)
}
guard let homePanelController = self.homePanelController else {
assertionFailure("homePanelController is still nil after assignment.")
return
}
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
homePanelController.applyTheme(isPrivate ? Theme.Private : Theme.Normal)
let panelNumber = tabManager.selectedTab?.url?.fragment
// splitting this out to see if we can get better crash reports when this has a problem
var newSelectedButtonIndex = 0
if let numberArray = panelNumber?.components(separatedBy: "=") {
if let last = numberArray.last, let lastInt = Int(last) {
newSelectedButtonIndex = lastInt
}
}
homePanelController.selectedPanel = HomePanelType(rawValue: newSelectedButtonIndex)
// We have to run this animation, even if the view is already showing because there may be a hide animation running
// and we want to be sure to override its results.
UIView.animate(withDuration: 0.2, animations: { () -> Void in
homePanelController.view.alpha = 1
}, completion: { finished in
if finished {
self.webViewContainer.accessibilityElementsHidden = true
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
}
})
view.setNeedsUpdateConstraints()
}
fileprivate func hideHomePanelController() {
if let controller = homePanelController {
self.homePanelController = nil
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in
controller.view.alpha = 0
}, completion: { _ in
controller.willMove(toParentViewController: nil)
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.webViewContainer.accessibilityElementsHidden = false
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// Refresh the reading view toolbar since the article record may have changed
if let readerMode = self.tabManager.selectedTab?.getContentScript(name: ReaderMode.name()) as? ReaderMode, readerMode.state == .active {
self.showReaderModeBar(animated: false)
}
})
}
}
fileprivate func updateInContentHomePanel(_ url: URL?) {
if !urlBar.inOverlayMode {
guard let url = url else {
hideHomePanelController()
return
}
if url.isAboutHomeURL {
showHomePanelController(inline: true)
} else if !url.isLocalUtility || url.isReaderModeURL {
hideHomePanelController()
}
}
}
fileprivate func showSearchController() {
if searchController != nil {
return
}
let isPrivate = tabManager.selectedTab?.isPrivate ?? false
searchController = SearchViewController(isPrivate: isPrivate)
searchController!.searchEngines = profile.searchEngines
searchController!.searchDelegate = self
searchController!.profile = self.profile
searchLoader = SearchLoader(profile: profile, urlBar: urlBar)
searchLoader?.addListener(searchController!)
addChildViewController(searchController!)
view.addSubview(searchController!.view)
searchController!.view.snp.makeConstraints { make in
make.top.equalTo(self.urlBar.snp.bottom)
make.left.right.bottom.equalTo(self.view)
return
}
homePanelController?.view?.isHidden = true
searchController!.didMove(toParentViewController: self)
}
fileprivate func hideSearchController() {
if let searchController = searchController {
searchController.willMove(toParentViewController: nil)
searchController.view.removeFromSuperview()
searchController.removeFromParentViewController()
self.searchController = nil
homePanelController?.view?.isHidden = false
searchLoader = nil
}
}
func finishEditingAndSubmit(_ url: URL, visitType: VisitType) {
urlBar.currentURL = url
urlBar.leaveOverlayMode()
guard let tab = tabManager.selectedTab else {
return
}
if let webView = tab.webView {
resetSpoofedUserAgentIfRequired(webView, newURL: url)
}
if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) {
self.recordNavigationInTab(tab, navigation: nav, visitType: visitType)
}
}
func addBookmark(_ tabState: TabState) {
guard let url = tabState.url else { return }
let absoluteString = url.absoluteString
let shareItem = ShareItem(url: absoluteString, title: tabState.title, favicon: tabState.favicon)
_ = profile.bookmarks.shareItem(shareItem)
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark,
withUserData: userData,
toApplication: UIApplication.shared)
}
override func accessibilityPerformEscape() -> Bool {
if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
return true
} else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack {
selectedTab.goBack()
return true
}
return false
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
let webView = object as! WKWebView
guard let kp = keyPath, let path = KVOConstants(rawValue: kp) else {
assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
return
}
switch path {
case .estimatedProgress:
guard webView == tabManager.selectedTab?.webView,
let progress = change?[.newKey] as? Float else { break }
if !(webView.url?.isLocalUtility ?? false) {
urlBar.updateProgressBar(progress)
} else {
urlBar.hideProgressBar()
}
case .loading:
guard let loading = change?[.newKey] as? Bool else { break }
if webView == tabManager.selectedTab?.webView {
navigationToolbar.updateReloadStatus(loading)
}
if !loading {
runScriptsOnWebView(webView)
}
case .URL:
guard let tab = tabManager[webView] else { break }
// To prevent spoofing, only change the URL immediately if the new URL is on
// the same origin as the current URL. Otherwise, do nothing and wait for
// didCommitNavigation to confirm the page load.
if tab.url?.origin == webView.url?.origin {
tab.url = webView.url
if tab === tabManager.selectedTab && !tab.restoring {
updateUIForReaderHomeStateForTab(tab)
}
}
case .title:
guard let tab = tabManager[webView] else { break }
// Ensure that the tab title *actually* changed to prevent repeated calls
// to navigateInTab(tab:).
guard let title = tab.title else { break }
if !title.isEmpty && title != tab.lastTitle {
navigateInTab(tab: tab)
}
case .canGoBack:
guard webView == tabManager.selectedTab?.webView,
let canGoBack = change?[.newKey] as? Bool else { break }
navigationToolbar.updateBackStatus(canGoBack)
case .canGoForward:
guard webView == tabManager.selectedTab?.webView,
let canGoForward = change?[.newKey] as? Bool else { break }
navigationToolbar.updateForwardStatus(canGoForward)
default:
assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")")
}
}
fileprivate func runScriptsOnWebView(_ webView: WKWebView) {
guard let url = webView.url, url.isWebPage(), !url.isLocal else {
return
}
webView.evaluateJavaScript("__firefox__.metadata && __firefox__.metadata.extractMetadata()", completionHandler: nil)
if #available(iOS 11, *) {
if NoImageModeHelper.isActivated(profile.prefs) {
webView.evaluateJavaScript("__firefox__.NoImageMode.setEnabled(true)", completionHandler: nil)
}
}
}
func updateUIForReaderHomeStateForTab(_ tab: Tab) {
updateURLBarDisplayURL(tab)
scrollController.showToolbars(animated: false)
if let url = tab.url {
if url.isReaderModeURL {
showReaderModeBar(animated: false)
NotificationCenter.default.addObserver(self, selector: #selector(SELDynamicFontChanged), name: .DynamicFontChanged, object: nil)
} else {
hideReaderModeBar(animated: false)
NotificationCenter.default.removeObserver(self, name: .DynamicFontChanged, object: nil)
}
updateInContentHomePanel(url as URL)
}
}
/// Updates the URL bar text and button states.
/// Call this whenever the page URL changes.
fileprivate func updateURLBarDisplayURL(_ tab: Tab) {
urlBar.currentURL = tab.url?.displayURL
let isPage = tab.url?.displayURL?.isWebPage() ?? false
navigationToolbar.updatePageStatus(isPage)
}
// MARK: Opening New Tabs
func switchToPrivacyMode(isPrivate: Bool ) {
// applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode)
let tabTrayController = self.tabTrayController ?? TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self)
if tabTrayController.privateMode != isPrivate {
tabTrayController.changePrivacyMode(isPrivate)
}
self.tabTrayController = tabTrayController
}
func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false, isPrivileged: Bool) {
popToBVC()
if let tab = tabManager.getTabForURL(url) {
tabManager.selectTab(tab)
} else {
openURLInNewTab(url, isPrivate: isPrivate, isPrivileged: isPrivileged)
}
}
func openURLInNewTab(_ url: URL?, isPrivate: Bool = false, isPrivileged: Bool) {
if let selectedTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(selectedTab)
}
let request: URLRequest?
if let url = url {
request = isPrivileged ? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url)
} else {
request = nil
}
switchToPrivacyMode(isPrivate: isPrivate)
_ = tabManager.addTabAndSelect(request, isPrivate: isPrivate)
if url == nil && NewTabAccessors.getNewTabPage(profile.prefs) == .blankPage {
urlBar.tabLocationViewDidTapLocation(urlBar.locationView)
}
}
func openBlankNewTab(focusLocationField: Bool, isPrivate: Bool = false) {
popToBVC()
openURLInNewTab(nil, isPrivate: isPrivate, isPrivileged: true)
if focusLocationField {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {
// Without a delay, the text field fails to become first responder
self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView)
}
}
}
fileprivate func popToBVC() {
guard let currentViewController = navigationController?.topViewController else {
return
}
currentViewController.dismiss(animated: true, completion: nil)
if currentViewController != self {
_ = self.navigationController?.popViewController(animated: true)
} else if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
}
}
// MARK: User Agent Spoofing
func resetSpoofedUserAgentIfRequired(_ webView: WKWebView, newURL: URL) {
// Reset the UA when a different domain is being loaded
if webView.url?.host != newURL.host {
webView.customUserAgent = nil
}
}
func restoreSpoofedUserAgentIfRequired(_ webView: WKWebView, newRequest: URLRequest) {
// Restore any non-default UA from the request's header
let ua = newRequest.value(forHTTPHeaderField: "User-Agent")
webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil
}
fileprivate func presentActivityViewController(_ url: URL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) {
let helper = ShareExtensionHelper(url: url, tab: tab)
let controller = helper.createActivityViewController({ [unowned self] completed, _ in
// After dismissing, check to see if there were any prompts we queued up
self.showQueuedAlertIfAvailable()
// Usually the popover delegate would handle nil'ing out the references we have to it
// on the BVC when displaying as a popover but the delegate method doesn't seem to be
// invoked on iOS 10. See Bug 1297768 for additional details.
self.displayedPopoverController = nil
self.updateDisplayedPopoverProperties = nil
})
if let popoverPresentationController = controller.popoverPresentationController {
popoverPresentationController.sourceView = sourceView
popoverPresentationController.sourceRect = sourceRect
popoverPresentationController.permittedArrowDirections = arrowDirection
popoverPresentationController.delegate = self
}
present(controller, animated: true, completion: nil)
LeanPlumClient.shared.track(event: .userSharedWebpage)
}
func updateFindInPageVisibility(visible: Bool) {
if visible {
if findInPageBar == nil {
let findInPageBar = FindInPageBar()
self.findInPageBar = findInPageBar
findInPageBar.delegate = self
alertStackView.addArrangedSubview(findInPageBar)
findInPageBar.snp.makeConstraints { make in
make.height.equalTo(UIConstants.ToolbarHeight)
make.leading.trailing.equalTo(alertStackView)
}
updateViewConstraints()
// We make the find-in-page bar the first responder below, causing the keyboard delegates
// to fire. This, in turn, will animate the Find in Page container since we use the same
// delegate to slide the bar up and down with the keyboard. We don't want to animate the
// constraints added above, however, so force a layout now to prevent these constraints
// from being lumped in with the keyboard animation.
findInPageBar.layoutIfNeeded()
}
self.findInPageBar?.becomeFirstResponder()
} else if let findInPageBar = self.findInPageBar {
findInPageBar.endEditing(true)
guard let webView = tabManager.selectedTab?.webView else { return }
webView.evaluateJavaScript("__firefox__.findDone()", completionHandler: nil)
findInPageBar.removeFromSuperview()
self.findInPageBar = nil
updateViewConstraints()
}
}
@objc fileprivate func openSettings() {
assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread")
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
settingsTableViewController.settingsDelegate = self
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = .formSheet
self.present(controller, animated: true, completion: nil)
}
fileprivate func postLocationChangeNotificationForTab(_ tab: Tab, navigation: WKNavigation?) {
let notificationCenter = NotificationCenter.default
var info = [AnyHashable: Any]()
info["url"] = tab.url?.displayURL
info["title"] = tab.title
if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue {
info["visitType"] = visitType
}
info["isPrivate"] = tab.isPrivate
notificationCenter.post(name: .OnLocationChange, object: self, userInfo: info)
}
func navigateInTab(tab: Tab, to navigation: WKNavigation? = nil) {
tabManager.expireSnackbars()
guard let webView = tab.webView else {
print("Cannot navigate in tab without a webView")
return
}
if let url = webView.url, !url.isErrorPageURL && !url.isAboutHomeURL {
tab.lastExecutedTime = Date.now()
postLocationChangeNotificationForTab(tab, navigation: navigation)
// Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore
// because that event wil not always fire due to unreliable page caching. This will either let us know that
// the currently loaded page can be turned into reading mode or if the page already is in reading mode. We
// ignore the result because we are being called back asynchronous when the readermode status changes.
webView.evaluateJavaScript("\(ReaderModeNamespace).checkReadability()", completionHandler: nil)
// Re-run additional scripts in webView to extract updated favicons and metadata.
runScriptsOnWebView(webView)
}
if tab === tabManager.selectedTab {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// must be followed by LayoutChanged, as ScreenChanged will make VoiceOver
// cursor land on the correct initial element, but if not followed by LayoutChanged,
// VoiceOver will sometimes be stuck on the element, not allowing user to move
// forward/backward. Strange, but LayoutChanged fixes that.
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
} else if let webView = tab.webView {
// To Screenshot a tab that is hidden we must add the webView,
// then wait enough time for the webview to render.
view.insertSubview(webView, at: 0)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
self.screenshotHelper.takeScreenshot(tab)
if webView.superview == self.view {
webView.removeFromSuperview()
}
}
}
// Remember whether or not a desktop site was requested
tab.desktopSite = webView.customUserAgent?.isEmpty == false
}
// MARK: open in helper utils
func addViewForOpenInHelper(_ openInHelper: OpenInHelper) {
guard let view = openInHelper.openInView else { return }
webViewContainerToolbar.addSubview(view)
webViewContainerToolbar.snp.updateConstraints { make in
make.height.equalTo(OpenInViewUX.ViewHeight)
}
view.snp.makeConstraints { make in
make.edges.equalTo(webViewContainerToolbar)
}
self.openInHelper = openInHelper
}
func removeOpenInView() {
guard let _ = self.openInHelper else { return }
webViewContainerToolbar.subviews.forEach { $0.removeFromSuperview() }
webViewContainerToolbar.snp.updateConstraints { make in
make.height.equalTo(0)
}
self.openInHelper = nil
}
}
extension BrowserViewController: ClipboardBarDisplayHandlerDelegate {
func shouldDisplay(clipboardBar bar: ButtonToast) {
show(buttonToast: bar, duration: ClipboardBarToastUX.ToastDelay)
}
}
extension BrowserViewController: QRCodeViewControllerDelegate {
func didScanQRCodeWithURL(_ url: URL) {
openBlankNewTab(focusLocationField: false)
finishEditingAndSubmit(url, visitType: VisitType.typed)
UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeURL)
}
func didScanQRCodeWithText(_ text: String) {
openBlankNewTab(focusLocationField: false)
submitSearchText(text)
UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeText)
}
}
extension BrowserViewController: SettingsDelegate {
func settingsOpenURLInNewTab(_ url: URL) {
self.openURLInNewTab(url, isPrivileged: false)
}
}
extension BrowserViewController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
self.dismiss(animated: animated, completion: nil)
}
}
/**
* History visit management.
* TODO: this should be expanded to track various visit types; see Bug 1166084.
*/
extension BrowserViewController {
func ignoreNavigationInTab(_ tab: Tab, navigation: WKNavigation) {
self.ignoredNavigation.insert(navigation)
}
func recordNavigationInTab(_ tab: Tab, navigation: WKNavigation, visitType: VisitType) {
self.typedNavigation[navigation] = visitType
}
/**
* Untrack and do the right thing.
*/
func getVisitTypeForTab(_ tab: Tab, navigation: WKNavigation?) -> VisitType? {
guard let navigation = navigation else {
// See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390
return VisitType.link
}
if let _ = self.ignoredNavigation.remove(navigation) {
return nil
}
return self.typedNavigation.removeValue(forKey: navigation) ?? VisitType.link
}
}
extension BrowserViewController: URLBarDelegate {
func showTabTray() {
webViewContainerToolbar.isHidden = true
updateFindInPageVisibility(visible: false)
let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self)
if let tab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(tab)
}
navigationController?.pushViewController(tabTrayController, animated: true)
self.tabTrayController = tabTrayController
}
func urlBarDidPressReload(_ urlBar: URLBarView) {
tabManager.selectedTab?.reload()
}
func urlBarDidPressQRButton(_ urlBar: URLBarView) {
let qrCodeViewController = QRCodeViewController()
qrCodeViewController.qrCodeDelegate = self
let controller = QRCodeNavigationController(rootViewController: qrCodeViewController)
self.present(controller, animated: true, completion: nil)
}
func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton) {
let actionMenuPresenter: (URL, Tab, UIView, UIPopoverArrowDirection) -> Void = { (url, tab, view, _) in
self.presentActivityViewController(url, tab: tab, sourceView: view, sourceRect: view.bounds, arrowDirection: .up)
}
let findInPageAction = {
self.updateFindInPageVisibility(visible: true)
}
let successCallback: (String) -> Void = { (successMessage) in
SimpleToast().showAlertWithText(successMessage, bottomContainer: self.webViewContainer)
}
guard let tab = tabManager.selectedTab, let urlString = tab.url?.absoluteString else { return }
fetchBookmarkStatus(for: urlString).uponQueue(.main) {
let isBookmarked = $0.successValue ?? false
let pageActions = self.getTabActions(tab: tab, buttonView: button, presentShareMenu: actionMenuPresenter,
findInPage: findInPageAction, presentableVC: self, isBookmarked: isBookmarked,
success: successCallback)
self.presentSheetWith(actions: pageActions, on: self, from: button)
}
}
func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton) {
guard let tab = tabManager.selectedTab else { return }
guard let url = tab.canonicalURL?.displayURL else { return }
presentActivityViewController(url, tab: tab, sourceView: button, sourceRect: button.bounds, arrowDirection: .up)
}
func urlBarDidPressStop(_ urlBar: URLBarView) {
tabManager.selectedTab?.stop()
}
func urlBarDidPressTabs(_ urlBar: URLBarView) {
showTabTray()
}
func urlBarDidPressReaderMode(_ urlBar: URLBarView) {
if let tab = tabManager.selectedTab {
if let readerMode = tab.getContentScript(name: "ReaderMode") as? ReaderMode {
switch readerMode.state {
case .available:
enableReaderMode()
UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeOpenButton)
LeanPlumClient.shared.track(event: .useReaderView)
case .active:
disableReaderMode()
UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeCloseButton)
case .unavailable:
break
}
}
}
}
func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool {
guard let tab = tabManager.selectedTab,
let url = tab.url?.displayURL,
let result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name)
else {
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed."))
return false
}
switch result {
case .success:
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action."))
// TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback?
case .failure(let error):
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it’s already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures."))
print("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)")
}
return true
}
func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] {
if UIPasteboard.general.string != nil {
return [pasteGoAction, pasteAction, copyAddressAction]
} else {
return [copyAddressAction]
}
}
func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool) {
// use the initial value for the URL so we can do proper pattern matching with search URLs
var searchURL = self.tabManager.selectedTab?.currentInitialURL
if searchURL?.isErrorPageURL ?? true {
searchURL = url
}
if let query = profile.searchEngines.queryForSearchURL(searchURL as URL?) {
return (query, true)
} else {
return (url?.absoluteString, false)
}
}
func urlBarDidLongPressLocation(_ urlBar: URLBarView) {
let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
for action in locationActionsForURLBar(urlBar) {
longPressAlertController.addAction(action.alertAction(style: .default))
}
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: { (alert: UIAlertAction) -> Void in
})
longPressAlertController.addAction(cancelAction)
let setupPopover = { [unowned self] in
if let popoverPresentationController = longPressAlertController.popoverPresentationController {
popoverPresentationController.sourceView = urlBar
popoverPresentationController.sourceRect = urlBar.frame
popoverPresentationController.permittedArrowDirections = .any
popoverPresentationController.delegate = self
}
}
setupPopover()
if longPressAlertController.popoverPresentationController != nil {
displayedPopoverController = longPressAlertController
updateDisplayedPopoverProperties = setupPopover
}
self.present(longPressAlertController, animated: true, completion: nil)
}
func urlBarDidPressScrollToTop(_ urlBar: URLBarView) {
if let selectedTab = tabManager.selectedTab {
// Only scroll to top if we are not showing the home view controller
if homePanelController == nil {
selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true)
}
}
}
func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? {
return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction }
}
func urlBar(_ urlBar: URLBarView, didEnterText text: String) {
if text.isEmpty {
hideSearchController()
} else {
showSearchController()
searchController?.searchQuery = text
searchLoader?.query = text
}
}
func urlBar(_ urlBar: URLBarView, didSubmitText text: String) {
if let fixupURL = URIFixup.getURL(text) {
// The user entered a URL, so use it.
finishEditingAndSubmit(fixupURL, visitType: VisitType.typed)
return
}
// We couldn't build a URL, so check for a matching search keyword.
let trimmedText = text.trimmingCharacters(in: .whitespaces)
guard let possibleKeywordQuerySeparatorSpace = trimmedText.index(of: " ") else {
submitSearchText(text)
return
}
let possibleKeyword = trimmedText.substring(to: possibleKeywordQuerySeparatorSpace)
let possibleQuery = trimmedText.substring(from: trimmedText.index(after: possibleKeywordQuerySeparatorSpace))
profile.bookmarks.getURLForKeywordSearch(possibleKeyword).uponQueue(.main) { result in
if var urlString = result.successValue,
let escapedQuery = possibleQuery.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed),
let range = urlString.range(of: "%s") {
urlString.replaceSubrange(range, with: escapedQuery)
if let url = URL(string: urlString) {
self.finishEditingAndSubmit(url, visitType: VisitType.typed)
return
}
}
self.submitSearchText(text)
}
}
fileprivate func submitSearchText(_ text: String) {
let engine = profile.searchEngines.defaultEngine
if let searchURL = engine.searchURLForQuery(text) {
// We couldn't find a matching search keyword, so do a search query.
Telemetry.default.recordSearch(location: .actionBar, searchEngine: engine.engineID ?? "other")
finishEditingAndSubmit(searchURL, visitType: VisitType.typed)
} else {
// We still don't have a valid URL, so something is broken. Give up.
print("Error handling URL entry: \"\(text)\".")
assertionFailure("Couldn't generate search URL: \(text)")
}
}
func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) {
guard let profile = profile as? BrowserProfile else {
return
}
if .blankPage == NewTabAccessors.getNewTabPage(profile.prefs) {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
} else {
if let toast = clipboardBarDisplayHandler?.clipboardToast {
toast.removeFromSuperview()
}
showHomePanelController(inline: false)
}
LeanPlumClient.shared.track(event: .interactWithURLBar)
}
func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) {
hideSearchController()
updateInContentHomePanel(tabManager.selectedTab?.url as URL?)
}
}
extension BrowserViewController: TabToolbarDelegate, PhotonActionSheetProtocol {
func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goBack()
}
func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
showBackForwardList()
}
func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.reload()
}
func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
guard let tab = tabManager.selectedTab, tab.webView?.url != nil && (tab.getContentScript(name: ReaderMode.name()) as? ReaderMode)?.state != .active else {
return
}
let toggleActionTitle: String
if tab.desktopSite {
toggleActionTitle = NSLocalizedString("Request Mobile Site", comment: "Action Sheet Button for Requesting the Mobile Site")
} else {
toggleActionTitle = NSLocalizedString("Request Desktop Site", comment: "Action Sheet Button for Requesting the Desktop Site")
}
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: toggleActionTitle, style: .default, handler: { _ in tab.toggleDesktopSite() }))
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil))
if #available(iOS 11, *) {
if let helper = tab.contentBlocker as? ContentBlockerHelper {
let state = helper.userOverrideForTrackingProtection
if state != .disallowUserOverride {
let title = state == .forceDisabled ? Strings.TrackingProtectionReloadWith : Strings.TrackingProtectionReloadWithout
controller.addAction(UIAlertAction(title: title, style: .default, handler: {_ in
helper.overridePrefsAndReloadTab(enableTrackingProtection: state == .forceDisabled)
}))
}
}
}
controller.popoverPresentationController?.sourceView = toolbar ?? urlBar
controller.popoverPresentationController?.sourceRect = button.frame
present(controller, animated: true, completion: nil)
}
func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.stop()
}
func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goForward()
}
func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
showBackForwardList()
}
func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
// ensure that any keyboards or spinners are dismissed before presenting the menu
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
var actions: [[PhotonActionSheetItem]] = []
actions.append(getHomePanelActions())
actions.append(getOtherPanelActions(vcDelegate: self))
// force a modal if the menu is being displayed in compact split screen
let shouldSupress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad
presentSheetWith(actions: actions, on: self, from: button, supressPopover: shouldSupress)
}
func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
showTabTray()
}
func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) {
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: Strings.NewTabTitle, style: .default, handler: { _ in
self.tabManager.addTabAndSelect(isPrivate: false)
}))
controller.addAction(UIAlertAction(title: Strings.NewPrivateTabTitle, style: .default, handler: { _ in
self.tabManager.addTabAndSelect(isPrivate: true)
}))
controller.addAction(UIAlertAction(title: Strings.CloseTabTitle, style: .destructive, handler: { _ in
if let tab = self.tabManager.selectedTab {
self.tabManager.removeTab(tab)
}
}))
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil))
controller.popoverPresentationController?.sourceView = toolbar ?? urlBar
controller.popoverPresentationController?.sourceRect = button.frame
present(controller, animated: true, completion: nil)
}
func showBackForwardList() {
if let backForwardList = tabManager.selectedTab?.webView?.backForwardList {
let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList)
backForwardViewController.tabManager = tabManager
backForwardViewController.bvc = self
backForwardViewController.modalPresentationStyle = .overCurrentContext
backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator()
self.present(backForwardViewController, animated: true, completion: nil)
}
}
}
extension BrowserViewController: TabDelegate {
func tab(_ tab: Tab, didCreateWebView webView: WKWebView) {
webView.frame = webViewContainer.frame
// Observers that live as long as the tab. Make sure these are all cleared in willDeleteWebView below!
KVOs.forEach { webView.addObserver(self, forKeyPath: $0.rawValue, options: .new, context: nil) }
webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue, options: .new, context: nil)
webView.uiDelegate = self
let formPostHelper = FormPostHelper(tab: tab)
tab.addContentScript(formPostHelper, name: FormPostHelper.name())
let readerMode = ReaderMode(tab: tab)
readerMode.delegate = self
tab.addContentScript(readerMode, name: ReaderMode.name())
// only add the logins helper if the tab is not a private browsing tab
if !tab.isPrivate {
let logins = LoginsHelper(tab: tab, profile: profile)
tab.addContentScript(logins, name: LoginsHelper.name())
}
let contextMenuHelper = ContextMenuHelper(tab: tab)
contextMenuHelper.delegate = self
tab.addContentScript(contextMenuHelper, name: ContextMenuHelper.name())
let errorHelper = ErrorPageHelper()
tab.addContentScript(errorHelper, name: ErrorPageHelper.name())
let sessionRestoreHelper = SessionRestoreHelper(tab: tab)
sessionRestoreHelper.delegate = self
tab.addContentScript(sessionRestoreHelper, name: SessionRestoreHelper.name())
let findInPageHelper = FindInPageHelper(tab: tab)
findInPageHelper.delegate = self
tab.addContentScript(findInPageHelper, name: FindInPageHelper.name())
let noImageModeHelper = NoImageModeHelper(tab: tab)
tab.addContentScript(noImageModeHelper, name: NoImageModeHelper.name())
let printHelper = PrintHelper(tab: tab)
tab.addContentScript(printHelper, name: PrintHelper.name())
let customSearchHelper = CustomSearchHelper(tab: tab)
tab.addContentScript(customSearchHelper, name: CustomSearchHelper.name())
let nightModeHelper = NightModeHelper(tab: tab)
tab.addContentScript(nightModeHelper, name: NightModeHelper.name())
// XXX: Bug 1390200 - Disable NSUserActivity/CoreSpotlight temporarily
// let spotlightHelper = SpotlightHelper(tab: tab)
// tab.addHelper(spotlightHelper, name: SpotlightHelper.name())
tab.addContentScript(LocalRequestHelper(), name: LocalRequestHelper.name())
let historyStateHelper = HistoryStateHelper(tab: tab)
historyStateHelper.delegate = self
tab.addContentScript(historyStateHelper, name: HistoryStateHelper.name())
if #available(iOS 11, *) {
(tab.contentBlocker as? ContentBlockerHelper)?.setupForWebView()
}
let metadataHelper = MetadataParserHelper(tab: tab, profile: profile)
tab.addContentScript(metadataHelper, name: MetadataParserHelper.name())
}
func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) {
tab.cancelQueuedAlerts()
KVOs.forEach { webView.removeObserver(self, forKeyPath: $0.rawValue) }
webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue)
webView.uiDelegate = nil
webView.scrollView.delegate = nil
webView.removeFromSuperview()
}
fileprivate func findSnackbar(_ barToFind: SnackBar) -> Int? {
let bars = alertStackView.arrangedSubviews
for (index, bar) in bars.enumerated() where bar === barToFind {
return index
}
return nil
}
func showBar(_ bar: SnackBar, animated: Bool) {
view.layoutIfNeeded()
UIView.animate(withDuration: animated ? 0.25 : 0, animations: { _ in
self.alertStackView.insertArrangedSubview(bar, at: 0)
self.view.layoutIfNeeded()
})
}
func removeBar(_ bar: SnackBar, animated: Bool) {
UIView.animate(withDuration: animated ? 0.25 : 0, animations: { _ in
bar.removeFromSuperview()
})
}
func removeAllBars() {
alertStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
}
func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) {
showBar(bar, animated: true)
}
func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) {
removeBar(bar, animated: true)
}
func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) {
updateFindInPageVisibility(visible: true)
findInPageBar?.text = selection
}
}
extension BrowserViewController: HomePanelViewControllerDelegate {
func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) {
finishEditingAndSubmit(url, visitType: visitType)
}
func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) {
if let url = tabManager.selectedTab?.url, url.isAboutHomeURL {
tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil)
}
}
func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) {
let tab = self.tabManager.addTab(PrivilegedRequest(url: url) as URLRequest, afterTab: self.tabManager.selectedTab, isPrivate: isPrivate)
// If we are showing toptabs a user can just use the top tab bar
// If in overlay mode switching doesnt correctly dismiss the homepanels
guard !topTabsVisible, !self.urlBar.inOverlayMode else {
return
}
// We're not showing the top tabs; show a toast to quick switch to the fresh new tab.
let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in
if buttonPressed {
self.tabManager.selectTab(tab)
}
})
self.show(buttonToast: toast)
}
}
extension BrowserViewController: SearchViewControllerDelegate {
func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) {
finishEditingAndSubmit(url, visitType: VisitType.typed)
}
func searchViewController(_ searchViewController: SearchViewController, didLongPressSuggestion suggestion: String) {
self.urlBar.setLocation(suggestion, search: true)
}
func presentSearchSettingsController() {
let settingsNavigationController = SearchSettingsTableViewController()
settingsNavigationController.model = self.profile.searchEngines
settingsNavigationController.profile = self.profile
let navController = ModalSettingsNavigationController(rootViewController: settingsNavigationController)
self.present(navController, animated: true, completion: nil)
}
}
extension BrowserViewController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {
// Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it
// and having multiple views with the same label confuses tests.
if let wv = previous?.webView {
removeOpenInView()
wv.endEditing(true)
wv.accessibilityLabel = nil
wv.accessibilityElementsHidden = true
wv.accessibilityIdentifier = nil
wv.removeFromSuperview()
}
if let tab = selected, let webView = tab.webView {
updateURLBarDisplayURL(tab)
if tab.isPrivate != previous?.isPrivate {
applyTheme(tab.isPrivate ? .Private : .Normal)
}
readerModeCache = tab.isPrivate ? MemoryReaderModeCache.sharedInstance : DiskReaderModeCache.sharedInstance
if let privateModeButton = topTabsViewController?.privateModeButton, previous != nil && previous?.isPrivate != tab.isPrivate {
privateModeButton.setSelected(tab.isPrivate, animated: true)
}
ReaderModeHandlers.readerModeCache = readerModeCache
scrollController.tab = selected
webViewContainer.addSubview(webView)
webView.snp.makeConstraints { make in
make.top.equalTo(webViewContainerToolbar.snp.bottom)
make.left.right.bottom.equalTo(self.webViewContainer)
}
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.accessibilityIdentifier = "contentView"
webView.accessibilityElementsHidden = false
if webView.url == nil {
// The web view can go gray if it was zombified due to memory pressure.
// When this happens, the URL is nil, so try restoring the page upon selection.
tab.reload()
}
}
if let selected = selected, let previous = previous, selected.isPrivate != previous.isPrivate {
updateTabCountUsingTabManager(tabManager)
}
removeAllBars()
if let bars = selected?.bars {
for bar in bars {
showBar(bar, animated: true)
}
}
updateFindInPageVisibility(visible: false)
navigationToolbar.updateReloadStatus(selected?.loading ?? false)
navigationToolbar.updateBackStatus(selected?.canGoBack ?? false)
navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false)
if !(selected?.webView?.url?.isLocalUtility ?? false) {
self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0))
}
if let readerMode = selected?.getContentScript(name: ReaderMode.name()) as? ReaderMode {
urlBar.updateReaderModeState(readerMode.state)
if readerMode.state == .active {
showReaderModeBar(animated: false)
} else {
hideReaderModeBar(animated: false)
}
} else {
urlBar.updateReaderModeState(ReaderModeState.unavailable)
}
updateInContentHomePanel(selected?.url as URL?)
}
func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) {
// If we are restoring tabs then we update the count once at the end
if !tabManager.isRestoring {
updateTabCountUsingTabManager(tabManager)
}
tab.tabDelegate = self
}
func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) {
updateTabCountUsingTabManager(tabManager)
// tabDelegate is a weak ref (and the tab's webView may not be destroyed yet)
// so we don't expcitly unset it.
if let url = tab.url, !url.isAboutURL && !tab.isPrivate {
profile.recentlyClosedTabs.addTab(url as URL, title: tab.title, faviconURL: tab.displayFavicon?.url)
}
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
func show(buttonToast: ButtonToast, afterWaiting delay: DispatchTimeInterval = SimpleToastUX.ToastDelayBefore, duration: DispatchTimeInterval = SimpleToastUX.ToastDismissAfter) {
// If BVC isnt visible hold on to this toast until viewDidAppear
if self.view.window == nil {
self.pendingToast = buttonToast
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
self.view.addSubview(buttonToast)
buttonToast.snp.makeConstraints { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.webViewContainer)
}
buttonToast.showToast(duration: duration)
}
}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
guard let toast = toast, !tabTrayController.privateMode else {
return
}
show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay)
}
fileprivate func updateTabCountUsingTabManager(_ tabManager: TabManager, animated: Bool = true) {
if let selectedTab = tabManager.selectedTab {
let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count
toolbar?.updateTabCount(count, animated: animated)
urlBar.updateTabCount(count, animated: !urlBar.inOverlayMode)
topTabsViewController?.updateTabCount(count, animated: animated)
}
}
}
/// List of schemes that are allowed to open a popup window
private let SchemesAllowedToOpenPopups = ["http", "https", "javascript", "data"]
extension BrowserViewController: WKUIDelegate {
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
guard let parentTab = tabManager[webView] else { return nil }
if !navigationAction.isAllowed {
print("Denying unprivileged request: \(navigationAction.request)")
return nil
}
if let currentTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(currentTab)
}
let request: URLRequest
if let formPostHelper = parentTab.getContentScript(name: "FormPostHelper") as? FormPostHelper {
request = formPostHelper.urlRequestForNavigationAction(navigationAction)
} else {
request = navigationAction.request
}
// If the page uses window.open() or target="_blank", open the page in a new tab.
let newTab = tabManager.addTab(request, configuration: configuration, afterTab: parentTab, isPrivate: parentTab.isPrivate)
tabManager.selectTab(newTab)
// If the page we just opened has a bad scheme, we return nil here so that JavaScript does not
// get a reference to it which it can return from window.open() - this will end up as a
// CFErrorHTTPBadURL being presented.
guard let scheme = (navigationAction.request as NSURLRequest).url?.scheme?.lowercased(), SchemesAllowedToOpenPopups.contains(scheme) else {
return nil
}
return newTab.webView
}
fileprivate func canDisplayJSAlertForWebView(_ webView: WKWebView) -> Bool {
// Only display a JS Alert if we are selected and there isn't anything being shown
return ((tabManager.selectedTab == nil ? false : tabManager.selectedTab!.webView == webView)) && (self.presentedViewController == nil)
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler)
if canDisplayJSAlertForWebView(webView) {
present(messageAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(messageAlert)
} else {
// This should never happen since an alert needs to come from a web view but just in case call the handler
// since not calling it will result in a runtime exception.
completionHandler()
}
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler)
if canDisplayJSAlertForWebView(webView) {
present(confirmAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(confirmAlert)
} else {
completionHandler(false)
}
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText)
if canDisplayJSAlertForWebView(webView) {
present(textInputAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(textInputAlert)
} else {
completionHandler(nil)
}
}
/// Invoked when an error occurs while starting to load data for the main frame.
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
// Ignore the "Frame load interrupted" error that is triggered when we cancel a request
// to open an external application and hand it over to UIApplication.openURL(). The result
// will be that we switch to the external app, for example the app store, while keeping the
// original web page in the tab instead of replacing it with an error page.
let error = error as NSError
if error.domain == "WebKitErrorDomain" && error.code == 102 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error as NSError) {
return
}
if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) {
if let tab = tabManager[webView], tab === tabManager.selectedTab {
urlBar.currentURL = tab.url?.displayURL
}
return
}
if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL {
ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView)
// If the local web server isn't working for some reason (Firefox cellular data is
// disabled in settings, for example), we'll fail to load the session restore URL.
// We rely on loading that page to get the restore callback to reset the restoring
// flag, so if we fail to load that page, reset it here.
if url.aboutComponent == "sessionrestore" {
tabManager.tabs.filter { $0.webView == webView }.first?.restoring = false
}
}
}
fileprivate func checkIfWebContentProcessHasCrashed(_ webView: WKWebView, error: NSError) -> Bool {
if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" {
print("WebContent process has crashed. Trying to reloadFromOrigin to restart it.")
webView.reloadFromOrigin()
return true
}
return false
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let helperForURL = OpenIn.helperForResponse(navigationResponse.response)
if navigationResponse.canShowMIMEType {
if let openInHelper = helperForURL {
addViewForOpenInHelper(openInHelper)
}
decisionHandler(WKNavigationResponsePolicy.allow)
return
}
guard var openInHelper = helperForURL else {
let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: Strings.UnableToDownloadError])
ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.url!, inWebView: webView)
return decisionHandler(WKNavigationResponsePolicy.allow)
}
openInHelper.openInView = openInHelper.openInView ?? navigationToolbar.menuButton
openInHelper.open()
decisionHandler(WKNavigationResponsePolicy.cancel)
}
func webViewDidClose(_ webView: WKWebView) {
if let tab = tabManager[webView] {
self.tabManager.removeTab(tab)
}
}
}
extension BrowserViewController: ReaderModeDelegate {
func readerMode(_ readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forTab tab: Tab) {
// If this reader mode availability state change is for the tab that we currently show, then update
// the button. Otherwise do nothing and the button will be updated when the tab is made active.
if tabManager.selectedTab === tab {
urlBar.updateReaderModeState(state)
}
}
func readerMode(_ readerMode: ReaderMode, didDisplayReaderizedContentForTab tab: Tab) {
self.showReaderModeBar(animated: true)
tab.showContent(true)
}
}
// MARK: - UIPopoverPresentationControllerDelegate
extension BrowserViewController: UIPopoverPresentationControllerDelegate {
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
displayedPopoverController = nil
updateDisplayedPopoverProperties = nil
}
}
extension BrowserViewController: UIAdaptivePresentationControllerDelegate {
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
}
// MARK: - ReaderModeStyleViewControllerDelegate
extension BrowserViewController: ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(_ readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) {
// Persist the new style to the profile
let encodedStyle: [String: Any] = style.encodeAsDictionary()
profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle)
// Change the reader mode style on all tabs that have reader mode active
for tabIndex in 0..<tabManager.count {
if let tab = tabManager[tabIndex] {
if let readerMode = tab.getContentScript(name: "ReaderMode") as? ReaderMode {
if readerMode.state == ReaderModeState.active {
readerMode.style = style
}
}
}
}
}
}
extension BrowserViewController {
func updateReaderModeBar() {
if let readerModeBar = readerModeBar {
if let tab = self.tabManager.selectedTab, tab.isPrivate {
readerModeBar.applyTheme(.Private)
} else {
readerModeBar.applyTheme(.Normal)
}
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, let record = successValue {
readerModeBar.unread = record.unread
readerModeBar.added = true
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
}
}
func showReaderModeBar(animated: Bool) {
if self.readerModeBar == nil {
let readerModeBar = ReaderModeBarView(frame: CGRect.zero)
readerModeBar.delegate = self
view.insertSubview(readerModeBar, belowSubview: header)
self.readerModeBar = readerModeBar
}
updateReaderModeBar()
self.updateViewConstraints()
}
func hideReaderModeBar(animated: Bool) {
if let readerModeBar = self.readerModeBar {
readerModeBar.removeFromSuperview()
self.readerModeBar = nil
self.updateViewConstraints()
}
}
/// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode
/// and be done with it. In the more complicated case, reader mode was already open for this page and we simply
/// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version
/// of the current page is there. And if so, we go there.
func enableReaderMode() {
guard let tab = tabManager.selectedTab, let webView = tab.webView else { return }
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
guard let currentURL = webView.backForwardList.currentItem?.url, let readerModeURL = currentURL.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) else { return }
if backList.count > 1 && backList.last?.url == readerModeURL {
webView.go(to: backList.last!)
} else if forwardList.count > 0 && forwardList.first?.url == readerModeURL {
webView.go(to: forwardList.first!)
} else {
// Store the readability result in the cache and load it. This will later move to the ReadabilityHelper.
webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in
if let readabilityResult = ReadabilityResult(object: object as AnyObject?) {
do {
try self.readerModeCache.put(currentURL, readabilityResult)
} catch _ {
}
if let nav = webView.load(PrivilegedRequest(url: readerModeURL) as URLRequest) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
})
}
}
/// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which
/// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that
/// case we simply open a new page with the original url. In the more complicated page, the non-readerized version
/// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there.
func disableReaderMode() {
if let tab = tabManager.selectedTab,
let webView = tab.webView {
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
if let currentURL = webView.backForwardList.currentItem?.url {
if let originalURL = currentURL.decodeReaderModeURL {
if backList.count > 1 && backList.last?.url == originalURL {
webView.go(to: backList.last!)
} else if forwardList.count > 0 && forwardList.first?.url == originalURL {
webView.go(to: forwardList.first!)
} else {
if let nav = webView.load(URLRequest(url: originalURL)) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
}
}
}
}
func SELDynamicFontChanged(_ notification: Notification) {
guard notification.name == .DynamicFontChanged else { return }
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict as [String: AnyObject]) {
readerModeStyle = style
}
}
readerModeStyle.fontSize = ReaderModeFontSize.defaultSize
self.readerModeStyleViewController(ReaderModeStyleViewController(), didConfigureStyle: readerModeStyle)
}
}
extension BrowserViewController: ReaderModeBarViewDelegate {
func readerModeBar(_ readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) {
switch buttonType {
case .settings:
if let readerMode = tabManager.selectedTab?.getContentScript(name: "ReaderMode") as? ReaderMode, readerMode.state == ReaderModeState.active {
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict as [String: AnyObject]) {
readerModeStyle = style
}
}
let readerModeStyleViewController = ReaderModeStyleViewController()
readerModeStyleViewController.delegate = self
readerModeStyleViewController.readerModeStyle = readerModeStyle
readerModeStyleViewController.modalPresentationStyle = .popover
let setupPopover = { [unowned self] in
if let popoverPresentationController = readerModeStyleViewController.popoverPresentationController {
popoverPresentationController.backgroundColor = UIColor.white
popoverPresentationController.delegate = self
popoverPresentationController.sourceView = readerModeBar
popoverPresentationController.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1)
popoverPresentationController.permittedArrowDirections = .up
}
}
setupPopover()
if readerModeStyleViewController.popoverPresentationController != nil {
displayedPopoverController = readerModeStyleViewController
updateDisplayedPopoverProperties = setupPopover
}
self.present(readerModeStyleViewController, animated: true, completion: nil)
}
case .markAsRead:
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, let record = successValue {
profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail?
readerModeBar.unread = false
}
}
case .markAsUnread:
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, let record = successValue {
profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail?
readerModeBar.unread = true
}
}
case .addToReadingList:
if let tab = tabManager.selectedTab,
let rawURL = tab.url, rawURL.isReaderModeURL,
let url = rawURL.decodeReaderModeURL {
profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) // TODO Check result, can this fail?
readerModeBar.added = true
readerModeBar.unread = true
}
case .removeFromReadingList:
if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString,
let result = profile.readingList?.getRecordWithURL(url),
let successValue = result.successValue,
let record = successValue {
profile.readingList?.deleteRecord(record) // TODO Check result, can this fail?
readerModeBar.added = false
readerModeBar.unread = false
}
}
}
}
extension BrowserViewController: IntroViewControllerDelegate {
@discardableResult func presentIntroViewController(_ force: Bool = false, animated: Bool = true) -> Bool {
if let deeplink = self.profile.prefs.stringForKey("AdjustDeeplinkKey"), let url = URL(string: deeplink) {
self.launchFxAFromDeeplinkURL(url)
return true
}
if force || profile.prefs.intForKey(PrefsKeys.IntroSeen) == nil {
let introViewController = IntroViewController()
introViewController.delegate = self
// On iPad we present it modally in a controller
if topTabsVisible {
introViewController.preferredContentSize = CGSize(width: IntroUX.Width, height: IntroUX.Height)
introViewController.modalPresentationStyle = .formSheet
}
present(introViewController, animated: animated) {
// On first run (and forced) open up the homepage in the background.
if let homePageURL = HomePageAccessors.getHomePage(self.profile.prefs), let tab = self.tabManager.selectedTab, DeviceInfo.hasConnectivity() {
tab.loadRequest(URLRequest(url: homePageURL))
}
}
return true
}
return false
}
func launchFxAFromDeeplinkURL(_ url: URL) {
self.profile.prefs.removeObjectForKey("AdjustDeeplinkKey")
var query = url.getQuery()
query["entrypoint"] = "adjust_deepklink_ios"
let fxaParams: FxALaunchParams
fxaParams = FxALaunchParams(query: query)
self.presentSignInViewController(fxaParams)
}
func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool) {
self.profile.prefs.setInt(1, forKey: PrefsKeys.IntroSeen)
LeanPlumClient.shared.track(event: .dismissedOnboarding)
introViewController.dismiss(animated: true) { finished in
if self.navigationController?.viewControllers.count ?? 0 > 1 {
_ = self.navigationController?.popToRootViewController(animated: true)
}
if requestToLogin {
self.presentSignInViewController()
}
}
}
func presentSignInViewController(_ fxaOptions: FxALaunchParams? = nil) {
// Show the settings page if we have already signed in. If we haven't then show the signin page
let vcToPresent: UIViewController
if profile.hasAccount() {
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
vcToPresent = settingsTableViewController
} else {
let signInVC = FxAContentViewController(profile: profile, fxaOptions: fxaOptions)
signInVC.delegate = self
signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSignInViewController))
vcToPresent = signInVC
}
let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent)
settingsNavigationController.modalPresentationStyle = .formSheet
settingsNavigationController.navigationBar.isTranslucent = false
self.present(settingsNavigationController, animated: true, completion: nil)
}
func dismissSignInViewController() {
self.dismiss(animated: true, completion: nil)
}
}
extension BrowserViewController: FxAContentViewControllerDelegate {
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) {
if flags.verified {
self.dismiss(animated: true, completion: nil)
}
}
func contentViewControllerDidCancel(_ viewController: FxAContentViewController) {
self.dismiss(animated: true, completion: nil)
}
}
extension BrowserViewController: ContextMenuHelperDelegate {
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer) {
// locationInView can return (0, 0) when the long press is triggered in an invalid page
// state (e.g., long pressing a link before the document changes, then releasing after a
// different page loads).
let touchPoint = gestureRecognizer.location(in: view)
guard touchPoint != CGPoint.zero else { return }
let touchSize = CGSize(width: 0, height: 16)
let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
var dialogTitle: String?
if let url = elements.link, let currentTab = tabManager.selectedTab {
dialogTitle = url.absoluteString
let isPrivate = currentTab.isPrivate
let addTab = { (rURL: URL, isPrivate: Bool) in
let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate)
LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Long Press Context Menu" as AnyObject])
guard !self.topTabsVisible else {
return
}
// We're not showing the top tabs; show a toast to quick switch to the fresh new tab.
let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in
if buttonPressed {
self.tabManager.selectTab(tab)
}
})
self.show(buttonToast: toast)
}
if !isPrivate {
let newTabTitle = NSLocalizedString("Open in New Tab", comment: "Context menu item for opening a link in a new tab")
let openNewTabAction = UIAlertAction(title: newTabTitle, style: .default) { (action: UIAlertAction) in
addTab(url, false)
}
actionSheetController.addAction(openNewTabAction)
}
let openNewPrivateTabTitle = NSLocalizedString("Open in New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab")
let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: .default) { (action: UIAlertAction) in
addTab(url, true)
}
actionSheetController.addAction(openNewPrivateTabAction)
let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard")
let copyAction = UIAlertAction(title: copyTitle, style: .default) { (action: UIAlertAction) -> Void in
UIPasteboard.general.url = url as URL
}
actionSheetController.addAction(copyAction)
let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL")
let shareAction = UIAlertAction(title: shareTitle, style: .default) { _ in
self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .any)
}
actionSheetController.addAction(shareAction)
}
if let url = elements.image {
if dialogTitle == nil {
dialogTitle = url.absoluteString
}
let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus()
let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image")
let saveImageAction = UIAlertAction(title: saveImageTitle, style: .default) { (action: UIAlertAction) -> Void in
if photoAuthorizeStatus == .authorized || photoAuthorizeStatus == .notDetermined {
self.getImage(url as URL) {
UIImageWriteToSavedPhotosAlbum($0, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
} else {
let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: .alert)
let dismissAction = UIAlertAction(title: Strings.CancelString, style: .default, handler: nil)
accessDenied.addAction(dismissAction)
let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: .default ) { (action: UIAlertAction!) -> Void in
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:])
}
accessDenied.addAction(settingsAction)
self.present(accessDenied, animated: true, completion: nil)
}
}
actionSheetController.addAction(saveImageAction)
let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard")
let copyAction = UIAlertAction(title: copyImageTitle, style: .default) { (action: UIAlertAction) -> Void in
// put the actual image on the clipboard
// do this asynchronously just in case we're in a low bandwidth situation
let pasteboard = UIPasteboard.general
pasteboard.url = url as URL
let changeCount = pasteboard.changeCount
let application = UIApplication.shared
var taskId: UIBackgroundTaskIdentifier = 0
taskId = application.beginBackgroundTask (expirationHandler: { _ in
application.endBackgroundTask(taskId)
})
Alamofire.request(url).validate(statusCode: 200..<300).response { response in
// Only set the image onto the pasteboard if the pasteboard hasn't changed since
// fetching the image; otherwise, in low-bandwidth situations,
// we might be overwriting something that the user has subsequently added.
if changeCount == pasteboard.changeCount, let imageData = response.data, response.error == nil {
pasteboard.addImageWithData(imageData, forURL: url)
}
application.endBackgroundTask(taskId)
}
}
actionSheetController.addAction(copyAction)
}
// If we're showing an arrow popup, set the anchor to the long press location.
if let popoverPresentationController = actionSheetController.popoverPresentationController {
popoverPresentationController.sourceView = view
popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize)
popoverPresentationController.permittedArrowDirections = .any
popoverPresentationController.delegate = self
}
if actionSheetController.popoverPresentationController != nil {
displayedPopoverController = actionSheetController
}
actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength)
let cancelAction = UIAlertAction(title: Strings.CancelString, style: UIAlertActionStyle.cancel, handler: nil)
actionSheetController.addAction(cancelAction)
self.present(actionSheetController, animated: true, completion: nil)
}
fileprivate func getImage(_ url: URL, success: @escaping (UIImage) -> Void) {
Alamofire.request(url).validate(statusCode: 200..<300).response { response in
if let data = response.data, let image = data.isGIF ? UIImage.imageFromGIFDataThreadSafe(data) : UIImage.imageFromDataThreadSafe(data) {
success(image)
}
}
}
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer) {
displayedPopoverController?.dismiss(animated: true) {
self.displayedPopoverController = nil
}
}
}
extension BrowserViewController {
func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if error == nil {
LeanPlumClient.shared.track(event: .saveImage)
}
}
}
extension BrowserViewController: HistoryStateHelperDelegate {
func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab) {
navigateInTab(tab: tab)
tabManager.storeChanges()
}
}
/**
A third party search engine Browser extension
**/
extension BrowserViewController {
func addCustomSearchButtonToWebView(_ webView: WKWebView) {
//check if the search engine has already been added.
let domain = webView.url?.domainURL.host
let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain}
if !matches.isEmpty {
self.customSearchEngineButton.tintColor = UIColor.gray
self.customSearchEngineButton.isUserInteractionEnabled = false
} else {
self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor
self.customSearchEngineButton.isUserInteractionEnabled = true
}
/*
This is how we access hidden views in the WKContentView
Using the public headers we can find the keyboard accessoryView which is not usually available.
Specific values here are from the WKContentView headers.
https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h
*/
guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else {
/*
In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder
and a search button should not be added.
*/
return
}
guard let input = webContentView.perform(#selector(getter: UIResponder.inputAccessoryView)),
let inputView = input.takeUnretainedValue() as? UIInputView,
let nextButton = inputView.value(forKey: "_nextItem") as? UIBarButtonItem,
let nextButtonView = nextButton.value(forKey: "view") as? UIView else {
//failed to find the inputView instead lets use the inputAssistant
addCustomSearchButtonToInputAssistant(webContentView)
return
}
inputView.addSubview(self.customSearchEngineButton)
self.customSearchEngineButton.snp.remakeConstraints { make in
make.leading.equalTo(nextButtonView.snp.trailing).offset(20)
make.width.equalTo(inputView.snp.height)
make.top.equalTo(nextButtonView.snp.top)
make.height.equalTo(inputView.snp.height)
}
}
/**
This adds the customSearchButton to the inputAssistant
for cases where the inputAccessoryView could not be found for example
on the iPad where it does not exist. However this only works on iOS9
**/
func addCustomSearchButtonToInputAssistant(_ webContentView: UIView) {
guard customSearchBarButton == nil else {
return //The searchButton is already on the keyboard
}
let inputAssistant = webContentView.inputAssistantItem
let item = UIBarButtonItem(customView: customSearchEngineButton)
customSearchBarButton = item
_ = Try(withTry: {
inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item)
}) { (exception) in
Sentry.shared.send(message: "Failed adding custom search button to input assistant", tag: .general, severity: .error, description: "\(exception ??? "nil")")
}
}
func addCustomSearchEngineForFocusedElement() {
guard let webView = tabManager.selectedTab?.webView else {
return
}
webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in
guard let searchQuery = result as? String, let favicon = self.tabManager.selectedTab!.displayFavicon else {
//Javascript responded with an incorrectly formatted message. Show an error.
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.present(alert, animated: true, completion: nil)
return
}
self.addSearchEngine(searchQuery, favicon: favicon)
self.customSearchEngineButton.tintColor = UIColor.gray
self.customSearchEngineButton.isUserInteractionEnabled = false
}
}
func addSearchEngine(_ searchQuery: String, favicon: Favicon) {
guard searchQuery != "",
let iconURL = URL(string: favicon.url),
let url = URL(string: searchQuery.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!),
let shortName = url.domainURL.host else {
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.present(alert, animated: true, completion: nil)
return
}
let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in
self.customSearchEngineButton.tintColor = UIColor.gray
self.customSearchEngineButton.isUserInteractionEnabled = false
SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in
guard let image = image else {
let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch()
self.present(alert, animated: true, completion: nil)
return
}
self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image, searchTemplate: searchQuery, suggestTemplate: nil, isCustomEngine: true))
let Toast = SimpleToast()
Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded, bottomContainer: self.webViewContainer)
}
}
self.present(alert, animated: true, completion: {})
}
}
extension BrowserViewController: KeyboardHelperDelegate {
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
keyboardState = state
updateViewConstraints()
UIView.animate(withDuration: state.animationDuration) {
UIView.setAnimationCurve(state.animationCurve)
self.alertStackView.layoutIfNeeded()
}
guard let webView = tabManager.selectedTab?.webView else {
return
}
webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in
guard let _ = result as? String else {
return
}
self.addCustomSearchButtonToWebView(webView)
}
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
keyboardState = nil
updateViewConstraints()
//If the searchEngineButton exists remove it form the keyboard
if let buttonGroup = customSearchBarButton?.buttonGroup {
buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton }
customSearchBarButton = nil
}
if self.customSearchEngineButton.superview != nil {
self.customSearchEngineButton.removeFromSuperview()
}
UIView.animate(withDuration: state.animationDuration) {
UIView.setAnimationCurve(state.animationCurve)
self.alertStackView.layoutIfNeeded()
}
}
}
extension BrowserViewController: SessionRestoreHelperDelegate {
func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) {
tab.restoring = false
if let tab = tabManager.selectedTab, tab.webView === tab.webView {
updateUIForReaderHomeStateForTab(tab)
}
}
}
extension BrowserViewController: TabTrayDelegate {
// This function animates and resets the tab chrome transforms when
// the tab tray dismisses.
func tabTrayDidDismiss(_ tabTray: TabTrayController) {
resetBrowserChrome()
}
func tabTrayDidAddBookmark(_ tab: Tab) {
guard let url = tab.url?.absoluteString, !url.isEmpty else { return }
self.addBookmark(tab.tabState)
}
func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord? {
guard let url = tab.url?.absoluteString, !url.isEmpty else { return nil }
return profile.readingList?.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.current.name).successValue
}
func tabTrayRequestsPresentationOf(_ viewController: UIViewController) {
self.present(viewController, animated: false, completion: nil)
}
}
// MARK: Browser Chrome Theming
extension BrowserViewController: Themeable {
func applyTheme(_ theme: Theme) {
let ui: [Themeable?] = [urlBar, toolbar, readerModeBar, topTabsViewController]
ui.forEach { $0?.applyTheme(theme) }
statusBarOverlay.backgroundColor = shouldShowTopTabsForTraitCollection(traitCollection) ? UIColor.Defaults.Grey80 : urlBar.backgroundColor
setNeedsStatusBarAppearanceUpdate()
}
}
extension BrowserViewController: FindInPageBarDelegate, FindInPageHelperDelegate {
func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) {
find(text, function: "find")
}
func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) {
findInPageBar?.endEditing(true)
find(text, function: "findNext")
}
func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) {
findInPageBar?.endEditing(true)
find(text, function: "findPrevious")
}
func findInPageDidPressClose(_ findInPage: FindInPageBar) {
updateFindInPageVisibility(visible: false)
}
fileprivate func find(_ text: String, function: String) {
guard let webView = tabManager.selectedTab?.webView else { return }
let escaped = text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
webView.evaluateJavaScript("__firefox__.\(function)(\"\(escaped)\")", completionHandler: nil)
}
func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int) {
findInPageBar?.currentResult = currentResult
}
func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int) {
findInPageBar?.totalResults = totalResults
}
}
extension BrowserViewController: JSPromptAlertControllerDelegate {
func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) {
showQueuedAlertIfAvailable()
}
}
extension BrowserViewController: TopTabsDelegate {
func topTabsDidPressTabs() {
urlBar.leaveOverlayMode(didCancel: true)
self.urlBarDidPressTabs(urlBar)
}
func topTabsDidPressNewTab(_ isPrivate: Bool) {
openBlankNewTab(focusLocationField: false, isPrivate: isPrivate)
}
func topTabsDidTogglePrivateMode() {
guard let _ = tabManager.selectedTab else {
return
}
urlBar.leaveOverlayMode()
}
func topTabsDidChangeTab() {
urlBar.leaveOverlayMode(didCancel: true)
}
}
extension BrowserViewController: ClientPickerViewControllerDelegate, InstructionsViewControllerDelegate {
func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) {
self.popToBVC()
}
func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) {
self.popToBVC()
}
func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) {
guard let tab = tabManager.selectedTab, let url = tab.canonicalURL?.displayURL?.absoluteString else { return }
let shareItem = ShareItem(url: url, title: tab.title, favicon: tab.displayFavicon)
guard shareItem.isShareable else {
let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.popToBVC()})
present(alert, animated: true, completion: nil)
return
}
profile.sendItems([shareItem], toClients: clients).uponQueue(.main) { _ in
self.popToBVC()
}
}
}
| b3b62500487c1cc25a73a82e95849694 | 43.463681 | 406 | 0.661441 | false | false | false | false |
three-amigos/car-share-buddy | refs/heads/master | car-share-buddy/DriversViewController.swift | mit | 1 | //
// DriversViewController.swift
// car-share-buddy
//
// Created by Adnan on 01/08/2015.
// Copyright © 2015 three-amigos. All rights reserved.
//
import UIKit
class DriversViewController: UITableViewController {
let repository = DriverRepositoryFactory.getRepository()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repository.getAll().count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let driver: Driver = repository.getAll()[indexPath.row]
let altCarReg = "No Vehicle Registration"
cell.textLabel?.text = "\(driver.name): \(driver.carReg ?? altCarReg)"
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 469443ca85600cd8d32f74370bcbeb0e | 28.465517 | 119 | 0.667642 | false | false | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01101-swift-diagnosticengine-flushactivediagnostic.swift | apache-2.0 | 1 | // 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 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
func f<o>() -> (o, o -> o) -> o {
o m o.j = {
}
{
o) {
r }
}
p q) {
}
class m {
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
}
protocol A {
}
struct B<T : A> {
lett D : C {
func g<T where T.E == F>(f: B<T>) {
}
}
struct d<f : e, g: e where g.h == f.h> {
col P {
}
}
}
i struct c {
c a(b: Int0) {
}
protocol d : b { func b
func d(e: = { (g:A {
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
func g<T where T.E = {
}
struct D : C {
func g<T where T.E == F>(f:
| c1badf5de79ffda1b0e1c8291fa0a37d | 17.333333 | 79 | 0.5875 | false | false | false | false |
Drusy/auvergne-webcams-ios | refs/heads/master | Carthage/Checkouts/ObjectMapper/Sources/Mappable.swift | apache-2.0 | 4 | //
// Mappable.swift
// ObjectMapper
//
// Created by Scott Hoyt on 10/25/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2018 Tristan Himmelman
//
// 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
/// BaseMappable should not be implemented directly. Mappable or StaticMappable should be used instead
public protocol BaseMappable {
/// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process.
mutating func mapping(map: Map)
}
public protocol Mappable: BaseMappable {
/// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point
init?(map: Map)
}
public protocol StaticMappable: BaseMappable {
/// This is function that can be used to:
/// 1) provide an existing cached object to be used for mapping
/// 2) return an object of another class (which conforms to BaseMappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for any given mapping
static func objectForMapping(map: Map) -> BaseMappable?
}
public extension Mappable {
/// Initializes object from a JSON String
init?(JSONString: String, context: MapContext? = nil) {
if let obj: Self = Mapper(context: context).map(JSONString: JSONString) {
self = obj
} else {
return nil
}
}
/// Initializes object from a JSON Dictionary
init?(JSON: [String: Any], context: MapContext? = nil) {
if let obj: Self = Mapper(context: context).map(JSON: JSON) {
self = obj
} else {
return nil
}
}
}
public extension BaseMappable {
/// Returns the JSON Dictionary for the object
func toJSON() -> [String: Any] {
return Mapper().toJSON(self)
}
/// Returns the JSON String for the object
func toJSONString(prettyPrint: Bool = false) -> String? {
return Mapper().toJSONString(self, prettyPrint: prettyPrint)
}
}
public extension Array where Element: BaseMappable {
/// Initialize Array from a JSON String
init?(JSONString: String, context: MapContext? = nil) {
if let obj: [Element] = Mapper(context: context).mapArray(JSONString: JSONString) {
self = obj
} else {
return nil
}
}
/// Initialize Array from a JSON Array
init(JSONArray: [[String: Any]], context: MapContext? = nil) {
let obj: [Element] = Mapper(context: context).mapArray(JSONArray: JSONArray)
self = obj
}
/// Returns the JSON Array
func toJSON() -> [[String: Any]] {
return Mapper().toJSONArray(self)
}
/// Returns the JSON String for the object
func toJSONString(prettyPrint: Bool = false) -> String? {
return Mapper().toJSONString(self, prettyPrint: prettyPrint)
}
}
public extension Set where Element: BaseMappable {
/// Initializes a set from a JSON String
init?(JSONString: String, context: MapContext? = nil) {
if let obj: Set<Element> = Mapper(context: context).mapSet(JSONString: JSONString) {
self = obj
} else {
return nil
}
}
/// Initializes a set from JSON
init?(JSONArray: [[String: Any]], context: MapContext? = nil) {
guard let obj = Mapper(context: context).mapSet(JSONArray: JSONArray) as Set<Element>? else {
return nil
}
self = obj
}
/// Returns the JSON Set
func toJSON() -> [[String: Any]] {
return Mapper().toJSONSet(self)
}
/// Returns the JSON String for the object
func toJSONString(prettyPrint: Bool = false) -> String? {
return Mapper().toJSONString(self, prettyPrint: prettyPrint)
}
}
| 1b101e30527c14f3f7163352119403fb | 31.776978 | 208 | 0.711589 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | iOS/MasterFeed/Cell/MasterFeedTableViewSectionHeaderLayout.swift | mit | 1 | //
// MasterFeedTableViewSectionHeaderLayout.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 11/5/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
import RSCore
struct MasterFeedTableViewSectionHeaderLayout {
private static let labelMarginRight = CGFloat(integerLiteral: 8)
private static let unreadCountMarginRight = CGFloat(integerLiteral: 16)
private static let disclosureButtonSize = CGSize(width: 44, height: 44)
private static let verticalPadding = CGFloat(integerLiteral: 11)
private static let minRowHeight = CGFloat(integerLiteral: 44)
let titleRect: CGRect
let unreadCountRect: CGRect
let disclosureButtonRect: CGRect
let height: CGFloat
init(cellWidth: CGFloat, insets: UIEdgeInsets, label: UILabel, unreadCountView: MasterFeedUnreadCountView) {
let bounds = CGRect(x: insets.left, y: 0.0, width: floor(cellWidth - insets.right), height: 0.0)
// Disclosure Button
var rDisclosure = CGRect.zero
rDisclosure.size = MasterFeedTableViewSectionHeaderLayout.disclosureButtonSize
rDisclosure.origin.x = bounds.origin.x
// Unread Count
let unreadCountSize = unreadCountView.contentSize
let unreadCountIsHidden = unreadCountView.unreadCount < 1
var rUnread = CGRect.zero
if !unreadCountIsHidden {
rUnread.size = unreadCountSize
rUnread.origin.x = bounds.maxX - (MasterFeedTableViewSectionHeaderLayout.unreadCountMarginRight + unreadCountSize.width)
}
// Max Unread Count
// We can't reload Section Headers so we don't let the title extend into the (probably) worse case Unread Count area.
let maxUnreadCountView = MasterFeedUnreadCountView(frame: CGRect.zero)
maxUnreadCountView.unreadCount = 888
let maxUnreadCountSize = maxUnreadCountView.contentSize
// Title
let rLabelx = insets.left + MasterFeedTableViewSectionHeaderLayout.disclosureButtonSize.width
let rLabely = UIFontMetrics.default.scaledValue(for: MasterFeedTableViewSectionHeaderLayout.verticalPadding)
var labelWidth = CGFloat.zero
labelWidth = cellWidth - (rLabelx + MasterFeedTableViewSectionHeaderLayout.labelMarginRight + maxUnreadCountSize.width + MasterFeedTableViewSectionHeaderLayout.unreadCountMarginRight)
let labelSizeInfo = MultilineUILabelSizer.size(for: label.text ?? "", font: label.font, numberOfLines: 0, width: Int(floor(labelWidth)))
var rLabel = CGRect(x: rLabelx, y: rLabely, width: labelWidth, height: labelSizeInfo.size.height)
// Determine cell height
let paddedLabelHeight = rLabel.maxY + UIFontMetrics.default.scaledValue(for: MasterFeedTableViewSectionHeaderLayout.verticalPadding)
let maxGraphicsHeight = [rUnread, rDisclosure].maxY()
var cellHeight = max(paddedLabelHeight, maxGraphicsHeight)
if cellHeight < MasterFeedTableViewSectionHeaderLayout.minRowHeight {
cellHeight = MasterFeedTableViewSectionHeaderLayout.minRowHeight
}
// Center in Cell
let newBounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: cellHeight)
if !unreadCountIsHidden {
rUnread = MasterFeedTableViewCellLayout.centerVertically(rUnread, newBounds)
}
rDisclosure = MasterFeedTableViewCellLayout.centerVertically(rDisclosure, newBounds)
// Small fonts need centered if we hit the minimum row height
if cellHeight == MasterFeedTableViewSectionHeaderLayout.minRowHeight {
rLabel = MasterFeedTableViewCellLayout.centerVertically(rLabel, newBounds)
}
// Assign the properties
self.height = cellHeight
self.unreadCountRect = rUnread
self.disclosureButtonRect = rDisclosure
self.titleRect = rLabel
}
}
| 690ab0b2290c02e342d566960d011fe5 | 38.933333 | 185 | 0.789093 | false | false | false | false |
michaljach/unread | refs/heads/master | unread/Views/InboxTableViewCell.swift | gpl-3.0 | 1 | //
// InboxTableViewCell.swift
// unread
//
// Created by Michał Jach on 30/03/2017.
// Copyright © 2017 Michał Jach. All rights reserved.
//
import UIKit
protocol InboxTableViewCellDelegate {
func mailItemDeleted(thread: Thread)
}
class InboxTableViewCell: UITableViewCell {
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var subjectLabel: UILabel!
@IBOutlet weak var fromLabel: UILabel!
@IBOutlet weak var snippetLabel: UILabel!
@IBOutlet weak var rightIndicator: UIView!
@IBOutlet weak var leftIndicator: UIView!
// Original center point of cell view
var originalCenter = CGPoint()
// Dragging status
var deleteOnDragRelease = false
// Cell delegate
var delegate: InboxTableViewCellDelegate?
// Thread object that cell contains
var thread: Thread?
/**
* Layout subview
* Used for attaching gesture recognizer
*
*/
override func layoutSubviews() {
super.layoutSubviews()
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan))
recognizer.delegate = self
addGestureRecognizer(recognizer)
}
/**
* On pan gesture invoke
*
* - parameter recognizer: recognizer object
*/
func handlePan(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .began:
originalCenter = center
break
case .changed:
let translation = recognizer.translation(in: self)
center = CGPoint(x: originalCenter.x + translation.x, y: originalCenter.y)
deleteOnDragRelease = frame.origin.x > frame.size.width / 2.0
//let cueAlpha = fabs(frame.origin.x) / (frame.size.width / 2.0)
//rightIndicator.alpha = cueAlpha
//leftIndicator.alpha = cueAlpha
break
case .ended:
let originalFrame = CGRect(x: 0, y: frame.origin.y,
width: bounds.size.width, height: bounds.size.height)
if !deleteOnDragRelease {
UIView.animate(withDuration: 0.2, animations: {self.frame = originalFrame})
}
if deleteOnDragRelease {
if delegate != nil && thread != nil {
delegate!.mailItemDeleted(thread: thread!)
}
}
break
default: break
}
}
/**
* On gesture begin
*
* - parameter gestureRecognizer: recognizer object
*/
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer {
let translation = panGestureRecognizer.translation(in: superview!)
if fabs(translation.x) > fabs(translation.y) {
return true
}
return false
}
return false
}
}
| e575b1e68cf201b658df52ac74113d9d | 30.453608 | 98 | 0.603409 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/NewVersion/Discover/ZSDiscoverViewController.swift | mit | 1 | //
// ZSDiscoverViewController.swift
// ZSDiscover
//
// Created by caony on 2019/6/18.
//
import UIKit
enum ZSDiscover {
case rank(time:TimeInterval,token:String,userId:String,packageName:String)
case booklist(time:TimeInterval,token:String,userId:String,packageName:String)
case vip(time:TimeInterval,token:String,packageName:String)
case free(time:TimeInterval,token:String,packageName:String)
case cartoon(time:TimeInterval,token:String,userId:String,packageName:String)
case exclusiveList(time:TimeInterval,token:String,packageName:String)
var url:String {
switch self {
case let .rank(time, token, userId, packageName):
return "https://h5.zhuishushenqi.com/v2/ranking.html?timestamp=\(time)&platform=ios&gender=female&version=14&token=\(token)&userId=\(userId)&packageName=\(packageName)"
case let .booklist(time, token, userId, packageName):
return "https://h5.zhuishushenqi.com/v2/booklist.html?timestamp=\(time)&platform=ios&gender=female&version=14&token=\(token)&userId=\(userId)&packageName=\(packageName)"
case let .vip(time, token, packageName):
return "https://h5.zhuishushenqi.com/v2/vip3.html?posCode=B1&id=f3ac27f5c72542b897a8d9ad0632ab32&platform=ios&gender=female&timeInterval=\(time * 1000)&token=\(token)×tamp=\(time)&version=14&packageName=\(packageName)"
case let .free(time, token, packageName):
return "https://h5.zhuishushenqi.com/v2/free.html?posCode=B1&id=a4c7b8b791044c9abc413c277dd0b2f3&platform=ios&gender=female&timeInterval=\(time * 1000)&token=\(token)×tamp=\(time)&version=14&packageName=\(packageName)"
case let .cartoon(time, token, userId, packageName):
return "https://h5.zhuishushenqi.com/v2/cartoon.html?id=5a04005af958913a73b2ecdc&platform=ios×tamp=\(time)&gender=female&version=14&token=\(token)&userId=\(userId)&packageName=\(packageName)"
case let .exclusiveList(time, token, packageName):
return "https://h5.zhuishushenqi.com/v2/exclusiveList.html?token=\(token)×tamp=\(time)&gender=female&version=14&platform=ios&packageName=\(packageName)"
default:
return ""
}
}
}
class ZSDiscoverViewController: BaseViewController, ZSDiscoverNavigationBarDelegate, UITableViewDataSource, UITableViewDelegate {
lazy var navgationBar:ZSDiscoverNavigationBar = {
let nav = ZSDiscoverNavigationBar(frame: .zero)
nav.delegate = self
return nav
}()
lazy var tableView:UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.sectionHeaderHeight = 0.01
tableView.sectionFooterHeight = 0.01
if #available(iOS 11, *) {
tableView.contentInsetAdjustmentBehavior = .never
}
tableView.qs_registerCellClass(UITableViewCell.self)
tableView.qs_registerHeaderFooterClass(ZSDiscoverHeaderView.self)
let blurEffect = UIBlurEffect(style: .extraLight)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
tableView.backgroundView = blurEffectView
return tableView
}()
var menus:[ZSDiscoverItem] = []
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(navgationBar)
view.addSubview(tableView)
navgationBar.snp.remakeConstraints { (make) in
make.left.top.right.equalToSuperview()
make.height.equalTo(kNavgationBarHeight)
}
tableView.snp.remakeConstraints { (make) in
make.left.right.equalToSuperview()
make.top.equalTo(kNavgationBarHeight)
make.height.equalTo(ScreenHeight - kNavgationBarHeight - kTabbarBlankHeight - FOOT_BAR_Height)
}
setupMenus()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isNavigationBarHidden = true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func setupMenus() {
let vipItem = ZSDiscoverItem(type: .vip, title: "VIP专区", icon: "discover_icon_vip_26_26_26x26_")
let freeItem = ZSDiscoverItem(type: .free, title: "免费专区", icon: "discover_icon_free_26_26_26x26_")
let manhuaItem = ZSDiscoverItem(type: .manhua, title: "漫画专区", icon: "discover_icon_comics_26_26_26x26_")
let audioItem = ZSDiscoverItem(type: .vip, title: "有声小说", icon: "discover_icon_audiobook_26_26_26x26_")
let ramdomItem = ZSDiscoverItem(type: .vip, title: "随机看书", icon: "discover_icon_random_26_26_26x26_")
let personalItem = ZSDiscoverItem(type: .personal, title: "专属定制", icon: "discover_icon_exclusive_26_26_26x26_")
let huntItem = ZSDiscoverItem(type: .vip, title: "书荒互助", icon: "personal_icon_huntbook_24_24_24x24_")
menus.append(vipItem)
menus.append(freeItem)
menus.append(manhuaItem)
menus.append(audioItem)
menus.append(ramdomItem)
menus.append(personalItem)
menus.append(huntItem)
}
func jumpTo(index:Int) {
let timeInterval = Date().timeIntervalSince1970
var url:String = ""
var title:String = ""
if index == 0 {
let catelogVC = ZSCatelogViewController()
catelogVC.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(catelogVC, animated: true)
return
} else if index == 1 {
url = ZSDiscover.rank(time: timeInterval, token: ZSLogin.share.token, userId: ZSLogin.share.userInfo()?.user?._id ?? "", packageName: "com.ifmoc.ZhuiShuShenQi").url
title = "排行"
} else if index == 2 {
url = ZSDiscover.booklist(time: timeInterval, token: ZSLogin.share.token, userId: ZSLogin.share.userInfo()?.user?._id ?? "", packageName: "com.ifmoc.ZhuiShuShenQi").url
title = "书单"
}
jump(url: url, title: title)
}
func jump(url:String, title:String) {
let webVC = ZSWebViewController()
webVC.hidesBottomBarWhenPushed = true
webVC.url = url
webVC.title = title
navigationController?.pushViewController(webVC, animated: true)
}
//MARK: - ZSDiscoverNavigationBarDelegate
func nav(nav: ZSDiscoverNavigationBar, didClickSearch: UIButton) {
let searchVC = ZSSearchViewController()
searchVC.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(searchVC, animated: true)
}
//MARK - UITableViewDataSource, UITableViewDelegate
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menus.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.qs_dequeueReusableHeaderFooterView(ZSDiscoverHeaderView.self)
headerView?.handler = { [weak self] index in
self?.jumpTo(index: index)
}
return headerView
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.qs_dequeueReusableCell(UITableViewCell.self)
let menuItem = menus[indexPath.row]
cell?.imageView?.image = UIImage(named: "\(menuItem.icon ?? "")")
cell?.textLabel?.text = "\(menuItem.title ?? "")"
cell?.accessoryType = .disclosureIndicator
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let menuItem = menus[indexPath.row]
switch menuItem.type {
case .vip:
let timeInterval = Date().timeIntervalSince1970
let url = ZSDiscover.vip(time: timeInterval, token: ZSLogin.share.token, packageName: "com.ifmoc.ZhuiShuShenQi").url
jump(url: url, title: menuItem.title ?? "")
break
case .free:
let timeInterval = Date().timeIntervalSince1970
let url = ZSDiscover.free(time: timeInterval, token: ZSLogin.share.token, packageName: "com.ifmoc.ZhuiShuShenQi").url
jump(url: url, title: menuItem.title ?? "")
break
case .manhua:
let timeInterval = Date().timeIntervalSince1970
let url = ZSDiscover.cartoon(time: timeInterval, token: ZSLogin.share.token, userId: ZSLogin.share.userInfo()?.user?._id ?? "", packageName: "com.ifmoc.ZhuiShuShenQi").url
jump(url: url, title: menuItem.title ?? "")
break
case .personal:
let timeInterval = Date().timeIntervalSince1970
let url = ZSDiscover.exclusiveList(time: timeInterval, token: ZSLogin.share.token, packageName: "com.ifmoc.ZhuiShuShenQi").url
jump(url: url, title: menuItem.title ?? "")
break
default:
break
}
}
}
| c60908e951b9bce6d7efc7d41073d5be | 44.863415 | 235 | 0.65986 | false | false | false | false |
tectijuana/iOS | refs/heads/master | PáramoAimeé/Practicas Libro/2 Ejercicio.swift | mit | 2 | //Para leer el teclado
func input() ->NSString {
var keyboard = NSFileHandle.fileHandleWithStandardInput()
var inputData = keyboard.availableData
return NSString(data: inputData, encoding:NSUTF8StringEncoding)!
}
println("Ingresa un número")
var num1 = input()
var a=Int(0)
var i
var n
for value i=1; i<(n+1); ++i{
if var a!=2{
print("No es primo")
}
else{
print("Si es primo")
}
}
| 476f14627540be7d9237bc1e2114ce6b | 17.347826 | 68 | 0.651659 | false | false | false | false |
ainopara/Stage1st-Reader | refs/heads/master | Stage1st/Manager/EventTracker.swift | bsd-3-clause | 1 | //
// EventTracker.swift
// Stage1st
//
// Created by Zheng Li on 2018/10/3.
// Copyright © 2018 Renaissance. All rights reserved.
//
import Sentry
protocol EventTracker {
func recordAssertionFailure(_ error: Error)
func recordError(_ error: Error)
func recordError(_ error: Error, withAdditionalUserInfo userInfo: [String: Any]?)
func logEvent(_ name: String)
func logEvent(_ name: String, attributes: [String: String]?)
func logEvent(_ name: String, uploadImmediately: Bool)
func logEvent(_ name: String, attributes: [String: String]?, uploadImmediately: Bool)
func setObjectValue(_ value: String, forKey key: String)
}
class S1EventTracker: EventTracker {
private(set) var extraInfo: [String: String] = [:]
func recordAssertionFailure(_ error: Error) {
recordError(error, withAdditionalUserInfo: nil, level: .error)
}
func recordError(_ error: Error) {
recordError(error, withAdditionalUserInfo: nil, level: .warning)
}
func recordError(_ error: Error, withAdditionalUserInfo userInfo: [String: Any]?) {
recordError(error, withAdditionalUserInfo: userInfo, level: .warning)
}
func recordError(_ error: Error, withAdditionalUserInfo userInfo: [String: Any]?, level: SentryLevel) {
let extraInfoSnapshot = self.extraInfo
let event = Event(level: .warning)
let nsError = error as NSError
let message = "\(nsError.domain):\(nsError.code)"
event.message = SentryMessage(formatted: message)
event.extra = nsError.userInfo
.merging(userInfo ?? [:], uniquingKeysWith: { $1 })
.merging(extraInfoSnapshot, uniquingKeysWith: { $1 })
event.fingerprint = [message]
SentrySDK.capture(event: event)
}
func logEvent(_ name: String) {
self.logEvent(name, attributes: nil, uploadImmediately: false)
}
func logEvent(_ name: String, attributes: [String: String]?) {
self.logEvent(name, attributes: attributes, uploadImmediately: false)
}
func logEvent(_ name: String, uploadImmediately: Bool) {
self.logEvent(name, attributes: nil, uploadImmediately: uploadImmediately)
}
func logEvent(_ name: String, attributes: [String: String]?, uploadImmediately: Bool) {
let event = Event(level: .info)
event.message = SentryMessage(formatted: name)
event.tags = attributes
// Assigning an empty breadcrumbs will prevent client from attching stored breadcrumbs to this event
event.breadcrumbs = []
// Assigning threads and debugMeta will prevent client from generating threads and debugMeta for this event
event.threads = [Sentry.Thread(threadId: 0)]
event.debugMeta = [DebugMeta()]
SentrySDK.capture(event: event)
}
func setObjectValue(_ value: String, forKey key: String) {
extraInfo[key] = value
}
}
| 852559766469a41489cb0abd64b63c24 | 34.609756 | 115 | 0.671233 | false | false | false | false |
vitormesquita/Malert | refs/heads/master | Malert/Classes/MalertButtonView/MalertAction.swift | mit | 1 | //
// MalertAction.swift
// Malert
//
// Created by Vitor Mesquita on 16/07/2018.
//
import UIKit
/// Class to build `MalertButtonView`
public class MalertAction {
var title: String
var actionBlock: (() -> ())?
public var tintColor: UIColor?
public var backgroundColor: UIColor?
public var cornerRadius: CGFloat?
public var borderColor: UIColor?
public var borderWidth: CGFloat?
public init(title: String, actionBlock: (() -> ())? = nil) {
self.title = title
self.actionBlock = actionBlock
}
public init(title: String, backgroundColor: UIColor, actionBlock: (() -> ())? = nil) {
self.title = title
self.backgroundColor = backgroundColor
self.actionBlock = actionBlock
}
}
| 298d79f27231ce1847006f50fe3f851e | 23.40625 | 90 | 0.62612 | false | false | false | false |
SASAbus/SASAbus-ios | refs/heads/master | SASAbus/Data/Networking/RealTimeDataApiRouter.swift | gpl-3.0 | 1 | //
// RealTimeDataApiRouter.swift
// SASAbus
//
// Copyright (C) 2011-2015 Raiffeisen Online GmbH (Norman Marmsoler, Jürgen Sprenger, Aaron Falk) <[email protected]>
//
// This file is part of SASAbus.
//
// SASAbus is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SASAbus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SASAbus. If not, see <http://www.gnu.org/licenses/>.
//
import Alamofire
enum RealTimeDataApiRouter: URLRequestConvertible {
static let baseURLString = Configuration.realTimeDataUrl
// APIs exposed
case GetPositions()
case GetPositionForLineVariants([String])
case GetPositionForVehiclecode(Int)
var method: Alamofire.Method {
switch self {
case .GetPositions:
return .GET
case .GetPositionForLineVariants:
return .GET
case .GetPositionForVehiclecode:
return .GET
}
}
var path: String {
switch self {
case .GetPositions:
return "positions"
case .GetPositionForLineVariants(let lineVariants):
let param = lineVariants.joinWithSeparator(",")
return "positions?lines=\(param)"
case .GetPositionForVehiclecode(let vehiclecode):
return "positions?vehiclecode=\(vehiclecode)"
}
}
// MARK: URLRequestConvertible
var URLRequest: NSMutableURLRequest {
let URL = NSURL(string: RealTimeDataApiRouter.baseURLString + path)!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = method.rawValue
mutableURLRequest.timeoutInterval = Configuration.timeoutInterval
return mutableURLRequest
}
} | ed32f7a06005d9dbe41c58d855d20c26 | 32.338462 | 118 | 0.686057 | false | false | false | false |
hi-hu/Hu-Facebook | refs/heads/master | Hu-Facebook/HomeFeedViewController.swift | mit | 1 | //
// HomeFeedViewController.swift
// Hu-Facebook
//
// Created by Hi_Hu on 2/24/15.
// Copyright (c) 2015 hi_hu. All rights reserved.
//
import UIKit
class HomeFeedViewController: UIViewController, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate, UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var homeFeedImage: UIImageView!
@IBOutlet weak var wedding1: UIImageView!
@IBOutlet weak var wedding2: UIImageView!
@IBOutlet weak var wedding3: UIImageView!
@IBOutlet weak var wedding4: UIImageView!
@IBOutlet weak var wedding5: UIImageView!
var selectedImageView: UIImageView!
var isPresenting: Bool = true
var pageIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize = homeFeedImage.frame.size
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func imageDidTap(sender: UITapGestureRecognizer) {
selectedImageView = sender.view as UIImageView
// determine which image was selected
if(selectedImageView.isEqual(wedding1)) {
pageIndex = 0
} else if(selectedImageView.isEqual(wedding2)) {
pageIndex = 1
} else if(selectedImageView.isEqual(wedding3)) {
pageIndex = 2
} else if(selectedImageView.isEqual(wedding4)) {
pageIndex = 3
} else {
pageIndex = 4
}
performSegueWithIdentifier("photoSegue", sender: self)
}
/* Custom Transition Animations
----------------------------------------------------------------------------*/
// transition delegate methods
func animationControllerForPresentedController(presented: UIViewController!, presentingController presenting: UIViewController!, sourceController source: UIViewController!) -> UIViewControllerAnimatedTransitioning! {
isPresenting = true
return self
}
// transition delegate methods
func animationControllerForDismissedController(dismissed: UIViewController!) -> UIViewControllerAnimatedTransitioning! {
isPresenting = false
return self
}
// The value here should be the duration of the animations scheduled in the animationTransition method
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.4
}
// the methods that actually control the transitions
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// unque values to transitions
var containerView = transitionContext.containerView()
var toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
var fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
// getting the position and size of the frame from selectedImageView
var newFrame = containerView.convertRect(selectedImageView.frame, fromView: scrollView)
// present transition animation
if (isPresenting) {
var photoViewController = toViewController as PhotoViewController
var endFrame = photoViewController.endFrame
containerView.addSubview(toViewController.view)
// set all the transitions before hand
toViewController.view.alpha = 0
selectedImageView.hidden = true
// hide all the images
photoViewController.wedding1.hidden = true
photoViewController.wedding2.hidden = true
photoViewController.wedding3.hidden = true
photoViewController.wedding4.hidden = true
photoViewController.wedding5.hidden = true
// making a copy of the selected image view and setting the same size
var movingImageView = UIImageView(image: selectedImageView.image)
movingImageView.frame = newFrame // position & size
movingImageView.contentMode = selectedImageView.contentMode // e.g. aspect fill
movingImageView.clipsToBounds = selectedImageView.clipsToBounds // bool value for clipping
containerView.addSubview(movingImageView)
UIView.animateWithDuration(0.5, animations: { () -> Void in
toViewController.view.alpha = 1
// animating the copy of selectedImageView image to the photoViewController size and position
movingImageView.frame = endFrame
}) { (finished: Bool) -> Void in
transitionContext.completeTransition(true)
movingImageView.removeFromSuperview()
self.selectedImageView.hidden = false
// show all the images
photoViewController.wedding1.hidden = false
photoViewController.wedding2.hidden = false
photoViewController.wedding3.hidden = false
photoViewController.wedding4.hidden = false
photoViewController.wedding5.hidden = false
}
// dismiss transition animation
} else {
// to and from during the transition are different
var photoViewController = fromViewController as PhotoViewController
// making a copy of the image based on paging and setting the same size and frame
var movingImageView = UIImageView()
switch photoViewController.currentPage {
case 0:
movingImageView = UIImageView(image: photoViewController.wedding1.image)
newFrame = containerView.convertRect(wedding1.frame, fromView: scrollView)
case 1:
movingImageView = UIImageView(image: photoViewController.wedding2.image)
newFrame = containerView.convertRect(wedding2.frame, fromView: scrollView)
case 2:
movingImageView = UIImageView(image: photoViewController.wedding3.image)
newFrame = containerView.convertRect(wedding3.frame, fromView: scrollView)
case 3:
movingImageView = UIImageView(image: photoViewController.wedding4.image)
newFrame = containerView.convertRect(wedding4.frame, fromView: scrollView)
case 4:
movingImageView = UIImageView(image: photoViewController.wedding5.image)
newFrame = containerView.convertRect(wedding5.frame, fromView: scrollView)
default:
break
}
movingImageView.frame = photoViewController.scrolledPhotoFrame // position & size
movingImageView.contentMode = selectedImageView.contentMode // e.g. aspect fill
movingImageView.clipsToBounds = selectedImageView.clipsToBounds // bool value for clipping
containerView.addSubview(movingImageView)
UIView.animateWithDuration(0.5, animations: { () -> Void in
fromViewController.view.alpha = 0
// animating the copy of photoViewController image back to the selectedImageView size and position
movingImageView.frame = newFrame
}) { (finished: Bool) -> Void in
transitionContext.completeTransition(true)
fromViewController.view.removeFromSuperview()
movingImageView.removeFromSuperview()
self.selectedImageView.hidden = false
}
}
}
//-----------------------------------------------------------------------------
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var destinationViewController = segue.destinationViewController as PhotoViewController
// calculating the size and position of the final frame size and position of the image in photoViewController
var frameHeight = (320 * selectedImageView.image!.size.height) / selectedImageView.image!.size.width
var endFrame = CGRect(x: 0, y: (view.frame.size.height - frameHeight) / 2, width: 320, height: frameHeight )
// passing the photo and end frame data to photoViewController
destinationViewController.w1 = wedding1.image
destinationViewController.w2 = wedding2.image
destinationViewController.w3 = wedding3.image
destinationViewController.w4 = wedding4.image
destinationViewController.w5 = wedding5.image
destinationViewController.endFrame = endFrame
destinationViewController.pageIndex = pageIndex
destinationViewController.modalPresentationStyle = UIModalPresentationStyle.Custom
destinationViewController.transitioningDelegate = self
}
}
| aa882bbde93fbe69961d0c1f46aa3325 | 44.161765 | 220 | 0.642136 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | refs/heads/master | nRF Toolbox/Profiles/Template/PeripheralManager.swift | bsd-3-clause | 1 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
import CoreBluetooth
enum PeripheralStatus: CustomDebugStringConvertible, Equatable {
case poweredOff
case unauthorized
case connecting
case connected(CBPeripheral)
case disconnected(Error?)
case discoveringServicesAndCharacteristics
case discoveredRequiredServicesAndCharacteristics
static func ==(lhs: PeripheralStatus, rhs: PeripheralStatus) -> Bool {
switch (lhs, rhs) {
case (.poweredOff, poweredOff): return true
case (.unauthorized, .unauthorized): return true
case (.connecting, .connecting): return true
case (.connected(let p1), .connected(let p2)): return p1 == p2
case (.disconnected, .disconnected): return true
case (.discoveringServicesAndCharacteristics, .discoveringServicesAndCharacteristics): return true
case (.discoveredRequiredServicesAndCharacteristics, .discoveredRequiredServicesAndCharacteristics): return true
default: return false
}
}
var debugDescription: String {
switch self {
case .connecting: return "connecting"
case .connected(let p): return "connected to \(p.name ?? "__unnamed__")"
case .disconnected: return "disconnected"
case .poweredOff: return "powered off"
case .unauthorized: return "unauthorized"
case .discoveringServicesAndCharacteristics: return "discovering services"
case .discoveredRequiredServicesAndCharacteristics: return "discovered required services"
}
}
}
protocol StatusDelegate {
func statusDidChanged(_ status: PeripheralStatus)
}
protocol PeripheralListDelegate {
func peripheralsFound(_ peripherals: [DiscoveredPeripheral])
}
protocol PeripheralConnectionDelegate {
func scan(peripheral: PeripheralDescription)
func connect(peripheral: DiscoveredPeripheral)
func closeConnection(peripheral: CBPeripheral)
}
struct ConnectionTimeoutError: ReadableError {
var title: String {
"Connection Timeout"
}
var readableMessage: String
}
class PeripheralManager: NSObject {
private let manager: CBCentralManager
private var peripherals: Set<CBPeripheral> = []
private var timer: Timer?
var delegate: StatusDelegate?
var peripheralListDelegate: PeripheralListDelegate?
var connectingPeripheral: CBPeripheral?
var status: PeripheralStatus = .disconnected(nil) {
didSet {
self.delegate?.statusDidChanged(status)
}
}
init(peripheral: PeripheralDescription, manager: CBCentralManager = CBCentralManager()) {
self.manager = manager
super.init()
self.manager.delegate = self
}
func connect(peripheral: Peripheral) {
let uuid = peripheral.peripheral.identifier
guard let p = manager.retrievePeripherals(withIdentifiers: [uuid]).first else {
return
}
connectingPeripheral = p
manager.connect(p, options: nil)
self.status = .connecting
timer = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: false, block: { [weak self] (_) in
self?.closeConnection(peripheral: p)
let error = ConnectionTimeoutError(readableMessage: "Check your device, or try to restart Bluetooth in Settings.")
self?.status = .disconnected(error)
})
}
}
extension PeripheralManager: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if #available(iOS 13, *) {
switch central.authorization {
case .denied, .restricted:
self.status = .unauthorized
return
default:
break
}
}
switch central.state {
case .poweredOff:
self.status = .poweredOff
case .poweredOn:
self.status = .disconnected(nil)
case .unauthorized:
self.status = .unauthorized
default:
break
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
SystemLog(category: .ble, type: .debug).log(message: "Discovered peripheral: \(advertisementData[CBAdvertisementDataLocalNameKey] as? String ?? "__unnamed__")")
peripherals.insert(peripheral)
peripheralListDelegate?.peripheralsFound(peripherals.map { DiscoveredPeripheral(with: $0, RSSI: RSSI.int32Value) } )
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
SystemLog(category: .ble, type: .debug).log(message: "Connected to device: \(peripheral.name ?? "__unnamed__")")
status = .connected(peripheral)
timer?.invalidate()
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
SystemLog(category: .ble, type: .error).log(message: error?.localizedDescription ?? "Failed to Connect: (no message)")
timer?.invalidate()
let e: Error? = error ?? QuickError(message: "Unable to connect")
status = .disconnected(e)
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
SystemLog(category: .ble, type: .debug).log(message: "Disconnected peripheral: \(peripheral)")
error.map { SystemLog(category: .ble, type: .error).log(message: "Disconnected peripheral with error: \($0.localizedDescription)") }
status = .disconnected(error)
timer?.invalidate()
}
}
extension PeripheralManager: PeripheralConnectionDelegate {
func scan(peripheral: PeripheralDescription) {
manager.scanForPeripherals(withServices: peripheral.uuid.flatMap { [$0] }, options: [CBCentralManagerScanOptionAllowDuplicatesKey:true])
}
func closeConnection(peripheral: CBPeripheral) {
manager.cancelPeripheralConnection(peripheral)
}
func connect(peripheral: DiscoveredPeripheral) {
manager.connect(peripheral.peripheral, options: nil)
manager.stopScan()
}
}
| 9c44402d5e3c2b69c434584358e93270 | 37.9 | 168 | 0.694602 | false | false | false | false |
swordfishyou/fieldstool | refs/heads/master | FieldTool/Sources/Extensions/UIColor+Hex.swift | mit | 1 | //
// UIColor+Hex.swift
// FieldTool
//
// Created by Anatoly Tukhtarov on 2/19/17.
// Copyright © 2017 Anatoly Tukhtarov. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init?(hexString: String) {
let r, g, b: CGFloat
if hexString.hasPrefix("#") {
let start = hexString.index(hexString.startIndex, offsetBy: 1)
let hexColor = hexString.substring(from: start)
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
self.init(red: r, green: g, blue: b, alpha: 1.0)
return
}
}
return nil
}
}
| 86f52b598ca98d0b729d33d2058efdfc | 27.676471 | 74 | 0.518974 | false | false | false | false |
el-hoshino/NotAutoLayout | refs/heads/master | Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/RightMiddleWidth.Individual.swift | apache-2.0 | 1 | //
// RightMiddleWidth.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct RightMiddleWidth {
let right: LayoutElement.Horizontal
let middle: LayoutElement.Vertical
let width: LayoutElement.Length
}
}
// MARK: - Make Frame
extension IndividualProperty.RightMiddleWidth {
private func makeFrame(right: Float, middle: Float, width: Float, height: Float) -> Rect {
let x = right - width
let y = middle - height.half
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Height
extension IndividualProperty.RightMiddleWidth: LayoutPropertyCanStoreHeightToEvaluateFrameType {
public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let right = self.right.evaluated(from: parameters)
let middle = self.middle.evaluated(from: parameters)
let width = self.width.evaluated(from: parameters, withTheOtherAxis: .height(0))
let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width))
return self.makeFrame(right: right, middle: middle, width: width, height: height)
}
}
| 0df396d9070183210f9ab48efa8c49e7 | 22.763636 | 116 | 0.725325 | false | false | false | false |
buguanhu/THLiveSmart | refs/heads/master | Carthage/Checkouts/ReactiveCocoa/ReactiveCocoa/Swift/Observer.swift | apache-2.0 | 8 | //
// Observer.swift
// ReactiveCocoa
//
// Created by Andy Matuschak on 10/2/15.
// Copyright © 2015 GitHub. All rights reserved.
//
/// A protocol for type-constrained extensions of `Observer`.
public protocol ObserverType {
associatedtype Value
associatedtype Error: ErrorType
/// Puts a `Next` event into `self`.
func sendNext(value: Value)
/// Puts a `Failed` event into `self`.
func sendFailed(error: Error)
/// Puts a `Completed` event into `self`.
func sendCompleted()
/// Puts an `Interrupted` event into `self`.
func sendInterrupted()
}
/// An Observer is a simple wrapper around a function which can receive Events
/// (typically from a Signal).
public struct Observer<Value, Error: ErrorType> {
public typealias Action = Event<Value, Error> -> Void
/// An action that will be performed upon arrival of the event.
public let action: Action
/// An initializer that accepts a closure accepting an event for the
/// observer.
///
/// - parameters:
/// - action: A closure to lift over received event.
public init(_ action: Action) {
self.action = action
}
/// An initializer that accepts closures for different event types.
///
/// - parameters:
/// - failed: Optional closure that accepts an `Error` parameter when a
/// `Failed` event is observed.
/// - completed: Optional closure executed when a `Completed` event is
/// observed.
/// - interruped: Optional closure executed when an `Interrupted` event is
/// observed.
/// - next: Optional closure executed when a `Next` event is observed.
public init(failed: (Error -> Void)? = nil, completed: (() -> Void)? = nil, interrupted: (() -> Void)? = nil, next: (Value -> Void)? = nil) {
self.init { event in
switch event {
case let .Next(value):
next?(value)
case let .Failed(error):
failed?(error)
case .Completed:
completed?()
case .Interrupted:
interrupted?()
}
}
}
}
extension Observer: ObserverType {
/// Puts a `Next` event into `self`.
///
/// - parameters:
/// - value: A value sent with the `Next` event.
public func sendNext(value: Value) {
action(.Next(value))
}
/// Puts a `Failed` event into `self`.
///
/// - parameters:
/// - error: An error object sent with `Failed` event.
public func sendFailed(error: Error) {
action(.Failed(error))
}
/// Puts a `Completed` event into `self`.
public func sendCompleted() {
action(.Completed)
}
/// Puts an `Interrupted` event into `self`.
public func sendInterrupted() {
action(.Interrupted)
}
}
| 005e47792649ac85dd9269711725d4d1 | 25.090909 | 142 | 0.651955 | false | false | false | false |
siberianisaev/NeutronBarrel | refs/heads/master | NeutronBarrel/FileManager.swift | mit | 1 | //
// FileManager.swift
// NeutronBarrel
//
// Created by Andrey Isaev on 27.12.14.
// Copyright (c) 2018 Flerov Laboratory. All rights reserved.
//
import Foundation
class FileManager {
fileprivate class func desktopFolder() -> NSString? {
return NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true).first as NSString?
}
fileprivate class func createIfNeedsDirectoryAtPath(_ path: String?) {
if let path = path {
let fm = Foundation.FileManager.default
if false == fm.fileExists(atPath: path) {
do {
try fm.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
} catch {
print(error)
}
}
}
}
class func pathForDesktopFolder(_ folderName: String?) -> NSString? {
var path: NSString?
if let fn = folderName, fn.contains("/") { // User select custom path to directory
path = fn as NSString
} else { // Use Desktop folder by default
path = self.desktopFolder()
if let folderName = folderName {
path = path?.appendingPathComponent(folderName) as NSString?
}
}
createIfNeedsDirectoryAtPath(path as String?)
return path
}
fileprivate class func filePathWithName(_ fileName: String, folderName: String?) -> String? {
return pathForDesktopFolder(folderName)?.appendingPathComponent(fileName)
}
fileprivate class func fileName(prefix: String, folderName: String, timeStamp: String, postfix: String? = nil, fileExtension: String) -> String {
let lastFolder = (folderName as NSString).lastPathComponent
var components = [prefix, lastFolder]
if lastFolder != timeStamp {
components.append(timeStamp)
}
if let postfix = postfix {
components.append(postfix)
}
return components.joined(separator: "_") + "." + fileExtension
}
class func resultsFilePath(_ timeStamp: String, folderName: String) -> String? {
let name = fileName(prefix: "results", folderName: folderName, timeStamp: timeStamp, fileExtension: "csv")
return filePathWithName(name, folderName: folderName)
}
class func filePath(_ prefix: String, timeStamp: String, folderName: String) -> String? {
let name = fileName(prefix: prefix, folderName: folderName, timeStamp: timeStamp, fileExtension: "csv")
return filePathWithName(name, folderName: folderName)
}
class func statisticsFilePath(_ timeStamp: String, folderName: String) -> String? {
let name = fileName(prefix: "statistics", folderName: folderName, timeStamp: timeStamp, fileExtension: "csv")
return filePathWithName(name, folderName: folderName)
}
class func settingsFilePath(_ timeStamp: String, folderName: String) -> String? {
let name = fileName(prefix: "settings", folderName: folderName, timeStamp: timeStamp, fileExtension: "ini")
return filePathWithName(name, folderName: folderName)
}
class func inputFilePath(_ timeStamp: String, folderName: String, onEnd: Bool) -> String? {
let postfix = onEnd ? "end" : "start"
let name = fileName(prefix: "input", folderName: folderName, timeStamp: timeStamp, postfix: postfix, fileExtension: "png")
return filePathWithName(name, folderName: folderName)
}
class func multiplicityFilePath(_ timeStamp: String, folderName: String) -> String? {
let name = fileName(prefix: "multiplicity", folderName: folderName, timeStamp: timeStamp, fileExtension: "txt")
return filePathWithName(name, folderName: folderName)
}
class func calibrationFilePath(_ timeStamp: String, folderName: String) -> String? {
let name = fileName(prefix: "calibration", folderName: folderName, timeStamp: timeStamp, fileExtension: "txt")
return filePathWithName(name, folderName: folderName)
}
}
| e6c74b7240fb99e1131301c1e488fe2b | 41.78125 | 149 | 0.648892 | false | false | false | false |
dsxNiubility/SXSwiftWeibo | refs/heads/master | 103 - swiftWeibo/103 - swiftWeibo/Classes/UI/OAuth/OAuthViewController.swift | mit | 1 | import UIKit
import SXSwiftJ2M
// 定义全局常量
let WB_Login_Successed_Notification = "WB_Login_Successed_Notification"
class OAuthViewController: UIViewController {
let WB_API_URL_String = "https://api.weibo.com"
let WB_Redirect_URL_String = "http://www.baidu.com"
let WB_Client_ID = "258115387"
let WB_Client_Secret = "e6bc5950db8f4a041f09bd6ebeca8ec9"
let WB_Grant_Type = "authorization_code"
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
loadAuthPage()
}
/// 加载授权页面
func loadAuthPage() {
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=258115387&redirect_uri=http://www.baidu.com"
let url = NSURL(string: urlString)
webView.loadRequest(NSURLRequest(URL: url!))
}
}
extension OAuthViewController: UIWebViewDelegate {
func webViewDidStartLoad(webView: UIWebView) {
print(__FUNCTION__)
}
func webViewDidFinishLoad(webView: UIWebView) {
print(__FUNCTION__)
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
print(__FUNCTION__)
}
/// 页面重定向
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print(request.URL)
let result = continueWithCode(request.URL!)
if let code = result.code {
print("可以换 accesstoke \(code)")
let params = ["client_id": WB_Client_ID,
"client_secret": WB_Client_Secret,
"grant_type":WB_Grant_Type,
"redirect_uri": WB_Redirect_URL_String,
"code": code]
let net = NetworkManager.sharedManager
net.requestJSON(.POST, "https://api.weibo.com/oauth2/access_token", params) { (result, error) -> () in
print(result)
let token = AccessToken(dict: result as! NSDictionary)
token.saveAccessToken()
// 切换UI - 通知
NSNotificationCenter.defaultCenter().postNotificationName(WB_Login_Successed_Notification, object: nil)
}
}
if !result.load {
print(request.URL)
if result.reloadPage{
SVProgressHUD.showInfoWithStatus("真的要取消么", maskType: SVProgressHUDMaskType.Black)
loadAuthPage()
}
}
return result.load
}
/// 根据 URL 判断是否继续加载页面
/// 返回:是否加载,如果有 code,同时返回 code,否则返回 nil
func continueWithCode(url: NSURL) -> (load: Bool, code: String?, reloadPage: Bool) {
// 1. 将url转换成字符串
let urlString = url.absoluteString
// 2. 如果不是微博的 api 地址,都不加载
if !urlString.hasPrefix(WB_API_URL_String) {
// 3. 如果是回调地址,需要判断 code
if urlString.hasPrefix(WB_Redirect_URL_String) {
if let query = url.query {
let codestr: NSString = "code="
if query.hasPrefix(codestr as String) {
var q = query as NSString!
return (false, q.substringFromIndex(codestr.length),false)
}else {
return (false, nil, true)
}
}
}
return (false, nil,false)
}
return (true, nil,false)
}
}
| ebf3035bdc5d22ac0f7771ea06af72a8 | 30.318966 | 137 | 0.539774 | false | false | false | false |
ben-ng/swift | refs/heads/master | stdlib/public/core/CString.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// String interop with C
//===----------------------------------------------------------------------===//
import SwiftShims
extension String {
/// Creates a new string by copying the null-terminated UTF-8 data referenced
/// by the given pointer.
///
/// If `cString` contains ill-formed UTF-8 code unit sequences, this
/// initializer replaces them with the Unicode replacement character
/// (`"\u{FFFD}"`).
///
/// The following example calls this initializer with pointers to the
/// contents of two different `CChar` arrays---the first with well-formed
/// UTF-8 code unit sequences and the second with an ill-formed sequence at
/// the end.
///
/// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
/// validUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(cString: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "Café"
///
/// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
/// invalidUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(cString: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "Caf�"
///
/// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence.
public init(cString: UnsafePointer<CChar>) {
let len = UTF8._nullCodeUnitOffset(in: cString)
let (result, _) = cString.withMemoryRebound(to: UInt8.self, capacity: len) {
_decodeCString($0, as: UTF8.self, length: len,
repairingInvalidCodeUnits: true)!
}
self = result
}
/// Creates a new string by copying the null-terminated UTF-8 data referenced
/// by the given pointer.
///
/// This is identical to init(cString: UnsafePointer<CChar> but operates on an
/// unsigned sequence of bytes.
public init(cString: UnsafePointer<UInt8>) {
self = String.decodeCString(cString, as: UTF8.self,
repairingInvalidCodeUnits: true)!.result
}
/// Creates a new string by copying and validating the null-terminated UTF-8
/// data referenced by the given pointer.
///
/// This initializer does not try to repair ill-formed UTF-8 code unit
/// sequences. If any are found, the result of the initializer is `nil`.
///
/// The following example calls this initializer with pointers to the
/// contents of two different `CChar` arrays---the first with well-formed
/// UTF-8 code unit sequences and the second with an ill-formed sequence at
/// the end.
///
/// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
/// validUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(validatingUTF8: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "Optional(Café)"
///
/// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
/// invalidUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(validatingUTF8: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "nil"
///
/// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence.
public init?(validatingUTF8 cString: UnsafePointer<CChar>) {
let len = UTF8._nullCodeUnitOffset(in: cString)
guard let (result, _) =
cString.withMemoryRebound(to: UInt8.self, capacity: len, {
_decodeCString($0, as: UTF8.self, length: len,
repairingInvalidCodeUnits: false)
})
else {
return nil
}
self = result
}
/// Creates a new string by copying the null-terminated data referenced by
/// the given pointer using the specified encoding.
///
/// When you pass `true` as `isRepairing`, this method replaces ill-formed
/// sequences with the Unicode replacement character (`"\u{FFFD}"`);
/// otherwise, an ill-formed sequence causes this method to stop decoding
/// and return `nil`.
///
/// The following example calls this method with pointers to the contents of
/// two different `CChar` arrays---the first with well-formed UTF-8 code
/// unit sequences and the second with an ill-formed sequence at the end.
///
/// let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0]
/// validUTF8.withUnsafeBufferPointer { ptr in
/// let s = String.decodeCString(ptr.baseAddress,
/// as: UTF8.self,
/// repairingInvalidCodeUnits: true)
/// print(s)
/// }
/// // Prints "Optional((Café, false))"
///
/// let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0]
/// invalidUTF8.withUnsafeBufferPointer { ptr in
/// let s = String.decodeCString(ptr.baseAddress,
/// as: UTF8.self,
/// repairingInvalidCodeUnits: true)
/// print(s)
/// }
/// // Prints "Optional((Caf�, true))"
///
/// - Parameters:
/// - cString: A pointer to a null-terminated code sequence encoded in
/// `encoding`.
/// - encoding: The Unicode encoding of the data referenced by `cString`.
/// - isRepairing: Pass `true` to create a new string, even when the data
/// referenced by `cString` contains ill-formed sequences. Ill-formed
/// sequences are replaced with the Unicode replacement character
/// (`"\u{FFFD}"`). Pass `false` to interrupt the creation of the new
/// string if an ill-formed sequence is detected.
/// - Returns: A tuple with the new string and a Boolean value that indicates
/// whether any repairs were made. If `isRepairing` is `false` and an
/// ill-formed sequence is detected, this method returns `nil`.
///
/// - SeeAlso: `UnicodeCodec`
public static func decodeCString<Encoding : UnicodeCodec>(
_ cString: UnsafePointer<Encoding.CodeUnit>?,
as encoding: Encoding.Type,
repairingInvalidCodeUnits isRepairing: Bool = true)
-> (result: String, repairsMade: Bool)? {
guard let cString = cString else {
return nil
}
let len = encoding._nullCodeUnitOffset(in: cString)
return _decodeCString(cString, as: encoding, length: len,
repairingInvalidCodeUnits: isRepairing)
}
}
/// From a non-`nil` `UnsafePointer` to a null-terminated string
/// with possibly-transient lifetime, create a null-terminated array of 'C' char.
/// Returns `nil` if passed a null pointer.
public func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? {
guard let s = p else {
return nil
}
let count = Int(_swift_stdlib_strlen(s))
var result = [CChar](repeating: 0, count: count + 1)
for i in 0..<count {
result[i] = s[i]
}
return result
}
/// Creates a new string by copying the null-terminated data referenced by
/// the given pointer using the specified encoding.
///
/// This internal helper takes the string length as an argument.
func _decodeCString<Encoding : UnicodeCodec>(
_ cString: UnsafePointer<Encoding.CodeUnit>,
as encoding: Encoding.Type, length: Int,
repairingInvalidCodeUnits isRepairing: Bool = true)
-> (result: String, repairsMade: Bool)? {
let buffer = UnsafeBufferPointer<Encoding.CodeUnit>(
start: cString, count: length)
let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits(
buffer, encoding: encoding, repairIllFormedSequences: isRepairing)
return stringBuffer.map {
(result: String(_storage: $0), repairsMade: hadError)
}
}
extension String {
@available(*, unavailable, message: "Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.")
public static func fromCString(_ cs: UnsafePointer<CChar>) -> String? {
Builtin.unreachable()
}
@available(*, unavailable, message: "Please use String.init(cString:) instead. Note that it no longer accepts NULL as a valid input. See also String.decodeCString if you need more control.")
public static func fromCStringRepairingIllFormedUTF8(
_ cs: UnsafePointer<CChar>
) -> (String?, hadError: Bool) {
Builtin.unreachable()
}
}
| 104ebddaca5f6d94410bca78539aace2 | 39.535545 | 233 | 0.630188 | false | false | false | false |
myandy/shi_ios | refs/heads/master | shishi/UI/Edit/PingzeLinearView.swift | apache-2.0 | 1 | //
// PingzeLinearView.swift
// shishi
//
// Created by andymao on 2017/4/15.
// Copyright © 2017年 andymao. All rights reserved.
//
import Foundation
import UIKit
public class PingzeLinearView : UIView{
var code : String!
// public override func draw(_ rect: CGRect) {
//
// }
public func refresh(code:String){
self.backgroundColor = UIColor.clear
self.code = code
//setNeedsDisplay()
for subview in self.subviews {
subview.removeFromSuperview()
}
if code.isEmpty {
return
}
for i in 0...code.trimmingCharacters(in:NSCharacterSet.newlines).characters.count-1{
let index = code.index(code.startIndex, offsetBy: i)
let c = code[index]
NSLog(String(c))
let frame = CGRect(x:i*20,y:0,width:20,height:20)
if StringUtils.isPurnInt(string:String(c)){
let pingze = PingzeView(frame: frame ,shape:Int(String(c))!)
pingze.backgroundColor=UIColor.clear
addSubview(pingze)
pingze.snp.makeConstraints({ (maker) in
maker.height.width.equalTo(20)
maker.top.equalToSuperview()
maker.leading.equalToSuperview().offset(i * 20)
})
}
else{
let label = UILabel()
label.frame = frame
label.text=String(c)
label.textColor=UIColor.init(hex6: PingzeView.COLOR_ZE)
addSubview(label)
label.snp.makeConstraints({ (maker) in
maker.height.width.equalTo(20)
maker.top.equalToSuperview()
maker.leading.equalToSuperview().offset(i * 20)
})
}
}
}
// public override func layoutSubviews() {
//
// }
}
| fab55afc7c53c43969af28d2871ac1aa | 27.724638 | 92 | 0.515641 | false | false | false | false |
eurofurence/ef-app_ios | refs/heads/release/4.0.0 | Packages/EurofurenceComponents/Tests/ScheduleComponentTests/View Model Tests/Test Doubles/CapturingScheduleViewModelDelegate.swift | mit | 1 | import EurofurenceModel
import Foundation
import ScheduleComponent
class CapturingScheduleViewModelDelegate: ScheduleViewModelDelegate {
private(set) var viewModelDidBeginRefreshing = false
func scheduleViewModelDidBeginRefreshing() {
viewModelDidBeginRefreshing = true
}
private(set) var viewModelDidFinishRefreshing = false
func scheduleViewModelDidFinishRefreshing() {
viewModelDidFinishRefreshing = true
}
private(set) var daysViewModels: [ScheduleDayViewModel] = []
func scheduleViewModelDidUpdateDays(_ days: [ScheduleDayViewModel]) {
daysViewModels = days
}
private(set) var currentDayIndex: Int?
func scheduleViewModelDidUpdateCurrentDayIndex(to index: Int) {
currentDayIndex = index
}
private(set) var eventsViewModels: [ScheduleEventGroupViewModel] = []
func scheduleViewModelDidUpdateEvents(_ events: [ScheduleEventGroupViewModel]) {
eventsViewModels = events
}
enum FavouritesFilter: Equatable {
case unset
case favouritesOnly
case allEvents
}
private(set) var favouritesfilter: FavouritesFilter = .unset
func scheduleViewModelDidFilterToFavourites() {
favouritesfilter = .favouritesOnly
}
func scheduleViewModelDidRemoveFavouritesFilter() {
favouritesfilter = .allEvents
}
}
| 1d9662d77265b3eab4f8113bb67140c4 | 28.319149 | 84 | 0.722787 | false | false | false | false |
danielhour/PullQuotes_Server | refs/heads/master | Sources/App/Models/Alarm.swift | mit | 1 | //
// Alarm.swift
// App
//
// Created by Daniel Hour on 8/12/17.
//
import Vapor
import FluentProvider
import HTTP
final class Alarm: Model, Timestampable {
//---------------------------------------------------------------------------------------
//MARK: - Properties
let storage = Storage()
var time: String
var userId: Identifier?
var user: Parent<Alarm, User> {
return parent(id: self.userId)
}
static let timeKey = "time"
//---------------------------------------------------------------------------------------
//MARK: - Init
init(row: Row) throws {
self.time = try row.get(Alarm.timeKey)
self.userId = try row.get(User.foreignIdKey)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Alarm.timeKey, self.time)
try row.set(User.foreignIdKey, self.userId)
return row
}
init(time: String) {
self.time = time
}
//---------------------------------------------------------------------------------------
//MARK: - Relationship Methods
func setParent(from request: Request) throws {
let userId = try request.userTokenFromAuthToken()?.userId
self.userId = userId
}
//---------------------------------------------------------------------------------------
//MARK: - Helper Methods
func checkIfAlarmAlreadyExistsWithUser(in request: Request) throws {
let duplicates = try Alarm.makeQuery().filter(Alarm.timeKey, self.time).all()
let userToken = try request.userTokenFromAuthToken()
let userId = userToken?.userId
guard userId != duplicates.first?.userId else {
throw Abort(.badRequest, metadata: "this alarm already exists for this user")
}
}
}
//-------------------------------------------------------------------------------------------
//MARK: - Extensions
extension Alarm: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self, closure: { alarm in
alarm.id()
alarm.string(Alarm.timeKey)
alarm.parent(User.self)
})
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
extension Alarm: JSONConvertible {
convenience init(json: JSON) throws {
self.init(time: try json.get(Alarm.timeKey))
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Alarm.timeKey, self.time)
return json
}
}
extension Alarm: Updateable {
static var updateableKeys: [UpdateableKey<Alarm>] {
let name: UpdateableKey<Alarm> = UpdateableKey(Alarm.timeKey, String.self) { alarm, updatedTime in
alarm.time = updatedTime
}
return [name]
}
}
extension Alarm: ResponseRepresentable { }
| 9bcdded41c53259b05e302ff7875c2b5 | 25.486486 | 106 | 0.501701 | false | false | false | false |
yapmobile/ExpandingMenu | refs/heads/master | ExpandingMenu/Classes/ExpandingMenuItem.swift | mit | 1 | //
// ExpandingMenuButtonItem.swift
//
// Created by monoqlo on 2015/07/17.
// Copyright (c) 2015年 monoqlo All rights reserved.
//
import UIKit
open class ExpandingMenuItem: UIView {
open var title: String? {
get {
return self.titleButton?.titleLabel?.text
}
set {
if let title = newValue {
if let titleButton = self.titleButton {
titleButton.setTitle(title, for: UIControlState())
} else {
self.titleButton = self.createTitleButton(title, titleColor: self.titleColor)
}
self.titleButton?.sizeToFit()
} else {
self.titleButton = nil
}
}
}
open var titleFont: UIFont? {
get {
return self.titleButton?.titleLabel?.font
}
set (newFont) {
if let tb = self.titleButton {
tb.titleLabel?.font = newFont
tb.sizeToFit()
}
}
}
open var titleMargin: CGFloat = 8.0
open var titleColor: UIColor? {
get {
return self.titleButton?.titleColor(for: UIControlState())
}
set {
self.titleButton?.setTitleColor(newValue, for: UIControlState())
}
}
var titleTappedActionEnabled: Bool = true {
didSet {
self.titleButton?.isUserInteractionEnabled = titleTappedActionEnabled
}
}
var index: Int = 0
weak var delegate: ExpandingMenuButton?
fileprivate(set) var titleButton:UIButton?
fileprivate var frontImageView: UIImageView
fileprivate var tappedAction: (() -> Void)?
// MARK: - Initializer
public init(size: CGSize?, title: String? = nil, titleColor: UIColor? = nil, image: UIImage, highlightedImage: UIImage, backgroundImage: UIImage?, backgroundHighlightedImage: UIImage?, itemTapped: (() -> Void)?) {
// Initialize properties
//
self.frontImageView = UIImageView(image: image, highlightedImage: highlightedImage)
self.tappedAction = itemTapped
// Configure frame
//
let itemFrame: CGRect
if let itemSize = size , itemSize != CGSize.zero {
itemFrame = CGRect(x: 0.0, y: 0.0, width: itemSize.width, height: itemSize.height)
} else {
if let bgImage = backgroundImage , backgroundHighlightedImage != nil {
itemFrame = CGRect(x: 0.0, y: 0.0, width: bgImage.size.width, height: bgImage.size.height)
} else {
itemFrame = CGRect(x: 0.0, y: 0.0, width: image.size.width, height: image.size.height)
}
}
super.init(frame: itemFrame)
// Configure base button
//
let baseButton = UIButton()
baseButton.setImage(backgroundImage, for: UIControlState())
baseButton.setImage(backgroundHighlightedImage, for: UIControlState.highlighted)
baseButton.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(baseButton)
self.addConstraint(NSLayoutConstraint(item: baseButton, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: baseButton, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: baseButton, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: baseButton, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0))
// Add an action for the item
//
baseButton.addTarget(self, action: #selector(tapped), for: UIControlEvents.touchUpInside)
// Configure front images
//
self.frontImageView.contentMode = .center
self.frontImageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.frontImageView)
self.addConstraint(NSLayoutConstraint(item: self.frontImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self.frontImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self.frontImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self.frontImageView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0))
// Configure title button
//
if let title = title {
self.titleButton = self.createTitleButton(title, titleColor: titleColor)
}
}
public convenience init(image: UIImage, highlightedImage: UIImage, backgroundImage: UIImage?, backgroundHighlightedImage: UIImage?, itemTapped: (() -> Void)?) {
self.init(size: nil, title: nil, image: image, highlightedImage: highlightedImage, backgroundImage: backgroundImage, backgroundHighlightedImage: backgroundHighlightedImage, itemTapped: itemTapped)
}
public convenience init(title: String, titleColor: UIColor? = nil, image: UIImage, highlightedImage: UIImage, backgroundImage: UIImage?, backgroundHighlightedImage: UIImage?, itemTapped: (() -> Void)?) {
self.init(size: nil, title: title, titleColor: titleColor, image: image, highlightedImage: highlightedImage, backgroundImage: backgroundImage, backgroundHighlightedImage: backgroundHighlightedImage, itemTapped: itemTapped)
}
public convenience init(size: CGSize, image: UIImage, highlightedImage: UIImage, backgroundImage: UIImage?, backgroundHighlightedImage: UIImage?, itemTapped: (() -> Void)?) {
self.init(size: size, title: nil, image: image, highlightedImage: highlightedImage, backgroundImage: backgroundImage, backgroundHighlightedImage: backgroundHighlightedImage, itemTapped: itemTapped)
}
required public init?(coder aDecoder: NSCoder) {
self.frontImageView = UIImageView()
super.init(coder: aDecoder)
}
// MARK: - Title Button
fileprivate func createTitleButton(_ title: String, titleColor: UIColor? = nil) -> UIButton {
let button = UIButton()
button.setTitle(title, for: UIControlState())
button.setTitleColor(titleColor, for: UIControlState())
button.sizeToFit()
button.addTarget(self, action: #selector(tapped), for: UIControlEvents.touchUpInside)
return button
}
// MARK: - Tapped Action
func tapped() {
self.delegate?.menuItemTapped(self)
self.tappedAction?()
}
}
| 222a3b199c44f69748a8c312bd2b71ac | 42.790123 | 230 | 0.641528 | false | false | false | false |
enabledhq/Selfie-Bot | refs/heads/master | Selfie-Bot/ViewController.swift | mit | 1 | //
// ViewController.swift
// Selfie-Bot
//
// Created by Simeon on 17/2/17.
// Copyright © 2017 Enabled. All rights reserved.
//
import UIKit
import SnapKit
import AWSRekognition
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
private let cameraButton = UIButton()
private let selfieBotView = SelfieBotView()
private let chatView = ChatView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .darkGray
let gradient = GradientView(gradient: PXPGradientColor(startingColor: UIColor(white: 0.0, alpha: 0.6), endingColor: UIColor(white: 0.0, alpha: 0.0)), frame: .zero)
gradient.angle = 90.0
view.addSubview(gradient)
gradient.snp.makeConstraints {
make in
make.left.top.right.equalTo(0)
make.bottom.equalTo(view.snp.centerY)
}
view.addSubview(cameraButton)
cameraButton.setTitle("PICS!", for: .normal)
cameraButton.backgroundColor = .black
cameraButton.layer.cornerRadius = 5
cameraButton.snp.makeConstraints {
make in
make.bottom.equalTo(0).inset(10)
make.centerX.equalTo(view)
make.width.equalTo(100)
make.height.equalTo(44)
}
cameraButton.addTarget(self, action: #selector(cameraButtonPressed(_:)), for: .touchUpInside)
view.addSubview(selfieBotView)
selfieBotView.snp.makeConstraints {
make in
make.edges.equalTo(0)
}
chatView.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
view.addSubview(chatView)
chatView.snp.makeConstraints {
make in
make.centerX.equalTo(view)
make.top.equalTo(view).offset(120)
make.width.lessThanOrEqualTo(view).inset(40)
}
let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped(_:)))
view.addGestureRecognizer(tap)
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(viewDoubleTapped(_:)))
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)
}
//MARK: - Actions
@objc private func viewTapped(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: view)
//TODO: point should be converted to selfieBotView coords, but doesn't make a difference in this instance
selfieBotView.lookAt(point: point)
}
private let testWords = ["I DON'T LIKE YOUR FACE", "THIS ONE HAS FLESHY CHEEKS", "UNIMPRESSED", "SELFIE BOT JUDGES YOU... POORLY", "SELFIE BOT HAS MUCH TO COMPLAIN ABOUT THIS LOW QUALITY FACE BUT LACKS THE ROOM IN WHICH TO DO IT", "HA HA HA HA HA HA HA HA HA.\n\nHA HA HA HA"]
private var testWordIndex = 0
@objc private func viewDoubleTapped(_ sender: UITapGestureRecognizer) {
let phrase = testWords[testWordIndex]
let taggerOptions: NSLinguisticTagger.Options = [.omitWhitespace, .omitPunctuation, .omitOther]
let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagSchemeLexicalClass], options: Int(taggerOptions.rawValue))
tagger.string = phrase
var wordCount = 0
print("\nEvaluating phrase")
tagger.enumerateTags(in: NSMakeRange(0, phrase.characters.count), scheme: NSLinguisticTagSchemeLexicalClass, options: taggerOptions) { (tag, tokenRange, _, _) in
print("\((phrase as NSString).substring(with: tokenRange)) - tagged: \(tag)")
wordCount += 1
}
selfieBotView.speakWords(wordCount: wordCount)
chatView.present(phrase, duration: max(TimeInterval(wordCount) * 0.4, 1.0))
testWordIndex = (testWordIndex + 1) % testWords.count
}
@objc private func cameraButtonPressed(_ sender: UIButton) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .camera
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
//MARK: - Image Picker Delegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
selfieBotView.setSnapImage(image.normalizeOrientation())
let data = UIImageJPEGRepresentation(image, 0.7)
let request = AWSRekognitionDetectFacesRequest()
let image = AWSRekognitionImage()
image?.bytes = data
request?.image = image
request?.attributes = ["ALL"]
AWSRekognition.default().detectFaces(request!).continueOnSuccessWith {
$0.result?.faceDetails?.forEach {
print($0.confidence!)
}
}
}
dismiss(animated: true, completion: nil)
}
//MARK: - Status Bar
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
| a660115fd305c7e14a682c0ae04f3e80 | 33.99375 | 280 | 0.613681 | false | false | false | false |
NachoSoto/Decodable | refs/heads/master | Tests/Vehicle.swift | mit | 1 | //
// Vehicle.swift
// Decodable
//
// Created by Charlotte Tortorella on 12/04/2016.
// Copyright © 2016 anviking. All rights reserved.
//
@testable import Decodable
protocol Vehicle {
var driverless: Bool {get}
}
struct Car: Vehicle {
let driverless: Bool
}
extension Car: Decodable {
static func decode(json: AnyObject) throws -> Car {
return try Car(driverless: json => "driverless")
}
}
struct Train: Vehicle {
let driverless: Bool
let electric: Bool
}
extension Train: Decodable {
static func decode(json: AnyObject) throws -> Train {
return try Train(driverless: json => "driverless",
electric: json => "electric")
}
}
struct Truck: Vehicle {
let driverless: Bool
let wheels: UInt8
}
extension Truck: Decodable {
static func decode(json: AnyObject) throws -> Truck {
return try Truck(driverless: json => "driverless",
wheels: json => "wheels")
}
}
| 87b80209ea592f4f25b6d80de4c24c5e | 18.166667 | 54 | 0.673913 | false | false | false | false |
adamdahan/MaterialKit | refs/heads/v1.x.x | Source/FlatButton.swift | agpl-3.0 | 1 | //
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public class FlatButton : MaterialButton {
//
// :name: prepareButton
//
internal override func prepareButton() {
super.prepareButton()
setTitleColor(UIColor.purpleColor(), forState: .Normal)
pulseColor = .purpleColor()
backgroundColor = .clearColor()
backgroundColorView.layer.cornerRadius = 3
}
//
// :name: pulseBegan
//
internal override func pulseBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.pulseBegan(touches, withEvent: event)
UIView.animateWithDuration(0.3, animations: {
self.pulseView!.transform = CGAffineTransformMakeScale(10, 10)
self.transform = CGAffineTransformMakeScale(1.05, 1.1)
})
}
}
| 77bc80ebe30a4cac4fd73dcec261cc90 | 34.209302 | 90 | 0.740423 | false | false | false | false |
Otbivnoe/Framezilla | refs/heads/master | Tests/BaseTest.swift | mit | 1 | //
// BaseTest.swift
// Framezilla
//
// Created by Nikita on 06/09/16.
// Copyright © 2016 Nikita. All rights reserved.
//
import XCTest
class BaseTest: XCTestCase {
var mainView = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
var nestedView1 = UIView(frame: CGRect(x: 100, y: 100, width: 300, height: 300))
var nestedView2 = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 200))
var testingView = UIView()
override func setUp() {
super.setUp()
mainView.addSubview(nestedView1)
mainView.addSubview(testingView)
nestedView1.addSubview(nestedView2)
testingView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
}
override func tearDown() {
super.tearDown()
nestedView1.removeFromSuperview()
nestedView2.removeFromSuperview()
testingView.removeFromSuperview()
}
}
| d6f02aad07b0c47f52b047d6b023db42 | 24.972222 | 84 | 0.617112 | false | true | false | false |
Asura19/SwiftAlgorithm | refs/heads/master | SwiftAlgorithm/SwiftAlgorithm/LC083.swift | mit | 1 | //
// LC083.swift
// SwiftAlgorithm
//
// Created by Phoenix on 2019/5/27.
// Copyright © 2019 Phoenix. All rights reserved.
//
import Foundation
extension LeetCode {
// LeetCode 083 https://leetcode.com/problems/remove-duplicates-from-sorted-list/
static func deleteDuplicates(_ head: ListNode?) -> ListNode? {
guard let head = head else {
return nil
}
var cur: ListNode? = head
while cur?.next != nil {
while cur?.value == cur?.next?.value {
cur?.next = cur?.next?.next
}
cur = cur?.next
}
return head
}
}
| c5175115c9b785497bea14ad75f7b6cd | 22 | 85 | 0.551242 | false | false | false | false |
ReactiveX/RxSwift | refs/heads/develop | Example/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift | gpl-3.0 | 8 | //
// VirtualTimeConverterType.swift
// RxSwift
//
// Created by Krunoslav Zaher on 12/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/// Parametrization for virtual time used by `VirtualTimeScheduler`s.
public protocol VirtualTimeConverterType {
/// Virtual time unit used that represents ticks of virtual clock.
associatedtype VirtualTimeUnit
/// Virtual time unit used to represent differences of virtual times.
associatedtype VirtualTimeIntervalUnit
/**
Converts virtual time to real time.
- parameter virtualTime: Virtual time to convert to `Date`.
- returns: `Date` corresponding to virtual time.
*/
func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime
/**
Converts real time to virtual time.
- parameter time: `Date` to convert to virtual time.
- returns: Virtual time corresponding to `Date`.
*/
func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit
/**
Converts from virtual time interval to `NSTimeInterval`.
- parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`.
- returns: `NSTimeInterval` corresponding to virtual time interval.
*/
func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval
/**
Converts from `NSTimeInterval` to virtual time interval.
- parameter timeInterval: `NSTimeInterval` to convert to virtual time interval.
- returns: Virtual time interval corresponding to time interval.
*/
func convertToVirtualTimeInterval(_ timeInterval: TimeInterval) -> VirtualTimeIntervalUnit
/**
Offsets virtual time by virtual time interval.
- parameter time: Virtual time.
- parameter offset: Virtual time interval.
- returns: Time corresponding to time offsetted by virtual time interval.
*/
func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit
/**
This is additional abstraction because `Date` is unfortunately not comparable.
Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries.
*/
func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison
}
/**
Virtual time comparison result.
This is additional abstraction because `Date` is unfortunately not comparable.
Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries.
*/
public enum VirtualTimeComparison {
/// lhs < rhs.
case lessThan
/// lhs == rhs.
case equal
/// lhs > rhs.
case greaterThan
}
extension VirtualTimeComparison {
/// lhs < rhs.
var lessThen: Bool {
self == .lessThan
}
/// lhs > rhs
var greaterThan: Bool {
self == .greaterThan
}
/// lhs == rhs
var equal: Bool {
self == .equal
}
}
| d983b9a698b7159568b65fa677cd51a6 | 29.948454 | 111 | 0.696536 | false | false | false | false |
takeo-asai/math-puzzle | refs/heads/master | problems/10.swift | mit | 1 | let europians = [0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26]
let americans = [0, 28, 9, 26, 30, 11, 7, 20, 32, 17, 5, 22, 34, 15, 3, 24, 36, 13, 1, 00, 27, 10, 25, 29, 12, 8, 19, 31, 18, 6, 21, 33, 16, 4, 23, 35, 14, 2]
func max(a: [Int], n: Int) -> Int {
var max: Int = 0
for i in 0 ..< a.count {
var s = 0
for j in 0 ..< n {
s += a[(i+j)%a.count]
}
if s > max {
max = s
}
}
return max
}
var count = 0
for n in 2 ... 36 {
let euroMax = max(europians, n: n)
let amerMax = max(americans, n: n)
if euroMax < amerMax {
count++
}
}
print(count)
| 717dbea633cae2ff3c85c49eaeb19b11 | 23.592593 | 158 | 0.503012 | false | false | false | false |
Yufei-Yan/iOSProjectsAndTest | refs/heads/master | Ch8_test/Ch8_test/ViewController.swift | mit | 1 | //
// ViewController.swift
// Ch8_test
//
// Created by Yan on 11/1/16.
// Copyright © 2016 Yan. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let dwarves = [
"Sleepy", "Sneezy", "Bashful", "Happy",
"Doc", "Grumpy", "Dopey",
"Thorin", "Dorin", "Nori", "Ori",
"Balin", "Dwalin", "Fili", "Kili",
"Oin", "Gloin", "Bifur", "Bofur",
"Bombur"
]
let simpleTableIdentifier = "SimpleTableIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dwarves.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: simpleTableIdentifier)
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: simpleTableIdentifier)
}
let image = UIImage(named: "star")
cell?.imageView?.image = image
let highlightedImage = UIImage(named: "star2")
cell?.imageView?.highlightedImage = highlightedImage
if indexPath.row < 7 {
cell?.detailTextLabel?.text = "Mr Disney"
} else {
cell?.detailTextLabel?.text = "Mr Tolkien"
}
cell?.textLabel?.text = dwarves[indexPath.row]
cell?.textLabel?.font = UIFont .boldSystemFont(ofSize: 50)
return cell!
}
func tableView(_ tableView: UITableView,
indentationLevelForRowAt indexPath: IndexPath) -> Int {
return indexPath.row % 4
}
func tableView(_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return indexPath.row == 0 ? nil : indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let rowValue = dwarves[indexPath.row]
let message = "You selected \(rowValue)"
let controller = UIAlertController(title: "Row Selected",
message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Yes I Did",
style: .default, handler: nil)
controller.addAction(action)
present(controller, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.row == 0 ? 120 : 70
}
}
| 99d39fac4a991885652145450b13ff19 | 32.556818 | 111 | 0.601761 | false | false | false | false |
RTWeiss/pretto | refs/heads/master | Pretto/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Pretto
//
// Created by Josiah Gaskin on 6/3/15.
// Copyright (c) 2015 Pretto. All rights reserved.
//
import UIKit
let dateFormatter = NSDateFormatter()
let kUserDidLogOutNotification = "userDidLogOut"
let kShowLoginWindowNotification = "showLoginWindow"
let kShowLandingWindowNotification = "showLandingWindow"
let kIntroDidFinishNotification = "introIsOver"
let kShareOnFacebookNotification = "shareOnFacebook"
let kShareOnTwitterNotification = "shareOnTwitter"
let kShareByEmailNotification = "shareByEmail"
let kAcceptEventAndDismissVCNotification = "acceptEventAndDismissVC"
let kFirstTimeRunningPretto = "isTheFirstTimeEver"
let kDidPressCreateEventNotification = "createNewEvent"
let kUserDidPressCameraNotification = "openCamera"
let cameraView: UIImageView = UIImageView()
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate {
var window: UIWindow?
private var isTheFirstTimeEver = false
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
println("didFinishLaunchingWithOptions")
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false)
GlobalAppearance.setAll()
registerDataModels()
Parse.enableLocalDatastore()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showLoginWindow", name: kShowLoginWindowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "showLandingWindow", name: kShowLandingWindowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "introDidFinish", name: kIntroDidFinishNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "userDidLogOut", name: kUserDidLogOutNotification, object: nil)
// Initialize Parse.
Parse.setApplicationId("EwtAHVSdrZseylxvkalCaMQ3aTWknFUgnhJRcozx",
clientKey: "kA7v5dqEEndRpZgcOsL2G4jitdGuPzj63xmYm7xZ")
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
application.setMinimumBackgroundFetchInterval(60 * 60)
// Register for Push Notitications
self.registerForRemoteNotifications(application, launchOptions:launchOptions)
// check user and start a storyboard accordingly
let isFirstTime: Bool? = NSUserDefaults.standardUserDefaults().objectForKey(kFirstTimeRunningPretto) as? Bool
if isFirstTime == nil || isFirstTime == true {
self.showIntroWindow()
} else {
self.checkCurrentUser()
}
return false
}
func registerForRemoteNotifications(application: UIApplication, launchOptions: [NSObject: AnyObject]?) {
println("registerForRemoteNotifications")
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var pushPayload = false
if let options = launchOptions {
pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
}
if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptionsInBackground(launchOptions, block: nil)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
println("didRegisterForRemoteNotificationsWithDeviceToken")
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackgroundWithBlock(nil)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println("didFailToRegisterForRemoteNotificationsWithError")
if error.code == 3010 {
println("Push notifications are not supported in the iOS Simulator.")
} else {
println("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
println("didReceiveRemoteNotification")
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground(userInfo, block: nil)
}
println("Remote Notification Received!")
}
func application(application: UIApplication,
openURL url: NSURL,
sourceApplication: String?,
annotation: AnyObject?) -> Bool {
println("openURL")
return FBSDKApplicationDelegate.sharedInstance().application(
application,
openURL: url,
sourceApplication: sourceApplication,
annotation: annotation)
}
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// TODO - upload new pictures here
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
var currentInstallation = PFInstallation.currentInstallation()
if (currentInstallation.badge != 0) {
currentInstallation.badge = 0
currentInstallation.saveEventually()
}
}
func applicationWillTerminate(application: UIApplication) {
}
}
//MARK: Auxiliary Functions
extension AppDelegate {
func addCameraOverlay() {
var window = UIApplication.sharedApplication().keyWindow
let iconSize = CGSize(width: 56.0, height: 56.0)
let margin = CGFloat(8.0)
window?.addSubview(cameraView)
window?.bringSubviewToFront(cameraView)
cameraView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: iconSize)
cameraView.backgroundColor = UIColor.clearColor()
cameraView.image = UIImage(named: "OverlayCameraButtonOrange")
cameraView.center = CGPoint(x: window!.bounds.width - (iconSize.width / 2) - margin, y: window!.bounds.height - (iconSize.height / 2) - margin - 51)
cameraView.userInteractionEnabled = true
var tapRecognizer = UITapGestureRecognizer(target: self, action: "tappedOnCamera")
cameraView.addGestureRecognizer(tapRecognizer)
}
func tappedOnCamera() {
NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: kUserDidPressCameraNotification, object: nil))
}
func checkCurrentUser() {
println("AppDelegate: checkCurrentUser")
User.checkCurrentUser({ (user:User) -> Void in
println("Saving user details...")
user.save()
user.printProperties()
self.startMainStoryBoard()
self.fetchFriends(user)
},
otherwise: { (pfUser:PFUser?) -> Void in
if pfUser != nil {
println("Unlinking user from FB")
PFFacebookUtils.unlinkUserInBackground(pfUser!)
}
self.showLandingWindow()
})
}
func fetchFriends(user:User) {
Friend.getAllFriendsFromFacebook(user.facebookId!, onComplete: { (friends:[Friend]?) -> Void in
if friends != nil {
println("Friends retrieved from FB")
Friend.printDebugAll(friends!)
Friend.getAllFriendsFromDBase(user.facebookId!, onComplete: { (savedFriends:[Friend]?) -> Void in
if savedFriends != nil {
var unsavedFriends = Friend.subtract(friends!, from: savedFriends!)
if unsavedFriends.count > 0 {
Friend.saveAllInBackground(unsavedFriends)
println("Saving friends invoked for \(unsavedFriends.count)")
} else {
println("Friends are up to date.")
}
} else {
println("No friends are saved yet. Attempting to save all.")
Friend.saveAllInBackground(friends!)
println("Saving friends invoked for \(friends!.count)")
}
})
} else {
println("No FB friends using this app")
}
})
}
func userDidLogOut() {
PFUser.logOut()
(UIApplication.sharedApplication().delegate as! AppDelegate).showLandingWindow()
}
func introDidFinish() {
println("introDidFinish")
self.checkCurrentUser()
}
func showIntroWindow() {
println("showIntroWindow")
var introViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("IntroViewController") as! IntroViewController
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = introViewController
self.window!.makeKeyAndVisible()
}
func showLandingWindow() {
println("Show Landing Notification Received")
var landingViewController = CustomLandingViewController()
landingViewController.fields = .Facebook | .SignUpButton
landingViewController.delegate = self
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = landingViewController
self.window!.makeKeyAndVisible()
}
func showLoginWindow() {
println("Show Login Notification Received")
var logInViewController = CustomLoginViewController()
logInViewController.fields = .Facebook | .UsernameAndPassword | .PasswordForgotten | .LogInButton | .DismissButton
logInViewController.delegate = self
logInViewController.emailAsUsername = true
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = logInViewController
self.window!.makeKeyAndVisible()
}
func startMainStoryBoard() {
println("startMainStoryBoard")
self.window = UIWindow(frame:UIScreen.mainScreen().bounds)
var mainSB = UIStoryboard(name: "Main", bundle: nil)
let viewController = mainSB.instantiateInitialViewController() as! UITabBarController
viewController.selectedIndex = 1
self.window!.rootViewController = viewController
self.window!.makeKeyAndVisible()
self.addCameraOverlay()
}
}
//MARK: PFSignUpViewControllerDelegate {
extension AppDelegate: PFSignUpViewControllerDelegate {
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) {
println("Sign Up is Done")
signUpController.dismissViewControllerAnimated(true, completion: nil)
self.startMainStoryBoard()
}
func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) {
println("User did cancel Sign Up")
}
func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) {
println("Error while signing up new user. Error: \(error)")
}
}
//MARK: PFLogInViewControllerDelegate {
extension AppDelegate: PFLogInViewControllerDelegate {
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
println("FB login is done")
// Handles the very first time a user logs in
let isFirstTime: Bool? = NSUserDefaults.standardUserDefaults().objectForKey(kFirstTimeRunningPretto) as? Bool
if isFirstTime == nil || isFirstTime == true {
NSUserDefaults.standardUserDefaults().setBool(false, forKey: kFirstTimeRunningPretto)
logInController.dismissViewControllerAnimated(true, completion: nil)
self.checkCurrentUser()
} else {
logInController.dismissViewControllerAnimated(true, completion: nil)
self.startMainStoryBoard()
}
}
func logInViewControllerDidCancelLogIn(logInController: PFLogInViewController) {
println("User did cancel Sign Up")
}
func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) {
println("Error while loging in new user. Error: \(error)")
}
}
| 3182ce3d829e11596e3481d378e9ed38 | 41.489426 | 160 | 0.675199 | false | false | false | false |
jpush/jchat-swift | refs/heads/master | JChat/Src/Utilites/Extension/Array+JChat.swift | mit | 1 | //
// Array+JChat.swift
// JChat
//
// Created by JIGUANG on 2017/10/11.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
// MARK: - JCMessageType
extension Array where Element: JCMessageType {
func index(_ message: JMSGMessage) -> Int? {
return self.index(where: { (m) -> Bool in
m.msgId == message.msgId
})
}
func index(_ message: JCMessageType) -> Int? {
return self.index(where: { (m) -> Bool in
m.msgId == message.msgId
})
}
}
// MARK: - String
extension Array where Element == String {
func sortedKeys() -> [Element] {
var array = self.sorted(by: { (str1, str2) -> Bool in
return str1 < str2
})
if let first = array.first {
if first == "#" {
array.removeFirst()
array.append(first)
}
}
return array
}
}
| b89fb50d89b4e4248a812e8dea32ed48 | 20.952381 | 61 | 0.521692 | false | false | false | false |
gouyz/GYZBaking | refs/heads/master | baking/Classes/Mine/Controller/GYZBusinessProfileVC.swift | mit | 1 | //
// GYZBusinessProfileVC.swift
// baking
// 店铺资料
// Created by gouyz on 2017/4/2.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
import MBProgressHUD
private let businessProfileCell = "businessProfileCell"
private let businessProfileImagesCell = "businessProfileImagesCell"
class GYZBusinessProfileVC: GYZBaseVC,UITableViewDelegate,UITableViewDataSource {
let titles: [String] = ["店铺名称","店铺地址","签约时间","店铺实景"]
var signInfoModel: GYZSignInfoModel?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "店铺资料"
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalTo(0)
}
requestSignInfoData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 懒加载UITableView
lazy var tableView : UITableView = {
let table = UITableView(frame: CGRect.zero, style: .grouped)
table.dataSource = self
table.delegate = self
table.tableFooterView = UIView()
table.separatorColor = kGrayLineColor
table.register(GYZBusinessProfileCell.self, forCellReuseIdentifier: businessProfileCell)
table.register(GYZBusinessImgCell.self, forCellReuseIdentifier: businessProfileImagesCell)
return table
}()
///获取签约用户店铺信息
func requestSignInfoData(){
weak var weakSelf = self
showLoadingView()
GYZNetWork.requestNetwork("User/shopInfo",parameters: ["user_id":userDefaults.string(forKey: "userId") ?? ""], success: { (response) in
weakSelf?.hiddenLoadingView()
// GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
let data = response["result"]
guard let info = data["info"].dictionaryObject else { return }
weakSelf?.signInfoModel = GYZSignInfoModel.init(dict: info)
weakSelf?.tableView.reloadData()
}else{
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
}
}, failture: { (error) in
weakSelf?.hiddenLoadingView()
GYZLog(error)
})
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row < titles.count - 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: businessProfileCell) as! GYZBusinessProfileCell
cell.nameLab.text = titles[indexPath.row]
if indexPath.row == 0 {
cell.desLab.text = signInfoModel?.shop_name
} else if indexPath.row == 1 {
cell.desLab.text = signInfoModel?.address
}else if indexPath.row == 2 {
cell.desLab.text = signInfoModel?.signing_time?.dateFromTimeInterval()?.dateToStringWithFormat(format: "yyyy/MM/dd")
}
cell.selectionStyle = .none
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: businessProfileImagesCell) as! GYZBusinessImgCell
cell.nameLab.text = titles[indexPath.row]
cell.imgUrls = signInfoModel?.shop_img
cell.backgroundColor = kWhiteColor
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return kMargin
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row < titles.count - 1 {
return 40
}
return 40 + kBusinessImgHeight + kMargin
}
}
| be1fcffd650cabdb5294a984acda3350 | 32.642857 | 144 | 0.606275 | false | false | false | false |
withcopper/CopperKit | refs/heads/master | CopperKit/ModalCardTransitioningDelegate.swift | mit | 1 | //
// ModalCardTransitioningDelegate
// Copper
//
// Created by Doug Williams 3/31/16
// Copyright (c) 2016 Copper Technologies, Inc. All rights reserved.
//
import UIKit
public class ModalCardTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
public func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
let presentationController = ModalCardPresentationController(presentedViewController:presented, presentingViewController:presenting)
return presentationController
}
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animationController = ModalCardAnimatedTransitioning()
animationController.isPresentation = true
return animationController
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animationController = ModalCardAnimatedTransitioning()
animationController.isPresentation = false
return animationController
}
}
| 388ac769ee7bd04271ea7d2e8b664f1c | 44.933333 | 226 | 0.797533 | false | false | false | false |
rgcottrell/ReactiveStreams | refs/heads/master | Sources/AnySubscriber.swift | apache-2.0 | 1 | /*
* Copyright 2016 Robert Cottrell
*
* 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 type-erased `Subscriber` type.
///
/// Forwards operations to an arbitrary underlying subscriber with the same
/// `SubscribeTrype` type, hiding the specifics of the underlying subscriber.
public final class AnySubscriber<Element> : Subscriber {
/// The type of elements to be received.
public typealias SubscribeType = Element
/// The boxed processor which will receive forwarded calls.
internal let _box: _AnySubscriberBox<SubscribeType>
/// Create a type erased wrapper around a subscriber.
///
/// - parameter base: The subscriber to receive operations.
public init<S : Subscriber where S.SubscribeType == SubscribeType>(_ base: S) {
_box = _SubscriberBox(base)
}
/// Create a type erased wrapper having the same underlying `Subscriber`
/// as `other`.
///
/// - parameter other: The other `AnySubscriber` instance.
public init(_ other: AnySubscriber<Element>) {
_box = other._box
}
/// Forward `onSubscribe(subscription:)` to the boxed subscriber.
public func onSubscribe(subscription: Subscription) {
_box.onSubscribe(subscription: subscription)
}
/// Forward `onNext` to the boxed subscriber.
public func onNext(element: SubscribeType) {
_box.onNext(element: element)
}
/// Forward `onError(error:)` to the boxed subscriber.
public func onError(error: ErrorProtocol) {
_box.onError(error: error)
}
/// Forward `onComplete()` to the boxed subscriber.
public func onComplete() {
_box.onComplete()
}
}
internal final class _SubscriberBox<S : Subscriber> : _AnySubscriberBox<S.SubscribeType> {
private let _base: S
internal init(_ base: S) {
self._base = base
}
internal override func onSubscribe(subscription: Subscription) {
_base.onSubscribe(subscription: subscription)
}
internal override func onNext(element: S.SubscribeType) {
_base.onNext(element: element)
}
internal override func onError(error: ErrorProtocol) {
_base.onError(error: error)
}
internal override func onComplete() {
_base.onComplete()
}
}
internal class _AnySubscriberBox<Element> {
internal func onSubscribe(subscription: Subscription) {
_abstract()
}
internal func onNext(element: Element) {
_abstract()
}
internal func onError(error: ErrorProtocol) {
_abstract()
}
internal func onComplete() {
_abstract()
}
} | aba13921fc7f740b220f4d1368bf8441 | 29.132075 | 90 | 0.660821 | false | false | false | false |
marceloreis13/MRTableViewManager | refs/heads/master | MRTableViewManager/Classes/TableViewSection.swift | mit | 1 | //
// TableViewSection.swift
// Pods
//
// Created by Marcelo Reis on 6/21/16.
//
//
// MARK: - TableViewSection Class
open class TableViewSection {
// MARK: Enums and Structs
//Definition of row types
public enum SectionType:Int {
case unknow
case empty
case preload
case content
}
// MARK: - Proprieties
var rows: [TableViewRow]
var tag: String
var type: SectionType
// MARK: - Init
init(rows: [TableViewRow] = [], tag: String = "", type: SectionType = .unknow){
self.rows = rows
self.tag = tag
self.type = type
}
func add(_ row: TableViewRow) {
self.rows.append(row)
}
}
| 5ea22473be32b189f86114c133d3e900 | 16.083333 | 80 | 0.652033 | false | false | false | false |
ContinuousLearning/PokemonKit | refs/heads/1.6 | Carthage/Checkouts/Alamofire/Tests/ValidationTests.swift | apache-2.0 | 133 | //
// ValidationTests.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@testable import Alamofire
import Foundation
import XCTest
class StatusCodeValidationTestCase: BaseTestCase {
func testThatValidationForRequestWithAcceptableStatusCodeResponseSucceeds() {
// Given
let URLString = "https://httpbin.org/status/200"
let expectation = expectationWithDescription("request should return 200 status code")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(statusCode: 200..<300)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNil(error)
}
func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() {
// Given
let URLString = "https://httpbin.org/status/404"
let expectation = expectationWithDescription("request should return 404 status code")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(statusCode: [200])
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(error)
if let error = error {
XCTAssertEqual(error.domain, Error.Domain)
XCTAssertEqual(error.code, Error.Code.StatusCodeValidationFailed.rawValue)
XCTAssertEqual(error.userInfo[Error.UserInfoKeys.StatusCode] as? Int, 404)
} else {
XCTFail("error should not be nil")
}
}
func testThatValidationForRequestWithNoAcceptableStatusCodesFails() {
// Given
let URLString = "https://httpbin.org/status/201"
let expectation = expectationWithDescription("request should return 201 status code")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(statusCode: [])
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(error)
if let error = error {
XCTAssertEqual(error.domain, Error.Domain)
XCTAssertEqual(error.code, Error.Code.StatusCodeValidationFailed.rawValue)
XCTAssertEqual(error.userInfo[Error.UserInfoKeys.StatusCode] as? Int, 201)
} else {
XCTFail("error should not be nil")
}
}
}
// MARK: -
class ContentTypeValidationTestCase: BaseTestCase {
func testThatValidationForRequestWithAcceptableContentTypeResponseSucceeds() {
// Given
let URLString = "https://httpbin.org/ip"
let expectation = expectationWithDescription("request should succeed and return ip")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(contentType: ["application/json"])
.validate(contentType: ["application/json;charset=utf8"])
.validate(contentType: ["application/json;q=0.8;charset=utf8"])
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNil(error)
}
func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() {
// Given
let URLString = "https://httpbin.org/ip"
let expectation = expectationWithDescription("request should succeed and return ip")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(contentType: ["*/*"])
.validate(contentType: ["application/*"])
.validate(contentType: ["*/json"])
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNil(error)
}
func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() {
// Given
let URLString = "https://httpbin.org/xml"
let expectation = expectationWithDescription("request should succeed and return xml")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(contentType: ["application/octet-stream"])
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(error)
if let error = error {
XCTAssertEqual(error.domain, Error.Domain)
XCTAssertEqual(error.code, Error.Code.ContentTypeValidationFailed.rawValue)
XCTAssertEqual(error.userInfo[Error.UserInfoKeys.ContentType] as? String, "application/xml")
} else {
XCTFail("error should not be nil")
}
}
func testThatValidationForRequestWithNoAcceptableContentTypeResponseFails() {
// Given
let URLString = "https://httpbin.org/xml"
let expectation = expectationWithDescription("request should succeed and return xml")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(contentType: [])
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
if let error = error {
XCTAssertEqual(error.domain, Error.Domain)
XCTAssertEqual(error.code, Error.Code.ContentTypeValidationFailed.rawValue)
XCTAssertEqual(error.userInfo[Error.UserInfoKeys.ContentType] as? String, "application/xml")
} else {
XCTFail("error should not be nil")
}
}
func testThatValidationForRequestWithNoAcceptableContentTypeResponseSucceedsWhenNoDataIsReturned() {
// Given
let URLString = "https://httpbin.org/status/204"
let expectation = expectationWithDescription("request should succeed and return no data")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(contentType: [])
.response { _, response, data, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNil(error)
}
func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceedsWhenResponseIsNil() {
// Given
class MockManager: Manager {
override func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask!
dispatch_sync(queue) {
dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
}
let request = MockRequest(session: session, task: dataTask)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
}
class MockRequest: Request {
override var response: NSHTTPURLResponse? {
return MockHTTPURLResponse(
URL: NSURL(string: request!.URLString)!,
statusCode: 204,
HTTPVersion: "HTTP/1.1",
headerFields: nil
)
}
}
class MockHTTPURLResponse: NSHTTPURLResponse {
override var MIMEType: String? { return nil }
}
let manager: Manager = {
let configuration: NSURLSessionConfiguration = {
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
return configuration
}()
return MockManager(configuration: configuration)
}()
let URLString = "https://httpbin.org/delete"
let expectation = expectationWithDescription("request should be stubbed and return 204 status code")
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
manager.request(.DELETE, URLString)
.validate(contentType: ["*/*"])
.response { _, responseResponse, responseData, responseError in
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(response)
XCTAssertNotNil(data)
XCTAssertNil(error)
if let response = response {
XCTAssertEqual(response.statusCode, 204)
XCTAssertNil(response.MIMEType)
}
}
}
// MARK: -
class MultipleValidationTestCase: BaseTestCase {
func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
// Given
let URLString = "https://httpbin.org/ip"
let expectation = expectationWithDescription("request should succeed and return ip")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNil(error)
}
func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithStatusCodeError() {
// Given
let URLString = "https://httpbin.org/xml"
let expectation = expectationWithDescription("request should succeed and return xml")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(statusCode: 400..<600)
.validate(contentType: ["application/octet-stream"])
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(error)
if let error = error {
XCTAssertEqual(error.domain, Error.Domain)
XCTAssertEqual(error.code, Error.Code.StatusCodeValidationFailed.rawValue)
XCTAssertEqual(error.userInfo[Error.UserInfoKeys.StatusCode] as? Int, 200)
} else {
XCTFail("error should not be nil")
}
}
func testThatValidationForRequestWithUnacceptableStatusCodeAndContentTypeResponseFailsWithContentTypeError() {
// Given
let URLString = "https://httpbin.org/xml"
let expectation = expectationWithDescription("request should succeed and return xml")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate(contentType: ["application/octet-stream"])
.validate(statusCode: 400..<600)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(error)
if let error = error {
XCTAssertEqual(error.domain, Error.Domain)
XCTAssertEqual(error.code, Error.Code.ContentTypeValidationFailed.rawValue)
XCTAssertEqual(error.userInfo[Error.UserInfoKeys.ContentType] as? String, "application/xml")
} else {
XCTFail("error should not be nil")
}
}
}
// MARK: -
class AutomaticValidationTestCase: BaseTestCase {
func testThatValidationForRequestWithAcceptableStatusCodeAndContentTypeResponseSucceeds() {
// Given
let URL = NSURL(string: "https://httpbin.org/ip")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")
let expectation = expectationWithDescription("request should succeed and return ip")
var error: NSError?
// When
Alamofire.request(mutableURLRequest)
.validate()
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNil(error)
}
func testThatValidationForRequestWithUnacceptableStatusCodeResponseFails() {
// Given
let URLString = "https://httpbin.org/status/404"
let expectation = expectationWithDescription("request should return 404 status code")
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.validate()
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(error)
if let error = error {
XCTAssertEqual(error.domain, Error.Domain)
XCTAssertEqual(error.code, Error.Code.StatusCodeValidationFailed.rawValue)
XCTAssertEqual(error.userInfo[Error.UserInfoKeys.StatusCode] as? Int, 404)
} else {
XCTFail("error should not be nil")
}
}
func testThatValidationForRequestWithAcceptableWildcardContentTypeResponseSucceeds() {
// Given
let URL = NSURL(string: "https://httpbin.org/ip")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.setValue("application/*", forHTTPHeaderField: "Accept")
let expectation = expectationWithDescription("request should succeed and return ip")
var error: NSError?
// When
Alamofire.request(mutableURLRequest)
.validate()
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNil(error)
}
func testThatValidationForRequestWithAcceptableComplexContentTypeResponseSucceeds() {
// Given
let URL = NSURL(string: "https://httpbin.org/xml")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
let headerValue = "text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8,*/*;q=0.5"
mutableURLRequest.setValue(headerValue, forHTTPHeaderField: "Accept")
let expectation = expectationWithDescription("request should succeed and return xml")
var error: NSError?
// When
Alamofire.request(mutableURLRequest)
.validate()
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNil(error)
}
func testThatValidationForRequestWithUnacceptableContentTypeResponseFails() {
// Given
let URL = NSURL(string: "https://httpbin.org/xml")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")
let expectation = expectationWithDescription("request should succeed and return xml")
var error: NSError?
// When
Alamofire.request(mutableURLRequest)
.validate()
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(error)
if let error = error {
XCTAssertEqual(error.domain, Error.Domain)
XCTAssertEqual(error.code, Error.Code.ContentTypeValidationFailed.rawValue)
XCTAssertEqual(error.userInfo[Error.UserInfoKeys.ContentType] as? String, "application/xml")
} else {
XCTFail("error should not be nil")
}
}
}
| 7c31f6754fa9a7248e78bf5e3ad4067a | 32.809259 | 121 | 0.620474 | false | true | false | false |
at-internet/atinternet-ios-swift-sdk | refs/heads/master | Tracker/TrackerTests/ScreenTests.swift | mit | 1 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// ScreenTests.swift
// Tracker
//
import UIKit
import XCTest
class ScreenTests: XCTestCase {
lazy var screen: Screen = Screen(tracker: Tracker())
lazy var screens: Screens = Screens(tracker: Tracker())
lazy var dynamicScreen: DynamicScreen = DynamicScreen(tracker: Tracker())
lazy var dynamicScreens: DynamicScreens = DynamicScreens(tracker: Tracker())
let curDate = Date()
let dateFormatter: DateFormatter = DateFormatter()
func testInitScreen() {
XCTAssertTrue(screen.name == "", "Le nom de l'écran doit être vide")
XCTAssertTrue(screen.level2 == nil, "Le niveau 2 de l'écran doit etre nil")
}
func testSetScreen() {
screen.name = "Home"
screen.setEvent()
XCTAssertEqual(screen.tracker.buffer.volatileParameters.count, 4, "Le nombre de paramètres volatiles doit être égal à 4")
XCTAssert(screen.tracker.buffer.volatileParameters[0].key == "type", "Le premier paramètre doit être type")
XCTAssert(screen.tracker.buffer.volatileParameters[0].value() == "screen", "La valeur du premier paramètre doit être screen")
XCTAssert(screen.tracker.buffer.volatileParameters[1].key == "action", "Le second paramètre doit être action")
XCTAssert(screen.tracker.buffer.volatileParameters[1].value() == "view", "La valeur du second paramètre doit être view")
XCTAssert(screen.tracker.buffer.volatileParameters[2].key == "p", "Le troisième paramètre doit être p")
XCTAssert(screen.tracker.buffer.volatileParameters[2].value() == "Home", "La valeur du troisième paramètre doit être Home")
}
func testSetScreenWithNameAndChapter() {
screen = screens.add("Basket", chapter1: "Sport")
screen.setEvent()
XCTAssert(screen.tracker.buffer.volatileParameters[2].key == "p", "Le troisième paramètre doit être p")
XCTAssert(screen.tracker.buffer.volatileParameters[2].value() == "Sport::Basket", "La valeur du troisième paramètre doit être Sport::Basket")
}
func testAddScreen() {
screen = screens.add()
XCTAssert(screens.tracker.businessObjects.count == 1, "Le nombre d'objet en attente doit être égale à 1")
XCTAssert(screen.name == "", "Le nom de l'écran doit etre vide")
XCTAssert((screens.tracker.businessObjects[screen.id] as! Screen).name == "", "Le nom de l'écran doit etre vide")
}
func testAddScreenWithName() {
screen = screens.add("Home")
XCTAssert(screens.tracker.businessObjects.count == 1, "Le nombre d'objet en attente doit être égale à 1")
XCTAssert(screen.name == "Home", "Le nom de l'écran doit etre égal à Home")
XCTAssert((screens.tracker.businessObjects[screen.id] as! Screen).name == "Home", "Le nom de l'écran doit etre égal à Home")
}
func testAddScreenWithNameAndLevel2() {
screen = screens.add("Home")
screen.level2 = 1
XCTAssert(screens.tracker.businessObjects.count == 1, "Le nombre d'objet en attente doit être égale à 1")
XCTAssert(screen.name == "Home", "Le nom de l'écran doit etre égal à Home")
XCTAssert(screen.level2! == 1, "Le niveau 2 doit être égal à 1")
XCTAssert((screens.tracker.businessObjects[screen.id] as! Screen).name == "Home", "Le nom de l'écran doit etre égal à Home")
XCTAssert((screens.tracker.businessObjects[screen.id] as! Screen).level2! == 1, "Le niveau 2 doit être égal à 1")
}
func testSetDynamicScreen() {
dateFormatter.dateFormat = "YYYYMMddHHmm"
dynamicScreen.screenId = "123"
dynamicScreen.update = curDate;
dynamicScreen.name = "HomeDyn"
dynamicScreen.chapter1 = "chap1"
dynamicScreen.chapter2 = "chap2"
dynamicScreen.chapter3 = "chap3"
dynamicScreen.setEvent()
XCTAssertEqual(dynamicScreen.tracker.buffer.volatileParameters.count, 7, "Le nombre de paramètres volatiles doit être égal à 7")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[0].key == "pchap", "Le paramètre doit être pchap")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[0].value() == "chap1::chap2::chap3", "La valeur doit être chap1::chap2::chap3")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[1].key == "pid", "Le paramètre doit être pid")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[1].value() == "123", "La valeur doit être 123")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[2].key == "pidt", "Le paramètre doit être pidt")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[2].value() == dateFormatter.string(from: curDate), "La valeur doit être curDate")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[3].key == "type", "Le premier paramètre doit être type")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[3].value() == "screen", "La valeur du premier paramètre doit être screen")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[4].key == "action", "Le second paramètre doit être action")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[4].value() == "view", "La valeur du second paramètre doit être view")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[5].key == "p", "Le troisième paramètre doit être p")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[5].value() == "HomeDyn", "La valeur du troisième paramètre doit être HomeDyn")
}
func testSetDynamicScreenWithTooLongStringId() {
dateFormatter.dateFormat = "YYYYMMddHHmm"
var s = ""
for i in 0 ..< 256 {
s += String(i)
}
dynamicScreen.screenId = s
dynamicScreen.update = curDate;
dynamicScreen.name = "HomeDyn"
dynamicScreen.chapter1 = "chap1"
dynamicScreen.chapter2 = "chap2"
dynamicScreen.chapter3 = "chap3"
dynamicScreen.setEvent()
XCTAssertEqual(dynamicScreen.tracker.buffer.volatileParameters.count, 7, "Le nombre de paramètres volatiles doit être égal à 7")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[0].key == "pchap", "Le paramètre doit être pchap")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[0].value() == "chap1::chap2::chap3", "La valeur doit être chap1::chap2::chap3")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[1].key == "pid", "Le paramètre doit être pid")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[1].value() == "", "La valeur doit être vide")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[2].key == "pidt", "Le paramètre doit être pidt")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[2].value() == dateFormatter.string(from: curDate), "La valeur doit être curDate")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[3].key == "type", "Le premier paramètre doit être type")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[3].value() == "screen", "La valeur du premier paramètre doit être screen")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[4].key == "action", "Le second paramètre doit être action")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[4].value() == "view", "La valeur du second paramètre doit être view")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[5].key == "p", "Le troisième paramètre doit être p")
XCTAssert(dynamicScreen.tracker.buffer.volatileParameters[5].value() == "HomeDyn", "La valeur du troisième paramètre doit être HomeDyn")
}
func testAddDynamicScreen() {
dateFormatter.dateFormat = "YYYYMMddHHmm"
dynamicScreen = dynamicScreens.add("123", update: curDate, name: "HomeDyn")
XCTAssert(dynamicScreens.tracker.businessObjects.count == 1, "Le nombre d'objet en attente doit être égale à 1")
XCTAssert(dynamicScreen.name == "HomeDyn", "Le nom de l'écran doit etre égal à HomeDyn")
XCTAssert((dynamicScreens.tracker.businessObjects[dynamicScreen.id] as! DynamicScreen).name == "HomeDyn", "Le nom de l'écran doit etre égal à HomeDyn")
XCTAssert(dynamicScreen.screenId == "123", "L'identifiant d'écran doit etre égal à 123")
XCTAssert((dynamicScreens.tracker.businessObjects[dynamicScreen.id] as! DynamicScreen).screenId == "123", "L'identifiant d'écran doit etre égal à 123")
XCTAssert(dynamicScreen.update == curDate, "La date de l'écran doit être égal à curDate")
XCTAssert((dynamicScreens.tracker.businessObjects[dynamicScreen.id] as! DynamicScreen).update == curDate, "La date de l'écran doit être égal à curDate")
}
func testAddDynamicScreenWithChapter() {
dateFormatter.dateFormat = "YYYYMMddHHmm"
dynamicScreen = dynamicScreens.add(123, update: curDate, name: "HomeDyn", chapter1: "chap1")
XCTAssert(dynamicScreens.tracker.businessObjects.count == 1, "Le nombre d'objet en attente doit être égale à 1")
XCTAssert(dynamicScreen.name == "HomeDyn", "Le nom de l'écran doit etre égal à HomeDyn")
XCTAssert((dynamicScreens.tracker.businessObjects[dynamicScreen.id] as! DynamicScreen).name == "HomeDyn", "Le nom de l'écran doit etre égal à HomeDyn")
XCTAssert(dynamicScreen.screenId == "123", "L'identifiant d'écran doit etre égal à 123")
XCTAssert((dynamicScreens.tracker.businessObjects[dynamicScreen.id] as! DynamicScreen).screenId == "123", "L'identifiant d'écran doit etre égal à 123")
XCTAssert(dynamicScreen.update == curDate, "La date de l'écran doit être égal à curDate")
XCTAssert((dynamicScreens.tracker.businessObjects[dynamicScreen.id] as! DynamicScreen).update == curDate, "La date de l'écran doit être égal à curDate")
XCTAssert(dynamicScreen.chapter1 == "chap1", "Le chapitre 1 de l'écran doit être égal à chap1")
XCTAssert((dynamicScreens.tracker.businessObjects[dynamicScreen.id] as! DynamicScreen).chapter1 == "chap1", "Le chapitre 1 de l'écran doit être égal à chap1")
}
}
| d518d614d821c9b4ee4bc8b5a40c67b9 | 55.533981 | 166 | 0.692856 | false | true | false | false |
Bizzi-Body/Bizzi-Body-ParseTutorialPart3-Complete-Solution | refs/heads/master | SignUpInViewController.swift | mit | 2 | //
// SignUpInViewController.swift
// ParseTutorial
//
// Created by Ian Bradbury on 10/02/2015.
// Copyright (c) 2015 bizzi-body. All rights reserved.
//
import UIKit
class SignUpInViewController: UIViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var message: UILabel!
@IBOutlet weak var emailAddress: UITextField!
@IBOutlet weak var password: UITextField!
@IBAction func signUp(sender: AnyObject) {
// Build the terms and conditions alert
let alertController = UIAlertController(title: "Agree to terms and conditions",
message: "Click I AGREE to signal that you agree to the End User Licence Agreement.",
preferredStyle: UIAlertControllerStyle.Alert
)
alertController.addAction(UIAlertAction(title: "I AGREE",
style: UIAlertActionStyle.Default,
handler: { alertController in self.processSignUp()})
)
alertController.addAction(UIAlertAction(title: "I do NOT agree",
style: UIAlertActionStyle.Default,
handler: nil)
)
// Display alert
self.presentViewController(alertController, animated: true, completion: nil)
}
@IBAction func signIn(sender: AnyObject) {
activityIndicator.hidden = false
activityIndicator.startAnimating()
var userEmailAddress = emailAddress.text
userEmailAddress = userEmailAddress.lowercaseString
var userPassword = password.text
PFUser.logInWithUsernameInBackground(userEmailAddress, password:userPassword) {
(user: PFUser?, error: NSError?) -> Void in
if user != nil {
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("signInToNavigation", sender: self)
}
} else {
self.activityIndicator.stopAnimating()
if let message: AnyObject = error!.userInfo!["error"] {
self.message.text = "\(message)"
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.hidden = true
activityIndicator.hidesWhenStopped = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func processSignUp() {
var userEmailAddress = emailAddress.text
var userPassword = password.text
// Ensure username is lowercase
userEmailAddress = userEmailAddress.lowercaseString
// Add email address validation
// Start activity indicator
activityIndicator.hidden = false
activityIndicator.startAnimating()
// Create the user
var user = PFUser()
user.username = userEmailAddress
user.password = userPassword
user.email = userEmailAddress
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if error == nil {
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("signInToNavigation", sender: self)
}
} else {
self.activityIndicator.stopAnimating()
if let message: AnyObject = error!.userInfo!["error"] {
self.message.text = "\(message)"
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 27c4bc71ff2c7e58d2bf9ba195a52cfc | 25.217054 | 103 | 0.719397 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.