repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PekanMmd/Pokemon-XD-Code | Objects/scripts/XD/XGScriptOps.swift | 1 | 1272 | //
// XGScriptOps.swift
// XGCommandLineTools
//
// Created by StarsMmd on 21/05/2016.
// Copyright © 2016 StarsMmd. All rights reserved.
//
import Foundation
#if GAME_PBR
let instructionNames = [
"nop",
"operator",
"ldimm",
"ldvar",
"setvar",
"setvector",
"pop",
"call",
"return",
"callstd",
"jmptrue",
"jmpfalse",
"jmp",
"reserve",
"release",
"exit",
"setline",
"ldncpvar",
"unknown18",
"loadShortImmediate"
]
#else
let instructionNames = [
"nop",
"operator",
"ldimm",
"ldvar",
"setvar",
"setvector",
"pop",
"call",
"return",
"callstd",
"jmptrue",
"jmpfalse",
"jmp",
"reserve",
"release",
"exit",
"setline",
"ldncpvar",
]
#endif
let vectorCoordNames = ["x","y","z","4"]
enum XGScriptOps : Int {
case nop = 0
case xd_operator = 1
case loadImmediate = 2
case loadVariable = 3
case setVariable = 4
case setVector = 5
case pop = 6
case call = 7
case return_op = 8
case callStandard = 9
case jumpIfTrue = 10
case jumpIfFalse = 11
case jump = 12
case reserve = 13
case release = 14
case exit = 15
case setLine = 16
case loadNonCopyableVariable = 17
#if GAME_PBR
case unknown18 = 18
case loadShortImmediate = 19
#endif
var name : String {
get {
return instructionNames[self.rawValue]
}
}
}
| gpl-2.0 | 819769c0d2710e3547326e1a2ae0d958 | 12.967033 | 51 | 0.638867 | 2.521825 | false | false | false | false |
peteratseneca/dps923winter2015 | Project_Templates/ClassesV1/Classes/Model.swift | 1 | 2979 | //
// Model.swift
// Classes
//
// Created by Peter McIntyre on 2015-02-01.
// Copyright (c) 2015 School of ICT, Seneca College. All rights reserved.
//
import CoreData
class Model {
// MARK: - Private properties
private var cdStack: CDStack!
lazy private var applicationDocumentsDirectory: NSURL = {
return NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
}()
// MARK: - Public properties
lazy var frc_example: NSFetchedResultsController = {
// Use this as a template to create other fetched results controllers
let frc = self.cdStack.frcForEntityNamed("Example", withPredicateFormat: nil, predicateObject: nil, sortDescriptors: "attribute1,true", andSectionNameKeyPath: nil)
return frc
}()
// MARK: - Public methods
init() {
// Check whether the app is being launched for the first time
// If yes, check if there's an object store file in the app bundle
// If yes, copy the object store file to the Documents directory
// If no, create some new data if you need to
// URL to the object store file in the app bundle
let storeFileInBundle: NSURL? = NSBundle.mainBundle().URLForResource("ObjectStore", withExtension: "sqlite")
// URL to the object store file in the Documents directory
let storeFileInDocumentsDirectory: NSURL = applicationDocumentsDirectory.URLByAppendingPathComponent("ObjectStore.sqlite")
// System file manager
let fs: NSFileManager = NSFileManager()
// Check whether this is the first launch of the app
let isFirstLaunch: Bool = !fs.fileExistsAtPath(storeFileInDocumentsDirectory.path!)
// Check whether the app is supplied with starter data in the app bundle
let hasStarterData: Bool = storeFileInBundle != nil
if isFirstLaunch {
if hasStarterData {
// Use the supplied starter data
fs.copyItemAtURL(storeFileInBundle!, toURL: storeFileInDocumentsDirectory, error: nil)
// Initialize the Core Data stack
cdStack = CDStack()
} else {
// Initialize the Core Data stack before creating new data
cdStack = CDStack()
// Create some new data
StoreInitializer.create(cdStack)
}
} else {
// This app has been used/started before, so initialize the Core Data stack
cdStack = CDStack()
}
}
func saveChanges() { cdStack.saveContext() }
// Add more methods here for data maintenance
// For example, get-all, get-some, get-one, add, update, delete
// And other command-oriented operations
}
| mit | fb33220926dece197d30c10d5085d44e | 33.639535 | 171 | 0.611279 | 5.33871 | false | false | false | false |
Andgfaria/MiniGitClient-iOS | MiniGitClient/MiniGitClientTests/Scenes/Detail/Header/RepositoryDetailHeaderViewSpec.swift | 1 | 4450 | /*
Copyright 2017 - André Gimenez Faria
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Quick
import Nimble
@testable import MiniGitClient
class RepositoryDetailHeaderViewSpec: QuickSpec {
override func spec() {
describe("The RepositoryDetailHeaderView") {
var headerView = RepositoryDetailHeaderView()
var loadView : LoadMoreView?
beforeEach {
headerView = RepositoryDetailHeaderView()
if let stackView = headerView.subviews.first as? UIStackView {
loadView = stackView.arrangedSubviews.flatMap{ $0 as? LoadMoreView }.first
}
}
context("has", {
it("a wrapper stack view") {
expect(headerView.subviews.count) == 1
expect(headerView.subviews.first).to(beAKindOf(UIStackView.self))
}
it("has a name label") {
expect(headerView.nameLabel).toNot(beNil())
}
it("has an info label") {
expect(headerView.infoLabel).toNot(beNil())
}
it("has a load view") {
expect(loadView).toNot(beNil())
}
})
context("layout", {
it("intrisic content size is calculated based on its labels and its state") {
let height = headerView.nameLabel.intrinsicContentSize.height + headerView.infoLabel.intrinsicContentSize.height + 114
expect(headerView.intrinsicContentSize.width) == headerView.bounds.size.width
expect(headerView.intrinsicContentSize.height) == height
headerView.currentState.value = .loaded
expect(headerView.intrinsicContentSize.width) == headerView.bounds.size.width
expect(headerView.intrinsicContentSize.height) == height - 48
}
it("updates the labels preferred max width") {
headerView.adjustLayout(withWidth: 100)
expect(headerView.nameLabel.preferredMaxLayoutWidth) == 100 - 32
expect(headerView.infoLabel.preferredMaxLayoutWidth) == headerView.nameLabel.preferredMaxLayoutWidth
}
})
context("changes the view hierarchy") {
it("in the loading state") {
headerView.currentState.value = .loading
expect(loadView?.currentState.value) == .loading
expect(loadView?.superview).toNot(beNil())
}
it("in the showing retry option state") {
headerView.currentState.value = .showingRetryOption
expect(loadView?.currentState.value) == .normal
expect(loadView?.superview).toNot(beNil())
}
it("in the loaded state") {
headerView.currentState.value = .loaded
expect(loadView?.superview).to(beNil())
}
}
}
}
}
| mit | 1e3bbe5dc3193858852c12ad4160e010 | 43.939394 | 461 | 0.562823 | 6.136552 | false | false | false | false |
rporzuc/FindFriends | FindFriends/FindFriends/Extensions/UIImage+extensions.swift | 1 | 1861 | //
// UIImage+extensions.swift
// FindFriends
//
// Created by MacOSXRAFAL on 2/28/17.
// Copyright © 2017 MacOSXRAFAL. All rights reserved.
//
import Foundation
import UIKit
extension UIImage
{
func alpha(value : CGFloat) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: .zero, blendMode: .normal, alpha: value)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func imageFromColor(color : UIColor) -> UIImage{
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
func imageResizeAndRounding(sizeChange:CGSize)-> UIImage{
let hasAlpha = true
let scale: CGFloat = 0.0
UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
let rect = CGRect(origin: CGPoint.zero, size: sizeChange)
UIBezierPath(roundedRect: rect, cornerRadius: sizeChange.height/2).addClip()
self.draw(in: rect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}
func jpeg(_ quality: JPEGQuality) -> Data? {
return UIImageJPEGRepresentation(self, quality.rawValue)
}
}
| gpl-3.0 | 141c2c3b296500971b50dc00c973e22b | 25.197183 | 84 | 0.609677 | 5.152355 | false | false | false | false |
milankamilya/SpringAnimation | Animation/SpringAnimationViewController.swift | 1 | 7264 | //
// SpringAnimationViewController.swift
// Animation
//
// Created by Milan Kamilya on 15/09/15.
// Copyright (c) 2015 innofied. All rights reserved.
//
import UIKit
class SpringAnimationViewController: UIViewController {
//MARK:- CONTANTS
let themeColor: UIColor = UIColor(red: 204.0/255.0, green: 204.0/255.0, blue: 204.0/255.0, alpha: 1.0)
//MARK:- STORYBOARD COMPONENT
@IBOutlet weak var textViewForMessagingText: UITextView!
@IBOutlet weak var viewAtBackOfMessagingText: UIView!
@IBOutlet weak var slideTimeDuration: UISlider!
@IBOutlet weak var slideDelay: UISlider!
@IBOutlet weak var slideDamping: UISlider!
@IBOutlet weak var slideVelocity: UISlider!
//MARK:- PRIVATE PROPERTIES
var springView: MKFluidView?
//MARK: - LIFE CYCLE METHODS
override func viewDidLoad() {
super.viewDidLoad()
springView = MKFluidView(frame: CGRectMake(0, 0, 320, self.view.frame.size.height - viewAtBackOfMessagingText.frame.size.height))
springView?.backgroundColor = UIColor.orangeColor()
springView?.fillColor = themeColor
springView?.directionOfBouncing = .SurfaceTension
springView?.animationDuration = NSTimeInterval(slideTimeDuration.value)
springView?.animationSpecs = Animation( sideDelay : 0.1, sideDumping : 0.4, sideVelocity : 0.9, centerDelay: NSTimeInterval( slideDelay.value), centerDumping: CGFloat(slideDamping.value), centerVelocity: CGFloat(slideVelocity.value) )
self.view.addSubview(springView!)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
//MARK:- USER INTERACTION
@IBAction func springAnimationFetched(sender: UIButton) {
//println("\(slideTimeDuration.value) \(slideDelay.value) \(slideDamping.value) \(slideVelocity.value)")
var menuView = UIView(frame: CGRectMake(0, 100, 320, 60))
menuView.backgroundColor = themeColor
// 🚀 Following line goes with UILabel
//springView = MKFluidView(frame: CGRectMake(150-12, viewAtBackOfMessagingText.frame.origin.y - 20, 150+24, 20))
springView = MKFluidView(frame: CGRectMake(0, viewAtBackOfMessagingText.frame.origin.y - 50, 320, 50))
self.view.addSubview(springView!)
springView?.curveType = .EggShape
springView?.fillColor = themeColor
springView?.directionOfBouncing = .SurfaceTension
springView?.animationDuration = NSTimeInterval(slideTimeDuration.value)
springView?.animationSpecs = Animation( sideDelay : 0.1, sideDumping : 0.4, sideVelocity : 0.9, centerDelay: NSTimeInterval( slideDelay.value), centerDumping: CGFloat(slideDamping.value), centerVelocity: CGFloat(slideVelocity.value) )
springView?.animateWithSurfaceTension(callback: { () -> Void in
self.springView?.removeFromSuperview()
self.springView = nil
})
// UILabel Animation
// TODO:- Open Label Animation
/*
var labelMessage: UILabel = UILabel(frame: CGRectMake(100, viewAtBackOfMessagingText.frame.origin.y , 120, 50))
labelMessage.text = "Hello World"
labelMessage.textAlignment = .Center
labelMessage.backgroundColor = themeColor
labelMessage.layer.cornerRadius = 25.0
labelMessage.layer.masksToBounds = true
self.view.addSubview(labelMessage)
UIView.animateWithDuration( NSTimeInterval(slideTimeDuration.value + 0.45), delay: NSTimeInterval(slideDelay.value), usingSpringWithDamping: CGFloat(slideDamping.value), initialSpringVelocity: CGFloat(slideVelocity.value), options: (UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.AllowUserInteraction), animations: { () -> Void in
labelMessage.frame = CGRectMake(100, self.viewAtBackOfMessagingText.frame.origin.y - 60, 120, 50)
}, completion:{ (finish) -> Void in
UIView.animateWithDuration(NSTimeInterval(0.5), delay: NSTimeInterval(0.0), usingSpringWithDamping: CGFloat(0.6), initialSpringVelocity: CGFloat(0.5), options: (UIViewAnimationOptions.BeginFromCurrentState), animations: { () -> Void in
labelMessage.frame = CGRectMake(180, self.viewAtBackOfMessagingText.frame.origin.y - 200, 120, 50)
}, completion: { (finish) -> Void in
labelMessage.removeFromSuperview()
})
})
*/
}
//MARK:- CUSTOM VIEW
//MARK:- UTILITY METHODS
func textDrawing() {
let path: UIBezierPath = UIBezierPath()
path.moveToPoint(CGPointMake(20, 300))
path.addCurveToPoint(CGPointMake(300, 300), controlPoint1: CGPointMake(230, 230), controlPoint2: CGPointMake(160, 370))
path.stroke()
var shapeLayer: CAShapeLayer = CAShapeLayer()
shapeLayer.path = path.CGPath
self.view.layer.addSublayer(shapeLayer)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if touches.count == 1 {
for touch in touches {
let touchLocal: UITouch = touch as! UITouch
var point: CGPoint = touchLocal.locationInView(touchLocal.view)
if CGRectContainsPoint(viewAtBackOfMessagingText.bounds, point) {
point = touchLocal.view.convertPoint(point, toView: nil)
springView?.initializeTouchRecognizer(point)
}
}
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if touches.count == 1 {
for touch in touches {
let touchLocal: UITouch = touch as! UITouch
var point: CGPoint = touchLocal.locationInView(touchLocal.view)
point = touchLocal.view.convertPoint(point, toView: nil)
springView?.movingTouchRecognizer(point)
}
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
if touches.count == 1 {
for touch in touches {
let touchLocal: UITouch = touch as! UITouch
var point: CGPoint = touchLocal.locationInView(touchLocal.view)
point = touchLocal.view.convertPoint(point, toView: nil)
springView?.endTouchRecognizer(point)
}
}
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
if touches.count == 1 {
for touch in touches {
let touchLocal: UITouch = touch as! UITouch
var point: CGPoint = touchLocal.locationInView(touchLocal.view)
point = touchLocal.view.convertPoint(point, toView: nil)
springView?.endTouchRecognizer(point)
}
}
}
}
| mit | 5efd3256354e7dc271c289fa0cc9a183 | 39.338889 | 361 | 0.624019 | 4.85361 | false | false | false | false |
gavinbunney/Toucan | Tests/ToucanTestCase.swift | 1 | 2871 | //
// Copyright (c) 2014-2019 Gavin Bunney
//
// 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 XCTest
class ToucanTestCase : XCTestCase {
internal var portraitImage : UIImage {
let imageData = try? Data(contentsOf: Bundle(for: ToucanTestCase.self).url(forResource: "Portrait", withExtension: "jpg")!)
let image = UIImage(data: imageData!)
XCTAssertEqual(image!.size, CGSize(width: 1593, height: 2161), "Verify portrait image size")
return image!
}
internal var landscapeImage : UIImage {
let imageData = try? Data(contentsOf: Bundle(for: ToucanTestCase.self).url(forResource: "Landscape", withExtension: "jpg")!)
let image = UIImage(data: imageData!)
XCTAssertEqual(image!.size, CGSize(width: 3872, height: 2592), "Verify landscape image size")
return image!
}
internal var maskImage : UIImage {
let imageData = try? Data(contentsOf: Bundle(for: ToucanTestCase.self).url(forResource: "OctagonMask", withExtension: "png")!)
let image = UIImage(data: imageData!)
XCTAssertEqual(image!.size, CGSize(width: 500, height: 500), "Verify mask image size")
return image!
}
internal func getPixelRGBA(_ image: UIImage, point: CGPoint) -> (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
let pixelData : CFData = image.cgImage!.dataProvider!.data!
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((image.cgImage!.width * Int(point.y)) + Int(point.x)) * 4
let red = CGFloat((data[pixelInfo]))
let green = CGFloat((data[pixelInfo + 1]))
let blue = CGFloat((data[pixelInfo + 2]))
let alpha = CGFloat((data[pixelInfo + 3]))
return (red, green, blue, alpha)
}
}
| mit | 7b3d615e16a25a8851fa008c2ea69e93 | 46.065574 | 134 | 0.6907 | 4.437403 | false | true | false | false |
AlexChekanov/Gestalt | Gestalt/UI/Views/Details/Process/StepCollectionViewCell.swift | 1 | 2444 | import UIKit
class StepCollectionViewCell: UICollectionViewCell {
@IBOutlet var title: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
// override var isSelected: Bool {
//
// }
// Configure the view for the selected state
}
//MARK: - Configure
extension StepCollectionViewCell {
func configure(with presenter: StepCollectionViewCellPresenter) {
getSomeData { [weak self] in
guard let strongSelf = self else { return }
strongSelf.set(brief: presenter.brief)
}
}
fileprivate func getSomeData(finished: @escaping ()->Void ) {
}
}
//MARK: - Dynamic Sizing font - iOS 10
extension StepCollectionViewCell {
func commonInit() {
setAccessibilityProperties()
}
func setAccessibilityProperties() {
title.isAccessibilityElement = true
title.adjustsFontForContentSizeCategory = true
}
func set(brief: String) {
title.text = brief
title.accessibilityValue = brief
}
func set(due: Date) {
title.text = String(describing: due)
}
}
//MARK: - Helper Methods
extension StepCollectionViewCell {
public static var cellId: String {
return "StepCell"
}
public static var bundle: Bundle {
return Bundle(for: StepCollectionViewCell.self)
}
public static var nib: UINib {
return UINib(nibName: StepCollectionViewCell.cellId, bundle: StepCollectionViewCell.bundle)
}
public static func register(with collectionView: UICollectionView) {
collectionView.register(StepCollectionViewCell.nib, forCellWithReuseIdentifier: cellId)
}
public static func loadFromNib(owner: Any?) -> ActionTableViewCell {
return bundle.loadNibNamed(self.cellId, owner: owner, options: nil)?.first as! ActionTableViewCell
}
public static func dequeue(from collectionView: UICollectionView, for indexPath: IndexPath, with StepCollectionViewCellPresenter: StepCollectionViewCellPresenter) -> StepCollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath) as! StepCollectionViewCell
cell.configure(with: StepCollectionViewCellPresenter)
return cell
}
}
| apache-2.0 | 9a35c1d7ec3e58fcdbf7778bec4f8e67 | 24.726316 | 194 | 0.652209 | 5.395143 | false | false | false | false |
sync/NearbyTrams | NearbyTramsKit/Source/RoutesViewModel.swift | 1 | 10979 | //
// Copyright (c) 2014 Dblechoc. All rights reserved.
//
import Foundation
import NearbyTramsStorageKit
public protocol RoutesViewModelDelegate
{
func routesViewModelDidAddRoutes(routesViewModel: RoutesViewModel, routes: [RouteViewModel])
func routesViewModelDidRemoveRoutes(routesViewModel: RoutesViewModel, routes: [RouteViewModel])
func routesViewModelDidUpdateRoutes(routesViewModel: RoutesViewModel, routes: [RouteViewModel])
}
public class RoutesViewModel: NSObject, SNRFetchedResultsControllerDelegate
{
public var delegate: RoutesViewModelDelegate?
let managedObjectContext: NSManagedObjectContext
var fetchedResultsController: SNRFetchedResultsController?
var routesStorage: Dictionary<String, RouteViewModel> = [ : ]
var currentChangeSet: FetchedResultsControllerChangeSet?
public init (managedObjectContext: NSManagedObjectContext)
{
self.managedObjectContext = managedObjectContext
}
var orderedRouteIdentifiers: [String] {
if let fetchedResultsController = self.fetchedResultsController
{
if let fetchedObjects: [Route] = fetchedResultsController.fetchedObjects as? [Route]
{
return fetchedObjects.filter {
route -> Bool in
if let uniqueIdentifier = route.uniqueIdentifier
{
return self.routesStorage.indexForKey(uniqueIdentifier) != nil
}
return false
}.map {
route -> String in
return route.uniqueIdentifier!
}
}
}
return []
}
public var routes: [RouteViewModel] {
return self.orderedRouteIdentifiers.filter {
identifier -> Bool in
self.routesStorage.indexForKey(identifier) != nil
}.map {
identifier -> RouteViewModel in
return self.routesStorage[identifier]!
}
}
public var routesCount: Int {
return self.routes.count
}
public func routeAtIndex(index: Int) -> RouteViewModel
{
return self.routes[index]
}
public func startUpdatingRoutesWithFetchRequest(fetchRequest: NSFetchRequest)
{
let currentFetchedResultsController = SNRFetchedResultsController(managedObjectContext: managedObjectContext, fetchRequest: fetchRequest)
currentFetchedResultsController.delegate = self
var error: NSError?
if currentFetchedResultsController.performFetch(&error)
{
if let fetchedRoutes = currentFetchedResultsController.fetchedObjects as? [Route]
{
synchronizeRoutesWithObjectsFromArray(fetchedRoutes)
}
}
else
{
println("Failed to perform fetch routes with request '\(fetchRequest)': \(error)");
}
self.fetchedResultsController = currentFetchedResultsController
}
public func stopUpdatingRoutes()
{
if let currentFetchedResultsController = fetchedResultsController
{
currentFetchedResultsController.delegate = nil
}
self.fetchedResultsController = nil
}
func existingModelForRoute(route: Route) -> RouteViewModel?
{
if let identifier = route.uniqueIdentifier
{
return routesStorage[identifier]
}
return nil
}
func synchronizeRoutesWithObjectsFromArray(array: [Route])
{
var routesByIdentifier: Dictionary<String, Route> = [ : ]
for route in array
{
if let identifier = route.uniqueIdentifier
{
routesByIdentifier[identifier] = route
}
}
var currentIdentifiers = NSSet(array: Array(routesStorage.keys))
var newIdentifiers = NSSet(array: Array(routesByIdentifier.keys))
let identifiersToAdd = NSMutableSet(set: newIdentifiers)
identifiersToAdd.minusSet(currentIdentifiers)
let identifiersToRemove = NSMutableSet(set: currentIdentifiers)
identifiersToRemove.minusSet(newIdentifiers)
let identifiersToUpdate = NSMutableSet(set: currentIdentifiers)
identifiersToUpdate.intersectSet(newIdentifiers)
if identifiersToAdd.allObjects
{
var addedObjects: [Route] = []
for identifier : AnyObject in identifiersToAdd.allObjects
{
let route = routesByIdentifier[identifier as String]
if route.hasValue
{
addedObjects.append(route!)
}
}
addRoutesForObjects(addedObjects)
}
if identifiersToRemove.allObjects
{
var removedObjects: [Route] = []
for identifier : AnyObject in identifiersToRemove.allObjects
{
let routeViewModel = routesStorage[identifier as String]
if routeViewModel.hasValue
{
var result: (route: Route?, error:NSError?) = Route.fetchOneForPrimaryKeyValue(routeViewModel!.identifier, usingManagedObjectContext: managedObjectContext)
if let route = result.route
{
removedObjects.append(route)
}
}
}
removeRoutesForObjects(removedObjects)
}
if identifiersToUpdate.allObjects
{
var updatedObjects: [Route] = []
for identifier : AnyObject in identifiersToUpdate.allObjects
{
let route = routesByIdentifier[identifier as String]
if route.hasValue
{
updatedObjects.append(route!)
}
}
updateRoutesForObjects(updatedObjects)
}
}
func addRoutesForObjects(array: [Route])
{
if !array.isEmpty
{
let routesViewModel = array.filter {
route -> Bool in
return route.isValidForViewModel
}.map {
route -> RouteViewModel in
assert(!self.existingModelForRoute(route).hasValue, "route should not already exist!")
let identifier = route.uniqueIdentifier!
let viewModel = RouteViewModel(identifier: identifier, routeNo: route.routeNo!, routeDescription: route.routeDescription!, downDestination: route.downDestination!, upDestination: route.upDestination!)
self.routesStorage[identifier] = viewModel
return viewModel
}
if !routesViewModel.isEmpty
{
didAddRoutes(routesViewModel)
}
}
}
func updateRoutesForObjects(array: [Route])
{
if !array.isEmpty
{
var updatedRoutes: [RouteViewModel] = []
var deletedRoutes: [Route] = []
for route in array {
if let existingRouteModel = existingModelForRoute(route)
{
if route.isValidForViewModel
{
existingRouteModel.updateWithRouteNo(route.routeNo!, routeDescription: route.routeDescription!, downDestination: route.downDestination!, upDestination: route.upDestination!)
updatedRoutes.append(existingRouteModel)
}
else
{
deletedRoutes.append(route)
}
}
}
if !deletedRoutes.isEmpty
{
removeRoutesForObjects(deletedRoutes)
}
if !updatedRoutes.isEmpty
{
didUpdateRoutes(updatedRoutes)
}
}
}
func removeRoutesForObjects(array: [Route])
{
if !array.isEmpty
{
var removedRoutes: [RouteViewModel] = []
for route in array {
if let existingRouteModel = existingModelForRoute(route)
{
removedRoutes.append(existingRouteModel)
routesStorage.removeValueForKey(existingRouteModel.identifier)
}
}
if !removedRoutes.isEmpty
{
didRemoveRoutes(removedRoutes)
}
}
}
func didAddRoutes(routes: [RouteViewModel])
{
self.delegate?.routesViewModelDidAddRoutes(self, routes: routes)
}
func didRemoveRoutes(routes: [RouteViewModel])
{
self.delegate?.routesViewModelDidRemoveRoutes(self, routes: routes)
}
func didUpdateRoutes(routes: [RouteViewModel])
{
self.delegate?.routesViewModelDidUpdateRoutes(self, routes: routes)
}
public func controllerWillChangeContent(controller: SNRFetchedResultsController!)
{
if let changeSet = currentChangeSet
{
updateModelWithChangeSet(changeSet)
}
currentChangeSet = FetchedResultsControllerChangeSet();
}
func controller(controller: SNRFetchedResultsController!, didChangeObject anObject: AnyObject!, atIndex index: Int, forChangeType type: SNRFetchedResultsChangeType, newIndex: Int)
{
if controller == fetchedResultsController
{
currentChangeSet?.addChange(FetchedResultsControllerChange(changedObject: anObject, atIndexPath: NSIndexPath(index: index), forChangeType: type, newIndexPath: NSIndexPath(index: newIndex)))
}
}
public func controllerDidChangeContent(controller: SNRFetchedResultsController!)
{
if let changeSet = currentChangeSet
{
updateModelWithChangeSet(changeSet)
}
currentChangeSet = nil
}
func updateModelWithChangeSet(changeSet: FetchedResultsControllerChangeSet)
{
if let addedObjects = changeSet.allAddedObjects as? [Route]
{
addRoutesForObjects(addedObjects)
}
if let updatedObjects = changeSet.allUpdatedObjects as? [Route]
{
updateRoutesForObjects(updatedObjects)
}
if let removedObjects = changeSet.allRemovedObjects as? [Route]
{
removeRoutesForObjects(removedObjects)
}
}
}
extension Route
{
var isValidForViewModel: Bool {
return (self.uniqueIdentifier.hasValue && self.routeNo.hasValue && self.routeDescription.hasValue && self.downDestination.hasValue && self.upDestination.hasValue)
}
}
| mit | cd81ae1ac1db751d4403d00d43708796 | 31.96997 | 220 | 0.586301 | 5.966848 | false | false | false | false |
Brandon-J-Campbell/codemash | AutoLayoutSession/completed/demo7/codemash/ScheduleCollectionViewController.swift | 1 | 6388 | //
// ScheduleCollectionViewController.swift
// codemash
//
// Created by Brandon Campbell on 12/30/16.
// Copyright © 2016 Brandon Campbell. All rights reserved.
//
import Foundation
import UIKit
class ScheduleeRow {
var header : String?
var items = Array<ScheduleeRow>()
var session : Session?
convenience init(withHeader: String, items: Array<ScheduleeRow>) {
self.init()
self.header = withHeader
self.items = items
}
convenience init(withSession: Session) {
self.init()
self.session = withSession
}
}
class ScheduleCollectionCell : UICollectionViewCell {
@IBOutlet var titleLabel : UILabel?
@IBOutlet var roomLabel: UILabel?
@IBOutlet var speakerImageView: UIImageView?
var session : Session?
static func cellIdentifier() -> String {
return "ScheduleCollectionCell"
}
static func cell(forCollectionView collectionView: UICollectionView, indexPath: IndexPath, session: Session) -> ScheduleCollectionCell {
let cell : ScheduleCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: ScheduleCollectionCell.cellIdentifier(), for: indexPath) as! ScheduleCollectionCell
cell.speakerImageView?.image = nil
cell.titleLabel?.text = session.title
cell.roomLabel?.text = session.rooms[0]
cell.session = session
if let url = URL.init(string: "https:" + (session.speakers[0].gravatarUrl)) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
cell.speakerImageView?.image = UIImage(data: data)
}
}.resume()
}
return cell
}
}
class ScheduleCollectionHeaderView : UICollectionReusableView {
@IBOutlet var headerLabel : UILabel?
static func cellIdentifier() -> String {
return "ScheduleCollectionHeaderView"
}
}
class ScheduleCollectionViewController : UICollectionViewController {
var sections = Array<ScheduleTableRow>()
var sessions : Array<Session> = Array<Session>.init() {
didSet {
self.data = Dictionary<Date, Array<Session>>()
self.setupSections()
}
}
var data = Dictionary<Date, Array<Session>>()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showSession" {
let vc = segue.destination as! SessionViewController
let cell = sender as! ScheduleCollectionCell
vc.session = cell.session
}
}
func setupSections() {
let timeFormatter = DateFormatter.init()
timeFormatter.dateFormat = "EEEE h:mm:ssa"
for session in self.sessions {
if data[session.startTime] == nil {
data[session.startTime] = Array<Session>()
}
data[session.startTime]?.append(session)
}
var sections : Array<ScheduleTableRow> = []
for key in data.keys.sorted() {
var rows : Array<ScheduleTableRow> = []
for session in data[key]! {
rows.append(ScheduleTableRow.init(withSession: session))
}
let time = timeFormatter.string(from: key)
sections.append(ScheduleTableRow.init(withHeader: time, items: rows))
}
self.sections = sections
self.collectionView?.reloadData()
}
}
extension ScheduleCollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.sections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let section = self.sections[section]
return section.items.count
}
}
extension ScheduleCollectionViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let section = self.sections[indexPath.section]
let row = section.items[indexPath.row]
let cell = ScheduleCollectionCell.cell(forCollectionView: collectionView, indexPath: indexPath, session: row.session!)
cell.contentView.layer.cornerRadius = 10
cell.contentView.layer.borderColor = UIColor.black.cgColor
if (self.view.traitCollection.horizontalSizeClass != UIUserInterfaceSizeClass.compact) {
cell.contentView.layer.borderWidth = 1.0
} else {
cell.contentView.layer.borderWidth = 0.0
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let section = self.sections[indexPath.section]
let headerView: ScheduleCollectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ScheduleCollectionHeaderView.cellIdentifier(), for: indexPath) as! ScheduleCollectionHeaderView
headerView.headerLabel?.text = section.header
return headerView
}
}
extension ScheduleCollectionViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var width : CGFloat
if (self.view.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.compact) {
width = collectionView.bounds.size.width
} else {
let flowLayout : UICollectionViewFlowLayout = collectionViewLayout as! UICollectionViewFlowLayout
width = (collectionView.bounds.size.width - flowLayout.minimumLineSpacing - flowLayout.minimumInteritemSpacing - flowLayout.sectionInset.left - flowLayout.sectionInset.right) / (collectionView.bounds.size.width > 800.0 ? 3.0 : 2.0)
}
return CGSize.init(width: width, height: 100.0)
}
}
| mit | 8978f3ee8e69422963fb91aec57d5968 | 37.245509 | 243 | 0.658369 | 5.340301 | false | false | false | false |
mpclarkson/StravaSwift | Example/StravaSwift/ActivitiesViewController.swift | 1 | 2394 | //
// ActivitiesViewController.swift
// StravaSwift
//
// Created by MATTHEW CLARKSON on 23/05/2016.
// Copyright © 2016 Matthew Clarkson. All rights reserved.
//
import UIKit
import StravaSwift
class ActivitiesViewController: UITableViewController {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView?
fileprivate var activities: [Activity] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
update()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "SegueActivityDetail":
// User tapped on a row and wants to view the ActivityDetailVC
// We must set the activityId property during the segue
if let vc = segue.destination as? ActivityDetailVC?, let indexPath = tableView.indexPathForSelectedRow {
vc?.activityID = activities[indexPath.row].id
}
default: break
}
}
}
extension ActivitiesViewController {
fileprivate func update(params: Router.Params = nil) {
activityIndicator?.startAnimating()
StravaClient.sharedInstance.request(Router.athleteActivities(params: params), result: { [weak self] (activities: [Activity]?) in
guard let self = self else { return }
self.activityIndicator?.stopAnimating()
guard let activities = activities else { return }
self.activities = activities
self.tableView?.reloadData()
}, failure: { (error: NSError) in
self.activityIndicator?.stopAnimating()
debugPrint(error)
})
}
}
extension ActivitiesViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activities.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "activity", for: indexPath)
let activity = activities[indexPath.row]
cell.textLabel?.text = activity.name
if let date = activity.startDate {
cell.detailTextLabel?.text = "\(date)"
}
return cell
}
}
| mit | 06e6abc234f20176b4824353d1b548b1 | 30.906667 | 136 | 0.645215 | 5.190889 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceKit/Sources/EurofurenceKit/Entities/Image.swift | 1 | 3221 | import CoreData
import EurofurenceWebAPI
import Logging
@objc(Image)
public class Image: Entity {
private static let logger = Logger(label: "Image")
@nonobjc class func fetchRequest() -> NSFetchRequest<Image> {
return NSFetchRequest<Image>(entityName: "Image")
}
@NSManaged public var contentHashSHA1: String
@NSManaged public var estimatedSizeInBytes: Int64
@NSManaged public var internalReference: String
@NSManaged public var mimeType: String
@NSManaged public var cachedImageURL: URL?
@NSManaged var width: Int32
@NSManaged var height: Int32
override public func prepareForDeletion() {
super.prepareForDeletion()
deleteCachedImage()
}
private func deleteCachedImage() {
guard let cachedImageURL = cachedImageURL else { return }
do {
Self.logger.info("Deleting image", metadata: ["ID": .string(identifier)])
try managedObjectContext?.properties?.removeContainerResource(at: cachedImageURL)
} catch {
let metadata: Logger.Metadata = [
"ID": .string(identifier),
"Error": .string(String(describing: error))
]
Self.logger.error("Failed to delete image.", metadata: metadata)
}
}
}
// MARK: - Sizing
extension Image {
public var size: Size {
Size(width: Int(width), height: Int(height))
}
public struct Size: Equatable {
public var width: Int
public var height: Int
public init(width: Int, height: Int) {
self.width = width
self.height = height
}
}
}
// MARK: - Fetching
extension Image {
class func identifiedBy(
identifier: String,
in managedObjectContext: NSManagedObjectContext
) -> Self {
let entityDescription: NSEntityDescription = Self.entity()
guard let entityName = entityDescription.name else {
fatalError("Entity \(String(describing: Self.self)) does not possess a name in its NSEntityDescription!")
}
let fetchRequest: NSFetchRequest<Self> = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "identifier == %@", identifier)
let results = try? managedObjectContext.fetch(fetchRequest)
if let existingImage = results?.first {
return existingImage
} else {
let newImage = Self(context: managedObjectContext)
newImage.identifier = identifier
return newImage
}
}
}
// MARK: - Consuming Remote Response
extension Image {
func update(from remoteResponse: EurofurenceWebAPI.Image) {
identifier = remoteResponse.id
lastEdited = remoteResponse.lastChangeDateTimeUtc
contentHashSHA1 = remoteResponse.contentHashSha1
estimatedSizeInBytes = Int64(remoteResponse.sizeInBytes)
internalReference = remoteResponse.internalReference
mimeType = remoteResponse.mimeType
width = Int32(remoteResponse.width)
height = Int32(remoteResponse.height)
}
}
| mit | e9b80d2ff225836d729421d78a719854 | 28.281818 | 117 | 0.630239 | 5.178457 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/NewFeedVoiceRecord/NewFeedVoiceRecordViewController.swift | 1 | 11524 | //
// NewFeedVoiceRecordViewController.swift
// Yep
//
// Created by nixzhu on 15/11/25.
// Copyright © 2015年 Catch Inc. All rights reserved.
//
import UIKit
import AVFoundation
import YepKit
import Proposer
import AudioBot
final class NewFeedVoiceRecordViewController: SegueViewController {
var preparedSkill: Skill?
var beforeUploadingFeedAction: ((feed: DiscoveredFeed, newFeedViewController: NewFeedViewController) -> Void)?
var afterCreatedFeedAction: ((feed: DiscoveredFeed) -> Void)?
var getFeedsViewController: (() -> FeedsViewController?)?
@IBOutlet private weak var nextButton: UIBarButtonItem!
@IBOutlet private weak var voiceRecordSampleView: VoiceRecordSampleView!
@IBOutlet private weak var voiceIndicatorImageView: UIImageView!
@IBOutlet private weak var voiceIndicatorImageViewCenterXConstraint: NSLayoutConstraint!
@IBOutlet private weak var timeLabel: UILabel!
@IBOutlet private weak var voiceRecordButton: RecordButton!
@IBOutlet private weak var playButton: UIButton!
@IBOutlet private weak var resetButton: UIButton!
private enum State {
case Default
case Recording
case FinishRecord
}
private var state: State = .Default {
willSet {
switch newValue {
case .Default:
do {
AudioBot.stopPlay()
voiceRecordSampleView.reset()
sampleValues = []
audioPlaying = false
audioPlayedDuration = 0
}
nextButton.enabled = false
voiceIndicatorImageView.alpha = 0
UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.voiceRecordButton.alpha = 1
self?.voiceRecordButton.appearance = .Default
self?.playButton.alpha = 0
self?.resetButton.alpha = 0
}, completion: nil)
voiceIndicatorImageViewCenterXConstraint.constant = 0
view.layoutIfNeeded()
case .Recording:
nextButton.enabled = false
voiceIndicatorImageView.alpha = 0
UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.voiceRecordButton.alpha = 1
self?.voiceRecordButton.appearance = .Recording
self?.playButton.alpha = 0
self?.resetButton.alpha = 0
}, completion: nil)
case .FinishRecord:
nextButton.enabled = true
voiceIndicatorImageView.alpha = 0
UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.voiceRecordButton.alpha = 0
self?.playButton.alpha = 1
self?.resetButton.alpha = 1
}, completion: nil)
let fullWidth = voiceRecordSampleView.bounds.width
if !voiceRecordSampleView.sampleValues.isEmpty {
let firstIndexPath = NSIndexPath(forItem: 0, inSection: 0)
voiceRecordSampleView.sampleCollectionView.scrollToItemAtIndexPath(firstIndexPath, atScrollPosition: .Left, animated: true)
}
UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.voiceIndicatorImageView.alpha = 1
}, completion: { _ in
UIView.animateWithDuration(0.75, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.voiceIndicatorImageViewCenterXConstraint.constant = -fullWidth * 0.5 + 2
self?.view.layoutIfNeeded()
}, completion: { _ in })
})
}
}
}
private var sampleValues: [CGFloat] = [] {
didSet {
let count = sampleValues.count
let frequency = 10
let minutes = count / frequency / 60
let seconds = count / frequency - minutes * 60
let subSeconds = count - seconds * frequency - minutes * 60 * frequency
timeLabel.text = String(format: "%02d:%02d.%d", minutes, seconds, subSeconds)
}
}
private var audioPlaying: Bool = false {
willSet {
if newValue != audioPlaying {
if newValue {
playButton.setImage(UIImage.yep_buttonVoicePause, forState: .Normal)
} else {
playButton.setImage(UIImage.yep_buttonVoicePlay, forState: .Normal)
}
}
}
}
private var audioPlayedDuration: NSTimeInterval = 0 {
willSet {
guard newValue != audioPlayedDuration else {
return
}
let sampleStep: CGFloat = (4 + 2)
let fullWidth = voiceRecordSampleView.bounds.width
let fullOffsetX = CGFloat(sampleValues.count) * sampleStep
let currentOffsetX = CGFloat(newValue) * (10 * sampleStep)
// 0.5 用于回去
let duration: NSTimeInterval = newValue > audioPlayedDuration ? 0.02 : 0.5
if fullOffsetX > fullWidth {
if currentOffsetX <= fullWidth * 0.5 {
UIView.animateWithDuration(duration, delay: 0.0, options: .CurveLinear, animations: { [weak self] in
self?.voiceIndicatorImageViewCenterXConstraint.constant = -fullWidth * 0.5 + 2 + currentOffsetX
self?.view.layoutIfNeeded()
}, completion: { _ in })
} else {
voiceRecordSampleView.sampleCollectionView.setContentOffset(CGPoint(x: currentOffsetX - fullWidth * 0.5 , y: 0), animated: false)
}
} else {
UIView.animateWithDuration(duration, delay: 0.0, options: .CurveLinear, animations: { [weak self] in
self?.voiceIndicatorImageViewCenterXConstraint.constant = -fullWidth * 0.5 + 2 + currentOffsetX
self?.view.layoutIfNeeded()
}, completion: { _ in })
}
}
}
private var feedVoice: FeedVoice?
deinit {
println("deinit NewFeedVoiceRecord")
}
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("New Voice", comment: "")
nextButton.title = NSLocalizedString("Next", comment: "")
state = .Default
// 如果进来前有声音在播放,令其停止
if let audioPlayer = YepAudioService.sharedManager.audioPlayer where audioPlayer.playing {
audioPlayer.pause()
} // TODO: delete
AudioBot.stopPlay()
}
// MARK: - Actions
@IBAction private func cancel(sender: UIBarButtonItem) {
AudioBot.stopPlay()
dismissViewControllerAnimated(true) {
AudioBot.stopRecord { _, _, _ in
}
}
}
@IBAction private func next(sender: UIBarButtonItem) {
AudioBot.stopPlay()
if let feedVoice = feedVoice {
performSegueWithIdentifier("showNewFeed", sender: Box(feedVoice))
}
}
@IBAction private func voiceRecord(sender: UIButton) {
if state == .Recording {
AudioBot.stopRecord { [weak self] fileURL, duration, decibelSamples in
guard duration > YepConfig.AudioRecord.shortestDuration else {
YepAlert.alertSorry(message: NSLocalizedString("Voice recording time is too short!", comment: ""), inViewController: self, withDismissAction: { [weak self] in
self?.state = .Default
})
return
}
let compressedDecibelSamples = AudioBot.compressDecibelSamples(decibelSamples, withSamplingInterval: 1, minNumberOfDecibelSamples: 10, maxNumberOfDecibelSamples: 50)
let feedVoice = FeedVoice(fileURL: fileURL, sampleValuesCount: decibelSamples.count, limitedSampleValues: compressedDecibelSamples.map({ CGFloat($0) }))
self?.feedVoice = feedVoice
self?.state = .FinishRecord
}
} else {
proposeToAccess(.Microphone, agreed: { [weak self] in
do {
let decibelSamplePeriodicReport: AudioBot.PeriodicReport = (reportingFrequency: 10, report: { decibelSample in
SafeDispatch.async { [weak self] in
let value = CGFloat(decibelSample)
self?.sampleValues.append(value)
self?.voiceRecordSampleView.appendSampleValue(value)
}
})
AudioBot.mixWithOthersWhenRecording = true
try AudioBot.startRecordAudioToFileURL(nil, forUsage: .Normal, withDecibelSamplePeriodicReport: decibelSamplePeriodicReport)
self?.state = .Recording
} catch let error {
println("record error: \(error)")
}
}, rejected: { [weak self] in
self?.alertCanNotAccessMicrophone()
})
}
}
@IBAction private func playOrPauseAudio(sender: UIButton) {
if AudioBot.playing {
AudioBot.pausePlay()
audioPlaying = false
} else {
guard let fileURL = feedVoice?.fileURL else {
return
}
do {
let progressPeriodicReport: AudioBot.PeriodicReport = (reportingFrequency: 60, report: { progress in
//println("progress: \(progress)")
})
try AudioBot.startPlayAudioAtFileURL(fileURL, fromTime: audioPlayedDuration, withProgressPeriodicReport: progressPeriodicReport, finish: { [weak self] success in
self?.audioPlayedDuration = 0
if success {
self?.state = .FinishRecord
}
})
AudioBot.reportPlayingDuration = { [weak self] duration in
self?.audioPlayedDuration = duration
}
audioPlaying = true
} catch let error {
println("AudioBot: \(error)")
}
}
}
@IBAction private func reset(sender: UIButton) {
state = .Default
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let identifier = segue.identifier else {
return
}
switch identifier {
case "showNewFeed":
if let feedVoice = (sender as? Box<FeedVoice>)?.value {
let vc = segue.destinationViewController as! NewFeedViewController
vc.attachment = .Voice(feedVoice)
vc.preparedSkill = preparedSkill
vc.beforeUploadingFeedAction = beforeUploadingFeedAction
vc.afterCreatedFeedAction = afterCreatedFeedAction
vc.getFeedsViewController = getFeedsViewController
}
default:
break
}
}
}
| mit | 4fe098e5df658f3ed88bc2f32ad59015 | 32.472303 | 181 | 0.566937 | 5.369972 | false | false | false | false |
Meru-Interactive/iOSC | swiftOSC/Elements/OSCBundle.swift | 2 | 1319 | import Foundation
public class OSCBundle: OSCElement, CustomStringConvertible {
//MARK: Properties
public var timetag: Timetag
public var elements:[OSCElement] = []
public var data: Data {
get {
var data = Data()
//add "#bundle" tag
data.append("#bundle".toDataBase32())
//add timetag
data.append(timetag.data)
//add elements data
for element in elements {
let elementData = element.data
data.append(Int32(elementData.count).toData())
data.append(element.data)
}
return data
}
}
public var description: String {
get {
return "OSCBundle [Timetag<\(self.timetag)> Elements<\(elements.count)>]"
}
}
//MARK: Initializers
public init(_ timetag: Timetag){
self.timetag = timetag
}
public init (_ timetag: Timetag, _ elements: OSCElement...){
self.timetag = timetag
self.elements = elements
}
public init (_ elements: OSCElement...){
self.timetag = 1
self.elements = elements
}
//MARK: Methods
public func add(_ elements: OSCElement...){
self.elements += elements
}
}
| mit | 52623378285019f3b5bb45c8a42414af | 25.918367 | 85 | 0.535254 | 4.595819 | false | false | false | false |
briancroom/BackgroundFetchLogger | BackgroundFetchLogger/Logger.swift | 1 | 1986 | import Foundation
struct LogEvent : Printable {
let eventName : String
let timestamp : NSDate
static func fromDict(dict: NSDictionary) -> LogEvent {
return LogEvent(eventName: dict["eventName"] as? String ?? "", timestamp: NSDate(timeIntervalSince1970: (dict["timestamp"] as? NSNumber)?.doubleValue ?? 0))
}
func toDict() -> NSDictionary {
return ["eventName": eventName, "timestamp": timestamp.timeIntervalSince1970]
}
private static var dateFormatter:NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .ShortStyle
return formatter
}()
var description: String {
get {
return "\(LogEvent.dateFormatter.stringFromDate(timestamp)): \(eventName)"
}
}
}
class Logger {
typealias Log = [LogEvent]
typealias Observer = LogEvent -> ()
private let logURL: NSURL
private var observers: [Observer] = []
var events: Log = []
init(logURL: NSURL) {
self.logURL = logURL
events = loadEvents()
}
func logEvent(eventName: String) {
let event = LogEvent(eventName: eventName, timestamp: NSDate())
events.append(event)
saveEvents()
notifyObserversOfEvent(event)
}
func addObserver(observer: Observer) {
observers.append(observer)
}
private func timestampString() -> String {
let formatter = NSDateFormatter()
return formatter.stringFromDate(NSDate())
}
private func saveEvents() {
(events.map { $0.toDict() } as NSArray).writeToURL(logURL, atomically: true)
}
private func loadEvents() -> Log {
let array = NSArray(contentsOfURL: logURL) ?? []
return (array as [NSDictionary]).map { LogEvent.fromDict($0) }
}
private func notifyObserversOfEvent(event: LogEvent) {
for observer in observers {
observer(event)
}
}
}
| mit | a500fd5aa12689c2d40a43f45cee233d | 26.205479 | 164 | 0.625378 | 4.71734 | false | false | false | false |
king7532/MyContacts | MyContacts/AppDelegate.swift | 1 | 4946 | //
// AppDelegate.swift
// MyContacts
//
// Created by Benjamin King on 3/12/15.
// Copyright (c) 2015 Benjamin King. All rights reserved.
//
import UIKit
import AddressBook
import AddressBookUI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UINavigationControllerDelegate, ABPeoplePickerNavigationControllerDelegate, ABPersonViewControllerDelegate {
var window: UIWindow?
var addressBook: ABAddressBook!
var masterNav: UINavigationController?
// MARK: - UIApplicationDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow.init(frame: UIScreen.mainScreen().bounds)
self.masterNav = UINavigationController.init()
self.masterNav?.delegate = self
self.window?.rootViewController = self.masterNav?
self.window?.makeKeyAndVisible()
self.checkAddressBookAccess()
return true
}
func checkAddressBookAccess() {
switch(ABAddressBookGetAuthorizationStatus()) {
case .Authorized: self.accessGrantedForAddressBook()
case .NotDetermined: self.requestAddressBookAccess()
case .Denied: fallthrough
case .Restricted:
println("Address Book access either Denied or Restricted")
}
}
func requestAddressBookAccess() {
ABAddressBookRequestAccessWithCompletion(addressBook) {
(granted: Bool, err: CFError!) in
if(granted) {
dispatch_async(dispatch_get_main_queue()) {
self.accessGrantedForAddressBook()
}
} else {
println("ABAddressBookRequestAccessWithCompletion handler got denied!")
}
}
}
func accessGrantedForAddressBook() {
println("accessGrantedForAddressBook")
var err: Unmanaged<CFError>? = nil
let ab = ABAddressBookCreateWithOptions(nil, &err)
if err == nil {
self.addressBook = ab.takeRetainedValue()
} else {
assertionFailure("Could not create Address Book!")
// Tell the user to go to Settings.app -> Privacy -> Contacts -> Enable ABC
}
showPeoplePickerController()
}
func showPeoplePickerController() {
println("showPeoplePickerController")
let picker = ABPeoplePickerNavigationController()
picker.peoplePickerDelegate = self
// This is nil.... apparently this started in iOS 8
//println("ABPeoplePickerNavigationController.topViewController = \(picker.topViewController?)")
// This crashes!
//self.masterNav?.setViewControllers([picker.topViewController], animated: true)
// This the only way I was able to add ABPeoplePicker to my root UINavigationController
self.masterNav?.view.addSubview(picker.view) // This must come before addChildViewController!!!
self.masterNav?.addChildViewController(picker)
picker.didMoveToParentViewController(self.masterNav?)
}
// MARK: - ABPeoplePickerNavigationControllerDelegate
func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, didSelectPerson person: ABRecord!) {
let personVC = ABPersonViewController()
personVC.personViewDelegate = self
personVC.allowsEditing = true
personVC.allowsActions = true
personVC.displayedPerson = person
// This appears to do nothing :(
self.masterNav?.setNavigationBarHidden(false, animated: false)
// This works but there is no navigation bar!? WHY? Please help me :|
self.masterNav?.showViewController(personVC, sender: nil)
// Does not work!
//self.masterNav?.view.addSubview(personVC.view)
//self.masterNav?.addChildViewController(personVC)
}
func peoplePickerNavigationControllerDidCancel(peoplePicker: ABPeoplePickerNavigationController!) {
println("peoplePickerNavigationControllerDidCancel")
}
// MARK: - ABPersonViewControllerDelegate
func personViewController(personViewController: ABPersonViewController!, shouldPerformDefaultActionForPerson person: ABRecord!, property: ABPropertyID, identifier: ABMultiValueIdentifier) -> Bool {
println("personViewController - shouldPerformDefaultActionForPerson - property - identifier")
return true
}
// MARK: - UINavigationControllerDelegate
func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
println("navigationController: \(navigationController) didShowViewController: \(viewController)")
println("navigationBar: \(navigationController.navigationBar)")
}
}
| unlicense | 53a2109447771836427f04f4fd4b7c99 | 37.640625 | 201 | 0.682572 | 5.784795 | false | false | false | false |
apple/swift | test/IRGen/ptrauth-dynamic_replaceable_opaque_return.swift | 4 | 3030 | // RUN: %target-swift-frontend -disable-availability-checking -module-name A -swift-version 5 -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=arm64e
// CHECK: @"$s1A3baryQrSiFQOMk" = global %swift.dyn_repl_link_entry { {{.*}}@"$s1A3baryQrSiFQOMh.ptrauth" to i8*), %swift.dyn_repl_link_entry* null }
// CHECK: @"$s1A3baryQrSiFQOMh.ptrauth" = private constant { i8*, i32, i64, i64 } { {{.*}}@"$s1A3baryQrSiFQOMh" to i8*), i32 0, i64 ptrtoint (%swift.dyn_repl_link_entry* @"$s1A3baryQrSiFQOMk" to i64), i64 44678 }, section "llvm.ptrauth"
// CHECK: @"$s1A3baryQrSiFQOMj" = constant %swift.dyn_repl_key { {{.*}}%swift.dyn_repl_link_entry* @"$s1A3baryQrSiFQOMk"{{.*}}, i32 44678 }, section "__TEXT,__const"
// CHECK: @"$s1A16_replacement_bar1yQrSi_tFQOMk" = global %swift.dyn_repl_link_entry zeroinitializer
// CHECK: @"\01l_unnamed_dynamic_replacements" =
// CHECK: private constant { i32, i32, [2 x { i32, i32, i32, i32 }] }
// CHECK: { i32 0, i32 2, [2 x { i32, i32, i32, i32 }] [
// CHECK: { i32, i32, i32, i32 } { {{.*}}%swift.dyn_repl_key* @"$s1A3baryQrSiFTx"{{.*}}@"$s1A16_replacement_bar1yQrSi_tF"{{.*}}%swift.dyn_repl_link_entry* @"$s1A16_replacement_bar1yQrSi_tFTX"{{.*}}, i32 0 },
// CHECK: { i32, i32, i32, i32 } { {{.*}}%swift.dyn_repl_key* @"$s1A3baryQrSiFQOMj"{{.*}},{{.*}}@"$s1A16_replacement_bar1yQrSi_tFQOMg"{{.*}},{{.*}}@"$s1A16_replacement_bar1yQrSi_tFQOMk"{{.*}}, i32 0 }] }, section "__TEXT,__const", align 8
public protocol P {
func myValue() -> Int
}
extension Int: P {
public func myValue() -> Int {
return self
}
}
// Opaque result type descriptor accessor for bar.
// CHECK-LABEL: define swiftcc %swift.type_descriptor* @"$s1A3baryQrSiFQOMg"()
// CHECK: entry:
// CHECK: %0 = load i8*, i8** getelementptr inbounds (%swift.dyn_repl_link_entry, %swift.dyn_repl_link_entry* @"$s1A3baryQrSiFQOMk", i32 0, i32 0)
// CHECK: %1 = bitcast i8* %0 to %swift.type_descriptor* ()*
// CHECK: %2 = call i64 @llvm.ptrauth.blend(i64 ptrtoint (%swift.dyn_repl_link_entry* @"$s1A3baryQrSiFQOMk" to i64), i64 44678)
// CHECK: %3 = tail call swiftcc %swift.type_descriptor* %1() [ "ptrauth"(i32 0, i64 %2) ]
// CHECK: ret %swift.type_descriptor* %3
// CHECK: }
// Opaque result type descriptor accessor impl.
// CHECK-LABEL: define swiftcc %swift.type_descriptor* @"$s1A3baryQrSiFQOMh"()
// CHECK: entry:
// CHECK: ret %swift.type_descriptor* bitcast ({{.*}}* @"$s1A3baryQrSiFQOMQ" to %swift.type_descriptor*)
// CHECK: }
public dynamic func bar(_ x: Int) -> some P {
return x
}
struct Pair : P {
var x = 0
var y = 1
func myValue() -> Int{
return y
}
}
// Opaque result type descriptor accessor for _replacement_bar.
// CHECK: define swiftcc %swift.type_descriptor* @"$s1A16_replacement_bar1yQrSi_tFQOMg"()
// CHECK: entry:
// CHECK: ret %swift.type_descriptor* bitcast ({{.*}} @"$s1A16_replacement_bar1yQrSi_tFQOMQ" to %swift.type_descriptor*)
// CHECK: }
@_dynamicReplacement(for:bar(_:))
public func _replacement_bar(y x: Int) -> some P {
return Pair()
}
| apache-2.0 | 6a9fb4136d4bedeeeaff02b1fe9e1a51 | 50.355932 | 242 | 0.653795 | 2.757052 | false | false | false | false |
NetBUG/classintouch | app/ClassInTouch/ClassInTouch/CreateViewController.swift | 1 | 1605 | //
// CreateViewController.swift
// ClassInTouch
//
// Created by Justin Jia on 10/24/15.
// Copyright © 2015 ClassInTouch. All rights reserved.
//
import UIKit
class CreateViewController: UIViewController {
@IBOutlet weak var titleField: UITextField!
var longitude: Float?
var latitude: Float?
lazy var context: NSManagedObjectContext = {
let delegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
return delegate.managedObjectContext
}()
lazy var networkHandler: PGNetworkHandler = {
return PGNetworkHandler(baseURL: NSURL(string: "http://classintouch.club"))
}()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.titleField.becomeFirstResponder()
}
@IBAction func cancelButtonTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func doneButtonTapped(sender: AnyObject) {
guard let longitude = self.longitude else {
return
}
guard let latitude = self.latitude else {
return
}
guard let name = titleField.text else {
return
}
self.view.userInteractionEnabled = false
networkHandler.createClass(longitude, latitude: latitude, name: name, context: context, success: { (result) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}, failure: nil) { () -> Void in
self.view.userInteractionEnabled = true
}
}
}
| apache-2.0 | 88cb5800eff76015faac1c9750375248 | 27.140351 | 126 | 0.650249 | 5.10828 | false | false | false | false |
taoguan/firefox-ios | Client/Frontend/Browser/BrowserViewController.swift | 1 | 94220 | /* 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
private let log = Logger.browserLogger
private let OKString = NSLocalizedString("OK", comment: "OK button")
private let CancelString = NSLocalizedString("Cancel", comment: "Cancel button")
private let OpenInString = NSLocalizedString("Open in…", comment: "String indicating that the file can be opened in another application on the device")
private let KVOLoading = "loading"
private let KVOEstimatedProgress = "estimatedProgress"
private let KVOURL = "URL"
private let KVOCanGoBack = "canGoBack"
private let KVOCanGoForward = "canGoForward"
private let KVOContentSize = "contentSize"
private let ActionSheetTitleMaxLength = 120
private struct BrowserViewControllerUX {
private static let BackgroundColor = UIConstants.AppBackgroundColor
private static let ShowHeaderTapAreaHeight: CGFloat = 32
private static let BookmarkStarAnimationDuration: Double = 0.5
private static let BookmarkStarAnimationOffset: CGFloat = 80
}
class BrowserViewController: UIViewController {
var homePanelController: HomePanelViewController?
var webViewContainer: UIView!
var urlBar: URLBarView!
var readerModeBar: ReaderModeBarView?
private var statusBarOverlay: UIView!
private var toolbar: BrowserToolbar?
private var searchController: SearchViewController?
private let uriFixup = URIFixup()
private var screenshotHelper: ScreenshotHelper!
private var homePanelIsInline = false
private var searchLoader: SearchLoader!
private let snackBars = UIView()
private let auralProgress = AuralProgressBar()
// location label actions
private var pasteGoAction: AccessibleAction!
private var pasteAction: AccessibleAction!
private var copyAddressAction: AccessibleAction!
private weak var tabTrayController: TabTrayController!
private let profile: Profile
let tabManager: TabManager
// These views wrap the urlbar and toolbar to provide background effects on them
var header: UIView!
var headerBackdrop: UIView!
var footer: UIView!
var footerBackdrop: UIView!
private var footerBackground: UIView!
private var topTouchArea: UIButton!
// Backdrop used for displaying greyed background for private tabs
private var webViewContainerBackdrop: UIView!
private var scrollController = BrowserScrollingController()
private var keyboardState: KeyboardState?
let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"]
// Tracking navigation items to record history types.
// TODO: weak references?
var ignoredNavigation = Set<WKNavigation>()
var typedNavigation = [WKNavigation: VisitType]()
var navigationToolbar: BrowserToolbarProtocol {
return toolbar ?? urlBar
}
init(profile: Profile, tabManager: TabManager) {
self.profile = profile
self.tabManager = tabManager
super.init(nibName: nil, bundle: nil)
didInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.AllButUpsideDown
} else {
return UIInterfaceOrientationMask.All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
log.debug("BVC received memory warning")
}
private func didInit() {
screenshotHelper = BrowserScreenshotHelper(controller: self)
tabManager.addDelegate(self)
tabManager.addNavigationDelegate(self)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
func shouldShowFooterForTraitCollection(previousTraitCollection: UITraitCollection) -> Bool {
return previousTraitCollection.verticalSizeClass != .Compact &&
previousTraitCollection.horizontalSizeClass != .Regular
}
func toggleSnackBarVisibility(show show: Bool) {
if show {
UIView.animateWithDuration(0.1, animations: { self.snackBars.hidden = false })
} else {
snackBars.hidden = true
}
}
private func updateToolbarStateForTraitCollection(newCollection: UITraitCollection) {
let showToolbar = shouldShowFooterForTraitCollection(newCollection)
urlBar.setShowToolbar(!showToolbar)
toolbar?.removeFromSuperview()
toolbar?.browserToolbarDelegate = nil
footerBackground?.removeFromSuperview()
footerBackground = nil
toolbar = nil
if showToolbar {
toolbar = BrowserToolbar()
toolbar?.browserToolbarDelegate = self
footerBackground = wrapInEffect(toolbar!, parent: footer)
}
view.setNeedsUpdateConstraints()
if let home = homePanelController {
home.view.setNeedsUpdateConstraints()
}
if let tab = tabManager.selectedTab,
webView = tab.webView {
updateURLBarDisplayURL(tab)
navigationToolbar.updateBackStatus(webView.canGoBack)
navigationToolbar.updateForwardStatus(webView.canGoForward)
navigationToolbar.updateReloadStatus(tab.loading ?? false)
}
}
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
updateToolbarStateForTraitCollection(newCollection)
// WKWebView looks like it has a bug where it doesn't invalidate it's visible area when the user
// performs a device rotation. Since scrolling calls
// _updateVisibleContentRects (https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKWebView.mm#L1430)
// this method nudges the web view's scroll view by a single pixel to force it to invalidate.
if let scrollView = self.tabManager.selectedTab?.webView?.scrollView {
let contentOffset = scrollView.contentOffset
coordinator.animateAlongsideTransition({ context in
scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y + 1), animated: true)
self.scrollController.showToolbars(animated: false)
}, completion: { context in
scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y), animated: false)
})
}
}
func SELtappedTopArea() {
scrollController.showToolbars(animated: true)
}
func SELappWillResignActiveNotification() {
// If we are displying a private tab, hide any elements in the browser that we wouldn't want shown
// when the app is in the home switcher
guard let privateTab = tabManager.selectedTab where privateTab.isPrivate else {
return
}
webViewContainerBackdrop.alpha = 1
webViewContainer.alpha = 0
urlBar.locationView.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.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.webViewContainer.alpha = 1
self.urlBar.locationView.alpha = 1
self.view.backgroundColor = UIColor.clearColor()
}, completion: { _ in
self.webViewContainerBackdrop.alpha = 0
})
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: BookmarkStatusChangedNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELBookmarkStatusDidChange:", name: BookmarkStatusChangedNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELappWillResignActiveNotification", name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELappDidBecomeActiveNotification", name: UIApplicationDidBecomeActiveNotification, object: nil)
KeyboardHelper.defaultHelper.addDelegate(self)
footerBackdrop = UIView()
footerBackdrop.backgroundColor = UIColor.whiteColor()
view.addSubview(footerBackdrop)
headerBackdrop = UIView()
headerBackdrop.backgroundColor = UIColor.whiteColor()
view.addSubview(headerBackdrop)
webViewContainerBackdrop = UIView()
webViewContainerBackdrop.backgroundColor = UIColor.grayColor()
webViewContainerBackdrop.alpha = 0
view.addSubview(webViewContainerBackdrop)
webViewContainer = UIView()
view.addSubview(webViewContainer)
// Temporary work around for covering the non-clipped web view content
statusBarOverlay = UIView()
statusBarOverlay.backgroundColor = BrowserViewControllerUX.BackgroundColor
view.addSubview(statusBarOverlay)
topTouchArea = UIButton()
topTouchArea.isAccessibilityElement = false
topTouchArea.addTarget(self, action: "SELtappedTopArea", forControlEvents: UIControlEvents.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.browserToolbarDelegate = self
header = wrapInEffect(urlBar, parent: view, backgroundColor: nil)
// 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.generalPasteboard().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.generalPasteboard().string {
// Enter overlay mode and fire the text entered callback to make the search controller appear.
self.urlBar.enterOverlayMode(pasteboardContents, pasted: true)
self.urlBar(self.urlBar, didEnterText: pasteboardContents)
return true
}
return false
})
copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in
if let urlString = self.urlBar.currentURL?.absoluteString {
UIPasteboard.generalPasteboard().string = urlString
}
return true
})
searchLoader = SearchLoader(profile: profile, urlBar: urlBar)
footer = UIView()
self.view.addSubview(footer)
self.view.addSubview(snackBars)
snackBars.backgroundColor = UIColor.clearColor()
scrollController.urlBar = urlBar
scrollController.header = header
scrollController.footer = footer
scrollController.snackBars = snackBars
self.updateToolbarStateForTraitCollection(self.traitCollection)
setupConstraints()
}
private func setupConstraints() {
urlBar.snp_makeConstraints { make in
make.edges.equalTo(self.header)
}
let viewBindings: [String: AnyObject] = [
"header": header,
"topLayoutGuide": topLayoutGuide
]
let topConstraint = NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide][header]", options: [], metrics: nil, views: viewBindings)
view.addConstraints(topConstraint)
scrollController.headerTopConstraint = topConstraint.first
header.snp_makeConstraints { make in
make.height.equalTo(UIConstants.ToolbarHeight)
make.left.right.equalTo(self.view)
}
headerBackdrop.snp_makeConstraints { make in
make.edges.equalTo(self.header)
}
webViewContainerBackdrop.snp_makeConstraints { make in
make.edges.equalTo(webViewContainer)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
statusBarOverlay.snp_remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(self.topLayoutGuide.length)
}
}
func loadQueuedTabs() {
log.debug("Loading queued tabs in the background.")
// Chain off of a trivial deferred in order to run on the background queue.
succeed().upon() { res in
self.dequeueQueuedTabs()
}
}
private func dequeueQueuedTabs() {
assert(!NSThread.currentThread().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.
log.debug("Queue. Count: \(cursor.count).")
if cursor.count > 0 {
var urls = [NSURL]()
for row in cursor {
if let url = row?.url.asURL {
log.debug("Queuing \(url).")
urls.append(url)
}
}
if !urls.isEmpty {
dispatch_async(dispatch_get_main_queue()) {
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()
}
}
func startTrackingAccessibilityStatus() {
NSNotificationCenter.defaultCenter().addObserverForName(UIAccessibilityVoiceOverStatusChanged, object: nil, queue: nil) { (notification) -> Void in
self.auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning()
}
auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning()
}
func stopTrackingAccessibilityStatus() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIAccessibilityVoiceOverStatusChanged, object: nil)
auralProgress.hidden = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// On iPhone, if we are about to show the On-Boarding, blank out the browser 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.currentDevice().userInterfaceIdiom == .Phone {
self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0
}
if activeCrashReporter?.previouslyCrashed ?? false {
// Reset previous crash state
activeCrashReporter?.resetPreviousCrashState()
let crashPrompt = UIAlertView(
title: CrashPromptMessaging.Title,
message: CrashPromptMessaging.Description,
delegate: self,
cancelButtonTitle: CrashPromptMessaging.Negative,
otherButtonTitles: CrashPromptMessaging.Affirmative
)
crashPrompt.show()
} else {
restoreTabs()
}
}
private func restoreTabs() {
if tabManager.count == 0 && !AppConstants.IsRunningTest {
tabManager.restoreTabs()
}
if tabManager.count == 0 {
let tab = tabManager.addTab()
tabManager.selectTab(tab)
}
}
override func viewDidAppear(animated: Bool) {
startTrackingAccessibilityStatus()
presentIntroViewController()
super.viewDidAppear(animated)
}
override func viewDidDisappear(animated: Bool) {
stopTrackingAccessibilityStatus()
}
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).constraint
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)
}
if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp_top)
} else {
make.bottom.equalTo(self.view)
}
}
// Setup the bottom toolbar
toolbar?.snp_remakeConstraints { make in
make.edges.equalTo(self.footerBackground!)
make.height.equalTo(UIConstants.ToolbarHeight)
}
footer.snp_remakeConstraints { make in
scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp_bottom).constraint
make.top.equalTo(self.snackBars.snp_top)
make.leading.trailing.equalTo(self.view)
}
footerBackdrop.snp_remakeConstraints { make in
make.edges.equalTo(self.footer)
}
adjustFooterSize(nil)
footerBackground?.snp_remakeConstraints { make in
make.bottom.left.right.equalTo(self.footer)
make.height.equalTo(UIConstants.ToolbarHeight)
}
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)
}
}
}
private func wrapInEffect(view: UIView, parent: UIView) -> UIView {
return self.wrapInEffect(view, parent: parent, backgroundColor: UIColor.clearColor())
}
private func wrapInEffect(view: UIView, parent: UIView, backgroundColor: UIColor?) -> UIView {
let effect = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight))
effect.clipsToBounds = false
effect.translatesAutoresizingMaskIntoConstraints = false
if let _ = backgroundColor {
view.backgroundColor = backgroundColor
}
effect.addSubview(view)
parent.addSubview(effect)
return effect
}
private func showHomePanelController(inline inline: Bool) {
homePanelIsInline = inline
if homePanelController == nil {
homePanelController = HomePanelViewController()
homePanelController!.profile = profile
homePanelController!.delegate = self
homePanelController!.url = tabManager.selectedTab?.displayURL
homePanelController!.view.alpha = 0
addChildViewController(homePanelController!)
view.addSubview(homePanelController!.view)
homePanelController!.didMoveToParentViewController(self)
}
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?.componentsSeparatedByString("=") {
if let last = numberArray.last, lastInt = Int(last) {
newSelectedButtonIndex = lastInt
}
}
homePanelController?.selectedButtonIndex = 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.animateWithDuration(0.2, animations: { () -> Void in
self.homePanelController!.view.alpha = 1
}, completion: { finished in
if finished {
self.webViewContainer.accessibilityElementsHidden = true
self.stopTrackingAccessibilityStatus()
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
}
})
view.setNeedsUpdateConstraints()
}
private func hideHomePanelController() {
if let controller = homePanelController {
UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in
controller.view.alpha = 0
}, completion: { finished in
if finished {
controller.willMoveToParentViewController(nil)
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.homePanelController = nil
self.webViewContainer.accessibilityElementsHidden = false
self.startTrackingAccessibilityStatus()
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// Refresh the reading view toolbar since the article record may have changed
if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode where readerMode.state == .Active {
self.showReaderModeBar(animated: false)
}
}
})
}
}
private func updateInContentHomePanel(url: NSURL?) {
if !urlBar.inOverlayMode {
if AboutUtils.isAboutHomeURL(url){
showHomePanelController(inline: (tabManager.selectedTab?.canGoForward ?? false || tabManager.selectedTab?.canGoBack ?? false))
} else {
hideHomePanelController()
}
}
}
private func showSearchController() {
if searchController != nil {
return
}
searchController = SearchViewController()
searchController!.searchEngines = profile.searchEngines
searchController!.searchDelegate = self
searchController!.profile = self.profile
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?.hidden = true
searchController!.didMoveToParentViewController(self)
}
private func hideSearchController() {
if let searchController = searchController {
searchController.willMoveToParentViewController(nil)
searchController.view.removeFromSuperview()
searchController.removeFromParentViewController()
self.searchController = nil
homePanelController?.view?.hidden = false
}
}
private func finishEditingAndSubmit(url: NSURL, visitType: VisitType) {
urlBar.currentURL = url
urlBar.leaveOverlayMode()
if let tab = tabManager.selectedTab,
let nav = tab.loadRequest(NSURLRequest(URL: url)) {
self.recordNavigationInTab(tab, navigation: nav, visitType: visitType)
}
}
func addBookmark(url: String, title: String?) {
let shareItem = ShareItem(url: url, title: title, favicon: nil)
profile.bookmarks.shareItem(shareItem)
animateBookmarkStar()
// Dispatch to the main thread to update the UI
dispatch_async(dispatch_get_main_queue()) { _ in
self.toolbar?.updateBookmarkStatus(true)
self.urlBar.updateBookmarkStatus(true)
}
}
private func animateBookmarkStar() {
let offset: CGFloat
let button: UIButton!
if let toolbar: BrowserToolbar = self.toolbar {
offset = BrowserViewControllerUX.BookmarkStarAnimationOffset * -1
button = toolbar.bookmarkButton
} else {
offset = BrowserViewControllerUX.BookmarkStarAnimationOffset
button = self.urlBar.bookmarkButton
}
let offToolbar = CGAffineTransformMakeTranslation(0, offset)
UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 2.0, options: [], animations: { () -> Void in
button.transform = offToolbar
let rotation = CABasicAnimation(keyPath: "transform.rotation")
rotation.toValue = CGFloat(M_PI * 2.0)
rotation.cumulative = true
rotation.duration = BrowserViewControllerUX.BookmarkStarAnimationDuration + 0.075
rotation.repeatCount = 1.0
rotation.timingFunction = CAMediaTimingFunction(controlPoints: 0.32, 0.70 ,0.18 ,1.00)
button.imageView?.layer.addAnimation(rotation, forKey: "rotateStar")
}, completion: { finished in
UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.15, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in
button.transform = CGAffineTransformIdentity
}, completion: nil)
})
}
private func removeBookmark(url: String) {
profile.bookmarks.removeByURL(url).uponQueue(dispatch_get_main_queue()) { res in
if res.isSuccess {
self.toolbar?.updateBookmarkStatus(false)
self.urlBar.updateBookmarkStatus(false)
}
}
}
func SELBookmarkStatusDidChange(notification: NSNotification) {
if let bookmark = notification.object as? BookmarkItem {
if bookmark.url == urlBar.currentURL?.absoluteString {
if let userInfo = notification.userInfo as? Dictionary<String, Bool>{
if let added = userInfo["added"]{
self.toolbar?.updateBookmarkStatus(added)
self.urlBar.updateBookmarkStatus(added)
}
}
}
}
}
override func accessibilityPerformEscape() -> Bool {
if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
return true
} else if let selectedTab = tabManager.selectedTab where selectedTab.canGoBack {
selectedTab.goBack()
return true
}
return false
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
let webView = object as! WKWebView
if webView !== tabManager.selectedTab?.webView {
return
}
guard let path = keyPath else { assertionFailure("Unhandled KVO key: \(keyPath)"); return }
switch path {
case KVOEstimatedProgress:
guard let progress = change?[NSKeyValueChangeNewKey] as? Float else { break }
urlBar.updateProgressBar(progress)
// when loading is stopped, KVOLoading is fired first, and only then KVOEstimatedProgress with progress 1.0 which would leave the progress bar running
if progress != 1.0 || tabManager.selectedTab?.loading ?? false {
auralProgress.progress = Double(progress)
}
case KVOLoading:
guard let loading = change?[NSKeyValueChangeNewKey] as? Bool else { break }
toolbar?.updateReloadStatus(loading)
urlBar.updateReloadStatus(loading)
auralProgress.progress = loading ? 0 : nil
case KVOURL:
if let tab = tabManager.selectedTab where tab.webView?.URL == nil {
log.debug("URL is nil!")
}
if let tab = tabManager.selectedTab where tab.webView === webView && !tab.restoring {
updateUIForReaderHomeStateForTab(tab)
}
case KVOCanGoBack:
guard let canGoBack = change?[NSKeyValueChangeNewKey] as? Bool else { break }
navigationToolbar.updateBackStatus(canGoBack)
case KVOCanGoForward:
guard let canGoForward = change?[NSKeyValueChangeNewKey] as? Bool else { break }
navigationToolbar.updateForwardStatus(canGoForward)
default:
assertionFailure("Unhandled KVO key: \(keyPath)")
}
}
private func updateUIForReaderHomeStateForTab(tab: Browser) {
updateURLBarDisplayURL(tab)
scrollController.showToolbars(animated: false)
if let url = tab.url {
if ReaderModeUtils.isReaderModeURL(url) {
showReaderModeBar(animated: false)
} else {
hideReaderModeBar(animated: false)
}
updateInContentHomePanel(url)
}
}
private func isWhitelistedUrl(url: NSURL) -> Bool {
for entry in WhiteListedUrls {
if let _ = url.absoluteString.rangeOfString(entry, options: .RegularExpressionSearch) {
return UIApplication.sharedApplication().canOpenURL(url)
}
}
return false
}
/// Updates the URL bar text and button states.
/// Call this whenever the page URL changes.
private func updateURLBarDisplayURL(tab: Browser) {
urlBar.currentURL = tab.displayURL
let isPage = (tab.displayURL != nil) ? isWebPage(tab.displayURL!) : false
navigationToolbar.updatePageStatus(isWebPage: isPage)
if let url = tab.displayURL?.absoluteString {
profile.bookmarks.isBookmarked(url, success: { bookmarked in
self.navigationToolbar.updateBookmarkStatus(bookmarked)
}, failure: { err in
log.error("Error getting bookmark status: \(err).")
})
}
}
func openURLInNewTab(url: NSURL) {
let tab = tabManager.addTab(NSURLRequest(URL: url))
tabManager.selectTab(tab)
}
}
/**
* History visit management.
* TODO: this should be expanded to track various visit types; see Bug 1166084.
*/
extension BrowserViewController {
func ignoreNavigationInTab(tab: Browser, navigation: WKNavigation) {
self.ignoredNavigation.insert(navigation)
}
func recordNavigationInTab(tab: Browser, navigation: WKNavigation, visitType: VisitType) {
self.typedNavigation[navigation] = visitType
}
/**
* Untrack and do the right thing.
*/
func getVisitTypeForTab(tab: Browser, 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.removeValueForKey(navigation) ?? VisitType.Link
}
}
extension BrowserViewController: URLBarDelegate {
func urlBarDidPressReload(urlBar: URLBarView) {
tabManager.selectedTab?.reload()
}
func urlBarDidPressStop(urlBar: URLBarView) {
tabManager.selectedTab?.stop()
}
func urlBarDidPressTabs(urlBar: URLBarView) {
let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile)
if let tab = tabManager.selectedTab {
tab.setScreenshot(screenshotHelper.takeScreenshot(tab, aspectRatio: 0, quality: 1))
}
self.navigationController?.pushViewController(tabTrayController, animated: true)
self.tabTrayController = tabTrayController
}
func urlBarDidPressReaderMode(urlBar: URLBarView) {
if let tab = tabManager.selectedTab {
if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode {
switch readerMode.state {
case .Available:
enableReaderMode()
case .Active:
disableReaderMode()
case .Unavailable:
break
}
}
}
}
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool {
guard let tab = tabManager.selectedTab,
url = tab.displayURL,
result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().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."))
log.error("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)")
}
return true
}
func locationActionsForURLBar(urlBar: URLBarView) -> [AccessibleAction] {
if UIPasteboard.generalPasteboard().string != nil {
return [pasteGoAction, pasteAction, copyAddressAction]
} else {
return [copyAddressAction]
}
}
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: "Cancel alert view"), style: .Cancel, handler: { (alert: UIAlertAction) -> Void in
})
longPressAlertController.addAction(cancelAction)
if let popoverPresentationController = longPressAlertController.popoverPresentationController {
popoverPresentationController.sourceView = urlBar
popoverPresentationController.sourceRect = urlBar.frame
popoverPresentationController.permittedArrowDirections = .Any
}
self.presentViewController(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(CGPointZero, animated: true)
}
}
}
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]? {
return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction }
}
func urlBar(urlBar: URLBarView, didEnterText text: String) {
searchLoader.query = text
if text.isEmpty {
hideSearchController()
} else {
showSearchController()
searchController!.searchQuery = text
}
}
func urlBar(urlBar: URLBarView, didSubmitText text: String) {
var url = uriFixup.getURL(text)
// If we can't make a valid URL, do a search query.
if url == nil {
url = profile.searchEngines.defaultEngine.searchURLForQuery(text)
}
// If we still don't have a valid URL, something is broken. Give up.
if url == nil {
log.error("Error handling URL entry: \"\(text)\".")
return
}
finishEditingAndSubmit(url!, visitType: VisitType.Typed)
}
func urlBarDidEnterOverlayMode(urlBar: URLBarView) {
showHomePanelController(inline: false)
}
func urlBarDidLeaveOverlayMode(urlBar: URLBarView) {
hideSearchController()
updateInContentHomePanel(tabManager.selectedTab?.url)
}
}
extension BrowserViewController: BrowserToolbarDelegate {
func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goBack()
}
func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
// See 1159373 - Disable long press back/forward for backforward list
// let controller = BackForwardListViewController()
// controller.listData = tabManager.selectedTab?.backList
// controller.tabManager = tabManager
// presentViewController(controller, animated: true, completion: nil)
}
func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.reload()
}
func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.stop()
}
func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goForward()
}
func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
// See 1159373 - Disable long press back/forward for backforward list
// let controller = BackForwardListViewController()
// controller.listData = tabManager.selectedTab?.forwardList
// controller.tabManager = tabManager
// presentViewController(controller, animated: true, completion: nil)
}
func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
if let tab = tabManager.selectedTab,
let url = tab.displayURL?.absoluteString {
profile.bookmarks.isBookmarked(url,
success: { isBookmarked in
if isBookmarked {
self.removeBookmark(url)
} else {
self.addBookmark(url, title: tab.title)
}
},
failure: { err in
log.error("Bookmark error: \(err).")
}
)
} else {
log.error("Bookmark error: No tab is selected, or no URL in tab.")
}
}
func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
}
func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
if let selected = tabManager.selectedTab {
if let url = selected.displayURL {
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.jobName = url.absoluteString
printInfo.outputType = .General
let renderer = BrowserPrintPageRenderer(browser: selected)
let activityItems = [printInfo, renderer, selected.title ?? url.absoluteString, url]
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
// Hide 'Add to Reading List' which currently uses Safari.
// Also hide our own View Later… after all, you're in the browser!
let viewLater = NSBundle.mainBundle().bundleIdentifier! + ".ViewLater"
activityViewController.excludedActivityTypes = [
UIActivityTypeAddToReadingList,
viewLater, // Doesn't work: rdar://19430419
]
activityViewController.completionWithItemsHandler = { activityType, completed, _, _ in
log.debug("Selected activity type: \(activityType).")
if completed {
if let selectedTab = self.tabManager.selectedTab {
// We don't know what share action the user has chosen so we simply always
// update the toolbar and reader mode bar to refelect the latest status.
self.updateURLBarDisplayURL(selectedTab)
self.updateReaderModeBar()
}
}
}
if let popoverPresentationController = activityViewController.popoverPresentationController {
// Using the button for the sourceView here results in this not showing on iPads.
popoverPresentationController.sourceView = toolbar ?? urlBar
popoverPresentationController.sourceRect = button.frame ?? button.frame
popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Up
popoverPresentationController.delegate = self
}
presentViewController(activityViewController, animated: true, completion: nil)
}
}
}
}
extension BrowserViewController: WindowCloseHelperDelegate {
func windowCloseHelper(helper: WindowCloseHelper, didRequestToCloseBrowser browser: Browser) {
tabManager.removeTab(browser)
}
}
extension BrowserViewController: BrowserDelegate {
func browser(browser: Browser, didCreateWebView webView: WKWebView) {
webViewContainer.insertSubview(webView, atIndex: 0)
webView.snp_makeConstraints { make in
make.edges.equalTo(self.webViewContainer)
}
// Observers that live as long as the tab. Make sure these are all cleared
// in willDeleteWebView below!
webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .New, context: nil)
webView.addObserver(self, forKeyPath: KVOLoading, options: .New, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .New, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .New, context: nil)
browser.webView?.addObserver(self, forKeyPath: KVOURL, options: .New, context: nil)
webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOContentSize, options: .New, context: nil)
webView.UIDelegate = self
let readerMode = ReaderMode(browser: browser)
readerMode.delegate = self
browser.addHelper(readerMode, name: ReaderMode.name())
let favicons = FaviconManager(browser: browser, profile: profile)
browser.addHelper(favicons, name: FaviconManager.name())
// only add the logins helper if the tab is not a private browsing tab
if !browser.isPrivate {
let logins = LoginsHelper(browser: browser, profile: profile)
browser.addHelper(logins, name: LoginsHelper.name())
}
let contextMenuHelper = ContextMenuHelper(browser: browser)
contextMenuHelper.delegate = self
browser.addHelper(contextMenuHelper, name: ContextMenuHelper.name())
let errorHelper = ErrorPageHelper()
browser.addHelper(errorHelper, name: ErrorPageHelper.name())
let windowCloseHelper = WindowCloseHelper(browser: browser)
windowCloseHelper.delegate = self
browser.addHelper(windowCloseHelper, name: WindowCloseHelper.name())
let sessionRestoreHelper = SessionRestoreHelper(browser: browser)
sessionRestoreHelper.delegate = self
browser.addHelper(sessionRestoreHelper, name: SessionRestoreHelper.name())
}
func browser(browser: Browser, willDeleteWebView webView: WKWebView) {
webView.removeObserver(self, forKeyPath: KVOEstimatedProgress)
webView.removeObserver(self, forKeyPath: KVOLoading)
webView.removeObserver(self, forKeyPath: KVOCanGoBack)
webView.removeObserver(self, forKeyPath: KVOCanGoForward)
webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOContentSize)
webView.removeObserver(self, forKeyPath: KVOURL)
webView.UIDelegate = nil
webView.scrollView.delegate = nil
webView.removeFromSuperview()
}
private func findSnackbar(barToFind: SnackBar) -> Int? {
let bars = snackBars.subviews
for (index, bar) in bars.enumerate() {
if bar === barToFind {
return index
}
}
return nil
}
private func adjustFooterSize(top: UIView? = nil) {
snackBars.snp_remakeConstraints { make in
let bars = self.snackBars.subviews
// if the keyboard is showing then ensure that the snackbars are positioned above it, otherwise position them above the toolbar/view bottom
if bars.count > 0 {
let view = bars[bars.count-1]
make.top.equalTo(view.snp_top)
if let state = keyboardState {
make.bottom.equalTo(-(state.intersectionHeightForView(self.view)))
} else {
make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom)
}
} else {
make.top.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom)
}
if traitCollection.horizontalSizeClass != .Regular {
make.leading.trailing.equalTo(self.footer)
self.snackBars.layer.borderWidth = 0
} else {
make.centerX.equalTo(self.footer)
make.width.equalTo(SnackBarUX.MaxWidth)
self.snackBars.layer.borderColor = UIConstants.BorderColor.CGColor
self.snackBars.layer.borderWidth = 1
}
}
}
// This removes the bar from its superview and updates constraints appropriately
private func finishRemovingBar(bar: SnackBar) {
// If there was a bar above this one, we need to remake its constraints.
if let index = findSnackbar(bar) {
// If the bar being removed isn't on the top of the list
let bars = snackBars.subviews
if index < bars.count-1 {
// Move the bar above this one
let nextbar = bars[index+1] as! SnackBar
nextbar.snp_updateConstraints { make in
// If this wasn't the bottom bar, attach to the bar below it
if index > 0 {
let bar = bars[index-1] as! SnackBar
nextbar.bottom = make.bottom.equalTo(bar.snp_top).constraint
} else {
// Otherwise, we attach it to the bottom of the snackbars
nextbar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).constraint
}
}
}
}
// Really remove the bar
bar.removeFromSuperview()
}
private func finishAddingBar(bar: SnackBar) {
snackBars.addSubview(bar)
bar.snp_remakeConstraints { make in
// If there are already bars showing, add this on top of them
let bars = self.snackBars.subviews
// Add the bar on top of the stack
// We're the new top bar in the stack, so make sure we ignore ourself
if bars.count > 1 {
let view = bars[bars.count - 2]
bar.bottom = make.bottom.equalTo(view.snp_top).offset(0).constraint
} else {
bar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).offset(0).constraint
}
make.leading.trailing.equalTo(self.snackBars)
}
}
func showBar(bar: SnackBar, animated: Bool) {
finishAddingBar(bar)
adjustFooterSize(bar)
bar.hide()
view.layoutIfNeeded()
UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in
bar.show()
self.view.layoutIfNeeded()
})
}
func removeBar(bar: SnackBar, animated: Bool) {
if let _ = findSnackbar(bar) {
UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in
bar.hide()
self.view.layoutIfNeeded()
}) { success in
// Really remove the bar
self.finishRemovingBar(bar)
// Adjust the footer size to only contain the bars
self.adjustFooterSize()
}
}
}
func removeAllBars() {
let bars = snackBars.subviews
for bar in bars {
if let bar = bar as? SnackBar {
bar.removeFromSuperview()
}
}
self.adjustFooterSize()
}
func browser(browser: Browser, didAddSnackbar bar: SnackBar) {
showBar(bar, animated: true)
}
func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) {
removeBar(bar, animated: true)
}
}
extension BrowserViewController: HomePanelViewControllerDelegate {
func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectURL url: NSURL, visitType: VisitType) {
finishEditingAndSubmit(url, visitType: visitType)
}
func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) {
if AboutUtils.isAboutHomeURL(tabManager.selectedTab?.url) {
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
}
}
extension BrowserViewController: SearchViewControllerDelegate {
func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL) {
finishEditingAndSubmit(url, visitType: VisitType.Typed)
}
func presentSearchSettingsController() {
let settingsNavigationController = SearchSettingsTableViewController()
settingsNavigationController.model = self.profile.searchEngines
let navController = UINavigationController(rootViewController: settingsNavigationController)
self.presentViewController(navController, animated: true, completion: nil)
}
}
extension BrowserViewController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) {
// 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 {
wv.endEditing(true)
wv.accessibilityLabel = nil
wv.accessibilityElementsHidden = true
wv.accessibilityIdentifier = nil
// due to screwy handling within iOS, the scrollToTop handling does not work if there are
// more than one scroll view in the view hierarchy
// we therefore have to hide all the scrollViews that we are no actually interesting in interacting with
// to ensure that scrollsToTop actually works
wv.scrollView.hidden = true
}
if let tab = selected, webView = tab.webView {
// if we have previously hidden this scrollview in order to make scrollsToTop work then
// we should ensure that it is not hidden now that it is our foreground scrollView
if webView.scrollView.hidden {
webView.scrollView.hidden = false
}
updateURLBarDisplayURL(tab)
let count = tab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count
urlBar.updateTabCount(count, animated: false)
scrollController.browser = selected
webViewContainer.addSubview(webView)
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.accessibilityIdentifier = "contentView"
webView.accessibilityElementsHidden = false
if let url = webView.URL?.absoluteString {
profile.bookmarks.isBookmarked(url, success: { bookmarked in
self.toolbar?.updateBookmarkStatus(bookmarked)
self.urlBar.updateBookmarkStatus(bookmarked)
}, failure: { err in
log.error("Error getting bookmark status: \(err).")
})
} else {
// 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()
}
}
removeAllBars()
if let bars = selected?.bars {
for bar in bars {
showBar(bar, animated: true)
}
}
navigationToolbar.updateReloadStatus(selected?.loading ?? false)
navigationToolbar.updateBackStatus(selected?.canGoBack ?? false)
navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false)
self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0))
if let readerMode = selected?.getHelper(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)
}
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) {
}
func tabManager(tabManager: TabManager, didAddTab tab: Browser, restoring: Bool) {
// If we are restoring tabs then we update the count once at the end
if !restoring {
updateTabCountUsingTabManager(tabManager)
}
tab.browserDelegate = self
}
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser) {
updateTabCountUsingTabManager(tabManager)
// browserDelegate is a weak ref (and the tab's webView may not be destroyed yet)
// so we don't expcitly unset it.
}
func tabManagerDidAddTabs(tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
func tabManagerDidRestoreTabs(tabManager: TabManager) {
updateTabCountUsingTabManager(tabManager)
}
private func isWebPage(url: NSURL) -> Bool {
let httpSchemes = ["http", "https"]
if let _ = httpSchemes.indexOf(url.scheme) {
return true
}
return false
}
private func updateTabCountUsingTabManager(tabManager: TabManager) {
if let selectedTab = tabManager.selectedTab {
let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count
urlBar.updateTabCount(max(count, 1))
}
}
}
extension BrowserViewController: WKNavigationDelegate {
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if tabManager.selectedTab?.webView !== webView {
return
}
// If we are going to navigate to a new page, hide the reader mode button. Unless we
// are going to a about:reader page. Then we keep it on screen: it will change status
// (orange color) as soon as the page has loaded.
if let url = webView.URL {
if !ReaderModeUtils.isReaderModeURL(url) {
urlBar.updateReaderModeState(ReaderModeState.Unavailable)
hideReaderModeBar(animated: false)
}
}
}
private func openExternal(url: NSURL, prompt: Bool = true) {
if prompt {
// Ask the user if it's okay to open the url with UIApplication.
let alert = UIAlertController(
title: String(format: NSLocalizedString("Opening %@", comment:"Opening an external URL"), url),
message: NSLocalizedString("This will open in another application", comment: "Opening an external app"),
preferredStyle: UIAlertControllerStyle.Alert
)
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: { (action: UIAlertAction) in
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"Alert OK Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in
UIApplication.sharedApplication().openURL(url)
}))
presentViewController(alert, animated: true, completion: nil)
} else {
UIApplication.sharedApplication().openURL(url)
}
}
private func callExternal(url: NSURL) {
if let phoneNumber = url.resourceSpecifier.stringByRemovingPercentEncoding {
let alert = UIAlertController(title: phoneNumber, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: NSLocalizedString("Call", comment:"Alert Call Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in
UIApplication.sharedApplication().openURL(url)
}))
presentViewController(alert, animated: true, completion: nil)
}
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.URL else {
decisionHandler(WKNavigationActionPolicy.Cancel)
return
}
switch url.scheme {
case "about", "http", "https":
if isWhitelistedUrl(url) {
// If the url is whitelisted, we open it without prompting…
// … unless the NavigationType is Other, which means it is JavaScript- or Redirect-initiated.
openExternal(url, prompt: navigationAction.navigationType == WKNavigationType.Other)
decisionHandler(WKNavigationActionPolicy.Cancel)
} else {
decisionHandler(WKNavigationActionPolicy.Allow)
}
case "tel":
callExternal(url)
decisionHandler(WKNavigationActionPolicy.Cancel)
default:
if UIApplication.sharedApplication().canOpenURL(url) {
openExternal(url)
}
decisionHandler(WKNavigationActionPolicy.Cancel)
}
}
func webView(webView: WKWebView,
didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest {
if let tab = tabManager[webView] {
let helper = tab.getHelper(name: LoginsHelper.name()) as! LoginsHelper
helper.handleAuthRequest(self, challenge: challenge).uponQueue(dispatch_get_main_queue()) { res in
if let credentials = res.successValue {
completionHandler(.UseCredential, credentials.credentials)
} else {
completionHandler(NSURLSessionAuthChallengeDisposition.RejectProtectionSpace, nil)
}
}
}
} else {
completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling, nil)
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
let tab: Browser! = tabManager[webView]
tabManager.expireSnackbars()
if let url = webView.URL where !ErrorPageHelper.isErrorPageURL(url) && !AboutUtils.isAboutHomeURL(url) {
tab.lastExecutedTime = NSDate.now()
if navigation == nil {
log.warning("Implicitly unwrapped optional navigation was nil.")
}
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("_firefox_ReaderMode.checkReadability()", completionHandler: nil)
}
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)
}
}
private func postLocationChangeNotificationForTab(tab: Browser, navigation: WKNavigation?) {
let notificationCenter = NSNotificationCenter.defaultCenter()
var info = [NSObject: AnyObject]()
info["url"] = tab.displayURL
info["title"] = tab.title
if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue {
info["visitType"] = visitType
}
info["isPrivate"] = tab.isPrivate
notificationCenter.postNotificationName(NotificationOnLocationChange, object: self, userInfo: info)
}
}
extension BrowserViewController: WKUIDelegate {
func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if let currentTab = tabManager.selectedTab {
currentTab.setScreenshot(screenshotHelper.takeScreenshot(currentTab, aspectRatio: 0, quality: 1))
}
// If the page uses window.open() or target="_blank", open the page in a new tab.
// TODO: This doesn't work for window.open() without user action (bug 1124942).
let tab = tabManager.addTab(navigationAction.request, configuration: configuration)
tabManager.selectTab(tab)
return tab.webView
}
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) {
tabManager.selectTab(tabManager[webView])
// Show JavaScript alerts.
let title = frame.request.URL!.host
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in
completionHandler()
}))
presentViewController(alertController, animated: true, completion: nil)
}
func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) {
tabManager.selectTab(tabManager[webView])
// Show JavaScript confirm dialogs.
let title = frame.request.URL!.host
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in
completionHandler(false)
}))
presentViewController(alertController, animated: true, completion: nil)
}
func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) {
tabManager.selectTab(tabManager[webView])
// Show JavaScript input dialogs.
let title = frame.request.URL!.host
let alertController = UIAlertController(title: title, message: prompt, preferredStyle: UIAlertControllerStyle.Alert)
var input: UITextField!
alertController.addTextFieldWithConfigurationHandler({ (textField: UITextField) in
textField.text = defaultText
input = textField
})
alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in
completionHandler(input.text)
}))
alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in
completionHandler(nil)
}))
presentViewController(alertController, animated: true, completion: nil)
}
/// Invoked when an error occurs during a committed main frame navigation.
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) {
return
}
// Ignore the "Plug-in handled load" error. Which is more like a notification than an error.
// Note that there are no constants in the SDK for the WebKit domain or error codes.
if error.domain == "WebKitErrorDomain" && error.code == 204 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error) {
return
}
if let url = error.userInfo["NSErrorFailingURLKey"] as? NSURL {
ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView)
}
}
/// Invoked when an error occurs while starting to load data for the main frame.
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
// 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.
if error.domain == "WebKitErrorDomain" && error.code == 102 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error) {
return
}
if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) {
if let browser = tabManager[webView] where browser === tabManager.selectedTab {
urlBar.currentURL = browser.displayURL
}
return
}
if let url = error.userInfo["NSErrorFailingURLKey"] as? NSURL {
ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView)
}
}
private func checkIfWebContentProcessHasCrashed(webView: WKWebView, error: NSError) -> Bool {
if error.code == WKErrorCode.WebContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" {
log.debug("WebContent process has crashed. Trying to reloadFromOrigin to restart it.")
webView.reloadFromOrigin()
return true
}
return false
}
func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) {
if navigationResponse.canShowMIMEType {
decisionHandler(WKNavigationResponsePolicy.Allow)
return
}
let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: "Downloads aren't supported in Firefox yet (but we're working on it)."])
ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.URL!, inWebView: webView)
decisionHandler(WKNavigationResponsePolicy.Allow)
}
}
extension BrowserViewController: ReaderModeDelegate, UIPopoverPresentationControllerDelegate {
func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser) {
// 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 === browser {
urlBar.updateReaderModeState(state)
}
}
func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser) {
self.showReaderModeBar(animated: true)
browser.showContent(true)
}
// 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 adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
}
extension BrowserViewController: ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) {
// Persist the new style to the profile
let encodedStyle: [String:AnyObject] = style.encode()
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.getHelper(name: "ReaderMode") as? ReaderMode {
if readerMode.state == ReaderModeState.Active {
readerMode.style = style
}
}
}
}
}
}
extension BrowserViewController {
func updateReaderModeBar() {
if let readerModeBar = readerModeBar {
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, 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 animated: Bool) {
if self.readerModeBar == nil {
let readerModeBar = ReaderModeBarView(frame: CGRectZero)
readerModeBar.delegate = self
view.insertSubview(readerModeBar, belowSubview: header)
self.readerModeBar = readerModeBar
}
updateReaderModeBar()
self.updateViewConstraints()
}
func hideReaderModeBar(animated 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, webView = tab.webView else { return }
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
guard let currentURL = webView.backForwardList.currentItem?.URL, let readerModeURL = ReaderModeUtils.encodeURL(currentURL) else { return }
if backList.count > 1 && backList.last?.URL == readerModeURL {
webView.goToBackForwardListItem(backList.last!)
} else if forwardList.count > 0 && forwardList.first?.URL == readerModeURL {
webView.goToBackForwardListItem(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) {
do {
try ReaderModeCache.sharedInstance.put(currentURL, readabilityResult)
} catch _ {
}
if let nav = webView.loadRequest(NSURLRequest(URL: readerModeURL)) {
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 = ReaderModeUtils.decodeURL(currentURL) {
if backList.count > 1 && backList.last?.URL == originalURL {
webView.goToBackForwardListItem(backList.last!)
} else if forwardList.count > 0 && forwardList.first?.URL == originalURL {
webView.goToBackForwardListItem(forwardList.first!)
} else {
if let nav = webView.loadRequest(NSURLRequest(URL: originalURL)) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
}
}
}
}
}
extension BrowserViewController: ReaderModeBarViewDelegate {
func readerModeBar(readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) {
switch buttonType {
case .Settings:
if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode where readerMode.state == ReaderModeState.Active {
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict) {
readerModeStyle = style
}
}
let readerModeStyleViewController = ReaderModeStyleViewController()
readerModeStyleViewController.delegate = self
readerModeStyleViewController.readerModeStyle = readerModeStyle
readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.Popover
let popoverPresentationController = readerModeStyleViewController.popoverPresentationController
popoverPresentationController?.backgroundColor = UIColor.whiteColor()
popoverPresentationController?.delegate = self
popoverPresentationController?.sourceView = readerModeBar
popoverPresentationController?.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1)
popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up
self.presentViewController(readerModeStyleViewController, animated: true, completion: nil)
}
case .MarkAsRead:
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, 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?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, 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 url = tab.url where ReaderModeUtils.isReaderModeURL(url) {
if let url = ReaderModeUtils.decodeURL(url) {
profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail?
readerModeBar.added = true
}
}
case .RemoveFromReadingList:
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, record = successValue {
profile.readingList?.deleteRecord(record) // TODO Check result, can this fail?
readerModeBar.added = false
}
}
}
}
}
private class BrowserScreenshotHelper: ScreenshotHelper {
private weak var controller: BrowserViewController?
init(controller: BrowserViewController) {
self.controller = controller
}
func takeScreenshot(tab: Browser, aspectRatio: CGFloat, quality: CGFloat) -> UIImage? {
if let url = tab.url {
if url == UIConstants.AboutHomeURL {
if let homePanel = controller?.homePanelController {
return homePanel.view.screenshot(aspectRatio, quality: quality)
}
} else {
let offset = CGPointMake(0, -(tab.webView?.scrollView.contentInset.top ?? 0))
return tab.webView?.screenshot(aspectRatio, offset: offset, quality: quality)
}
}
return nil
}
}
extension BrowserViewController: IntroViewControllerDelegate {
func presentIntroViewController(force: Bool = false) -> Bool{
if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil {
let introViewController = IntroViewController()
introViewController.delegate = self
// On iPad we present it modally in a controller
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height)
introViewController.modalPresentationStyle = UIModalPresentationStyle.FormSheet
}
presentViewController(introViewController, animated: true) {
self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey)
}
return true
}
return false
}
func introViewControllerDidFinish(introViewController: IntroViewController) {
introViewController.dismissViewControllerAnimated(true) { finished in
if self.navigationController?.viewControllers.count > 1 {
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
func presentSignInViewController() {
// 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 = SettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
vcToPresent = settingsTableViewController
} else {
let signInVC = FxAContentViewController()
signInVC.delegate = self
signInVC.url = profile.accountConfiguration.signInURL
signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "dismissSignInViewController")
vcToPresent = signInVC
}
let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent)
settingsNavigationController.modalPresentationStyle = .FormSheet
self.presentViewController(settingsNavigationController, animated: true, completion: nil)
}
func dismissSignInViewController() {
self.dismissViewControllerAnimated(true, completion: nil)
}
func introViewControllerDidRequestToLogin(introViewController: IntroViewController) {
introViewController.dismissViewControllerAnimated(true, completion: { () -> Void in
self.presentSignInViewController()
})
}
}
extension BrowserViewController: FxAContentViewControllerDelegate {
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
log.debug("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
profile.setAccount(account)
if let account = self.profile.getAccount() {
account.advance()
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
log.info("Did cancel out of FxA signin")
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension BrowserViewController: ContextMenuHelperDelegate {
func contextMenuHelper(contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) {
let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
var dialogTitle: String?
if let url = elements.link {
dialogTitle = url.absoluteString
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: UIAlertActionStyle.Default) { (action: UIAlertAction) in
self.scrollController.showToolbars(animated: !self.scrollController.toolbarsShowing, completion: { _ in
self.tabManager.addTab(NSURLRequest(URL: url))
})
}
actionSheetController.addAction(openNewTabAction)
let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard")
let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
let pasteBoard = UIPasteboard.generalPasteboard()
pasteBoard.string = url.absoluteString
}
actionSheetController.addAction(copyAction)
}
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: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
if photoAuthorizeStatus == PHAuthorizationStatus.Authorized || photoAuthorizeStatus == PHAuthorizationStatus.NotDetermined {
self.getImage(url) { UIImageWriteToSavedPhotosAlbum($0, nil, nil, 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: UIAlertControllerStyle.Alert)
let dismissAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Default, handler: nil)
accessDenied.addAction(dismissAction)
let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.Default ) { (action: UIAlertAction!) -> Void in
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
accessDenied.addAction(settingsAction)
self.presentViewController(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: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
let pasteBoard = UIPasteboard.generalPasteboard()
pasteBoard.string = url.absoluteString
// TODO: put the actual image on the clipboard
}
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: gestureRecognizer.locationInView(view), size: CGSizeMake(0, 16))
popoverPresentationController.permittedArrowDirections = .Any
}
actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength)
let cancelAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: nil)
actionSheetController.addAction(cancelAction)
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
private func getImage(url: NSURL, success: UIImage -> ()) {
Alamofire.request(.GET, url)
.validate(statusCode: 200..<300)
.response { _, _, data, _ in
if let data = data,
let image = UIImage(data: data) {
success(image)
}
}
}
}
extension BrowserViewController: KeyboardHelperDelegate {
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
keyboardState = state
// if we are already showing snack bars, adjust them so they sit above the keyboard
if snackBars.subviews.count > 0 {
adjustFooterSize(nil)
}
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
keyboardState = nil
// if we are showing snack bars, adjust them so they are no longer sitting above the keyboard
if snackBars.subviews.count > 0 {
adjustFooterSize(nil)
}
}
}
extension BrowserViewController: SessionRestoreHelperDelegate {
func sessionRestoreHelper(helper: SessionRestoreHelper, didRestoreSessionForBrowser browser: Browser) {
browser.restoring = false
if let tab = tabManager.selectedTab where tab.webView === browser.webView {
updateUIForReaderHomeStateForTab(tab)
}
}
}
private struct CrashPromptMessaging {
static let Title = NSLocalizedString("Well, this is embarrassing.", comment: "Restore Tabs Prompt Title")
static let Description = NSLocalizedString("Looks like Firefox crashed previously. Would you like to restore your tabs?", comment: "Restore Tabs Prompt Description")
static let Affirmative = NSLocalizedString("Okay", comment: "Restore Tabs Affirmative Action")
static let Negative = NSLocalizedString("No", comment: "Restore Tabs Negative Action")
}
extension BrowserViewController: UIAlertViewDelegate {
private enum CrashPromptIndex: Int {
case Cancel = 0
case Restore = 1
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
func addAndSelect() {
let tab = tabManager.addTab()
tabManager.selectTab(tab)
}
if buttonIndex == CrashPromptIndex.Restore.rawValue {
self.restoreTabs()
if tabManager.count == 0 {
addAndSelect()
}
} else {
addAndSelect()
}
}
}
| mpl-2.0 | f96cd252cf0bc3fbe4df5888c4cf8dc9 | 43.272556 | 406 | 0.655723 | 5.902268 | false | false | false | false |
tlax/looper | looper/View/Camera/Scale/VCameraScale.swift | 1 | 7223 | import UIKit
class VCameraScale:VView
{
private weak var controller:CCameraScale!
private weak var viewSlider:VCameraScaleSlider!
private weak var spinner:VSpinner!
private weak var buttonDone:UIButton!
private weak var buttonReset:UIButton!
private weak var layoutDoneLeft:NSLayoutConstraint!
private var totalHeight:CGFloat
private var minPercent:CGFloat
private let kButtonDoneHeight:CGFloat = 35
private let kButtonResetHeight:CGFloat = 50
private let kButtonWidth:CGFloat = 120
private let kSliderTop:CGFloat = 90
private let kSliderBottom:CGFloat = -40
private let kAlphaLoading:CGFloat = 0.3
override init(controller:CController)
{
totalHeight = 0
minPercent = 0
super.init(controller:controller)
backgroundColor = UIColor.clear
self.controller = controller as? CCameraScale
if let imageSize:CGFloat = self.controller.record.items.first?.image.size.width
{
minPercent = MCamera.kImageMinSize / imageSize
}
let blur:VBlur = VBlur.extraLight()
let buttonDone:UIButton = UIButton()
buttonDone.translatesAutoresizingMaskIntoConstraints = false
buttonDone.clipsToBounds = true
buttonDone.backgroundColor = UIColor.genericLight
buttonDone.layer.cornerRadius = kButtonDoneHeight / 2.0
buttonDone.setTitleColor(
UIColor.white,
for:UIControlState.normal)
buttonDone.setTitleColor(
UIColor(white:1, alpha:0.1),
for:UIControlState.highlighted)
buttonDone.setTitle(
NSLocalizedString("VCameraScale_done", comment:""),
for:UIControlState.normal)
buttonDone.titleLabel!.font = UIFont.bold(size:17)
buttonDone.addTarget(
self,
action:#selector(actionDone(sender:)),
for:UIControlEvents.touchUpInside)
self.buttonDone = buttonDone
let buttonReset:UIButton = UIButton()
buttonReset.translatesAutoresizingMaskIntoConstraints = false
buttonReset.clipsToBounds = true
buttonReset.backgroundColor = UIColor.clear
buttonReset.setTitleColor(
UIColor.black,
for:UIControlState.normal)
buttonReset.setTitleColor(
UIColor(white:0, alpha:0.2),
for:UIControlState.highlighted)
buttonReset.setTitle(
NSLocalizedString("VCameraScale_reset", comment:""),
for:UIControlState.normal)
buttonReset.titleLabel!.font = UIFont.medium(size:14)
buttonReset.addTarget(
self,
action:#selector(actionReset(sender:)),
for:UIControlEvents.touchUpInside)
self.buttonReset = buttonReset
let viewSlider:VCameraScaleSlider = VCameraScaleSlider(controller:self.controller)
self.viewSlider = viewSlider
let spinner:VSpinner = VSpinner()
spinner.stopAnimating()
self.spinner = spinner
addSubview(blur)
addSubview(viewSlider)
addSubview(buttonDone)
addSubview(buttonReset)
addSubview(spinner)
NSLayoutConstraint.equals(
view:blur,
toView:self)
NSLayoutConstraint.equals(
view:spinner,
toView:viewSlider)
NSLayoutConstraint.bottomToTop(
view:buttonDone,
toView:buttonReset)
NSLayoutConstraint.height(
view:buttonDone,
constant:kButtonDoneHeight)
NSLayoutConstraint.width(
view:buttonDone,
constant:kButtonWidth)
layoutDoneLeft = NSLayoutConstraint.leftToLeft(
view:buttonDone,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:buttonReset,
toView:self)
NSLayoutConstraint.height(
view:buttonReset,
constant:kButtonResetHeight)
NSLayoutConstraint.equalsHorizontal(
view:buttonReset,
toView:buttonDone)
NSLayoutConstraint.topToTop(
view:viewSlider,
toView:self,
constant:kSliderTop)
NSLayoutConstraint.leftToLeft(
view:viewSlider,
toView:self)
NSLayoutConstraint.rightToRight(
view:viewSlider,
toView:self)
NSLayoutConstraint.bottomToTop(
view:viewSlider,
toView:buttonDone,
constant:kSliderBottom)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
totalHeight = bounds.maxY - (kSliderTop - kSliderBottom + kButtonDoneHeight + kButtonResetHeight)
let width:CGFloat = bounds.maxX
let remain:CGFloat = width - kButtonWidth
let margin:CGFloat = remain / 2.0
layoutDoneLeft.constant = margin
super.layoutSubviews()
}
override func touchesBegan(_ touches:Set<UITouch>, with event:UIEvent?)
{
guard
let touch:UITouch = touches.first,
let view:VCameraScaleSlider = touch.view as? VCameraScaleSlider
else
{
return
}
let point:CGPoint = touch.location(in:view)
touchAtPoint(point:point)
}
override func touchesMoved(_ touches:Set<UITouch>, with event:UIEvent?)
{
guard
let touch:UITouch = touches.first,
let view:VCameraScaleSlider = touch.view as? VCameraScaleSlider
else
{
return
}
let point:CGPoint = touch.location(in:view)
touchAtPoint(point:point)
}
override func touchesCancelled(_ touches:Set<UITouch>, with event:UIEvent?)
{
}
override func touchesEnded(_ touches:Set<UITouch>, with event:UIEvent?)
{
}
//MARK: actions
func actionDone(sender button:UIButton)
{
button.isUserInteractionEnabled = false
controller.save()
}
func actionReset(sender button:UIButton)
{
controller.reset()
}
//MARK: private
private func touchAtPoint(point:CGPoint)
{
let pointY:CGFloat = point.y
let normalY:CGFloat = totalHeight - pointY
var percent:CGFloat = normalY / totalHeight
if percent > 1
{
percent = 1
}
else if percent < minPercent
{
percent = minPercent
}
controller.currentPercent = percent
updateSlider()
}
//MARK: public
func updateSlider()
{
viewSlider.sliderSelected(percent:controller.currentPercent)
}
func startLoading()
{
spinner.startAnimating()
viewSlider.isHidden = true
buttonDone.isUserInteractionEnabled = false
buttonReset.isUserInteractionEnabled = false
buttonDone.alpha = kAlphaLoading
buttonReset.alpha = kAlphaLoading
}
}
| mit | 9e5887c121c22045fdaa92d94cabd2db | 28.602459 | 105 | 0.603766 | 5.249273 | false | false | false | false |
tlax/looper | looper/Controller/Camera/CCameraMore.swift | 1 | 887 | import UIKit
class CCameraMore:CController
{
let model:MCameraMore
weak var controller:CCamera!
weak var viewMore:VCameraMore!
weak var record:MCameraRecord?
init(controller:CCamera, record:MCameraRecord)
{
model = MCameraMore(record:record)
self.controller = controller
self.record = record
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
viewMore.open()
}
override func loadView()
{
let viewMore:VCameraMore = VCameraMore(controller:self)
self.viewMore = viewMore
view = viewMore
}
//MARK: public
func close(completion:(() -> ())?)
{
parentController.dismissAnimateOver(completion:completion)
}
}
| mit | a421ac2e4eeb7cc9035d660f2ee140b9 | 20.119048 | 66 | 0.608794 | 4.457286 | false | false | false | false |
DavidSkrundz/Hash | Sources/Hash/SHA/sha512.swift | 1 | 925 | //
// sha512.swift
// Hash
//
// Reference: https://tools.ietf.org/html/rfc6234
public struct sha512 {
private init() {}
}
extension sha512: SHA2Type, SHA512Type {
public typealias Data = UInt64
public static let sha2_lengthBytesPrefix = sha384.sha2_lengthBytesPrefix
public static let sha2_hashByteCount = 512 / 8
public static let sha2_blockSize = sha384.sha2_blockSize
public static let sha2_blockBufferSize = sha384.sha2_blockBufferSize
public static let sha2_constant = sha384.sha2_constant
public static var sha2_initialDigest: [Data] = [
0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b, 0x5be0cd19137e2179
]
}
extension sha512: SHA3Type {
public static let sha3_blockSize = 72
public static let sha3_hashByteCount = 512 / 8
public static var sha3_initialDigest = [UInt64](repeating: 0, count: 25)
}
| lgpl-3.0 | a76714d9eac0b563bae478683c099364 | 27.90625 | 73 | 0.770811 | 2.704678 | false | false | false | false |
lukesutton/uut | Sources/PropertyValues-Box.swift | 1 | 3183 | extension PropertyValues {
public enum BoxSizing: String, PropertyValue {
case BorderBox = "border-box"
case ContentBox = "content-box"
case Initial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum Position: String, PropertyValue {
case Static = "static"
case Absolute = "absolute"
case Fixed = "fixed"
case Relative = "relative"
case Initial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum Clear: String, PropertyValue {
case None = "none"
case Left = "left"
case Right = "right"
case Both = "both"
case Initial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum Clip: String, PropertyValue {
case None = "none"
case Left = "left"
case Right = "right"
case Both = "both"
case Initial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum Display: String, PropertyValue {
case Inline = "inline"
case Block = "block"
case Flex = "flex"
case InlineBlock = "inline-block"
case InlineFlex = "inline-flex"
case ListItem = "list-item"
case RunIn = "run-in"
case Table = "table"
case TableCaption = "table-caption"
case TableColumnGroup = "table-column-group"
case TableHeaderGroup = "table-header-group"
case TableFooterGroup = "table-footer-group"
case TableRowGroup = "table-row-group"
case TableCell = "table-cell"
case TableColumn = "table-column"
case TableRow = "table-row"
case None = "none"
case Initial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum Float: String, PropertyValue {
case None = "none"
case Left = "left"
case Right = "right"
case Initial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum Overflow: String, PropertyValue {
case Visible = "visible"
case Hidden = "hidden"
case Scroll = "scroll"
case Auto = "auto"
case Initial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum Visibility: String, PropertyValue {
case Visible = "visible"
case Hidden = "hidden"
case Collapse = "collapse"
case Auto = "auto"
case Initial = "initial"
case Inherit = "inherit"
public var stringValue: String {
return rawValue
}
}
public enum VerticalAlign: PropertyValue {
case Baseline
case Value(Measurement)
case Sub
case Super
case Top
case TextTop
case Middle
case Bottom
case TextBottom
case Initial
case Inherit
public var stringValue: String {
switch self {
case let Value(n): return n.stringValue
case TextTop: return "text-top"
case TextBottom: return "text-bottom"
default: return String(self).lowercaseString
}
}
}
}
| mit | 516c8e637057686887ca8a2641068c4b | 22.065217 | 52 | 0.629595 | 4.177165 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/Setting/YellowPage/YellowPageCell.swift | 1 | 8935 | //
// YellowPageCell.swift
// YellowPage
//
// Created by Halcao on 2017/2/22.
// Copyright © 2017年 Halcao. All rights reserved.
//
import UIKit
import SnapKit
protocol YellowPageCellDelegate: NSObjectProtocol {
func showViewController(vc: UIViewController, sender: AnyObject?)
}
// haeder: the view on top
// section: which can be fold and unfold
// item: for each item in section
// detailed: detailed info
enum YellowPageCellStyle: String {
case header = "headerCell"
case section = "sectionCell"
case item = "itemCell"
case detailed = "detailedCell"
}
class YellowPageCell: UITableViewCell {
weak var delegate: YellowPageCellDelegate?
var canUnfold = true {
didSet {
if self.canUnfold && style == .section {
arrowView.image = UIImage(named: "ic_arrow_right")
} else {
arrowView.image = UIImage(named: "ic_arrow_down")
}
}
}
var name = ""
let arrowView = UIImageView()
var countLabel: UILabel! = nil
var style: YellowPageCellStyle = .header
var detailedModel: ClientItem! = nil
var commonView: CommonView! = nil
var likeView: TappableImageView! = nil
convenience init(with style: YellowPageCellStyle, name: String) {
self.init(style: .Default, reuseIdentifier: style.rawValue)
self.style = style
switch style {
case .header:
commonView = CommonView(with: [])
commonView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
self.contentView.addSubview(commonView)
commonView.snp_makeConstraints { make in
make.width.equalTo(UIScreen.mainScreen().bounds.size.width)
make.height.equalTo(200)
make.top.equalTo(contentView)
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.bottom.equalTo(contentView)
}
case .section:
arrowView.image = UIImage(named: self.canUnfold ? "ic_arrow_right" : "ic_arrow_down")
arrowView.sizeToFit()
self.contentView.addSubview(arrowView)
arrowView.snp_makeConstraints { make in
make.width.equalTo(15)
make.height.equalTo(15)
make.left.equalTo(contentView).offset(10)
make.centerY.equalTo(contentView)
}
let label = UILabel()
self.contentView.addSubview(label)
// TODO: adjust font size
label.text = name
label.font = UIFont.flexibleFont(with: 15)
label.sizeToFit()
label.snp_makeConstraints { make in
make.top.equalTo(contentView).offset(20)
make.left.equalTo(arrowView.snp_right).offset(10)
make.centerY.equalTo(contentView)
make.bottom.equalTo(contentView).offset(-20)
}
countLabel = UILabel()
self.contentView.addSubview(countLabel)
countLabel.textColor = UIColor.lightGrayColor()
countLabel.font = UIFont.systemFontOfSize(14)
countLabel.snp_makeConstraints { make in
make.left.equalTo(contentView.snp_right).offset(-30)
make.centerY.equalTo(contentView)
}
case .item:
self.textLabel?.text = name
textLabel?.font = UIFont.flexibleFont(with: 14)
textLabel?.sizeToFit()
textLabel?.snp_makeConstraints { make in
make.top.equalTo(contentView).offset(12)
make.centerY.equalTo(contentView)
make.left.equalTo(contentView).offset(15)
make.bottom.equalTo(contentView).offset(-12)
}
case .detailed:
fatalError("这个方法请调用func init(with style: YellowPageCellStyle, model: ClientItem)")
}
}
convenience init(with style: YellowPageCellStyle, model: ClientItem) {
self.init(style: .Default, reuseIdentifier: style.rawValue)
guard style == .detailed else {
return
}
self.detailedModel = model
let nameLabel = UILabel()
nameLabel.text = model.name
nameLabel.font = UIFont.flexibleFont(with: 14)
nameLabel.sizeToFit()
// paste
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(YellowPageCell.longPressed))
self.addGestureRecognizer(longPress)
self.contentView.addSubview(nameLabel)
nameLabel.snp_makeConstraints { make in
make.top.equalTo(contentView).offset(10)
make.left.equalTo(contentView).offset(15)
//make.bottom.equalTo(nameLabel).offset(-12)
}
let phoneLabel = UILabel()
let str = NSMutableAttributedString(string: model.phone, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue, NSForegroundColorAttributeName: UIColor.flatBlueColor()])
phoneLabel.attributedText = str
phoneLabel.font = UIFont.flexibleFont(with: 14)
phoneLabel.sizeToFit()
self.contentView.addSubview(phoneLabel)
phoneLabel.snp_makeConstraints { make in
make.top.equalTo(nameLabel.snp_bottom).offset(13)
make.left.equalTo(contentView).offset(15)
make.bottom.equalTo(contentView).offset(-6)
}
phoneLabel.userInteractionEnabled = true
let labelTapGesture = UITapGestureRecognizer(target: self, action: #selector(YellowPageCell.labelTapped(_:)))
phoneLabel.addGestureRecognizer(labelTapGesture)
likeView = TappableImageView(with: CGRect.zero, imageSize: CGSize(width: 18, height: 18), image: UIImage(named: model.isFavorite ? "like" : "dislike"))
self.contentView.addSubview(likeView)
likeView.snp_makeConstraints { make in
make.width.equalTo(24)
make.height.equalTo(24)
make.right.equalTo(contentView).offset(-14)
make.centerY.equalTo(phoneLabel.snp_centerY)
}
likeView.userInteractionEnabled = true
let likeTapGesture = UITapGestureRecognizer(target: self, action: #selector(YellowPageCell.likeTapped))
likeView.addGestureRecognizer(likeTapGesture)
let phoneView = TappableImageView(with: CGRect.zero, imageSize: CGSize(width: 18, height: 18), image: UIImage(named: "phone"))
let phoneTapGesture = UITapGestureRecognizer(target: self, action: #selector(YellowPageCell.phoneTapped))
phoneView.addGestureRecognizer(phoneTapGesture)
self.contentView.addSubview(phoneView)
phoneView.snp_makeConstraints { make in
make.width.equalTo(24)
make.height.equalTo(24)
make.right.equalTo(likeView.snp_left).offset(-24)
make.centerY.equalTo(phoneLabel.snp_centerY)
}
}
func likeTapped() {
if detailedModel.isFavorite {
PhoneBook.shared.removeFromFavorite(with: self.detailedModel.name) {
self.likeView.imgView.image = UIImage(named: "dislike")
}
detailedModel.isFavorite = false
// TODO: animation
} else {
PhoneBook.shared.addToFavorite(with: self.detailedModel.name) {
self.likeView.imgView.image = UIImage(named: "like")
}
detailedModel.isFavorite = true
// TODO: animation
// refresh data
}
}
func labelTapped(model: ClientItem) {
// delegate?.cellDetailTapped(model)
let alertVC = UIAlertController(title: "详情", message: "您想要做什么?", preferredStyle: .ActionSheet)
let copyAction = UIAlertAction(title: "复制到剪切板", style: .Default) { action in
self.longPressed()
}
// let savePhoneBook
let cancelAction = UIAlertAction(title: "取消", style: .Cancel) { action in
}
alertVC.addAction(copyAction)
alertVC.addAction(cancelAction)
if let vc = delegate as? UIViewController {
vc.presentViewController(alertVC, animated: true, completion: nil)
}
}
func phoneTapped() {
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://\(self.detailedModel.phone)")!)
}
func longPressed() {
if let text = UIPasteboard.generalPasteboard().string {
if text == self.detailedModel.phone {
MsgDisplay.showSuccessMsg("已经复制到剪切板")
return
}
}
UIPasteboard.generalPasteboard().string = self.detailedModel.phone
MsgDisplay.showSuccessMsg("已经复制到剪切板")
}
}
| mit | c38b3f2fc83a56a66a193b9c71fe3750 | 38.168142 | 205 | 0.612743 | 4.764263 | false | false | false | false |
kaideyi/KDYSample | KYChat/KYChat/BizsClass/Base/KYTabBarController.swift | 1 | 7419 | //
// KYTabBarController.swift
// KYChat
//
// Created by KYCoder on 2017/8/30.
// Copyright © 2017年 mac. All rights reserved.
//
import UIKit
import UserNotifications
class KYTabBarController: UITabBarController {
// MARK:
// 默认播放声音的间隔
let kDefaultPlaySoundInterval = 3.0
let kMessageType = "MessageType"
let kConversationChatter = "ConversationChatter"
var lastPlaySoundDate: Date = Date()
let conversationVC = KYConversationController()
let contactVC = KYContactsController()
let meVC = KYMeViewController()
var connectionState: EMConnectionState = EMConnectionConnected
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupViewControllers()
setupUnReadMessages()
setupUntreatedApplys()
setupNotifications()
KYChatHelper.share.contactVC = contactVC
KYChatHelper.share.conversationVC = conversationVC
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(kUnReadMessagesNoti), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(kUTreatApplysNoti), object: nil)
}
func setupViewControllers() {
let titleArray = ["Chats", "通讯录", "我"]
let imagesNormal = [
KYAsset.TabChatNormal.image,
KYAsset.TabContactsNormal.image,
KYAsset.TabMeNormal.image
]
let imagesSelect = [
KYAsset.TabChatSelect.image,
KYAsset.TabContactsSelect.image,
KYAsset.TabMeSelect.image
]
let controllers = [conversationVC, contactVC, meVC]
var navigationControllers: [KYNavigationController] = []
for (index, controller) in controllers.enumerated() {
controller.title = titleArray[index]
controller.tabBarItem.title = titleArray[index]
if let imageNormal = imagesNormal[index],
let imageSelect = imagesSelect[index] {
controller.tabBarItem.image = imageNormal.withRenderingMode(.alwaysOriginal)
controller.tabBarItem.selectedImage = imageSelect.withRenderingMode(.alwaysOriginal)
}
controller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.lightGray], for: .normal)
controller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: KYColor.TabbarSelectedText.color], for: .selected)
let navigation = KYNavigationController(rootViewController: controller)
navigationControllers.append(navigation)
}
self.viewControllers = navigationControllers as [KYNavigationController]
}
func setupNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(setupUnReadMessages), name: NSNotification.Name(kUnReadMessagesNoti), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(setupUnReadMessages), name: NSNotification.Name(kUTreatApplysNoti), object: nil)
}
// MARK: - Public Methods
func setupUnReadMessages() {
if let conversations = EMClient.shared().chatManager.getAllConversations() as? [EMConversation] {
if conversations.count == 0 { return }
var unReadCounts: Int32 = 0
for conversation in conversations {
unReadCounts += conversation.unreadMessagesCount
}
if unReadCounts > 0 {
conversationVC.tabBarItem.badgeValue = String("\(unReadCounts)")
} else {
conversationVC.tabBarItem.badgeValue = nil
}
UIApplication.shared.applicationIconBadgeNumber = Int(unReadCounts)
}
}
func setupUntreatedApplys() {
}
func setupNetworkState(_ state: EMConnectionState) {
connectionState = state
conversationVC.networkIsConnected()
}
// 播放声音或振动(有新消息时)
func playSoundAndVibration() {
let timeInterval: TimeInterval = Date().timeIntervalSince(lastPlaySoundDate)
if timeInterval < kDefaultPlaySoundInterval {
// 如果距离上次响铃和震动时间太短, 则跳过响铃
print("skip ringing & vibration \(Date()), \(lastPlaySoundDate)")
return;
}
self.lastPlaySoundDate = Date()
EMCDDeviceManager.sharedInstance().playVibration()
EMCDDeviceManager.sharedInstance().playNewMessageSound()
}
// 显示推送消息
func showPushNotification(withMessage message: EMMessage) {
let pushOptions: EMPushOptions = EMClient.shared().pushOptions
var alertBody: String = ""
let title = message.from
if pushOptions.displayStyle == EMPushDisplayStyleMessageSummary { // 显示具体内容
guard let messageBody = message.body else { return }
var pushMessageStr: String = ""
switch messageBody.type {
case EMMessageBodyTypeText: pushMessageStr = (messageBody as! EMTextMessageBody).text
case EMMessageBodyTypeImage: pushMessageStr = "[图片]"
case EMMessageBodyTypeVideo: pushMessageStr = "[视频]"
case EMMessageBodyTypeLocation: pushMessageStr = "[位置]"
case EMMessageBodyTypeVoice: pushMessageStr = "[语音]"
default: pushMessageStr = ""
}
alertBody = String(format: "%@: %@", title!, pushMessageStr)
} else {
alertBody = "您有一条新消息"
}
var isPlaySound = false
let timeInterval: TimeInterval = Date().timeIntervalSince(lastPlaySoundDate)
if timeInterval > kDefaultPlaySoundInterval {
isPlaySound = true
}
var userInfo = [String: AnyObject]()
userInfo[kMessageType] = NSNumber(value: message.chatType.rawValue)
userInfo[kConversationChatter] = message.conversationId as AnyObject
// 发送本地通知
if #available(iOS 10, *) {
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
let content = UNMutableNotificationContent()
content.body = alertBody
content.userInfo = userInfo
if isPlaySound {
content.sound = UNNotificationSound.default()
}
let request = UNNotificationRequest(identifier: message.messageId, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
} else {
let notification = UILocalNotification()
notification.fireDate = Date()
notification.alertBody = alertBody
notification.userInfo = userInfo
if isPlaySound {
notification.soundName = UILocalNotificationDefaultSoundName
}
UIApplication.shared.scheduleLocalNotification(notification)
}
}
}
| mit | ab056db308f554cf54eaf74015d4f310 | 35.119403 | 155 | 0.620937 | 5.401786 | false | false | false | false |
niunaruto/DeDaoAppSwift | DeDaoSwift/Pods/ReactiveSwift/Sources/Property.swift | 1 | 27276 | import Foundation
import enum Result.NoError
/// Represents a property that allows observation of its changes.
///
/// Only classes can conform to this protocol, because having a signal
/// for changes over time implies the origin must have a unique identity.
public protocol PropertyProtocol: class, BindingSourceProtocol {
associatedtype Value
/// The current value of the property.
var value: Value { get }
/// The values producer of the property.
///
/// It produces a signal that sends the property's current value,
/// followed by all changes over time. It completes when the property
/// has deinitialized, or has no further change.
///
/// - note: If `self` is a composed property, the producer would be
/// bound to the lifetime of its sources.
var producer: SignalProducer<Value, NoError> { get }
/// A signal that will send the property's changes over time. It
/// completes when the property has deinitialized, or has no further
/// change.
///
/// - note: If `self` is a composed property, the signal would be
/// bound to the lifetime of its sources.
var signal: Signal<Value, NoError> { get }
}
extension PropertyProtocol {
@discardableResult
public func observe(_ observer: Observer<Value, NoError>, during lifetime: Lifetime) -> Disposable? {
return producer.observe(observer, during: lifetime)
}
}
/// Represents an observable property that can be mutated directly.
public protocol MutablePropertyProtocol: PropertyProtocol, BindingTargetProtocol {
/// The current value of the property.
var value: Value { get set }
}
/// Default implementation of `MutablePropertyProtocol` for `BindingTarget`.
extension MutablePropertyProtocol {
public func consume(_ value: Value) {
self.value = value
}
}
// Property operators.
//
// A composed property is a transformed view of its sources, and does not
// own its lifetime. Its producer and signal are bound to the lifetime of
// its sources.
extension PropertyProtocol {
/// Lifts a unary SignalProducer operator to operate upon PropertyProtocol instead.
fileprivate func lift<U>(_ transform: @escaping (SignalProducer<Value, NoError>) -> SignalProducer<U, NoError>) -> Property<U> {
return Property(self, transform: transform)
}
/// Lifts a binary SignalProducer operator to operate upon PropertyProtocol instead.
fileprivate func lift<P: PropertyProtocol, U>(_ transform: @escaping (SignalProducer<Value, NoError>) -> (SignalProducer<P.Value, NoError>) -> SignalProducer<U, NoError>) -> (P) -> Property<U> {
return { otherProperty in
return Property(self, otherProperty, transform: transform)
}
}
/// Maps the current value and all subsequent values to a new property.
///
/// - parameters:
/// - transform: A closure that will map the current `value` of this
/// `Property` to a new value.
///
/// - returns: A new instance of `AnyProperty` who's holds a mapped value
/// from `self`.
public func map<U>(_ transform: @escaping (Value) -> U) -> Property<U> {
return lift { $0.map(transform) }
}
/// Combines the current value and the subsequent values of two `Property`s in
/// the manner described by `Signal.combineLatestWith:`.
///
/// - parameters:
/// - other: A property to combine `self`'s value with.
///
/// - returns: A property that holds a tuple containing values of `self` and
/// the given property.
public func combineLatest<P: PropertyProtocol>(with other: P) -> Property<(Value, P.Value)> {
return lift(SignalProducer.combineLatest(with:))(other)
}
/// Zips the current value and the subsequent values of two `Property`s in
/// the manner described by `Signal.zipWith`.
///
/// - parameters:
/// - other: A property to zip `self`'s value with.
///
/// - returns: A property that holds a tuple containing values of `self` and
/// the given property.
public func zip<P: PropertyProtocol>(with other: P) -> Property<(Value, P.Value)> {
return lift(SignalProducer.zip(with:))(other)
}
/// Forward events from `self` with history: values of the returned property
/// 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.
///
/// - parameters:
/// - initial: A value that will be combined with the first value sent by
/// `self`.
///
/// - returns: A property that holds tuples that contain previous and
/// current values of `self`.
public func combinePrevious(_ initial: Value) -> Property<(Value, Value)> {
return lift { $0.combinePrevious(initial) }
}
/// Forward only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value.
///
/// - parameters:
/// - isRepeat: A predicate to determine if the two given values are equal.
///
/// - returns: A property that does not emit events for two equal values
/// sequentially.
public func skipRepeats(_ isRepeat: @escaping (Value, Value) -> Bool) -> Property<Value> {
return lift { $0.skipRepeats(isRepeat) }
}
}
extension PropertyProtocol where Value: Equatable {
/// Forward only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value.
///
/// - returns: A property that does not emit events for two equal values
/// sequentially.
public func skipRepeats() -> Property<Value> {
return lift { $0.skipRepeats() }
}
}
extension PropertyProtocol where Value: PropertyProtocol {
/// Flattens the inner property held by `self` (into a single property of
/// values), according to the semantics of the given strategy.
///
/// - parameters:
/// - strategy: The preferred flatten strategy.
///
/// - returns: A property that sends the values of its inner properties.
public func flatten(_ strategy: FlattenStrategy) -> Property<Value.Value> {
return lift { $0.flatMap(strategy) { $0.producer } }
}
}
extension PropertyProtocol {
/// Maps each property from `self` to a new property, then flattens the
/// resulting properties (into a single property), according to the
/// semantics of the given strategy.
///
/// - parameters:
/// - strategy: The preferred flatten strategy.
/// - transform: The transform to be applied on `self` before flattening.
///
/// - returns: A property that sends the values of its inner properties.
public func flatMap<P: PropertyProtocol>(_ strategy: FlattenStrategy, transform: @escaping (Value) -> P) -> Property<P.Value> {
return lift { $0.flatMap(strategy) { transform($0).producer } }
}
/// Forward only those values from `self` that have unique identities across
/// the set of all values that have been held.
///
/// - note: This causes the identities to be retained to check for
/// uniqueness.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns identity
/// value.
///
/// - returns: A property that sends unique values during its lifetime.
public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> Property<Value> {
return lift { $0.uniqueValues(transform) }
}
}
extension PropertyProtocol 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 identities 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.
///
/// - returns: A property that sends unique values during its lifetime.
public func uniqueValues() -> Property<Value> {
return lift { $0.uniqueValues() }
}
}
extension PropertyProtocol {
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol>(_ a: A, _ b: B) -> Property<(A.Value, B.Value)> where Value == A.Value {
return a.combineLatest(with: b)
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol>(_ a: A, _ b: B, _ c: C) -> Property<(A.Value, B.Value, C.Value)> where Value == A.Value {
return combineLatest(a, b)
.combineLatest(with: c)
.map(repack)
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D) -> Property<(A.Value, B.Value, C.Value, D.Value)> where Value == A.Value {
return combineLatest(a, b, c)
.combineLatest(with: d)
.map(repack)
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value)> where Value == A.Value {
return combineLatest(a, b, c, d)
.combineLatest(with: e)
.map(repack)
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value)> where Value == A.Value {
return combineLatest(a, b, c, d, e)
.combineLatest(with: f)
.map(repack)
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value)> where Value == A.Value {
return combineLatest(a, b, c, d, e, f)
.combineLatest(with: g)
.map(repack)
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value)> where Value == A.Value {
return combineLatest(a, b, c, d, e, f, g)
.combineLatest(with: h)
.map(repack)
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol, I: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value)> where Value == A.Value {
return combineLatest(a, b, c, d, e, f, g, h)
.combineLatest(with: i)
.map(repack)
}
/// Combines the values of all the given properties, in the manner described
/// by `combineLatest(with:)`.
public static func combineLatest<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol, I: PropertyProtocol, J: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value)> where Value == A.Value {
return combineLatest(a, b, c, d, e, f, g, h, i)
.combineLatest(with: j)
.map(repack)
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`. Returns nil if the sequence is empty.
public static func combineLatest<S: Sequence>(_ properties: S) -> Property<[S.Iterator.Element.Value]>? where S.Iterator.Element: PropertyProtocol {
var generator = properties.makeIterator()
if let first = generator.next() {
let initial = first.map { [$0] }
return IteratorSequence(generator).reduce(initial) { property, next in
property.combineLatest(with: next).map { $0.0 + [$0.1] }
}
}
return nil
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol>(_ a: A, _ b: B) -> Property<(A.Value, B.Value)> where Value == A.Value {
return a.zip(with: b)
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol>(_ a: A, _ b: B, _ c: C) -> Property<(A.Value, B.Value, C.Value)> where Value == A.Value {
return zip(a, b)
.zip(with: c)
.map(repack)
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D) -> Property<(A.Value, B.Value, C.Value, D.Value)> where Value == A.Value {
return zip(a, b, c)
.zip(with: d)
.map(repack)
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value)> where Value == A.Value {
return zip(a, b, c, d)
.zip(with: e)
.map(repack)
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value)> where Value == A.Value {
return zip(a, b, c, d, e)
.zip(with: f)
.map(repack)
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value)> where Value == A.Value {
return zip(a, b, c, d, e, f)
.zip(with: g)
.map(repack)
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value)> where Value == A.Value {
return zip(a, b, c, d, e, f, g)
.zip(with: h)
.map(repack)
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol, I: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value)> where Value == A.Value {
return zip(a, b, c, d, e, f, g, h)
.zip(with: i)
.map(repack)
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`.
public static func zip<A: PropertyProtocol, B: PropertyProtocol, C: PropertyProtocol, D: PropertyProtocol, E: PropertyProtocol, F: PropertyProtocol, G: PropertyProtocol, H: PropertyProtocol, I: PropertyProtocol, J: PropertyProtocol>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> Property<(A.Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value)> where Value == A.Value {
return zip(a, b, c, d, e, f, g, h, i)
.zip(with: j)
.map(repack)
}
/// Zips the values of all the given properties, in the manner described by
/// `zip(with:)`. Returns nil if the sequence is empty.
public static func zip<S: Sequence>(_ properties: S) -> Property<[S.Iterator.Element.Value]>? where S.Iterator.Element: PropertyProtocol {
var generator = properties.makeIterator()
if let first = generator.next() {
let initial = first.map { [$0] }
return IteratorSequence(generator).reduce(initial) { property, next in
property.zip(with: next).map { $0.0 + [$0.1] }
}
}
return nil
}
}
/// A read-only property that can be observed for its changes over time. There
/// are three categories of read-only properties:
///
/// # Constant property
/// Created by `Property(value:)`, the producer and signal of a constant
/// property would complete immediately when it is initialized.
///
/// # Existential property
/// Created by `Property(capturing:)`, it wraps any arbitrary `PropertyProtocol`
/// types, and passes through the behavior. Note that it would retain the
/// wrapped property.
///
/// Existential property would be deprecated when generalized existential
/// eventually lands in Swift.
///
/// # Composed property
/// A composed property presents a composed view of its sources, which can be
/// one or more properties, a producer, or a signal. It can be created using
/// property composition operators, `Property(_:)` or `Property(initial:then:)`.
///
/// It does not own its lifetime, and its producer and signal are bound to the
/// lifetime of its sources. It also does not have an influence on its sources,
/// so retaining a composed property would not prevent its sources from
/// deinitializing.
///
/// Note that composed properties do not retain any of its sources.
public final class Property<Value>: PropertyProtocol {
private let disposable: Disposable?
private let _value: () -> Value
private let _producer: () -> SignalProducer<Value, NoError>
private let _signal: () -> Signal<Value, NoError>
/// The current value of the property.
public var value: Value {
return _value()
}
/// A producer for Signals that will send the property's current
/// value, followed by all changes over time, then complete when the
/// property has deinitialized or has no further changes.
///
/// - note: If `self` is a composed property, the producer would be
/// bound to the lifetime of its sources.
public var producer: SignalProducer<Value, NoError> {
return _producer()
}
/// A signal that will send the property's changes over time, then
/// complete when the property has deinitialized or has no further changes.
///
/// - note: If `self` is a composed property, the signal would be
/// bound to the lifetime of its sources.
public var signal: Signal<Value, NoError> {
return _signal()
}
/// Initializes a constant property.
///
/// - parameters:
/// - property: A value of the constant property.
public init(value: Value) {
disposable = nil
_value = { value }
_producer = { SignalProducer(value: value) }
_signal = { Signal<Value, NoError>.empty }
}
/// Initializes an existential property which wraps the given property.
///
/// - note: The resulting property retains the given property.
///
/// - parameters:
/// - property: A property to be wrapped.
public init<P: PropertyProtocol>(capturing property: P) where P.Value == Value {
disposable = nil
_value = { property.value }
_producer = { property.producer }
_signal = { property.signal }
}
/// Initializes a composed property which reflects the given property.
///
/// - note: The resulting property does not retain the given property.
///
/// - parameters:
/// - property: A property to be wrapped.
public convenience init<P: PropertyProtocol>(_ property: P) where P.Value == Value {
self.init(unsafeProducer: property.producer)
}
/// Initializes a composed property that first takes on `initial`, then each
/// value sent on a signal created by `producer`.
///
/// - parameters:
/// - initial: Starting value for the property.
/// - values: A producer that will start immediately and send values to
/// the property.
public convenience init(initial: Value, then values: SignalProducer<Value, NoError>) {
self.init(unsafeProducer: values.prefix(value: initial))
}
/// Initialize a composed property that first takes on `initial`, then each
/// value sent on `signal`.
///
/// - parameters:
/// - initialValue: Starting value for the property.
/// - values: A signal that will send values to the property.
public convenience init(initial: Value, then values: Signal<Value, NoError>) {
self.init(unsafeProducer: SignalProducer(values).prefix(value: initial))
}
/// Initialize a composed property by applying the unary `SignalProducer`
/// transform on `property`.
///
/// - parameters:
/// - property: The source property.
/// - transform: A unary `SignalProducer` transform to be applied on
/// `property`.
fileprivate convenience init<P: PropertyProtocol>(
_ property: P,
transform: @escaping (SignalProducer<P.Value, NoError>) -> SignalProducer<Value, NoError>
) {
self.init(unsafeProducer: transform(property.producer))
}
/// Initialize a composed property by applying the binary `SignalProducer`
/// transform on `firstProperty` and `secondProperty`.
///
/// - parameters:
/// - firstProperty: The first source property.
/// - secondProperty: The first source property.
/// - transform: A binary `SignalProducer` transform to be applied on
/// `firstProperty` and `secondProperty`.
fileprivate convenience init<P1: PropertyProtocol, P2: PropertyProtocol>(_ firstProperty: P1, _ secondProperty: P2, transform: @escaping (SignalProducer<P1.Value, NoError>) -> (SignalProducer<P2.Value, NoError>) -> SignalProducer<Value, NoError>) {
self.init(unsafeProducer: transform(firstProperty.producer)(secondProperty.producer))
}
/// Initialize a composed property from a producer that promises to send
/// at least one value synchronously in its start handler before sending any
/// subsequent event.
///
/// - important: The producer and the signal of the created property would
/// complete only when the `unsafeProducer` completes.
///
/// - warning: If the producer fails its promise, a fatal error would be
/// raised.
///
/// - parameters:
/// - unsafeProducer: The composed producer for creating the property.
private init(unsafeProducer: SignalProducer<Value, NoError>) {
// Share a replayed producer with `self.producer` and `self.signal` so
// they see a consistent view of the `self.value`.
// https://github.com/ReactiveCocoa/ReactiveCocoa/pull/3042
let producer = unsafeProducer.replayLazily(upTo: 1)
let atomic = Atomic<Value?>(nil)
disposable = producer.startWithValues { atomic.value = $0 }
// Verify that an initial is sent. This is friendlier than deadlocking
// in the event that one isn't.
guard atomic.value != nil else {
fatalError("A producer promised to send at least one value. Received none.")
}
_value = { atomic.value! }
_producer = { producer }
_signal = { producer.startAndRetrieveSignal() }
}
deinit {
disposable?.dispose()
}
}
/// A mutable property of type `Value` that allows observation of its changes.
///
/// Instances of this class are thread-safe.
public final class MutableProperty<Value>: MutablePropertyProtocol {
private let token: Lifetime.Token
private let observer: Signal<Value, NoError>.Observer
private let atomic: RecursiveAtomic<Value>
/// The current value of the property.
///
/// Setting this to a new value will notify all observers of `signal`, or
/// signals created using `producer`.
public var value: Value {
get {
return atomic.withValue { $0 }
}
set {
swap(newValue)
}
}
/// The lifetime of the property.
public let lifetime: Lifetime
/// A signal that will send the property's changes over time,
/// then complete when the property has deinitialized.
public let signal: Signal<Value, NoError>
/// A producer for Signals that will send the property's current value,
/// followed by all changes over time, then complete when the property has
/// deinitialized.
public var producer: SignalProducer<Value, NoError> {
return SignalProducer { [atomic, weak self] producerObserver, producerDisposable in
atomic.withValue { value in
if let strongSelf = self {
producerObserver.send(value: value)
producerDisposable += strongSelf.signal.observe(producerObserver)
} else {
producerObserver.send(value: value)
producerObserver.sendCompleted()
}
}
}
}
/// Initializes a mutable property that first takes on `initialValue`
///
/// - parameters:
/// - initialValue: Starting value for the mutable property.
public init(_ initialValue: Value) {
(signal, observer) = Signal.pipe()
token = Lifetime.Token()
lifetime = Lifetime(token)
/// Need a recursive lock around `value` to allow recursive access to
/// `value`. Note that recursive sets will still deadlock because the
/// underlying producer prevents sending recursive events.
atomic = RecursiveAtomic(initialValue,
name: "org.reactivecocoa.ReactiveSwift.MutableProperty",
didSet: observer.send(value:))
}
/// Atomically replaces the contents of the variable.
///
/// - parameters:
/// - newValue: New property value.
///
/// - returns: The previous property value.
@discardableResult
public func swap(_ newValue: Value) -> Value {
return atomic.swap(newValue)
}
/// Atomically modifies the variable.
///
/// - parameters:
/// - action: A closure that accepts old property value and returns a new
/// property value.
///
/// - returns: The result of the action.
@discardableResult
public func modify<Result>(_ action: (inout Value) throws -> Result) rethrows -> Result {
return try atomic.modify(action)
}
/// Atomically performs an arbitrary action using the current value of the
/// variable.
///
/// - parameters:
/// - action: A closure that accepts current property value.
///
/// - returns: the result of the action.
@discardableResult
public func withValue<Result>(action: (Value) throws -> Result) rethrows -> Result {
return try atomic.withValue(action)
}
deinit {
observer.sendCompleted()
}
}
| mit | 1f22862278b2fe9188bcd33545a6bf27 | 40.963077 | 453 | 0.684008 | 3.662683 | false | true | false | false |
DrabWeb/Komikan | Komikan/Komikan/KMReaderPageJumpData.swift | 1 | 5297 | //
// KMReaderPageJumpData.swift
// Komikan
//
// Created by Seth on 2016-02-22.
//
import Foundation
import AppKit
class KMReaderPageJumpData : NSObject {
/// The NSImage for the leftmost thumbnails image
var thumbnailOne : NSImage = NSImage();
/// The NSImage for the center thumbnails image
var thumbnailTwo : NSImage = NSImage();
/// The NSImage for the rightmost thumbnails image
var thumbnailThree : NSImage = NSImage();
/// The page that will be jumped to when you click on the leftmost thumbnail
var thumbnailOnePage : Int = -1;
/// The page that will be jumped to when you click on the center thumbnail
var thumbnailTwoPage : Int = -1;
/// The page that will be jumped to when you click on the rightmost thumbnail
var thumbnailThreePage : Int = -1;
/// Is the first thumbnail's page bookmarked?
var thumbnailOneBookmarked : Bool = false;
/// Is the second thumbnail's page bookmarked?
var thumbnailTwoBookmarked : Bool = false;
/// Is the third thumbnail's page bookmarked?
var thumbnailThreeBookmarked : Bool = false;
/// Loads the passed array of NSImages into their respective thumbnail slots
func loadThumbnailsFromArray(_ thumbnails : [NSImage]) {
// For every image in the thumbnails array...
for(currentIndex, currentImage) in thumbnails.enumerated() {
// If this is the first image...
if(currentIndex == 0) {
thumbnailOne = currentImage;
}
// If this is the second image...
else if(currentIndex == 1) {
thumbnailTwo = currentImage;
}
// If this is the third image
else if(currentIndex == 2) {
// Set thumbnail three to the current image
thumbnailThree = currentImage;
}
}
}
/// Loads the page numbers from the passed array of Bools
func loadPageNumbersFromArray(_ pages : [Int]) {
// For every item in the pages array...
for(currentIndex, currentPageNumber) in pages.enumerated() {
// If this is the first page number...
if(currentIndex == 0) {
// Set the first thumbnails page to the current page
thumbnailOnePage = currentPageNumber;
}
// If this is the second page number...
else if(currentIndex == 1) {
// Set the second thumbnails page to the current page
thumbnailTwoPage = currentPageNumber;
}
// If this is the third page number...
else if(currentIndex == 2) {
// Set the third thumbnails page to the current page
thumbnailThreePage = currentPageNumber;
}
}
}
/// Loads the bookmarks from the passed array of Ints
func loadBookmarksFromArray(_ bookmarks : [Bool]) {
// For every item in the bookmarks array...
for(currentIndex, currentBookmark) in bookmarks.enumerated() {
// If this is the first bookmark...
if(currentIndex == 0) {
// Set the first thumbnails bookmarked value to the current bookmark value
thumbnailOneBookmarked = !currentBookmark;
}
// If this is the second bookmark...
else if(currentIndex == 1) {
// Set the second thumbnails bookmarked value to the current bookmark value
thumbnailTwoBookmarked = !currentBookmark;
}
// If this is the third bookmark...
else if(currentIndex == 2) {
// Set the third thumbnails bookmarked value to the current bookmark value
thumbnailThreeBookmarked = !currentBookmark;
}
}
}
// A blank init
override init() {
}
// Init with one page
init(thumbOne : NSImage, thumbOnePage : Int, thumbOneBookmarked : Bool) {
thumbnailOne = thumbOne;
thumbnailOnePage = thumbOnePage;
thumbnailOneBookmarked = thumbOneBookmarked;
}
// Init with two pages
init(thumbOne : NSImage, thumbOnePage : Int, thumbOneBookmarked : Bool, thumbTwo : NSImage, thumbTwoPage : Int, thumbTwoBookmarked : Bool) {
thumbnailOne = thumbOne;
thumbnailOnePage = thumbOnePage;
thumbnailOneBookmarked = thumbOneBookmarked;
thumbnailTwo = thumbTwo;
thumbnailTwoPage = thumbTwoPage;
thumbnailTwoBookmarked = thumbTwoBookmarked;
}
// Init with three pages
init(thumbOne : NSImage, thumbOnePage : Int, thumbOneBookmarked : Bool, thumbTwo : NSImage, thumbTwoPage : Int, thumbTwoBookmarked : Bool, thumbThree : NSImage, thumbThreePage : Int, thumbThreeBookmarked : Bool) {
thumbnailOne = thumbOne;
thumbnailOnePage = thumbOnePage;
thumbnailOneBookmarked = thumbOneBookmarked;
thumbnailTwo = thumbTwo;
thumbnailTwoPage = thumbTwoPage;
thumbnailTwoBookmarked = thumbTwoBookmarked;
thumbnailThree = thumbThree;
thumbnailThreePage = thumbThreePage;
thumbnailThreeBookmarked = thumbThreeBookmarked;
}
}
| gpl-3.0 | bc0d1fbfa17007a7e8a54500a9965930 | 36.835714 | 217 | 0.609213 | 5.122824 | false | false | false | false |
vermont42/Conjugar | Conjugar/StubLocale.swift | 1 | 481 | //
// StubLocale.swift
// Conjugar
//
// Created by Joshua Adams on 12/15/20.
// Copyright © 2020 Josh Adams. All rights reserved.
//
import Foundation
struct StubLocale: Locale {
var languageCode: String
var regionCode: String
private static let english = "en"
private static let america = "US"
init(languageCode: String = StubLocale.english, regionCode: String = StubLocale.america) {
self.languageCode = languageCode
self.regionCode = regionCode
}
}
| agpl-3.0 | dcbe9e29aa5ae93f7fddf5849ccc2246 | 21.857143 | 92 | 0.7125 | 3.870968 | false | false | false | false |
GuiBayma/PasswordVault | PasswordVaultTests/Model/CoreData Managers/GroupManagerTests.swift | 1 | 2934 | //
// GroupManagerTests.swift
// PasswordVault
//
// Created by Guilherme Bayma on 8/1/17.
// Copyright © 2017 Bayma. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import PasswordVault
class GroupManagerTests: QuickSpec {
override func spec() {
describe("GroupManager tests") {
var sut: GroupManager?
var group: Group?
var item: Item?
beforeEach {
sut = GroupManager.sharedInstance
}
afterEach {
if let grp = group {
if let s = sut {
if !s.delete(object: grp) {
fail("could not delete Group")
}
}
}
if let item = item {
if !ItemManager.sharedInstance.delete(object: item) {
fail("could not delete item")
}
}
}
it("should not be nil") {
expect(sut).toNot(beNil())
}
it("should create a new group correctly") {
group = sut?.newGroup()
if !(sut?.save() ?? false) {
fail("could not save new Group")
}
expect(group).toNot(beNil())
}
it("should return all groups correctly") {
group = sut?.newGroup()
if !(sut?.save() ?? false) {
fail("could not save new Group")
}
let groups = sut?.getAllGroups()
expect(groups?.count) >= 1
}
it("should save a new group correctly") {
let count = sut?.getAllGroups().count ?? 0
group = sut?.newGroup()
_ = sut?.save()
let newCount = sut?.getAllGroups().count
expect(newCount) == count + 1
}
it("should delete the group correctly") {
let groupCount = sut?.getAllGroups().count ?? 0
let itemCount = ItemManager.sharedInstance.getAllItems().count
group = sut?.newGroup()
item = ItemManager.sharedInstance.newItem()
if let item = item {
group?.addItem(item)
}
if let group = group {
if let s = sut {
if !s.delete(object: group) {
fail("could not delete group")
}
}
}
let newGroupCount = sut?.getAllGroups().count
let newItemCount = ItemManager.sharedInstance.getAllItems().count
expect(newGroupCount) == groupCount
expect(newItemCount) == itemCount
}
}
}
}
| mit | 8531ccc4b3f6d400960a43854113d337 | 28.039604 | 81 | 0.438118 | 5.441558 | false | false | false | false |
QuantumExplorer/breadwallet | WatchApp Extension/BRAWReceiveMoneyInterfaceController.swift | 2 | 3729 | //
// BRAWReceiveMoneyInterfaceController.swift
// DashWallet
//
// Created by Henry on 10/27/15.
// Copyright (c) 2015 Aaron Voisine <[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 WatchConnectivity
import WatchKit
final class BRAWReceiveMoneyInterfaceController: WKInterfaceController, BRAWKeypadDelegate {
@IBOutlet private var loadingIndicator: WKInterfaceGroup!
@IBOutlet private var qrCodeButton: WKInterfaceButton!
var customQR: UIImage?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
}
override func willActivate() {
super.willActivate()
customQR = nil
updateReceiveUI()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(
self,
selector: #selector(BRAWReceiveMoneyInterfaceController.updateReceiveUI),
name: DWWatchDataManager.ApplicationDataDidUpdateNotification,
object: nil
)
subscribeToTxNotifications()
}
override func didDeactivate() {
super.didDeactivate()
unsubsribeFromTxNotifications()
NotificationCenter.default.removeObserver(self)
}
@objc
func updateReceiveUI() {
if Thread.current != .main {
DispatchQueue.main.async {
self.updateReceiveUI()
}
return
}
if DWWatchDataManager.shared.receiveMoneyQRCodeImage == nil {
loadingIndicator.setHidden(false)
qrCodeButton.setHidden(true)
}
else {
loadingIndicator.setHidden(true)
qrCodeButton.setHidden(false)
var qrImg = DWWatchDataManager.shared.receiveMoneyQRCodeImage
if customQR != nil {
print("Using custom qr image")
qrImg = customQR
}
qrCodeButton.setBackgroundImage(qrImg)
}
}
@IBAction private func qrCodeTap(_ sender: AnyObject?) {
let ctx = BRAWKeypadModel(delegate: self)
presentController(withName: "Keypad", context: ctx)
}
// - MARK: Keypad delegate
func keypadDidFinish(_ stringValueBits: String) {
qrCodeButton.setHidden(true)
loadingIndicator.setHidden(false)
DWWatchDataManager.shared.requestQRCodeForBalance(stringValueBits) { qrImage, error -> Void in
if let qrImage = qrImage {
self.customQR = qrImage
}
self.updateReceiveUI()
print("Got new qr image: \(String(describing: qrImage)) error: \(String(describing: error))")
}
dismiss()
}
}
| mit | 503cf79699d7534b3541d385e498d70a | 34.514286 | 105 | 0.669348 | 4.824062 | false | false | false | false |
rderoldan1/psychologist | Psychologist/PsychologistViewController.swift | 1 | 941 | //
// ViewController.swift
// Psychologist
//
// Created by Ruben Espinosa Roldan on 8/09/15.
// Copyright © 2015 Ruben Espinosa Roldan. All rights reserved.
//
import UIKit
class PsychologistViewController: UIViewController {
@IBAction func nothing(sender: UIButton) {
performSegueWithIdentifier("nothing", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var destination = segue.destinationViewController as? UIViewController
if let navCon = destination as? UINavigationController {
destination = navCon.visibleViewController
}
if let hvc = destination as? HappinessViewController {
if let identifier = segue.identifier {
switch identifier {
case "sad": hvc.happiness = 0
case "happy": hvc.happiness = 100
case "nothing": hvc.happiness = 25
default: hvc.happiness = 50
}
}
}
}
}
| mit | 808285bf1673bf9cfc947f94f14e3e1e | 23.736842 | 79 | 0.678723 | 4.676617 | false | false | false | false |
CrazyZhangSanFeng/BanTang | BanTang/BanTang/Classes/Home/ScrollPageView/ScrollPageView.swift | 1 | 5014 | //
// ScrollPageView.swift
// ScrollViewController
//
// Created by jasnig on 16/4/6.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public class ScrollPageView: UIView {
static let cellId = "cellId"
private var segmentStyle = SegmentStyle()
/// 附加按钮点击响应
public var extraBtnOnClick: ((extraBtn: UIButton) -> Void)? {
didSet {
segView.extraBtnOnClick = extraBtnOnClick
}
}
private var segView: ScrollSegmentView!
private var contentView: ContentView!
private var titlesArray: [String] = []
/// 所有的子控制器
private var childVcs: [UIViewController] = []
// 这里使用weak避免循环引用
private weak var parentViewController: UIViewController?
public init(frame:CGRect, segmentStyle: SegmentStyle, titles: [String], childVcs:[UIViewController], parentViewController: UIViewController) {
self.parentViewController = parentViewController
self.childVcs = childVcs
self.titlesArray = titles
self.segmentStyle = segmentStyle
assert(childVcs.count == titles.count, "标题的个数必须和子控制器的个数相同")
super.init(frame: frame)
// 初始化设置了frame后可以在以后的任何地方直接获取到frame了, 就不必重写layoutsubview()方法在里面设置各个控件的frame
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func commonInit() {
backgroundColor = UIColor.whiteColor()
segView = ScrollSegmentView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: 44), segmentStyle: segmentStyle, titles: titlesArray)
guard let parentVc = parentViewController else { return }
contentView = ContentView(frame: CGRect(x: 0, y: CGRectGetMaxY(segView.frame), width: bounds.size.width, height: bounds.size.height - 44), childVcs: childVcs, parentViewController: parentVc)
contentView.delegate = self
addSubview(segView)
addSubview(contentView)
// 在这里调用了懒加载的collectionView, 那么之前设置的self.frame将会用于collectionView,如果在layoutsubviews()里面没有相关的处理frame的操作, 那么将导致内容显示不正常
// 避免循环引用
segView.titleBtnOnClick = {[unowned self] (label: UILabel, index: Int) in
// 切换内容显示
self.contentView.setContentOffSet(CGPoint(x: self.contentView.bounds.size.width * CGFloat(index), y: 0), animated: self.segmentStyle.changeContentAnimated)
}
}
deinit {
parentViewController = nil
// print("\(self.debugDescription) --- 销毁")
}
}
//MARK: - public helper
extension ScrollPageView {
/// 给外界设置选中的下标的方法
public func selectedIndex(selectedIndex: Int, animated: Bool) {
// 移动滑块的位置
segView.selectedIndex(selectedIndex, animated: animated)
}
/// 给外界重新设置视图内容的标题的方法, 在设置之前需要先移除childViewControllers, 然后添加新的childViewControllers
///
/// - parameter titles: newTitles
/// - parameter newChildVcs: newChildVcs
public func reloadChildVcsWithNewTitles(titles: [String], andNewChildVcs newChildVcs: [UIViewController]) {
self.childVcs = newChildVcs
self.titlesArray = titles
segView.reloadTitlesWithNewTitles(titlesArray)
contentView.reloadAllViewsWithNewChildVcs(childVcs)
}
}
extension ScrollPageView: ContentViewDelegate {
public var segmentView: ScrollSegmentView {
return segView
}
} | apache-2.0 | c966c57d78eb920ad4a815208ce41732 | 35.912 | 198 | 0.69716 | 4.397521 | false | false | false | false |
aschwaighofer/swift | test/Constraints/fixes.swift | 2 | 17739 | // RUN: %target-typecheck-verify-swift
func f1() -> Int { }
func f2(_: Int = 5) -> Int { }
func f3(_: Int...) -> Int { }
class A { }
class B : A {
func iAmAB() {}
func createB() -> B { return B() }
}
func f4() -> B { }
func f5(_ a: A) { }
func f6(_ a: A, _: Int) { }
func createB() -> B { }
func createB(_ i: Int) -> B { }
func f7(_ a: A, _: @escaping () -> Int) -> B { }
func f7(_ a: A, _: Int) -> Int { }
// Forgot the '()' to call a function.
func forgotCall() {
// Simple cases
var x: Int
x = f1 // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}}
x = f2 // expected-error{{cannot assign value of type '(Int) -> Int' to type 'Int'}}
x = f3 // expected-error{{cannot assign value of type '(Int...) -> Int' to type 'Int'}}
// With a supertype conversion
var a = A()
a = f4 // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}{{9-9=()}}
// As a call
f5(f4) // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}{{8-8=()}}
f6(f4, f2) // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}{{8-8=()}}
// expected-error@-1 {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{12-12=()}}
// With overloading: only one succeeds.
a = createB // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}
let _: A = createB // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} {{21-21=()}}
let _: B = createB // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} {{21-21=()}}
// With overloading, pick the fewest number of fixes.
var b = f7(f4, f1) // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}
b.iAmAB()
}
/// Forgot the '!' to unwrap an optional.
func parseInt() -> Int? { }
func <(lhs: A, rhs: A) -> A? { return nil }
func forgotOptionalBang(_ a: A, obj: AnyObject) {
var i: Int = parseInt() // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{26-26= ?? <#default value#>}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{26-26=!}}
var a = A(), b = B()
b = a as? B // expected-error{{value of optional type 'B?' must be unwrapped to a value of type 'B'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{14-14= ?? <#default value#>}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{7-7=(}}{{14-14=)!}}
a = a < a // expected-error{{value of optional type 'A?' must be unwrapped to a value of type 'A'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{7-7=(}}{{12-12=) ?? <#default value#>}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{7-7=(}}{{12-12=)!}}
// rdar://problem/20377684 -- take care that the '!' doesn't fall into an
// optional evaluation context
let bo: B? = b
let b2: B = bo?.createB() // expected-error{{value of optional type 'B?' must be unwrapped to a value of type 'B'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
func forgotAnyObjectBang(_ obj: AnyObject) {
var a = A()
a = obj // expected-error{{'AnyObject' is not convertible to 'A'; did you mean to use 'as!' to force downcast?}}{{10-10= as! A}}
_ = a
}
func increment(_ x: inout Int) { }
func forgotAmpersand() {
var i = 5
increment(i) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{13-13=&}}
var array = [1,2,3]
increment(array[1]) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{13-13=&}}
}
func maybeFn() -> ((Int) -> Int)? { }
func extraCall() {
var i = 7
i = i() // expected-error{{cannot call value of non-function type 'Int'}}{{8-10=}}
maybeFn()(5) // expected-error{{value of optional type '((Int) -> Int)?' must be unwrapped to a value of type '(Int) -> Int'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
class U {
var prop1 = 0
}
class T {
func m1() {
// <rdar://problem/17741575>
let l = self.m2!.prop1
// expected-error@-1 {{cannot force unwrap value of non-optional type '() -> U?'}} {{22-23=}}
// expected-error@-2 {{method 'm2' was used as a property; add () to call it}} {{22-22=()}}
}
func m2() -> U! {
return U()
}
}
// Used an optional in a conditional expression
class C {
var a: Int = 1
}
var co: C? = nil
var ciuo: C! = nil
if co {} // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{4-4=(}} {{6-6= != nil)}}
if ciuo {} // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{4-4=(}} {{8-8= != nil)}}
co ? true : false // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{1-1=(}} {{3-3= != nil)}}
!co ? false : true // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{4-4= == nil)}}
ciuo ? true : false // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{1-1=(}} {{5-5= != nil)}}
!ciuo ? false : true // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{6-6= == nil)}}
!co // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{4-4= == nil)}}
!ciuo // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{6-6= == nil)}}
// Used an integer in a conditional expression
var n1: Int = 1
var n2: UInt8 = 0
var n3: Int16 = 2
if n1 {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} {{4-4=(}} {{6-6= != 0)}}
if !n1 {} // expected-error {{type 'Int' cannot be used as a boolean; test for '== 0' instead}} {{4-5=}} {{5-5=(}} {{7-7= == 0)}}
n1 ? true : false // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} {{1-1=(}} {{3-3= != 0)}}
!n1 ? false : true // expected-error {{type 'Int' cannot be used as a boolean; test for '== 0' instead}} {{1-2=}} {{2-2=(}} {{4-4= == 0)}}
!n1 // expected-error {{type 'Int' cannot be used as a boolean; test for '== 0' instead}} {{1-2=}} {{2-2=(}} {{4-4= == 0)}}
if n2 {} // expected-error {{type 'UInt8' cannot be used as a boolean; test for '!= 0' instead}} {{4-4=(}} {{6-6= != 0)}}
!n3 // expected-error {{type 'Int16' cannot be used as a boolean; test for '== 0' instead}} {{1-2=}} {{2-2=(}} {{4-4= == 0)}}
// Forgotten ! or ?
var someInt = co.a // expected-error{{value of optional type 'C?' must be unwrapped to refer to member 'a' of wrapped base type 'C'}}
// expected-note@-1{{chain the optional using '?' to access member 'a' only for non-'nil' base values}}{{17-17=?}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{17-17=!}}
// SR-839
struct Q {
let s: String?
}
let q = Q(s: nil)
let a: Int? = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}}
// expected-error@-1 {{cannot convert value of type 'String.UTF8View?' to specified type 'Int?'}}
// expected-note@-2{{chain the optional using '?'}}{{18-18=?}}
let b: Int = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}}
// expected-error@-1 {{cannot convert value of type 'String.UTF8View' to specified type 'Int'}}
// expected-note@-2{{chain the optional using '?'}}{{17-17=?}}
// expected-note@-3{{force-unwrap using '!'}}{{17-17=!}}
let d: Int! = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}}
// expected-error@-1 {{cannot convert value of type 'String.UTF8View?' to specified type 'Int?'}}
// expected-note@-2{{chain the optional using '?'}}{{18-18=?}}
let c = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}}
// expected-note@-1{{chain the optional using '?' to access member 'utf8' only for non-'nil' base values}}{{12-12=?}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{12-12=!}}
// SR-1116
struct S1116 {
var s: Int?
}
let a1116: [S1116] = []
var s1116 = Set(1...10).subtracting(a1116.map({ $0.s })) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{49-49=(}} {{53-53= ?? <#default value#>)}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{53-53=!}}
func makeArray<T>(_ x: T) -> [T] { [x] }
func sr12399(_ x: Int?) {
_ = Set(0...10).subtracting(makeArray(x)) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{42-42= ?? <#default value#>}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{42-42=!}}
}
func moreComplexUnwrapFixes() {
struct S {
let value: Int
let optValue: Int? = nil
}
struct T {
let s: S
let optS: S?
}
func takeNon(_ x: Int) -> Void {}
func takeOpt(_ x: Int?) -> Void {}
let s = S(value: 0)
let t: T? = T(s: s, optS: nil)
let os: S? = s
takeOpt(os.value) // expected-error{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}}
// expected-note@-1{{chain the optional using '?'}}{{13-13=?}}
takeNon(os.value) // expected-error{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}}
// expected-note@-1{{chain the optional using '?'}}{{13-13=?}}
// expected-note@-2{{force-unwrap using '!'}}{{13-13=!}}
// FIXME: Ideally we'd recurse evaluating chaining fixits instead of only offering just the unwrap of t
takeOpt(t.s.value) // expected-error{{value of optional type 'T?' must be unwrapped to refer to member 's' of wrapped base type 'T'}}
// expected-note@-1{{chain the optional using '?'}}{{12-12=?}}
// expected-note@-2{{force-unwrap using '!'}}{{12-12=!}}
takeOpt(t.optS.value) // expected-error{{value of optional type 'T?' must be unwrapped to refer to member 'optS' of wrapped base type 'T'}}
// expected-note@-1{{chain the optional using '?'}}{{12-12=?}}
// expected-error@-2{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}}
// expected-note@-3{{chain the optional using '?'}}{{17-17=?}}
takeNon(t.optS.value) // expected-error{{value of optional type 'T?' must be unwrapped to refer to member 'optS' of wrapped base type 'T'}}
// expected-note@-1{{chain the optional using '?'}}{{12-12=?}}
// expected-error@-2{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}}
// expected-note@-3{{chain the optional using '?'}}{{17-17=?}}
// expected-note@-4{{force-unwrap using '!'}}{{17-17=!}}
takeNon(os?.value) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{force-unwrap using '!'}}{{13-14=!}}
// expected-note@-2{{coalesce}}
takeNon(os?.optValue) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{force-unwrap using '!'}}{{11-11=(}} {{23-23=)!}}
// expected-note@-2{{coalesce}}
func sample(a: Int?, b: Int!) {
let aa = a
// expected-note@-1{{short-circuit using 'guard'}}{{5-5=guard }} {{15-15= else \{ return \}}}
// expected-note@-2{{force-unwrap}}
// expected-note@-3{{coalesce}}
let bb = b // expected-note{{value inferred to be type 'Int?' when initialized with an implicitly unwrapped value}}
// expected-note@-1{{short-circuit using 'guard'}}{{5-5=guard }} {{15-15= else \{ return \}}}
// expected-note@-2{{force-unwrap}}
// expected-note@-3{{coalesce}}
let cc = a
takeNon(aa) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}}
takeNon(bb) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}}
_ = [].map { takeNon(cc) } // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}}
takeOpt(cc)
}
func sample2(a: Int?) -> Int {
let aa = a
// expected-note@-1{{short-circuit using 'guard'}}{{5-5=guard }} {{15-15= else \{ return <#default value#> \}}}
// expected-note@-2{{force-unwrap}}
// expected-note@-3{{coalesce}}
return aa // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}}
}
}
struct FooStruct {
func a() -> Int?? { return 10 }
var b: Int?? {
return 15
}
func c() -> Int??? { return 20 }
var d: Int??? {
return 25
}
let e: BarStruct? = BarStruct()
func f() -> Optional<Optional<Int>> { return 29 }
}
struct BarStruct {
func a() -> Int? { return 30 }
var b: Int?? {
return 35
}
}
let thing: FooStruct? = FooStruct()
let _: Int? = thing?.a() // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
let _: Int? = thing?.b // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
let _: Int?? = thing?.c() // expected-error {{value of optional type 'Int???' must be unwrapped to a value of type 'Int??'}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
let _: Int?? = thing?.d // expected-error {{value of optional type 'Int???' must be unwrapped to a value of type 'Int??'}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
let _: Int = thing?.e?.a() // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
let _: Int? = thing?.e?.b // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
let _: Int? = thing?.f() // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
// SR-9851 - https://bugs.swift.org/browse/SR-9851
func coalesceWithParensRootExprFix() {
let optionalBool: Bool? = false
if !optionalBool { } // expected-error{{value of optional type 'Bool?' must be unwrapped to a value of type 'Bool'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{7-7=(}}{{19-19= ?? <#default value#>)}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
func test_explicit_call_with_overloads() {
func foo(_: Int) {}
struct S {
func foo(_: Int) -> Int { return 0 }
func foo(_: Int = 32, _: String = "hello") -> Int {
return 42
}
}
foo(S().foo)
// expected-error@-1 {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{14-14=()}}
}
// SR-11476
func testKeyPathSubscriptArgFixes(_ fn: @escaping () -> Int) {
struct S {
subscript(x: Int) -> Int { x }
}
var i: Int?
_ = \S.[i] // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{12-12= ?? <#default value#>}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{12-12=!}}
_ = \S.[nil] // expected-error {{'nil' is not compatible with expected argument type 'Int'}}
_ = \S.[fn] // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{13-13=()}}
}
func sr12426(a: Any, _ str: String?) {
a == str // expected-error {{cannot convert value of type 'Any' to expected argument type 'String'}}
// expected-error@-1 {{value of optional type 'String?' must be unwrapped to a value of type 'String'}}
// expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
| apache-2.0 | ce14ba930e20cc503996425db5f87cc4 | 47.6 | 151 | 0.626078 | 3.408724 | false | false | false | false |
studyYF/YueShiJia | YueShiJia/YueShiJia/Classes/Home/Views/YFHomeTypeThreeCell.swift | 1 | 1367 | //
// YFHomeTypeThreeCell.swift
// YueShiJia
//
// Created by YangFan on 2017/5/11.
// Copyright © 2017年 YangFan. All rights reserved.
//
import UIKit
class YFHomeTypeThreeCell: UITableViewCell {
//MARK: 属性
@IBOutlet weak var goodImgv: UIImageView!
/// 商品名称
@IBOutlet weak var goodsNameLabel: UILabel!
/// 商品描述
@IBOutlet weak var goodDesLabel: UILabel!
/// 价格,购买按钮
@IBOutlet weak var priceButton: UIButton!
/// 收藏按钮
@IBOutlet weak var likeButton: UIButton!
var item: YFHomeItem? {
didSet {
goodImgv.kf.setImage(with: URL(string: (item?.relation_object_image)!),placeholder: UIImage(named: "bg_loding_defalut"))
goodsNameLabel.text = item?.relation_object_title
goodDesLabel.text = item?.relation_object_jingle
priceButton.setTitle("¥\((item?.goods_price) ?? "其他类型")", for: .normal)
}
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
priceButton.layer.borderColor = kColor.cgColor
priceButton.layer.borderWidth = 0.3
likeButton.layer.borderColor = kColor.cgColor
likeButton.layer.borderWidth = 0.3
likeButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0)
}
}
| apache-2.0 | aece33f7a2cdf1837630dd8f82d53684 | 26.333333 | 132 | 0.628049 | 3.975758 | false | false | false | false |
ahoppen/swift | test/Constraints/sr10757.swift | 9 | 452 | // RUN: %target-typecheck-verify-swift
// SR-10757
struct Parser<A> {
let run: (inout Substring) -> A?
func map<B>(_ f: @escaping (A) -> B) -> Parser<B> {
return Parser<B> { input in
self.run(&input).map(f)
}
}
}
let char = Parser<Character> { str in
guard let match = str.first else { return nil }
str.removeFirst()
return match
}
let northSouth = char.map {
$0 == "N"
? 1.0
: $0 == "S" ? -1 : nil // Ok
}
| apache-2.0 | 0683b3654331fde4f5a3d7b6bfb79924 | 17.08 | 53 | 0.553097 | 2.825 | false | false | false | false |
huangboju/Moots | Examples/CIFilter/MetalFilters-master/MetalFilters/Views/FilterTintColorPicker.swift | 1 | 2328 | //
// FilterTintColorPicker.swift
// MetalFilters
//
// Created by xu.shuifeng on 2018/6/14.
// Copyright © 2018 shuifeng.me. All rights reserved.
//
import UIKit
protocol FilterTintColorPickerDelegate {
}
class FilterTintColorPicker: UIControl, UIGestureRecognizerDelegate {
private var boundingBoxes: [CGRect] = []
private let padding: CGFloat = 30.0
private let itemSize: CGFloat = 16.0
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .clear
var elements: [UIAccessibilityElement] = []
let colors = MTTintColor.colors()
let numberOfColors = colors.count
let width = frame.width - 2*padding
let spaceWidth = (width - CGFloat(numberOfColors)*itemSize)/CGFloat(numberOfColors-1)
for index in 0..<numberOfColors {
let color = colors[index]
let x = padding + CGFloat(index)*(spaceWidth + itemSize)
let rect = CGRect(x: x, y: 75, width: itemSize, height: itemSize)
boundingBoxes.append(rect)
let accessibilityElement = UIAccessibilityElement(accessibilityContainer: self)
accessibilityElement.isAccessibilityElement = true
accessibilityElement.accessibilityFrame = rect
accessibilityElement.accessibilityLabel = color.displayName
accessibilityElement.accessibilityHint = "Tap to apply this color. Tap again to adjust strength."
elements.append(accessibilityElement)
}
self.accessibilityElements = elements
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
addGestureRecognizer(tapGesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func draw(_ rect: CGRect) {
// Drawing code
// TODO
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// layoutIfNeeded
}
@objc private func handleTapGesture(_ gesture: UITapGestureRecognizer) {
//let point = gesture.location(in: self)
}
}
| mit | 249d9f6c7fe5336a45d6ea22cefba7ee | 30.445946 | 109 | 0.637731 | 5.14823 | false | false | false | false |
tsc000/SCCycleScrollView | SCCycleScrollView/SCCycleScrollView/SecondViewController.swift | 1 | 18862 | //
// SecondViewController.swift
// SCCycleScrollView
//
// Created by 童世超 on 2017/6/21.
// Copyright © 2017年 童世超. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController, SCCycleScrollViewDelegate {
var injectedTag: NSInteger = 0
private var sccyleScrollView: SCCycleScrollView!
private var sccyleTitleScrollView: SCCycleScrollView!
private var scCycle1: SCCycleScrollView!
private var scCycle2: SCCycleScrollView!
private var scCycle3: SCCycleScrollView!
private var pageControl: RoundedRectanglePageControl!
private var rPageControl: RectanglePageControl!
private var mPageControl: MergeRectanglePageControl!
private var revert: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.lightGray
let methodString = ["createImageScrollView", "createNetImage", "createImage", "createTitleScrollView",
"createCustomCellScrollView", "createCustomPagecontrol", "createCustomPagecontrolAndCell", "createChangeImage",
"createTmallImage", "createJingdongImage"
]
let selector = Selector(methodString[injectedTag - 1000])
perform(selector)
}
//图 + 文字
@objc private func createImageScrollView() {
let frame = CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 200)
let placeholderImage = UIImage(named: "swift.jpeg")
let imageArray = [
"https://cdn.pixabay.com/photo/2016/07/16/13/50/sun-flower-1521851_960_720.jpg",
"https://cdn.pixabay.com/photo/2014/08/11/23/10/bud-416110_960_720.jpg",
"https://cdn.pixabay.com/photo/2016/10/03/17/11/cosmos-flower-1712177_960_720.jpg",
"https://cdn.pixabay.com/photo/2015/06/13/19/00/dandelion-808255_960_720.jpg"
] as [AnyObject]
let titleArray = [
"感谢您的支持",
"如果发现代码出现bug",
"请联系QQ:767616124",
"或发至邮箱:[email protected]",
"轮播图持续维护中..."
]
let sccyleScrollView = SCCycleScrollView.cycleScrollView(frame: frame, delegate: nil, imageArray: nil, titleArray: nil, placeholderImage: placeholderImage)
sccyleScrollView.imageArray = imageArray as [AnyObject]
sccyleScrollView.titleArray = titleArray
sccyleScrollView.titleFont = UIFont.systemFont(ofSize: 16)
sccyleScrollView.titleColor = UIColor.orange
sccyleScrollView.center = view.center
self.sccyleScrollView = sccyleScrollView
// sccyleScrollView.delegate = self
sccyleScrollView.pageControlOrigin = CGPoint(x: (sccyleScrollView.frame.width - sccyleScrollView.pageControlSize.width) / 2.0, y: sccyleScrollView.frame.height - 40 - sccyleScrollView.pageControlSize.height - 6);
view.addSubview(sccyleScrollView)
}
//网络图片
@objc func createNetImage() {
let frame = CGRect(x: 0, y: 300, width: UIScreen.main.bounds.width, height: 200)
let placeholderImage = UIImage(named: "swift.jpeg")
let imageArray = [
"https://cdn.pixabay.com/photo/2016/07/16/13/50/sun-flower-1521851_960_720.jpg",
"https://cdn.pixabay.com/photo/2014/08/11/23/10/bud-416110_960_720.jpg",
"https://cdn.pixabay.com/photo/2016/10/03/17/11/cosmos-flower-1712177_960_720.jpg",
"https://cdn.pixabay.com/photo/2015/06/13/19/00/dandelion-808255_960_720.jpg"
] as [AnyObject]
let cycleScrollView = SCCycleScrollView.cycleScrollView(frame: frame, delegate: nil, imageArray: nil, placeholderImage: placeholderImage)
cycleScrollView.imageArray = imageArray
cycleScrollView.center = view.center
cycleScrollView.scrollDirection = .vertical
cycleScrollView.pageControlOrigin = CGPoint(x: (cycleScrollView.frame.width - cycleScrollView.pageControlSize.width) / 2.0, y: cycleScrollView.frame.height - cycleScrollView.pageControlSize.height - 10);
view.addSubview(cycleScrollView)
}
//本地图片
@objc func createImage() {
let frame = CGRect(x: 0, y: 484, width: UIScreen.main.bounds.width, height: 200)
let placeholderImage = UIImage(named: "swift.jpeg")
let imageArray = [
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
"5.jpg",
"6.jpg"
] as [AnyObject]
scCycle3 = SCCycleScrollView.cycleScrollView(frame: frame, delegate: self, imageArray: nil, placeholderImage: placeholderImage)
scCycle3.imageArray = imageArray
scCycle3.scrollDirection = .vertical
scCycle3.pageControlOrigin = CGPoint(x: (scCycle3.frame.width - scCycle3.pageControlSize.width) / 2.0, y: scCycle3.frame.height - scCycle3.pageControlSize.height - 10);
scCycle3.center = view.center
view.addSubview(scCycle3)
}
//纯文字
@objc private func createTitleScrollView() {
let frame = CGRect(x: 0, y: 550, width: UIScreen.main.bounds.width, height: 80)
let titleArray = [
"感谢您的支持",
"如果发现代码出现bug",
"请联系QQ:767616124",
"或发至邮箱:[email protected]",
"轮播图持续维护中..."
]
let sccyleTitleScrollView = SCCycleScrollView.cycleScrollView(frame: frame, delegate: nil, titleArray: titleArray)
sccyleTitleScrollView.imageArray = nil
sccyleTitleScrollView.scrollDirection = .vertical
sccyleTitleScrollView.titleLeftMargin = 15
sccyleTitleScrollView.titleContainerAlpha = 0.5
sccyleTitleScrollView.titleContainerBackgroundColor = UIColor.black
sccyleTitleScrollView.titleColor = UIColor.white
sccyleTitleScrollView.timeInterval = 2.0
self.sccyleTitleScrollView = sccyleTitleScrollView
view.backgroundColor = UIColor.orange
// sccyleTitleScrollView.delegate = self
sccyleTitleScrollView.center = view.center
view.addSubview(sccyleTitleScrollView)
}
//自定义cell
@objc private func createCustomCellScrollView() -> SCCycleScrollView {
let frame = CGRect(x: 0, y: 300, width: UIScreen.main.bounds.width, height: 200)
let imageArray = [
"http://jbcdn1.b0.upaiyun.com/2015/09/031814sbu.jpg",
"https://cdn.pixabay.com/photo/2016/07/16/13/50/sun-flower-1521851_960_720.jpg",
"https://cdn.pixabay.com/photo/2014/08/11/23/10/bud-416110_960_720.jpg",
"https://cdn.pixabay.com/photo/2016/10/03/17/11/cosmos-flower-1712177_960_720.jpg",
"https://cdn.pixabay.com/photo/2015/06/13/19/00/dandelion-808255_960_720.jpg"
] as [AnyObject]
let titleArray = [
"感谢您的支持",
"如果发现代码出现bug",
"请联系QQ:767616124",
"或发至邮箱:[email protected]",
"轮播图持续维护中..."
]
let sccyleScrollView = SCCycleScrollView(frame: frame)
sccyleScrollView.cellType = .custom
sccyleScrollView.delegate = self
sccyleScrollView.imageArray = imageArray as [AnyObject]
sccyleScrollView.titleArray = titleArray
sccyleScrollView.titleFont = UIFont.systemFont(ofSize: 16)
sccyleScrollView.titleColor = UIColor.orange
sccyleScrollView.pageControlOrigin = CGPoint(x: (sccyleScrollView.frame.width - sccyleScrollView.pageControlSize.width) / 2.0, y: sccyleScrollView.frame.height - sccyleScrollView.pageControlSize.height - 20);
sccyleScrollView.center = view.center
view.addSubview(sccyleScrollView)
return sccyleScrollView
}
//自定义pagecontrol
@objc func createCustomPagecontrol() {
let frame = CGRect(x: 0, y: 300, width: UIScreen.main.bounds.width, height: 200)
let placeholderImage = UIImage(named: "swift.jpeg")
let imageArray = [
"https:cdn.pixabay.com/photo/2016/07/16/13/50/sun-flower-1521851_960_720.jpg",
"https:cdn.pixabay.com/photo/2014/08/11/23/10/bud-416110_960_720.jpg",
"https:cdn.pixabay.com/photo/2016/10/03/17/11/cosmos-flower-1712177_960_720.jpg",
"https:cdn.pixabay.com/photo/2015/06/13/19/00/dandelion-808255_960_720.jpg"
] as [AnyObject]
let cycleScrollView = SCCycleScrollView.cycleScrollView(frame: frame, delegate: self, imageArray: nil, pageControlStyle: .custom, placeholderImage: placeholderImage)
cycleScrollView.imageArray = imageArray
cycleScrollView.center = view.center
cycleScrollView.scrollDirection = .horizontal
cycleScrollView.pageControlOrigin = CGPoint(x: (cycleScrollView.frame.width - cycleScrollView.pageControlSize.width) / 2.0, y: cycleScrollView.frame.height - cycleScrollView.pageControlSize.height - 10);
pageControl = RoundedRectanglePageControl(frame: CGRect.null)
// pageControl.backgroundColor = UIColor.clear
pageControl.numberOfPages = imageArray.count
pageControl.currentPageWidth = 40
cycleScrollView.addSubview(pageControl)
view.addSubview(cycleScrollView)
}
//自定义pagecontrol 和cell
@objc func createCustomPagecontrolAndCell() {
let frame = CGRect(x: 0, y: 300, width: UIScreen.main.bounds.width, height: 200)
let imageArray = [
"https:cdn.pixabay.com/photo/2016/07/16/13/50/sun-flower-1521851_960_720.jpg",
"https:cdn.pixabay.com/photo/2014/08/11/23/10/bud-416110_960_720.jpg",
"https:cdn.pixabay.com/photo/2016/10/03/17/11/cosmos-flower-1712177_960_720.jpg",
"https:cdn.pixabay.com/photo/2015/06/13/19/00/dandelion-808255_960_720.jpg"
] as [AnyObject]
let cycleScrollView = SCCycleScrollView(frame: frame)
cycleScrollView.cellType = .custom
cycleScrollView.pageControlStyle = .custom
cycleScrollView.delegate = self
cycleScrollView.imageArray = imageArray
cycleScrollView.center = view.center
cycleScrollView.scrollDirection = .horizontal
cycleScrollView.pageControlOrigin = CGPoint(x: (cycleScrollView.frame.width - cycleScrollView.pageControlSize.width) / 2.0, y: cycleScrollView.frame.height - cycleScrollView.pageControlSize.height - 10);
pageControl = RoundedRectanglePageControl(frame: CGRect.null)
pageControl.backgroundColor = UIColor.clear
pageControl.numberOfPages = imageArray.count
pageControl.currentPageWidth = 40
cycleScrollView.addSubview(pageControl)
view.addSubview(cycleScrollView)
}
//切换数据源
@objc func createChangeImage() {
let frame = CGRect(x: 0, y: 300, width: UIScreen.main.bounds.width, height: 200)
let placeholderImage = UIImage(named: "swift.jpeg")
let imageArray = [
"https://cdn.pixabay.com/photo/2016/07/16/13/50/sun-flower-1521851_960_720.jpg",
"https://cdn.pixabay.com/photo/2014/08/11/23/10/bud-416110_960_720.jpg",
"https://cdn.pixabay.com/photo/2016/10/03/17/11/cosmos-flower-1712177_960_720.jpg",
"https://cdn.pixabay.com/photo/2015/06/13/19/00/dandelion-808255_960_720.jpg"
] as [AnyObject]
scCycle2 = SCCycleScrollView.cycleScrollView(frame: frame, delegate: nil, imageArray: nil, placeholderImage: placeholderImage)
scCycle2.imageArray = imageArray
scCycle2.center = view.center
scCycle2.scrollDirection = .vertical
scCycle2.pageControlOrigin = CGPoint(x: (scCycle2.frame.width - scCycle2.pageControlSize.width) / 2.0, y: scCycle2.frame.height - scCycle2.pageControlSize.height - 10);
view.addSubview(scCycle2)
createButton()
}
//天猫
@objc func createTmallImage() {
let frame = CGRect(x: 0, y: 300, width: UIScreen.main.bounds.width, height: 200)
let placeholderImage = UIImage(named: "swift.jpeg")
let imageArray = [
"https:cdn.pixabay.com/photo/2016/07/16/13/50/sun-flower-1521851_960_720.jpg",
"https:cdn.pixabay.com/photo/2014/08/11/23/10/bud-416110_960_720.jpg",
"https:cdn.pixabay.com/photo/2016/10/03/17/11/cosmos-flower-1712177_960_720.jpg",
"https:cdn.pixabay.com/photo/2015/06/13/19/00/dandelion-808255_960_720.jpg"
] as [AnyObject]
let cycleScrollView = SCCycleScrollView.cycleScrollView(frame: frame, delegate: self, imageArray: nil, pageControlStyle: .custom, placeholderImage: placeholderImage)
cycleScrollView.imageArray = imageArray
cycleScrollView.center = view.center
cycleScrollView.scrollDirection = .horizontal
cycleScrollView.pageControlOrigin = CGPoint(x: (cycleScrollView.frame.width - cycleScrollView.pageControlSize.width) / 2.0, y: cycleScrollView.frame.height - cycleScrollView.pageControlSize.height - 10);
rPageControl = RectanglePageControl(frame: CGRect.null)
rPageControl.numberOfPages = imageArray.count
rPageControl.currentPageWidth = 17
rPageControl.minimumInteritemSpacing = 3
rPageControl.pageHeight = 3
cycleScrollView.addSubview(rPageControl)
view.addSubview(cycleScrollView)
}
//京东
@objc func createJingdongImage() {
let frame = CGRect(x: 0, y: 300, width: UIScreen.main.bounds.width, height: 200)
let placeholderImage = UIImage(named: "swift.jpeg")
let imageArray = [
"https:cdn.pixabay.com/photo/2016/07/16/13/50/sun-flower-1521851_960_720.jpg",
"https:cdn.pixabay.com/photo/2014/08/11/23/10/bud-416110_960_720.jpg",
"https:cdn.pixabay.com/photo/2016/10/03/17/11/cosmos-flower-1712177_960_720.jpg",
"https:cdn.pixabay.com/photo/2015/06/13/19/00/dandelion-808255_960_720.jpg"
] as [AnyObject]
let cycleScrollView = SCCycleScrollView.cycleScrollView(frame: frame, delegate: self, imageArray: nil, pageControlStyle: .custom, placeholderImage: placeholderImage)
cycleScrollView.imageArray = imageArray
cycleScrollView.center = view.center
cycleScrollView.scrollDirection = .horizontal
mPageControl = MergeRectanglePageControl(frame: CGRect.null)
mPageControl.numberOfPages = imageArray.count
// mPageControl.currentPageWidth = 17
// mPageControl.minimumInteritemSpacing = 3
// mPageControl.pageHeight = 3
cycleScrollView.addSubview(mPageControl)
view.addSubview(cycleScrollView)
}
private func createButton() {
let button = UIButton()
button.setTitle("切换", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.addTarget(self, action: #selector(buttonDidClick), for: .touchUpInside)
button.frame = CGRect(x: (view.frame.width - 40 ) / 2.0, y: 700, width: 40, height: 40)
view.addSubview(button)
}
@objc private func buttonDidClick() {
if revert {
scCycle2.imageArray = [
"http://jbcdn1.b0.upaiyun.com/2015/09/031814sbu.jpg",
"https://cdn.pixabay.com/photo/2013/11/26/01/45/flower-218485_960_720.jpg",
"https://cdn.pixabay.com/photo/2014/08/11/23/10/bud-416110_960_720.jpg",
"https://cdn.pixabay.com/photo/2016/10/03/17/11/cosmos-flower-1712177_960_720.jpg",
"https://cdn.pixabay.com/photo/2015/06/13/19/00/dandelion-808255_960_720.jpg"
] as [AnyObject]
scCycle2.titleArray = [
"感谢您的支持",
"如果发现代码出现bug",
"请联系QQ:767616124",
"或发至邮箱:[email protected]",
"轮播图持续维护中..."
]
scCycle2.pageControlOrigin = CGPoint(x: (scCycle2.frame.width - scCycle2.pageControlSize.width) / 2.0, y: scCycle2.frame.height - scCycle2.pageControlSize.height - 10 );
revert = false
} else {
scCycle2.imageArray = ["http://zhsq2dev.loganwy.com/upload/ads/C3D058A0-10CD-DA2B-5947-EF7B9203FBF3/20181130/cc4e01b1db02fd4c63688beac97dd2ef.jpg"]
scCycle2.isHiddenOnlyPage = false
scCycle2.titleArray = []
scCycle2.pageControlOrigin = CGPoint(x: (scCycle2.frame.width - scCycle2.pageControlSize.width) / 2.0, y: scCycle2.frame.height - scCycle2.pageControlSize.height - 10 );
revert = true
}
}
//下面两个是处定义cell代理
func configureCollectionViewCell(cell: UICollectionViewCell, atIndex index: NSInteger, for cycleScrollView: SCCycleScrollView) {
let _ = cell as! CustomCollectionViewCell
}
func cellType(for cycleScrollView: SCCycleScrollView) -> AnyClass {
return CustomCollectionViewCell.self
}
//下面自定义Pagecontrol代理
func cycleScrollView(_ cycleScrollView: SCCycleScrollView, didScroll scrollView: UIScrollView, atIndex index: NSInteger) {
if pageControl != nil {
pageControl.currentPage = index
pageControl.frame.origin = CGPoint(x: (cycleScrollView.frame.width - pageControl.frame.width) / 2.0, y: cycleScrollView.frame.height - 20 - pageControl.pageHeight)
} else if rPageControl != nil {
rPageControl.currentPage = index
rPageControl.frame.origin = CGPoint(x: (cycleScrollView.frame.width - rPageControl.frame.width) / 2.0, y: cycleScrollView.frame.height - 10 - rPageControl.pageHeight)
} else {
mPageControl.currentPage = index
mPageControl.frame.origin = CGPoint(x: (cycleScrollView.frame.width - mPageControl.frame.width) / 2.0, y: cycleScrollView.frame.height - 10 - mPageControl.pageHeight)
}
}
}
| mit | a964daf17d91af83d054d46f7d820f49 | 41.713626 | 220 | 0.635361 | 3.939297 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/Metadata/ExperimentUpdateManager.swift | 1 | 21731 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// The experiment update manager delegate is designed to observe events specific to the operation
/// of the manager, not for observing changes to an experiment. Register as a listener for
/// experiment-level updates.
protocol ExperimentUpdateManagerDelegate: class {
/// Informs the delegate an experiment was saved.
///
/// - Parameter experimentID: An experiment ID.
func experimentUpdateManagerDidSaveExperiment(withID experimentID: String)
/// Informs the delegate a cover image asset was deleted.
///
/// - Parameters:
/// - assetPath: The deleted asset path.
/// - experimentID: The ID of the experiment that owns the asset.
func experimentUpdateManagerDidDeleteCoverImageAsset(withPath assetPath: String,
experimentID: String)
}
/// Manages changes to an experiment and notifies interested objects via a listener pattern.
class ExperimentUpdateManager {
// MARK: - Properties
/// The experiment being updated.
var experiment: Experiment
/// The delegate.
weak var delegate: ExperimentUpdateManagerDelegate?
private let experimentDataDeleter: ExperimentDataDeleter
private let sensorDataManager: SensorDataManager
private let metadataManager: MetadataManager
private var updateListeners = NSHashTable<AnyObject>.weakObjects()
// MARK: - Public
/// Designated initializer.
///
/// - Parameters:
/// - experiment: The experiment to manage.
/// - experimentDataDeleter: The experiment data deleter.
/// - metadataManager: The metadata manager.
/// - sensorDataManager: The sensor data manager.
init(experiment: Experiment,
experimentDataDeleter: ExperimentDataDeleter,
metadataManager: MetadataManager,
sensorDataManager: SensorDataManager) {
self.experiment = experiment
self.experimentDataDeleter = experimentDataDeleter
self.metadataManager = metadataManager
self.sensorDataManager = sensorDataManager
// Register for trial stats update notifications.
NotificationCenter.default.addObserver(self,
selector: #selector(handleTrialStatsDidCompleteNotification(notification:)),
name: SensorDataManager.TrialStatsCalculationDidComplete,
object: nil)
}
/// Convenience initializer that loads an experiment based on its ID, if possible.
///
/// - Parameters:
/// - experimentID: An experiment ID.
/// - experimentDataDeleter: The experiment data deleter.
/// - metadataManager: The metadata manager.
/// - sensorDataManager: The sensor data manager.
convenience init?(experimentID: String,
experimentDataDeleter: ExperimentDataDeleter,
metadataManager: MetadataManager,
sensorDataManager: SensorDataManager) {
guard let experiment = metadataManager.experiment(withID: experimentID) else {
return nil
}
self.init(experiment: experiment,
experimentDataDeleter: experimentDataDeleter,
metadataManager: metadataManager,
sensorDataManager: sensorDataManager)
}
/// Adds the given object as a listener to experiment changes. Listener must conform to
/// ExperimentUpdateListener to actually recieve updates. Maintains a weak reference to listeners.
///
/// - Parameter listener: Any object that conforms to ExperimentUpdateListener.
func addListener(_ listener: AnyObject) {
updateListeners.add(listener)
}
/// Removes a listener.
///
/// - Parameter listener: The listener to remove.
func removeListener(_ listener: AnyObject) {
updateListeners.remove(listener)
}
/// Sets the title of an experiment. Passing nil removes the title.
///
/// - Parameter title: A string title.
func setTitle(_ title: String?) {
experiment.setTitle(title)
saveExperiment()
}
/// Sets the experiment's cover image. Passing nil removes the previous image and deletes the
/// asset from disk.
///
/// - Parameters:
/// - imageData: The image data.
/// - metadata: The image metadata associated with the image.
func setCoverImageData(_ imageData: Data?, metadata: NSDictionary?) {
let previousCoverImagePath = experiment.imagePath
metadataManager.saveCoverImageData(imageData,
metadata: metadata,
forExperiment: experiment)
if let previousCoverImagePath = previousCoverImagePath,
!experiment.isImagePathInUseByNotes(previousCoverImagePath) {
experimentDataDeleter.permanentlyDeleteAsset(atPath: previousCoverImagePath,
experimentID: experiment.ID)
delegate?.experimentUpdateManagerDidDeleteCoverImageAsset(withPath: previousCoverImagePath,
experimentID: experiment.ID)
}
saveExperiment()
}
/// Adds a note to the trial with the given ID.
///
/// - Parameters:
/// - note: A note.
/// - trialID: A trial ID.
func addTrialNote(_ note: Note, trialID: String) {
insertTrialNote(note, trialID: trialID, atIndex: nil)
}
/// Inserts a note in a trial with the given ID at a specific index.
///
/// - Parameters:
/// - note: A note.
/// - trialID: A trial ID.
/// - index: The index to insert the note in the trial.
func insertTrialNote(_ note: Note, trialID: String, atIndex index: Int?) {
// Get the trial corresponding to the display trial and the updated note.
guard let trial = experiment.trial(withID: trialID) else {
return
}
insertTrialNote(note, trial: trial, atIndex: index, isUndo: false)
}
/// Inserts a note in a trial at a specifc index.
///
/// - Parameters:
/// - note: A note.
/// - trial: A trial.
/// - index: The index to insert the note in the trial.
/// - isUndo: Whether the insert is undoing a deletion.
func insertTrialNote(_ note: Note, trial: Trial, atIndex index: Int?, isUndo: Bool) {
// Add to the end if no index is specified.
var insertedIndex: Int
if let index = index {
insertedIndex = index
} else {
insertedIndex = trial.notes.endIndex
}
trial.insertNote(note, atIndex: insertedIndex, experiment: experiment, isUndo: isUndo)
if let pictureNote = note as? PictureNote, let filePath = pictureNote.filePath {
metadataManager.updateCoverImageForAddedImageIfNeeded(imagePath: filePath,
experiment: experiment)
}
saveExperiment()
notifyListeners { (listener) in
listener.experimentUpdateTrialNoteAdded(note, toTrial: trial)
}
}
/// Add a note to the experiment.
///
/// - Parameter note: A note.
func addExperimentNote(_ note: Note) {
insertExperimentNote(note, atIndex: nil, isUndo: false)
}
/// Inserts a note in the experiment at a specific index.
///
/// - Parameters:
/// - note: A note.
/// - index: The index to insert the note.
/// - isUndo: Whether the insert is undoing a deletion.
func insertExperimentNote(_ note: Note, atIndex index: Int?, isUndo: Bool) {
// Add to the end if no index is specified.
var insertedIndex: Int
if let index = index {
insertedIndex = index
} else {
insertedIndex = experiment.notes.endIndex
}
experiment.insertNote(note, atIndex: insertedIndex, isUndo: isUndo)
if let pictureNote = note as? PictureNote, let filePath = pictureNote.filePath {
metadataManager.updateCoverImageForAddedImageIfNeeded(imagePath: filePath,
experiment: experiment)
}
saveExperiment()
notifyListeners { (listener) in
listener.experimentUpdateExperimentNoteAdded(note, toExperiment: experiment)
}
}
/// Deletes a note from the experiment.
///
/// - Parameter noteID: A note ID.
func deleteExperimentNote(withID noteID: String) {
guard let (removedNote, removedIndex) = experiment.removeNote(withID: noteID) else {
return
}
// Attempt to delete an associated image if one exists.
let imagePath = (removedNote as? PictureNote)?.filePath
var coverImageUndo: (() -> Void)?
if let imagePath = imagePath {
experimentDataDeleter.performUndoableDeleteForAsset(atPath: imagePath,
experimentID: experiment.ID)
coverImageUndo =
metadataManager.updateCoverImageForRemovedImageIfNeeded(imagePath: imagePath,
experiment: experiment)
}
saveExperiment()
let undoBlock = {
self.insertExperimentNote(removedNote, atIndex: removedIndex, isUndo: true)
if let imagePath = imagePath {
self.experimentDataDeleter.restoreAsset(atPath: imagePath, experimentID: self.experiment.ID)
}
coverImageUndo?()
}
notifyListeners { (listener) in
listener.experimentUpdateExperimentNoteDeleted(removedNote,
experiment: self.experiment,
undoBlock: undoBlock)
}
}
/// Deletes a note from a trial.
///
/// - Parameters:
/// - noteID: A note ID.
/// - trialID: A trial ID.
func deleteTrialNote(withID noteID: String, trialID: String) {
guard let trial = experiment.trial(withID: trialID), let (removedNote, removedIndex) =
trial.removeNote(withID: noteID, experiment: experiment) else {
return
}
// Attempt to delete an associated image if one exists.
let imagePath = (removedNote as? PictureNote)?.filePath
var coverImageUndo: (() -> Void)?
if let imagePath = imagePath {
experimentDataDeleter.performUndoableDeleteForAsset(atPath: imagePath,
experimentID: experiment.ID)
coverImageUndo =
metadataManager.updateCoverImageForRemovedImageIfNeeded(imagePath: imagePath,
experiment: experiment)
}
saveExperiment()
let undoBlock = {
self.insertTrialNote(removedNote, trial: trial, atIndex: removedIndex, isUndo: true)
if let imagePath = imagePath {
self.experimentDataDeleter.restoreAsset(atPath: imagePath, experimentID: self.experiment.ID)
}
coverImageUndo?()
}
notifyListeners { (listener) in
listener.experimentUpdateTrialNoteDeleted(removedNote,
trial: trial,
experiment: experiment,
undoBlock: undoBlock)
}
}
/// Updates a note's caption. Text notes do not support captions so if `noteID` matches a text
/// note this method is a no-op.
///
/// - Parameters:
/// - captionString: The new caption string or nil to remove the caption.
/// - noteID: A note ID.
/// - trialID: A trial ID if the note belongs to a trial.
func updateNoteCaption(_ captionString: String?, forNoteWithID noteID: String, trialID: String?) {
let (note, trial) = noteWithID(noteID, trialID: trialID)
// Protect against adding captions to text notes.
guard let captionedNote = note, !(captionedNote is TextNote) else {
return
}
if let captionString = captionString {
captionedNote.caption = Caption(text: captionString)
} else {
captionedNote.caption = nil
}
experiment.noteCaptionUpdated(withID: noteID)
saveExperiment()
notifyListeners { (listener) in
listener.experimentUpdateNoteUpdated(captionedNote,
trial: trial,
experiment: experiment)
}
}
/// Updates a text note's text. If `noteID` matches a non-text note, this method is a no-op.
///
/// - Parameters:
/// - text: The new note text.
/// - noteID: A note ID.
/// - trialID: A trial ID if the note belongs to a trial.
func updateText(_ text: String, forNoteWithID noteID: String, trialID: String?) {
let (note, trial) = noteWithID(noteID, trialID: trialID)
// Only text notes have a text attribute.
guard let textNote = note as? TextNote else {
return
}
textNote.text = text
experiment.noteUpdated(withID: noteID)
saveExperiment()
notifyListeners { (listener) in
listener.experimentUpdateNoteUpdated(textNote, trial: trial, experiment: experiment)
}
}
/// Updates a trial's crop range, title or caption string. Passing nil for an attribute means it
/// will not be updated. To remove an attribute set an empty value.
///
/// - Parameters:
/// - cropRange: A new crop range, optional.
/// - trialName: A new trial title, optional.
/// - captionString: A new caption string, optional.
/// - trialID: A trial ID.
func updateTrial(cropRange: ChartAxis<Int64>?,
name trialName: String?,
captionString: String?,
forTrialID trialID: String) {
guard let trial = experiment.trial(withID: trialID) else {
return
}
var saveNeeded = false
if let cropRange = cropRange {
trial.cropRange = cropRange
trial.trialStats.forEach { $0.status = .needsUpdate }
sensorDataManager.recalculateStatsForTrial(trial, experimentID: experiment.ID)
saveNeeded = true
}
if let trialName = trialName {
trial.setTitle(trialName, experiment: experiment)
saveNeeded = true
}
if let captionString = captionString {
trial.caption = Caption(text: captionString)
saveNeeded = true
}
guard saveNeeded else {
return
}
experiment.trialUpdated(withID: trialID)
saveExperiment()
notifyListeners { (listener) in
listener.experimentUpdateTrialUpdated(trial, experiment: experiment, updatedStats: false)
}
}
/// Adds a trial to the experiment.
///
/// - Parameters:
/// - trial: A trial.
/// - isRecording: Whether the trial is actively recording data.
func addTrial(_ trial: Trial, recording isRecording: Bool) {
addTrial(trial, recording: isRecording, isUndo: false)
}
/// Deletes a trial from the experiment. This method does not remove a trial's sensor data in case
/// the user undoes the delete.
///
/// - Parameter trialID: A trial ID.
func deleteTrial(withID trialID: String) {
guard let trial = experiment.removeTrial(withID: trialID) else {
return
}
experimentDataDeleter.performUndoableDeleteForAssets(atPaths: trial.allImagePaths,
experimentID: experiment.ID)
let coverImageUndo =
metadataManager.updateCoverImageForRemovedImagesIfNeeded(imagePaths: trial.allImagePaths,
experiment: experiment)
saveExperiment()
let undoBlock = {
self.addTrial(trial, recording: false, isUndo: true)
self.experimentDataDeleter.restoreAssets(atPaths: trial.allImagePaths,
experimentID: self.experiment.ID)
coverImageUndo?()
}
notifyListeners { (listener) in
listener.experimentUpdateTrialDeleted(trial, fromExperiment: experiment, undoBlock: undoBlock)
}
}
/// Confirms a trial should be deleted and will not be undone. This should be called after a trial
/// has been deleted and the user declined to perform an undo.
///
/// - Parameter trial: The deleted trial.
func confirmTrialDeletion(for trial: Trial) {
sensorDataManager.removeData(forTrialID: trial.ID)
experimentDataDeleter.confirmDeleteAssets(atPaths: trial.allImagePaths,
experimentID: experiment.ID)
}
/// Permanently deletes a trial and its associated data. Cannot be undone.
///
/// - Parameter trialID: The ID of the trail to delete.
func permanentlyDeleteTrial(withID trialID: String) {
guard let trial = experiment.removeTrial(withID: trialID) else {
return
}
experimentDataDeleter.permanentlyDeleteAssets(atPaths: trial.allImagePaths,
experimentID: experiment.ID)
_ = metadataManager.updateCoverImageForRemovedImagesIfNeeded(imagePaths: trial.allImagePaths,
experiment: experiment)
sensorDataManager.removeData(forTrialID: trial.ID)
saveExperiment()
notifyListeners { (listener) in
listener.experimentUpdateTrialDeleted(trial, fromExperiment: experiment, undoBlock: nil)
}
}
/// Toggles the archive state of an experiment.
///
/// - Parameter trialID: A trial ID.
func toggleArchivedState(forTrialID trialID: String) {
guard let trial = experiment.trials.first(where: { $0.ID == trialID }) else {
return
}
trial.isArchived.toggle()
experiment.trialUpdated(withID: trialID)
saveExperiment()
let undoBlock = {
self.toggleArchivedState(forTrialID: trialID)
}
notifyListeners { (listener) in
listener.experimentUpdateTrialArchiveStateChanged(trial,
experiment: experiment,
undoBlock: undoBlock)
}
}
/// Notifies the experiment update manager the experiment was changed externally and should
/// be saved.
func recordingTrialChangedExternally(_ recordingTrial: Trial) {
if let existingIndex = experiment.trials.firstIndex(where: { $0.ID == recordingTrial.ID }) {
experiment.trials[existingIndex] = recordingTrial
saveExperiment()
}
}
/// Handles experiment changes that weren't triggered through the ExperimentUpdateManager.
/// This can happen with a drive sync while an experiment is open.
/// - Parameter trialID: ID of trial that was deleted.
/// - Parameter experimentID: experimentID of experiment from which the trial was deleted.
func experimentTrialDeletedExternally(trialID: String, experimentID: String) {
guard experimentID == experiment.ID else {
return
}
guard let trial = experiment.trial(withID: trialID) else {
return
}
notifyListeners { (listener) in
listener.experimentUpdateTrialDeleted(trial, fromExperiment: experiment, undoBlock: nil)
}
}
// MARK: - Private
/// Adds a trial to the experiment.
///
/// - Parameters:
/// - trial: A trial.
/// - isRecording: Whether the trial is actively recording data.
/// - isUndo: Whether the add is undoing a deletion.
private func addTrial(_ trial: Trial, recording isRecording: Bool, isUndo: Bool) {
// Recording trials are new, so update the stored trial indexes.
if isRecording {
experiment.totalTrials += 1
trial.trialNumberInExperiment = experiment.totalTrials
}
experiment.addTrial(trial, isUndo: isUndo)
saveExperiment()
notifyListeners { (listener) in
listener.experimentUpdateTrialAdded(trial, toExperiment: experiment, recording: isRecording)
}
}
/// Notifies all listeners by calling the given block on each valid listener.
///
/// - Parameter block: A block with a listener parameter.
private func notifyListeners(_ block: (ExperimentUpdateListener) -> Void) {
updateListeners.allObjects.forEach { (object) in
guard let listener = object as? ExperimentUpdateListener else { return }
block(listener)
}
}
/// Returns the note with the given ID. Searches trial notes if a trial ID is given.
///
/// - Parameters:
/// - noteID: A note ID.
/// - trialID: A trial ID.
/// - Returns: A tuple containing an optional note and an optional trial.
private func noteWithID(_ noteID: String, trialID: String?) -> (Note?, Trial?) {
var foundNote: Note?
var foundTrial: Trial?
if let trialID = trialID {
if let trial = experiment.trial(withID: trialID),
let note = trial.note(withID: noteID) {
foundNote = note
foundTrial = trial
}
} else {
if let note = experiment.note(withID: noteID) {
foundNote = note
}
}
return (foundNote, foundTrial)
}
/// Saves the experiment.
private func saveExperiment() {
metadataManager.saveExperiment(experiment)
delegate?.experimentUpdateManagerDidSaveExperiment(withID: experiment.ID)
}
// MARK: - Notifications
@objc private func handleTrialStatsDidCompleteNotification(notification: Notification) {
guard let trialID =
notification.userInfo?[SensorDataManager.TrialStatsDidCompleteTrialIDKey] as? String,
let trial = experiment.trial(withID: trialID) else {
return
}
saveExperiment()
notifyListeners { (listener) in
listener.experimentUpdateTrialUpdated(trial, experiment: experiment, updatedStats: true)
}
}
}
| apache-2.0 | 5cfbf5870b9e9212f5e9b51e613750f6 | 34.859736 | 100 | 0.653168 | 4.798189 | false | false | false | false |
GEOSwift/GEOSwift | Sources/GEOSwift/GEOS/LineStringConvertible+GEOS.swift | 1 | 2422 | import geos
public extension LineStringConvertible {
// MARK: - Linear Referencing Functions
/// - returns: The distance of a point projected on the calling line
func distanceFromStart(toProjectionOf point: Point) throws -> Double {
let context = try GEOSContext()
let lineStringGeosObject = try lineString.geosObject(with: context)
let pointGeosObject = try point.geosObject(with: context)
// returns -1 on exception
let result = GEOSProject_r(context.handle, lineStringGeosObject.pointer, pointGeosObject.pointer)
guard result != -1 else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return result
}
func normalizedDistanceFromStart(toProjectionOf point: Point) throws -> Double {
let context = try GEOSContext()
let lineStringGeosObject = try lineString.geosObject(with: context)
let pointGeosObject = try point.geosObject(with: context)
// returns -1 on exception
let result = GEOSProjectNormalized_r(context.handle, lineStringGeosObject.pointer, pointGeosObject.pointer)
guard result != -1 else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return result
}
/// If distance is negative, the interpolation starts from the end and works backwards
func interpolatedPoint(withDistance distance: Double) throws -> Point {
let context = try GEOSContext()
let lineStringGeosObject = try lineString.geosObject(with: context)
guard let pointer = GEOSInterpolate_r(context.handle, lineStringGeosObject.pointer, distance) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return try Point(geosObject: GEOSObject(context: context, pointer: pointer))
}
/// If fraction is negative, the interpolation starts from the end and works backwards
func interpolatedPoint(withFraction fraction: Double) throws -> Point {
let context = try GEOSContext()
let lineStringGeosObject = try lineString.geosObject(with: context)
guard let pointer = GEOSInterpolateNormalized_r(context.handle, lineStringGeosObject.pointer, fraction) else {
throw GEOSError.libraryError(errorMessages: context.errors)
}
return try Point(geosObject: GEOSObject(context: context, pointer: pointer))
}
}
| mit | 468d2cc49d7df93b2bd34ca1d1b7a309 | 46.490196 | 118 | 0.702312 | 5.014493 | false | false | false | false |
GreenCom-Networks/ios-charts | Charts/Classes/Renderers/ChartYAxisRenderer.swift | 1 | 18069 | //
// ChartYAxisRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class ChartYAxisRenderer: ChartAxisRendererBase
{
public var yAxis: ChartYAxis?
public init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer)
self.yAxis = yAxis
}
/// Computes the axis values.
public func computeAxis(yMin yMin: Double, yMax: Double)
{
guard let yAxis = yAxis else { return }
var yMin = yMin, yMax = yMax
// calculate the starting and entry point of the y-labels (depending on
// zoom / contentrect bounds)
if (viewPortHandler.contentWidth > 10.0 && !viewPortHandler.isFullyZoomedOutY)
{
let p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
let p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
if (!yAxis.isInverted)
{
yMin = Double(p2.y)
yMax = Double(p1.y)
}
else
{
yMin = Double(p1.y)
yMax = Double(p2.y)
}
}
computeAxisValues(min: yMin, max: yMax)
}
/// Sets up the y-axis labels. Computes the desired number of labels between
/// the two given extremes. Unlike the papareXLabels() method, this method
/// needs to be called upon every refresh of the view.
public func computeAxisValues(min min: Double, max: Double)
{
guard let yAxis = yAxis else { return }
let yMin = min
let yMax = max
let labelCount = yAxis.labelCount
let range = abs(yMax - yMin)
if (labelCount == 0 || range <= 0)
{
yAxis.entries = [Double]()
return
}
// Find out how much spacing (in y value space) between axis values
let rawInterval = range / Double(labelCount)
var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval))
// If granularity is enabled, then do not allow the interval to go below specified granularity.
// This is used to avoid repeated values when rounding values for display.
if yAxis.granularityEnabled
{
interval = interval < yAxis.granularity ? yAxis.granularity : interval
}
// Normalize interval
let intervalMagnitude = ChartUtils.roundToNextSignificant(number: pow(10.0, floor(log10(interval))))
let intervalSigDigit = (interval / intervalMagnitude)
if (intervalSigDigit > 5)
{
// Use one order of magnitude higher, to avoid intervals like 0.9 or 90
interval = floor(10.0 * intervalMagnitude)
}
// force label count
if yAxis.isForceLabelsEnabled
{
let step = Double(range) / Double(labelCount - 1)
if yAxis.entries.count < labelCount
{
// Ensure stops contains at least numStops elements.
yAxis.entries.removeAll(keepCapacity: true)
}
else
{
yAxis.entries = [Double]()
yAxis.entries.reserveCapacity(labelCount)
}
var v = yMin
for _ in 0 ..< labelCount
{
yAxis.entries.append(v)
v += step
}
}
else
{
// no forced count
// if the labels should only show min and max
if (yAxis.isShowOnlyMinMaxEnabled)
{
yAxis.entries = [yMin, yMax]
}
else
{
let first = ceil(Double(yMin) / interval) * interval
let last = ChartUtils.nextUp(floor(Double(yMax) / interval) * interval)
var n = 0
for _ in first.stride(through: last, by: interval)
{
n += 1
}
if (yAxis.entries.count < n)
{
// Ensure stops contains at least numStops elements.
yAxis.entries = [Double](count: n, repeatedValue: 0.0)
}
else if (yAxis.entries.count > n)
{
yAxis.entries.removeRange(n..<yAxis.entries.count)
}
var f = first
var i = 0
while (i < n)
{
if (f == 0.0)
{ // Fix for IEEE negative zero case (Where value == -0.0, and 0.0 == -0.0)
f = 0.0
}
yAxis.entries[i] = Double(f)
f += interval
i += 1
}
}
}
}
/// draws the y-axis labels to the screen
public override func renderAxisLabels(context context: CGContext)
{
guard let yAxis = yAxis else { return }
if (!yAxis.isEnabled || !yAxis.isDrawLabelsEnabled)
{
return
}
let xoffset = yAxis.xOffset
let yoffset = yAxis.labelFont.lineHeight / 2.5 + yAxis.yOffset
let dependency = yAxis.axisDependency
let labelPosition = yAxis.labelPosition
var xPos = CGFloat(0.0)
var textAlign: NSTextAlignment
if (dependency == .Left)
{
if (labelPosition == .OutsideChart)
{
textAlign = .Right
xPos = viewPortHandler.offsetLeft - xoffset
}
else
{
textAlign = .Left
xPos = viewPortHandler.offsetLeft + xoffset
}
}
else
{
if (labelPosition == .OutsideChart)
{
textAlign = .Left
xPos = viewPortHandler.contentRight + xoffset
}
else
{
textAlign = .Right
xPos = viewPortHandler.contentRight - xoffset
}
}
drawYLabels(context: context, fixedPosition: xPos, offset: yoffset - yAxis.labelFont.lineHeight, textAlign: textAlign)
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderAxisLine(context context: CGContext)
{
guard let yAxis = yAxis else { return }
if (!yAxis.isEnabled || !yAxis.drawAxisLineEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, yAxis.axisLineColor.CGColor)
CGContextSetLineWidth(context, yAxis.axisLineWidth)
if (yAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, yAxis.axisLineDashPhase, yAxis.axisLineDashLengths, yAxis.axisLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
if (yAxis.axisDependency == .Left)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
else
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
CGContextRestoreGState(context)
}
/// draws the y-labels on the specified x-position
internal func drawYLabels(context context: CGContext, fixedPosition: CGFloat, offset: CGFloat, textAlign: NSTextAlignment)
{
guard let yAxis = yAxis else { return }
let labelFont = yAxis.labelFont
let labelTextColor = yAxis.labelTextColor
let valueToPixelMatrix = transformer.valueToPixelMatrix
var pt = CGPoint()
for i in 0 ..< yAxis.entryCount
{
let text = yAxis.getFormattedLabel(i)
if (!yAxis.isDrawTopYLabelEntryEnabled && i >= yAxis.entryCount - 1)
{
break
}
pt.x = 0
pt.y = CGFloat(yAxis.entries[i])
pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix)
pt.x = fixedPosition
pt.y += offset
ChartUtils.drawText(context: context, text: text, point: pt, align: textAlign, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
}
}
private var _gridLineBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderGridLines(context context: CGContext)
{
guard let yAxis = yAxis else { return }
if !yAxis.isEnabled
{
return
}
if yAxis.drawGridLinesEnabled
{
CGContextSaveGState(context)
CGContextSetShouldAntialias(context, yAxis.gridAntialiasEnabled)
CGContextSetStrokeColorWithColor(context, yAxis.gridColor.CGColor)
CGContextSetLineWidth(context, yAxis.gridLineWidth)
CGContextSetLineCap(context, yAxis.gridLineCap)
if (yAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, yAxis.gridLineDashPhase, yAxis.gridLineDashLengths, yAxis.gridLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
// draw the horizontal grid
for i in 0 ..< yAxis.entryCount
{
position.x = 0.0
position.y = CGFloat(yAxis.entries[i])
position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
_gridLineBuffer[0].x = viewPortHandler.contentLeft
_gridLineBuffer[0].y = position.y
_gridLineBuffer[1].x = viewPortHandler.contentRight
_gridLineBuffer[1].y = position.y
CGContextStrokeLineSegments(context, _gridLineBuffer, 2)
}
CGContextRestoreGState(context)
}
if yAxis.drawZeroLineEnabled
{
// draw zero line
var position = CGPoint(x: 0.0, y: 0.0)
transformer.pointValueToPixel(&position)
drawZeroLine(context: context,
x1: viewPortHandler.contentLeft,
x2: viewPortHandler.contentRight,
y1: position.y,
y2: position.y);
}
}
/// Draws the zero line at the specified position.
public func drawZeroLine(
context context: CGContext,
x1: CGFloat,
x2: CGFloat,
y1: CGFloat,
y2: CGFloat)
{
guard let
yAxis = yAxis,
zeroLineColor = yAxis.zeroLineColor
else { return }
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, zeroLineColor.CGColor)
CGContextSetLineWidth(context, yAxis.zeroLineWidth)
if (yAxis.zeroLineDashLengths != nil)
{
CGContextSetLineDash(context, yAxis.zeroLineDashPhase, yAxis.zeroLineDashLengths!, yAxis.zeroLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextMoveToPoint(context, x1, y1)
CGContextAddLineToPoint(context, x2, y2)
CGContextDrawPath(context, CGPathDrawingMode.Stroke)
CGContextRestoreGState(context)
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderLimitLines(context context: CGContext)
{
guard let yAxis = yAxis else { return }
var limitLines = yAxis.limitLines
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
position.x = 0.0
position.y = CGFloat(l.limit)
position = CGPointApplyAffineTransform(position, trans)
_limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_limitLineSegmentsBuffer[0].y = position.y
_limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_limitLineSegmentsBuffer[1].y = position.y
if !l.filled {
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor)
CGContextSetLineWidth(context, l.lineWidth)
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2)
} else {
let zeroLine = CGPointApplyAffineTransform(CGPoint(x: 0.0,y: 0.0), trans)
let rect = CGRectMake(viewPortHandler.contentLeft, position.y, viewPortHandler.contentRight, zeroLine.y)
CGContextSetFillColorWithColor(context, l.lineColor.CGColor)
CGContextFillRect(context, rect)
}
let label = l.label
// if drawing the limit-value label is enabled
if (label.characters.count > 0)
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset: CGFloat = 4.0 + l.xOffset
let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset
switch l.labelPosition {
case .RightTop:
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
break
case .RightBottom:
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
break
case .LeftTop:
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
break
default:
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
break
}
}
}
CGContextRestoreGState(context)
}
} | apache-2.0 | 729eeeb6b2cf5ff6dc66d1ae09fb65a9 | 34.431373 | 184 | 0.51652 | 5.961399 | false | false | false | false |
SuPair/VPNOn | TodayWidget/VPNTypeTag.swift | 1 | 2300 | //
// VPNTypeTag.swift
// VPNOn
//
// Created by Lex Tang on 1/28/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
enum VPNType {
case IKEv1, IKEv2
func simpleDescription() -> String {
switch self {
case IKEv2:
return "IKEv2"
default:
return "IKEv1"
}
}
}
class VPNTypeTag: UIVisualEffectView
{
var type: VPNType = .IKEv1
override func willMoveToSuperview(newSuperview: UIView?) {
backgroundColor = UIColor.clearColor()
}
override func drawRect(rect: CGRect) {
drawIKEv2Tag(radius: 3, rect: CGRectInset(rect, 1, 1), tagText: type.simpleDescription(), color: UIColor.whiteColor())
}
func drawIKEv2Tag(radius radius: CGFloat, rect: CGRect, tagText: String, color: UIColor) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Variable Declarations
let height: CGFloat = rect.size.height / 1.20
//// Rectangle Drawing
let rectanglePath = UIBezierPath(roundedRect: rect, cornerRadius: radius)
color.setStroke()
rectanglePath.lineWidth = 1
rectanglePath.stroke()
//// Text Drawing
let textRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.Center
let textFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(height - 1), NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: textStyle]
let textTextHeight: CGFloat = NSString(string: tagText).boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, textRect);
NSString(string: tagText).drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
CGContextRestoreGState(context)
}
}
| mit | 9f626f054d31c5ec3db0a9b507487d34 | 36.096774 | 244 | 0.677391 | 4.925054 | false | false | false | false |
luinily/hOme | hOme/Scenes/CreateDevice/CreateDeviceConfigurator.swift | 1 | 1357 | //
// CreateDeviceConfigurator.swift
// hOme
//
// Created by Coldefy Yoann on 2016/05/21.
// Copyright (c) 2016年 YoannColdefy. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
// MARK: Connect View, Interactor, and Presenter
extension CreateDeviceViewController: CreateDevicePresenterOutput {
func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
router.passDataToNextScene(segue)
}
}
extension CreateDeviceInteractor: CreateDeviceViewControllerOutput {
}
extension CreateDevicePresenter: CreateDeviceInteractorOutput {
}
class CreateDeviceConfigurator {
// MARK: Object lifecycle
class var sharedInstance: CreateDeviceConfigurator {
struct Static {
static var instance = CreateDeviceConfigurator()
static var token: Int = 0
}
return Static.instance
}
// MARK: Configuration
func configure(_ viewController: CreateDeviceViewController) {
let router = CreateDeviceRouter()
router.viewController = viewController
let presenter = CreateDevicePresenter()
presenter.output = viewController
let interactor = CreateDeviceInteractor()
interactor.output = presenter
viewController.output = interactor
viewController.router = router
}
}
| mit | 0e6fc71777b3875cc53949f28113ad93 | 23.196429 | 79 | 0.764576 | 4.301587 | false | true | false | false |
LuAndreCast/iOS_WatchProjects | watchOS2/PrimeNumbers/PrimeNumbers WatchKit Extension/InterfaceController.swift | 1 | 2202 | //
// InterfaceController.swift
// PrimeNumbers WatchKit Extension
//
// Created by Luis Castillo on 1/6/16.
// Copyright © 2016 Luis Castillo. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet var numberSlider: WKInterfaceSlider!
@IBOutlet var primeQLabel: WKInterfaceLabel!
@IBOutlet var Updatebutton: WKInterfaceButton!
@IBOutlet var resultLabel: WKInterfaceLabel!
var number:Int = 50
override func awakeWithContext(context: AnyObject?)
{
super.awakeWithContext(context)
numberSlider.setValue( Float(number) )
primeQLabel.setText("is \(number) prime?")
resultLabel.setText("")
}//eom
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}//eom
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}//eom
@IBAction func sliderValueChanged(value: Float)
{
number = Int(value)
//setting up new question
primeQLabel.setText("is \(number) Prime?")
//clearing results since its a new Question
resultLabel.setText("")
}//eo-a
@IBAction func findOut()
{
//checking if prime
var isPrime:Bool = true
if number == 1 || number == 0
{
isPrime = false
}
if number != 2 && number != 1
{
for (var iter = 2; iter < number ;iter++)
{
if number % iter == 0
{
isPrime = false
}
}//eofl
}
//print("is prime? \(isPrime)")//testing
//update result
if isPrime
{
resultLabel.setText("\(number) is Prime")
}
else
{
resultLabel.setText("\(number) is NOT Prime")
}
}//eo-a
}
| mit | eecb1f6525fcb433bef5c00e6dad0ba9 | 20.578431 | 90 | 0.529305 | 5.26555 | false | false | false | false |
iCrany/iOSExample | iOSExample/Module/TransitionExample/ViewController/Session2/BouncePresentAnimation.swift | 1 | 1818 | //
// BouncePresentAnimation.swift
// iOSExample
//
// Created by iCrany on 2017/6/3.
// Copyright (c) 2017 iCrany. All rights reserved.
//
import Foundation
class BouncePresentAnimation: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.8
}
// This method can only be a nop if the transition is interactive and not a percentDriven interactive transition.
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// Get controllers from transition context
let toVCTemp: UIViewController? = transitionContext.viewController(forKey: .to)
guard let toVC = toVCTemp else {
return
}
// Set init frame for toVC
let screenBounds: CGRect = UIScreen.main.bounds
let finalFrame: CGRect = transitionContext.finalFrame(for: toVC)
toVC.view.frame = finalFrame.offsetBy(dx: 0, dy: screenBounds.size.height)
// Add toVC.view to containerView
let containerView: UIView = transitionContext.containerView
containerView.addSubview(toVC.view)
// Do animate now
let duration: TimeInterval = self.transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration,
delay: 0.0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.0,
animations: {
toVC.view.frame = finalFrame
},
completion: {(_: Bool) -> Void in
// Tell Context if we complete success
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
| mit | 2e6808128b42c50c375428e816741d29 | 35.36 | 118 | 0.653465 | 5.525836 | false | false | false | false |
cooliean/CLLKit | XLForm/Examples/Swift/SwiftExample/CustomRows/Rating/XLFormRatingCell.swift | 14 | 2067 | // XLFormRatingCell.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
let XLFormRowDescriptorTypeRate = "XLFormRowDescriptorTypeRate"
class XLFormRatingCell : XLFormBaseCell {
@IBOutlet weak var rateTitle: UILabel!
@IBOutlet weak var ratingView: XLRatingView!
override func configure() {
super.configure()
selectionStyle = .None
ratingView.addTarget(self, action: "rateChanged:", forControlEvents:.ValueChanged)
}
override func update() {
super.update()
ratingView.value = rowDescriptor!.value!.floatValue
rateTitle.text = rowDescriptor!.title
ratingView.alpha = rowDescriptor!.isDisabled() ? 0.6 : 1
rateTitle.alpha = rowDescriptor!.isDisabled() ? 0.6 : 1
}
//MARK: Events
func rateChanged(ratingView : XLRatingView){
rowDescriptor!.value = ratingView.value
}
}
| mit | a8739eff813a774fe174af50d424d1b9 | 35.910714 | 90 | 0.711176 | 4.624161 | false | false | false | false |
february29/Learning | swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Producer.swift | 163 | 3171 | //
// Producer.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/20/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
class Producer<Element> : Observable<Element> {
override init() {
super.init()
}
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
if !CurrentThreadScheduler.isScheduleRequired {
// The returned disposable needs to release all references once it was disposed.
let disposer = SinkDisposer()
let sinkAndSubscription = run(observer, cancel: disposer)
disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription)
return disposer
}
else {
return CurrentThreadScheduler.instance.schedule(()) { _ in
let disposer = SinkDisposer()
let sinkAndSubscription = self.run(observer, cancel: disposer)
disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription)
return disposer
}
}
}
func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
rxAbstractMethod()
}
}
fileprivate final class SinkDisposer: Cancelable {
fileprivate enum DisposeState: UInt32 {
case disposed = 1
case sinkAndSubscriptionSet = 2
}
// Jeej, swift API consistency rules
fileprivate enum DisposeStateInt32: Int32 {
case disposed = 1
case sinkAndSubscriptionSet = 2
}
private var _state: AtomicInt = 0
private var _sink: Disposable? = nil
private var _subscription: Disposable? = nil
var isDisposed: Bool {
return AtomicFlagSet(DisposeState.disposed.rawValue, &_state)
}
func setSinkAndSubscription(sink: Disposable, subscription: Disposable) {
_sink = sink
_subscription = subscription
let previousState = AtomicOr(DisposeState.sinkAndSubscriptionSet.rawValue, &_state)
if (previousState & DisposeStateInt32.sinkAndSubscriptionSet.rawValue) != 0 {
rxFatalError("Sink and subscription were already set")
}
if (previousState & DisposeStateInt32.disposed.rawValue) != 0 {
sink.dispose()
subscription.dispose()
_sink = nil
_subscription = nil
}
}
func dispose() {
let previousState = AtomicOr(DisposeState.disposed.rawValue, &_state)
if (previousState & DisposeStateInt32.disposed.rawValue) != 0 {
return
}
if (previousState & DisposeStateInt32.sinkAndSubscriptionSet.rawValue) != 0 {
guard let sink = _sink else {
rxFatalError("Sink not set")
}
guard let subscription = _subscription else {
rxFatalError("Subscription not set")
}
sink.dispose()
subscription.dispose()
_sink = nil
_subscription = nil
}
}
}
| mit | bae8dde291fe9452fdc4c448a78f0a87 | 31.346939 | 136 | 0.617035 | 5.205255 | false | false | false | false |
evilBird/music-notation-swift | MusicNotationKit/MusicNotationKit/Note.swift | 1 | 1048 | //
// Note.swift
// MusicNotation
//
// Created by Kyle Sherman on 6/12/15.
// Copyright (c) 2015 Kyle Sherman. All rights reserved.
//
public struct Note {
public let noteDuration: NoteDuration
public let tones: [Tone]
public let isRest: Bool
public var dot: Dot?
public var accent: Accent?
public var isStaccato: Bool = false
public var dynamics: Dynamics?
public var striking: Striking?
internal var tie: Tie?
/**
Initialize a rest.
*/
public init(noteDuration: NoteDuration) {
self.noteDuration = noteDuration
self.tones = []
self.isRest = true
}
/**
Initialize a note with a single tone.
*/
public init(noteDuration: NoteDuration, tone: Tone) {
self.noteDuration = noteDuration
self.tones = [tone]
self.isRest = false
}
/**
Initialize a note with multiple tones (chord).
*/
public init(noteDuration: NoteDuration, tones: [Tone]) {
isRest = false
self.noteDuration = noteDuration
self.tones = tones
}
}
extension Note: NoteCollection {
internal var noteCount: Int { return 1 }
}
| mit | 623cd839b20d92bc04e0ac21b17252b7 | 18.054545 | 57 | 0.692748 | 3.254658 | false | false | false | false |
evgenyneu/SigmaSwiftStatistics | SigmaSwiftStatisticsTests/CovarianceTests.swift | 1 | 1491 | import XCTest
import SigmaSwiftStatistics
class CovarianceTests: XCTestCase {
// MARK: - Sample covariance
func testSampleCovariance() {
let x = [1, 2, 3.5, 3.7, 8, 12]
let y = [0.5, 1, 2.1, 3.4, 3.4, 4]
let result = Sigma.covarianceSample(x: x, y: y)!
XCTAssertEqual(5.03, Helpers.round10(result))
}
func testSampleCovariance_unequalSamples() {
let x = [1, 2, 3.5, 3.7, 8, 12]
let y = [0.5, 4]
let result = Sigma.covarianceSample(x: x, y: y)
XCTAssert(result == nil)
}
func testSampleCovariance_whenGivenSingleSetOfValues() {
let x = [1.2]
let y = [0.5]
let result = Sigma.covarianceSample(x: x, y: y)
XCTAssert(result == nil)
}
func testSampleCovariance_samplesAreEmpty() {
let result = Sigma.covarianceSample(x: [], y: [])
XCTAssert(result == nil)
}
// MARK: - Population covariance
func testPopulationCovariance() {
let x = [1, 2, 3.5, 3.7, 8, 12]
let y = [0.5, 1, 2.1, 3.4, 3.4, 4]
let result = Sigma.covariancePopulation(x: x, y: y)!
XCTAssertEqual(4.1916666667, Helpers.round10(result))
}
func testPopulationCovariance_unequalSamples() {
let x = [1, 2, 3.5, 3.7, 8, 12]
let y = [0.5]
let result = Sigma.covariancePopulation(x: x, y: y)
XCTAssert(result == nil)
}
func testPopulationCovariance_emptySamples() {
let result = Sigma.covariancePopulation(x: [], y: [])
XCTAssert(result == nil)
}
}
| mit | 229ddd0be0a3d4f22ca88eb3d167eced | 23.442623 | 58 | 0.600939 | 3.093361 | false | true | false | false |
hallelujahbaby/CFNotify | CFNotify/Notifier.swift | 1 | 13690 | //
// Messager.swift
// CFNotify
//
// Created by Johnny on 12/11/2016.
// Copyright © 2016 Johnny Choi@Co-Fire. All rights reserved.
//
import UIKit
class Notifier: NSObject, UIGestureRecognizerDelegate {
let config: CFNotify.Config
let view: UIView
let containerView: UIView
let panRecognizer: UIPanGestureRecognizer
let tapRecognizer: UITapGestureRecognizer
var animator: UIDynamicAnimator
var snapPoint: CGPoint
var snapBehaviour : UISnapBehavior!
var attachmentBehaviour : UIAttachmentBehavior!
var gravityBehaviour : UIGravityBehavior!
var collisionBehaviour : UICollisionBehavior!
var isHidding: Bool
weak var delegate: NotifierDelegate?
var fieldMargin: CGFloat //Margin to remove message from view
var angularVelocity: CGFloat = 0
let tapAction: (()->Void)?
init(config: CFNotify.Config, view: UIView, tapHandler: (()->Void)?, delegate: NotifierDelegate) {
self.config = config
self.view = view
self.containerView = UIView()
self.panRecognizer = UIPanGestureRecognizer()
self.tapRecognizer = UITapGestureRecognizer()
self.animator = UIDynamicAnimator()
self.snapPoint = CGPoint.zero
self.isHidding = false
self.delegate = delegate
self.fieldMargin = (view.bounds.width > view.bounds.height) ? view.bounds.width : view.bounds.height
self.tapAction = tapHandler
super.init()
self.panRecognizer.addTarget(self, action: #selector(Notifier.pan(gesture:)))
self.panRecognizer.maximumNumberOfTouches = 1
self.tapRecognizer.addTarget(self, action: #selector(Notifier.tap(gesture:)))
}
var hideTime: TimeInterval? {
let duration: TimeInterval?
switch self.config.hideTime {
case .default:
duration = 3.0
case .never:
duration = nil
case .custom(let seconds):
duration = seconds
}
return duration
}
func present(completion: @escaping (_ completed: Bool) -> Void){
guard let appDelegate = UIApplication.shared.delegate else { return }
guard let keyWindow = appDelegate.window! else { return }
self.animator = UIDynamicAnimator(referenceView: keyWindow)
let initPoint: CGPoint
switch self.config.initPosition {
case .top(let position):
switch position {
case .center:
initPoint = CGPoint(keyWindow.bounds.midX, 0 - self.view.bounds.height)
case .left:
initPoint = CGPoint(0 - self.view.bounds.width, 0 - self.view.bounds.height)
case .right:
initPoint = CGPoint(keyWindow.bounds.width, 0 - self.view.bounds.height)
case .random:
initPoint = CGPoint(randomBetweenNumbers(firstNum: 0 - self.view.bounds.width, secondNum: keyWindow.bounds.width + self.view.bounds.width), 0 - self.view.bounds.height)
}
case .bottom(let position):
switch position {
case .center:
initPoint = CGPoint(keyWindow.bounds.midX, keyWindow.bounds.height)
case .left:
initPoint = CGPoint(0 - self.view.bounds.width, keyWindow.bounds.height)
case .right:
initPoint = CGPoint(keyWindow.bounds.width, keyWindow.bounds.height)
case .random:
initPoint = CGPoint(randomBetweenNumbers(firstNum: 0 - self.view.bounds.width, secondNum: keyWindow.bounds.width + self.view.bounds.width), keyWindow.bounds.height)
}
case .left:
initPoint = CGPoint(0 - self.view.bounds.width, keyWindow.bounds.midY)
case .right:
initPoint = CGPoint(keyWindow.bounds.width, keyWindow.bounds.midY)
case .custom(let point):
initPoint = point
}
self.view.frame.origin = CGPoint.zero
self.containerView.frame.origin = initPoint
self.containerView.bounds = self.view.bounds
self.containerView.backgroundColor = UIColor.clear
self.containerView.addSubview(self.view)
self.containerView.bringSubviewToFront(self.view)
self.containerView.addGestureRecognizer(self.panRecognizer)
if self.tapAction == nil {
self.containerView.addGestureRecognizer(self.tapRecognizer)
}
keyWindow.addSubview(self.containerView)
if let delegate = self.delegate {
delegate.notifierDidAppear()
}
switch self.config.appearPosition {
case .bottom:
self.snapPoint = CGPoint(x: keyWindow.bounds.midX, y: keyWindow.bounds.bottom - 50 - self.containerView.bounds.midY)
case .center:
self.snapPoint = keyWindow.bounds.center
case .top:
self.snapPoint = CGPoint(x: keyWindow.bounds.midX, y: 70 + self.containerView.bounds.height/2)
case .custom(let point):
self.snapPoint = point
}
self.addSnap(view: self.containerView, toPoint: self.snapPoint) { (completed) in
completion(completed)
}
}
func hide() {
self.animator.removeAllBehaviors()
if let gestureViewGestureRecognizers = self.containerView.gestureRecognizers {
for gestureRecongnizers in gestureViewGestureRecognizers {
self.containerView.removeGestureRecognizer(gestureRecongnizers)
}
}
self.gravityBehaviour = UIGravityBehavior(items: [self.containerView])
self.gravityBehaviour.action = { [weak self] in
guard let strongSelf = self else { return }
strongSelf.removeFromSuperView(completion: { (completed) in
if let delegate = strongSelf.delegate, completed {
delegate.notifierDidDisappear(notifier: strongSelf)
}
})
}
self.animator.addBehavior(self.gravityBehaviour)
}
func removeFromSuperView(completion: @escaping (_ completed: Bool) -> Void) {
if self.containerView.superview != nil {
//TOP
if containerView.frame.top >= (containerView.superview!.bounds.bottom + fieldMargin) {
self.containerView.removeFromSuperview()
completion(true)
}
//BOTTOM
else if (containerView.frame.bottom) <= (containerView.superview!.bounds.top - fieldMargin) {
self.containerView.removeFromSuperview()
completion(true)
}
//RIGHT
else if (containerView.frame.right) <= (containerView.superview!.bounds.left - fieldMargin) {
self.containerView.removeFromSuperview()
completion(true)
}
//LEFT
else if containerView.frame.left >= (containerView.superview!.bounds.right + fieldMargin) {
self.containerView.removeFromSuperview()
completion(true)
}
else {
self.isHidding = true
completion(false)
}
}
}
func addSnap(view: UIView, toPoint: CGPoint, completion: ((_ completed: Bool) -> Void)? = nil) {
var counter = 0
snapBehaviour = UISnapBehavior(item: view, snapTo: toPoint)
snapBehaviour.damping = self.config.snapDamping
snapBehaviour.action = {
// Check if the view reach the snap point
if self.distance(from: view.center, to: toPoint) < 1 && counter == 0 {
counter += 1
if let completion = completion {
completion(true)
}
} else {
if let completion = completion {
completion(false)
}
}
}
self.animator.addBehavior(snapBehaviour)
}
func removeSnap(view: UIView) {
self.animator.removeBehavior(snapBehaviour)
}
@objc func pan(gesture: UIPanGestureRecognizer) {
let gestureView = gesture.view!
let dragPoint: CGPoint = gesture.location(in: gestureView)
let viewCenter = gestureView.center //Center of message view in its superview
let movedDistance = distance(from: snapPoint, to: viewCenter)
let offsetFromCenterInView: UIOffset = UIOffset(horizontal: dragPoint.x - gestureView.bounds.midX, vertical: dragPoint.y - gestureView.bounds.midY)
let velocity: CGPoint = gesture.velocity(in: gestureView.superview)
let vector = CGVector(dx: (velocity.x), dy: (velocity.y))
var lastTime: CFAbsoluteTime
var lastAngle: CGFloat
switch gesture.state {
//Start Dragging
case .began:
if let delegate = self.delegate {
delegate.notifierStartDragging(atPoint: dragPoint)
}
self.animator.removeAllBehaviors()
let anchorPoint: CGPoint = gesture.location(in: gestureView.superview)
attachmentBehaviour = UIAttachmentBehavior(item: gestureView, offsetFromCenter: offsetFromCenterInView, attachedToAnchor: anchorPoint)
lastTime = CFAbsoluteTime()
lastAngle = CGFloat(self.angleOfView(view: gestureView))
attachmentBehaviour.action = { [weak self] in
guard let strongSelf = self else { return }
//Calculate Angular Velocity
let time = CFAbsoluteTimeGetCurrent()
let angle = CGFloat(strongSelf.angleOfView(view: gestureView))
if time > lastTime {
strongSelf.angularVelocity = (angle - lastAngle) / CGFloat((time - lastTime))
lastTime = time
lastAngle = angle
}
}
self.animator.addBehavior(attachmentBehaviour)
//Dragging
case .changed:
let touchPoint : CGPoint = gesture.location(in: gestureView.superview)
attachmentBehaviour.anchorPoint = touchPoint
if let delegate = delegate {
delegate.notifierIsDragging(atPoint: touchPoint)
}
//End Dragging
case .ended:
if let delegate = self.delegate {
delegate.notifierEndDragging(atPoint: dragPoint)
}
self.animator.removeAllBehaviors()
if movedDistance < self.config.thresholdDistance {
addSnap(view: gestureView, toPoint: self.snapPoint)
}
else
{
animator.removeAllBehaviors()
if let gestureViewGestureRecognizers = gestureView.gestureRecognizers {
for gestureRecongnizers in gestureViewGestureRecognizers {
gestureView.removeGestureRecognizer(gestureRecongnizers)
}
}
//Add Push Behaviour
let pushBehavior = UIPushBehavior(items: [gestureView], mode: UIPushBehavior.Mode.instantaneous)
pushBehavior.pushDirection = vector
let pushMagnitude : CGFloat = pushBehavior.magnitude * self.config.pushForceFactor
let massFactor: CGFloat = (gestureView.bounds.height * gestureView.bounds.width) / (100*100)
pushBehavior.magnitude = (pushMagnitude > self.config.minPushForce) ? pushMagnitude*massFactor : self.config.defaultPushForce*massFactor
// pushBehavior.setTargetOffsetFromCenter(offsetFromCenterInWindow, for: gestureView)
self.animator.addBehavior(pushBehavior)
//Add Item Behaviour
let itemBehaviour = UIDynamicItemBehavior(items: [gestureView])
itemBehaviour.addAngularVelocity(angularVelocity * self.config.angularVelocityFactor, for: gestureView)
itemBehaviour.angularResistance = self.config.angularResistance
itemBehaviour.action = { [weak self] in
guard let strongSelf = self else { return }
strongSelf.removeFromSuperView(completion: { [weak self] (completed) in
guard let strongSelf = self else { return }
if let delegate = strongSelf.delegate, completed {
delegate.notifierDidDisappear(notifier: strongSelf)
}
})
}
self.animator.addBehavior(itemBehaviour)
}
default:
break
}
}
@objc func tap(gesture: UITapGestureRecognizer) {
if let delegate = self.delegate {
delegate.notifierIsTapped()
}
if let tapAction = self.tapAction {
tapAction()
}
}
func distance(from:CGPoint, to:CGPoint) -> CGFloat {
let xDist = (to.x - from.x)
let yDist = (to.y - from.y)
return sqrt((xDist * xDist) + (yDist * yDist))
}
func angleOfView(view: UIView) -> Float {
return Float(atan2(view.transform.b, view.transform.a))
}
//http://stackoverflow.com/questions/26029393/random-number-between-two-decimals-in-swift
func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{
return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}
}
| mit | 194bf9029801cf6d5f39226203c402f3 | 40.607903 | 184 | 0.59756 | 5.142374 | false | false | false | false |
jackywpy/AudioKit | Tests/Tests/AKVariableFrequencyResponseBandPassFilter.swift | 11 | 2074 | //
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 12/22/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: NSTimeInterval = 10.0
class Instrument : AKInstrument {
var auxilliaryOutput = AKAudio()
override init() {
super.init()
let oscillator = AKFMOscillator()
auxilliaryOutput = AKAudio.globalParameter()
assignOutput(auxilliaryOutput, to:oscillator)
}
}
class Processor : AKInstrument {
init(audioSource: AKAudio) {
super.init()
let cutoffFrequency = AKLine(firstPoint: 220.ak, secondPoint: 3000.ak, durationBetweenPoints: testDuration.ak)
let bandwidth = AKLine(firstPoint: 10.ak, secondPoint: 100.ak, durationBetweenPoints: testDuration.ak)
let variableFrequencyResponseBandPassFilter = AKVariableFrequencyResponseBandPassFilter(input: audioSource)
variableFrequencyResponseBandPassFilter.cutoffFrequency = cutoffFrequency
variableFrequencyResponseBandPassFilter.bandwidth = bandwidth
variableFrequencyResponseBandPassFilter.scalingFactor = AKVariableFrequencyResponseBandPassFilter.scalingFactorPeak()
let balance = AKBalance(input: variableFrequencyResponseBandPassFilter, comparatorAudioSource: audioSource)
setAudioOutput(balance)
enableParameterLog(
"Cutoff Frequency = ",
parameter: variableFrequencyResponseBandPassFilter.cutoffFrequency,
timeInterval:0.1
)
enableParameterLog(
"Bandwidth = ",
parameter: variableFrequencyResponseBandPassFilter.bandwidth,
timeInterval:0.1
)
resetParameter(audioSource)
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
let processor = Processor(audioSource: instrument.auxilliaryOutput)
AKOrchestra.addInstrument(instrument)
AKOrchestra.addInstrument(processor)
processor.play()
instrument.play()
NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
| mit | c59c6f17cd704bf32108bd2eb326cfa3 | 29.5 | 125 | 0.732883 | 5.415144 | false | true | false | false |
JavanC/Popup | popup/PopupController.swift | 1 | 6050 | //
// PopupControllerViewController.swift
// popup
//
// Created by Javan Chen on 2017/6/16.
// Copyright © 2017年 Javan Chen. All rights reserved.
//
import UIKit
class PopupController: PopupBaseController {
private var imageView: UIImageView?
private var messageView: UIView?
private var messageAttributes = [TextAttribute]()
private struct TextAttribute {
var text: String
var key: String
var value: Any
}
var messageViewWidth: CGFloat { return self.popupWidth - self.horizontalPadding * 2 }
let minContentHeight: CGFloat = 174
// MARK: - Initial
func setupImage(name: String) {
guard let image = UIImage(named: name) else { return }
self.imageView = UIImageView(image: image)
self.imageView?.frame.size = CGSize(width: 100, height: 100)
}
func setupMessageView(view: UIView) {
self.messageView = view
}
func addMeesageAttributed(text: String, with value: Any, for key: String) {
self.messageAttributes.append(TextAttribute(text: text, key: key, value: value))
}
func addMessageUnderlineAttributed(text: String) {
self.addMeesageAttributed(text: text, with: NSUnderlineStyle.styleSingle.rawValue, for: NSUnderlineStyleAttributeName)
}
func addMessageSizeAttributed(text: String, size: CGFloat) {
self.addMeesageAttributed(text: text, with: messageFont.withSize(size), for: NSFontAttributeName)
}
// MARK: - Lifecycle
override func viewDidLoad() {
// Setup 'color' for popup
self.titleColor = UIColorFromHex(0x434F5A)
self.messageColor = UIColorFromHex(0x8A8B87)
self.defaultColor = UIColorFromHex(0x76C9CF)
self.cancelColor = UIColorFromHex(0xA3A49F)
// Setup 'stackView'
let stackView = UIStackView()
let stackViewWidth = popupWidth - horizontalPadding * 2
var stackViewHeigh:CGFloat = 0
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.alignment = .center
stackView.spacing = spacing
// Setup 'image' If need
if let imageView = imageView {
self.constraintFrameSize(view: imageView)
stackView.addArrangedSubview(imageView)
stackViewHeigh += imageView.frame.height + spacing
}
// Setup 'title' If need
if let title = title {
let titleLabel = self.sizeToFitLabel(text: title, width: stackViewWidth, font: titleFont)
titleLabel.textColor = titleColor
self.constraintFrameSize(view: titleLabel)
stackView.addArrangedSubview(titleLabel)
stackViewHeigh += titleLabel.frame.height + spacing
}
// Setup 'line' if has no image
if imageView == nil {
let line = UIView(frame: CGRect(origin: .zero, size: CGSize(width: stackViewWidth, height: 0.5)))
line.backgroundColor = UIColor.gray
self.constraintFrameSize(view: line)
stackView.addArrangedSubview(line)
stackViewHeigh += line.frame.height + spacing
}
// Setup 'message' If need
if let messageView = messageView {
messageView.frame = CGRect(origin: .zero, size: CGSize(width: stackViewWidth, height: messageView.frame.height))
self.constraintFrameSize(view: messageView)
stackView.addArrangedSubview(messageView)
stackViewHeigh += messageView.frame.height
} else if let message = message {
let messageLabel = self.sizeToFitLabel(text: message, width: stackViewWidth, font: messageFont)
messageLabel.textColor = messageColor
self.setupAttributes(label: messageLabel, attrubutes: messageAttributes)
self.constraintFrameSize(view: messageLabel)
stackView.addArrangedSubview(messageLabel)
stackViewHeigh += messageLabel.frame.height
}
// setup 'spacing' if need
if stackViewHeigh + verticalPadding * 2 < minContentHeight {
let spacing = minContentHeight - (stackViewHeigh + verticalPadding * 2)
let spacingView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: stackViewWidth, height: spacing)))
self.constraintFrameSize(view: spacingView)
stackView.addArrangedSubview(spacingView)
stackViewHeigh += spacingView.frame.height
}
// Setup 'contentView'
let contentView = UIView()
stackView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(stackView)
contentView.frame.size = CGSize(width: self.popupWidth, height: stackViewHeigh + verticalPadding * 2)
stackView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
self.setupContenView(view: contentView)
// Setup 'Popup Base Controller'
super.viewDidLoad()
}
// MARK: - Constraint View with View Frame Size
private func constraintFrameSize(view: UIView) {
view.heightAnchor.constraint(equalToConstant: view.frame.height).isActive = true
view.widthAnchor.constraint(equalToConstant: view.frame.width).isActive = true
}
// MARK: - Setup Label Attributes
private func setupAttributes(label: UILabel, attrubutes: [TextAttribute]) {
guard let text = label.text else { return }
let mutableAttributedString = NSMutableAttributedString(string: text)
for messageAttribute in attrubutes {
let range = (text as NSString).range(of: messageAttribute.text)
mutableAttributedString.addAttribute(messageAttribute.key, value: messageAttribute.value, range: range)
}
label.attributedText = mutableAttributedString
label.sizeToFit()
}
}
| mit | cfe33a2a83044590cef906a565eec2c0 | 39.046358 | 126 | 0.656524 | 4.972862 | false | false | false | false |
wiruzx/QuickJump | QuickJump/DVTSourceTextView.swift | 1 | 2638 | //
// DVTSourceTextView.swift
// QuickJump
//
// Created by Victor Shamanov on 5/28/15.
// Copyright (c) 2015 Victor Shamanov. All rights reserved.
//
import Foundation
extension DVTSourceTextView {
static var activeEditorView: DVTSourceTextView? {
let windowController = NSApplication.shared().keyWindow?.windowController as? IDEWorkspaceWindowController
let editor = windowController?.editorArea?.lastActiveEditorContext?.editor
return editor?.mainScrollView?.contentView.documentView as? DVTSourceTextView
}
var visibleTextRange: NSRange {
if let clipView = superview as? NSClipView,
let layoutManager = layoutManager,
let textContainer = textContainer {
let glyphRange = layoutManager.glyphRange(forBoundingRect: clipView.documentVisibleRect,
in: textContainer)
return layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
} else {
fatalError("Unhandled error")
}
}
var sourceCode: String {
return textStorage!.string
}
func rangesOfVisible(_ char: Character) -> [NSRange] {
return sourceCode.allRangesOfCharacters(char, inRange: visibleTextRange)
}
func rangesOfBeginingWords(_ char: Character) -> [NSRange] {
return sourceCode.allRangesOfCharacterInBeginigOfWord(char, inRange: visibleTextRange)
}
func rangesOfBeginingsOfTheLines() -> [NSRange] {
return sourceCode.allRangesOfBeginingsOfTheLinesInRange(visibleTextRange)
}
func widthOfFirstNonEmptyChar(_ location: Int = 0) -> CGFloat {
let width = firstRect(forCharacterRange: NSMakeRange(location, 1), actualRange: nil).width
if width > 0 {
return width
} else if location > 999 {
return 0
} else {
return widthOfFirstNonEmptyChar(location + 1)
}
}
func rectFromRange(_ range: NSRange) -> NSRect {
var rect = firstRect(forCharacterRange: range, actualRange: nil)
if rect.width == 0 {
rect.size.width = widthOfFirstNonEmptyChar()
}
let rectInWindow = window!.convertFromScreen(rect)
var rectInView = self.convert(rectInWindow, from: nil)
let expandSize: CGFloat = 2
rectInView.size.width += expandSize
rectInView.origin.x -= expandSize / 2
return rectInView
}
}
| mit | 46c702d74297ff0798ec0b6926a45fe2 | 31.170732 | 114 | 0.615997 | 5.034351 | false | false | false | false |
codestergit/swift | test/IRGen/objc_class_export.swift | 2 | 5838 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
// CHECK: %swift.refcounted = type
// CHECK: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }>
// CHECK: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }>
// CHECK: [[INT:%TSi]] = type <{ i64 }>
// CHECK: [[DOUBLE:%TSd]] = type <{ double }>
// CHECK: [[NSRECT:%TSC6NSRectV]] = type <{ %TSC7NSPointV, %TSC6NSSizeV }>
// CHECK: [[NSPOINT:%TSC7NSPointV]] = type <{ %TSd, %TSd }>
// CHECK: [[NSSIZE:%TSC6NSSizeV]] = type <{ %TSd, %TSd }>
// CHECK: [[OBJC:%objc_object]] = type opaque
// CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class {
// CHECK: %objc_class* @"OBJC_METACLASS_$_SwiftObject",
// CHECK: %objc_class* @"OBJC_METACLASS_$_SwiftObject",
// CHECK: %swift.opaque* @_objc_empty_cache,
// CHECK: %swift.opaque* null,
// CHECK: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64)
// CHECK: }
// CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00"
// CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
// CHECK: i32 129,
// CHECK: i32 40,
// CHECK: i32 40,
// CHECK: i32 0,
// CHECK: i8* null,
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK: @_CLASS_METHODS__TtC17objc_class_export3Foo,
// CHECK: i8* null,
// CHECK: i8* null,
// CHECK: i8* null,
// CHECK: i8* null
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
// CHECK: i32 128,
// CHECK: i32 16,
// CHECK: i32 24,
// CHECK: i32 0,
// CHECK: i8* null,
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo,
// CHECK: i8* null,
// CHECK: @_IVARS__TtC17objc_class_export3Foo,
// CHECK: i8* null,
// CHECK: _PROPERTIES__TtC17objc_class_export3Foo
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_T017objc_class_export3FooCMf = internal global <{{.*i64}} }> <{
// CHECK: void ([[FOO]]*)* @_T017objc_class_export3FooCfD,
// CHECK: i8** @_T0BOWV,
// CHECK: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64),
// CHECK: %objc_class* @"OBJC_CLASS_$_SwiftObject",
// CHECK: %swift.opaque* @_objc_empty_cache,
// CHECK: %swift.opaque* null,
// CHECK: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 1),
// CHECK: [[FOO]]* (%swift.type*)* @_T017objc_class_export3FooC6createACyFZ,
// CHECK: void (double, double, double, double, [[FOO]]*)* @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tF
// CHECK: }>, section "__DATA,__objc_data, regular"
// -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of
// Foo.
// CHECK: @_T017objc_class_export3FooCN = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @_T017objc_class_export3FooCMf, i32 0, i32 2) to %swift.type*)
// CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = alias %swift.type, %swift.type* @_T017objc_class_export3FooCN
import gizmo
class Hoozit {}
struct BigStructWithNativeObjects {
var x, y, w : Double
var h : Hoozit
}
@objc class Foo {
@objc var x = 0
@objc class func create() -> Foo {
return Foo()
}
@objc func drawInRect(dirty dirty: NSRect) {
}
// CHECK: define internal void @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tFTo([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]*
// CHECK: call swiftcc void @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
// CHECK: }
@objc func bounds() -> NSRect {
return NSRect(origin: NSPoint(x: 0, y: 0),
size: NSSize(width: 0, height: 0))
}
// CHECK: define internal void @_T017objc_class_export3FooC6boundsSC6NSRectVyFTo([[NSRECT]]* noalias nocapture sret, [[OPAQUE4:%.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]*
// CHECK: call swiftcc { double, double, double, double } @_T017objc_class_export3FooC6boundsSC6NSRectVyF([[FOO]]* swiftself [[CAST]])
@objc func convertRectToBacking(r r: NSRect) -> NSRect {
return r
}
// CHECK: define internal void @_T017objc_class_export3FooC20convertRectToBackingSC6NSRectVAF1r_tFTo([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]*
// CHECK: call swiftcc { double, double, double, double } @_T017objc_class_export3FooC20convertRectToBackingSC6NSRectVAF1r_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
func doStuffToSwiftSlice(f f: [Int]) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @_T017objc_class_export3FooC19doStuffToSwiftSliceySaySiG1f_tcAAFTo
func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStructfS_FT1fV17objc_class_export27BigStructWithNativeObjects_T_
init() { }
}
| apache-2.0 | 9d15417459e76861331af2198db1f0f6 | 48.897436 | 218 | 0.642343 | 3.121925 | false | false | false | false |
AndrewBennet/readinglist | ReadingList/ViewControllers/Settings/BackupFrequency.swift | 1 | 1710 | import UIKit
import PersistedPropertyWrapper
class BackupFrequency: UITableViewController {
weak var delegate: BackupFrequencyDelegate?
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return BackupFrequencyPeriod.allCases.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BasicCell", for: indexPath)
guard let label = cell.textLabel else { preconditionFailure("Missing cell text label") }
let backupFrequencyPeriod = BackupFrequencyPeriod.allCases[indexPath.row]
label.text = backupFrequencyPeriod.description
cell.accessoryType = backupFrequencyPeriod == AutoBackupManager.shared.backupFrequency ? .checkmark : .none
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let newBackupFrequency = BackupFrequencyPeriod.allCases[indexPath.row]
if AutoBackupManager.shared.backupFrequency == newBackupFrequency { return }
AutoBackupManager.shared.setBackupFrequency(newBackupFrequency)
tableView.reloadData()
delegate?.backupFrequencyDidChange()
}
}
protocol BackupFrequencyDelegate: AnyObject {
func backupFrequencyDidChange()
}
extension BackupFrequencyPeriod: CustomStringConvertible {
var description: String {
switch self {
case .daily: return "Daily"
case .weekly: return "Weekly"
case .off: return "Off"
}
}
}
| gpl-3.0 | 36eda09ac8249032cf2f9989928a1370 | 37 | 115 | 0.726901 | 5.277778 | false | false | false | false |
supertommy/yahoo-weather-ios-watchkit-swift | weather/ModelController.swift | 1 | 2872 | //
// ModelController.swift
// weather
//
// Created by Tommy Leung on 3/14/15.
// Copyright (c) 2015 Tommy Leung. All rights reserved.
//
import UIKit
/*
A controller object that manages a simple model -- a collection of month names.
The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:.
It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application.
There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand.
*/
class ModelController: NSObject, UIPageViewControllerDataSource {
var pageData: [WeatherData] = []
override init()
{
super.init()
// Create the data model.
pageData.append(WeatherData(location: "new york, ny"))
}
func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> DataViewController?
{
// Return the data view controller for the given index.
if (self.pageData.count == 0) || (index >= self.pageData.count)
{
return nil
}
// Create a new view controller and pass suitable data.
let dataViewController = storyboard.instantiateViewControllerWithIdentifier("DataViewController") as DataViewController
dataViewController.weatherData = self.pageData[index]
return dataViewController
}
func indexOfViewController(viewController: DataViewController) -> Int {
return NSNotFound
}
// MARK: - Page View Controller Data Source
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?
{
var index = self.indexOfViewController(viewController as DataViewController)
if (index == 0) || (index == NSNotFound)
{
return nil
}
index--
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController?
{
var index = self.indexOfViewController(viewController as DataViewController)
if index == NSNotFound
{
return nil
}
index++
if index == self.pageData.count
{
return nil
}
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
}
| mit | 98c626d2a8914f6cfa8216550280066b | 33.190476 | 225 | 0.693942 | 5.642436 | false | false | false | false |
DigitasLabsParis/UnicornHorn | iOSApp/BLE Test/Extensions.swift | 3 | 5196 | //
// Extensions.swift
// Adafruit Bluefruit LE Connect
//
// Created by Collin Cunningham on 10/14/14.
// Copyright (c) 2014 Adafruit Industries. All rights reserved.
//
import Foundation
import CoreBluetooth
extension NSData {
func hexRepresentationWithSpaces(spaces:Bool) ->NSString {
var byteArray = [UInt8](count: self.length, repeatedValue: 0x0)
// The Test Data is moved into the 8bit Array.
self.getBytes(&byteArray, length:self.length)
// self.debugDescription
var hexBits = "" as String
for value in byteArray {
let newHex = NSString(format:"0x%2X", value) as String
hexBits += newHex.stringByReplacingOccurrencesOfString(" ", withString: "0", options: NSStringCompareOptions.CaseInsensitiveSearch)
if spaces {
hexBits += " "
}
}
return hexBits
}
func hexRepresentation()->String {
let dataLength:Int = self.length
var string = NSMutableString(capacity: dataLength*2)
let dataBytes:UnsafePointer<Void> = self.bytes
for idx in 0...(dataLength-1) {
string.appendFormat("%02x", [UInt(dataBytes[idx])] )
}
return string
}
func stringRepresentation()->String {
//Write new received data to the console text view
//convert data to string & replace characters we can't display
let dataLength:Int = self.length
var data = [UInt8](count: dataLength, repeatedValue: 0)
self.getBytes(&data, length: dataLength)
for index in 0...dataLength-1 {
if (data[index] <= 0x1f) || (data[index] >= 0x80) { //null characters
if (data[index] != 0x9) //0x9 == TAB
&& (data[index] != 0xa) //0xA == NL
&& (data[index] != 0xd) { //0xD == CR
data[index] = 0xA9
}
}
}
let newString = NSString(bytes: &data, length: dataLength, encoding: NSUTF8StringEncoding)
return newString!
}
}
extension NSString {
func toHexSpaceSeparated() ->NSString {
let len = UInt(self.length)
var charArray = [unichar](count: self.length, repeatedValue: 0x0)
// let chars = UnsafeMutablePointer<unichar>(malloc(len * UInt(sizeofValue(unichar))))
self.getCharacters(&charArray)
var hexString = NSMutableString()
var charString:NSString
for i in 0...(len-1) {
charString = NSString(format: "0x%02X", charArray[Int(i)])
if (charString.length == 1){
charString = "0".stringByAppendingString(charString)
}
hexString.appendString(charString.stringByAppendingString(" "))
}
// free(chars)
return hexString
}
}
extension CBUUID {
func representativeString() ->NSString{
let data = self.data
var byteArray = [UInt8](count: data.length, repeatedValue: 0x0)
data.getBytes(&byteArray, length:data.length)
let outputString = NSMutableString(capacity: 16)
for value in byteArray {
switch (value){
// case 3:
// case 5:
// case 7:
case 9:
outputString.appendFormat("%02x-", value)
break
default:
outputString.appendFormat("%02x", value)
}
}
return outputString
}
func equalsString(toString:String, caseSensitive:Bool, omitDashes:Bool)->Bool {
var aString = toString
var verdict = false
var options = NSStringCompareOptions.CaseInsensitiveSearch
if omitDashes == true {
aString = toString.stringByReplacingOccurrencesOfString("-", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
}
if caseSensitive == true {
options = NSStringCompareOptions.LiteralSearch
}
// println("\(self.representativeString()) ?= \(aString)")
verdict = aString.compare(self.representativeString(), options: options, range: nil, locale: NSLocale.currentLocale()) == NSComparisonResult.OrderedSame
return verdict
}
}
func printLog(obj:AnyObject, funcName:String, logString:String) {
if LOGGING != true {
return
}
println("\(obj.classForCoder.description()) \(funcName) : \(logString)")
}
func binaryforByte(value: UInt8) -> String {
var str = String(value, radix: 2)
let len = countElements(str)
if len < 8 {
var addzeroes = 8 - len
while addzeroes > 0 {
str = "0" + str
addzeroes -= 1
}
}
return str
} | apache-2.0 | 37503bfdc6eea94d68ca9079200bd5f9 | 26.791444 | 160 | 0.534257 | 5.00578 | false | false | false | false |
Donkey-Tao/SinaWeibo | SinaWeibo/SinaWeibo/Classes/Main/Visitor/TFBaseViewController.swift | 1 | 2666 | //
// TFBaseViewController.swift
// SinaWeibo
//
// Created by Donkey-Tao on 2016/09/27.
// Copyright © 2016年 http://taofei.me All rights reserved.
//
import UIKit
class TFBaseViewController: UITableViewController {
//MARK:- 懒加载属性
lazy var visitorView : TFVisitorView = TFVisitorView.TFVisitorView()
//MARK:- 定义是否已经登录状态变量
var isLogin :Bool = TFUserAccountViewModel.shareInstance.isLogin
//MARK:- 重写系统回调函数
/// 重写加载View的方法
override func loadView() {
//判断要加载哪一个View
isLogin ? super.loadView() : setupVisitorView()
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationItem()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
}
//MARK:- 设置UI
extension TFBaseViewController{
///设置访客视图
func setupVisitorView() {
view = visitorView
//监听访客视图中的注册、登录按钮的点击
visitorView.registerBtn.addTarget(self, action: #selector(TFBaseViewController.registerBtnClick), for: .touchUpInside)
visitorView.loginBtn.addTarget(self, action: #selector(TFBaseViewController.loginBtnClick), for: .touchUpInside)
}
///设置导航栏左右的注册、登录按钮
func setupNavigationItem(){
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain , target: self, action:#selector(TFBaseViewController.registerBtnClick))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain , target: self, action:#selector(TFBaseViewController.loginBtnClick))
}
}
//MARK:- 时间监听
extension TFBaseViewController{
///注册按钮点击
@objc func registerBtnClick(){
TFLog("注册按钮点击")
}
///登录按钮点击
@objc func loginBtnClick(){
//1.创建授权控制器
let oauthVC = TFOAuthViewController()
//2.包装一个导航控制器
let oauthNavVC = UINavigationController(rootViewController: oauthVC)
//3.弹出控制器
present(oauthNavVC, animated: true, completion: nil)
TFLog("登录按钮点击")
}
}
| mit | 11fab9f300f4e062706bbafca2881cf4 | 23.690722 | 158 | 0.65428 | 4.723866 | false | false | false | false |
brentsimmons/Frontier | BeforeTheRename/UserTalk/UserTalk/Node/ComparisonNode.swift | 1 | 1348 | //
// ComparisonNode.swift
// UserTalk
//
// Created by Brent Simmons on 5/3/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
final class ComparisonNode: CodeTreeNode {
// Both sides always evaluated.
let operation: CodeTreeOperation
let textPosition: TextPosition
let node1: CodeTreeNode
let node2: CodeTreeNode
init(_ operation: CodeTreeOperation, _ textPosition: TextPosition, _ node1: CodeTreeNode, _ node2: CodeTreeNode) {
self.operation = operation
self.textPosition = textPosition
self.node1 = node1
self.node2 = node2
}
func evaluate() throws -> Value {
do {
let val1 = evaluate(node1)
let val2 = evaluate(node2)
switch operation {
case .equalsOp:
return try val1.equals(val2)
case .notEqualsOp:
return try !(val1.equals(val2))
case .greaterThanOp:
return try val1.greaterThan(val2)
case .lessThanOp:
return try val1.lessThan(val2)
case .greaterThanEqualsOp:
return try val1.greaterThanEqual(val2)
case .lessThanEqualsOp:
return try val1.lessThanEqual(val2)
case .beginsWithOp:
return try val1.beginsWith(val2)
case .containsOp:
return try val1.contains(val2)
default:
throw LangError(.illegalTokenError, textPosition: textPosition)
}
}
catch { throw error }
}
}
| gpl-2.0 | f7217c54dfe576699dcf19d4b0fbbc4f | 19.104478 | 115 | 0.71121 | 3.37594 | false | false | false | false |
yossan4343434/TK_15 | src/app/Visy/Pods/Spring/Spring/SpringView.swift | 67 | 2694 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([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
public class SpringView: UIView, Springable {
@IBInspectable public var autostart: Bool = false
@IBInspectable public var autohide: Bool = false
@IBInspectable public var animation: String = ""
@IBInspectable public var force: CGFloat = 1
@IBInspectable public var delay: CGFloat = 0
@IBInspectable public var duration: CGFloat = 0.7
@IBInspectable public var damping: CGFloat = 0.7
@IBInspectable public var velocity: CGFloat = 0.7
@IBInspectable public var repeatCount: Float = 1
@IBInspectable public var x: CGFloat = 0
@IBInspectable public var y: CGFloat = 0
@IBInspectable public var scaleX: CGFloat = 1
@IBInspectable public var scaleY: CGFloat = 1
@IBInspectable public var rotate: CGFloat = 0
@IBInspectable public var curve: String = ""
public var opacity: CGFloat = 1
public var animateFrom: Bool = false
lazy private var spring : Spring = Spring(self)
override public func awakeFromNib() {
super.awakeFromNib()
self.spring.customAwakeFromNib()
}
public override func layoutSubviews() {
super.layoutSubviews()
spring.customLayoutSubviews()
}
public func animate() {
self.spring.animate()
}
public func animateNext(completion: () -> ()) {
self.spring.animateNext(completion)
}
public func animateTo() {
self.spring.animateTo()
}
public func animateToNext(completion: () -> ()) {
self.spring.animateToNext(completion)
}
} | mit | a80f391aa10cc1e9d6eadafced5d5320 | 36.957746 | 81 | 0.709354 | 4.69338 | false | false | false | false |
openbuild-sheffield/jolt | Sources/RouteStencil/route.StencilRAML.swift | 1 | 3404 | import OpenbuildExtensionPerfect
import OpenbuildSingleton
import OpenbuildRouteRegistry
import PerfectLib
import PerfectHTTP
import RouteCMS
import Stencil
private struct ramlCache {
private static var cache: String?
static func get() -> String? {
if let data = self.cache {
return data
} else {
return nil
}
}
static func set(content: String) {
self.cache = content
}
static func delete() {
self.cache = nil
}
}
public let handlerRouteStencilRAML = {
(request: HTTPRequest, response: HTTPResponse) in
let cached = ramlCache.get()
if cached != nil {
response.setHeader(.contentType, value: "application/raml+yaml")
response.appendBody(string: cached!)
response.completed()
return
}
struct genericRaml {var name: String; var docs: [String];}
struct routeRaml {var method: String; var docs: [String];}
struct routeUri {var uri: String; var methods: [routeRaml]}
let renderer = Renderer(response: response)
renderer.setFileSystemPaths(paths: ["./Views/"])
var URIMap:[String:[routeRaml]] = [:]
for (_, map) in RouteRegistry.getRouteMap().sorted(by: {$0.value.uri < $1.value.uri}) {
let handlerRequest = RouteRegistry.getHandlerRequest(uri: map.uri.lowercased(), method: map.method)
let handlerResponse = RouteRegistry.getHandlerResponse(uri: map.uri.lowercased(), method: map.method)
if handlerRequest != nil && handlerResponse != nil {
let docsRequest = handlerRequest!.getDocumentation(handlerResponse: handlerResponse!)
let docs = docsRequest.asRaml(description: handlerRequest!.description)
if URIMap[map.uri] == nil {
URIMap[map.uri] = [routeRaml(method: map.method.description, docs: docs)]
} else {
URIMap[map.uri]!.append(routeRaml(method: map.method.description, docs: docs))
}
}
}
//Flatten the structure so it can be used by the template
var uris = [routeUri]()
for (uri, data) in URIMap.sorted(by: { $0.0 < $1.0 }) {
uris.append(routeUri(uri:uri, methods: data))
}
let context = Context(dictionary: [
"generic": [
genericRaml(name: "Response400", docs: ResponseModel400Messages.describeRAML()),
genericRaml(name: "Response403", docs: ResponseModel403.describeRAML()),
genericRaml(name: "Response404", docs: ResponseModel404.describeRAML()),
genericRaml(name: "Response422", docs: ResponseModel422.describeRAML()),
genericRaml(name: "Response500", docs: ResponseModel500Messages.describeRAML())
],
"uris": uris
])
let content = renderer.render(template: "api.raml", context: context, contentType: "application/raml+yaml")
if content != nil {
ramlCache.set(content: content!)
}
}
public class RouteStencilRAML: OpenbuildRouteRegistry.FactoryRoute {
override public func route() -> NamedRoute? {
return NamedRoute(
method: "get",
uri: "/api.raml",
handlerRoute: handlerRouteStencilRAML
)
}
} | gpl-2.0 | 9e8c719128e299237b56e509b1dc29a9 | 28.868421 | 115 | 0.600764 | 4.380952 | false | false | false | false |
crossroadlabs/Express | Express/AnyContent+XML.swift | 2 | 1107 | //===--- AnyContent+XML.swift ---------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express 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 Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
public extension AnyContent {
func asXML() throws -> Any? {
throw ExpressError.NotImplemented(description: "XML parsing is not implemented yet")
}
} | gpl-3.0 | 25e851c6ff06d2e23f43c967d9fad1a2 | 38.571429 | 92 | 0.65131 | 4.710638 | false | false | false | false |
pbunting/OHTreesStorageManagerKit | OHTreesStorageManagerApp/MasterViewController.swift | 1 | 3619 | //
// MasterViewController.swift
// OHTreesStorageManagerApp
//
// Created by Paul Bunting on 4/10/16.
// Copyright © 2016 Paul Bunting. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(MasterViewController.insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| gpl-3.0 | c918b2d505ed78d3860ab4e83b17d11d | 37.489362 | 157 | 0.696241 | 5.742857 | false | false | false | false |
64characters/Telephone | UseCasesTestDoubles/UserAgentSpy.swift | 1 | 1778 | //
// UserAgentSpy.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone 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.
//
// Telephone 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.
//
import Domain
import UseCases
public final class UserAgentSpy {
public var isStarted = false
public var maxCalls = 0
public var didCallStart = false
public private(set) var didCallAudioDevices = false
public var audioDevicesResult = [UserAgentAudioDevice]()
public private(set) var didCallUpdateAudioDevices = false
public private(set) var soundIOSelectionCallCount = 0
public var didSelectSoundIO: Bool { return soundIOSelectionCallCount > 0 }
public private(set) var invokedInputDeviceID: Int?
public private(set) var invokedOutputDeviceID: Int?
public init() {}
}
extension UserAgentSpy: UserAgent {
public func start() {
didCallStart = true
}
public func audioDevices() throws -> [UserAgentAudioDevice] {
didCallAudioDevices = true
return audioDevicesResult
}
public func updateAudioDevices() {
didCallUpdateAudioDevices = true
}
public func selectSoundIODeviceIDs(input: Int, output: Int) throws {
soundIOSelectionCallCount += 1
invokedInputDeviceID = input
invokedOutputDeviceID = output
}
}
| gpl-3.0 | d983006a23948658de92f0d3a737a96c | 28.6 | 78 | 0.716779 | 4.612987 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Helpers/UIImage+ImageUtilities.swift | 1 | 5977 | // Wire
// Copyright (C) 2019 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
import UIKit
extension UIImage {
func imageScaled(with scaleFactor: CGFloat) -> UIImage? {
let size = self.size.applying(CGAffineTransform(scaleX: scaleFactor, y: scaleFactor))
let scale: CGFloat = 0 // Automatically use scale factor of main screens
let hasAlpha = false
UIGraphicsBeginImageContextWithOptions(size, _: !hasAlpha, _: scale)
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
func desaturatedImage(with context: CIContext, saturation: Double = 0) -> UIImage? {
guard let filter = CIFilter(name: "CIColorControls"),
let cg = cgImage
else { return nil }
let i: CIImage = CIImage(cgImage: cg)
filter.setValue(i, forKey: kCIInputImageKey)
filter.setValue(saturation, forKey: "InputSaturation")
guard let result = filter.outputImage,
let cgImage: CGImage = context.createCGImage(result, from: result.extent) else { return nil }
return UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation)
}
func with(insets: UIEdgeInsets, backgroundColor: UIColor? = nil) -> UIImage? {
let newSize = CGSize(width: size.width + insets.left + insets.right, height: size.height + insets.top + insets.bottom)
UIGraphicsBeginImageContextWithOptions(newSize, _: 0.0 != 0, _: 0.0)
backgroundColor?.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
draw(in: CGRect(x: insets.left, y: insets.top, width: size.width, height: size.height))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return colorImage
}
class func singlePixelImage(with color: UIColor) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
class func deviceOptimizedImage(from imageData: Data) -> UIImage? {
return UIImage(from: imageData, withMaxSize: UIScreen.main.nativeBounds.size.height)
}
convenience init?(from imageData: Data, withMaxSize maxSize: CGFloat) {
guard let source: CGImageSource = CGImageSourceCreateWithData(imageData as CFData, nil),
let scaledImage = CGImageSourceCreateThumbnailAtIndex(source, 0, UIImage.thumbnailOptions(withMaxSize: maxSize)) else { return nil }
self.init(cgImage: scaledImage, scale: 2.0, orientation: .up)
}
private class func thumbnailOptions(withMaxSize maxSize: CGFloat) -> CFDictionary {
return [
kCGImageSourceCreateThumbnailWithTransform: kCFBooleanTrue,
kCGImageSourceCreateThumbnailFromImageIfAbsent: kCFBooleanTrue,
kCGImageSourceCreateThumbnailFromImageAlways: kCFBooleanTrue,
kCGImageSourceThumbnailMaxPixelSize: NSNumber(value: Float(maxSize))
] as CFDictionary
}
private class func size(for source: CGImageSource) -> CGSize {
let options = [
kCGImageSourceShouldCache: kCFBooleanTrue
] as CFDictionary
guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, options) as? [CFString: Any] else {
return .zero
}
if let height = properties[kCGImagePropertyPixelHeight] as? CGFloat,
let width = properties[kCGImagePropertyPixelWidth] as? CGFloat {
return CGSize(width: width, height: height)
}
return .zero
}
convenience init?(from imageData: Data, withShorterSideLength shorterSideLength: CGFloat) {
guard let source: CGImageSource = CGImageSourceCreateWithData(imageData as CFData, nil) else { return nil }
let size = UIImage.size(for: source)
if size.width <= 0 || size.height <= 0 {
return nil
}
var longSideLength = shorterSideLength
if size.width > size.height {
longSideLength = shorterSideLength * (size.width / size.height)
} else if size.height > size.width {
longSideLength = shorterSideLength * (size.height / size.width)
}
guard let scaledImage = CGImageSourceCreateThumbnailAtIndex(source, 0, UIImage.thumbnailOptions(withMaxSize: longSideLength)) else { return nil }
// TODO: read screen scale
self.init(cgImage: scaledImage, scale: 2.0, orientation: .up)
}
convenience init(color: UIColor, andSize size: CGSize) {
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(cgImage: (image?.cgImage)!)
}
}
| gpl-3.0 | 3ee3f0fbcd3664345a608aec9d578e81 | 38.065359 | 153 | 0.679271 | 4.887163 | false | false | false | false |
jianghongbing/APIReferenceDemo | UserNotifications/LocalNotificationDemo/LocalNotificationDemo/ViewController.swift | 1 | 5812 | //
// ViewController.swift
// LocalNotificationDemo
//
// Created by pantosoft on 2017/9/7.
// Copyright © 2017年 jianghongbing. All rights reserved.
//
import UIKit
import UserNotifications
class ViewController: UITableViewController {
var authenticationStatus: UNAuthorizationStatus = .notDetermined
override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().getNotificationSettings {
self.authenticationStatus = $0.authorizationStatus
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
startRequestAuthentication()
}else {
if authenticationStatus != .authorized {
UIAlertController.confirmAlert(withTitle: "请先请求用户允许发送通知", message: "发送通知前,必须让用户允许发送通知", fromController: self)
return
}
if indexPath.row == 1 {
sendNormalNotification()
}else if indexPath.row == 2 {
sendNotificationWithActions()
}else if indexPath.row == 3 {
}
}
}
private func startRequestAuthentication() {
//1.获取当前notification的相关的授权状态
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
self.authenticationStatus = settings.authorizationStatus
switch settings.authorizationStatus {
//2.通知授权状态还没有确认
case .notDetermined:
//3.向用户发起请求,是否开启通知
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
if granted {
self.startRequestAuthentication()
}else {
if let error = error {
print(error.localizedDescription)
}
}
})
//4.用户已经拒绝接受通知
case .denied:
UIAlertController.confirmAlert(withTitle: "通知已经被拒绝", message: "请到设置里面去开启通知", fromController: self)
//5.用户已经开启通知
case .authorized:
UIAlertController.confirmAlert(withTitle: "通知已经被允许", message: "可以开始发通知", fromController: self)
case .provisional:
break;
}
}
}
private func sendNormalNotification() {
/**
guard authenticationStatus == .authorized else {
UIAlertController.confirmAlert(withTitle: "通知已经被拒绝", message: "请到设置里面去开启通知", fromController: self)
return
}
*/
//6.通知内容的创建
let notificationContent = UNMutableNotificationContent()
//7.设置通知内容的标题
notificationContent.title = "notification title"
//8.设置通知内容的副标题
notificationContent.subtitle = "notification subtitle"
//9.设置打开通知时,进入应用的luanchImage
//notificationContent.launchImageName = ""
//
//9.设置通知body
notificationContent.body = "push notification by UNUserNotification"
//10.设置badge number
notificationContent.badge = (UIApplication.shared.applicationIconBadgeNumber + 1) as NSNumber
//11.定时通知,timeInterval:多少秒后发送, repeats:是否重复
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false)
//12.创建notification request
let reqeust = UNNotificationRequest(identifier: "jianghongbing", content: notificationContent, trigger:trigger)
//13.发送通知
UNUserNotificationCenter.current().add(reqeust) {
if let error = $0 {
print("error:\(error.localizedDescription)")
}else {
print("send notification success")
}
}
}
private func sendNotificationWithActions() {
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "action notification"
notificationContent.subtitle = "notification with actions "
notificationContent.body = "push notification by UNUserNotification"
//14.设置通知到来的时候声音
notificationContent.sound = UNNotificationSound.default()
notificationContent.categoryIdentifier = NotificationCategoryType.input.rawValue
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false)
let reqeust = UNNotificationRequest(identifier: "jianghongbing", content: notificationContent, trigger:trigger)
UNUserNotificationCenter.current().add(reqeust) {
if let error = $0 {
print("error:\(error.localizedDescription)")
}else {
print("send notification success")
}
}
}
}
extension UIAlertController {
static func confirmAlert(withTitle title: String, message: String, fromController: UIViewController) {
let action = UIAlertAction(title: "Done", style: .default, handler: nil)
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(action)
fromController.present(alertController, animated: true, completion: nil)
}
}
| mit | c975011802fd8566b4c40e0ed86a4a23 | 36.992958 | 147 | 0.61557 | 5.471602 | false | false | false | false |
lee0741/Glider | Glider/Comment.swift | 1 | 1895 | //
// Comment.swift
// Glider
//
// Created by Yancen Li on 2/24/17.
// Copyright © 2017 Yancen Li. All rights reserved.
//
import Foundation
struct Comment {
let id: Int
let level: Int
let time_ago: String
let content: String
var user: String?
init(from json: [String: Any]) {
self.id = json["id"] as! Int
self.level = json["level"] as! Int
self.time_ago = json["time_ago"] as! String
self.content = json["content"] as! String
self.user = json["user"] as? String
}
}
extension Comment {
static func extractComments(from rawComment: [String: Any]) -> [Comment] {
var kids = [Comment]()
if let comments = rawComment["comments"] as? [[String: Any]] {
comments.forEach { (comment) in
kids.append(contentsOf: extractComments(from: comment))
}
}
let kid = Comment(from: rawComment)
if kid.content != "[deleted]" {
kids.insert(Comment(from: rawComment), at: 0)
}
return kids
}
static func getComments(from itemId: Int, completion: @escaping ([Comment], Story?) -> Void) {
URLSession.shared.dataTask(with: URL(string: "https://glider.herokuapp.com/item/\(itemId)")!) { (data, response, error) in
var comments = [Comment]()
var story: Story?
if let error = error {
print("Failed to fetch data: \(error)")
return
}
guard let data = data else { return }
if let rawData = try? JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] {
story = Story(from: rawData)
let rawComments = rawData["comments"] as! [[String: Any]]
rawComments.forEach { rawComment in
comments.append(contentsOf: extractComments(from: rawComment))
}
}
DispatchQueue.main.async {
completion(comments, story)
}
}.resume()
}
}
| mit | 108b4d5b842b0f2aa9f5965be2cb9e45 | 25.305556 | 126 | 0.596621 | 3.803213 | false | false | false | false |
cavalcantedosanjos/ND-OnTheMap | OnTheMap/OnTheMap/ViewControllers/MapViewController.swift | 1 | 6924 | //
// MapViewController.swift
// OnTheMap
//
// Created by Joao Anjos on 06/02/17.
// Copyright © 2017 Joao Anjos. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var studentsMapView: MKMapView!
let kLocationSegue = "locationSegue"
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
getStudentsLocation()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if(StudentDataSource.sharedInstance.studentData.count > 0) {
addAnnotations(locations: StudentDataSource.sharedInstance.studentData)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
getUserInformation(key: User.current.key!)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == kLocationSegue) {
let vc = segue.destination as! SearchLocationViewController
vc.delegate = self
}
}
// MARK: - Actions
@IBAction func logoutButton_Clicked(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
logout()
}
@IBAction func refreshButton_Clicked(_ sender: Any) {
getStudentsLocation()
}
@IBAction func pinButton_Clicked(_ sender: Any) {
getCurrentLocation {
self.checkLocation()
}
}
// MARK: - Services
func getStudentsLocation() {
LocationService.sharedInstance().getStudentsLocation(onSuccess: { (studentsLocation) in
StudentDataSource.sharedInstance.studentData.removeAll()
if studentsLocation.count > 0 {
StudentDataSource.sharedInstance.studentData = studentsLocation
DispatchQueue.main.async {
self.addAnnotations(locations: studentsLocation)
}
} else {
self.removeAllAnnotations()
}
}, onFailure: { (error) in
self.showMessage(message: error.error!, title: "")
}, onCompleted: {
//Nothing
})
}
func getCurrentLocation(onCompletedWithSuccess: @escaping ()-> Void) {
LocationService.sharedInstance().getCurrentLocation(onSuccess: { (locations) in
if let location = locations.first{
User.current.location = location
}
onCompletedWithSuccess()
}, onFailure: { (errorRespons) in
self.showMessage(message: errorRespons.error!, title: "")
}, onCompleted: {
//Nothing
})
}
func logout() {
StudentService.sharedInstance().logout(onSuccess: {
//Nothing
}, onFailure: { (error) in
//Nothing
}, onCompleted: {
//Nothing
})
}
func getUserInformation(key: String) {
StudentService.sharedInstance().getUserInformation(key: key, onSuccess: { (user) in
User.current = user
}, onFailure: { (error) in
self.showMessage(message: error.error!, title: "")
}, onCompleted: {
//Nothing
})
}
// MARK: - Helpers
func addAnnotations(locations: [StudentLocation]) {
removeAllAnnotations()
var annotations: [MKAnnotation] = [MKAnnotation]()
for location in locations {
let coordinate = CLLocationCoordinate2D(latitude: location.latitude!, longitude: location.longitude!)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = location.fullName()
annotation.subtitle = location.mediaUrl!
annotations.append(annotation)
}
self.studentsMapView.showAnnotations(annotations, animated: true)
}
func removeAllAnnotations() {
studentsMapView.removeAnnotations(studentsMapView.annotations)
}
func showMessage(message: String, title: String) {
let alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
func checkLocation() {
if User.current.location != nil{
let alert: UIAlertController = UIAlertController(title: "", message: "You Have Already Posted a Student Location. Would You Like to Overwrite. Your Current Location?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Overwrite", style: .default, handler: { (action) in
self.performSegue(withIdentifier: "locationSegue", sender: nil)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
} else {
performSegue(withIdentifier: "locationSegue", sender: nil)
}
}
}
// MARK: - MKMapViewDelegate
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
else {
pinView!.annotation = annotation
}
return pinView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
if let toOpen = view.annotation?.subtitle! {
if let url = URL(string: toOpen) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
showMessage(message: "Can't Open URL", title: "")
}
}
}
}
}
// MARK: - SearchLocationViewControllerDelegate
extension MapViewController: SearchLocationViewControllerDelegate {
func didFinishedPostLocation() {
self.getStudentsLocation()
}
}
| mit | 5ca1419266116081eef182afc7cb9399 | 31.966667 | 203 | 0.592518 | 5.36251 | false | false | false | false |
MaddTheSane/Simple-Comic | Classes/Thumbnail View/TSSTThumbnailView.swift | 1 | 6868 | //
// TSSTThumbnailView.swift
// SimpleComic
//
// Created by C.W. Betts on 10/25/15.
//
//
import Cocoa
class TSSTThumbnailView: NSView {
@IBOutlet weak var pageController: NSArrayController!
@IBOutlet weak var thumbnailView: TSSTImageView!
@objc weak var dataSource: TSSTSessionWindowController?
private var trackingRects = IndexSet()
private var trackingIndexes = Set<NSNumber>()
private var hoverIndex: Int? = nil
private var limit = 0
private var thumbLock = NSLock()
private var threadIdent: UInt32 = 0
override func awakeFromNib() {
super.awakeFromNib()
self.window?.makeFirstResponder(self)
self.window?.acceptsMouseMovedEvents = true
thumbnailView.clears = true
}
private func rect(for index: Int) -> NSRect {
var bounds = window!.screen!.visibleFrame
let fullBounds = window!.screen!.frame
bounds.origin.x -= fullBounds.origin.x
bounds.origin.y -= fullBounds.origin.y
let ratio = bounds.height / bounds.width
let horCount = Int(ceil(sqrt(CGFloat((pageController!.content! as AnyObject).count) / ratio)))
let vertCount = Int(ceil(CGFloat((pageController!.content! as AnyObject).count) / CGFloat(horCount)))
let side = bounds.height / CGFloat(vertCount)
let horSide = bounds.width / CGFloat(horCount)
let horGridPos = index % horCount
let vertGridPos = (index / horCount) % vertCount
let thumbRect: NSRect
if dataSource!.session.pageOrder {
thumbRect = NSRect(x: CGFloat(horGridPos) * horSide, y: bounds.maxY - side - CGFloat(vertGridPos) * side, width: horSide, height: side)
}
else {
thumbRect = NSRect(x: bounds.maxX - horSide - CGFloat(horGridPos) * horSide, y: bounds.maxY - side - CGFloat(vertGridPos) * side, width: horSide, height: side)
}
return thumbRect
}
private func removeTrackingRects() {
thumbnailView.image = nil
hoverIndex = nil
for tagIndex in trackingRects.reversed() {
self.removeTrackingRect(tagIndex)
}
trackingRects.removeAll()
trackingIndexes.removeAll()
}
@objc func buildTrackingRects() {
hoverIndex = nil
removeTrackingRects()
var trackRect: NSRect
var rectIndex: NSNumber
for counter in 0 ..< (pageController!.content! as AnyObject).count {
trackRect = rect(for: counter).insetBy(dx: 2, dy: 2)
rectIndex = NSNumber(value: counter)
let tagIndex = addTrackingRect(trackRect, owner: self, userData: Unmanaged.passUnretained(rectIndex).toOpaque(), assumeInside: false)
trackingRects.insert(tagIndex)
trackingIndexes.insert(rectIndex)
}
needsDisplay = true
}
@objc func processThumbs() {
autoreleasepool() {
threadIdent += 1
let localIdent = threadIdent
thumbLock.lock()
let pageCount: Int = (pageController!.content! as AnyObject).count
limit = 0
while limit < (pageCount) && localIdent == threadIdent &&
dataSource?.responds(to: #selector(TSSTSessionWindowController.imageForPage(at:))) ?? false {
autoreleasepool() {
dataSource!.imageForPage(at: limit)
if (limit % 5) == 0 {
DispatchQueue.main.async {
if self.window!.isVisible {
self.needsDisplay = true
}
}
}
limit += 1
}
}
thumbLock.unlock()
}
DispatchQueue.main.sync {
needsDisplay = true
}
}
override func draw(_ rect: NSRect) {
let mousePoint = convert(window!.mouseLocationOutsideOfEventStream, from: nil)
for counter in 0 ..< limit {
let thumbnail = dataSource!.imageForPage(at: counter)
var drawRect = self.rect(for: counter)
drawRect = rectCentered(with: thumbnail.size, in: drawRect.insetBy(dx: 2, dy: 2))
thumbnail.draw(in: drawRect, from: .zero, operation: .sourceOver, fraction: 1.0)
if NSMouseInRect(mousePoint, drawRect, false) {
hoverIndex = counter
zoomThumbnail(at: hoverIndex!)
}
}
}
override func mouseEntered(with theEvent: NSEvent) {
hoverIndex = unsafeBitCast(theEvent.userData, to: NSNumber.self).intValue
if limit == (pageController.content! as AnyObject).count {
Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(TSSTThumbnailView.dwell(_:)), userInfo: (hoverIndex! as NSNumber), repeats: false)
}
}
override func mouseExited(with theEvent: NSEvent) {
if unsafeBitCast(theEvent.userData, to: NSNumber.self).intValue == hoverIndex {
hoverIndex = nil
thumbnailView.image = nil
window!.removeChildWindow(thumbnailView.window!)
thumbnailView.window!.orderOut(self)
}
}
@objc private func dwell(_ timer: Timer) {
if let userInfo = timer.userInfo as? NSNumber,
let hoverIndex = hoverIndex,
userInfo.intValue == hoverIndex {
zoomThumbnail(at: hoverIndex)
}
}
private func zoomThumbnail(at index: Int) {
guard let arrangedObject = (pageController.arrangedObjects as? NSArray)?[index] as? NSObject,
let thumb = arrangedObject.value(forKey: "pageImage") as? NSImage else {
assert(false, "could not get image at index \(index)")
return
}
thumbnailView.image = thumb
thumbnailView.needsDisplay = true
var imageSize = thumb.size
thumbnailView.imageName = arrangedObject.value(forKey: "name") as? String
let indexRect = rect(for: index)
let visibleRect = window!.screen!.visibleFrame
var thumbPoint = NSPoint(x: indexRect.minX + indexRect.width / 2, y: indexRect.minY + indexRect.height / 2)
let viewSize: CGFloat = 312 //[thumbnailView frame].size.width;
let aspect = imageSize.width / imageSize.height
if aspect <= 1 {
imageSize = NSSize(width: aspect * viewSize, height: viewSize)
} else {
imageSize = NSSize(width: viewSize, height: viewSize / aspect)
}
if thumbPoint.y + imageSize.height / 2 > visibleRect.maxY {
thumbPoint.y = visibleRect.maxY - imageSize.height / 2
}
else if thumbPoint.y - imageSize.height / 2 < visibleRect.minY {
thumbPoint.y = visibleRect.minY + imageSize.height / 2
}
if thumbPoint.x + imageSize.width / 2 > visibleRect.maxX {
thumbPoint.x = visibleRect.maxX - imageSize.width / 2
} else if thumbPoint.x - imageSize.width / 2 < visibleRect.minX {
thumbPoint.x = visibleRect.minX + imageSize.width / 2
}
thumbPoint.x -= imageSize.width / 2
thumbPoint.y -= imageSize.height / 2
(thumbnailView.window as! TSSTInfoWindow).setFrame(NSRect(origin: thumbPoint, size: imageSize), display: false, animate: false)
window?.addChildWindow(thumbnailView.window!, ordered: .above)
}
override func mouseDown(with theEvent: NSEvent) {
if let hoverIndex = hoverIndex, hoverIndex < (pageController.content! as AnyObject).count && hoverIndex >= 0 {
pageController.setSelectionIndex(hoverIndex)
}
window?.orderOut(self)
}
override func keyDown(with theEvent: NSEvent) {
guard let chars = theEvent.charactersIgnoringModifiers else {
return
}
if let nsChar = chars.utf16.first, nsChar == 27 {
(window!.windowController! as! TSSTSessionWindowController).killTopOptionalUIElement()
}
}
}
| mit | 16dd20c22cdb720340f0a0a33f82772c | 32.502439 | 162 | 0.71258 | 3.562241 | false | false | false | false |
RaviDesai/RSDRestServices | Example/Tests/MockedRESTCalls.swift | 1 | 10232 | //
// MockedRESTCalls.swift
// CEVFoundation
//
// Created by Ravi Desai on 4/29/15.
// Copyright (c) 2015 CEV. All rights reserved.
//
import Foundation
import OHHTTPStubs
import RSDRESTServices
import RSDSerialization
class MockedRESTCalls {
static var id0 = NSUUID()
static var id1 = NSUUID()
static var id2 = NSUUID()
static var id3 = NSUUID()
static var id4 = NSUUID()
static func sampleITunesResultData() -> NSData {
let bundle : NSBundle = NSBundle(forClass: self)
let path = bundle.pathForResource("iTunesResults", ofType: "json")!
let content = NSData(contentsOfFile: path)
return content!;
}
static func sampleUsers() -> [User] {
return [User(id: id0, prefix: "Sir", first: "David", middle: "Jon", last: "Gilmour", suffix: "CBE", friends: nil),
User(id: id1, prefix: nil, first: "Roger", middle: nil, last: "Waters", suffix: nil, friends: nil),
User(id: id2, prefix: "Sir", first: "Bob", middle: nil, last: "Geldof", suffix: "KBE", friends: nil),
User(id: id3, prefix: "Mr", first: "Nick", middle: "Berkeley", last: "Mason", suffix: nil, friends: nil),
User(id: id4, prefix: "", first: "Richard", middle: "William", last: "Wright", suffix: "", friends: nil)]
}
static func sampleUsersData() -> NSData {
let jsonArray = MockedRESTCalls.sampleUsers().convertToJSONArray()
return try! NSJSONSerialization.dataWithJSONObject(jsonArray, options: NSJSONWritingOptions.PrettyPrinted)
}
class func hijackITunesSearch() {
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != "itunes.apple.com") { return false; }
if (request.URL?.path != "/search") { return false; }
return true;
}, withStubResponse: { (request) -> OHHTTPStubsResponse in
let data = self.sampleITunesResultData()
return OHHTTPStubsResponse(data: data, statusCode: 200, headers: ["Content-Type": "application/json"])
})
}
class func hijackUserGetAll() {
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != .Some("com.desai")) { return false }
if (request.URL?.path != .Some("/api/Users")) { return false }
if (request.HTTPMethod != "GET") { return false }
if (request.URL?.query != nil) { return false }
return true
}) { (request) -> OHHTTPStubsResponse in
let data = sampleUsersData()
return OHHTTPStubsResponse(data: data, statusCode: 200, headers: ["Content-Type": "application/json"])
}
}
class func hijackUserGetMatching() {
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != .Some("com.desai")) { return false }
if (request.URL?.path != .Some("/api/Users")) { return false }
if (request.HTTPMethod != "GET") { return false }
if (request.URL?.query == nil) { return false }
return true
}) { (request) -> OHHTTPStubsResponse in
var query = request.URL!.absoluteString
query = query.stringByRemovingPercentEncoding!
let comp = NSURLComponents(string: query)
let items = comp!.queryItems!
var users = sampleUsers()
for item in items {
users = users.filter {
switch(item.name.lowercaseString) {
case "prefix": return $0.prefix == item.value
case "first": return $0.first == item.value
case "middle": return $0.middle == item.value
case "last": return $0.last == item.value
case "suffix": return $0.prefix == item.value
default: return false
}
}
}
let jsonArray = users.convertToJSONArray()
if let data = try? NSJSONSerialization.dataWithJSONObject(jsonArray, options: NSJSONWritingOptions.PrettyPrinted) {
return OHHTTPStubsResponse(data: data, statusCode: 200, headers: ["Content-Type": "application/json"])
}
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 500, headers: nil)
}
}
class func hijackUserPost() {
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != .Some("com.desai")) { return false }
if (request.URL?.path != .Some("/api/Users")) { return false }
if (request.HTTPMethod != "POST") { return false }
if (request.URL?.query != nil) { return false }
return true
}) { (request) -> OHHTTPStubsResponse in
if let data = NSURLProtocol.propertyForKey("PostedData", inRequest: request) as? NSData {
if let json: JSON = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) {
if let newUser = User.createFromJSON(json) {
let found = sampleUsers().filter { $0 == newUser }.first
if found == nil {
var returnUser = newUser
returnUser.id = NSUUID()
if let resultData = try? NSJSONSerialization.dataWithJSONObject(returnUser.convertToJSON(), options: NSJSONWritingOptions.PrettyPrinted) {
return OHHTTPStubsResponse(data: resultData, statusCode: 200, headers: ["Content-Type": "application/json"])
} else {
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 500, headers: nil)
}
} else {
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 409, headers: nil)
}
}
}
}
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 422, headers: nil)
}
}
class func hijackUserPut() {
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != .Some("com.desai")) { return false }
if (request.URL?.path != .Some("/api/Users")) { return false }
if (request.HTTPMethod != "PUT") { return false }
if (request.URL?.query != nil) { return false }
return true
}) { (request) -> OHHTTPStubsResponse in
if let data = NSURLProtocol.propertyForKey("PostedData", inRequest: request) as? NSData {
if let json: JSON = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) {
if let newUser = User.createFromJSON(json) {
if (newUser.id == nil) {
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 404, headers: nil)
}
let found = sampleUsers().filter { $0 == newUser }.first
if found != nil {
if let resultData = try? NSJSONSerialization.dataWithJSONObject(newUser.convertToJSON(), options: NSJSONWritingOptions.PrettyPrinted) {
return OHHTTPStubsResponse(data: resultData, statusCode: 200, headers: ["Content-Type": "application/json"])
} else {
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 500, headers: nil)
}
} else {
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 404, headers: nil)
}
}
}
}
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 422, headers: nil)
}
}
class func hijackUserDelete() {
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
if (request.URL?.host != .Some("com.desai")) { return false }
if (request.URL?.path != .Some("/api/Users")) { return false }
if (request.HTTPMethod != "DELETE") { return false }
if (request.URL?.query != nil) { return false }
return true
}) { (request) -> OHHTTPStubsResponse in
if let data = NSURLProtocol.propertyForKey("PostedData", inRequest: request) as? NSData {
if let json: JSON = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) {
if let newUser = User.createFromJSON(json) {
if (newUser.id == nil) {
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 404, headers: nil)
}
let found = sampleUsers().filter { $0 == newUser }.first
if found != nil {
if let resultData = try? NSJSONSerialization.dataWithJSONObject(newUser.convertToJSON(), options: NSJSONWritingOptions.PrettyPrinted) {
return OHHTTPStubsResponse(data: resultData, statusCode: 200, headers: ["Content-Type": "application/json"])
} else {
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 500, headers: nil)
}
} else {
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 404, headers: nil)
}
}
}
}
return OHHTTPStubsResponse(JSONObject: JSONDictionary(), statusCode: 422, headers: nil)
}
}
} | mit | a5239de486cef3a662f64786744ae764 | 51.209184 | 167 | 0.544468 | 5.266083 | false | false | false | false |
OscarSwanros/swift | benchmark/single-source/DictionaryGroup.swift | 5 | 1619 | //===--- DictionaryGroup.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let DictionaryGroup = [
BenchmarkInfo(name: "DictionaryGroup", runFunction: run_DictionaryGroup, tags: [.validation, .api, .Dictionary]),
BenchmarkInfo(name: "DictionaryGroupOfObjects", runFunction: run_DictionaryGroupOfObjects, tags: [.validation, .api, .Dictionary]),
]
let count = 10_000
let result = count / 10
@inline(never)
public func run_DictionaryGroup(_ N: Int) {
for _ in 1...N {
let dict = Dictionary(grouping: 0..<count, by: { $0 % 10 })
CheckResults(dict.count == 10)
CheckResults(dict[0]!.count == result)
}
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_DictionaryGroupOfObjects(_ N: Int) {
let objects = (0..<count).map { Box($0) }
for _ in 1...N {
let dict = Dictionary(grouping: objects, by: { Box($0.value % 10) })
CheckResults(dict.count == 10)
CheckResults(dict[Box(0)]!.count == result)
}
}
| apache-2.0 | 82852bcd065ce10dddd61128220aa043 | 27.910714 | 133 | 0.615195 | 3.939173 | false | false | false | false |
yulingtianxia/Spiral | Spiral/Rope.swift | 1 | 1001 | //
// Rope.swift
// Spiral
//
// Created by 杨萧玉 on 14-10-11.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import SpriteKit
class Rope: SKSpriteNode {
let maxLength:CGFloat
let fixWidth:CGFloat = 5
init(length:CGFloat) {
let texture = SKTexture(imageNamed: "rope")
maxLength = texture.size().height / (texture.size().width / fixWidth)
let size = CGSize(width: fixWidth, height: min(length,maxLength))
super.init(texture: SKTexture(rect: CGRect(origin: CGPoint.zero, size: CGSize(width: 1, height: min(length / maxLength, 1))), in: texture),color:SKColor.clear, size: size)
// normalTexture = texture?.textureByGeneratingNormalMapWithSmoothness(0.5, contrast: 0.5)
// lightingBitMask = playerLightCategory|killerLightCategory|scoreLightCategory|shieldLightCategory|reaperLightCategory
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 810a6c74f94f1fd34ae81c3784c02956 | 35.555556 | 179 | 0.684904 | 3.901186 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Services/Constants/ApiParam.swift | 1 | 1513 | import Foundation
struct ApiParam {
static let PAYER_ACCESS_TOKEN = "access_token"
static let PUBLIC_KEY = "public_key"
static let BIN = "bin"
static let AMOUNT = "amount"
static let TRANSACTION_AMOUNT = "transaction_amount"
static let ISSUER_ID = "issuer.id"
static let PAYMENT_METHOD_ID = "payment_method_id"
static let PROCESSING_MODES = "processing_modes"
static let PAYMENT_TYPE = "payment_type"
static let API_VERSION = "api_version"
static let SITE_ID = "site_id"
static let CUSTOMER_ID = "customer_id"
static let EMAIL = "email"
static let DEFAULT_PAYMENT_METHOD = "default_payment_method"
static let EXCLUDED_PAYMENT_METHOD = "excluded_payment_methods"
static let EXCLUDED_PAYMET_TYPES = "excluded_payment_types"
static let DIFFERENTIAL_PRICING_ID = "differential_pricing_id"
static let DEFAULT_INSTALLMENTS = "default_installments"
static let MAX_INSTALLMENTS = "max_installments"
static let MARKETPLACE = "marketplace"
static let PRODUCT_ID = "product_id"
static let LABELS = "labels"
static let CHARGES = "charges"
static let PAYMENT_IDS = "payment_ids"
static let PAYMENT_METHODS_IDS = "payment_methods_ids"
static let PLATFORM = "platform"
static let CAMPAIGN_ID = "campaign_id"
static let FLOW_NAME = "flow_name"
static let MERCHANT_ORDER_ID = "merchant_order_id"
static let IFPE = "ifpe"
static let PREF_ID = "pref_id"
static let PAYMENT_TYPE_ID = "payment_type_id"
}
| mit | 8ccca95384ce25495037900122976eed | 41.027778 | 67 | 0.69729 | 3.470183 | false | false | false | false |
KempinGe/LiveBroadcast | LIveBroadcast/LIveBroadcast/classes/Home/ViewModel/BaseViewModel.swift | 1 | 926 | //
// BaseViewModel.swift
// LIveBroadcast
//
// Created by KempinGe on 2016/12/13.
// Copyright © 2016年 盖凯宾. All rights reserved.
//
import UIKit
class BaseViewModel {
var gameModels : [GKBAllGameModel] = [GKBAllGameModel]()
func reloadData(URL: String, parameters : [String : Any]? = nil, finishedCallBack : @escaping () ->()) {
GKBNetworkTool.request(type: .GET, URL: URL, parameters: parameters, finishBlock: { (result) in
guard let resultData = result as? [String : Any] else { return }
guard let dataArray = resultData["data"] as? [[String : Any]] else {return}
for dict in dataArray {
let gameModel = GKBAllGameModel(dict: dict)
self.gameModels.append(gameModel)
}
GKBLog(message: self.gameModels.count)
finishedCallBack()
})
}
}
| mit | 0b9ce137dcce165211f8f2b5c55b0672 | 29.566667 | 108 | 0.581243 | 4.225806 | false | false | false | false |
Instagram/IGListKit | Examples/Examples-iOS/IGListKitExamples/Views/RemoveCell.swift | 1 | 1580 | /*
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import UIKit
protocol RemoveCellDelegate: class {
func removeCellDidTapButton(_ cell: RemoveCell)
}
final class RemoveCell: UICollectionViewCell {
weak var delegate: RemoveCellDelegate?
private lazy var label: UILabel = {
let label = UILabel()
label.backgroundColor = .clear
self.contentView.addSubview(label)
return label
}()
fileprivate lazy var button: UIButton = {
let button = UIButton(type: .custom)
button.setTitle("Remove", for: UIControl.State())
button.setTitleColor(.blue, for: UIControl.State())
button.backgroundColor = .clear
button.addTarget(self, action: #selector(RemoveCell.onButton(_:)), for: .touchUpInside)
self.contentView.addSubview(button)
return button
}()
var text: String? {
get {
return label.text
}
set {
label.text = newValue
}
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.backgroundColor = UIColor.background
let bounds = contentView.bounds
let divide = bounds.divided(atDistance: 100, from: .maxXEdge)
label.frame = divide.slice.insetBy(dx: 15, dy: 0)
button.frame = divide.remainder
}
@objc func onButton(_ button: UIButton) {
delegate?.removeCellDidTapButton(self)
}
}
| mit | 3172d80b151f6837321866f7e6ae0ffd | 26.719298 | 95 | 0.639241 | 4.593023 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Core/TileAvailability.swift | 1 | 17782 | //
// TileAvailability.swift
// CesiumKit
//
// Created by Ryan Walklin on 30/4/17.
// Copyright © 2017 Test Toast. All rights reserved.
//
import Foundation
class TileAvailability {
private let _tilingScheme: TilingScheme
private let _maximumLevel: Int
private var _rootNodes = [QuadtreeNode]()
/**
* Reports the availability of tiles in a {@link TilingScheme}.
*
* @alias TileAvailability
* @constructor
*
* @param {TilingScheme} tilingScheme The tiling scheme in which to report availability.
* @param {Number} maximumLevel The maximum tile level that is potentially available.
*/
init (tilingScheme: TilingScheme, maximumLevel: Int) {
_tilingScheme = tilingScheme
_maximumLevel = maximumLevel
for y in 0..<tilingScheme.numberOfXTilesAt(level: 0) {
for x in 0..<tilingScheme.numberOfYTilesAt(level: 0) {
_rootNodes.append(QuadtreeNode(tilingScheme: tilingScheme, parent: nil, level: 0, x: x, y: y))
}
}
}
/**
* Marks a rectangular range of tiles in a particular level as being available. For best performance,
* add your ranges in order of increasing level.
*
* @param {Number} level The level.
* @param {Number} startX The X coordinate of the first available tiles at the level.
* @param {Number} startY The Y coordinate of the first available tiles at the level.
* @param {Number} endX The X coordinate of the last available tiles at the level.
* @param {Number} endY The Y coordinate of the last available tiles at the level.
*/
func addAvailableTileRange (level: Int, startX: Int, startY: Int, endX: Int, endY: Int) {
let startRectangle = _tilingScheme.tileXYToRectangle(x: startX, y: startY, level: level)
let west = startRectangle.west
let north = startRectangle.north
let endRectangle = _tilingScheme.tileXYToRectangle(x: endX, y: endY, level: level)
let east = endRectangle.east
let south = endRectangle.south
let rectangleWithLevel =
RectangleWithLevel(
level: level,
west: west,
south: south,
east: east,
north: north
)
for rootNode in _rootNodes {
if rectanglesOverlap(rectangle1: rootNode.extent, rectangle2: rectangleWithLevel) {
putRectangleInQuadtree(maxDepth: _maximumLevel, node: rootNode, rectangle: rectangleWithLevel)
}
}
};
/*
/**
+ * Determines the level of the most detailed tile covering the position. This function
+ * usually completes in time logarithmic to the number of rectangles added with
+ * {@link TileAvailability#addAvailableTileRange}.
+ *
+ * @param {Cartographic} position The position for which to determine the maximum available level. The height component is ignored.
+ * @return {Number} The level of the most detailed tile covering the position.
+ * @throws {DeveloperError} If position is outside any tile according to the tiling scheme.
+ */
+ TileAvailability.prototype.computeMaximumLevelAtPosition = function(position) {
+ // Find the root node that contains this position.
+ var node;
+ for (var nodeIndex = 0; nodeIndex < this._rootNodes.length; ++nodeIndex) {
+ var rootNode = this._rootNodes[nodeIndex];
+ if (rectangleContainsPosition(rootNode.extent, position)) {
+ node = rootNode;
+ break;
+ }
+ }
+
+ //>>includeStart('debug', pragmas.debug);
+ if (!defined(node)) {
+ throw new DeveloperError('The specified position does not exist in any root node of the tiling scheme.');
+ }
+ //>>includeEnd('debug');
+
+ return findMaxLevelFromNode(undefined, node, position);
+ };
+
+ var rectanglesScratch = [];
+ var remainingToCoverByLevelScratch = [];
+ var westScratch = new Rectangle();
+ var eastScratch = new Rectangle();
+
+ /**
+ * Finds the most detailed level that is available _everywhere_ within a given rectangle. More detailed
+ * tiles may be available in parts of the rectangle, but not the whole thing. The return value of this
+ * function may be safely passed to {@link sampleTerrain} for any position within the rectangle. This function
+ * usually completes in time logarithmic to the number of rectangles added with
+ * {@link TileAvailability#addAvailableTileRange}.
+ *
+ * @param {Rectangle} rectangle The rectangle.
+ * @return {Number} The best available level for the entire rectangle.
+ */
+ TileAvailability.prototype.computeBestAvailableLevelOverRectangle = function(rectangle) {
+ var rectangles = rectanglesScratch;
+ rectangles.length = 0;
+
+ if (rectangle.east < rectangle.west) {
+ // Rectangle crosses the IDL, make it two rectangles.
+ rectangles.push(Rectangle.fromRadians(-Math.PI, rectangle.south, rectangle.east, rectangle.north, westScratch));
+ rectangles.push(Rectangle.fromRadians(rectangle.west, rectangle.south, Math.PI, rectangle.north, eastScratch));
+ } else {
+ rectangles.push(rectangle);
+ }
+
+ var remainingToCoverByLevel = remainingToCoverByLevelScratch;
+ remainingToCoverByLevel.length = 0;
+
+ var i;
+ for (i = 0; i < this._rootNodes.length; ++i) {
+ updateCoverageWithNode(remainingToCoverByLevel, this._rootNodes[i], rectangles);
+ }
+
+ for (i = remainingToCoverByLevel.length - 1; i >= 0; --i) {
+ if (defined(remainingToCoverByLevel[i]) && remainingToCoverByLevel[i].length === 0) {
+ return i;
+ }
+ }
+
+ return 0;
+ };
+
+ var cartographicScratch = new Cartographic();
+
+ /**
+ * Determines if a particular tile is available.
+ * @param {Number} level The tile level to check.
+ * @param {Number} x The X coordinate of the tile to check.
+ * @param {Number} y The Y coordinate of the tile to check.
+ * @return {Boolean} True if the tile is available; otherwise, false.
+ */
+ TileAvailability.prototype.isTileAvailable = function(level, x, y) {
+ // Get the center of the tile and find the maximum level at that position.
+ // Because availability is by tile, if the level is available at that point, it
+ // is sure to be available for the whole tile. We assume that if a tile at level n exists,
+ // then all its parent tiles back to level 0 exist too. This isn't really enforced
+ // anywhere, but Cesium would never load a tile for which this is not true.
+ var rectangle = this._tilingScheme.tileXYToRectangle(x, y, level, rectangleScratch);
+ Rectangle.center(rectangle, cartographicScratch);
+ return this.computeMaximumLevelAtPosition(cartographicScratch) >= level;
+ };
+
+ /**
+ * Computes a bit mask indicating which of a tile's four children exist.
+ * If a child's bit is set, a tile is available for that child. If it is cleared,
+ * the tile is not available. The bit values are as follows:
+ * <table>
+ * <tr><th>Bit Position</th><th>Bit Value</th><th>Child Tile</th></tr>
+ * <tr><td>0</td><td>1</td><td>Southwest</td></tr>
+ * <tr><td>1</td><td>2</td><td>Southeast</td></tr>
+ * <tr><td>2</td><td>4</td><td>Northwest</td></tr>
+ * <tr><td>3</td><td>8</td><td>Northeast</td></tr>
+ * </table>
+ *
+ * @param {Number} level The level of the parent tile.
+ * @param {Number} x The X coordinate of the parent tile.
+ * @param {Number} y The Y coordinate of the parent tile.
+ * @return {Number} The bit mask indicating child availability.
+ */
+ TileAvailability.prototype.computeChildMaskForTile = function(level, x, y) {
+ var childLevel = level + 1;
+ if (childLevel >= this._maximumLevel) {
+ return 0;
+ }
+
+ var mask = 0;
+
+ mask |= this.isTileAvailable(childLevel, 2 * x, 2 * y + 1) ? 1 : 0;
+ mask |= this.isTileAvailable(childLevel, 2 * x + 1, 2 * y + 1) ? 2 : 0;
+ mask |= this.isTileAvailable(childLevel, 2 * x, 2 * y) ? 4 : 0;
+ mask |= this.isTileAvailable(childLevel, 2 * x + 1, 2 * y) ? 8 : 0;
+
+ return mask;
+ };
+
+
+
+ defineProperties(QuadtreeNode.prototype, {
+ nw: {
+ get: function() {
+ if (!this._nw) {
+ this._nw = new QuadtreeNode(this.tilingScheme, this, this.level + 1, this.x * 2, this.y * 2);
+ }
+ return this._nw;
+ }
+ },
+
+ ne: {
+ get: function() {
+ if (!this._ne) {
+ this._ne = new QuadtreeNode(this.tilingScheme, this, this.level + 1, this.x * 2 + 1, this.y * 2);
+ }
+ return this._ne;
+ }
+ },
+
+ sw: {
+ get: function() {
+ if (!this._sw) {
+ this._sw = new QuadtreeNode(this.tilingScheme, this, this.level + 1, this.x * 2, this.y * 2 + 1);
+ }
+ return this._sw;
+ }
+ },
+
+ se: {
+ get: function() {
+ if (!this._se) {
+ this._se = new QuadtreeNode(this.tilingScheme, this, this.level + 1, this.x * 2 + 1, this.y * 2 + 1);
+ }
+ return this._se;
+ }
+ }
+ });
*/
func rectanglesOverlap (rectangle1: Rectangle, rectangle2: RectangleWithLevel) -> Bool {
let west = max(rectangle1.west, rectangle2.west)
let south = max(rectangle1.south, rectangle2.south)
let east = min(rectangle1.east, rectangle2.east)
let north = min(rectangle1.north, rectangle2.north)
return south < north && west < east
}
func putRectangleInQuadtree(maxDepth: Int, node: QuadtreeNode, rectangle: RectangleWithLevel) {
var node = node
while node.level < maxDepth {
if rectangleFullyContainsRectangle(potentialContainer: node.nw.extent, rectangleToTest: rectangle) {
node = node.nw
} else if (rectangleFullyContainsRectangle(potentialContainer: node.ne.extent, rectangleToTest: rectangle)) {
node = node.ne
} else if (rectangleFullyContainsRectangle(potentialContainer: node.sw.extent, rectangleToTest: rectangle)) {
node = node.sw
} else if (rectangleFullyContainsRectangle(potentialContainer: node.se.extent, rectangleToTest: rectangle)) {
node = node.se
} else {
break
}
}
if node.rectangles.isEmpty || node.rectangles.last!.level <= rectangle.level {
node.rectangles.append(rectangle)
} else {
// Maintain ordering by level when inserting.
var index = node.rectangles.binarySearch(rectangle) { a, b in
return a.level - b.level
}
if (index <= 0) {
index = ~index
}
node.rectangles.insert(rectangle, at: index)
}
}
func rectangleFullyContainsRectangle(potentialContainer: Rectangle, rectangleToTest: RectangleWithLevel) -> Bool {
return rectangleToTest.west >= potentialContainer.west &&
rectangleToTest.east <= potentialContainer.east &&
rectangleToTest.south >= potentialContainer.south &&
rectangleToTest.north <= potentialContainer.north
}
/*
+ function rectangleContainsPosition(potentialContainer, positionToTest) {
+ return positionToTest.longitude >= potentialContainer.west &&
+ positionToTest.longitude <= potentialContainer.east &&
+ positionToTest.latitude >= potentialContainer.south &&
+ positionToTest.latitude <= potentialContainer.north;
+ }
+
+ function findMaxLevelFromNode(stopNode, node, position) {
+ var maxLevel = 0;
+
+ // Find the deepest quadtree node containing this point.
+ while (true) {
+ var nw = node._nw && rectangleContainsPosition(node._nw.extent, position);
+ var ne = node._ne && rectangleContainsPosition(node._ne.extent, position);
+ var sw = node._sw && rectangleContainsPosition(node._sw.extent, position);
+ var se = node._se && rectangleContainsPosition(node._se.extent, position);
+
+ // The common scenario is that the point is in only one quadrant and we can simply
+ // iterate down the tree. But if the point is on a boundary between tiles, it is
+ // in multiple tiles and we need to check all of them, so use recursion.
+ if (nw + ne + sw + se > 1) {
+ if (nw) {
+ maxLevel = Math.max(maxLevel, findMaxLevelFromNode(node, node._nw, position));
+ }
+ if (ne) {
+ maxLevel = Math.max(maxLevel, findMaxLevelFromNode(node, node._ne, position));
+ }
+ if (sw) {
+ maxLevel = Math.max(maxLevel, findMaxLevelFromNode(node, node._sw, position));
+ }
+ if (se) {
+ maxLevel = Math.max(maxLevel, findMaxLevelFromNode(node, node._se, position));
+ }
+ break;
+ } else if (nw) {
+ node = node._nw;
+ } else if (ne) {
+ node = node._ne;
+ } else if (sw) {
+ node = node._sw;
+ } else if (se) {
+ node = node._se;
+ } else {
+ break;
+ }
+ }
+
+ // Work up the tree until we find a rectangle that contains this point.
+ while (node !== stopNode) {
+ var rectangles = node.rectangles;
+
+ // Rectangles are sorted by level, lowest first.
+ for (var i = rectangles.length - 1; i >= 0 && rectangles[i].level > maxLevel; --i) {
+ var rectangle = rectangles[i];
+ if (rectangleContainsPosition(rectangle, position)) {
+ maxLevel = rectangle.level;
+ }
+ }
+
+ node = node.parent;
+ }
+
+ return maxLevel;
+ }
+
+ function updateCoverageWithNode(remainingToCoverByLevel, node, rectanglesToCover) {
+ if (!node) {
+ return;
+ }
+
+ var i;
+ var anyOverlap = false;
+ for (i = 0; i < rectanglesToCover.length; ++i) {
+ anyOverlap = anyOverlap || rectanglesOverlap(node.extent, rectanglesToCover[i]);
+ }
+
+ if (!anyOverlap) {
+ // This node is not applicable to the rectangle(s).
+ return;
+ }
+
+ var rectangles = node.rectangles;
+ for (i = 0; i < rectangles.length; ++i) {
+ var rectangle = rectangles[i];
+
+ if (!remainingToCoverByLevel[rectangle.level]) {
+ remainingToCoverByLevel[rectangle.level] = rectanglesToCover;
+ }
+
+ remainingToCoverByLevel[rectangle.level] = subtractRectangle(remainingToCoverByLevel[rectangle.level], rectangle);
+ }
+
+ // Update with child nodes.
+ updateCoverageWithNode(remainingToCoverByLevel, node._nw, rectanglesToCover);
+ updateCoverageWithNode(remainingToCoverByLevel, node._ne, rectanglesToCover);
+ updateCoverageWithNode(remainingToCoverByLevel, node._sw, rectanglesToCover);
+ updateCoverageWithNode(remainingToCoverByLevel, node._se, rectanglesToCover);
+ }
+
+ function subtractRectangle(rectangleList, rectangleToSubtract) {
+ var result = [];
+ for (var i = 0; i < rectangleList.length; ++i) {
+ var rectangle = rectangleList[i];
+ if (!rectanglesOverlap(rectangle, rectangleToSubtract)) {
+ // Disjoint rectangles. Original rectangle is unmodified.
+ result.push(rectangle);
+ } else {
+ // rectangleToSubtract partially or completely overlaps rectangle.
+ if (rectangle.west < rectangleToSubtract.west) {
+ result.push(new Rectangle(rectangle.west, rectangle.south, rectangleToSubtract.west, rectangle.north));
+ }
+ if (rectangle.east > rectangleToSubtract.east) {
+ result.push(new Rectangle(rectangleToSubtract.east, rectangle.south, rectangle.east, rectangle.north));
+ }
+ if (rectangle.south < rectangleToSubtract.south) {
+ result.push(new Rectangle(Math.max(rectangleToSubtract.west, rectangle.west), rectangle.south, Math.min(rectangleToSubtract.east, rectangle.east), rectangleToSubtract.south));
+ }
+ if (rectangle.north > rectangleToSubtract.north) {
+ result.push(new Rectangle(Math.max(rectangleToSubtract.west, rectangle.west), rectangleToSubtract.north, Math.min(rectangleToSubtract.east, rectangle.east), rectangle.north));
+ }
+ }
+ }
+
+ return result;
+ }
+
+ return TileAvailability;
+});
*/
}
| apache-2.0 | 63d10f42f2452f0490f168bf136797b2 | 41.640288 | 197 | 0.576289 | 3.983199 | false | false | false | false |
3drobotics/SwiftIO | Sources/Address+Interfaces.swift | 2 | 1186 | //
// Address+Interfaces.swift
// SwiftIO
//
// Created by Jonathan Wight on 3/18/16.
// Copyright © 2016 schwa.io. All rights reserved.
//
import Darwin
public extension Address {
static func addressesForInterfaces() throws -> [String: [Address]] {
let addressesForInterfaces = getAddressesForInterfaces() as! [String: [NSData]]
let pairs: [(String, [Address])] = addressesForInterfaces.flatMap() {
(interface, addressData) -> (String, [Address])? in
if addressData.count == 0 {
return nil
}
let addresses = addressData.map() {
(addressData: NSData) -> Address in
let addr = sockaddr_storage(addr: UnsafePointer <sockaddr> (addressData.bytes), length: addressData.length)
let address = Address(sockaddr: addr)
return address
}
return (interface, addresses.sort(<))
}
return Dictionary <String, [Address]> (pairs)
}
}
// MARK: -
private extension Dictionary {
init(_ pairs: [Element]) {
self.init()
for (k, v) in pairs {
self[k] = v
}
}
}
| mit | 7367b846e3a46a2e8ceecd065e823fea | 27.214286 | 123 | 0.566245 | 4.277978 | false | false | false | false |
haskellswift/swift-package-manager | Sources/Utility/misc.swift | 1 | 1430 | /*
This source file is part of the Swift.org open source project
Copyright 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// Get clang's version from the given version output string on Ubuntu.
public func getClangVersion(versionOutput: String) -> (major: Int, minor: Int)? {
// Clang outputs version in this format on Ubuntu:
// Ubuntu clang version 3.6.0-2ubuntu1~trusty1 (tags/RELEASE_360/final) (based on LLVM 3.6.0)
let versionStringPrefix = "Ubuntu clang version "
let versionStrings = versionOutput.utf8.split(separator: UInt8(ascii: "-")).flatMap(String.init)
guard let clangVersionString = versionStrings.first,
clangVersionString.hasPrefix(versionStringPrefix) else {
return nil
}
let versionStartIndex = clangVersionString.index(clangVersionString.startIndex, offsetBy: versionStringPrefix.utf8.count)
let versionString = clangVersionString[versionStartIndex..<clangVersionString.endIndex]
// Split major minor patch etc.
let versions = versionString.utf8.split(separator: UInt8(ascii: ".")).flatMap(String.init)
guard versions.count > 1, let major = Int(versions[0]), let minor = Int(versions[1]) else {
return nil
}
return (major, minor)
}
| apache-2.0 | cc519ea8f7072756c4d75f10dc758bbf | 48.310345 | 125 | 0.738462 | 4.156977 | false | false | false | false |
kildevaeld/File | Pod/Classes/Bytes/FileReadableStream+Bytes.swift | 1 | 1707 |
import Darwin
import Bytes
extension ReadableFileStream: CollectionType {
public typealias Generator = IndexingGenerator<ReadableFileStream>
public typealias Element = UInt8
public typealias Index = Int
public var startIndex: Index {
return 0
}
public var endIndex: Index {
return self.count
}
/*public subscript(i: Index) -> UInt8 {
get {
return self.read(i)
} set (value) {
self[i] = value
}
}*/
public func generate() -> Generator {
return IndexingGenerator(self)
}
}
extension ReadableFileStream: ReadableBytesType {
public func read(buffer: UnsafeMutablePointer<UInt8>, index: Int, to: Int) -> Int {
let prev = self.tell
self.seek(index, whence: .Start)
let diff = to - index
let ret = self.read(buffer, length: diff)
self.seek(prev, whence: .Start)
return ret
}
public func read(index: Int) -> UInt8 {
self.read(index)!.first!
}
public func read(index: Int, to: Int) -> ReadableBytesSlice? {
if to > self.size { return nil }
let pos = SlicePosition(index: index, to:to)
}
}
extension ReadableFileStream: Sliceable {
public typealias SubSlice = Bytes
public subscript(i: Range<Index>) -> ReadableBytesSlice? {
let prev = self.tell
self.seek(i.startIndex, whence: .Start)
let diff = i.endIndex - i.startIndex
let bytes = Bytes(count: diff)
self.read(bytes.buffer, length: diff)
self.seek(prev, whence: .Start)
return bytes
}
} | mit | 205d5389d7ad9c6cfe44bebabe2280b5 | 22.722222 | 87 | 0.577622 | 4.321519 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Controllers/Auth/RegisterUsernameTableViewController.swift | 1 | 4296 | //
// RegisterUsernameTableViewController.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 04/03/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
import SwiftyJSON
final class RegisterUsernameTableViewController: BaseTableViewController {
internal var requesting = false
var serverPublicSettings: AuthSettings?
@IBOutlet weak var textFieldUsername: UITextField!
@IBOutlet weak var registerButton: StyledButton!
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
if let serverURL = AuthManager.selectedServerInformation()?[ServerPersistKeys.serverURL], let url = URL(string: serverURL) {
navigationItem.title = url.host
} else {
navigationItem.title = SocketManager.sharedInstance.serverURL?.host
}
if let nav = navigationController as? AuthNavigationController {
nav.setGrayTheme()
}
setupAuth()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textFieldUsername.becomeFirstResponder()
}
func startLoading() {
DispatchQueue.main.async {
self.textFieldUsername.alpha = 0.5
self.requesting = true
self.view.layoutIfNeeded()
self.registerButton.startLoading()
self.textFieldUsername.resignFirstResponder()
}
}
func stopLoading() {
DispatchQueue.main.async {
self.textFieldUsername.alpha = 1
self.requesting = false
self.registerButton.stopLoading()
}
}
// MARK: Request username
func setupAuth() {
let presentGenericSocketError = {
Alert(
title: localized("error.socket.default_error.title"),
message: localized("error.socket.default_error.message")
).present()
}
guard let auth = AuthManager.isAuthenticated() else {
presentGenericSocketError()
return
}
startLoading()
AuthManager.resume(auth) { [weak self] response in
self?.stopLoading()
if response.isError() {
presentGenericSocketError()
} else {
self?.startLoading()
AuthManager.usernameSuggestion { (response) in
self?.stopLoading()
if !response.isError() {
DispatchQueue.main.async {
self?.textFieldUsername.text = response.result["result"].stringValue
}
}
}
}
}
}
@IBAction func didPressedRegisterButton() {
guard !requesting else {
return
}
requestUsername()
}
fileprivate func requestUsername() {
let error = { (errorMessage: String?) in
Alert(
title: localized("error.socket.default_error.title"),
message: errorMessage ?? localized("error.socket.default_error.message")
).present()
}
guard let username = textFieldUsername.text, !username.isEmpty else {
return error(nil)
}
startLoading()
AuthManager.setUsername(textFieldUsername.text ?? "") { [weak self] success, errorMessage in
DispatchQueue.main.async {
self?.stopLoading()
if !success {
error(errorMessage)
} else {
self?.dismiss(animated: true, completion: nil)
AppManager.reloadApp()
}
}
}
}
}
extension RegisterUsernameTableViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return !requesting
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if !requesting {
requestUsername()
}
return true
}
}
// MARK: Disable Theming
extension RegisterUsernameTableViewController {
override func applyTheme() { }
}
| mit | 17e55300f6ad3b9eee61e798df5cf21f | 26.88961 | 132 | 0.581141 | 5.541935 | false | false | false | false |
Mobilette/AniMee | AniMee/Classes/Modules/Anime/List/Day/User Interface/Cell/AnimeListDayCell.swift | 1 | 1449 | //
// AnimeListDayCell.swift
// AniMee
//
// Created by Benaly Issouf M'sa on 09/02/16.
// Copyright © 2016 Mobilette. All rights reserved.
//
import UIKit
class AnimeListDayCell: UICollectionViewCell {
var name: String = "" {
didSet {
self.animeTitle.text = name
}
}
var season: String = "" {
didSet {
self.animeSeason.text = season
}
}
var number: String = "" {
didSet {
self.episodeNumber.text = number
}
}
var title: String = "" {
didSet {
self.episodeTitle.text = title
}
}
var hour: String = "" {
didSet {
self.releaseHour.text = hour
}
}
var imageURL: NSURL? = nil {
didSet {
self.animeImageView.image = UIImage()
if let url = imageURL {
ImageAPIService.fetchImage(url).then { [unowned self] data -> Void in
self.animeImageView.image = UIImage(data: data)
}
}
}
}
// MARK: - Outlet
@IBOutlet private weak var animeTitle: UILabel!
@IBOutlet private weak var animeSeason: UILabel!
@IBOutlet private weak var episodeNumber: UILabel!
@IBOutlet private weak var episodeTitle: UILabel!
@IBOutlet private weak var releaseHour: UILabel!
@IBOutlet private weak var animeImageView: UIImageView!
}
| mit | ff38748c32156f75cd9744f14768daa2 | 22.354839 | 85 | 0.547652 | 4.441718 | false | false | false | false |
CoderXiaoming/Ronaldo | SaleManager/SaleManager/Stock/Controller/SAMStockViewController.swift | 1 | 71177 | //
// SAMStockViewController.swift
// SaleManager
//
// Created by apple on 16/11/9.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
import MJRefresh
import Speech
import MBProgressHUD
///控制器类型
enum stockControllerType {
case normal //常规
case requestStock //查询库存
case requestBuildOrder //创建订单
}
///刚是否成功上传成功图片
var SAMStockHasUnloadProductImage = false
///产品cell重用标识符
private let SAMStockProductCellReuseIdentifier = "SAMStockProductCellReuseIdentifier"
///产品cell正常状态size
private let SAMStockProductCellNormalSize = CGSize(width: ScreenW, height: SAMStockProductCellNormalHeight)
class SAMStockViewController: UIViewController {
///对外提供的类工厂方法
class func instance(shoppingCarListModel: SAMShoppingCarListModel?, QRCodeScanStr: String?, type: stockControllerType) ->SAMStockViewController {
let vc = SAMStockViewController()
//判断控制器类型
switch type {
case .normal:
//监听来自二维码扫描界面的通知
NotificationCenter.default.addObserver(vc, selector: #selector(SAMStockViewController.receiveProductNameFromQRCodeView(notification:)), name: NSNotification.Name.init(SAMQRCodeViewGetProductNameNotification), object: nil)
return vc
case .requestStock:
//购物车数据模型
vc.shoppingCarListModel = shoppingCarListModel
//当前有外部查询请求
vc.hasOutRequest = true
//当前不可以操作产品Cell
vc.couldOperateCell = false
return vc
case .requestBuildOrder:
//记录控制器状态
vc.isFromBuildOrder = true
if QRCodeScanStr != nil {
//当前有外部查询请求
vc.hasOutRequest = true
vc.productNameSearchStr = QRCodeScanStr!
}
return vc
}
}
//MARK: - viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
//初始化UI
setupBasicUI()
//设置导航栏右边按钮
setupRightNavBarItem()
//设置展示库存的collectionView
setupCollectionView()
//设置一般监听
setupNormalMonitorNotification()
//设置长按手势
setupSpeechRecognizer()
}
///初始化UI
fileprivate func setupBasicUI() {
//设置标题
navigationItem.title = "库存查询"
//设置textField监听方法
productNameTF.addTarget(self, action: #selector(SAMStockViewController.textFieldDidEditChange(_:)), for: .editingChanged)
}
///设置导航栏右边按钮
fileprivate func setupRightNavBarItem() {
let conSearchBtn = UIButton()
conSearchBtn.setImage(UIImage(named: "nameScan_nav"), for: UIControlState())
conSearchBtn.sizeToFit()
conSearchBtn.addTarget(self, action: #selector(SAMStockViewController.searchBtnClick), for: .touchUpInside)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: conSearchBtn)
}
///初始化collectionView
fileprivate func setupCollectionView() {
//注册cell
collectionView.register(UINib(nibName: "SAMStockProductCell", bundle: nil), forCellWithReuseIdentifier: SAMStockProductCellReuseIdentifier)
//设置上拉下拉
collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(SAMStockViewController.loadConSearchNewInfo))
collectionView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(SAMStockViewController.loadConSearchMoreInfo))
//没有数据自动隐藏footer
collectionView.mj_footer.isAutomaticallyHidden = true
//隐藏滑动条
collectionView.showsVerticalScrollIndicator = false
}
///设置一般通知监听
fileprivate func setupNormalMonitorNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(SAMStockViewController.receiveStockDetailVCDismissNotification), name: NSNotification.Name.init(SAMStockDetailControllerDismissSuccessNotification), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SAMStockViewController.receiveStockConSearchVCDismissNotification), name: NSNotification.Name.init(SAMStockConSearchControllerDismissSuccessNotification), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SAMStockViewController.receiveSpeechSearch(notification:)), name: NSNotification.Name.init(SAMStockConSearchControllerSpeechSuccessNotification), object: nil)
}
//MARK: - 接收到通知调用的方法
///从产品详情控制器收到通知调用的方法
func receiveStockDetailVCDismissNotification() {
stockDetailVC = nil
}
///从产品条件搜索控制器收到通知调用的方法
func receiveStockConSearchVCDismissNotification() {
conditionalSearchVC = nil
}
///从二维码扫描界面收到通知调用的方法
func receiveProductNameFromQRCodeView(notification: Notification) {
//获取产品名
let productIDName = notification.userInfo!["productIDName"] as! String
//记录获取到的搜索字符串
productNameSearchStr = productIDName
//记录控制器状态
hasOutRequest = true
}
///从语音识别收到通知调用的方法
func receiveSpeechSearch(notification: Notification) {
productNameSearchStr = notification.userInfo!["searchString"] as! String
productNameTF.text = productNameSearchStr
collectionView.mj_header.beginRefreshing()
}
//MARK: - 设置语音识别
fileprivate func setupSpeechRecognizer() {
//设置语音识别按钮
if #available(iOS 10.0, *) {
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(SAMStockViewController.longPressView(longPress:)))
view.addGestureRecognizer(longPress)
}
}
//MARK: - viewDidAppear
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
noOrdercountPSearchAlertVCIsShowing = false
//判断是否刚上传图片成功 或者是否有外界请求,如果有则触发下拉刷新。
if SAMStockHasUnloadProductImage || hasOutRequest {
collectionView.mj_header.beginRefreshing()
if hasOutRequest { //如果有外界请求,赋值产品名搜索文本框
//赋值文本框
productNameTF.text = productNameSearchStr
}
}
}
//MARK: - 搜索按钮点击
func searchBtnClick() {
//判断当前是产品名搜索状态还是条件搜索状态
if productNameTF.hasText {
//退出编辑
endProductNameTFEditing(false)
//开始搜索
collectionView.mj_header.beginRefreshing()
}else { //条件搜索状态
//清空产品名文本框,退出编辑
endProductNameTFEditing(true)
//创建条件搜索界面,并展示
conditionalSearchVC = SAMStockConditionalSearchController.instance()
conditionalSearchVC!.transitioningDelegate = self
conditionalSearchVC!.modalPresentationStyle = UIModalPresentationStyle.custom
conditionalSearchVC!.setCompletionCallback({[weak self] (parameters) in
//赋值数据模型
self!.conSearchParameters = parameters
//计算动画所需数据
let originalFrame = self!.view.convert(self!.conditionalSearchVC!.view.frame, from: self!.conditionalSearchVC!.view)
let originalCenterY = (originalFrame.maxY - originalFrame.origin.y) * 0.5
let transformY = self!.collectionView.frame.origin.y - originalCenterY - 15
//动画隐藏界面
UIView.animate(withDuration: 0.3, animations: {
let transform = CGAffineTransform(translationX: 0, y: transformY)
self!.conditionalSearchVC!.view.transform = transform.scaledBy(x: 0.0001, y: 0.0001)
}, completion: { (_) in
//恢复界面形变,刷新数据
self!.conditionalSearchVC!.dismiss(animated: true, completion: {
self!.collectionView.mj_header.beginRefreshing()
})
})
})
//展示条件搜索控制器8
present(conditionalSearchVC!, animated: true, completion: nil)
}
}
//MARK: - 长按界面监听方法,调用语音识别
func longPressView(longPress: UILongPressGestureRecognizer) {
if longPress.state == .began {
//退出编辑状态
view.endEditing(true)
//添加麦克风图片
microphoneImageView = UIImageView(image: UIImage(named: "microphone"))
microphoneImageView?.frame = CGRect.zero
microphoneImageView?.frame.size = CGSize(width: ScreenW, height: ScreenW)
microphoneImageView!.center = KeyWindow!.center
KeyWindow!.addSubview(microphoneImageView!)
if #available(iOS 10.0, *) {
LXMSpeechWorker.startRecording()
} else {
// Fallback on earlier versions
}
}
if longPress.state == .ended {
//移除麦克风图片
microphoneImageView?.removeFromSuperview()
microphoneImageView = nil
if #available(iOS 10.0, *) {
LXMSpeechWorker.stopRecording()
} else {
// Fallback on earlier versions
}
}
}
//MARK: - 加载数据
func loadConSearchNewInfo() {
//结束下拉刷新
collectionView.mj_footer.endRefreshing()
//恢复记录状态
SAMStockHasUnloadProductImage = false
hasOutRequest = false
//销毁条件搜索控制器
conditionalSearchVC = nil
//如果是产品名搜索,设置请求参数
if productNameSearchStr != "" {
conSearchParameters = ["productIDName": productNameSearchStr as AnyObject, "minCountM": "0" as AnyObject, "parentID": "-1" as AnyObject, "storehouseID": "-1" as AnyObject]
}
//如果此时conSearchParemeters为空,说明为空搜索名下拉,而且没有之前的搜索条件
if conSearchParameters == nil {
let _ = SAMHUD.showMessage("你想搜什么?", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
collectionView.mj_header.endRefreshing()
return
}
//创建请求参数
conSearchPageIndex = 1
let index = String(format: "%d", conSearchPageIndex)
let size = String(format: "%d", conSearchPageSize)
conSearchParameters!["pageSize"] = size as AnyObject?
conSearchParameters!["pageIndex"] = index as AnyObject?
conSearchParameters!["showAlert"] = false as AnyObject?
//发送请求
SAMNetWorker.sharedNetWorker().get("getStock.ashx", parameters: conSearchParameters!, progress: nil, success: {[weak self] (Task, json) in
//清空原先数据
self!.stockProductModels.removeAllObjects()
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let count = dictArr?.count ?? 0
//判断是否有模型数据
if count == 0 { //没有模型数据
//回主线程提示用户信息
DispatchQueue.main.async(execute: {
let _ = SAMHUD.showMessage("没有数据", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
})
}else { //有数据模型
let arr = SAMStockProductModel.mj_objectArray(withKeyValuesArray: dictArr)!
if arr.count < self!.conSearchPageSize { //设置footer状态,提示用户没有更多信息
//回主线程处理下拉
DispatchQueue.main.async(execute: {
self!.collectionView.mj_footer.endRefreshingWithNoMoreData()
})
}else { //设置pageIndex,可能还有更多信息
self!.conSearchPageIndex += 1
}
self!.stockProductModels.addObjects(from: arr as [AnyObject])
//如果不能操作Cell,赋值状态BOOL变量
if !self!.couldOperateCell {
for obj in self!.stockProductModels {
let model = obj as! SAMStockProductModel
model.couldOperateCell = self!.couldOperateCell
}
}
//当前为购物车传过来查询库存的数据
if self!.shoppingCarListModel != nil {
let model = self!.stockProductModels[0] as! SAMStockProductModel
self!.shoppingCarListModel?.stockCountP = model.countP
self!.shoppingCarListModel?.stockCountM = model.countM
self!.shoppingCarListModel?.thumbUrl = model.thumbUrl1
self!.shoppingCarListModel = nil
}
}
//回主线程
DispatchQueue.main.async(execute: {
//结束上拉
self!.collectionView.mj_header.endRefreshing()
//请求统计数据
self!.calculateStockStatistic()
//刷新数据
self!.collectionView.reloadData()
})
}) {[weak self] (Task, Error) in
//清空条件搜索控制器
self!.conditionalSearchVC = nil
DispatchQueue.main.async(execute: {
//处理上拉
self!.collectionView.mj_header.endRefreshing()
let _ = SAMHUD.showMessage("请检查网络", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
})
}
}
//MARK: - 加载所有库存数据统计
fileprivate func calculateStockStatistic() {
let parameters = ["productIDName": conSearchParameters!["productIDName"], "minCountM": conSearchParameters!["minCountM"], "parentID": conSearchParameters!["parentID"], "storehouseID": conSearchParameters!["storehouseID"]]
SAMNetWorker.sharedNetWorker().get("getStockStatic.ashx", parameters: parameters, progress: nil, success: {[weak self] (Task, Json) in
//获取模型数组
let Json = Json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
self!.totalCountPString = dictArr![0]["totalCountP"] as? String
self!.totalCountMString = dictArr![0]["totalCountM"] as? String
}) {[weak self] (Task, error) in
self!.totalCountPString = "--"
self!.totalCountMString = "---"
}
var staticCountP = 0
var staticCountM = 0.0
for obj in stockProductModels {
let model = obj as! SAMStockProductModel
staticCountP += model.countP
staticCountM += model.countM
}
totalCountPString = String(format: "%d", staticCountP)
totalCountMString = String(format: "%.1f", staticCountM)
}
//MARK: - 加载更多数据
func loadConSearchMoreInfo() {
//结束下拉刷新
collectionView.mj_header.endRefreshing()
//创建请求参数
let index = String(format: "%d", conSearchPageIndex)
conSearchParameters!["pageIndex"] = index as AnyObject?
//发送请求
SAMNetWorker.sharedNetWorker().get("getStock.ashx", parameters: conSearchParameters!, progress: nil, success: {[weak self] (Task, json) in
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let count = dictArr?.count ?? 0
//判断是否有模型数据
if count == 0 { //没有模型数据
DispatchQueue.main.async(execute: {
//提示用户
let _ = SAMHUD.showMessage("没有更多数据", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
//设置footer
self!.collectionView.mj_footer.endRefreshingWithNoMoreData()
})
}else {//有数据模型
let arr = SAMStockProductModel.mj_objectArray(withKeyValuesArray: dictArr)!
//判断是否还有更多数据
if arr.count < self!.conSearchPageSize { //没有更多数据
DispatchQueue.main.async(execute: {
//设置footer状态
self!.collectionView.mj_footer.endRefreshingWithNoMoreData()
})
}else { //可能有更多数据
//设置pageIndex
self!.conSearchPageIndex += 1
DispatchQueue.main.async(execute: {
//处理下拉
self!.collectionView.mj_footer.endRefreshing()
})
}
self!.stockProductModels.addObjects(from: arr as [AnyObject])
//刷新数据
DispatchQueue.main.async(execute: {
self!.collectionView.reloadData()
})
}
}) {[weak self] (Task, Error) in
DispatchQueue.main.async(execute: {
//处理下拉
self!.collectionView.mj_footer.endRefreshing()
let _ = SAMHUD.showMessage("请检查网络", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
})
}
}
//MARK: - 懒加载属性
///条件搜索控制器
fileprivate var conditionalSearchVC: SAMStockConditionalSearchController?
///库存详情控制器
fileprivate var stockDetailVC: SAMStockDetailController?
///条件搜索参数字典
var conSearchParameters: [String: AnyObject]?
///一次数据请求获取的数据最大条数
fileprivate let conSearchPageSize = 15
///当前产品名搜索获取数据的页码
fileprivate var conSearchPageIndex = 1
///当前是否有外界查询请求
fileprivate var hasOutRequest: Bool = false
///当前是否可以操作产品Cell
fileprivate var couldOperateCell: Bool = true
///当前是否为来自创建订单控制器
fileprivate var isFromBuildOrder: Bool = false
///产品名搜索字符串
fileprivate var productNameSearchStr = ""
///购物车穿过来的数据模型
fileprivate var shoppingCarListModel: SAMShoppingCarListModel? {
didSet{
if shoppingCarListModel != nil {
productNameSearchStr = shoppingCarListModel!.productIDName
}
}
}
///库存数据模型数组
fileprivate let stockProductModels = NSMutableArray()
///总匹数字符串
fileprivate var totalCountPString: String? {
didSet{
pishuLabel.text = totalCountPString
}
}
///总米数字符串
fileprivate var totalCountMString: String? {
didSet{
mishuLabel.text = totalCountMString
}
}
///购物车选择控件
fileprivate var productOperationView: SAMProductOperationView?
///展示购物车时,主界面添加的蒙版
fileprivate lazy var productOperationMaskView: UIView = {
let maskView = UIView(frame: UIScreen.main.bounds)
maskView.backgroundColor = UIColor.black
maskView.alpha = 0.0
//添加手势
let tap = UITapGestureRecognizer(target: self, action: #selector(SAMStockViewController.hideProductOperationViewWhenMaskViewDidClick))
maskView.addGestureRecognizer(tap)
return maskView
}()
///添加购物车成功时候的动画layer
fileprivate lazy var productAnimlayer: CALayer? = {
let layer = CALayer()
layer.contentsGravity = kCAGravityResizeAspectFill
layer.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
layer.cornerRadius = 10
layer.masksToBounds = true
layer.position = CGPoint(x: 50, y: ScreenH)
KeyWindow?.layer.addSublayer(layer)
return layer
}()
///添加购物车成功时,layer执行的组动画
fileprivate lazy var groupAnimation: CAAnimationGroup = {
/****************** layer动画路线 ******************/
let pathAnimation = CAKeyframeAnimation(keyPath: "position")
//动画路线
let path = UIBezierPath()
//计算各点
let startPoint = CGPoint(x: 30, y: ScreenH)
let endPoint = CGPoint(x: ScreenW * (3 / 5) + 23, y: ScreenH - 43)
let controlPoint = CGPoint(x: (endPoint.x - startPoint.x) * 0.5, y: (endPoint.y - 250))
//连线
path.move(to: startPoint)
path.addQuadCurve(to: endPoint, controlPoint: controlPoint)
pathAnimation.path = path.cgPath
pathAnimation.rotationMode = kCAAnimationRotateAuto
/****************** layer放大动画 ******************/
let expandAnimation = CABasicAnimation(keyPath: "transform.scale")
expandAnimation.fromValue = 0.5
expandAnimation.toValue = 2
expandAnimation.duration = 0.4
expandAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
/****************** layer缩小动画 ******************/
let narrowAnimation = CABasicAnimation(keyPath: "transform.scale")
narrowAnimation.fromValue = 2
narrowAnimation.toValue = 0.4
narrowAnimation.beginTime = 0.4
narrowAnimation.duration = 0.5
expandAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
let group = CAAnimationGroup()
group.animations = [pathAnimation,expandAnimation,narrowAnimation]
group.duration = 0.79
group.isRemovedOnCompletion = false
group.fillMode = kCAFillModeForwards
group.delegate = self
return group
}()
///话筒图片
fileprivate var microphoneImageView: UIImageView?
///统计匹数订单管理数据模型数组
fileprivate var stockSearchProductName = ""
fileprivate var loadModelSuccess = true
fileprivate let orderMarr1 = NSMutableArray()
fileprivate var orderMarr1DidSet = false
fileprivate let orderMarr2 = NSMutableArray()
fileprivate var orderMarr2DidSet = false
fileprivate let orderMarr3 = NSMutableArray()
fileprivate var orderMarr3DidSet = false
fileprivate let orderMarr4 = NSMutableArray()
fileprivate var orderMarr4DidSet = false
fileprivate let orderMarr5 = NSMutableArray()
fileprivate var orderMarr5DidSet = false
fileprivate let forSaleModels = NSMutableArray()
fileprivate var forSaleModelsDidSet = false
fileprivate let orderManageModels = NSMutableArray()
fileprivate let searchShoppingCarListArr = NSMutableArray()
fileprivate var noOrdercountP = 0
fileprivate var noOrdercountM = 0.0
fileprivate var noOrdercountPSearchIsSuccess = true {
didSet{
if noOrdercountPSearchIsSuccess == false {
noOrderSearchProgressHud!.hide(true)
noOrderSearchProgressHud = nil
}
}
}
fileprivate var noOrdercountPSearchHud: SAMHUD?
fileprivate var noOrdercountPSearchAlertVC: UIAlertController?
fileprivate var noOrdercountPSearchAlertVCIsShowing = false
fileprivate var noOrderSearchProgressHud: SAMHUD?
fileprivate var hudProgress: Float {
get{
return Float(currentOrderSearchCount1 + currentOrderSearchCount2 + currentOrderSearchCount3 + currentOrderSearchCount4 + currentOrderSearchCount5) / Float(self.orderManageModels.count)
}
}
fileprivate var orderArr1DidSet = true
fileprivate let orderManageModels1 = NSMutableArray()
fileprivate let searchShoppingCarListArr1 = NSMutableArray()
fileprivate var currentOrderSearchCount1 = 0 {
didSet{
setHUDProgress()
}
}
fileprivate var noOrdercountP1 = 0
fileprivate var noOrdercountM1 = 0.0
fileprivate var currentOrderCountM1 = 0.0 {
didSet{
noOrdercountM1 += currentOrderCountM1
}
}
fileprivate var currentOrderCountP1 = 0 {
didSet{
if !noOrdercountPSearchIsSuccess {
return
}
if currentOrderCountP1 == -1 {
if noOrdercountPSearchHud != nil {
noOrdercountPSearchHud?.hide(true)
}
let _ = SAMHUD.showMessage("获取订单详情失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
noOrdercountPSearchIsSuccess = false
}else {
noOrdercountP1 += currentOrderCountP1
if currentOrderSearchCount1 == orderManageModels1.count {
orderArr1DidSet = true
getOrderDetail()
}else {
let model = orderManageModels1[currentOrderSearchCount1] as! SAMOrderModel
loadOrderDetailArr1(orderModel: model)
}
}
}
}
fileprivate var orderArr2DidSet = true
fileprivate let orderManageModels2 = NSMutableArray()
fileprivate let searchShoppingCarListArr2 = NSMutableArray()
fileprivate var currentOrderSearchCount2 = 0 {
didSet{
setHUDProgress()
}
}
fileprivate var noOrdercountP2 = 0
fileprivate var noOrdercountM2 = 0.0
fileprivate var currentOrderCountM2 = 0.0 {
didSet{
noOrdercountM2 += currentOrderCountM2
}
}
fileprivate var currentOrderCountP2 = 0 {
didSet{
if !noOrdercountPSearchIsSuccess {
return
}
if currentOrderCountP2 == -1 {
if noOrdercountPSearchHud != nil {
noOrdercountPSearchHud?.hide(true)
}
let _ = SAMHUD.showMessage("获取订单详情失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
noOrdercountPSearchIsSuccess = false
}else {
noOrdercountP2 += currentOrderCountP2
if currentOrderSearchCount2 == orderManageModels2.count {
orderArr2DidSet = true
getOrderDetail()
}else {
let model = orderManageModels2[currentOrderSearchCount2] as! SAMOrderModel
loadOrderDetailArr2(orderModel: model)
}
}
}
}
fileprivate var orderArr3DidSet = true
fileprivate let orderManageModels3 = NSMutableArray()
fileprivate let searchShoppingCarListArr3 = NSMutableArray()
fileprivate var currentOrderSearchCount3 = 0 {
didSet{
setHUDProgress()
}
}
fileprivate var noOrdercountP3 = 0
fileprivate var noOrdercountM3 = 0.0
fileprivate var currentOrderCountM3 = 0.0 {
didSet{
noOrdercountM3 += currentOrderCountM3
}
}
fileprivate var currentOrderCountP3 = 0 {
didSet{
if !noOrdercountPSearchIsSuccess {
return
}
if currentOrderCountP3 == -1 {
if noOrdercountPSearchHud != nil {
noOrdercountPSearchHud?.hide(true)
}
let _ = SAMHUD.showMessage("获取订单详情失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
noOrdercountPSearchIsSuccess = false
}else {
noOrdercountP3 += currentOrderCountP3
if currentOrderSearchCount3 == orderManageModels3.count {
orderArr3DidSet = true
getOrderDetail()
}else {
let model = orderManageModels3[currentOrderSearchCount3] as! SAMOrderModel
loadOrderDetailArr3(orderModel: model)
}
}
}
}
fileprivate var orderArr4DidSet = true
fileprivate let orderManageModels4 = NSMutableArray()
fileprivate let searchShoppingCarListArr4 = NSMutableArray()
fileprivate var currentOrderSearchCount4 = 0 {
didSet{
setHUDProgress()
}
}
fileprivate var noOrdercountP4 = 0
fileprivate var noOrdercountM4 = 0.0
fileprivate var currentOrderCountM4 = 0.0 {
didSet{
noOrdercountM4 += currentOrderCountM4
}
}
fileprivate var currentOrderCountP4 = 0 {
didSet{
if !noOrdercountPSearchIsSuccess {
return
}
if currentOrderCountP4 == -1 {
if noOrdercountPSearchHud != nil {
noOrdercountPSearchHud?.hide(true)
}
let _ = SAMHUD.showMessage("获取订单详情失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
noOrdercountPSearchIsSuccess = false
}else {
noOrdercountP4 += currentOrderCountP4
if currentOrderSearchCount4 == orderManageModels4.count {
orderArr4DidSet = true
getOrderDetail()
}else {
let model = orderManageModels4[currentOrderSearchCount4] as! SAMOrderModel
loadOrderDetailArr4(orderModel: model)
}
}
}
}
fileprivate var orderArr5DidSet = true
fileprivate let orderManageModels5 = NSMutableArray()
fileprivate let searchShoppingCarListArr5 = NSMutableArray()
fileprivate var currentOrderSearchCount5 = 0 {
didSet{
setHUDProgress()
}
}
fileprivate var noOrdercountP5 = 0
fileprivate var noOrdercountM5 = 0.0
fileprivate var currentOrderCountM5 = 0.0 {
didSet{
noOrdercountM5 += currentOrderCountM5
}
}
fileprivate var currentOrderCountP5 = 0 {
didSet{
if !noOrdercountPSearchIsSuccess {
return
}
if currentOrderCountP5 == -1 {
if noOrdercountPSearchHud != nil {
noOrdercountPSearchHud?.hide(true)
}
let _ = SAMHUD.showMessage("获取订单详情失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
noOrdercountPSearchIsSuccess = false
}else {
noOrdercountP5 += currentOrderCountP5
if currentOrderSearchCount5 == orderManageModels5.count {
orderArr5DidSet = true
getOrderDetail()
}else {
let model = orderManageModels5[currentOrderSearchCount5] as! SAMOrderModel
loadOrderDetailArr5(orderModel: model)
}
}
}
}
//MARK: - xibffs束属性
///所有库存控件顶部距离
@IBOutlet weak var allStockViewTopDistance: NSLayoutConstraint!
//MARK: - xib链接控件
@IBOutlet weak var allStockView: UIView!
@IBOutlet weak var pishuLabel: UILabel!
@IBOutlet weak var mishuLabel: UILabel!
@IBOutlet weak var productNameTF: SAMLoginTextField!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var indicaterView: UIView!
//MARK: - 其他方法
fileprivate init() {
super.init(nibName: nil, bundle: nil)
}
fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = Bundle.main.loadNibNamed("SAMStockViewController", owner: self, options: nil)![0] as! UIView
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
//MARK: - CollectionView数据源方法UICollectionViewDataSource
extension SAMStockViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return stockProductModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SAMStockProductCellReuseIdentifier, for: indexPath) as! SAMStockProductCell
//取出模型
let model = stockProductModels[indexPath.row] as! SAMStockProductModel
cell.stockProductModel = model
//设置代理
cell.delegate = self
return cell
}
}
//MARK: - CollectionView代理UICollectionViewDelegate
extension SAMStockViewController: UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
endProductNameTFEditing(false)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
endProductNameTFEditing(false)
//获取数据模型
let selectedModel = stockProductModels[indexPath.item] as! SAMStockProductModel
//展示产品详情控制器
let codeName = selectedModel.codeName
let sameCodeNameModels = stockProductModels.compare(modelKeys: ["codeName"], searchItems: [codeName])
let productInfoVC = SAMStockProductInfoController.instance(stockModel: selectedModel, sameCodeNameModels: NSMutableArray(array: sameCodeNameModels))
// productInfoVC!.stockProductModel = selectedModel
//TODO: - 暂时注释,看有没有影响
navigationController!.pushViewController(productInfoVC!, animated: true)
}
}
//MARK: - collectionView布局代理
extension SAMStockViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return SAMStockProductCellNormalSize
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
//MARK: - 条件搜索控制器的转场动画代理
extension SAMStockViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SAMPresentingAnimator()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SAMDismissingAnimator()
}
}
//MARK: - 库存产品CELL的代理SAMStockProductCellDelegate
extension SAMStockViewController: SAMStockProductCellDelegate {
//点击了产品图片
func productCellDidClickProductImage(_ stockProductModel: SAMStockProductModel) {
//展示产品图片控制器
let codeName = stockProductModel.codeName
let sameCodeNameModels = stockProductModels.compare(modelKeys: ["codeName"], searchItems: [codeName])
let productImageVC = SAMProductImageController.instance(stockModel: stockProductModel, sameNameModels: NSMutableArray(array: sameCodeNameModels))
navigationController!.pushViewController(productImageVC, animated: true)
}
//长按了产品图片
func productCellDidLongPressProductImage(_ stockProductModel: SAMStockProductModel) {
//创建条件搜索界面,并展示
stockDetailVC = SAMStockDetailController.instance(stockModel: stockProductModel)
stockDetailVC!.transitioningDelegate = self
stockDetailVC!.modalPresentationStyle = UIModalPresentationStyle.custom
present(stockDetailVC!, animated: true) {
}
}
//点击了库存警报图片
func productCellDidTapWarnningImage(_ stockProductModel: SAMStockProductModel) {
let owedVC = SAMOrderOwedOperationController.buildOwe(productModel: stockProductModel, type: .buildOwe)
navigationController!.pushViewController(owedVC, animated: true)
}
//长按了库存警报图片
func productCellDidLongPressWarnningImage(_ stockProductModel: SAMStockProductModel) {
let productName = stockProductModel.productIDName
//发出通知
NotificationCenter.default.post(name: NSNotification.Name.init(SAMStockProductCellLongPressWarnningImageNotification), object: nil, userInfo: ["productIDName": productName])
//切换到库存查询界面
tabBarController!.selectedIndex = 0
let animation = CATransition()
animation.duration = 0.4
animation.timingFunction = CAMediaTimingFunction(name: "easeInEaseOut")
animation.type = "kCATransitionFade"
tabBarController?.view.layer.add(animation, forKey: nil)
}
func productCellDidTapShoppingCarImage(_ stockProductModel: SAMStockProductModel, stockProductImage: UIImage) {
//展示购物车
showShoppingCar(stockProductImage, productModel: stockProductModel)
}
func productCellDidLongPressShoppingCarImage(_ stockProductModel: SAMStockProductModel) {
stockSearchProductName = stockProductModel.productIDName
countCountPInNoOrder()
}
}
//MARK: - 购物车控件代理
extension SAMStockViewController: SAMProductOperationViewDelegate {
func operationViewDidClickDismissButton() {
//隐藏购物车
hideProductOperationView(false, produtImage: nil)
}
func operationViewAddOrEditProductSuccess(_ productImage: UIImage, postShoppingCarListModelSuccess: Bool) {
if isFromBuildOrder && postShoppingCarListModelSuccess {
//隐藏购物车, 提示用户
hideProductOperationView(false, produtImage: productImage)
let _ = SAMHUD.showMessage("添加成功", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}else if isFromBuildOrder && !postShoppingCarListModelSuccess {
//隐藏购物车, 提示用户
hideProductOperationView(false, produtImage: productImage)
let _ = SAMHUD.showMessage("添加失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}else {
//隐藏购物车
hideProductOperationView(true, produtImage: productImage)
}
}
//MARK: - 购物车相关4各方法
//主控制器View展示购物车时的第一步形变
fileprivate func firstTran() -> CATransform3D {
var transform = CATransform3DIdentity
transform.m24 = -1/2000
transform = CATransform3DScale(transform, 0.9, 0.9, 1)
return transform
}
//主控制器View展示购物车时的第二步形变
fileprivate func secondTran() -> CATransform3D {
var transform = CATransform3DIdentity
transform = CATransform3DTranslate(transform, 0, self.view.frame.size.height * (-0.08), 0)
transform = CATransform3DScale(transform, 0.8, 0.8, 1)
return transform
}
//展示购物车控件
fileprivate func showShoppingCar(_ productImage: UIImage, productModel: SAMStockProductModel) {
//设置购物车控件的目标frame
productOperationView = SAMProductOperationView.operationViewWillShow(productModel, editProductModel: nil, isFromeCheckOrder: false, postModelAfterOperationSuccess: isFromBuildOrder)
productOperationView!.delegate = self
productOperationView!.frame = CGRect(x: 0, y: ScreenH, width: ScreenW, height: 350)
var rect = productOperationView!.frame
rect.origin.y = ScreenH - rect.size.height
//添加背景View
tabBarController!.view.addSubview(productOperationMaskView)
KeyWindow?.addSubview(productOperationView!)
//动画展示购物车控件
UIView.animate(withDuration: 0.5, animations: {
self.productOperationView!.frame = rect
})
//动画移动背景View
UIView.animate(withDuration: 0.25, animations: {
//执行第一步动画
self.productOperationMaskView.alpha = 0.5
self.tabBarController!.view.layer.transform = self.firstTran()
}, completion: { (_) in
//执行第二步动画
UIView.animate(withDuration: 0.25, animations: {
self.tabBarController!.view.layer.transform = self.secondTran()
}, completion: { (_) in
})
})
}
//点击maskView隐藏购物车控件
func hideProductOperationViewWhenMaskViewDidClick() {
hideProductOperationView(false, produtImage: nil)
}
//隐藏购物车控件
fileprivate func hideProductOperationView(_ didAddProduct: Bool, produtImage: UIImage?) {
//设置购物车目标frame
var rect = self.productOperationView!.frame
rect.origin.y = ScreenH
//动画隐藏购物车控件
UIView.animate(withDuration: 0.5, animations: {
self.productOperationView!.frame = rect
})
//动画展示主View
UIView.animate(withDuration: 0.25, animations: {
self.tabBarController!.view.layer.transform = self.firstTran()
self.productOperationMaskView.alpha = 0.0
}, completion: { (_) in
//移除蒙板
self.productOperationMaskView.removeFromSuperview()
UIView.animate(withDuration: 0.25, animations: {
self.tabBarController!.view.layer.transform = CATransform3DIdentity
}, completion: { (_) in
//移除购物车
self.productOperationView!.removeFromSuperview()
//调用成功添加购物车的动画
if didAddProduct {
self.addToShoppingCarSuccess(produtImage!)
}
})
})
}
//添加到购物车之后的产品图片动画方法
fileprivate func addToShoppingCarSuccess(_ productImage: UIImage) {
//设置用户界面不可交互
tabBarController?.view.isUserInteractionEnabled = false
//设置动画layer
productAnimlayer!.contents = productImage.cgImage
KeyWindow?.layer.addSublayer(productAnimlayer!)
productAnimlayer?.add(groupAnimation, forKey: "group")
}
}
//MARK: - 添加产品至购物车成功后,产品图片动画的监听代理
extension SAMStockViewController: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if anim == productAnimlayer?.animation(forKey: "group") {
//改变shoppingCar控制器的badgeValue
SAMShoppingCarController.sharedInstanceMain().addOrMinusProductCountOne(true)
//恢复界面交互状态
tabBarController?.view.isUserInteractionEnabled = true
//移除动画
productAnimlayer?.removeFromSuperlayer()
//移除动画图层
productAnimlayer?.removeFromSuperlayer()
}
}
}
//MARK: - 文本框相关方法
extension SAMStockViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//结束编辑状态
endProductNameTFEditing(false)
//触发collectionView下拉
collectionView.mj_header.beginRefreshing()
return true
}
///文本框监听的方法
func textFieldDidEditChange(_ textField: UITextField) {
//获取搜索字符串
productNameSearchStr = textField.text!.lxm_stringByTrimmingWhitespace()!
}
///结束产品文本框编辑状态
fileprivate func endProductNameTFEditing(_ clear: Bool) {
if clear {
productNameTF.text = ""
productNameSearchStr = ""
}
let _ = productNameTF.resignFirstResponder()
}
}
//MARK: - 新增扩展方法,计算未开单总匹数
extension SAMStockViewController {
///设置初始化数据,调用获取订单,待售布匹方法
func countCountPInNoOrder() {
//初始化数据
orderManageModels.removeAllObjects()
orderMarr1.removeAllObjects()
orderMarr2.removeAllObjects()
orderMarr3.removeAllObjects()
orderMarr4.removeAllObjects()
orderMarr5.removeAllObjects()
forSaleModels.removeAllObjects()
orderMarr1DidSet = false
orderMarr2DidSet = false
orderMarr3DidSet = false
orderMarr4DidSet = false
orderMarr5DidSet = false
forSaleModelsDidSet = false;
//设置加载hud
noOrdercountPSearchHud = SAMHUD.showAdded(to: KeyWindow!, animated: true)
noOrdercountPSearchHud!.labelText = NSLocalizedString("", comment: "HUD loading title")
self.loadNewforSaleModels()
self.loadModel(pageIndex: "1")
self.loadModel(pageIndex: "2")
self.loadModel(pageIndex: "3")
self.loadModel(pageIndex: "4")
self.loadModel(pageIndex: "5")
}
///获取订单
func loadModel(pageIndex: String) {
//创建请求参数
let employeeID = "-1"
let CGUnitName = ""
let pageSize = "100"
let statusStr = "未开单"
let yesterDayStr = Date.init(timeIntervalSinceNow: -60 * 60 * 24).yyyyMMddStr()
let startDate = yesterDayStr
let endDate = Date().yyyyMMddStr()
let orderRequestParameters = ["employeeID": employeeID, "CGUnitName": CGUnitName, "pageSize": pageSize, "pageIndex": pageIndex, "startDate": startDate, "endDate": endDate, "status": statusStr]
SAMNetWorker.sharedNetWorker().get("getOrderMainData.ashx", parameters: orderRequestParameters, progress: nil, success: {[weak self] (Task, json) in
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let arr = SAMOrderModel.mj_objectArray(withKeyValuesArray: dictArr)!
let pageIndexStr = orderRequestParameters["pageIndex"]!
switch pageIndexStr {
case "1":
self!.orderMarr1DidSet = true
self!.orderMarr1.addObjects(from: arr as! [Any])
self!.setModelArr()
break
case "2":
self!.orderMarr2DidSet = true
self!.orderMarr2.addObjects(from: arr as! [Any])
self!.setModelArr()
break
case "3":
self!.orderMarr3DidSet = true
self!.orderMarr3.addObjects(from: arr as! [Any])
self!.setModelArr()
break
case "4":
self!.orderMarr4DidSet = true
self!.orderMarr4.addObjects(from: arr as! [Any])
self!.setModelArr()
break
case "5":
self!.orderMarr5DidSet = true
self!.orderMarr5.addObjects(from: arr as! [Any])
self!.setModelArr()
break
default:
break
}
}) {[weak self] (Task, Error) in
if self!.noOrdercountPSearchHud != nil {
self!.noOrdercountPSearchHud?.hide(true)
}
let _ = SAMHUD.showMessage("获取订单失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
self!.loadModelSuccess = false
}
}
///获取待售布匹
func loadNewforSaleModels() {
//创建请求参数
let userID = "-1"
let CGUnitName = ""
let productIDName = stockSearchProductName
let parameters = ["userID": userID, "CGUnitName": CGUnitName, "productIDName": productIDName]
//发送请求
SAMNetWorker.sharedNetWorker().get("getReadySellProductListNew.ashx", parameters: parameters, progress: nil, success: {[weak self] (Task, json) in
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let arr = SAMForSaleModel.mj_objectArray(withKeyValuesArray: dictArr)!
self!.forSaleModels.addObjects(from: arr as [AnyObject])
self!.forSaleModelsDidSet = true;
}) {[weak self] (Task, Error) in
self!.loadModelSuccess = false
self!.forSaleModelsDidSet = true;
if self!.noOrdercountPSearchHud != nil {
self!.noOrdercountPSearchHud?.hide(true)
}
let _ = SAMHUD.showMessage("获取待售布匹失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}
}
///订单获取后调用方法,对订单进行筛选
func setModelArr() {
if !loadModelSuccess {
return
}
if orderMarr1DidSet && orderMarr2DidSet && orderMarr3DidSet && orderMarr4DidSet && orderMarr5DidSet && forSaleModelsDidSet {
orderManageModels.addObjects(from: orderMarr1 as! [Any])
orderManageModels.addObjects(from: orderMarr2 as! [Any])
orderManageModels.addObjects(from: orderMarr3 as! [Any])
orderManageModels.addObjects(from: orderMarr4 as! [Any])
orderManageModels.addObjects(from: orderMarr5 as! [Any])
if orderManageModels.count == 0 {
_ = SAMHUD.showMessage("暂无未开单订单", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
return
}
//剔除已在待售布匹里的订单
if forSaleModels.count > 0 {
let forSaleOrderArr = NSMutableArray()
for forSaleIndex in 0...(forSaleModels.count - 1) {
let model = forSaleModels[forSaleIndex] as! SAMForSaleModel
let orderBillNum = model.orderBillNumber
for orderIndex in 0...(orderManageModels.count - 1) {
let orderModel = orderManageModels[orderIndex] as! SAMOrderModel
if orderModel.billNumber == orderBillNum {
if !forSaleOrderArr.contains(orderModel) {
forSaleOrderArr.add(orderModel)
break
}
}
}
}
orderManageModels.removeObjects(in: forSaleOrderArr as! [Any])
}
if orderManageModels.count == 0 {
return
}
searchShoppingCarListArr.removeAllObjects()
noOrdercountPSearchIsSuccess = true
noOrdercountP = 0
noOrdercountM = 0.0
orderArr1DidSet = false
orderManageModels1.removeAllObjects()
searchShoppingCarListArr1.removeAllObjects()
currentOrderSearchCount1 = 0
noOrdercountP1 = 0
noOrdercountM1 = 0.0
orderArr2DidSet = false
orderManageModels2.removeAllObjects()
searchShoppingCarListArr2.removeAllObjects()
currentOrderSearchCount2 = 0
noOrdercountP2 = 0
noOrdercountM2 = 0.0
orderArr3DidSet = false
orderManageModels3.removeAllObjects()
searchShoppingCarListArr3.removeAllObjects()
currentOrderSearchCount3 = 0
noOrdercountP3 = 0
noOrdercountM3 = 0.0
orderArr4DidSet = false
orderManageModels4.removeAllObjects()
searchShoppingCarListArr4.removeAllObjects()
currentOrderSearchCount4 = 0
noOrdercountP4 = 0
noOrdercountM4 = 0.0
orderArr5DidSet = false
orderManageModels5.removeAllObjects()
searchShoppingCarListArr5.removeAllObjects()
currentOrderSearchCount5 = 0
noOrdercountP5 = 0
noOrdercountM5 = 0.0
let perCount = orderManageModels.count / 5
for index in 0...(orderManageModels.count - 1) {
if index < perCount {
orderManageModels1.add(orderManageModels[index])
}else if (index >= perCount) && (index < perCount * 2) {
orderManageModels2.add(orderManageModels[index])
}else if (index >= perCount * 2) && (index < perCount * 3) {
orderManageModels3.add(orderManageModels[index])
}else if (index >= perCount * 3) && (index < perCount * 4) {
orderManageModels4.add(orderManageModels[index])
}else {
orderManageModels5.add(orderManageModels[index])
}
}
setupProgressHUD()
let model1 = orderManageModels1[0] as! SAMOrderModel
loadOrderDetailArr1(orderModel: model1)
let model2 = orderManageModels2[0] as! SAMOrderModel
loadOrderDetailArr2(orderModel: model2)
let model3 = orderManageModels3[0] as! SAMOrderModel
loadOrderDetailArr3(orderModel: model3)
let model4 = orderManageModels4[0] as! SAMOrderModel
loadOrderDetailArr4(orderModel: model4)
let model5 = orderManageModels5[0] as! SAMOrderModel
loadOrderDetailArr5(orderModel: model5)
}
}
fileprivate func setupProgressHUD() {
if noOrdercountPSearchHud != nil {
noOrdercountPSearchHud?.hide(true)
}
noOrderSearchProgressHud = SAMHUD.showAdded(to: KeyWindow!, animated: true)
noOrderSearchProgressHud!.mode = MBProgressHUDMode.annularDeterminate
let userName = UserDefaults.standard.object(forKey: "userNameStrKey") as? String
var remarkText: String?
if userName == "任玉" {
remarkText = String.init(format: "别急嘛~ 小玉😳", userName!)
}else if userName == "王超超" {
remarkText = String.init(format: "别急嘛~ 超超😉", userName!)
}else {
remarkText = "正在解析..."
}
noOrderSearchProgressHud!.labelText = NSLocalizedString(remarkText!, comment: "HUD loading title")
setHUDProgress()
}
fileprivate func setHUDProgress() {
if noOrderSearchProgressHud == nil {
return
}
if hudProgress < 1.0 {
noOrderSearchProgressHud!.progress = hudProgress
}else {
noOrderSearchProgressHud!.hide(true)
noOrderSearchProgressHud = nil
}
}
fileprivate func getOrderDetail() {
if orderArr1DidSet && orderArr2DidSet && orderArr3DidSet && orderArr4DidSet && orderArr5DidSet{
searchShoppingCarListArr.addObjects(from: searchShoppingCarListArr1 as! [Any])
noOrdercountP += noOrdercountP1
noOrdercountM += noOrdercountM1
searchShoppingCarListArr.addObjects(from: searchShoppingCarListArr2 as! [Any])
noOrdercountP += noOrdercountP2
noOrdercountM += noOrdercountM2
searchShoppingCarListArr.addObjects(from: searchShoppingCarListArr3 as! [Any])
noOrdercountP += noOrdercountP3
noOrdercountM += noOrdercountM3
searchShoppingCarListArr.addObjects(from: searchShoppingCarListArr4 as! [Any])
noOrdercountP += noOrdercountP4
noOrdercountM += noOrdercountM4
searchShoppingCarListArr.addObjects(from: searchShoppingCarListArr5 as! [Any])
noOrdercountP += noOrdercountP5
noOrdercountM += noOrdercountM5
if noOrdercountPSearchHud != nil {
noOrdercountPSearchHud?.hide(true)
}
if !noOrdercountPSearchAlertVCIsShowing {
if noOrdercountP == 0 {
let message = String(format: "未开单中共有%d匹", noOrdercountP)
noOrdercountPSearchAlertVC = UIAlertController(title: nil, message: message, preferredStyle: .alert)
noOrdercountPSearchAlertVC!.addAction(UIAlertAction(title: "确定", style: .cancel, handler: { (action) in
self.noOrdercountPSearchAlertVCIsShowing = false
}))
present(noOrdercountPSearchAlertVC!, animated: true, completion: nil)
}else {
let vc = SAMNoOrderSearchDetailController.instance(orderArr: orderManageModels, shoppingCarListArr: searchShoppingCarListArr, productIDName: stockSearchProductName, countP: noOrdercountP, countM: noOrdercountM)
present(vc, animated: true, completion: nil)
}
noOrdercountPSearchAlertVCIsShowing = true
}
}
}
func loadOrderDetailArr1(orderModel: SAMOrderModel){
if !noOrdercountPSearchIsSuccess {
return
}
//发送请求,获取订单产品数据模型数组
SAMNetWorker.sharedNetWorker().get("getOrderDetailData.ashx", parameters: ["billNumber": orderModel.billNumber], progress: nil, success: {[weak self] (Task, json) in
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let count = dictArr?.count ?? 0
//判断是否有模型数据
if count == 0 { //没有数据
self!.currentOrderSearchCount1 += 1
self!.currentOrderCountP1 = 0
self!.currentOrderCountM1 = 0.0
}else { //有数据模型
let arr = SAMShoppingCarListModel.mj_objectArray(withKeyValuesArray: dictArr)!
var countP = 0
var countM = 0.0
for model in arr {
let shoppingCarListModel = model as! SAMShoppingCarListModel
if shoppingCarListModel.productIDName == self!.stockSearchProductName {
countP += shoppingCarListModel.countP
countM += shoppingCarListModel.countM
self!.searchShoppingCarListArr1.add(shoppingCarListModel)
}
}
self!.currentOrderSearchCount1 += 1
self!.currentOrderCountP1 = countP
self!.currentOrderCountM1 = countM
}
}) {[weak self] (Task, Error) in
self!.currentOrderSearchCount1 += 1
self!.currentOrderCountP1 = -1
}
}
func loadOrderDetailArr2(orderModel: SAMOrderModel){
if !noOrdercountPSearchIsSuccess {
return
}
//发送请求,获取订单产品数据模型数组
SAMNetWorker.sharedNetWorker().get("getOrderDetailData.ashx", parameters: ["billNumber": orderModel.billNumber], progress: nil, success: {[weak self] (Task, json) in
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let count = dictArr?.count ?? 0
//判断是否有模型数据
if count == 0 { //没有数据
self!.currentOrderSearchCount2 += 1
self!.currentOrderCountP2 = 0
self!.currentOrderCountM2 = 0.0
}else { //有数据模型
let arr = SAMShoppingCarListModel.mj_objectArray(withKeyValuesArray: dictArr)!
var countP = 0
var countM = 0.0
for model in arr {
let shoppingCarListModel = model as! SAMShoppingCarListModel
if shoppingCarListModel.productIDName == self!.stockSearchProductName {
countP += shoppingCarListModel.countP
countM += shoppingCarListModel.countM
self!.searchShoppingCarListArr2.add(shoppingCarListModel)
}
}
self!.currentOrderSearchCount2 += 1
self!.currentOrderCountP2 = countP
self!.currentOrderCountM2 = countM
}
}) {[weak self] (Task, Error) in
self!.currentOrderSearchCount2 += 1
self!.currentOrderCountP2 = -1
}
}
func loadOrderDetailArr3(orderModel: SAMOrderModel){
if !noOrdercountPSearchIsSuccess {
return
}
//发送请求,获取订单产品数据模型数组
SAMNetWorker.sharedNetWorker().get("getOrderDetailData.ashx", parameters: ["billNumber": orderModel.billNumber], progress: nil, success: {[weak self] (Task, json) in
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let count = dictArr?.count ?? 0
//判断是否有模型数据
if count == 0 { //没有数据
self!.currentOrderSearchCount3 += 1
self!.currentOrderCountP3 = 0
self!.currentOrderCountM3 = 0.0
}else { //有数据模型
let arr = SAMShoppingCarListModel.mj_objectArray(withKeyValuesArray: dictArr)!
var countP = 0
var countM = 0.0
for model in arr {
let shoppingCarListModel = model as! SAMShoppingCarListModel
if shoppingCarListModel.productIDName == self!.stockSearchProductName {
countP += shoppingCarListModel.countP
countM += shoppingCarListModel.countM
self!.searchShoppingCarListArr3.add(shoppingCarListModel)
}
}
self!.currentOrderSearchCount3 += 1
self!.currentOrderCountP3 = countP
self!.currentOrderCountM3 = countM
}
}) {[weak self] (Task, Error) in
self!.currentOrderSearchCount3 += 1
self!.currentOrderCountP3 = -1
}
}
func loadOrderDetailArr4(orderModel: SAMOrderModel){
if !noOrdercountPSearchIsSuccess {
return
}
//发送请求,获取订单产品数据模型数组
SAMNetWorker.sharedNetWorker().get("getOrderDetailData.ashx", parameters: ["billNumber": orderModel.billNumber], progress: nil, success: {[weak self] (Task, json) in
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let count = dictArr?.count ?? 0
//判断是否有模型数据
if count == 0 { //没有数据
self!.currentOrderSearchCount4 += 1
self!.currentOrderCountP4 = 0
self!.currentOrderCountM4 = 0.0
}else { //有数据模型
let arr = SAMShoppingCarListModel.mj_objectArray(withKeyValuesArray: dictArr)!
var countP = 0
var countM = 0.0
for model in arr {
let shoppingCarListModel = model as! SAMShoppingCarListModel
if shoppingCarListModel.productIDName == self!.stockSearchProductName {
countP += shoppingCarListModel.countP
countM += shoppingCarListModel.countM
self!.searchShoppingCarListArr4.add(shoppingCarListModel)
}
}
self!.currentOrderSearchCount4 += 1
self!.currentOrderCountP4 = countP
self!.currentOrderCountM4 = countM
}
}) {[weak self] (Task, Error) in
self!.currentOrderSearchCount4 += 1
self!.currentOrderCountP4 = -1
}
}
func loadOrderDetailArr5(orderModel: SAMOrderModel){
if !noOrdercountPSearchIsSuccess {
return
}
//发送请求,获取订单产品数据模型数组
SAMNetWorker.sharedNetWorker().get("getOrderDetailData.ashx", parameters: ["billNumber": orderModel.billNumber], progress: nil, success: {[weak self] (Task, json) in
//获取模型数组
let Json = json as! [String: AnyObject]
let dictArr = Json["body"] as? [[String: AnyObject]]
let count = dictArr?.count ?? 0
//判断是否有模型数据
if count == 0 { //没有数据
self!.currentOrderSearchCount5 += 1
self!.currentOrderCountP5 = 0
self!.currentOrderCountM5 = 0.0
}else { //有数据模型
let arr = SAMShoppingCarListModel.mj_objectArray(withKeyValuesArray: dictArr)!
var countP = 0
var countM = 0.0
for model in arr {
let shoppingCarListModel = model as! SAMShoppingCarListModel
if shoppingCarListModel.productIDName == self!.stockSearchProductName {
countP += shoppingCarListModel.countP
countM += shoppingCarListModel.countM
self!.searchShoppingCarListArr5.add(shoppingCarListModel)
}
}
self!.currentOrderSearchCount5 += 1
self!.currentOrderCountP5 = countP
self!.currentOrderCountM5 = countM
}
}) {[weak self] (Task, Error) in
self!.currentOrderSearchCount5 += 1
self!.currentOrderCountP5 = -1
}
}
}
| apache-2.0 | 00863d285e158ac9ecde5845728dba6f | 36.193584 | 240 | 0.573908 | 5.082458 | false | false | false | false |
RxSwiftCommunity/RxWebKit | Example/JavaScriptAlertPanelViewController.swift | 1 | 1450 | //
// JavaScriptAlertPanelViewController.swift
// Example
//
// Created by Bob Obi on 25.10.17.
// Copyright © 2017 RxSwift Community. All rights reserved.
//
import UIKit
import WebKit
import RxWebKit
import RxSwift
import RxCocoa
class JavaScriptAlertPanelViewController: UIViewController {
let bag = DisposeBag()
let wkWebView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(wkWebView)
wkWebView.load(URLRequest(url: URL(string: "https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert")!))
wkWebView.rx
.javaScriptAlertPanel
.debug("javaScriptAlertPanel")
.subscribe(onNext: { [weak self] webView, message, frame, handler in
guard let self = self else { return }
let alert = UIAlertController(title: "JavaScriptAlertPanel", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
handler()
})
.disposed(by: bag)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let originY = UIApplication.shared.statusBarFrame.maxY
wkWebView.frame = CGRect(x: 0, y: originY, width: view.bounds.width, height: view.bounds.height)
}
}
| mit | cc960b79222e0567dc5fb0ae14200f4e | 32.697674 | 122 | 0.645273 | 4.556604 | false | false | false | false |
dalequi/yelpitoff | Demo/OAuthSwift/OAuthSwiftDemo/Services.swift | 1 | 1724 | //
// Services.swift
// OAuthSwift
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
// Class which contains services parameters like consumer key and secret
class Services {
var parameters : [String: [String: String]]
init() {
self.parameters = [:]
}
subscript(service: String) -> [String:String]? {
get {
return parameters[service]
}
set {
if let value = newValue where !Services.parametersEmpty(value) {
parameters[service] = value
}
}
}
func loadFromFile(path: String) {
if let newParameters = NSDictionary(contentsOfFile: path) as? [String: [String: String]] {
for (service, dico) in newParameters {
if parameters[service] != nil && Services.parametersEmpty(dico) { // no value to set
continue
}
updateService(service, dico: dico)
}
}
}
func updateService(service: String, dico: [String: String]) {
var resultdico = dico
if let oldDico = self.parameters[service] {
resultdico = oldDico
resultdico += dico
}
self.parameters[service] = resultdico
}
static func parametersEmpty(dico: [String: String]) -> Bool {
return Array(dico.values).filter({ (p) -> Bool in !p.isEmpty }).isEmpty
}
var keys: [String] {
return Array(self.parameters.keys)
}
}
func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
} | mit | 2bc09caee474c777aa7acb2f33e38b72 | 25.953125 | 114 | 0.563805 | 4.342569 | false | false | false | false |
tkremenek/swift | stdlib/public/Concurrency/AsyncLet.swift | 1 | 1649 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
// ==== Async Let -------------------------------------------------------------
// Only has internal / builtin functions as it is not really accessible directly
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_asyncLet_start")
public func _asyncLetStart<T>(
asyncLet: Builtin.RawPointer,
options: Builtin.RawPointer?,
operation: @Sendable () async throws -> T
)
/// Similar to _taskFutureGet but for AsyncLet
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_asyncLet_wait")
public func _asyncLetGet<T>(asyncLet: Builtin.RawPointer) async -> T
///// Similar to _taskFutureGetThrowing but for AsyncLet
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_asyncLet_wait_throwing")
public func _asyncLetGetThrowing<T>(asyncLet: Builtin.RawPointer) async throws -> T
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_asyncLet_end")
public func _asyncLetEnd(
asyncLet: Builtin.RawPointer // TODO: should this take __owned?
)
@_silgen_name("swift_asyncLet_extractTask")
func _asyncLetExtractTask(
of asyncLet: Builtin.RawPointer
) -> Builtin.NativeObject
| apache-2.0 | b3079877b726d88617ee09e29d12a600 | 34.085106 | 83 | 0.647665 | 4.239075 | false | false | false | false |
joerocca/GitHawk | Classes/Notifications/NotificationClient.swift | 1 | 4244 | //
// NotificationClient.swift
// Freetime
//
// Created by Ryan Nystrom on 6/30/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
final class NotificationClient {
private var openedNotificationIDs = Set<String>()
let githubClient: GithubClient
init(githubClient: GithubClient) {
self.githubClient = githubClient
}
// Public API
static private let openOnReadKey = "com.freetime.NotificationClient.read-on-open"
static func readOnOpen() -> Bool {
return UserDefaults.standard.bool(forKey: openOnReadKey)
}
static func setReadOnOpen(open: Bool) {
UserDefaults.standard.set(open, forKey: openOnReadKey)
}
// https://developer.github.com/v3/activity/notifications/#list-your-notifications
func requestNotifications(
all: Bool = false,
participating: Bool = false,
since: Date? = nil,
page: Int = 1,
before: Date? = nil,
width: CGFloat,
completion: @escaping (Result<([NotificationViewModel], Int?)>) -> Void
) {
var parameters: [String: Any] = [
"all": all ? "true" : "false",
"participating": participating ? "true" : "false",
"page": page,
"per_page": "50"
]
if let since = since {
parameters["since"] = GithubAPIDateFormatter().string(from: since)
}
if let before = before {
parameters["before"] = GithubAPIDateFormatter().string(from: before)
}
let cache = githubClient.cache
githubClient.request(GithubClient.Request(
path: "notifications",
method: .get,
parameters: parameters,
headers: nil
) { (response, nextPage) in
if let notifications = (response.value as? [[String:Any]])?.flatMap({ NotificationResponse(json: $0) }) {
let viewModels = CreateViewModels(containerWidth: width, notifications: notifications)
cache.set(values: viewModels)
completion(.success((viewModels, nextPage?.next)))
} else {
completion(.error(response.error))
}
})
}
typealias MarkAllCompletion = (Bool) -> Void
func markAllNotifications(completion: MarkAllCompletion? = nil) {
githubClient.request(GithubClient.Request(
path: "notifications",
method: .put) { (response, _) in
guard let completion = completion else { return }
// https://developer.github.com/v3/activity/notifications/#mark-as-read
let success = response.response?.statusCode == 205
completion(success)
})
}
func notificationOpened(id: String) -> Bool {
return openedNotificationIDs.contains(id)
}
func markNotificationRead(id: String, isOpen: Bool) {
let oldModel = githubClient.cache.get(id: id) as NotificationViewModel?
if isOpen {
openedNotificationIDs.insert(id)
} else {
// optimistically set the model to read
// if the request fails, replace this model w/ the old one.
if let old = oldModel {
githubClient.cache.set(value: NotificationViewModel(
id: old.id,
title: old.title,
type: old.type,
date: old.date,
read: true,
owner: old.owner,
repo: old.repo,
identifier: old.identifier
))
}
}
githubClient.request(GithubClient.Request(
path: "notifications/threads/\(id)",
method: .patch) { [weak self] (response, _) in
// https://developer.github.com/v3/activity/notifications/#mark-a-thread-as-read
if response.response?.statusCode != 205 {
if isOpen {
self?.openedNotificationIDs.remove(id)
} else if let old = oldModel {
self?.githubClient.cache.set(value: old)
}
}
})
}
}
| mit | 38298e660fafe1c3016b0f41d9e40567 | 32.674603 | 117 | 0.555975 | 4.622004 | false | false | false | false |
ProjectDent/ARKit-CoreLocation | ARKit+CoreLocation/SettingsViewController.swift | 1 | 7948 | //
// SettingsViewController.swift
// ARKit+CoreLocation
//
// Created by Eric Internicola on 2/19/19.
// Copyright © 2019 Project Dent. All rights reserved.
//
import CoreLocation
import MapKit
import UIKit
@available(iOS 11.0, *)
class SettingsViewController: UIViewController {
@IBOutlet weak var showMapSwitch: UISwitch!
@IBOutlet weak var showPointsOfInterest: UISwitch!
@IBOutlet weak var showRouteDirections: UISwitch!
@IBOutlet weak var addressText: UITextField!
@IBOutlet weak var searchResultTable: UITableView!
@IBOutlet weak var refreshControl: UIActivityIndicatorView!
var locationManager = CLLocationManager()
var mapSearchResults: [MKMapItem]?
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.headingFilter = kCLHeadingFilterNone
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.delegate = self
locationManager.startUpdatingHeading()
locationManager.startUpdatingLocation()
locationManager.requestWhenInUseAuthorization()
addressText.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
@IBAction
func toggledSwitch(_ sender: UISwitch) {
if sender == showPointsOfInterest {
showRouteDirections.isOn = !sender.isOn
searchResultTable.reloadData()
} else if sender == showRouteDirections {
showPointsOfInterest.isOn = !sender.isOn
searchResultTable.reloadData()
}
}
@IBAction
func tappedSearch(_ sender: Any) {
guard let text = addressText.text, !text.isEmpty else {
return
}
searchForLocation()
}
}
// MARK: - UITextFieldDelegate
@available(iOS 11.0, *)
extension SettingsViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string == "\n" {
DispatchQueue.main.async { [weak self] in
self?.searchForLocation()
}
}
return true
}
}
// MARK: - DataSource
@available(iOS 11.0, *)
extension SettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if showPointsOfInterest.isOn {
return 1
}
guard let mapSearchResults = mapSearchResults else {
return 0
}
return mapSearchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if showPointsOfInterest.isOn {
let cell = tableView.dequeueReusableCell(withIdentifier: "OpenARCell", for: indexPath)
guard let openARCell = cell as? OpenARCell else {
return cell
}
openARCell.parentVC = self
return openARCell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "LocationCell", for: indexPath)
guard let mapSearchResults = mapSearchResults,
indexPath.row < mapSearchResults.count,
let locationCell = cell as? LocationCell else {
return cell
}
locationCell.locationManager = locationManager
locationCell.mapItem = mapSearchResults[indexPath.row]
return locationCell
}
}
}
// MARK: - UITableViewDelegate
@available(iOS 11.0, *)
extension SettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let mapSearchResults = mapSearchResults, indexPath.row < mapSearchResults.count else {
return
}
let selectedMapItem = mapSearchResults[indexPath.row]
getDirections(to: selectedMapItem)
}
}
// MARK: - CLLocationManagerDelegate
@available(iOS 11.0, *)
extension SettingsViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
}
}
// MARK: - Implementation
@available(iOS 11.0, *)
extension SettingsViewController {
func createARVC() -> POIViewController {
let arclVC = POIViewController.loadFromStoryboard()
arclVC.showMap = showMapSwitch.isOn
return arclVC
}
func getDirections(to mapLocation: MKMapItem) {
refreshControl.startAnimating()
let request = MKDirections.Request()
request.source = MKMapItem.forCurrentLocation()
request.destination = mapLocation
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
directions.calculate(completionHandler: { response, error in
defer {
DispatchQueue.main.async { [weak self] in
self?.refreshControl.stopAnimating()
}
}
if let error = error {
return print("Error getting directions: \(error.localizedDescription)")
}
guard let response = response else {
return assertionFailure("No error, but no response, either.")
}
DispatchQueue.main.async { [weak self] in
guard let self = self else {
return
}
let arclVC = self.createARVC()
arclVC.routes = response.routes
self.navigationController?.pushViewController(arclVC, animated: true)
}
})
}
/// Searches for the location that was entered into the address text
func searchForLocation() {
guard let addressText = addressText.text, !addressText.isEmpty else {
return
}
showRouteDirections.isOn = true
toggledSwitch(showRouteDirections)
refreshControl.startAnimating()
defer {
self.addressText.resignFirstResponder()
}
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = addressText
let search = MKLocalSearch(request: request)
search.start { response, error in
defer {
DispatchQueue.main.async { [weak self] in
self?.refreshControl.stopAnimating()
}
}
if let error = error {
return assertionFailure("Error searching for \(addressText): \(error.localizedDescription)")
}
guard let response = response, response.mapItems.count > 0 else {
return assertionFailure("No response or empty response")
}
DispatchQueue.main.async { [weak self] in
guard let self = self else {
return
}
self.mapSearchResults = response.sortedMapItems(byDistanceFrom: self.locationManager.location)
self.searchResultTable.reloadData()
}
}
}
}
extension MKLocalSearch.Response {
func sortedMapItems(byDistanceFrom location: CLLocation?) -> [MKMapItem] {
guard let location = location else {
return mapItems
}
return mapItems.sorted { (first, second) -> Bool in
guard let d1 = first.placemark.location?.distance(from: location),
let d2 = second.placemark.location?.distance(from: location) else {
return true
}
return d1 < d2
}
}
}
| mit | 30fc5d6f27c8618904d21d1ddcc396ce | 29.565385 | 129 | 0.628539 | 5.431989 | false | false | false | false |
sbooth/SFBAudioEngine | Input/SFBInputSource.swift | 1 | 3109 | //
// Copyright (c) 2020 - 2021 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
import Foundation
extension InputSource {
/// Reads bytes from the input
/// - parameter buffer: A buffer to receive data
/// - parameter length: The maximum number of bytes to read
/// - returns: The number of bytes actually read
/// - throws: An `NSError` object if an error occurs
public func read(_ buffer: UnsafeMutableRawPointer, length: Int) throws -> Int {
var bytesRead = 0
try __readBytes(buffer, length: length, bytesRead: &bytesRead)
return bytesRead
}
/// Returns the current offset in the input, in bytes
/// - throws: An `NSError` object if an error occurs
public func offset() throws -> Int {
var offset = 0
try __getOffset(&offset)
return offset
}
/// Returns the length of the input, in bytes
/// - throws: An `NSError` object if an error occurs
public func length() throws -> Int {
var length = 0
try __getLength(&length)
return length
}
/// Reads and returns a binary integer
/// - returns: The integer value read
/// - throws: An `NSError` object if an error occurs
public func read<T: BinaryInteger>() throws -> T {
var i: T = 0
var bytesRead = 0
let size = MemoryLayout<T>.size
try withUnsafePointer(to: &i) {
bytesRead = try read(UnsafeMutablePointer(mutating: $0), length: size)
}
if bytesRead != size {
throw NSError(domain: NSPOSIXErrorDomain, code: Int(EIO), userInfo: nil)
}
return i
}
/// Reads a 16-bit integer from the input in big-endian format and returns the value
/// - throws: An `NSError` object if an error occurs
public func readBigEndian() throws -> UInt16 {
let ui16: UInt16 = try read()
return CFSwapInt16HostToBig(ui16)
}
/// Reads a 32-bit integer from the input in big-endian format and returns the value
/// - throws: An `NSError` object if an error occurs
public func readBigEndian() throws -> UInt32 {
let ui32: UInt32 = try read()
return CFSwapInt32HostToBig(ui32)
}
/// Reads a 64-bit integer from the input in big-endian format and returns the value
/// - throws: An `NSError` object if an error occurs
public func readBigEndian() throws -> UInt64 {
let ui64: UInt64 = try read()
return CFSwapInt64HostToBig(ui64)
}
/// Reads a 16-bit integer from the input in little-endian format and returns the value
/// - throws: An `NSError` object if an error occurs
public func readLittleEndian() throws -> UInt16 {
let ui16: UInt16 = try read()
return CFSwapInt16HostToLittle(ui16)
}
/// Reads a 32-bit integer from the input in little-endian format and returns the value
/// - throws: An `NSError` object if an error occurs
public func readLittleEndian() throws -> UInt32 {
let ui32: UInt32 = try read()
return CFSwapInt32HostToLittle(ui32)
}
/// Reads a 64-bit integer from the input in little-endian format and returns the value
/// - throws: An `NSError` object if an error occurs
public func readLittleEndian() throws -> UInt64 {
let ui64: UInt64 = try read()
return CFSwapInt64HostToLittle(ui64)
}
}
| mit | e29b7ca8e1b53c5b2fd6d82db4bae604 | 30.40404 | 88 | 0.701512 | 3.501126 | false | false | false | false |
shorlander/firefox-ios | Shared/Prefs.swift | 5 | 6150 | /* 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
public struct PrefsKeys {
public static let KeyLastRemoteTabSyncTime = "lastRemoteTabSyncTime"
public static let KeyLastSyncFinishTime = "lastSyncFinishTime"
public static let KeyTopSitesCacheIsValid = "topSitesCacheIsValid"
public static let KeyTopSitesCacheSize = "topSitesCacheSize"
public static let KeyDefaultHomePageURL = "KeyDefaultHomePageURL"
public static let KeyHomePageButtonIsInMenu = "HomePageButtonIsInMenuPrefKey"
public static let KeyNoImageModeButtonIsInMenu = "NoImageModeButtonIsInMenuPrefKey"
public static let KeyNoImageModeStatus = "NoImageModeStatus"
public static let KeyNewTab = "NewTabPrefKey"
public static let KeyNightModeButtonIsInMenu = "NightModeButtonIsInMenuPrefKey"
public static let KeyNightModeStatus = "NightModeStatus"
public static let KeyMailToOption = "MailToOption"
}
public struct PrefsDefaults {
public static let ChineseHomePageURL = "http://mobile.firefoxchina.cn/"
public static let ChineseNewTabDefault = "HomePage"
}
public protocol Prefs {
func getBranchPrefix() -> String
func branch(_ branch: String) -> Prefs
func setTimestamp(_ value: Timestamp, forKey defaultName: String)
func setLong(_ value: UInt64, forKey defaultName: String)
func setLong(_ value: Int64, forKey defaultName: String)
func setInt(_ value: Int32, forKey defaultName: String)
func setString(_ value: String, forKey defaultName: String)
func setBool(_ value: Bool, forKey defaultName: String)
func setObject(_ value: Any?, forKey defaultName: String)
func stringForKey(_ defaultName: String) -> String?
func objectForKey<T: Any>(_ defaultName: String) -> T?
func boolForKey(_ defaultName: String) -> Bool?
func intForKey(_ defaultName: String) -> Int32?
func timestampForKey(_ defaultName: String) -> Timestamp?
func longForKey(_ defaultName: String) -> Int64?
func unsignedLongForKey(_ defaultName: String) -> UInt64?
func stringArrayForKey(_ defaultName: String) -> [String]?
func arrayForKey(_ defaultName: String) -> [Any]?
func dictionaryForKey(_ defaultName: String) -> [String : Any]?
func removeObjectForKey(_ defaultName: String)
func clearAll()
}
open class MockProfilePrefs: Prefs {
let prefix: String
open func getBranchPrefix() -> String {
return self.prefix
}
// Public for testing.
open var things: NSMutableDictionary = NSMutableDictionary()
public init(things: NSMutableDictionary, prefix: String) {
self.things = things
self.prefix = prefix
}
public init() {
self.prefix = ""
}
open func branch(_ branch: String) -> Prefs {
return MockProfilePrefs(things: self.things, prefix: self.prefix + branch + ".")
}
private func name(_ name: String) -> String {
return self.prefix + name
}
open func setTimestamp(_ value: Timestamp, forKey defaultName: String) {
self.setLong(value, forKey: defaultName)
}
open func setLong(_ value: UInt64, forKey defaultName: String) {
setObject(NSNumber(value: value as UInt64), forKey: defaultName)
}
open func setLong(_ value: Int64, forKey defaultName: String) {
setObject(NSNumber(value: value as Int64), forKey: defaultName)
}
open func setInt(_ value: Int32, forKey defaultName: String) {
things[name(defaultName)] = NSNumber(value: value as Int32)
}
open func setString(_ value: String, forKey defaultName: String) {
things[name(defaultName)] = value
}
open func setBool(_ value: Bool, forKey defaultName: String) {
things[name(defaultName)] = value
}
open func setObject(_ value: Any?, forKey defaultName: String) {
things[name(defaultName)] = value
}
open func stringForKey(_ defaultName: String) -> String? {
return things[name(defaultName)] as? String
}
open func boolForKey(_ defaultName: String) -> Bool? {
return things[name(defaultName)] as? Bool
}
open func objectForKey<T: Any>(_ defaultName: String) -> T? {
return things[name(defaultName)] as? T
}
open func timestampForKey(_ defaultName: String) -> Timestamp? {
return unsignedLongForKey(defaultName)
}
open func unsignedLongForKey(_ defaultName: String) -> UInt64? {
let num = things[name(defaultName)] as? UInt64
if let num = num {
return num
}
return nil
}
open func longForKey(_ defaultName: String) -> Int64? {
let num = things[name(defaultName)] as? Int64
if let num = num {
return num
}
return nil
}
open func intForKey(_ defaultName: String) -> Int32? {
let num = things[name(defaultName)] as? Int32
if let num = num {
return num
}
return nil
}
open func stringArrayForKey(_ defaultName: String) -> [String]? {
if let arr = self.arrayForKey(defaultName) {
if let arr = arr as? [String] {
return arr
}
}
return nil
}
open func arrayForKey(_ defaultName: String) -> [Any]? {
let r: Any? = things.object(forKey: name(defaultName)) as Any?
if r == nil {
return nil
}
if let arr = r as? [Any] {
return arr
}
return nil
}
open func dictionaryForKey(_ defaultName: String) -> [String : Any]? {
return things.object(forKey: name(defaultName)) as? [String: Any]
}
open func removeObjectForKey(_ defaultName: String) {
self.things.removeObject(forKey: name(defaultName))
}
open func clearAll() {
let dictionary = things as! [String: Any]
let keysToDelete: [String] = dictionary.keys.filter { $0.startsWith(self.prefix) }
things.removeObjects(forKeys: keysToDelete)
}
}
| mpl-2.0 | 9f1df230d82eef4587694f63e49fd928 | 33.357542 | 90 | 0.65561 | 4.558933 | false | false | false | false |
chrisbudro/GrowlerHour | growlers/StyleBrowseTableViewController.swift | 1 | 1551 | //
// StyleBrowseTableViewController.swift
// growlers
//
// Created by Chris Budro on 9/8/15.
// Copyright (c) 2015 chrisbudro. All rights reserved.
//
import UIKit
class StyleBrowseTableViewController: BaseBrowseViewController {
//MARK: Life Cycle Methods
override func viewDidLoad() {
super.viewDidLoad()
title = "Styles"
cellReuseIdentifier = kStyleCellReuseIdentifier
tableView.registerNib(UINib(nibName: kBeerStyleNibName, bundle: nil), forCellReuseIdentifier: cellReuseIdentifier)
dataSource = TableViewDataSource(cellReuseIdentifier: cellReuseIdentifier, configureCell: configureCell)
tableView.dataSource = dataSource
updateBrowseList()
}
}
//MARK: Table View Delegate
extension StyleBrowseTableViewController {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let vc = BeerStyleDetailViewController(style: .Plain)
if let beerStyle = dataSource?.objectAtIndexPath(indexPath) as? BeerStyle {
vc.beerStyle = beerStyle
if let queryManager = queryManager {
let styleQueryManager = QueryManager(type: .Tap, filter: queryManager.filter)
vc.queryManager = styleQueryManager
}
}
navigationController?.pushViewController(vc, animated: true)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//TODO: Not a valid solution. Need to solve UITableViewAutomaticDimension bug with insertRowAtIndexPaths
return 60
}
}
| mit | 8b51906213c60b6236d71df8953ce570 | 31.3125 | 118 | 0.749194 | 5.003226 | false | false | false | false |
louisdh/panelkit | PanelKit/PanelContentDelegate/PanelContentDelegate+Default.swift | 1 | 2482 | //
// PanelContentDelegate+Default.swift
// PanelKit
//
// Created by Louis D'hauwe on 12/03/2017.
// Copyright © 2017 Silver Fox. All rights reserved.
//
import UIKit
public extension PanelContentDelegate {
var hideCloseButtonWhileFloating: Bool {
return false
}
var hideCloseButtonWhilePinned: Bool {
return false
}
var closeButtonTitle: String {
return "Close"
}
var popButtonTitle: String {
return "⬇︎"
}
var modalCloseButtonTitle: String {
return "Back"
}
func updateConstraintsForKeyboardShow(with frame: CGRect) {
}
func updateUIForKeyboardShow(with frame: CGRect) {
}
func updateConstraintsForKeyboardHide() {
}
func updateUIForKeyboardHide() {
}
/// Defaults to false
var shouldAdjustForKeyboard: Bool {
return false
}
/// Excludes potential "close" or "pop" buttons
var leftBarButtonItems: [UIBarButtonItem] {
return []
}
/// Excludes potential "close" or "pop" buttons
var rightBarButtonItems: [UIBarButtonItem] {
return []
}
func panelDragGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return true
}
var preferredPanelPinnedWidth: CGFloat {
return preferredPanelContentSize.width
}
var preferredPanelPinnedHeight: CGFloat {
return preferredPanelContentSize.height
}
var minimumPanelContentSize: CGSize {
return preferredPanelContentSize
}
var maximumPanelContentSize: CGSize {
return preferredPanelContentSize
}
}
public extension PanelContentDelegate where Self: UIViewController {
func updateNavigationButtons() {
guard let panel = panelNavigationController?.panelViewController else {
return
}
if panel.isPresentedModally {
let backBtn = getBackBtn()
navigationItem.leftBarButtonItems = [backBtn] + leftBarButtonItems
} else {
if !panel.canFloat {
navigationItem.leftBarButtonItems = leftBarButtonItems
} else {
if panel.contentDelegate?.hideCloseButtonWhileFloating == true, panel.isFloating {
navigationItem.leftBarButtonItems = leftBarButtonItems
} else if panel.contentDelegate?.hideCloseButtonWhilePinned == true, panel.isPinned {
navigationItem.leftBarButtonItems = leftBarButtonItems
} else {
let panelToggleBtn = getPanelToggleBtn()
navigationItem.leftBarButtonItems = [panelToggleBtn] + leftBarButtonItems
}
}
}
navigationItem.rightBarButtonItems = rightBarButtonItems
}
}
| mit | fea8161dafab4a18a9355d165611051f | 17.765152 | 114 | 0.731126 | 4.135225 | false | false | false | false |
jpvasquez/Eureka | Example/Example/Controllers/NativeEventExample.swift | 1 | 7945 | //
// NativeEventExample.swift
// Example
//
// Created by Mathias Claassen on 3/15/18.
// Copyright © 2018 Xmartlabs. All rights reserved.
//
import Eureka
class NativeEventNavigationController: UINavigationController, RowControllerType {
var onDismissCallback : ((UIViewController) -> ())?
}
class NativeEventFormViewController : FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
initializeForm()
navigationItem.leftBarButtonItem?.target = self
navigationItem.leftBarButtonItem?.action = #selector(NativeEventFormViewController.cancelTapped(_:))
}
private func initializeForm() {
form +++
TextRow("Title").cellSetup { cell, row in
cell.textField.placeholder = row.tag
}
<<< TextRow("Location").cellSetup {
$1.cell.textField.placeholder = $0.row.tag
}
+++
SwitchRow("All-day") {
$0.title = $0.tag
}.onChange { [weak self] row in
let startDate: DateTimeInlineRow! = self?.form.rowBy(tag: "Starts")
let endDate: DateTimeInlineRow! = self?.form.rowBy(tag: "Ends")
if row.value ?? false {
startDate.dateFormatter?.dateStyle = .medium
startDate.dateFormatter?.timeStyle = .none
endDate.dateFormatter?.dateStyle = .medium
endDate.dateFormatter?.timeStyle = .none
}
else {
startDate.dateFormatter?.dateStyle = .short
startDate.dateFormatter?.timeStyle = .short
endDate.dateFormatter?.dateStyle = .short
endDate.dateFormatter?.timeStyle = .short
}
startDate.updateCell()
endDate.updateCell()
startDate.inlineRow?.updateCell()
endDate.inlineRow?.updateCell()
}
<<< DateTimeInlineRow("Starts") {
$0.title = $0.tag
$0.value = Date().addingTimeInterval(60*60*24)
}
.onChange { [weak self] row in
let endRow: DateTimeInlineRow! = self?.form.rowBy(tag: "Ends")
if row.value?.compare(endRow.value!) == .orderedDescending {
endRow.value = Date(timeInterval: 60*60*24, since: row.value!)
endRow.cell!.backgroundColor = .white
endRow.updateCell()
}
}
.onExpandInlineRow { [weak self] cell, row, inlineRow in
inlineRow.cellUpdate() { cell, row in
let allRow: SwitchRow! = self?.form.rowBy(tag: "All-day")
if allRow.value ?? false {
cell.datePicker.datePickerMode = .date
}
else {
cell.datePicker.datePickerMode = .dateAndTime
}
}
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
<<< DateTimeInlineRow("Ends"){
$0.title = $0.tag
$0.value = Date().addingTimeInterval(60*60*25)
}
.onChange { [weak self] row in
let startRow: DateTimeInlineRow! = self?.form.rowBy(tag: "Starts")
if row.value?.compare(startRow.value!) == .orderedAscending {
row.cell!.backgroundColor = .red
}
else{
row.cell!.backgroundColor = .white
}
row.updateCell()
}
.onExpandInlineRow { [weak self] cell, row, inlineRow in
inlineRow.cellUpdate { cell, dateRow in
let allRow: SwitchRow! = self?.form.rowBy(tag: "All-day")
if allRow.value ?? false {
cell.datePicker.datePickerMode = .date
}
else {
cell.datePicker.datePickerMode = .dateAndTime
}
}
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
form +++
PushRow<RepeatInterval>("Repeat") {
$0.title = $0.tag
$0.options = RepeatInterval.allCases
$0.value = .Never
}.onPresent({ (_, vc) in
vc.enableDeselection = false
vc.dismissOnSelection = false
})
form +++
PushRow<EventAlert>() {
$0.title = "Alert"
$0.options = EventAlert.allCases
$0.value = .Never
}
.onChange { [weak self] row in
if row.value == .Never {
if let second : PushRow<EventAlert> = self?.form.rowBy(tag: "Another Alert"), let secondIndexPath = second.indexPath {
row.section?.remove(at: secondIndexPath.row)
}
}
else{
guard let _ : PushRow<EventAlert> = self?.form.rowBy(tag: "Another Alert") else {
let second = PushRow<EventAlert>("Another Alert") {
$0.title = $0.tag
$0.value = .Never
$0.options = EventAlert.allCases
}
row.section?.insert(second, at: row.indexPath!.row + 1)
return
}
}
}
form +++
PushRow<EventState>("Show As") {
$0.title = "Show As"
$0.options = EventState.allCases
}
form +++
URLRow("URL") {
$0.placeholder = "URL"
}
<<< TextAreaRow("notes") {
$0.placeholder = "Notes"
$0.textAreaHeight = .dynamic(initialTextViewHeight: 50)
}
}
@objc func cancelTapped(_ barButtonItem: UIBarButtonItem) {
(navigationController as? NativeEventNavigationController)?.onDismissCallback?(self)
}
enum RepeatInterval : String, CaseIterable, CustomStringConvertible {
case Never = "Never"
case Every_Day = "Every Day"
case Every_Week = "Every Week"
case Every_2_Weeks = "Every 2 Weeks"
case Every_Month = "Every Month"
case Every_Year = "Every Year"
var description : String { return rawValue }
}
enum EventAlert : String, CaseIterable, CustomStringConvertible {
case Never = "None"
case At_time_of_event = "At time of event"
case Five_Minutes = "5 minutes before"
case FifTeen_Minutes = "15 minutes before"
case Half_Hour = "30 minutes before"
case One_Hour = "1 hour before"
case Two_Hour = "2 hours before"
case One_Day = "1 day before"
case Two_Days = "2 days before"
var description : String { return rawValue }
}
enum EventState : CaseIterable {
case busy
case free
}
}
| mit | e36a099411755cd93a01380b75413a26 | 36.121495 | 142 | 0.47495 | 5.493776 | false | false | false | false |
danlozano/Filtr | Filtr/Classes/FilterStack.swift | 1 | 1818 | //
// FilterStack.swift
// Filtr
//
// Created by Daniel Lozano on 6/22/16.
// Copyright © 2016 danielozano. All rights reserved.
//
import Foundation
import CoreImage
public class FilterStack {
public var effectFilter: EffectFilter?
public var fadeFilter: FadeFilter?
public var dictionary: [String : String] {
var representation: [String : String] = [:]
if let effectFilter = effectFilter {
representation[Constants.Keys.effectFilterTypeKey] = effectFilter.type.rawValue
representation[Constants.Keys.effectFilterIntensityKey] = String(effectFilter.inputIntensity)
}
if let fadeFilter = fadeFilter {
representation[Constants.Keys.fadeFilterIntensityKey] = String(describing: fadeFilter.intensity)
}
return representation
}
public init() {
}
public init(dictionary: [String : String]) {
if let effectFilterType = dictionary[Constants.Keys.effectFilterTypeKey],
let type = EffectFilterType(rawValue: effectFilterType){
effectFilter = EffectFilter(type: type)
if let intensity = dictionary[Constants.Keys.effectFilterIntensityKey],
let floatIntensity = Float(intensity){
effectFilter?.inputIntensity = floatIntensity
}
}
if let fadeFilterIntensity = dictionary[Constants.Keys.fadeFilterIntensityKey],
let intensity = Float(fadeFilterIntensity){
fadeFilter = FadeFilter()
fadeFilter?.intensity = CGFloat(intensity)
}
}
public var activeFilters: [CIFilter] {
let allFilters: [CIFilter?] = [effectFilter, fadeFilter]
return allFilters.flatMap({ $0 })
}
}
| mit | f0a675f7996e54547da79fa31c960459 | 29.79661 | 108 | 0.632361 | 5.033241 | false | false | false | false |
lenssss/whereAmI | Whereami/Controller/Chat/ChatMainNavigationViewController.swift | 1 | 1435 | //
// ChatMainNavigationViewController.swift
// Whereami
//
// Created by WuQifei on 16/2/17.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
class ChatMainNavigationViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationBar.backgroundColor = UIColor.getNavigationBarColor()
// self.navigationBar.setBackgroundImage(UIImage.imageWithColor(UIColor(red: 81/255.0, green: 136/255.0, blue: 199/255.0, alpha: 1.0)), forBarMetrics: UIBarMetrics.Default)
self.navigationBar.shadowImage = UIImage.imageWithColor(UIColor.clearColor())
self.navigationBar.tintColor = UIColor.whiteColor()
self.navigationBar.barTintColor = UIColor.getNavigationBarColor()
self.navigationBar.translucent = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | cb540b454748b8ba90c688fb369d512f | 33.095238 | 179 | 0.705307 | 5.024561 | false | false | false | false |
YoungGary/30daysSwiftDemo | day1/day1/day1/ViewController.swift | 1 | 2759 | //
// ViewController.swift
// day1
//
// Created by YOUNG on 16/9/25.
// Copyright © 2016年 Young. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//constains
@IBOutlet weak var blackViewHeightCons: NSLayoutConstraint!
@IBOutlet weak var blueViewWidthCons: NSLayoutConstraint!
//控件属性
@IBOutlet weak var resetButton: UIButton!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var pauseButton: UIButton!
@IBOutlet weak var playButton: UIButton!
//定义属性
var time = 0.0
var isPlaying = false
var timer : NSTimer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
//constains
setupConstains()
//UI
setup()
timeLabel.text = String(time)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
//MARK:constains
extension ViewController{
private func setupConstains(){
blackViewHeightCons.constant = UIScreen.mainScreen().bounds.height * 0.4
blueViewWidthCons.constant = UIScreen.mainScreen().bounds.width * 0.45
}
}
//MARK:事件监听
extension ViewController{
private func setup(){
playButton.addTarget(self, action: #selector(ViewController.didClickPlayButton), forControlEvents: .TouchUpInside)
pauseButton.addTarget(self, action: #selector(ViewController.didClickPauseButton), forControlEvents: .TouchUpInside)
resetButton.addTarget(self, action: #selector(ViewController.didClickResetButton), forControlEvents: .TouchUpInside)
}
}
extension ViewController{
@objc private func didClickPlayButton(){//点击play
if isPlaying {
return
}
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(ViewController.timerFunction), userInfo: nil, repeats: true)
isPlaying = true
playButton.enabled = false
pauseButton.enabled = true
}
@objc private func didClickPauseButton(){//点击暂停
timeLabel.text = String(format: "%.1f",time)
timer.invalidate()
playButton.enabled = true
pauseButton.enabled = false
isPlaying = false
}
//NSTimer
@objc private func timerFunction(){
time += 0.1
timeLabel.text = String(format: "%.1f",time)
}
//点击reset
@objc private func didClickResetButton(){
time = 0.0
timer.invalidate()
timeLabel.text = String(time)
isPlaying = false
playButton.enabled = true
pauseButton.enabled = true
}
}
| mit | 5982af3f355fd0013443d50dbb2ae433 | 22.213675 | 154 | 0.638807 | 4.947177 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Tanh Distortion.xcplaygroundpage/Contents.swift | 1 | 1952 | //: ## Tanh Distortion
//: ##
//:
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
let player = try AKAudioPlayer(file: file)
player.looping = true
var distortion = AKTanhDistortion(player)
distortion.pregain = 1.0
distortion.postgain = 1.0
distortion.postiveShapeParameter = 1.0
distortion.negativeShapeParameter = 1.0
AudioKit.output = distortion
AudioKit.start()
player.play()
//: User Interface Set up
import AudioKitUI
class LiveView: AKLiveViewController {
override func viewDidLoad() {
addTitle("Tanh Distortion")
addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles))
addView(AKButton(title: "Stop Distortion") { button in
let node = distortion
node.isStarted ? node.stop() : node.play()
button.title = node.isStarted ? "Stop Distortion" : "Start Distortion"
})
addView(AKSlider(property: "Pre-gain", value: distortion.pregain, range: 0 ... 10) { sliderValue in
distortion.pregain = sliderValue
})
addView(AKSlider(property: "Post-gain", value: distortion.postgain, range: 0 ... 10) { sliderValue in
distortion.postgain = sliderValue
})
addView(AKSlider(property: "Postive Shape Parameter",
value: distortion.postiveShapeParameter,
range: -10 ... 10
) { sliderValue in
distortion.postiveShapeParameter = sliderValue
})
addView(AKSlider(property: "Negative Shape Parameter",
value: distortion.negativeShapeParameter,
range: -10 ... 10
) { sliderValue in
distortion.negativeShapeParameter = sliderValue
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| mit | ebb735b73623fc7a8c3bf91be5815aeb | 29.984127 | 109 | 0.65625 | 4.692308 | false | false | false | false |
vadymmarkov/Faker | Tests/Fakery/Generators/HobbitSpec.swift | 3 | 1233 | import Quick
import Nimble
@testable import Fakery
final class HobbitSpec: QuickSpec {
override func spec() {
describe("Hobbit") {
var hobbit: Faker.Hobbit!
beforeEach {
let parser = Parser(locale: "en-TEST")
hobbit = Faker.Hobbit(parser: parser)
}
describe("#character") {
it("returns the correct text") {
let character = hobbit.character()
expect(character).to(equal("Bilbo Baggins"))
}
}
describe("#thorins_company") {
it("returns the correct text") {
let thorinsCompany = hobbit.thorinsCompany()
expect(thorinsCompany).to(equal("Thorin Oakenshield"))
}
}
describe("#quote") {
it("returns the correct text") {
let quote = hobbit.quote()
expect(quote).to(equal("Do you wish me a good morning, or mean that it is a good morning whether I want it or"
+ " not; or that you feel good this morning; or that it is a morning to be good on?"))
}
}
describe("#location") {
it("returns the correct text") {
let location = hobbit.location()
expect(location).to(equal("Bree"))
}
}
}
}
}
| mit | 445a33d4da72804fd03c1816a80ca713 | 26.4 | 120 | 0.568532 | 3.939297 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit | SwiftKit/netWork/BQRequest.swift | 1 | 1430 | //
// BQRequest.swift
// BQTabBarTest
//
// Created by MrBai on 2017/7/20.
// Copyright © 2017年 MrBai. All rights reserved.
//
import UIKit
class BQRequest: NSObject {
var method: HTTPMethod = .post
var result: Any?
weak var task: URLSessionTask?
public func url() -> String { return "" }
public func toDiction() -> [String: Any] {
let mir = Mirror(reflecting: self)
var dict = [String: AnyObject]()
for p in mir.children {
if p.label == "method" || p.label == "result" || p.label == "task"{
continue
}
dict[p.label!] = (p.value as AnyObject)
}
return dict
}
public func responseAction(data: Data?, response: URLResponse?, error: Error?) {
if let data = data {
do {
self.result = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
} catch let err as NSError {
print(err.localizedDescription)
}
}
if let error = error {
print(error.localizedDescription)
}
}
deinit {
print("request释放")
if let task = self.task{
if task.state == .running || task.state == .suspended {
print("cancel \(task)")
task.cancel()
}
self.task = nil
print("释放task")
}
}
}
| apache-2.0 | 4f711922447ab272e6735e8509766efa | 26.823529 | 100 | 0.51797 | 4.261261 | false | false | false | false |
uphold/uphold-sdk-ios | Tests/IntegrationTests/ClientTests/UpholdRestAdapterTest.swift | 1 | 13123 | import XCTest
import ObjectMapper
import PromiseKit
import UpholdSdk
@testable import SwiftClient
/// UpholdRestAdapter integration tests.
class UpholdRestAdapterTest: UpholdTestCase {
func testBuildRequestShouldReturnRequest() {
let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
XCTAssertEqual(request.headers["user-agent"], String(format: "uphold-ios-sdk/%@ (%@)", GlobalConfigurations.UPHOLD_SDK_VERSION, GlobalConfigurations.SDK_GITHUB_URL), "Failed: Wrong headers.")
XCTAssertEqual(request.method, "foo", "Failed: Wrong method.")
XCTAssertNil(request.data, "Failed: Wrong body.")
}
func testBuildEmptyResponseShouldReturnBadRequestError() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let mockRequest = MockRequest(body: nil, code: 400, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<Response> = UpholdRestAdapter().buildEmptyResponse(request: request)
promise.catch(execute: { (error: Error) in
guard let badRequestError = error as? BadRequestError else {
XCTFail("Error should be BadRequestError.")
return
}
XCTAssertEqual(badRequestError.code, 400, "Failed: Wrong response HTTP status code.")
XCTAssertEqual(badRequestError.info["Bad request error"], "HTTP error 400 - Bad request.", "Failed: Wrong message.")
testExpectation.fulfill()
})
wait()
}
func testBuildEmptyResponseShouldReturnFulfilledPromise() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<Response> = UpholdRestAdapter().buildEmptyResponse(request: request)
promise.then { (response: Response) -> Void in
XCTAssertEqual(response.basicStatus, Response.BasicResponseType.ok, "Failed: Wrong response basic status code.")
XCTAssertNil(response.text, "Failed: Wrong response body.")
testExpectation.fulfill()
}.catch(execute: { (_: Error) in
XCTFail("Uphold REST adapter response test error.")
})
wait()
}
func testBuildEmptyResponseWithBodyShouldReturnFulfilledPromise() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let mockRequest = MockRequest(body: "", code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<Response> = UpholdRestAdapter().buildEmptyResponse(request: request)
promise.then { (response: Response) -> Void in
XCTAssertEqual(response.basicStatus, Response.BasicResponseType.ok, "Failed: Wrong response basic status code.")
XCTAssertEqual(response.text, "", "Failed: Wrong response body.")
testExpectation.fulfill()
}.catch(execute: { (_: Error) in
XCTFail("Uphold REST adapter response test error.")
})
wait()
}
func testBuildEmptyResponseShouldReturnLogicError() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let mockRequest = MockRequest(body: "foobar", code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<Response> = UpholdRestAdapter().buildEmptyResponse(request: request)
promise.catch(execute: { (error: Error) in
guard let logicError = error as? LogicError else {
XCTFail("Error should be LogicError.")
return
}
XCTAssertEqual(logicError.info, ["Logic error": "Response body should be empty."], "Failed: Wrong error message.")
XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.")
testExpectation.fulfill()
return
})
wait()
}
func testBuildResponseShouldReturnBadRequestError() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let json = "{" +
"\"ask\":\"1.2\"," +
"\"bid\":\"1\"," +
"\"currency\":\"BTC\"," +
"\"pair\":\"BTCBTC\"" +
"}"
let mockRequest = MockRequest(body: json, code: 400, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<Rate> = UpholdRestAdapter().buildResponse(request: request)
promise.catch(execute: { (error: Error) in
guard let badRequestError = error as? BadRequestError else {
XCTFail("Error should be BadRequestError.")
return
}
XCTAssertEqual(badRequestError.code, 400, "Failed: Wrong response HTTP status code.")
XCTAssertEqual(badRequestError.info["Bad request error"], "HTTP error 400 - Bad request.", "Failed: Wrong message.")
testExpectation.fulfill()
return
})
wait()
}
func testBuildResponseShouldReturnEmptyBodyLogicError() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<Rate> = UpholdRestAdapter().buildResponse(request: request)
promise.catch(execute: { (error: Error) in
guard let logicError = error as? LogicError else {
XCTFail("Error should be LogicError.")
return
}
XCTAssertEqual(logicError.info, ["Logic error": "Response body should not be empty."], "Failed: Wrong error message.")
XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.")
testExpectation.fulfill()
return
})
wait()
}
func testBuildResponseShouldReturnFailedMapLogicError() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let json = "{[" +
"\"ask\":\"1.2\"," +
"\"bid\":\"1\"," +
"\"currency\":\"BTC\"," +
"\"pair\":\"BTCBTC\"" +
"}"
let mockRequest = MockRequest(body: json, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<Rate> = UpholdRestAdapter().buildResponse(request: request)
promise.catch(execute: { (error: Error) in
guard let logicError = error as? LogicError else {
XCTFail("Error should be LogicError.")
return
}
XCTAssertEqual(logicError.info, ["Logic error": "Failed to map the JSON object."], "Failed: Wrong error message.")
XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.")
testExpectation.fulfill()
return
})
wait()
}
func testBuildResponseShouldReturnFulfilledPromise() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let json = "{" +
"\"ask\":\"1.2\"," +
"\"bid\":\"1\"," +
"\"currency\":\"BTC\"," +
"\"pair\":\"BTCBTC\"" +
"}"
let mockRequest = MockRequest(body: json, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<Rate> = UpholdRestAdapter().buildResponse(request: request)
promise.then { (rate: Rate) -> Void in
XCTAssertEqual(rate.ask, "1.2", "Failed: Wrong response object attribute.")
XCTAssertEqual(rate.bid, "1", "Failed: Wrong response object attribute.")
XCTAssertEqual(rate.currency, "BTC", "Failed: Wrong response object attribute.")
XCTAssertEqual(rate.pair, "BTCBTC", "Failed: Wrong response object attribute.")
testExpectation.fulfill()
}.catch(execute: { (_: Error) in
XCTFail("Uphold REST adapter response test error.")
})
wait()
}
func testBuildResponseArrayShouldReturnBadRequestError() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let json = "[{\"ask\":\"1\"}, {\"ask\":\"440.99\"}]"
let mockRequest = MockRequest(body: json, code: 400, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request: request)
promise.catch(execute: { (error: Error) in
guard let badRequestError = error as? BadRequestError else {
XCTFail("Error should be BadRequestError.")
return
}
XCTAssertEqual(badRequestError.code, 400, "Failed: Wrong response HTTP status code.")
XCTAssertEqual(badRequestError.info["Bad request error"], "HTTP error 400 - Bad request.", "Failed: Wrong message.")
testExpectation.fulfill()
return
})
wait()
}
func testBuildResponseArrayShouldReturnEmptyBodyLogicError() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request: request)
promise.catch(execute: { (error: Error) in
guard let logicError = error as? LogicError else {
XCTFail("Error should be LogicError.")
return
}
XCTAssertEqual(logicError.info, ["Logic error": "Response body should not be empty."], "Failed: Wrong error message.")
XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.")
testExpectation.fulfill()
return
})
wait()
}
func testBuildResponseArrayShouldReturnFailedMapLogicError() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let jsonRates = "[[{\"ask\":\"1\"}, {\"ask\":\"440.99\"}]"
let mockRequest = MockRequest(body: jsonRates, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request: request)
promise.catch(execute: { (error: Error) in
guard let logicError = error as? LogicError else {
XCTFail("Error should be LogicError.")
return
}
XCTAssertEqual(logicError.info, ["Logic error": "Failed to map the JSON object."], "Failed: Wrong error message.")
XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.")
testExpectation.fulfill()
return
})
wait()
}
func testBuildResponseArrayShouldReturnFulfilledPromise() {
let testExpectation = expectation(description: "Uphold REST adapter response test.")
let jsonRates = "[{\"ask\":\"1\"}, {\"ask\":\"440.99\"}]"
let mockRequest = MockRequest(body: jsonRates, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo")
let request = UpholdRestAdapter().buildRequest(request: mockRequest)
let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request: request)
promise.then { (rates: [Rate]) -> Void in
XCTAssertEqual(rates.count, 2, "Failed: Wrong response object size.")
XCTAssertEqual(rates[0].ask, "1", "Failed: Wrong response object attribute.")
XCTAssertEqual(rates[1].ask, "440.99", "Failed: Wrong response object attribute.")
testExpectation.fulfill()
}.catch(execute: { (_: Error) in
XCTFail("Uphold REST adapter response test error.")
})
wait()
}
}
| mit | 10623652d856ef6318fb71e01fcf13b6 | 40.397476 | 199 | 0.624933 | 4.763339 | false | true | false | false |
saagarjha/iina | iina/PowerSource.swift | 3 | 1219 | //
// PowerSource.swift
// iina
//
// Created by Collider LI on 13/12/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Cocoa
import IOKit.ps
class PowerSource {
var type: String?
var isCharging: Bool?
var isCharged: Bool?
var timeToFullyCharge: Int?
var timeToEmpty: Int?
var maxCapacity: Int?
var currentCapacity: Int?
class func getList() -> [PowerSource] {
let info = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let list = IOPSCopyPowerSourcesList(info).takeRetainedValue() as [CFTypeRef]
var result: [PowerSource] = []
for item in list {
if let desc = IOPSGetPowerSourceDescription(info, item).takeUnretainedValue() as? [String: Any] {
let ps = PowerSource()
ps.type = desc[kIOPSTypeKey] as? String
ps.isCharging = desc[kIOPSIsChargingKey] as? Bool
ps.isCharged = desc[kIOPSIsChargedKey] as? Bool
ps.maxCapacity = desc[kIOPSMaxCapacityKey] as? Int
ps.currentCapacity = desc[kIOPSCurrentCapacityKey] as? Int
ps.timeToEmpty = desc[kIOPSTimeToEmptyKey] as? Int
ps.timeToFullyCharge = desc[kIOPSTimeToFullChargeKey] as? Int
result.append(ps)
}
}
return result
}
}
| gpl-3.0 | c12fa131eda62d84661520f4aefaad19 | 26.066667 | 103 | 0.678161 | 3.55102 | false | false | false | false |
coderLL/PageView | TestPageVIew/TestPageVIew/PageView/PageTitleView.swift | 1 | 6707 | //
// PageTitleView.swift
// DYTV
//
// Created by coderLL on 16/9/28.
// Copyright © 2016年 coderLL. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate : class {
func pageTitltView(titleView: PageTitleView, selectedIndex index : Int)
}
// MARK:- 定义常量
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 {
// MARK:- 定义属性
private var currentIndex : Int = 0
var titles:[String]
weak var delegate : PageTitleViewDelegate?
// MARK:- 懒加载属性
private lazy var titleLabels: [UILabel] = [UILabel]()
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
private lazy var scrollLine: UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orangeColor()
return scrollLine
}()
// MARK:- 自定义构造函数
init(frame: CGRect, titles: [String]) {
self.titles = titles;
super.init(frame: frame);
// 设置UI界面
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面
extension PageTitleView {
private func setupUI() {
// 1.添加UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
// 2.添加titles对应的Label
setupTitleLabels()
// 3.设置底线和滚动的滑块
setupBottomLineAndScrollLine()
}
private func setupTitleLabels() {
// 0.确定lable的一些frame值
let labelW : CGFloat = frame.width/CGFloat(titles.count)
let labelH : CGFloat = frame.height - kScrollLineH
let labelY : CGFloat = 0
for (index, title) in titles.enumerate() {
// 1.创建UILabel
let label = UILabel()
// 2.设置Label的属性
label.text = title
label.tag = index
label.font = UIFont.systemFontOfSize(16.0)
label.textColor = UIColor(red: kNormalColor.0/255.0, green: kNormalColor.1/255.0, blue: kNormalColor.2/255.0, alpha: 1.0)
label.textAlignment = .Center
// 3.设置Label的frame
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
// 4.将label添加到scrollView上和titleLabels数组中
scrollView.addSubview(label)
titleLabels.append(label)
// 5.给Lable添加手势
label.userInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: Selector("titleLabelClick:"))
label.addGestureRecognizer(tapGes)
}
}
private func setupBottomLineAndScrollLine() {
// 1.添加底线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGrayColor()
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
// 2.添加滚动的滑块
// 2.1 获取第一个Label
guard let firstLabel = titleLabels.first else { return}
firstLabel.textColor = UIColor(red: kSelectColor.0/255.0, green: kSelectColor.1/255.0, blue: kSelectColor.2/255.0, alpha: 1.0)
// 2.2 设置scrollLine的属性
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH)
}
}
// MARK:- 监听Label的点击
extension PageTitleView {
@objc private func titleLabelClick(tapGes: UITapGestureRecognizer) {
// 0.获取当前Label
guard let currentLabel = tapGes.view as? UILabel else { return }
// 1.判断是否是重复点击同一个Label, 若是则直接返回
if currentLabel.tag == currentIndex { return }
// 2.获取之前的Label
let oldLabel = titleLabels[currentIndex]
// 3.切换文字的颜色
currentLabel.textColor = UIColor(red: kSelectColor.0/255.0, green: kSelectColor.1/255.0, blue: kSelectColor.2/255.0, alpha: 1.0)
oldLabel.textColor = UIColor(red: kNormalColor.0/255.0, green: kNormalColor.1/255.0, blue: kNormalColor.2/255.0, alpha: 1.0)
// 4.保存更新Label的下标值
currentIndex = currentLabel.tag
// 5.滚动条位置发生改变
let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width
// 6.动画
UIView.animateWithDuration(0.15) {
self.scrollLine.frame.origin.x = scrollLineX
}
// 7.通知代理
delegate?.pageTitltView(self, selectedIndex: currentIndex)
}
}
// MARK:- 对外暴露的方法
extension PageTitleView {
func setTitleWithProgress(progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
// 1.取出sourceLabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
// 2.处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
// 3.处理颜色的渐变(复杂)
// 3.1 取出变化的范围(元组类型)
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
// 3.2变化sourceLabel
sourceLabel.textColor = UIColor(red: (kSelectColor.0 - colorDelta.0 * progress)/255.0, green: (kSelectColor.1 - colorDelta.1 * progress)/255.0, blue: (kSelectColor.2 - colorDelta.2 * progress)/255.0, alpha: 1.0)
// 3.2变化targetLabel
targetLabel.textColor = UIColor(red: (kNormalColor.0 + colorDelta.0 * progress)/255.0, green: (kNormalColor.1 + colorDelta.1 * progress)/255.0, blue: (kNormalColor.2 + colorDelta.2 * progress)/255.0, alpha: 1.0)
// 3.记录最新的index
currentIndex = targetIndex
}
} | mit | af5a53ec32a1de0ce3128e8be51745c7 | 32.854839 | 219 | 0.61277 | 4.44319 | false | false | false | false |
iOS-Swift-Developers/Swift | 实战前技术点/15.JQGiftAnimation-送礼物/JQGiftAnimation/JQGiftAnimation/JQGiftModel.swift | 1 | 863 | //
// JQGiftModel.swift
// JQGiftAnimation
//
// Created by 韩俊强 on 2017/7/28.
// Copyright © 2017年 HaRi. All rights reserved.
//
import UIKit
class JQGiftModel: NSObject {
var senderName : String = ""
var senderURL : String = ""
var giftName : String = ""
var giftURL : String = ""
init(senderName : String, senderURL : String, giftName : String, giftURL : String) {
self.senderName = senderName
self.senderURL = senderURL
self.giftName = giftName
self.giftURL = giftURL
}
override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? JQGiftModel else {
return false
}
guard object.giftName == giftName && object.senderName == senderName else {
return false
}
return true
}
}
| mit | ad3257697ec2958d179c79a7fd5c6201 | 23.4 | 88 | 0.580796 | 4.186275 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.