repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
ranacquat/fish | Shared/FSAlbumView.swift | 1 | 21347 | //
// FSAlbumView.swift
// Fusuma
//
// Created by Yuta Akizuki on 2015/11/14.
// Copyright © 2015年 ytakzk. All rights reserved.
//
import UIKit
import Photos
@objc public protocol FSAlbumViewDelegate: class {
func albumViewCameraRollUnauthorized()
func albumViewCameraRollAuthorized()
}
final class FSAlbumView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, PHPhotoLibraryChangeObserver, UIGestureRecognizerDelegate {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var imageCropView: FSImageCropView!
@IBOutlet weak var imageCropViewContainer: UIView!
@IBOutlet weak var collectionViewConstraintHeight: NSLayoutConstraint!
@IBOutlet weak var imageCropViewConstraintTop: NSLayoutConstraint!
weak var delegate: FSAlbumViewDelegate? = nil
var images: PHFetchResult<PHAsset>!
var imageManager: PHCachingImageManager?
var previousPreheatRect: CGRect = .zero
let cellSize = CGSize(width: 100, height: 100)
var phAsset: PHAsset!
// Variables for calculating the position
enum Direction {
case scroll
case stop
case up
case down
}
let imageCropViewOriginalConstraintTop: CGFloat = 50
let imageCropViewMinimalVisibleHeight: CGFloat = 100
var dragDirection = Direction.up
var imaginaryCollectionViewOffsetStartPosY: CGFloat = 0.0
var cropBottomY: CGFloat = 0.0
var dragStartPos: CGPoint = CGPoint.zero
let dragDiff: CGFloat = 20.0
static func instance() -> FSAlbumView {
return UINib(nibName: "FSAlbumViewAdaptive", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSAlbumView
}
func initialize() {
if images != nil {
return
}
self.isHidden = false
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(FSAlbumView.panned(_:)))
panGesture.delegate = self
self.addGestureRecognizer(panGesture)
collectionViewConstraintHeight.constant = self.frame.height - imageCropView.frame.height - imageCropViewOriginalConstraintTop
imageCropViewConstraintTop.constant = 50
dragDirection = Direction.up
imageCropViewContainer.layer.shadowColor = UIColor.black.cgColor
imageCropViewContainer.layer.shadowRadius = 30.0
imageCropViewContainer.layer.shadowOpacity = 0.9
imageCropViewContainer.layer.shadowOffset = CGSize.zero
collectionView.register(UINib(nibName: "FSAlbumViewCell", bundle: Bundle(for: self.classForCoder)), forCellWithReuseIdentifier: "FSAlbumViewCell")
collectionView.backgroundColor = fusumaBackgroundColor
// Never load photos Unless the user allows to access to photo album
checkPhotoAuth()
// Sorting condition
let options = PHFetchOptions()
options.sortDescriptors = [
NSSortDescriptor(key: "creationDate", ascending: false)
]
images = PHAsset.fetchAssets(with: .image, options: options)
if images.count > 0 {
changeImage(images[0])
collectionView.reloadData()
collectionView.selectItem(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: UICollectionViewScrollPosition())
}
PHPhotoLibrary.shared().register(self)
}
deinit {
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func panned(_ sender: UITapGestureRecognizer) {
if sender.state == UIGestureRecognizerState.began {
let view = sender.view
let loc = sender.location(in: view)
let subview = view?.hitTest(loc, with: nil)
if subview == imageCropView && imageCropViewConstraintTop.constant == imageCropViewOriginalConstraintTop {
return
}
dragStartPos = sender.location(in: self)
cropBottomY = self.imageCropViewContainer.frame.origin.y + self.imageCropViewContainer.frame.height
// Move
if dragDirection == Direction.stop {
dragDirection = (imageCropViewConstraintTop.constant == imageCropViewOriginalConstraintTop) ? Direction.up : Direction.down
}
// Scroll event of CollectionView is preferred.
if (dragDirection == Direction.up && dragStartPos.y < cropBottomY + dragDiff) ||
(dragDirection == Direction.down && dragStartPos.y > cropBottomY) {
dragDirection = Direction.stop
imageCropView.changeScrollable(false)
} else {
imageCropView.changeScrollable(true)
}
} else if sender.state == UIGestureRecognizerState.changed {
let currentPos = sender.location(in: self)
if dragDirection == Direction.up && currentPos.y < cropBottomY - dragDiff {
imageCropViewConstraintTop.constant = max(imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height, currentPos.y + dragDiff - imageCropViewContainer.frame.height)
collectionViewConstraintHeight.constant = min(self.frame.height - imageCropViewMinimalVisibleHeight, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height)
} else if dragDirection == Direction.down && currentPos.y > cropBottomY {
imageCropViewConstraintTop.constant = min(imageCropViewOriginalConstraintTop, currentPos.y - imageCropViewContainer.frame.height)
collectionViewConstraintHeight.constant = max(self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height)
} else if dragDirection == Direction.stop && collectionView.contentOffset.y < 0 {
dragDirection = Direction.scroll
imaginaryCollectionViewOffsetStartPosY = currentPos.y
} else if dragDirection == Direction.scroll {
imageCropViewConstraintTop.constant = imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height + currentPos.y - imaginaryCollectionViewOffsetStartPosY
collectionViewConstraintHeight.constant = max(self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height, self.frame.height - imageCropViewConstraintTop.constant - imageCropViewContainer.frame.height)
}
} else {
imaginaryCollectionViewOffsetStartPosY = 0.0
if sender.state == UIGestureRecognizerState.ended && dragDirection == Direction.stop {
imageCropView.changeScrollable(true)
return
}
let currentPos = sender.location(in: self)
if currentPos.y < cropBottomY - dragDiff && imageCropViewConstraintTop.constant != imageCropViewOriginalConstraintTop {
// The largest movement
imageCropView.changeScrollable(false)
imageCropViewConstraintTop.constant = imageCropViewMinimalVisibleHeight - self.imageCropViewContainer.frame.height
collectionViewConstraintHeight.constant = self.frame.height - imageCropViewMinimalVisibleHeight
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
dragDirection = Direction.down
} else {
// Get back to the original position
imageCropView.changeScrollable(true)
imageCropViewConstraintTop.constant = imageCropViewOriginalConstraintTop
collectionViewConstraintHeight.constant = self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
dragDirection = Direction.up
}
}
}
// MARK: - UICollectionViewDelegate Protocol
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FSAlbumViewCell", for: indexPath) as! FSAlbumViewCell
let currentTag = cell.tag + 1
cell.tag = currentTag
let asset = self.images[(indexPath as NSIndexPath).item]
self.imageManager?.requestImage(for: asset,
targetSize: cellSize,
contentMode: .aspectFill,
options: nil) {
result, info in
if cell.tag == currentTag {
cell.image = result
// CAT
/*
asset.requestContentEditingInput(with: nil) { (contentEditingInput: PHContentEditingInput?, _) -> Void in
//Get full image
let url = contentEditingInput!.fullSizeImageURL
let orientation = contentEditingInput!.fullSizeImageOrientation
var inputImage = CIImage(contentsOf: url!)
inputImage = inputImage!.applyingOrientation(orientation)
for (key, value) in inputImage!.properties {
print("key: \(key)")
print("value: \(value)")
}
}
*/
if let location = asset.location {
Localizator().getAddress(location: location, completion: {
answer in
print("ADDRESS TRANSLATED IN FSALBUMVIEW")
cell.imageDescription = "\(answer!)\n\(self.getDate(date: asset.creationDate!))"
})
}
}
}
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images == nil ? 0 : images.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let width = (collectionView.frame.width - 3) / 4
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
changeImage(images[(indexPath as NSIndexPath).row])
imageCropView.changeScrollable(true)
imageCropViewConstraintTop.constant = imageCropViewOriginalConstraintTop
collectionViewConstraintHeight.constant = self.frame.height - imageCropViewOriginalConstraintTop - imageCropViewContainer.frame.height
UIView.animate(withDuration: 0.2, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
dragDirection = Direction.up
collectionView.scrollToItem(at: indexPath, at: .top, animated: true)
}
// MARK: - ScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == collectionView {
self.updateCachedAssets()
}
}
//MARK: - PHPhotoLibraryChangeObserver
func photoLibraryDidChange(_ changeInstance: PHChange) {
DispatchQueue.main.async {
let collectionChanges = changeInstance.changeDetails(for: self.images)
if collectionChanges != nil {
self.images = collectionChanges!.fetchResultAfterChanges
let collectionView = self.collectionView!
if !collectionChanges!.hasIncrementalChanges || collectionChanges!.hasMoves {
collectionView.reloadData()
} else {
collectionView.performBatchUpdates({
let removedIndexes = collectionChanges!.removedIndexes
if (removedIndexes?.count ?? 0) != 0 {
collectionView.deleteItems(at: removedIndexes!.aapl_indexPathsFromIndexesWithSection(0))
}
let insertedIndexes = collectionChanges!.insertedIndexes
if (insertedIndexes?.count ?? 0) != 0 {
collectionView.insertItems(at: insertedIndexes!.aapl_indexPathsFromIndexesWithSection(0))
}
let changedIndexes = collectionChanges!.changedIndexes
if (changedIndexes?.count ?? 0) != 0 {
collectionView.reloadItems(at: changedIndexes!.aapl_indexPathsFromIndexesWithSection(0))
}
}, completion: nil)
}
self.resetCachedAssets()
}
}
}
}
internal extension UICollectionView {
func aapl_indexPathsForElementsInRect(_ rect: CGRect) -> [IndexPath] {
let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect)
if (allLayoutAttributes?.count ?? 0) == 0 {return []}
var indexPaths: [IndexPath] = []
indexPaths.reserveCapacity(allLayoutAttributes!.count)
for layoutAttributes in allLayoutAttributes! {
let indexPath = layoutAttributes.indexPath
indexPaths.append(indexPath)
}
return indexPaths
}
}
internal extension IndexSet {
func aapl_indexPathsFromIndexesWithSection(_ section: Int) -> [IndexPath] {
var indexPaths: [IndexPath] = []
indexPaths.reserveCapacity(self.count)
(self as NSIndexSet).enumerate({idx, stop in
indexPaths.append(IndexPath(item: idx, section: section))
})
return indexPaths
}
}
private extension FSAlbumView {
func changeImage(_ asset: PHAsset) {
self.imageCropView.image = nil
self.phAsset = asset
DispatchQueue.global(qos: .default).async(execute: {
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
self.imageManager?.requestImage(for: asset,
targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight),
contentMode: .aspectFill,
options: options) {
result, info in
DispatchQueue.main.async(execute: {
self.imageCropView.imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
self.imageCropView.image = result
})
}
})
}
// Check the status of authorization for PHPhotoLibrary
func checkPhotoAuth() {
PHPhotoLibrary.requestAuthorization { (status) -> Void in
switch status {
case .authorized:
self.imageManager = PHCachingImageManager()
if self.images != nil && self.images.count > 0 {
self.changeImage(self.images[0])
}
DispatchQueue.main.async {
self.delegate?.albumViewCameraRollAuthorized()
}
case .restricted, .denied:
DispatchQueue.main.async(execute: { () -> Void in
self.delegate?.albumViewCameraRollUnauthorized()
})
default:
break
}
}
}
// MARK: - Asset Caching
func resetCachedAssets() {
imageManager?.stopCachingImagesForAllAssets()
previousPreheatRect = CGRect.zero
}
func updateCachedAssets() {
var preheatRect = self.collectionView!.bounds
preheatRect = preheatRect.insetBy(dx: 0.0, dy: -0.5 * preheatRect.height)
let delta = abs(preheatRect.midY - self.previousPreheatRect.midY)
if delta > self.collectionView!.bounds.height / 3.0 {
var addedIndexPaths: [IndexPath] = []
var removedIndexPaths: [IndexPath] = []
self.computeDifferenceBetweenRect(self.previousPreheatRect, andRect: preheatRect, removedHandler: {removedRect in
let indexPaths = self.collectionView.aapl_indexPathsForElementsInRect(removedRect)
removedIndexPaths += indexPaths
}, addedHandler: {addedRect in
let indexPaths = self.collectionView.aapl_indexPathsForElementsInRect(addedRect)
addedIndexPaths += indexPaths
})
let assetsToStartCaching = self.assetsAtIndexPaths(addedIndexPaths)
let assetsToStopCaching = self.assetsAtIndexPaths(removedIndexPaths)
self.imageManager?.startCachingImages(for: assetsToStartCaching,
targetSize: cellSize,
contentMode: .aspectFill,
options: nil)
self.imageManager?.stopCachingImages(for: assetsToStopCaching,
targetSize: cellSize,
contentMode: .aspectFill,
options: nil)
self.previousPreheatRect = preheatRect
}
}
func computeDifferenceBetweenRect(_ oldRect: CGRect, andRect newRect: CGRect, removedHandler: (CGRect)->Void, addedHandler: (CGRect)->Void) {
if newRect.intersects(oldRect) {
let oldMaxY = oldRect.maxY
let oldMinY = oldRect.minY
let newMaxY = newRect.maxY
let newMinY = newRect.minY
if newMaxY > oldMaxY {
let rectToAdd = CGRect(x: newRect.origin.x, y: oldMaxY, width: newRect.size.width, height: (newMaxY - oldMaxY))
addedHandler(rectToAdd)
}
if oldMinY > newMinY {
let rectToAdd = CGRect(x: newRect.origin.x, y: newMinY, width: newRect.size.width, height: (oldMinY - newMinY))
addedHandler(rectToAdd)
}
if newMaxY < oldMaxY {
let rectToRemove = CGRect(x: newRect.origin.x, y: newMaxY, width: newRect.size.width, height: (oldMaxY - newMaxY))
removedHandler(rectToRemove)
}
if oldMinY < newMinY {
let rectToRemove = CGRect(x: newRect.origin.x, y: oldMinY, width: newRect.size.width, height: (newMinY - oldMinY))
removedHandler(rectToRemove)
}
} else {
addedHandler(newRect)
removedHandler(oldRect)
}
}
func assetsAtIndexPaths(_ indexPaths: [IndexPath]) -> [PHAsset] {
if indexPaths.count == 0 { return [] }
var assets: [PHAsset] = []
assets.reserveCapacity(indexPaths.count)
for indexPath in indexPaths {
let asset = self.images[(indexPath as NSIndexPath).item]
assets.append(asset)
}
return assets
}
func getDate(date:Date)->String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
return dateFormatter.string(from: date)
}
}
| mit |
cuappdev/tcat-ios | TCAT/Views/SummaryView.swift | 1 | 7413 | //
// SummaryView.swift
// TCAT
//
// Created by Matthew Barker on 2/26/17.
// Copyright © 2017 cuappdev. All rights reserved.
//
import UIKit
class SummaryView: UIView {
private var iconView: UIView!
private let labelsContainerView = UIView()
private let liveIndicator = LiveIndicator(size: .small, color: .clear)
private let mainLabel = UILabel()
private let secondaryLabel = UILabel()
private let tab = UIView()
private let tabSize = CGSize(width: 32, height: 4)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(route: Route) {
// View Initialization
super.init(frame: .zero)
// TODO:
// This value ends up getting overwritten by constraints, which is what we want,
// but for some reason if it is not set prior to writing the constraints, the
// entire view comes out blank. I'm still investigating but it seems to be an,
// issue with the Pulley Pod that we're using.
frame.size = CGSize(width: UIScreen.main.bounds.width, height: 100)
backgroundColor = Colors.backgroundWash
roundCorners(corners: [.topLeft, .topRight], radius: 16)
setupTab()
setupLabelsContainerView(for: route)
setIcon(for: route)
setupConstraints()
}
func setupTab() {
tab.backgroundColor = Colors.metadataIcon
tab.layer.cornerRadius = tabSize.height / 2
tab.clipsToBounds = true
addSubview(tab)
}
func setupLabelsContainerView(for route: Route) {
setupMainLabel(for: route)
setupSecondaryLabel(for: route)
setupLabelConstraints()
addSubview(labelsContainerView)
}
func setupMainLabel(for route: Route) {
mainLabel.font = .getFont(.regular, size: 16)
mainLabel.textColor = Colors.primaryText
mainLabel.numberOfLines = 0
mainLabel.allowsDefaultTighteningForTruncation = true
mainLabel.lineBreakMode = .byTruncatingTail
configureMainLabelText(for: route)
labelsContainerView.addSubview(mainLabel)
}
func setupSecondaryLabel(for route: Route) {
secondaryLabel.font = .getFont(.regular, size: 12)
secondaryLabel.textColor = Colors.metadataIcon
secondaryLabel.text = "Trip Duration: \(route.totalDuration) minute\(route.totalDuration == 1 ? "" : "s")"
labelsContainerView.addSubview(secondaryLabel)
}
func setupLabelConstraints() {
let labelSpacing: CGFloat = 4
mainLabel.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
}
secondaryLabel.snp.makeConstraints { make in
make.top.equalTo(mainLabel.snp.bottom).offset(labelSpacing).priority(.high)
make.leading.trailing.equalTo(mainLabel)
make.bottom.equalToSuperview()
}
}
func setupConstraints() {
let labelLeadingInset = 120
let labelsContainerViewToTabSpacing: CGFloat = 10
let labelsContainerViewToBottomSpacing: CGFloat = 16
let tabTopInset: CGFloat = 6
let textLabelPadding: CGFloat = 16
let walkIconSize = CGSize(width: iconView.intrinsicContentSize.width * 2, height: iconView.intrinsicContentSize.height * 2)
tab.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.top.equalToSuperview().inset(tabTopInset)
make.size.equalTo(tabSize)
}
labelsContainerView.snp.makeConstraints { make in
make.top.equalTo(tab.snp.bottom).offset(labelsContainerViewToTabSpacing).priority(.high)
make.leading.equalToSuperview().inset(labelLeadingInset)
make.trailing.equalToSuperview().inset(textLabelPadding).priority(.high)
make.bottom.equalToSuperview().inset(labelsContainerViewToBottomSpacing)
}
iconView.snp.makeConstraints { make in
if iconView is UIImageView {
make.size.equalTo(walkIconSize)
} else if iconView is BusIcon {
make.size.equalTo(iconView.intrinsicContentSize)
}
make.centerY.equalToSuperview()
make.centerX.equalTo(labelLeadingInset/2)
}
}
/// Update summary card data and position accordingly
private func configureMainLabelText(for route: Route) {
let mainLabelBoldFont: UIFont = .getFont(.semibold, size: 14)
if let departDirection = (route.directions.filter { $0.type == .depart }).first {
var color: UIColor = Colors.primaryText
let content = "Depart at \(departDirection.startTimeWithDelayDescription) from \(departDirection.name)"
// This changes font to standard size. Label's font is different.
var attributedString = departDirection.startTimeWithDelayDescription.bold(
in: content,
from: mainLabel.font,
to: mainLabelBoldFont)
attributedString = departDirection.name.bold(in: attributedString, to: mainLabelBoldFont)
mainLabel.attributedText = attributedString
if let delay = departDirection.delay {
color = delay >= 60 ? Colors.lateRed : Colors.liveGreen
let range = (attributedString.string as NSString).range(of: departDirection.startTimeWithDelayDescription)
attributedString.addAttribute(.foregroundColor, value: color, range: range)
// Find time within label to place live indicator
if let stringRect = mainLabel.boundingRect(of: departDirection.startTimeWithDelayDescription + " ") {
// Add spacing to insert live indicator within text
attributedString.insert(NSAttributedString(string: " "), at: range.location + range.length)
liveIndicator.setColor(to: color)
if !mainLabel.subviews.contains(liveIndicator) {
mainLabel.addSubview(liveIndicator)
}
liveIndicator.snp.remakeConstraints { make in
make.leading.equalToSuperview().inset(stringRect.maxX)
make.centerY.equalTo(stringRect.midY)
}
mainLabel.attributedText = attributedString
}
}
} else {
let content = route.directions.first?.locationNameDescription ?? "Route Directions"
let pattern = route.directions.first?.name ?? ""
mainLabel.attributedText = pattern.bold(in: content, from: mainLabel.font, to: mainLabelBoldFont)
}
}
func updateTimes(for route: Route) {
configureMainLabelText(for: route)
}
private func setIcon(for route: Route) {
let firstBusRoute = route.directions.compactMap {
return $0.type == .depart ? $0.routeNumber : nil
}.first
if let first = firstBusRoute {
iconView = BusIcon(type: .directionLarge, number: first)
addSubview(iconView)
} else {
// Show walking glyph
iconView = UIImageView(image: #imageLiteral(resourceName: "walk"))
iconView.contentMode = .scaleAspectFit
iconView.tintColor = Colors.metadataIcon
addSubview(iconView)
}
}
}
| mit |
mbuchetics/RealmDataSource | Carthage/Checkouts/datasource/Example/ExampleTableViewController.swift | 1 | 10899 | //
// ExampleTableViewController
// Example
//
// Created by Matthias Buchetics on 24/11/15.
// Copyright © 2015 aaa - all about apps GmbH. All rights reserved.
//
import UIKit
import DataSource
enum Identifiers: String {
case TextCell
case PersonCell
case ButtonCell
}
enum Button: String {
case Add
case Remove
}
class ExampleTableViewController: UITableViewController {
var tableDataSource: TableViewDataSource!
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(Identifiers.ButtonCell.rawValue)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
tableView.dataSource = tableDataSource
tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
// MARK: Examples
/// demonstrates various ways to setup the same simple data source
func setupExample1() {
let dataSource1 = DataSource([
Section(rows: [
Row(identifier: Identifiers.TextCell.rawValue, data: "a"),
Row(identifier: Identifiers.TextCell.rawValue, data: "b"),
Row(identifier: Identifiers.TextCell.rawValue, data: "c"),
Row(identifier: Identifiers.TextCell.rawValue, data: "d"),
])
])
let dataSource2 = DataSource([
Section(rowIdentifier: Identifiers.TextCell.rawValue, rows: ["a", "b", "c", "d"])
])
let dataSource3 = ["a", "b", "c", "d"]
.toDataSourceSection(Identifiers.TextCell.rawValue)
.toDataSource()
let dataSource4 = ["a", "b", "c", "d"].toDataSource(Identifiers.TextCell.rawValue)
tableDataSource = TableViewDataSource(
dataSource: dataSource1,
configurator: TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, indexPath: NSIndexPath) in
cell.textLabel?.text = "\(indexPath.row): \(title)"
})
debugPrint(dataSource1)
debugPrint(dataSource2)
debugPrint(dataSource3)
debugPrint(dataSource4)
}
/// heterogenous data source with different row/cell types
func setupExample2() {
let dataSource = DataSource([
Section(title: "B", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [
Person(firstName: "Matthias", lastName: "Buchetics"),
]),
Section(title: "M", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [
Person(firstName: "Hugo", lastName: "Maier"),
Person(firstName: "Max", lastName: "Mustermann"),
]),
Section(title: "Strings", rowIdentifier: Identifiers.TextCell.rawValue, rows: [
"some text",
"another text"
]),
Section(rowIdentifier: Identifiers.ButtonCell.rawValue, rows: [
Button.Add,
Button.Remove
]),
])
debugPrint(dataSource)
tableDataSource = TableViewDataSource(
dataSource: dataSource,
configurators: [
TableViewCellConfigurator(Identifiers.PersonCell.rawValue) { (person: Person, cell: PersonCell, _) in
cell.firstNameLabel?.text = person.firstName
cell.lastNameLabel?.text = person.lastName
},
TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in
cell.textLabel?.text = title
},
TableViewCellConfigurator(Identifiers.ButtonCell.rawValue) { (button: Button, cell: ButtonCell, _) in
switch (button) {
case .Add:
cell.titleLabel?.text = "Add"
cell.backgroundColor = UIColor(red: 0, green: 0.7, blue: 0.2, alpha: 0.8)
case .Remove:
cell.titleLabel?.text = "Remove"
cell.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.8)
}
},
])
}
/// example how to combine and modify existing data sources
func setupExample3() {
let dataSource1 = DataSource([
Section(title: "B", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [
Person(firstName: "Matthias", lastName: "Buchetics"),
]),
Section(title: "M", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [
Person(firstName: "Hugo", lastName: "Maier"),
Person(firstName: "Max", lastName: "Mustermann"),
]),
])
let dataSource2 = DataSource(
Section(title: "Strings", rowIdentifier: Identifiers.TextCell.rawValue, rows: ["some text", "another text"]))
var compoundDataSource = DataSource(dataSources: [dataSource1, dataSource2])
compoundDataSource.appendDataSource(dataSource2)
compoundDataSource.appendDataSource(dataSource1)
compoundDataSource.removeSectionAtIndex(1)
debugPrint(compoundDataSource)
tableDataSource = TableViewDataSource(
dataSource: compoundDataSource,
configurators: [
TableViewCellConfigurator(Identifiers.PersonCell.rawValue) { (person: Person, cell: PersonCell, _) in
cell.firstNameLabel?.text = person.firstName
cell.lastNameLabel?.text = person.lastName
},
TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in
cell.textLabel?.text = title
}
])
}
/// shows how to transform a dictionary into data source
func setupExample4() {
let data = [
"section 1": ["a", "b", "c"],
"section 2": ["d", "e", "f"],
"section 3": ["g", "h", "i"],
]
let dataSource = data.toDataSource(Identifiers.TextCell.rawValue, orderedKeys: data.keys.sort())
tableDataSource = TableViewDataSource(
dataSource: dataSource,
configurator: TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in
cell.textLabel?.text = title
})
}
/// example with an empty section
func setupExample5() {
let dataSource = DataSource([
Section(title: "B", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [
Person(firstName: "Matthias", lastName: "Buchetics"),
]),
Section(title: "M", rowIdentifier: Identifiers.PersonCell.rawValue, rows: [
Person(firstName: "Hugo", lastName: "Maier"),
Person(firstName: "Max", lastName: "Mustermann"),
]),
Section(title: "Empty Section", rowIdentifier: Identifiers.TextCell.rawValue, rows: Array<String>()),
Section(title: "Strings", rowIdentifier: Identifiers.TextCell.rawValue, rows: ["some text", "another text"]),
])
debugPrint(dataSource)
tableDataSource = TableViewDataSource(
dataSource: dataSource,
configurators: [
TableViewCellConfigurator(Identifiers.PersonCell.rawValue) { (person: Person, cell: PersonCell, _) in
cell.firstNameLabel?.text = person.firstName
cell.lastNameLabel?.text = person.lastName
},
TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in
cell.textLabel?.text = title
},
])
}
/// example of an row creator closure
func setupExample6() {
let dataSource = DataSource([
Section(title: "test", rowCountClosure: { return 5 }, rowCreatorClosure: { (rowIndex) in
return Row(identifier: Identifiers.TextCell.rawValue, data: ((rowIndex + 1) % 2 == 0) ? "even" : "odd")
}),
Section<Any>(title: "mixed", rowCountClosure: { return 5 }, rowCreatorClosure: { (rowIndex) in
if rowIndex % 2 == 0 {
return Row(identifier: Identifiers.TextCell.rawValue, data: "test")
}
else {
return Row(identifier: Identifiers.PersonCell.rawValue, data: Person(firstName: "Max", lastName: "Mustermann"))
}
})
])
debugPrint(dataSource)
tableDataSource = TableViewDataSource(
dataSource: dataSource,
configurators: [
TableViewCellConfigurator(Identifiers.PersonCell.rawValue) { (person: Person, cell: PersonCell, _) in
cell.firstNameLabel?.text = person.firstName
cell.lastNameLabel?.text = person.lastName
},
TableViewCellConfigurator(Identifiers.TextCell.rawValue) { (title: String, cell: UITableViewCell, _) in
cell.textLabel?.text = title
},
])
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = tableDataSource.dataSource.rowAtIndexPath(indexPath)
let rowIdentifier = Identifiers.init(rawValue: row.identifier)!
switch (rowIdentifier) {
case .PersonCell:
let person = row.anyData as! Person
print("\(person) selected")
case .ButtonCell:
switch (row.anyData as! Button) {
case .Add:
print("add")
case .Remove:
print("remove")
}
default:
print("\(row.identifier) selected")
}
}
// need to fix section header and footer height if section is empty (only required for grouped table style)
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return tableView.heightForHeaderInSection(tableDataSource.sectionAtIndex(section))
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return tableView.heightForFooterInSection(tableDataSource.sectionAtIndex(section))
}
}
| mit |
Witcast/witcast-ios | Pods/PullToRefreshKit/Source/Classes/ElasticRefreshControl.swift | 1 | 5426 | //
// ElasticRefreshControl.swift
// SWTest
//
// Created by huangwenchen on 16/7/29.
// Copyright © 2016年 Leo. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
open class ElasticRefreshControl: UIView {
//目标,height 80, 高度 40
open let spinner:UIActivityIndicatorView = UIActivityIndicatorView()
var radius:CGFloat{
get{
return totalHeight / 4 - margin
}
}
open var progress:CGFloat = 0.0{
didSet{
setNeedsDisplay()
}
}
open var margin:CGFloat = 4.0{
didSet{
setNeedsDisplay()
}
}
var arrowRadius:CGFloat{
get{
return radius * 0.5 - 0.2 * radius * adjustedProgress
}
}
var adjustedProgress:CGFloat{
get{
return min(max(progress,0.0),1.0)
}
}
let totalHeight:CGFloat = 80
open var arrowColor = UIColor.white{
didSet{
setNeedsDisplay()
}
}
open var elasticTintColor = UIColor.init(white: 0.5, alpha: 0.6){
didSet{
setNeedsDisplay()
}
}
var animating = false{
didSet{
if animating{
spinner.startAnimating()
setNeedsDisplay()
}else{
spinner.stopAnimating()
setNeedsDisplay()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit(){
self.isOpaque = false
addSubview(spinner)
sizeToFit()
spinner.hidesWhenStopped = true
spinner.activityIndicatorViewStyle = .gray
}
open override func layoutSubviews() {
super.layoutSubviews()
spinner.center = CGPoint(x: self.bounds.width / 2.0, y: 0.75 * totalHeight)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func sinCGFloat(_ angle:CGFloat)->CGFloat{
let result = sinf(Float(angle))
return CGFloat(result)
}
func cosCGFloat(_ angle:CGFloat)->CGFloat{
let result = cosf(Float(angle))
return CGFloat(result)
}
open override func draw(_ rect: CGRect) {
//如果在Animating,则什么都不做
if animating {
super.draw(rect)
return
}
let context = UIGraphicsGetCurrentContext()
let centerX = rect.width/2.0
let lineWidth = 2.5 - 1.0 * adjustedProgress
//上面圆的信息
let upCenter = CGPoint(x: centerX, y: (0.75 - 0.5 * adjustedProgress) * totalHeight)
let upRadius = radius - radius * 0.3 * adjustedProgress
//下面圆的信息
let downRadius:CGFloat = radius - radius * 0.75 * adjustedProgress
let downCenter = CGPoint(x: centerX, y: totalHeight - downRadius - margin)
//偏移的角度
let offSetAngle:CGFloat = CGFloat.pi / 2.0 / 12.0
//计算上面圆的左/右的交点坐标
let upP1 = CGPoint(x: upCenter.x - upRadius * cosCGFloat(offSetAngle), y: upCenter.y + upRadius * sinCGFloat(offSetAngle))
let upP2 = CGPoint(x: upCenter.x + upRadius * cosCGFloat(offSetAngle), y: upCenter.y + upRadius * sinCGFloat(offSetAngle))
//计算下面的圆左/右叫点坐标
let downP1 = CGPoint(x: downCenter.x - downRadius * cosCGFloat(offSetAngle), y: downCenter.y - downRadius * sinCGFloat(offSetAngle))
//计算Control Point
let controPonintLeft = CGPoint(x: downCenter.x - downRadius, y: (downCenter.y + upCenter.y)/2)
let controPonintRight = CGPoint(x: downCenter.x + downRadius, y: (downCenter.y + upCenter.y)/2)
//实际绘制
context?.setFillColor(elasticTintColor.cgColor)
context?.addArc(center: upCenter, radius: upRadius, startAngle: -CGFloat.pi - offSetAngle, endAngle: offSetAngle, clockwise: false)
context?.move(to: CGPoint(x: upP1.x, y: upP1.y))
context?.addQuadCurve(to: downP1, control: controPonintLeft)
context?.addArc(center: downCenter, radius: downRadius, startAngle: -CGFloat.pi - offSetAngle, endAngle: offSetAngle, clockwise: true)
context?.addQuadCurve(to: upP2, control: controPonintRight)
context?.fillPath()
//绘制箭头
context?.setStrokeColor(arrowColor.cgColor)
context?.setLineWidth(lineWidth)
context?.addArc(center: upCenter, radius: arrowRadius, startAngle: 0, endAngle: CGFloat.pi * 1.5, clockwise: false)
context?.strokePath()
context?.setFillColor(arrowColor.cgColor)
context?.setLineWidth(0.0)
context?.move(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius - lineWidth * 1.5))
context?.addLine(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius + lineWidth * 1.5))
context?.addLine(to: CGPoint(x: upCenter.x + lineWidth * 0.865 * 3, y: upCenter.y - arrowRadius))
context?.addLine(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius - lineWidth * 1.5))
context?.fillPath()
}
override open func sizeToFit() {
var width = frame.size.width
if width < 30.0{
width = 30.0
}
self.frame = CGRect(x: frame.origin.x, y: frame.origin.y,width: width, height: totalHeight)
}
}
| apache-2.0 |
noodlewerk/XLForm | Examples/Swift/SwiftExample/CustomSelectors/CustomSelectorsFormViewController.swift | 33 | 3143 | //
// CustomSelectorsFormViewController.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.
import MapKit
class CustomSelectorsFormViewController : XLFormViewController {
private enum Tags : String {
case SelectorMap = "selectorMap"
case SelectorMapPopover = "selectorMapPopover"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initializeForm()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Custom Selectors")
section = XLFormSectionDescriptor.formSectionWithTitle("TextField Types")
section.footerTitle = "CustomSelectorsFormViewController.swift"
form.addFormSection(section)
// Selector Push
row = XLFormRowDescriptor(tag: Tags.SelectorMap.rawValue, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Coordinate")
row.action.viewControllerClass = MapViewController.self
row.valueTransformer = CLLocationValueTrasformer.self
row.value = CLLocation(latitude: -33, longitude: -56)
section.addFormRow(row)
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
// Selector PopOver
row = XLFormRowDescriptor(tag: Tags.SelectorMapPopover.rawValue, rowType: XLFormRowDescriptorTypeSelectorPopover, title: "Coordinate PopOver")
row.action.viewControllerClass = MapViewController.self
row.valueTransformer = CLLocationValueTrasformer.self
row.value = CLLocation(latitude: -33, longitude: -56)
section.addFormRow(row)
}
self.form = form
}
}
| mit |
koogawa/FoursquareAPIClient | FoursquareAPIClient/FoursquareAuthClient.swift | 1 | 1497 | //
// FoursquareAuthClient.swift
// FoursquareAPIClient
//
// Created by koogawa on 2015/07/27.
// Copyright (c) 2015 Kosuke Ogawa. All rights reserved.
//
import UIKit
@objc public protocol FoursquareAuthClientDelegate {
func foursquareAuthClientDidSucceed(accessToken: String)
@objc optional func foursquareAuthClientDidFail(error: Error)
}
public class FoursquareAuthClient: NSObject {
var clientId: String
var callback: String
var delegate: FoursquareAuthClientDelegate
public init(clientId: String, callback: String, delegate: FoursquareAuthClientDelegate) {
self.clientId = clientId
self.callback = callback
self.delegate = delegate
}
public func authorizeWithRootViewController(_ controller: UIViewController) {
let viewController = FoursquareAuthViewController(clientId: clientId, callback: callback)
viewController.delegate = self
let naviController = UINavigationController(rootViewController: viewController)
controller.present(naviController, animated: true, completion: nil)
}
}
// MARK: - FoursquareAuthViewControllerDelegate
extension FoursquareAuthClient: FoursquareAuthViewControllerDelegate {
func foursquareAuthViewControllerDidSucceed(accessToken: String) {
delegate.foursquareAuthClientDidSucceed(accessToken: accessToken)
}
func foursquareAuthViewControllerDidFail(error: Error) {
delegate.foursquareAuthClientDidFail?(error: error)
}
}
| mit |
huangboju/Moots | UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/Model/ImageInfo.swift | 2 | 286 | //
// ImageInfo.swift
// SwiftNetworkImages
//
// Created by Arseniy Kuznetsov on 30/4/16.
// Copyright © 2016 Arseniy Kuznetsov. All rights reserved.
//
import Foundation
/// Base image info model
struct ImageInfo {
let imageCaption: String
let imageURLString: String
}
| mit |
Jnosh/swift | test/Sema/accessibility_multi.swift | 26 | 1166 | // RUN: %target-swift-frontend -typecheck -primary-file %s %S/Inputs/accessibility_multi_other.swift -verify
func read(_ value: Int) {}
func reset(_ value: inout Int) { value = 0 }
func testGlobals() {
read(privateSetGlobal)
privateSetGlobal = 42 // expected-error {{cannot assign to value: 'privateSetGlobal' setter is inaccessible}}
reset(&privateSetGlobal) // expected-error {{cannot pass immutable value as inout argument: 'privateSetGlobal' setter is inaccessible}}
}
func testProperties(_ instance: Members) {
var instance = instance
read(instance.privateSetProp)
instance.privateSetProp = 42 // expected-error {{cannot assign to property: 'privateSetProp' setter is inaccessible}}
reset(&instance.privateSetProp) // expected-error {{cannot pass immutable value as inout argument: 'privateSetProp' setter is inaccessible}}
}
func testSubscript(_ instance: Members) {
var instance = instance
read(instance[])
instance[] = 42 // expected-error {{cannot assign through subscript: subscript setter is inaccessible}}
reset(&instance[]) // expected-error {{cannot pass immutable value as inout argument: subscript setter is inaccessible}}
}
| apache-2.0 |
bluesnap/bluesnap-ios | BluesnapSDK/BluesnapSDK/BSValidator.swift | 1 | 21061 | //
// BSValidator.swift
// BluesnapSDK
//
// Created by Shevie Chen on 04/04/2017.
// Copyright © 2017 Bluesnap. All rights reserved.
//
import Foundation
public class BSValidator: NSObject {
// MARK: Constants
static let ccnInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_CCN)
static let cvvInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_CVV)
static let expMonthInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_ExpMonth)
static let expPastInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_ExpIsInThePast)
static let expInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_EXP)
static let nameInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_Name)
static let emailInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_Email)
static let streetInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_Street)
static let cityInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_City)
static let countryInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_Country)
static let stateInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_State)
static let zipCodeInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_ZipCode)
static let postalCodeInvalidMessage = BSLocalizedStrings.getString(BSLocalizedString.Error_Invalid_PostalCode)
static let defaultFieldColor = UIColor.black
static let errorFieldColor = UIColor.red
// MARK: private properties
internal static var cardTypesRegex = [Int: (cardType: String, regexp: String)]()
// MARK: validation functions (check UI field and hide/show errors as necessary)
class func validateName(ignoreIfEmpty: Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool {
var result : Bool = true
let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces).capitalized ?? ""
input.setValue(newValue)
if let addressDetails = addressDetails {
addressDetails.name = newValue
}
if newValue.count == 0 && ignoreIfEmpty {
// ignore
} else if !isValidName(newValue) {
result = false
}
if result {
input.hideError()
} else {
input.showError(nameInvalidMessage)
}
return result
}
class func validateEmail(ignoreIfEmpty: Bool, input: BSInputLine, addressDetails: BSBillingAddressDetails?) -> Bool {
let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? ""
input.setValue(newValue)
if let addressDetails = addressDetails {
addressDetails.email = newValue
}
var result : Bool = true
if (ignoreIfEmpty && newValue.count == 0) {
// ignore
} else if (!isValidEmail(newValue)) {
result = false
} else {
result = true
}
if result {
input.hideError()
} else {
input.showError(emailInvalidMessage)
}
return result
}
// // no validation yet, this is just a preparation
// class func validatePhone(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSShippingAddressDetails?) -> Bool {
//
// let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? ""
// input.setValue(newValue)
// if let addressDetails = addressDetails {
// addressDetails.phone = newValue
// }
// return true
// }
class func validateStreet(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool {
let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? ""
input.setValue(newValue)
if let addressDetails = addressDetails {
addressDetails.address = newValue
}
var result : Bool = true
if (ignoreIfEmpty && newValue.count == 0) {
// ignore
} else if !isValidStreet(newValue) {
result = false
} else {
result = true
}
if result {
input.hideError()
} else {
input.showError(streetInvalidMessage)
}
return result
}
class func validateCity(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool {
let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? ""
input.setValue(newValue)
if let addressDetails = addressDetails {
addressDetails.city = newValue
}
var result : Bool = true
if (ignoreIfEmpty && newValue.count == 0) {
// ignore
} else if !isValidCity(newValue) {
result = false
} else {
result = true
}
if result {
input.hideError()
} else {
input.showError(cityInvalidMessage)
}
return result
}
class func validateCountry(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool {
let newValue = addressDetails?.country ?? ""
var result : Bool = true
if (ignoreIfEmpty && newValue.count == 0) {
// ignore
} else if !isValidCountry(countryCode: newValue) {
result = false
} else {
result = true
}
if result {
input.hideError()
} else {
input.showError(countryInvalidMessage)
}
return result
}
class func validateZip(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool {
var result : Bool = true
let newValue = input.getValue()?.trimmingCharacters(in: .whitespaces) ?? ""
input.setValue(newValue)
if let addressDetails = addressDetails {
addressDetails.zip = newValue
}
if (ignoreIfEmpty && newValue.count == 0) {
// ignore
} else if !isValidZip(countryCode: addressDetails?.country ?? "", zip: newValue) {
result = false
} else {
result = true
}
if result {
input.hideError()
} else {
let errorText = getZipErrorText(countryCode: addressDetails?.country ?? "")
input.showError(errorText)
}
return result
}
class func validateState(ignoreIfEmpty : Bool, input: BSInputLine, addressDetails: BSBaseAddressDetails?) -> Bool {
let newValue = addressDetails?.state ?? ""
var result : Bool = true
if ((ignoreIfEmpty || input.isHidden) && newValue.count == 0) {
// ignore
} else if !isValidCountry(countryCode: addressDetails?.country ?? "") {
result = false
} else if !isValidState(countryCode: addressDetails?.country ?? "", stateCode: addressDetails?.state) {
result = false
}
if result {
input.hideError()
} else {
input.showError(stateInvalidMessage)
}
return result
}
class func validateExp(input: BSCcInputLine) -> Bool {
var ok : Bool = true
var msg : String = expInvalidMessage
let newValue = input.expTextField.text ?? ""
if let p = newValue.firstIndex(of: "/") {
let mm = String(newValue[..<p])
let yy = BSStringUtils.removeNoneDigits(String(newValue[p ..< newValue.endIndex]))
if (mm.count < 2) {
ok = false
} else if !isValidMonth(mm) {
ok = false
msg = expMonthInvalidMessage
} else if (yy.count < 2) {
ok = false
} else {
(ok, msg) = isCcValidExpiration(mm: mm, yy: yy)
}
} else {
ok = false
}
if (ok) {
input.hideExpError()
} else {
input.showExpError(msg)
}
return ok
}
class func validateCvv(input: BSCcInputLine, cardType: String) -> Bool {
var result : Bool = true;
let newValue = input.getCvv() ?? ""
if newValue.count != getCvvLength(cardType: cardType) {
result = false
}
if result {
input.hideCvvError()
} else {
input.showCvvError(cvvInvalidMessage)
}
return result
}
class func validateCCN(input: BSCcInputLine) -> Bool {
var result : Bool = true;
let newValue : String! = input.getValue()
if !isValidCCN(newValue) {
result = false
}
if result {
input.hideError()
} else {
input.showError(ccnInvalidMessage)
}
return result
}
/**
Validate the shopper consent to store the credit card details in case it is mandatory.
The shopper concent is mandatory only in case it is a choose new card as payment method flow (shopper configuration).
*/
class func validateStoreCard(isShopperRequirements: Bool, isSubscriptionCharge: Bool, isStoreCard: Bool, isExistingCC: Bool) -> Bool {
return ((isShopperRequirements || isSubscriptionCharge) && !isExistingCC) ? isStoreCard : true
}
// MARK: field editing changed methods (to limit characters and sizes)
class func nameEditingChanged(_ sender: BSInputLine) {
var input : String = sender.getValue() ?? ""
input = BSStringUtils.removeNoneAlphaCharacters(input)
input = BSStringUtils.cutToMaxLength(input, maxLength: 100)
input = input.capitalized
sender.setValue(input)
}
// class func phoneEditingChanged(_ sender: BSInputLine) {
//
// var input : String = sender.getValue() ?? ""
// input = BSStringUtils.cutToMaxLength(input, maxLength: 30)
// sender.setValue(input)
// }
class func emailEditingChanged(_ sender: BSInputLine) {
var input : String = sender.getValue() ?? ""
input = BSStringUtils.removeNoneEmailCharacters(input)
input = BSStringUtils.cutToMaxLength(input, maxLength: 120)
sender.setValue(input)
}
class func addressEditingChanged(_ sender: BSInputLine) {
var input : String = sender.getValue() ?? ""
input = BSStringUtils.cutToMaxLength(input, maxLength: 100)
sender.setValue(input)
}
class func cityEditingChanged(_ sender: BSInputLine) {
var input : String = sender.getValue() ?? ""
input = BSStringUtils.removeNoneAlphaCharacters(input)
input = BSStringUtils.cutToMaxLength(input, maxLength: 50)
sender.setValue(input)
}
class func zipEditingChanged(_ sender: BSInputLine) {
var input : String = sender.getValue() ?? ""
input = BSStringUtils.cutToMaxLength(input, maxLength: 20)
sender.setValue(input)
}
class func ccnEditingChanged(_ sender: UITextField) {
var input : String = sender.text ?? ""
input = BSStringUtils.removeNoneDigits(input)
input = BSStringUtils.cutToMaxLength(input, maxLength: 21)
input = formatCCN(input)
sender.text = input
}
class func expEditingChanged(_ sender: UITextField) {
var input : String = sender.text ?? ""
input = BSStringUtils.removeNoneDigits(input)
input = BSStringUtils.cutToMaxLength(input, maxLength: 4)
input = formatExp(input)
sender.text = input
}
class func cvvEditingChanged(_ sender: UITextField) {
var input : String = sender.text ?? ""
input = BSStringUtils.removeNoneDigits(input)
input = BSStringUtils.cutToMaxLength(input, maxLength: 4)
sender.text = input
}
class func updateState(addressDetails: BSBaseAddressDetails!, stateInputLine: BSInputLine) {
let selectedCountryCode = addressDetails.country ?? ""
let selectedStateCode = addressDetails.state ?? ""
var hideState : Bool = true
stateInputLine.setValue("")
let countryManager = BSCountryManager.getInstance()
if countryManager.countryHasStates(countryCode: selectedCountryCode) {
hideState = false
if let stateName = countryManager.getStateName(countryCode: selectedCountryCode, stateCode: selectedStateCode){
stateInputLine.setValue(stateName)
}
} else {
addressDetails.state = nil
}
stateInputLine.isHidden = hideState
stateInputLine.hideError()
}
// MARK: Basic validation functions
open class func isValidMonth(_ str: String) -> Bool {
let validMonths = ["01","02","03","04","05","06","07","08","09","10","11","12"]
return validMonths.contains(str)
}
open class func isCcValidExpiration(mm: String, yy: String) -> (Bool, String) {
var ok = false
var msg = expInvalidMessage
if let month = Int(mm), let year = Int(yy) {
var dateComponents = DateComponents()
let currYear : Int! = getCurrentYear()
if yy.count < 4 {
dateComponents.year = year + (currYear / 100)*100
} else {
dateComponents.year = year
}
dateComponents.month = month
dateComponents.day = 1
let expDate = Calendar.current.date(from: dateComponents)!
if dateComponents.year! > currYear + 10 {
ok = false
} else if expDate < Date() {
ok = false
msg = expPastInvalidMessage
} else {
ok = true
}
}
return (ok, msg)
}
open class func isValidEmail(_ str: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: str)
}
open class func isValidCCN(_ str: String) -> Bool {
if str.count < 6 {
return false
}
var isOdd : Bool! = true
var sum : Int! = 0;
for character in str.reversed() {
if (character == " ") {
// ignore
} else if (character >= "0" && character <= "9") {
var digit : Int! = Int(String(character))!
isOdd = !isOdd
if (isOdd == true) {
digit = digit * 2
}
if digit > 9 {
digit = digit - 9
}
sum = sum + digit
} else {
return false
}
}
return sum % 10 == 0
}
open class func isValidName(_ str: String) -> Bool {
if let p = str.firstIndex(of: " ") {
let firstName = str[..<p].trimmingCharacters(in: .whitespaces)
let lastName = str[p..<str.endIndex].trimmingCharacters(in: .whitespaces)
if firstName.count < 1 || lastName.count < 1 {
return false
}
} else {
return false
}
return true
}
open class func isValidCity(_ str: String) -> Bool {
var result : Bool = false
if (str.count < 3) {
result = false
} else {
result = true
}
return result
}
open class func isValidStreet(_ str: String) -> Bool {
var result : Bool = false
if (str.count < 3) {
result = false
} else {
result = true
}
return result
}
open class func isValidZip(countryCode: String, zip: String) -> Bool {
var result : Bool = false
if BSCountryManager.getInstance().countryHasNoZip(countryCode: countryCode) {
result = true
} else if (zip.count < 3) {
result = false
} else {
result = true
}
return result
}
open class func isValidState(countryCode: String, stateCode: String?) -> Bool {
var result : Bool = true
if !isValidCountry(countryCode: countryCode) {
result = false
} else if BSCountryManager.getInstance().countryHasStates(countryCode: countryCode) {
if stateCode == nil || (stateCode?.count != 2) {
result = false
} else {
let stateName = BSCountryManager.getInstance().getStateName(countryCode: countryCode, stateCode: stateCode ?? "")
result = stateName != nil
}
} else if stateCode?.count ?? 0 > 0 {
result = false
}
return result
}
open class func isValidCountry(countryCode: String?) -> Bool {
var result : Bool = true
if countryCode == nil || BSCountryManager.getInstance().getCountryName(countryCode: countryCode!) == nil {
result = false
}
return result
}
open class func getCvvLength(cardType: String) -> Int {
var cvvLength = 3
if cardType.lowercased() == "amex" {
cvvLength = 4
}
return cvvLength
}
// MARK: formatting functions
class func getCurrentYear() -> Int! {
let date = Date()
let calendar = Calendar.current
let year = calendar.component(.year, from: date)
return year
}
class func getCcLengthByCardType(_ cardType: String) -> Int! {
var maxLength : Int = 16
if cardType == "amex" {
maxLength = 15
} else if cardType == "dinersclub" {
maxLength = 14
}
return maxLength
}
open class func formatCCN(_ str: String) -> String {
var result: String
let myLength = str.count
if (myLength > 4) {
let idx1 = str.index(str.startIndex, offsetBy: 4)
result = str[..<idx1] + " "
if (myLength > 8) {
let idx2 = str.index(idx1, offsetBy: 4)
result += str[idx1..<idx2] + " "
if (myLength > 12) {
let idx3 = str.index(idx2, offsetBy: 4)
result += str[idx2..<idx3] + " " + str[idx3...]
} else {
result += str[idx2...]
}
} else {
result += str[idx1...]
}
} else {
result = str
}
return result
}
open class func formatExp(_ str: String) -> String {
var result: String
let myLength = str.count
if (myLength > 2) {
let idx1 = str.index(str.startIndex, offsetBy: 2)
result = str[..<idx1] + "/" + str[idx1...]
} else {
result = str
}
return result
}
open class func getCCTypeByRegex(_ str: String) -> String? {
// remove blanks
let ccn = BSStringUtils.removeWhitespaces(str)
// Display the card type for the card Regex
for index in 0...self.cardTypesRegex.count-1 {
if let _ = ccn.range(of:self.cardTypesRegex[index]!.regexp, options: .regularExpression) {
return self.cardTypesRegex[index]!.cardType
}
}
return nil
}
// MARK: zip texts
open class func getZipLabelText(countryCode: String, forBilling: Bool) -> String {
if countryCode.uppercased() == BSCountryManager.US_COUNTRY_CODE {
if forBilling {
return BSLocalizedStrings.getString(BSLocalizedString.Label_Billing_Zip)
} else {
return BSLocalizedStrings.getString(BSLocalizedString.Label_Shipping_Zip)
}
} else {
return BSLocalizedStrings.getString(BSLocalizedString.Label_Postal_Code)
}
}
open class func getZipErrorText(countryCode: String) -> String {
if countryCode.uppercased() == BSCountryManager.US_COUNTRY_CODE {
return zipCodeInvalidMessage
} else {
return postalCodeInvalidMessage
}
}
open class func getZipKeyboardType(countryCode: String) -> UIKeyboardType {
if countryCode.uppercased() == BSCountryManager.US_COUNTRY_CODE {
return .numberPad
} else {
return .numbersAndPunctuation
}
}
}
| mit |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Me/Views/MeFooterSectionView.swift | 1 | 3770 | //
// MeFooterSectionView.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/25.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
import SnapKit
class MeFooterSectionView: UIView {
weak var delegate:MeFooterSectionViewDelegate?
var lineViewLeftConstraint:Constraint?
//MARK: 懒加载
lazy var singleGiftButton:UIButton = { () -> UIButton in
let button = UIButton(type: .custom)
button.tag = 0
button.setTitle("单品", for: .normal)
button.titleLabel?.font = fontSize15
button.setTitleColor(UIColor.gray, for: .normal)
return button
}()
lazy var strategyGiftButton:UIButton = { () -> UIButton in
let button = UIButton(type: .custom)
button.tag = 1
button.setTitle("攻略", for: .normal)
button.titleLabel?.font = fontSize15
button.setTitleColor(UIColor.gray, for: .normal)
return button
}()
lazy var lineView:UIView = { () -> UIView in
let view = UIView()
view.backgroundColor = SystemNavgationBarTintColor
return view
}()
lazy var bottomLine:UIView = { () -> UIView in
let view = UIView()
view.backgroundColor = SystemGlobalLineColor
return view
}()
//MARK: 构造方法
override init(frame: CGRect) {
super.init(frame: frame)
setupMeFooterSectionView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
setupMeFooterSectionViewSubView()
}
//MARK: 私有方法
private func setupMeFooterSectionView() {
backgroundColor = UIColor.white
addSubview(singleGiftButton)
addSubview(strategyGiftButton)
addSubview(lineView)
addSubview(bottomLine)
singleGiftButton.addTarget(self, action: #selector(buttonClick(button:)), for: .touchUpInside)
strategyGiftButton.addTarget(self, action: #selector(buttonClick(button:)), for: .touchUpInside)
}
private func setupMeFooterSectionViewSubView() {
DispatchQueue.once(token: "MeFooterSectionView.LayoutSubView") {
singleGiftButton.snp.makeConstraints { (make) in
make.left.top.equalToSuperview()
make.bottom.equalTo(lineView.snp.top)
make.width.equalTo(strategyGiftButton)
}
strategyGiftButton.snp.makeConstraints { (make) in
make.top.right.equalToSuperview()
make.left.equalTo(singleGiftButton.snp.right)
make.bottom.equalTo(singleGiftButton)
}
lineView.snp.makeConstraints { (make) in
lineViewLeftConstraint = make.left.equalToSuperview().constraint
make.bottom.equalToSuperview()
make.width.equalTo(singleGiftButton)
make.height.equalTo(5.0)
}
bottomLine.snp.makeConstraints({ (make) in
make.left.right.bottom.equalToSuperview()
make.height.equalTo(0.8)
})
}
}
//MARK: 内部处理方法
@objc private func buttonClick(button:UIButton) {
let offset = CGFloat(button.tag)*button.bounds.width
lineViewLeftConstraint?.update(offset: offset)
super.updateConstraints()
delegate?.meFooterSectionViewButtonClick(button: button)
}
}
//MARK: 协议
protocol MeFooterSectionViewDelegate:NSObjectProtocol {
func meFooterSectionViewButtonClick(button:UIButton)
}
| mit |
JosephNK/SwiftyIamport | SwiftyIamportDemo/Controller/WKHtml5InicisViewController.swift | 1 | 4296 | //
// WKHtml5InicisViewController.swift
// SwiftyIamportDemo
//
// Created by JosephNK on 29/11/2018.
// Copyright © 2018 JosephNK. All rights reserved.
//
import UIKit
import SwiftyIamport
import WebKit
class WKHtml5InicisViewController: UIViewController {
lazy var wkWebView: WKWebView = {
var view = WKWebView()
view.backgroundColor = UIColor.clear
view.navigationDelegate = self
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(wkWebView)
self.wkWebView.frame = self.view.bounds
// 결제 환경 설정
IAMPortPay.sharedInstance.configure(scheme: "iamporttest", // info.plist에 설정한 scheme
storeIdentifier: "imp68124833") // iamport 에서 부여받은 가맹점 식별코드
IAMPortPay.sharedInstance
.setPGType(.html5_inicis) // PG사 타입
.setIdName(nil) // 상점아이디 ({PG사명}.{상점아이디}으로 생성시 사용)
.setPayMethod(.card) // 결제 형식
.setWKWebView(self.wkWebView) // 현재 Controller에 있는 WebView 지정
.setRedirectUrl(nil) // m_redirect_url 주소
// 결제 정보 데이타
let parameters: IAMPortParameters = [
"merchant_uid": String(format: "merchant_%@", String(Int(NSDate().timeIntervalSince1970 * 1000))),
"name": "결제테스트",
"amount": "1004",
"buyer_email": "iamport@siot.do",
"buyer_name": "구매자",
"buyer_tel": "010-1234-5678",
"buyer_addr": "서울특별시 강남구 삼성동",
"buyer_postcode": "123-456",
"custom_data": ["A1": 123, "B1": "Hello"]
//"custom_data": "24"
]
IAMPortPay.sharedInstance.setParameters(parameters).commit()
// 결제 웹페이지(Local) 파일 호출
if let url = IAMPortPay.sharedInstance.urlFromLocalHtmlFile() {
let request = URLRequest(url: url)
self.wkWebView.load(request)
}
}
}
extension WKHtml5InicisViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let request = navigationAction.request
IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in
// Background Thread 처리
var resultData: [String: Any]?
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
switch statusCode {
case 200:
resultData = [
"isSuccess": "OK"
]
break
default:
break
}
}
return resultData
}) { (pasingData) in
// Main Thread 처리
}
let result = IAMPortPay.sharedInstance.requestAction(for: request)
decisionHandler(result ? .allow : .cancel)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// 결제 환경으로 설정에 의한 웹페이지(Local) 호출 결과
IAMPortPay.sharedInstance.requestIAMPortPayWKWebViewDidFinishLoad(webView) { (error) in
if error != nil {
switch error! {
case .custom(let reason):
print("error: \(reason)")
break
}
}else {
print("OK")
}
}
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("didFail")
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("didFailProvisionalNavigation \(error.localizedDescription)")
}
}
| mit |
androiddream/AlamofireImage | Source/ImageDownloader.swift | 6 | 16517 | // ImageDownloader.swift
//
// Copyright (c) 2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
#if os(iOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
/// The `ImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming
/// downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded
/// image is cached in the underlying `NSURLCache` as well as the in-memory image cache that supports image filters.
/// By default, any download request with a cached image equivalent in the image cache will automatically be served the
/// cached image representation. Additional advanced features include supporting multiple image filters and completion
/// handlers for a single request.
public class ImageDownloader {
/// The completion handler closure used when an image download completes.
public typealias CompletionHandler = (NSURLRequest?, NSHTTPURLResponse?, Result<Image>) -> Void
/**
Defines the order prioritization of incoming download requests being inserted into the queue.
- FIFO: All incoming downloads are added to the back of the queue.
- LIFO: All incoming downloads are added to the front of the queue.
*/
public enum DownloadPrioritization {
case FIFO, LIFO
}
class ResponseHandler {
let identifier: String
let request: Request
var filters: [ImageFilter?]
var completionHandlers: [CompletionHandler]
init(request: Request, filter: ImageFilter?, completion: CompletionHandler) {
self.request = request
self.identifier = ImageDownloader.identifierForURLRequest(request.request!)
self.filters = [filter]
self.completionHandlers = [completion]
}
}
// MARK: - Properties
/// The image cache used to store all downloaded images in.
public let imageCache: ImageRequestCache?
/// The credential used for authenticating each download request.
public private(set) var credential: NSURLCredential?
var queuedRequests: [Request]
var activeRequestCount: Int
let maximumActiveDownloads: Int
let sessionManager: Alamofire.Manager
private let synchronizationQueue: dispatch_queue_t
private let responseQueue: dispatch_queue_t
private let downloadPrioritization: DownloadPrioritization
private var responseHandlers: [String: ResponseHandler]
// MARK: - Initialization
/// The default instance of `ImageDownloader` initialized with default values.
public static let defaultInstance = ImageDownloader()
/**
Creates a default `NSURLSessionConfiguration` with common usage parameter values.
- returns: The default `NSURLSessionConfiguration` instance.
*/
public class func defaultURLSessionConfiguration() -> NSURLSessionConfiguration {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
configuration.HTTPShouldSetCookies = true
configuration.HTTPShouldUsePipelining = false
configuration.requestCachePolicy = .UseProtocolCachePolicy
configuration.allowsCellularAccess = true
configuration.timeoutIntervalForRequest = 60
configuration.URLCache = ImageDownloader.defaultURLCache()
return configuration
}
/**
Creates a default `NSURLCache` with common usage parameter values.
- returns: The default `NSURLCache` instance.
*/
public class func defaultURLCache() -> NSURLCache {
return NSURLCache(
memoryCapacity: 20 * 1024 * 1024, // 20 MB
diskCapacity: 150 * 1024 * 1024, // 150 MB
diskPath: "com.alamofire.imagedownloader"
)
}
/**
Initializes the `ImageDownloader` instance with the given configuration, download prioritization, maximum active
download count and image cache.
- parameter configuration: The `NSURLSessionConfiguration` to use to create the underlying Alamofire
`Manager` instance.
- parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
- parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
- parameter imageCache: The image cache used to store all downloaded images in.
- returns: The new `ImageDownloader` instance.
*/
public init(
configuration: NSURLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(),
downloadPrioritization: DownloadPrioritization = .FIFO,
maximumActiveDownloads: Int = 4,
imageCache: ImageRequestCache? = AutoPurgingImageCache())
{
self.sessionManager = Alamofire.Manager(configuration: configuration)
self.sessionManager.startRequestsImmediately = false
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
self.queuedRequests = []
self.responseHandlers = [:]
self.activeRequestCount = 0
self.synchronizationQueue = {
let name = String(format: "com.alamofire.imagedownloader.synchronizationqueue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL)
}()
self.responseQueue = {
let name = String(format: "com.alamofire.imagedownloader.responsequeue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT)
}()
}
// MARK: - Authentication
/**
Associates an HTTP Basic Auth credential with all future download requests.
- parameter user: The user.
- parameter password: The password.
- parameter persistence: The URL credential persistence. `.ForSession` by default.
*/
public func addAuthentication(
user user: String,
password: String,
persistence: NSURLCredentialPersistence = .ForSession)
{
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
addAuthentication(usingCredential: credential)
}
/**
Associates the specified credential with all future download requests.
- parameter credential: The credential.
*/
public func addAuthentication(usingCredential credential: NSURLCredential) {
dispatch_sync(synchronizationQueue) {
self.credential = credential
}
}
// MARK: - Download
/**
Creates a download request using the internal Alamofire `Manager` instance for the specified URL request.
If the same download request is already in the queue or currently being downloaded, the completion handler is
appended to the already existing request. Once the request completes, all completion handlers attached to the
request are executed in the order they were added.
- parameter URLRequest: The URL request.
- parameter completion: The closure called when the download request is complete.
- returns: The created download request if available. `nil` if the image is stored in the image cache and the
URL request cache policy allows the cache to be used.
*/
public func downloadImage(URLRequest URLRequest: URLRequestConvertible, completion: CompletionHandler) -> Request? {
return downloadImage(URLRequest: URLRequest, filter: nil, completion: completion)
}
/**
Creates a download request using the internal Alamofire `Manager` instance for the specified URL request.
If the same download request is already in the queue or currently being downloaded, the filter and completion
handler are appended to the already existing request. Once the request completes, all filters and completion
handlers attached to the request are executed in the order they were added. Additionally, any filters attached
to the request with the same identifiers are only executed once. The resulting image is then passed into each
completion handler paired with the filter.
- parameter URLRequest: The URL request.
- parameter filter The image filter to apply to the image after the download is complete.
- parameter completion: The closure called when the download request is complete.
- returns: The created download request if available. `nil` if the image is stored in the image cache and the
URL request cache policy allows the cache to be used.
*/
public func downloadImage(
URLRequest URLRequest: URLRequestConvertible,
filter: ImageFilter?,
completion: CompletionHandler)
-> Request?
{
var request: Request!
dispatch_sync(synchronizationQueue) {
// 1) Append the filter and completion handler to a pre-existing request if it already exists
let identifier = ImageDownloader.identifierForURLRequest(URLRequest)
if let responseHandler = self.responseHandlers[identifier] {
responseHandler.filters.append(filter)
responseHandler.completionHandlers.append(completion)
request = responseHandler.request
return
}
// 2) Attempt to load the image from the image cache if the cache policy allows it
switch URLRequest.URLRequest.cachePolicy {
case .UseProtocolCachePolicy, .ReturnCacheDataElseLoad, .ReturnCacheDataDontLoad:
if let image = self.imageCache?.imageForRequest(
URLRequest.URLRequest,
withAdditionalIdentifier: filter?.identifier)
{
dispatch_async(dispatch_get_main_queue()) {
completion(URLRequest.URLRequest, nil, .Success(image))
}
return
}
default:
break
}
// 3) Create the request and set up authentication, validation and response serialization
request = self.sessionManager.request(URLRequest)
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
request.validate()
request.response(
queue: self.responseQueue,
responseSerializer: Request.imageResponseSerializer(),
completionHandler: { [weak self] request, response, result in
guard let strongSelf = self, let request = request else { return }
let responseHandler = strongSelf.safelyRemoveResponseHandlerWithIdentifier(identifier)
switch result {
case .Success(let image):
var filteredImages: [String: Image] = [:]
for (filter, completion) in zip(responseHandler.filters, responseHandler.completionHandlers) {
var filteredImage: Image
if let filter = filter {
if let alreadyFilteredImage = filteredImages[filter.identifier] {
filteredImage = alreadyFilteredImage
} else {
filteredImage = filter.filter(image)
filteredImages[filter.identifier] = filteredImage
}
} else {
filteredImage = image
}
strongSelf.imageCache?.addImage(
image,
forRequest: request,
withAdditionalIdentifier: filter?.identifier
)
dispatch_async(dispatch_get_main_queue()) {
completion(request, response, .Success(filteredImage))
}
}
case .Failure:
for completion in responseHandler.completionHandlers {
dispatch_async(dispatch_get_main_queue()) {
completion(request, response, result)
}
}
}
strongSelf.safelyDecrementActiveRequestCount()
strongSelf.safelyStartNextRequestIfNecessary()
}
)
// 4) Store the response handler for use when the request completes
let responseHandler = ResponseHandler(request: request, filter: filter, completion: completion)
self.responseHandlers[identifier] = responseHandler
// 5) Either start the request or enqueue it depending on the current active request count
if self.isActiveRequestCountBelowMaximumLimit() {
self.startRequest(request)
} else {
self.enqueueRequest(request)
}
}
return request
}
// MARK: - Internal - Thread-Safe Request Methods
func safelyRemoveResponseHandlerWithIdentifier(identifier: String) -> ResponseHandler {
var responseHandler: ResponseHandler!
dispatch_sync(synchronizationQueue) {
responseHandler = self.responseHandlers.removeValueForKey(identifier)
}
return responseHandler
}
func safelyStartNextRequestIfNecessary() {
dispatch_sync(synchronizationQueue) {
guard self.isActiveRequestCountBelowMaximumLimit() else { return }
while (!self.queuedRequests.isEmpty) {
if let request = self.dequeueRequest() where request.task.state == .Suspended {
self.startRequest(request)
break
}
}
}
}
func safelyDecrementActiveRequestCount() {
dispatch_sync(self.synchronizationQueue) {
if self.activeRequestCount > 0 {
self.activeRequestCount -= 1
}
}
}
// MARK: - Internal - Non Thread-Safe Request Methods
func startRequest(request: Request) {
request.resume()
++activeRequestCount
}
func enqueueRequest(request: Request) {
switch downloadPrioritization {
case .FIFO:
queuedRequests.append(request)
case .LIFO:
queuedRequests.insert(request, atIndex: 0)
}
}
func dequeueRequest() -> Request? {
var request: Request?
if !queuedRequests.isEmpty {
request = queuedRequests.removeFirst()
}
return request
}
func isActiveRequestCountBelowMaximumLimit() -> Bool {
return activeRequestCount < maximumActiveDownloads
}
static func identifierForURLRequest(URLRequest: URLRequestConvertible) -> String {
return URLRequest.URLRequest.URLString
}
}
| mit |
sweetmandm/Validate | Sources/Validate/ValidationError.swift | 1 | 230 | //
// ValidationError.swift
// Validate
//
// Created by sweetman on 4/27/17.
// Copyright © 2017 tinfish. All rights reserved.
//
import Foundation
public protocol ValidationError: Error {
var reason: String { get }
}
| mit |
ovchinnikoff/FolioReaderKit | FolioReaderKit/FREpubParser.swift | 2 | 8772 | //
// FREpubParser.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 04/05/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
import SSZipArchive
class FREpubParser: NSObject {
let book = FRBook()
var bookBasePath: String!
var resourcesBasePath: String!
/**
Unzip and read an epub file.
Returns a FRBook.
*/
func readEpub(epubPath withEpubPath: String) -> FRBook {
// Unzip
let bookName = withEpubPath.lastPathComponent.stringByDeletingPathExtension
bookBasePath = kApplicationDocumentsDirectory.stringByAppendingPathComponent(bookName)
SSZipArchive.unzipFileAtPath(withEpubPath, toDestination: bookBasePath)
readContainer()
readOpf()
return book
}
/**
Read an unziped epub file.
Returns a FRBook.
*/
func readEpub(filePath withFilePath: String) -> FRBook {
return book
}
/**
Read and parse container.xml file.
*/
private func readContainer() {
let containerPath = "META-INF/container.xml"
let containerData = NSData(contentsOfFile: bookBasePath.stringByAppendingPathComponent(containerPath), options: .DataReadingMappedAlways, error: nil)
var error: NSError?
if let xmlDoc = AEXMLDocument(xmlData: containerData!, error: &error) {
let opfResource = FRResource()
opfResource.href = xmlDoc.root["rootfiles"]["rootfile"].attributes["full-path"] as! String
opfResource.mediaType = FRMediaType.determineMediaType(xmlDoc.root["rootfiles"]["rootfile"].attributes["full-path"] as! String)
book.opfResource = opfResource
resourcesBasePath = bookBasePath.stringByAppendingPathComponent(book.opfResource.href.stringByDeletingLastPathComponent)
}
}
/**
Read and parse .opf file.
*/
private func readOpf() {
let opfPath = bookBasePath.stringByAppendingPathComponent(book.opfResource.href)
let opfData = NSData(contentsOfFile: opfPath, options: .DataReadingMappedAlways, error: nil)
var error: NSError?
if let xmlDoc = AEXMLDocument(xmlData: opfData!, error: &error) {
for item in xmlDoc.root["manifest"]["item"].all! {
let resource = FRResource()
resource.id = item.attributes["id"] as! String
resource.href = item.attributes["href"] as! String
resource.fullHref = resourcesBasePath.stringByAppendingPathComponent(item.attributes["href"] as! String).stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
resource.mediaType = FRMediaType.mediaTypesByName[item.attributes["media-type"] as! String]
book.resources.add(resource)
}
// Get the first resource with the NCX mediatype
book.ncxResource = book.resources.findFirstResource(byMediaType: FRMediaType.NCX)
if book.ncxResource == nil {
println("ERROR: Could not find table of contents resource. The book don't have a NCX resource.")
}
// The book TOC
book.tableOfContents = findTableOfContents()
// Read metadata
book.metadata = readMetadata(xmlDoc.root["metadata"].children)
// Read the cover image
let coverImageID = book.metadata.findMetaByName("cover")
if (coverImageID != nil && book.resources.containsById(coverImageID!)) {
book.coverImage = book.resources.getById(coverImageID!)
}
// Read Spine
book.spine = readSpine(xmlDoc.root["spine"].children)
}
}
/**
Read and parse the Table of Contents.
*/
private func findTableOfContents() -> [FRTocReference] {
let ncxPath = resourcesBasePath.stringByAppendingPathComponent(book.ncxResource.href)
let ncxData = NSData(contentsOfFile: ncxPath, options: .DataReadingMappedAlways, error: nil)
var error: NSError?
var tableOfContent = [FRTocReference]()
if let xmlDoc = AEXMLDocument(xmlData: ncxData!, error: &error) {
for item in xmlDoc.root["navMap"]["navPoint"].all! {
tableOfContent.append(readTOCReference(item))
}
}
return tableOfContent
}
private func readTOCReference(navpointElement: AEXMLElement) -> FRTocReference {
let label = navpointElement["navLabel"]["text"].value as String!
let reference = navpointElement["content"].attributes["src"] as! String!
let hrefSplit = split(reference) {$0 == "#"}
let fragmentID = hrefSplit.count > 1 ? hrefSplit[1] : ""
let href = hrefSplit[0]
let resource = book.resources.getByHref(href)
let toc = FRTocReference(title: label, resource: resource!, fragmentID: fragmentID)
if navpointElement["navPoint"].all != nil {
for navPoint in navpointElement["navPoint"].all! {
toc.children.append(readTOCReference(navPoint))
}
}
return toc
}
/**
Read and parse <metadata>.
*/
private func readMetadata(tags: [AEXMLElement]) -> FRMetadata {
let metadata = FRMetadata()
for tag in tags {
if tag.name == "dc:title" {
metadata.titles.append(tag.value!)
}
if tag.name == "dc:identifier" {
metadata.identifiers.append(Identifier(scheme: tag.attributes["opf:scheme"] != nil ? tag.attributes["opf:scheme"] as! String : "", value: tag.value!))
}
if tag.name == "dc:language" {
metadata.language = tag.value != nil ? tag.value! : ""
}
if tag.name == "dc:creator" {
metadata.creators.append(Author(name: tag.value!, role: tag.attributes["opf:role"] != nil ? tag.attributes["opf:role"] as! String : "", fileAs: tag.attributes["opf:file-as"] != nil ? tag.attributes["opf:file-as"] as! String : ""))
}
if tag.name == "dc:contributor" {
metadata.creators.append(Author(name: tag.value!, role: tag.attributes["opf:role"] != nil ? tag.attributes["opf:role"] as! String : "", fileAs: tag.attributes["opf:file-as"] != nil ? tag.attributes["opf:file-as"] as! String : ""))
}
if tag.name == "dc:publisher" {
metadata.publishers.append(tag.value != nil ? tag.value! : "")
}
if tag.name == "dc:description" {
metadata.descriptions.append(tag.value != nil ? tag.value! : "")
}
if tag.name == "dc:subject" {
metadata.subjects.append(tag.value != nil ? tag.value! : "")
}
if tag.name == "dc:rights" {
metadata.rights.append(tag.value != nil ? tag.value! : "")
}
if tag.name == "dc:date" {
metadata.dates.append(Date(date: tag.value!, event: tag.attributes["opf:event"] != nil ? tag.attributes["opf:event"] as! String : ""))
}
if tag.name == "meta" {
if tag.attributes["name"] != nil {
metadata.metaAttributes.append(Meta(name: tag.attributes["name"] as! String, content: (tag.attributes["content"] != nil ? tag.attributes["content"] as! String : "")))
}
if tag.attributes["property"] != nil && tag.attributes["id"] != nil {
metadata.metaAttributes.append(Meta(id: tag.attributes["id"] as! String, property: tag.attributes["property"] as! String, value: tag.value != nil ? tag.value! : ""))
}
}
}
return metadata
}
/**
Read and parse <spine>.
*/
private func readSpine(tags: [AEXMLElement]) -> FRSpine {
let spine = FRSpine()
for tag in tags {
let idref = tag.attributes["idref"] as! String
var linear = true
if tag.attributes["linear"] != nil {
linear = tag.attributes["linear"] as! String == "yes" ? true : false
}
if book.resources.containsById(idref) {
spine.spineReferences.append(Spine(resource: book.resources.getById(idref)!, linear: linear))
}
}
return spine
}
}
| gpl-2.0 |
jpush/jchat-swift | ContacterModule/Model/JCVerificationInfo.swift | 1 | 806 | //
// JCVerificationInfo.swift
// JChat
//
// Created by JIGUANG on 14/04/2017.
// Copyright © 2017 HXHG. All rights reserved.
//
import UIKit
enum JCVerificationType: Int {
case wait
case accept
case reject
case receive
}
class JCVerificationInfo: NSObject {
var id = 0
var username: String = ""
var nickname: String = ""
var appkey: String = ""
var resaon: String = ""
var state: Int = 0
static func create(username: String, nickname: String?, appkey: String, resaon: String?, state: Int) -> JCVerificationInfo {
let info = JCVerificationInfo()
info.username = username
info.nickname = nickname ?? ""
info.appkey = appkey
info.resaon = resaon ?? ""
info.state = state
return info
}
}
| mit |
GTMYang/GTMRouter | GTMRouter/String+GTMRouter.swift | 1 | 1486 | //
// String+GTMRouter.swift
// GTMRouter
//
// Created by luoyang on 2016/12/19.
// Copyright © 2016年 luoyang. All rights reserved.
//
import Foundation
extension String {
var intValue:Int {
get {
if let val = Int(self) {
return val
}
return 0
}
}
var floatValue:Float {
get {
if let val = Float(self) {
return val
}
return 0
}
}
var doubleValue:Double {
get {
if let val = Double(self) {
return val
}
return 0
}
}
var boolValue:Bool {
get {
if let val = Bool(self) {
return val
}
return false
}
}
public var escaped: String {
get {
let legalURLCharactersToBeEscaped: CFString = ":&=;+!@#$()',*" as CFString
return CFURLCreateStringByAddingPercentEscapes(nil, self as CFString, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
public func asURL() -> URL? {
let utf8Str = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
guard let urlString = utf8Str, let url = URL(string: urlString) else {
print("GTMRouter ---> 字符串转URL出错,请检查URL字符串")
return nil
}
return url
}
}
| mit |
googleapis/google-auth-library-swift | Sources/OAuth2/PlatformNativeTokenProvider.swift | 1 | 5495 | // Copyright 2021 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.
#if os(macOS) || os(iOS)
import Dispatch
import Foundation
import AuthenticationServices
public struct NativeCredentials: Codable, CodeExchangeInfo, RefreshExchangeInfo {
let clientID: String
let authorizeURL: String
let accessTokenURL: String
let callbackScheme: String
enum CodingKeys: String, CodingKey {
case clientID = "client_id"
case authorizeURL = "authorize_url"
case accessTokenURL = "access_token_url"
case callbackScheme = "callback_scheme"
}
var redirectURI: String {
callbackScheme + ":/oauth2redirect"
}
var clientSecret: String {
""
}
}
@available(macOS 10.15.4, iOS 13.4, *)
public class PlatformNativeTokenProvider: TokenProvider {
private var credentials: NativeCredentials
private var session: Session?
public var token: Token?
// for parity with BrowserTokenProvider
public convenience init?(credentials: String, token tokenfile: String) {
let path = ProcessInfo.processInfo.environment["HOME"]!
+ "/.credentials/" + credentials
let url = URL(fileURLWithPath: path)
guard let credentialsData = try? Data(contentsOf: url) else {
print("No credentials data at \(path).")
return nil
}
self.init(credentials: credentialsData, token: tokenfile)
}
public init?(credentials: Data, token tokenfile: String) {
let decoder = JSONDecoder()
guard let credentials = try? decoder.decode(NativeCredentials.self,
from: credentials)
else {
print("Error reading credentials")
return nil
}
self.credentials = credentials
if tokenfile != "" {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: tokenfile))
let decoder = JSONDecoder()
guard let token = try? decoder.decode(Token.self, from: data)
else {
return nil
}
self.token = token
} catch {
// ignore errors due to missing token files
}
}
}
public func saveToken(_ filename: String) throws {
if let token = token {
try token.save(filename)
}
}
public func refreshToken(_ filename: String) throws {
if let token = token, token.isExpired() {
self.token = try Refresh(token: token).exchange(info: credentials)
try saveToken(filename)
}
}
private struct Session {
let webAuthSession: ASWebAuthenticationSession
let webAuthContext: ASWebAuthenticationPresentationContextProviding
}
// The presentation context provides a reference to a UIWindow that the auth
// framework uese to display the confirmation modal and sign in controller.
public func signIn(
scopes: [String],
context: ASWebAuthenticationPresentationContextProviding,
completion: @escaping (Token?, AuthError?) -> Void
) {
let state = UUID().uuidString
let scope = scopes.joined(separator: " ")
var urlComponents = URLComponents(string: credentials.authorizeURL)!
urlComponents.queryItems = [
URLQueryItem(name: "client_id", value: credentials.clientID),
URLQueryItem(name: "response_type", value: "code"),
URLQueryItem(name: "redirect_uri", value: credentials.redirectURI),
URLQueryItem(name: "state", value: state),
URLQueryItem(name: "scope", value: scope),
]
let session = ASWebAuthenticationSession(
url: urlComponents.url!,
callbackURLScheme: credentials.callbackScheme
) { url, err in
defer { self.session = nil }
if let e = err {
completion(nil, .webSession(inner: e))
return
}
guard let u = url else {
// If err is nil, url should not be, and vice versa.
completion(nil, .unknownError)
return
}
let code = Code(urlComponents: URLComponents(string: u.absoluteString)!)
do {
self.token = try code.exchange(info: self.credentials)
completion(self.token!, nil)
} catch let ae as AuthError {
completion(nil, ae)
} catch {
completion(nil, .unknownError)
}
}
session.presentationContextProvider = context
if !session.canStart {
// This happens if the context provider is not set, or if the session has
// already been started. We enforce correct usage so ignore.
return
}
let success = session.start()
if !success {
// This doesn't happen unless the context is not set, disappears (it's a
// weak ref internally), or the session was previously started, ignore.
return
}
self.session = Session(webAuthSession: session, webAuthContext: context)
}
// Canceling the session dismisses the view controller if it is showing.
public func cancelSignIn() {
session?.webAuthSession.cancel()
self.session = nil
}
public func withToken(_ callback: @escaping (Token?, Error?) -> Void) throws {
callback(token, nil)
}
}
#endif
| apache-2.0 |
hulinSun/MyRx | MyRx/Pods/ManualLayout/ManualLayout/UIScrollView+ManualLayout.swift | 2 | 1725 | //
// UIScrollView+ManualLayout.swift
// ManualLayout
//
// Created by Baris Sencan on 06/03/15.
// Copyright (c) 2015 Baris Sencan. All rights reserved.
//
import UIKit
public extension UIScrollView {
// MARK: - Content Size
public var contentWidth: CGFloat {
get {
return contentSize.width
}
set {
contentSize.width = snapToPixel(pointCoordinate: newValue)
}
}
public var contentHeight: CGFloat {
get {
return contentSize.height
}
set {
contentSize.height = snapToPixel(pointCoordinate: newValue)
}
}
// MARK: - Content Edges (For Convenience)
public var contentTop: CGFloat {
return 0
}
public var contentLeft: CGFloat {
return 0
}
public var contentBottom: CGFloat {
get {
return contentHeight
}
set {
contentHeight = newValue
}
}
public var contentRight: CGFloat {
get {
return contentWidth
}
set {
contentWidth = newValue
}
}
// MARK: - Viewport Edges
public var viewportTop: CGFloat {
get {
return contentOffset.y
}
set {
contentOffset.y = snapToPixel(pointCoordinate: newValue)
}
}
public var viewportLeft: CGFloat {
get {
return contentOffset.x
}
set {
contentOffset.x = snapToPixel(pointCoordinate: newValue)
}
}
public var viewportBottom: CGFloat {
get {
return contentOffset.y + height
}
set {
contentOffset.y = snapToPixel(pointCoordinate: newValue - height)
}
}
public var viewportRight: CGFloat {
get {
return contentOffset.x + width
}
set {
contentOffset.x = snapToPixel(pointCoordinate: newValue - width)
}
}
}
| mit |
bigtreenono/NSPTools | RayWenderlich/Introduction to Swift/6 . Control Flow/ChallengeControlFlow.playground/section-1.swift | 1 | 274 | for x in 1...100 {
let multipleOf3 = x % 3 == 0
let multipleOf5 = x % 5 == 0
if (multipleOf3 && multipleOf5) {
println("FizzBuzz")
} else if (multipleOf3) {
println("Fizz")
} else if (multipleOf5) {
println("Buzz")
} else {
println("\(x)")
}
}
| mit |
SuPair/firefox-ios | XCUITests/TabTraySearchTabsTests.swift | 1 | 2750 | import XCTest
let firstURL = "mozilla.org"
let secondURL = "mozilla.org/en-US/book"
let fullFirstURL = "https://www.mozilla.org/en-US/"
class TabTraySearchTabsTests: BaseTestCase {
func testSearchTabs() {
// Open two tabs and go to tab tray
navigator.openURL(firstURL)
waitUntilPageLoad()
navigator.openNewURL(urlString: secondURL )
navigator.goto(TabTray)
// Search no matches
waitforExistence(app.textFields["Search Tabs"])
XCTAssertTrue(app.textFields["Search Tabs"].exists)
searchTabs(tabTitleOrUrl: "foo")
// Search by title one match
XCTAssertEqual(app.collectionViews.cells.count, 0)
app.buttons["close medium"].tap()
searchTabs(tabTitleOrUrl: "Internet")
XCTAssertEqual(app.collectionViews.cells.count, 1)
// Search by url two matches
app.buttons["close medium"].tap()
searchTabs(tabTitleOrUrl: "mozilla")
XCTAssertEqual(app.collectionViews.cells.count, 2)
}
private func searchTabs(tabTitleOrUrl: String) {
waitforExistence(app.textFields["Search Tabs"])
app.textFields["Search Tabs"].tap()
app.textFields["Search Tabs"].typeText(tabTitleOrUrl)
}
func testSearchTabsPrivateMode() {
navigator.performAction(Action.TogglePrivateMode)
// Open two tabs to check that the search works
navigator.openNewURL(urlString: firstURL)
waitUntilPageLoad()
navigator.openNewURL(urlString: secondURL)
navigator.goto(TabTray)
searchTabs(tabTitleOrUrl: "internet")
XCTAssertEqual(app.collectionViews.cells.count, 1)
}
// Test disabled because the DragAndDrop is off due to a non repro crash bug 1486269
/*func testDragAndDropTabToSearchTabField() {
navigator.openURL(firstURL)
navigator.goto(TabTray)
waitforExistence(app.textFields["Search Tabs"])
app.collectionViews.cells["Internet for people, not profit — Mozilla"].press(forDuration: 2, thenDragTo: app.textFields["Search Tabs"])
waitForValueContains(app.textFields["Search Tabs"], value: "mozilla.org")
let searchValue = app.textFields["Search Tabs"].value
XCTAssertEqual(searchValue as! String, fullFirstURL)
}*/
func testSearchFieldClearedAfterVisingWebsite() {
navigator.openURL(firstURL)
navigator.goto(TabTray)
searchTabs(tabTitleOrUrl: "mozilla")
app.collectionViews.cells["Internet for people, not profit — Mozilla"].tap()
navigator.nowAt(BrowserTab)
navigator.goto(TabTray)
let searchValue = app.textFields["Search Tabs"].value
XCTAssertEqual(searchValue as! String, "Search Tabs")
}
}
| mpl-2.0 |
silence0201/Swift-Study | Swifter/01Selector.playground/Contents.swift | 1 | 1310 | //: Playground - noun: a place where people can play
import Foundation
class MyObject: NSObject {
func callMe() {
}
func callMeWithParm(obj: AnyObject) {
}
func trun(by angle: Int, speed: Float) {
}
func selecotrs() -> [Selector] {
let someMethod = #selector(callMe)
let anotherMethod = #selector(callMeWithParm(obj:))
let method = #selector(trun(by:speed:))
return [someMethod, anotherMethod, method]
}
func otherSelector() -> [Selector] {
let someMethod = #selector(callMe)
let anotherMethod = #selector(callMeWithParm)
let method = #selector(trun)
return [someMethod, anotherMethod, method]
}
func commonFunc() {
}
func commonFunc(input: Int) -> Int {
return input
}
func sameNameSelector() -> [Selector] {
let method1 = #selector(commonFunc as () -> Void)
let method2 = #selector(commonFunc as (Int) -> Int)
return [method1, method2]
}
}
let selectors = MyObject().selecotrs()
print(selectors)
let otherSelectors = MyObject().otherSelector()
print(otherSelectors)
let sameNameSelectors = MyObject().sameNameSelector()
print(sameNameSelectors)
| mit |
gmission/gmission-ios | gmission/Carthage/Checkouts/ImageViewer/ImageViewer/Source/GalleryCloseTransition.swift | 3 | 1310 | //
// GalleryCloseTransition.swift
// ImageViewer
//
// Created by Kristian Angyal on 04/03/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
final class GalleryCloseTransition: NSObject, UIViewControllerAnimatedTransitioning {
private let duration: NSTimeInterval
init(duration: NSTimeInterval) {
self.duration = duration
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let transitionContainerView = transitionContext.containerView()!
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
transitionContainerView.addSubview(fromViewController.view)
UIView.animateWithDuration(self.duration, delay: 0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in
/// Transition the frontend to full clear
fromViewController.view.alpha = 1.0
}) { finished in
transitionContext.completeTransition(finished)
}
}
} | mit |
czechboy0/XcodeServerSDK | XcodeServerSDK/Server Entities/BotSchedule.swift | 1 | 3428 | //
// BotSchedule.swift
// XcodeServerSDK
//
// Created by Mateusz Zając on 13.06.2015.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
public class BotSchedule : XcodeServerEntity {
public enum Schedule : Int {
case Periodical = 1
case Commit
case Manual
public func toString() -> String {
switch self {
case .Periodical:
return "Periodical"
case .Commit:
return "On Commit"
case .Manual:
return "Manual"
}
}
}
public enum Period : Int {
case Hourly = 1
case Daily
case Weekly
}
public enum Day : Int {
case Monday = 1
case Tuesday
case Wednesday
case Thursday
case Friday
case Saturday
case Sunday
}
public let schedule: Schedule!
public let period: Period?
public let day: Day!
public let hours: Int!
public let minutes: Int!
public required init(json: NSDictionary) throws {
let schedule = Schedule(rawValue: try json.intForKey("scheduleType"))!
self.schedule = schedule
if schedule == .Periodical {
let period = Period(rawValue: try json.intForKey("periodicScheduleInterval"))!
self.period = period
let minutes = json.optionalIntForKey("minutesAfterHourToIntegrate")
let hours = json.optionalIntForKey("hourOfIntegration")
switch period {
case .Hourly:
self.minutes = minutes!
self.hours = nil
self.day = nil
case .Daily:
self.minutes = minutes!
self.hours = hours!
self.day = nil
case .Weekly:
self.minutes = minutes!
self.hours = hours!
self.day = Day(rawValue: try json.intForKey("weeklyScheduleDay"))
}
} else {
self.period = nil
self.minutes = nil
self.hours = nil
self.day = nil
}
try super.init(json: json)
}
private init(schedule: Schedule, period: Period?, day: Day?, hours: Int?, minutes: Int?) {
self.schedule = schedule
self.period = period
self.day = day
self.hours = hours
self.minutes = minutes
super.init()
}
public class func manualBotSchedule() -> BotSchedule {
return BotSchedule(schedule: .Manual, period: nil, day: nil, hours: nil, minutes: nil)
}
public class func commitBotSchedule() -> BotSchedule {
return BotSchedule(schedule: .Commit, period: nil, day: nil, hours: nil, minutes: nil)
}
public override func dictionarify() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary["scheduleType"] = self.schedule.rawValue
dictionary["periodicScheduleInterval"] = self.period?.rawValue ?? 0
dictionary["weeklyScheduleDay"] = self.day?.rawValue ?? 0
dictionary["hourOfIntegration"] = self.hours ?? 0
dictionary["minutesAfterHourToIntegrate"] = self.minutes ?? 0
return dictionary
}
} | mit |
brentdax/swift | test/IRGen/sil_generic_witness_methods_objc.swift | 2 | 1721 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -enable-objc-interop -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: These should be SIL tests, but we can't parse generic types in SIL
// yet.
@objc protocol ObjC {
func method()
}
// CHECK-LABEL: define hidden swiftcc void @"$s32sil_generic_witness_methods_objc05call_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T) {{.*}} {
// CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(method)", align 8
// CHECK: [[CAST:%.*]] = bitcast %objc_object* %0 to [[SELFTYPE:%?.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[SELFTYPE]]*, i8*)*)([[SELFTYPE]]* [[CAST]], i8* [[SEL]])
func call_objc_method<T: ObjC>(_ x: T) {
x.method()
}
// CHECK-LABEL: define hidden swiftcc void @"$s32sil_generic_witness_methods_objc05call_f1_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T) {{.*}} {
// CHECK: call swiftcc void @"$s32sil_generic_witness_methods_objc05call_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T)
func call_call_objc_method<T: ObjC>(_ x: T) {
call_objc_method(x)
}
// CHECK-LABEL: define hidden swiftcc void @"$s32sil_generic_witness_methods_objc05call_E19_existential_method{{[_0-9a-zA-Z]*}}F"(%objc_object*) {{.*}} {
// CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(method)", align 8
// CHECK: [[CAST:%.*]] = bitcast %objc_object* %0 to [[SELFTYPE:%?.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[SELFTYPE]]*, i8*)*)([[SELFTYPE]]* [[CAST]], i8* [[SEL]])
func call_objc_existential_method(_ x: ObjC) {
x.method()
}
| apache-2.0 |
bascar2020/ios-truelinc | Truelinc/QrViewController.swift | 1 | 1015 | //
// QrViewController.swift
// Truelinc
//
// Created by Juan Diaz on 27/01/16.
// Copyright © 2016 Indibyte. All rights reserved.
//
import UIKit
class QrViewController: UIViewController {
@IBOutlet weak var img_qr_Full: UIImageView!
var viaSegueQrFull = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
img_qr_Full.image = viaSegueQrFull
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 |
AlesTsurko/DNMKit | DNM_iOS/DNM_iOS/ButtonSwitchNodeGroup.swift | 1 | 2371 | //
// ButtonSwitchNodeGroup.swift
// ComponentSelectorTest
//
// Created by James Bean on 10/8/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
public class ButtonSwitchNodeGroup {
public var id: String = ""
public var buttonSwitchNodes: [ButtonSwitchNode] = []
public var buttonSwitchNodeByID: [String : ButtonSwitchNode] = [:]
public var leaderButtonSwitchNode: ButtonSwitchNodeLeader?
public var stateByID: [String : ButtonSwitchNodeState] = [:]
public var line = CAShapeLayer() // refine
// view
public var colorHue: CGFloat = 214 {
didSet {
for buttonSwitchNode in buttonSwitchNodes { buttonSwitchNode.colorHue = colorHue }
}
}
public init(id: String) {
self.id = id
}
public func updateStateByID() {
for buttonSwitchNode in buttonSwitchNodes {
if buttonSwitchNode.text == id {
stateByID["performer"] = buttonSwitchNode.switch_state
}
else {
stateByID[buttonSwitchNode.text] = buttonSwitchNode.switch_state
}
}
}
public func addButtonSwitchNode(buttonSwitchNode: ButtonSwitchNode) {
if let leader = buttonSwitchNode as? ButtonSwitchNodeLeader {
buttonSwitchNodes.insert(buttonSwitchNode, atIndex: 0)
leaderButtonSwitchNode = leader
}
else { buttonSwitchNodes.append(buttonSwitchNode) }
buttonSwitchNodeByID[buttonSwitchNode.id] = buttonSwitchNode
}
public func buttonSwitchNodeWithID(id: String, andText text: String, isLeader: Bool = false) {
// TODO: non-hack width
let buttonSwitchNode: ButtonSwitchNode
switch isLeader {
case true:
buttonSwitchNode = ButtonSwitchNodeLeader(width: 50, text: text, id: id)
case false:
buttonSwitchNode = ButtonSwitchNode(width: 50, text: text, id: id)
}
addButtonSwitchNode(buttonSwitchNode)
}
public func stateHasChangedFromLeaderButtonSwitchNode(
leaderButtonSwitchNode: ButtonSwitchNodeLeader
)
{
// something
}
public func stateHasChangedFromFollowerButtonSwitchNode(
followerButtonSwitchNode: ButtonSwitchNode
)
{
// something
}
}
| gpl-2.0 |
InsectQY/HelloSVU_Swift | HelloSVU_Swift/Classes/Module/Map/Route/Main/Controller/RoutePageViewController.swift | 1 | 3540 | //
// RoutePageViewController.swift
// HelloSVU_Swift
//
// Created by Insect on 2017/10/3.
//Copyright © 2017年 Insect. All rights reserved.
//
import UIKit
let kTitleViewH: CGFloat = 30
class RoutePageViewController: BaseViewController {
@IBOutlet private weak var originField: UITextField!
@IBOutlet private weak var destinationField: UITextField!
private lazy var originPoint = AMapGeoPoint()
private lazy var destinationPoint = AMapGeoPoint()
// MARK: - LazyLoad
private lazy var pageView: QYPageView = {
let style = QYPageStyle()
style.normalColor = UIColor(r: 255, g: 255, b: 255)
style.selectColor = UIColor(r: 255, g: 255, b: 255)
style.titleViewHeight = kTitleViewH
style.bottomLineHeight = 2
var childVcs = [UIViewController]()
let vc = BusRouteViewController()
childVcs.append(vc)
let routeType: [routePlanType] = [.Walking,.Riding,.Driving]
for type in routeType {
let vc = BasePlanViewController()
vc.routePlanType = type
childVcs.append(vc)
}
let pageView = QYPageView(frame: CGRect(x: 0, y: 115, width: ScreenW, height: ScreenH - 115), titles: ["公交","步行","骑行","驾车"], titleStyle: style, childVcs: childVcs, parentVc: self)
pageView.backgroundColor = UIColor(r: 74, g: 137, b: 255)
return pageView
}()
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
}
}
// MARK: - 设置 UI 界面
extension RoutePageViewController {
private func setUpUI() {
fd_prefersNavigationBarHidden = true
view.addSubview(pageView)
}
// MARK: - 返回按钮点击事件
@IBAction func backBtnDidClick(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
}
// MARK: - UITextFieldDelegate
extension RoutePageViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
let searchVc = MapSearchViewController()
if textField == originField {
searchVc.searchBarText = "请输入起点"
searchVc.poiSuggestion = {[weak self] (poi) in
self?.originField.text = poi.name
if let originPoint = poi.location {
self?.originPoint = originPoint
}
self?.chooseNavType()
}
}else {
searchVc.searchBarText = "请输入终点"
searchVc.poiSuggestion = {[weak self] (poi) in
self?.destinationField.text = poi.name
if let destinationPoint = poi.location {
self?.destinationPoint = destinationPoint
}
self?.chooseNavType()
}
}
navigationController?.pushViewController(searchVc, animated: true)
}
}
// MARK: - 事件处理
extension RoutePageViewController {
private func chooseNavType() {
if destinationField.text == "请输入终点" {return}
startBusRoute()
}
private func startBusRoute() {
let vc = childViewControllers[0] as! BusRouteViewController
vc.searchRoutePlanningBus(0, originPoint, destinationPoint,(originField.text ?? ""),(destinationField.text ?? ""))
}
}
| apache-2.0 |
salesawagner/WASKit | Sources/Extensions/String/NSMutableAttributedString+WASApend.swift | 1 | 1866 | //
// WASKit
//
// Copyright (c) Wagner Sales (http://wagnersales.com.br/)
//
// 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 extension NSMutableAttributedString {
// MARK: - Public methods
/// Append text with custom font to AttributedString
///
/// - Example:
///
/// `let formattedString = NSMutableAttributedString()
/// formattedString.WASappendText(withFont: defaultFont, text: "NEW TEXT")`
///
/// - Returns: AttributedString + formatted text
@discardableResult func WASappendText(withFont font: UIFont, text: String) -> NSMutableAttributedString {
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font]
let attributedString = NSMutableAttributedString(string: text, attributes: attributes)
self.append(attributedString)
return self
}
}
| mit |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Jetpack/Jetpack Scan/JetpackScanThreatDetailsViewController.swift | 2 | 10638 | import UIKit
import WordPressFlux
protocol JetpackScanThreatDetailsViewControllerDelegate: AnyObject {
func willFixThreat(_ threat: JetpackScanThreat, controller: JetpackScanThreatDetailsViewController)
func willIgnoreThreat(_ threat: JetpackScanThreat, controller: JetpackScanThreatDetailsViewController)
}
class JetpackScanThreatDetailsViewController: UIViewController {
// MARK: - IBOutlets
/// General info
@IBOutlet private weak var generalInfoStackView: UIStackView!
@IBOutlet private weak var icon: UIImageView!
@IBOutlet private weak var generalInfoTitleLabel: UILabel!
@IBOutlet private weak var generalInfoDescriptionLabel: UILabel!
/// Problem
@IBOutlet private weak var problemStackView: UIStackView!
@IBOutlet private weak var problemTitleLabel: UILabel!
@IBOutlet private weak var problemDescriptionLabel: UILabel!
/// Technical details
@IBOutlet private weak var technicalDetailsStackView: UIStackView!
@IBOutlet private weak var technicalDetailsTitleLabel: UILabel!
@IBOutlet private weak var technicalDetailsDescriptionLabel: UILabel!
@IBOutlet private weak var technicalDetailsFileContainerView: UIView!
@IBOutlet private weak var technicalDetailsFileLabel: UILabel!
@IBOutlet private weak var technicalDetailsContextLabel: UILabel!
/// Fix
@IBOutlet private weak var fixStackView: UIStackView!
@IBOutlet private weak var fixTitleLabel: UILabel!
@IBOutlet private weak var fixDescriptionLabel: UILabel!
/// Buttons
@IBOutlet private weak var buttonsStackView: UIStackView!
@IBOutlet private weak var fixThreatButton: FancyButton!
@IBOutlet private weak var ignoreThreatButton: FancyButton!
@IBOutlet private weak var warningButton: MultilineButton!
@IBOutlet weak var ignoreActivityIndicatorView: UIActivityIndicatorView!
// MARK: - Properties
weak var delegate: JetpackScanThreatDetailsViewControllerDelegate?
private let blog: Blog
private let threat: JetpackScanThreat
private let hasValidCredentials: Bool
private lazy var viewModel: JetpackScanThreatViewModel = {
return JetpackScanThreatViewModel(threat: threat, hasValidCredentials: hasValidCredentials)
}()
// MARK: - Init
init(blog: Blog, threat: JetpackScanThreat, hasValidCredentials: Bool = false) {
self.blog = blog
self.threat = threat
self.hasValidCredentials = hasValidCredentials
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.title
configure(with: viewModel)
}
// MARK: - IBActions
@IBAction private func fixThreatButtonTapped(_ sender: Any) {
let alert = UIAlertController(title: viewModel.fixActionTitle,
message: viewModel.fixDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.cancel, style: .cancel))
alert.addAction(UIAlertAction(title: Strings.ok, style: .default, handler: { [weak self] _ in
guard let self = self else {
return
}
self.delegate?.willFixThreat(self.threat, controller: self)
self.trackEvent(.jetpackScanThreatFixTapped)
}))
present(alert, animated: true)
trackEvent(.jetpackScanFixThreatDialogOpen)
}
@IBAction private func ignoreThreatButtonTapped(_ sender: Any) {
guard let blogName = blog.settings?.name else {
return
}
let alert = UIAlertController(title: viewModel.ignoreActionTitle,
message: String(format: viewModel.ignoreActionMessage, blogName),
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.cancel, style: .cancel))
alert.addAction(UIAlertAction(title: Strings.ok, style: .default, handler: { [weak self] _ in
guard let self = self else {
return
}
self.ignoreThreatButton.isHidden = true
self.ignoreActivityIndicatorView.startAnimating()
self.delegate?.willIgnoreThreat(self.threat, controller: self)
self.trackEvent(.jetpackScanThreatIgnoreTapped)
}))
present(alert, animated: true)
trackEvent(.jetpackScanIgnoreThreatDialogOpen)
}
@IBAction func warningButtonTapped(_ sender: Any) {
guard let siteID = blog.dotComID as? Int,
let controller = JetpackWebViewControllerFactory.settingsController(siteID: siteID) else {
displayNotice(title: Strings.jetpackSettingsNotice)
return
}
let navVC = UINavigationController(rootViewController: controller)
present(navVC, animated: true)
}
// MARK: - Private
private func trackEvent(_ event: WPAnalyticsEvent) {
WPAnalytics.track(event, properties: ["threat_signature": threat.signature])
}
}
extension JetpackScanThreatDetailsViewController {
// MARK: - Configure
func configure(with viewModel: JetpackScanThreatViewModel) {
icon.image = viewModel.detailIconImage
icon.tintColor = viewModel.detailIconImageColor
generalInfoTitleLabel.text = viewModel.title
generalInfoDescriptionLabel.text = viewModel.description
problemTitleLabel.text = viewModel.problemTitle
problemDescriptionLabel.text = viewModel.problemDescription
if let attributedFileContext = self.viewModel.attributedFileContext {
technicalDetailsTitleLabel.text = viewModel.technicalDetailsTitle
technicalDetailsDescriptionLabel.text = viewModel.technicalDetailsDescription
technicalDetailsFileLabel.text = viewModel.fileName
technicalDetailsContextLabel.attributedText = attributedFileContext
technicalDetailsStackView.isHidden = false
} else {
technicalDetailsStackView.isHidden = true
}
fixTitleLabel.text = viewModel.fixTitle
fixDescriptionLabel.text = viewModel.fixDescription
if let fixActionTitle = viewModel.fixActionTitle {
fixThreatButton.setTitle(fixActionTitle, for: .normal)
fixThreatButton.isEnabled = viewModel.fixActionEnabled
fixThreatButton.isHidden = false
} else {
fixThreatButton.isHidden = true
}
if let ignoreActionTitle = viewModel.ignoreActionTitle {
ignoreThreatButton.setTitle(ignoreActionTitle, for: .normal)
ignoreThreatButton.isHidden = false
} else {
ignoreThreatButton.isHidden = true
}
if let warningActionTitle = viewModel.warningActionTitle {
let attributedTitle = WPStyleGuide.Jetpack.highlightString(warningActionTitle.substring,
inString: warningActionTitle.string)
warningButton.setAttributedTitle(attributedTitle, for: .normal)
warningButton.isHidden = false
} else {
warningButton.isHidden = true
}
applyStyles()
}
// MARK: - Styling
private func applyStyles() {
view.backgroundColor = .basicBackground
styleGeneralInfoSection()
styleProblemSection()
styleTechnicalDetailsSection()
styleFixSection()
styleButtons()
}
private func styleGeneralInfoSection() {
generalInfoTitleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold)
generalInfoTitleLabel.textColor = .error
generalInfoTitleLabel.numberOfLines = 0
generalInfoDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.body)
generalInfoDescriptionLabel.textColor = .text
generalInfoDescriptionLabel.numberOfLines = 0
}
private func styleProblemSection() {
problemTitleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold)
problemTitleLabel.textColor = .text
problemTitleLabel.numberOfLines = 0
problemDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.body)
problemDescriptionLabel.textColor = .text
problemDescriptionLabel.numberOfLines = 0
}
private func styleTechnicalDetailsSection() {
technicalDetailsTitleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold)
technicalDetailsTitleLabel.textColor = .text
technicalDetailsTitleLabel.numberOfLines = 0
technicalDetailsFileContainerView.backgroundColor = viewModel.fileNameBackgroundColor
technicalDetailsFileLabel.font = viewModel.fileNameFont
technicalDetailsFileLabel.textColor = viewModel.fileNameColor
technicalDetailsFileLabel.numberOfLines = 0
technicalDetailsDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.body)
technicalDetailsDescriptionLabel.textColor = .text
technicalDetailsDescriptionLabel.numberOfLines = 0
technicalDetailsContextLabel.numberOfLines = 0
}
private func styleFixSection() {
fixTitleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold)
fixTitleLabel.textColor = .text
fixTitleLabel.numberOfLines = 0
fixDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.body)
fixDescriptionLabel.textColor = .text
fixDescriptionLabel.numberOfLines = 0
}
private func styleButtons() {
fixThreatButton.isPrimary = true
ignoreThreatButton.isPrimary = false
warningButton.setTitleColor(.text, for: .normal)
warningButton.titleLabel?.lineBreakMode = .byWordWrapping
warningButton.titleLabel?.numberOfLines = 0
warningButton.setImage(.gridicon(.plusSmall), for: .normal)
}
}
extension JetpackScanThreatDetailsViewController {
private enum Strings {
static let title = NSLocalizedString("Threat details", comment: "Title for the Jetpack Scan Threat Details screen")
static let ok = NSLocalizedString("OK", comment: "OK button for alert")
static let cancel = NSLocalizedString("Cancel", comment: "Cancel button for alert")
static let jetpackSettingsNotice = NSLocalizedString("Unable to visit Jetpack settings for site", comment: "Message displayed when visiting the Jetpack settings page fails.")
}
}
| gpl-2.0 |
LiquidAnalytics/ld-api-examples | ios/LPKTutorialOne-Swift/LPKTutorialOne-Swift/ViewController.swift | 1 | 3373 | //
// ViewController.swift
// LPKTutorialOne-Swift
//
// Created by CARSON LI on 2016-06-30.
// Copyright © 2016 Liquid Analytics. All rights reserved.
//
import UIKit
import LiquidPlatformKit
class ViewController: UIViewController, LSCSeasideApplicationDelegate {
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var dummyButton: UIButton!
var loginCallback: ((String, String) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
self.dummyButton.hidden = true
self.infoLabel.text = ""
self.progressBar.progress = 0.0
self.progressBar.hidden = true
//load the DB in the background, typically there is a loading screen that goes here
//so we don't block the main thread
LDMDataManager.sharedInstance().executeAsynch {
LDMDataManager.sharedInstance().openDatabaseWithName("MovieCollection")
LSCSyncController.sharedInstance().startWithDelegate(self);
if let deviceId = NSUserDefaults.standardUserDefaults().objectForKey("seasideCustomDeviceId")
{
print(deviceId)
}
self.loginButton.enabled = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginButtonPressed()
{
self.loginButton.enabled = false
self.usernameField.enabled = false
self.passwordField.enabled = false
self.progressBar.hidden = false
LDMDataManager.sharedInstance().executeAsynch {
if let username = self.usernameField.text
{
if let password = self.passwordField.text
{
self.loginCallback!(username, password)
}
}
}
}
func updateLoginStatusLabel(status: String?, enable: Bool) {
dispatch_async(dispatch_get_main_queue()) {
self.infoLabel.text = status;
}
}
func authenticateWithMessage(message: String?, userEditable: Bool, providePasscode: Bool, callback: ((String, String) -> Void)?) {
self.loginCallback = callback;
dispatch_async(dispatch_get_main_queue()) {
self.loginButton.enabled = true
self.usernameField.enabled = true
self.passwordField.enabled = true
self.passwordField.text = "";
self.infoLabel.text = message;
}
}
func registeringWithMessage(message: String?, syncingData: Bool, syncProgress: Float) {
dispatch_async(dispatch_get_main_queue()) {
self.infoLabel.text = message;
self.progressBar.progress = syncProgress;
}
}
func selectCommunity() {
LSCSyncController.sharedInstance().communitySelected("MovieCollection");
}
func registered() {
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("showMovieSegue", sender: nil)
}
}
}
| apache-2.0 |
Estanque/RichEditorView | RichEditorViewSample/RichEditorViewSampleTests/RichEditorViewSampleTests.swift | 2 | 933 | //
// RichEditorViewSampleTests.swift
// RichEditorViewSampleTests
//
// Created by Caesar Wirth on 4/5/15.
// Copyright (c) 2015 Caesar Wirth. All rights reserved.
//
import UIKit
import XCTest
class RichEditorViewSampleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| bsd-3-clause |
nalexn/ViewInspector | Tests/ViewInspectorTests/ViewModifiers/TextInputModifiersTests.swift | 1 | 6523 | import XCTest
import SwiftUI
@testable import ViewInspector
// MARK: - TextInputModifiersTests
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class TextInputModifiersTests: XCTestCase {
#if os(iOS) || os(tvOS) || os(watchOS)
func testTextContentType() throws {
let sut = EmptyView().textContentType(.emailAddress)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
#endif
#if (os(iOS) || os(tvOS)) && !targetEnvironment(macCatalyst)
func testTextContentTypeInspection() throws {
let sut = AnyView(EmptyView()).textContentType(.emailAddress)
XCTAssertEqual(try sut.inspect().anyView().textContentType(), .emailAddress)
XCTAssertEqual(try sut.inspect().anyView().emptyView().textContentType(), .emailAddress)
}
#endif
#if (os(iOS) || os(tvOS)) && !targetEnvironment(macCatalyst)
func testKeyboardType() throws {
let sut = EmptyView().keyboardType(.namePhonePad)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testKeyboardTypeInspection() throws {
let sut = AnyView(EmptyView()).keyboardType(.namePhonePad)
XCTAssertEqual(try sut.inspect().anyView().keyboardType(), .namePhonePad)
XCTAssertEqual(try sut.inspect().anyView().emptyView().keyboardType(), .namePhonePad)
}
func testAutocapitalization() throws {
let sut = EmptyView().autocapitalization(.words)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testAutocapitalizationInspection() throws {
let sut = AnyView(EmptyView()).autocapitalization(.words)
XCTAssertEqual(try sut.inspect().anyView().autocapitalization(), .words)
XCTAssertEqual(try sut.inspect().anyView().emptyView().autocapitalization(), .words)
}
#endif
func testFont() throws {
let sut = EmptyView().font(.body)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testFontInspection() throws {
let sut = AnyView(EmptyView()).font(.largeTitle)
XCTAssertEqual(try sut.inspect().anyView().font(), .largeTitle)
XCTAssertEqual(try sut.inspect().anyView().emptyView().font(), .largeTitle)
}
func testTextFontOverrideWithNativeModifier() throws {
let sut = Group { Text("test").font(.callout) }.font(.footnote)
let group = try sut.inspect().group()
XCTAssertEqual(try group.font(), .footnote)
XCTAssertThrows(try EmptyView().inspect().font(),
"EmptyView does not have 'font' modifier")
XCTAssertEqual(try group.text(0).attributes().font(), .callout)
}
func testTextFontOverrideWithInnerModifier() throws {
let sut = AnyView(AnyView(Text("test")).font(.footnote)).font(.callout)
let text = try sut.inspect().find(text: "test")
XCTAssertEqual(try text.attributes().font(), .footnote)
}
func testLineLimit() throws {
let sut = EmptyView().lineLimit(5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testLineLimitInspection() throws {
let sut = AnyView(EmptyView()).lineLimit(5)
XCTAssertEqual(try sut.inspect().anyView().lineLimit(), 5)
XCTAssertEqual(try sut.inspect().anyView().emptyView().lineLimit(), 5)
}
func testLineSpacing() throws {
let sut = EmptyView().lineSpacing(5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testLineSpacingInspection() throws {
let sut = AnyView(EmptyView()).lineSpacing(4)
XCTAssertEqual(try sut.inspect().anyView().lineSpacing(), 4)
XCTAssertEqual(try sut.inspect().anyView().emptyView().lineSpacing(), 4)
}
func testMultilineTextAlignment() throws {
let sut = EmptyView().multilineTextAlignment(.center)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testMultilineTextAlignmentInspection() throws {
let sut = AnyView(EmptyView()).multilineTextAlignment(.center)
XCTAssertEqual(try sut.inspect().anyView().multilineTextAlignment(), .center)
XCTAssertEqual(try sut.inspect().anyView().emptyView().multilineTextAlignment(), .center)
}
func testMinimumScaleFactor() throws {
let sut = EmptyView().minimumScaleFactor(5)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testMinimumScaleFactorInspection() throws {
let sut = AnyView(EmptyView()).minimumScaleFactor(2)
XCTAssertEqual(try sut.inspect().anyView().minimumScaleFactor(), 2)
XCTAssertEqual(try sut.inspect().anyView().emptyView().minimumScaleFactor(), 2)
}
func testTruncationMode() throws {
let sut = EmptyView().truncationMode(.tail)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testTruncationModeInspection() throws {
let sut = AnyView(EmptyView()).truncationMode(.tail)
XCTAssertEqual(try sut.inspect().anyView().truncationMode(), .tail)
XCTAssertEqual(try sut.inspect().anyView().emptyView().truncationMode(), .tail)
}
func testAllowsTightening() throws {
let sut = EmptyView().allowsTightening(true)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testAllowsTighteningInspection() throws {
let sut = AnyView(EmptyView()).allowsTightening(true)
XCTAssertTrue(try sut.inspect().anyView().allowsTightening())
XCTAssertTrue(try sut.inspect().anyView().emptyView().allowsTightening())
}
#if !os(watchOS)
func testDisableAutocorrection() throws {
let sut = EmptyView().disableAutocorrection(false)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testDisableAutocorrectionInspection() throws {
let sut = AnyView(EmptyView()).disableAutocorrection(false)
XCTAssertEqual(try sut.inspect().anyView().disableAutocorrection(), false)
XCTAssertEqual(try sut.inspect().anyView().emptyView().disableAutocorrection(), false)
}
#endif
func testFlipsForRightToLeftLayoutDirection() throws {
let sut = EmptyView().flipsForRightToLeftLayoutDirection(true)
XCTAssertNoThrow(try sut.inspect().emptyView())
}
func testFlipsForRightToLeftLayoutDirectionInspection() throws {
let sut = EmptyView().flipsForRightToLeftLayoutDirection(true)
XCTAssertEqual(try sut.inspect().emptyView().flipsForRightToLeftLayoutDirection(), true)
}
}
| mit |
apple/swift | validation-test/compiler_crashers_fixed/26446-swift-generictypeparamtype-get.swift | 65 | 468 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class A{class A{
func d{{{
var A{
func a{
class A{enum S{
class
case,
| apache-2.0 |
sunyit-ncsclub/Poly-tool | Poly Tool/PolyMenuController.swift | 1 | 9204 | // Created by Joe on 12/8/14.
// Copyright (c) 2014 Joe Pasqualetti. All rights reserved.
import UIKit
let PolyMenuCellIdentifier = "PolyMenuCellIdentifier"
let PolyMenuHeaderIdentifier = "PolyMenuHeaderIdentifier"
let RefreshDisplayMessage = "Pull to Refresh"
let RefreshCommandDisplayValue = "refresh"
let SectionNameKey = "name"
let MenuItemKey = "items"
let MenuLocationKey = "locations"
enum PolyCampusIndex :Int {
case Albany = 0
case Utica = 1
}
typealias CampusMenuItem = (key: String, value: String)
typealias PolyCampusMenus = [[String : AnyObject]]
class PolyMenuController: UICollectionViewController {
var refreshControl: UIRefreshControl
var backgroundImage: UIImageView
var selectedCell: MenuItemCollectionViewCell?
required init(coder aDecoder: NSCoder) {
items = []
backgroundImage = UIImageView()
refreshControl = UIRefreshControl()
refreshControl.tintColor = Theme.highlightPrimary
super.init(coder: aDecoder)
}
var items: PolyCampusMenus
override func viewDidLoad() {
if let c = collectionView {
c.addSubview(refreshControl)
c.backgroundColor = Theme.backgroundPrimary.colorWithAlphaComponent(0.60)
c.alwaysBounceVertical = true
}
refreshControl.beginRefreshing()
refreshControl.addTarget(self, action: "requestData", forControlEvents: .ValueChanged)
requestData()
view.backgroundColor = Theme.backgroundPrimary
}
func loadMenu(menuItems: JSON, time: NSDate) {
if let campusMenu = menuItems as? PolyCampusMenus {
self.items = menuItems as! PolyCampusMenus
} else {
println(menuItems)
NetworkModel.invalidate("index.json")
return toast("Found invalidate data. Sorry!", duration: 5.0)
}
if menuItems.count == 0 {
refreshControl.endRefreshing()
NetworkModel.invalidate("index.json")
return toast("No data downloaded. Sorry!", duration: 5.0)
}
clearToast()
collectionView?.reloadData()
/* Format Last Refresh Date */
var f = NSDateFormatter()
f.doesRelativeDateFormatting = true
f.timeStyle = NSDateFormatterStyle.ShortStyle
refreshControl.attributedTitle = NSAttributedString(string: "Last updated \(f.stringFromDate(time))")
refreshControl.endRefreshing()
}
override func viewDidAppear(animated: Bool) {
UIView.animateWithDuration(0.175, animations: { () -> Void in
if let cell = self.selectedCell {
cell.unhighlight()
}
})
}
func failedMenuLoad(error: NSError, time: NSDate) {
clearToast()
items = [["name" : "Error Downloading…",
"items" : [RefreshDisplayMessage],
"locations" : [RefreshCommandDisplayValue]
]] as PolyCampusMenus
// TODO offer a way to re-try downloads without closing the app.
if let msg = error.localizedFailureReason {
items = [["name" : "Error Downloading…",
"items" : [RefreshDisplayMessage, msg],
"locations" : [RefreshCommandDisplayValue, RefreshCommandDisplayValue]
]] as PolyCampusMenus
}
collectionView?.reloadData()
println("Encountered error: \(error) at time \(time)")
NetworkModel.invalidate("index.json")
}
func requestData() {
refreshControl.beginRefreshing()
NetworkModel.sendRelativeRequest(self.loadMenu, appendage:"index.json", failure: self.failedMenuLoad)
}
func reload(regions: Array<Dictionary<String, AnyObject>>) {
collectionView?.reloadData()
}
func menuItem(path: NSIndexPath) -> String {
if let i = items[path.section][MenuItemKey] as? Array<String> {
return i[path.row]
} else {
return "Undetermined"
}
}
func menuValue(path: NSIndexPath) -> String {
if let i = items[path.section][MenuLocationKey] as? Array<String> {
return i[path.row]
} else {
return "Undetermined"
}
}
func itemTuple(path: NSIndexPath) -> CampusMenuItem {
if let i = items[path.section][MenuItemKey] as? Array<String> {
let item = i[path.row]
if let location = items[path.section][MenuLocationKey] as? Array<String> {
let value = location[path.row]
return CampusMenuItem(item, value)
}
}
return CampusMenuItem("Undetermined", "Undetermined")
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier(PolyMenuCellIdentifier, forIndexPath: indexPath) as! MenuItemCollectionViewCell
cell.prepareForReuse()
cell.textLabel?.textColor = Theme.textColor
let menu = menuItem(indexPath)
cell.textLabel?.text = menu
cell.selectedBackgroundView = UIView()
return cell
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let itemArray = items[section][MenuItemKey] as? Array<String> {
return itemArray.count
} else {
return 0
}
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
var header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: PolyMenuHeaderIdentifier, forIndexPath: indexPath) as! UICollectionReusableView
let section = indexPath.section
if header.subviews.count == 0 {
let labelFrame = CGRectInset(header.bounds, 10, 0)
let label = UILabel(frame: labelFrame)
label.font = UIFont.boldSystemFontOfSize(UIFont.systemFontSize() + 2)
header.addSubview(label)
header.bringSubviewToFront(label)
}
header.backgroundColor = Theme.subduedBackground
if let label = header.subviews[0] as? UILabel {
label.textColor = Theme.highlightPrimary
if let section = items[indexPath.section][SectionNameKey] as? String {
label.text = section
}
}
return header
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return items.count
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var indexPath: NSIndexPath
if let cell = sender as? MenuItemCollectionViewCell {
let indexPath = collectionView?.indexPathForCell(cell) as NSIndexPath!
let campusLookup = PolyCampusIndex(rawValue: indexPath.section)
let item = itemTuple(indexPath)
if let nav = segue.destinationViewController as? UINavigationController {
if let detail = nav.topViewController as? DetailWebController {
if let url = NSURL(string: item.value) {
detail.destination = url
detail.title = item.key
}
}
}
} else {
println("Could not set up segue with sender \(sender)")
return
}
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? MenuItemCollectionViewCell {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
selectedCell = cell.highlight()
} else {
cell.highlight()
UIView.animateWithDuration(0.3, delay: 0.4, options: .TransitionNone, animations: { () -> Void in
cell.unhighlight()
return
}, completion:
{ (complete: Bool) -> Void in
})
}
}
}
override func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? MenuItemCollectionViewCell {
cell.highlight()
}
}
override func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? MenuItemCollectionViewCell {
cell.unhighlight()
selectedCell = nil
}
}
/** Side-step segues for contact and club views. */
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
let menu = itemTuple(indexPath)
var campus: PolyCampusIndex
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? MenuItemCollectionViewCell {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
selectedCell = cell.highlight()
} else {
cell.highlight()
UIView.animateWithDuration(0.3, delay: 0.4, options: .TransitionNone, animations: { () -> Void in
cell.unhighlight()
return
}, completion:
{ (complete: Bool) -> Void in
})
}
}
if menu.value.lastPathComponent == "contact-index.json" {
let contacts = storyboard?.instantiateViewControllerWithIdentifier(ContactsControllerIdentifier) as! ContactsController
contacts.destination = menu.value
contacts.title = menu.key
let nav = UINavigationController(rootViewController: contacts)
showDetailViewController(nav, sender: self)
return false
} else if menu.value.lastPathComponent == "club-index.json" {
let clubs = storyboard?.instantiateViewControllerWithIdentifier(ClubsControllerIdentifier) as! ClubsController
clubs.destination = menu.value
clubs.title = menu.key
let nav = UINavigationController(rootViewController: clubs)
showDetailViewController(nav, sender: self)
return false
} else if menu.value == RefreshCommandDisplayValue {
requestData()
return false
} else {
return true
}
}
}
| mit |
modum-io/ios_client | PharmaSupplyChain/CodeScannerViewController.swift | 1 | 11313 | //
// QRScanner.swift
// PharmaSupplyChain
//
// Created by Yury Belevskiy on 27.11.16.
// Copyright © 2016 Modum. All rights reserved.
//
import AVFoundation
import UIKit
class CodeScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
// MARK: Properties
fileprivate var captureSession: AVCaptureSession?
fileprivate var videoPreviewLayer: AVCaptureVideoPreviewLayer?
fileprivate var isSensorMACDiscovered: Bool = false
fileprivate var sensorMACAddress: String?
fileprivate var isContractIDDiscovered: Bool = false
fileprivate var contractID: String?
/*
Determines which codes to scan based on this flag:
If set 'true', user has to only scan contract ID
If set 'false', user has to scan contract ID and QR code on the sensor
*/
var isReceivingParcel: Bool = false
// MARK: Outlets
@IBOutlet weak fileprivate var infoLabel: UILabel!
@IBOutlet weak fileprivate var typeOfCodeIcon: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
/* checking user permissions for the camera */
let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
switch authStatus {
case .authorized:
initialize()
case .denied, .restricted:
showCameraNotAvailableAlert()
case .notDetermined:
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: {
granted in
DispatchQueue.main.async {
[weak self] in
if let codeScannerViewController = self {
if granted {
codeScannerViewController.initialize()
} else {
codeScannerViewController.showCameraNotAvailableAlert()
}
}
}
})
}
}
// MARK: AVCaptureMetadataOutputObjectsDelegate
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
if !metadataObjects.isEmpty {
let metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
if metadataObject.type == AVMetadataObjectTypeQRCode, !isSensorMACDiscovered && !isReceivingParcel {
if metadataObject.stringValue != nil && !isSensorMACDiscovered {
if isValidMacAddress(metadataObject.stringValue) {
isSensorMACDiscovered = true
/* Separator symbols, ':', are removed from MAC address because advertised Bluetooth name of the sensor doesn't contain them */
sensorMACAddress = metadataObject.stringValue.removeNonHexSymbols()
if isContractIDDiscovered {
performSegue(withIdentifier: "goToParcelCreate", sender: self)
} else {
UIView.transition(with: infoLabel, duration: 1.0, options: [.curveEaseInOut, .transitionFlipFromRight], animations: {
[weak self] in
if let codeScannerController = self {
codeScannerController.infoLabel.text = "Please, scan Track&Trace number"
}
}, completion: nil)
UIView.transition(with: typeOfCodeIcon, duration: 1.0, options: [.curveEaseInOut, .transitionFlipFromRight], animations: {
[weak self] in
if let codeScannerController = self {
codeScannerController.typeOfCodeIcon.image = UIImage(named: "barcode")
}
}, completion: nil)
}
}
}
} else if metadataObject.type == AVMetadataObjectTypeCode128Code, !isContractIDDiscovered {
if metadataObject.stringValue != nil && !isContractIDDiscovered {
isContractIDDiscovered = true
contractID = metadataObject.stringValue
if isReceivingParcel {
performSegue(withIdentifier: "goToParcelReceive", sender: self)
} else {
if isSensorMACDiscovered {
performSegue(withIdentifier: "goToParcelCreate", sender: self)
} else {
UIView.transition(with: infoLabel, duration: 1.0, options: [.curveEaseInOut, .transitionFlipFromRight], animations: {
[weak self] in
if let codeScannerController = self {
codeScannerController.infoLabel.text = "Please, scan QR code on the sensor"
}
}, completion: nil)
UIView.transition(with: typeOfCodeIcon, duration: 1.0, options: [.curveEaseInOut, .transitionFlipFromRight], animations: {
[weak self] in
if let codeScannerController = self {
codeScannerController.typeOfCodeIcon.image = UIImage(named: "qr_code")
}
}, completion: nil)
}
}
}
}
}
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let parcelCreateViewController = segue.destination as? ParcelCreateViewController {
parcelCreateViewController.sensorMAC = sensorMACAddress
parcelCreateViewController.tntNumber = contractID
} else if let parcelReceiveViewController = segue.destination as? ParcelReceiveViewController {
parcelReceiveViewController.tntNumber = contractID
}
}
// MARK: Helper functions
fileprivate func initialize() {
/* instantiating video capture */
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
var captureInput: AVCaptureInput?
if let captureDevice = captureDevice {
do {
captureInput = try AVCaptureDeviceInput(device: captureDevice)
} catch {
log("Failed to instantiate AVCaptureInput with \(error.localizedDescription)")
return
}
/* adding video camera as input */
captureSession = AVCaptureSession()
if let captureSession = captureSession, let captureInput = captureInput {
captureSession.addInput(captureInput)
}
let captureMetadataOutput = AVCaptureMetadataOutput()
if let captureSession = captureSession {
captureSession.addOutput(captureMetadataOutput)
}
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode128Code]
/* initialize video preview layer */
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer?.frame = view.layer.bounds
view.layer.addSublayer(videoPreviewLayer!)
captureSession?.startRunning()
view.bringSubview(toFront: infoLabel)
}
/* UI configuration */
/* adding gradient backgroud */
let leftColor = TEMPERATURE_LIGHT_BLUE.cgColor
let middleColor = ROSE_COLOR.cgColor
let rightColor = LIGHT_BLUE_COLOR.cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = view.bounds
gradientLayer.colors = [leftColor, middleColor, rightColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
view.layer.insertSublayer(gradientLayer, at: 0)
/* adding transparent overlay */
let overlayPath = UIBezierPath(rect: view.bounds)
var transparentHole: UIBezierPath!
if getDeviceScreenSize() == .small {
transparentHole = UIBezierPath(rect: CGRect(x: 0, y: view.bounds.height/2.0 - 50.0, width: view.bounds.width, height: 200.0))
} else {
transparentHole = UIBezierPath(rect: CGRect(x: 0, y: view.bounds.height/2.0 - 100.0, width: view.bounds.width, height: 300.0))
}
overlayPath.append(transparentHole)
overlayPath.usesEvenOddFillRule = true
let fillLayer = CAShapeLayer()
fillLayer.path = overlayPath.cgPath
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = UIColor.black.withAlphaComponent(0.5).cgColor
view.layer.addSublayer(fillLayer)
view.bringSubview(toFront: infoLabel)
view.bringSubview(toFront: typeOfCodeIcon)
if isReceivingParcel {
infoLabel.text = "Please, scan Track&Trace number"
typeOfCodeIcon.image = UIImage(named: "barcode")
} else {
infoLabel.text = "Please, scan QR code on the sensor"
typeOfCodeIcon.image = UIImage(named: "qr_code")
}
}
fileprivate func showCameraNotAvailableAlert() {
let cameraNotAvailableAlertController = UIAlertController(title: "Camera isn't avaialable", message: "Please, set \"Camera\" to \"On\"", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
[weak self]
_ in
if let codeScannerViewController = self {
cameraNotAvailableAlertController.dismiss(animated: true, completion: nil)
_ = codeScannerViewController.navigationController?.popToRootViewController(animated: true)
}
})
let goToSettingsAction = UIAlertAction(title: "Settings", style: .default, handler: {
_ in
if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.open(settingsURL, completionHandler: nil)
}
})
cameraNotAvailableAlertController.addAction(goToSettingsAction)
cameraNotAvailableAlertController.addAction(cancelAction)
present(cameraNotAvailableAlertController, animated: true, completion: nil)
}
}
| apache-2.0 |
shvets/TVSetKit | Sources/Configuration.swift | 1 | 47 | public typealias Configuration = [String: Any]
| mit |
SandcastleApps/partyup | PartyUP/Advertisement.swift | 1 | 4333 | //
// Advertisement.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2016-01-12.
// Copyright © 2016 Sandcastle Application Development. All rights reserved.
//
import Foundation
import AWSDynamoDB
final class Advertisement: CustomDebugStringConvertible, Hashable
{
enum Style: Int {
case Page, Overlay
}
enum FeedCategory: String {
case All = "a", Venue = "v"
}
typealias FeedMask = [FeedCategory:NSRegularExpression]
let administration: String
let feeds: FeedMask
let pages: [Int]
let style: Style
let media: String
private let id: Character
init(administration: String, media: String, id: Character, feeds: FeedMask, pages: [Int], style: Style = .Page) {
self.administration = administration
self.feeds = feeds
self.pages = pages
self.style = style
self.media = media
self.id = id
Advertisement.ads.insert(self)
}
deinit {
Advertisement.ads.remove(self)
}
var debugDescription: String {
get { return "Administration = \(administration)\nFeeds = \(feeds)\nPages = \(pages)\nStyle = \(style)\nMedia = \(media)\n" }
}
func apropos(identifier: String, ofFeed feed: FeedCategory) -> Bool {
return feeds[feed]?.firstMatchInString(identifier, options: [.Anchored], range: NSRange(location: 0, length: identifier.utf16.count)) != nil
}
//MARK - Internal Dynamo Representation
internal convenience init(data: AdvertisementDB) {
var feeder = FeedMask(minimumCapacity: 3)
for filter in data.feeds {
if let category = FeedCategory(rawValue: filter[filter.startIndex..<filter.startIndex.advancedBy(1)]),
regex = try? NSRegularExpression(pattern: filter[filter.startIndex.advancedBy(2)..<filter.endIndex], options: []) {
feeder[category] = regex
}
}
self.init(
administration: data.administration,
media: data.media[data.media.startIndex.advancedBy(1)..<data.media.endIndex],
id: data.media.characters.first ?? "a",
feeds: feeder,
pages: Array<Int>(data.pages),
style: Style(rawValue: data.style) ?? .Page
)
}
internal var dynamo: AdvertisementDB {
get {
let db = AdvertisementDB()
db.administration = administration
db.feeds = Set<String>(feeds.map { $0.0.rawValue + ":" + $0.1.pattern })
db.pages = Set<Int>(pages)
db.style = style.rawValue
db.media = "\(id):\(media)"
return db
}
}
internal class AdvertisementDB: AWSDynamoDBObjectModel, AWSDynamoDBModeling
{
var administration: String!
var feeds: Set<String> = []
var pages: Set<Int> = []
var style: Int = 0
var media: String!
@objc static func dynamoDBTableName() -> String {
return "Advertisements"
}
@objc static func hashKeyAttribute() -> String {
return "administration"
}
@objc static func rangeKeyAttribute() -> String {
return "media"
}
}
var hashValue: Int {
return administration.hashValue ^ media.hashValue ^ id.hashValue
}
private static var ads = Set<Advertisement>()
static func apropos(identifier: String, ofFeed feed: FeedCategory) -> [Advertisement] {
return ads.filter { $0.apropos(identifier, ofFeed: feed) }
}
static func refresh(places: [Address]) {
ads.removeAll()
places.forEach { fetch($0) }
}
static func fetch(place: Address) {
let query = AWSDynamoDBQueryExpression()
let hash = String(format: "%@$%@", place.province, place.country)
query.keyConditionExpression = "#h = :hash"
query.expressionAttributeNames = ["#h": "administration"]
query.expressionAttributeValues = [":hash" : hash]
AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper().query(AdvertisementDB.self, expression: query).continueWithBlock { (task) in
if let result = task.result as? AWSDynamoDBPaginatedOutput {
if let items = result.items as? [AdvertisementDB] {
let wraps = items.map { Advertisement(data: $0) }
dispatch_async(dispatch_get_main_queue()) { Advertisement.ads.unionInPlace(wraps) }
}
}
return nil
}
}
}
func ==(lhs: Advertisement, rhs: Advertisement) -> Bool {
return lhs.administration == rhs.administration && lhs.id == rhs.id && lhs.media == rhs.media
}
| mit |
jverdi/Gramophone | Tests/LikesTests.swift | 1 | 6556 | //
// LikesTests.swift
// Gramophone
//
// Copyright (c) 2017 Jared Verdi. All Rights Reserved
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Quick
import Nimble
import OHHTTPStubs
import Result
@testable import Gramophone
class LikesSpec: QuickSpec {
override func spec() {
let mediaID = "1482048616133874767_989545"
let path = "/v1/media/\(mediaID)/likes"
describe("GET likes") {
if enableStubbing {
stub(condition: isHost(GramophoneTestsHost) && isPath(path) && isMethodGET()) { request in
return OHHTTPStubsResponse(
fileAtPath: OHPathForFile("likes.json", type(of: self))!,
statusCode: 200,
headers: GramophoneTestsHeaders
)
}
}
let scopes: [Scope] = [.publicContent]
it("requires the correct scopes") {
TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in
gramophone.client.likes(mediaID: mediaID) { completion($0) }
}
}
it("requires authentication") {
TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in
gramophone.client.likes(mediaID: mediaID) { completion($0) }
}
}
it("parses http successful response") {
TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in
gramophone.client.likes(mediaID: mediaID) { completion($0) }
}
}
it("parses into Like objects") {
TestingUtilities.testSuccessfulRequestWithDataConfirmation(httpCode: 200, scopes: scopes) { gramophone, completion in
gramophone.client.likes(mediaID: mediaID) {
completion($0) { likes in
expect(likes.items.count).to(equal(2))
expect(likes.items[0].ID).to(equal("24515474"))
expect(likes.items[0].username).to(equal("richkern"))
expect(likes.items[0].fullName).to(equal("Rich Kern"))
expect(likes.items[0].profilePictureURL).to(equal(URL(string:
"https://scontent.cdninstagram.com/t51.2885-19/11849395_467018326835121_804084785_a.jpg"
)!))
}
}
}
}
}
describe("POST like") {
if enableStubbing {
stub(condition: isHost(GramophoneTestsHost) && isPath(path) && isMethodPOST()) { request in
return OHHTTPStubsResponse(
fileAtPath: OHPathForFile("generic_success_response.json", type(of: self))!,
statusCode: 200,
headers: GramophoneTestsHeaders
)
}
}
let scopes: [Scope] = [.publicContent, .likes]
it("requires the correct scopes") {
TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in
gramophone.client.like(mediaID: mediaID) { completion($0) }
}
}
it("requires authentication") {
TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in
gramophone.client.like(mediaID: mediaID) { completion($0) }
}
}
it("parses http successful response") {
TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in
gramophone.client.like(mediaID: mediaID) { completion($0) }
}
}
}
describe("DELETE like") {
if enableStubbing {
stub(condition: isHost(GramophoneTestsHost) && isPath(path) && isMethodDELETE()) { request in
return OHHTTPStubsResponse(
fileAtPath: OHPathForFile("generic_success_response.json", type(of: self))!,
statusCode: 200,
headers: GramophoneTestsHeaders
)
}
}
let scopes: [Scope] = [.publicContent, .likes]
it("requires the correct scopes") {
TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in
gramophone.client.unlike(mediaID: mediaID) { completion($0) }
}
}
it("requires authentication") {
TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in
gramophone.client.unlike(mediaID: mediaID) { completion($0) }
}
}
it("parses http successful response") {
TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in
gramophone.client.unlike(mediaID: mediaID) { completion($0) }
}
}
}
}
}
| mit |
joelconnects/FlipTheBlinds | FlipTheBlinds/FromViewController.swift | 1 | 3035 | //
// FromViewController.swift
// FlipTheBlinds
//
// Created by Joel Bell on 1/2/17.
// Copyright © 2017 Joel Bell. All rights reserved.
//
import UIKit
// MARK: Main
class FromViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
configImageView()
configButton()
}
@objc func buttonTapped(_ sender: UIButton) {
let toViewController = ToViewController()
// POD: Set transitioningDelegate
toViewController.transitioningDelegate = self
self.present(toViewController, animated: true, completion: nil)
}
}
// MARK: Configure View
extension FromViewController {
private func configImageView() {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.image = #imageLiteral(resourceName: "treeGlobeImage")
view.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
imageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
private func configButton() {
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
let buttonSize: CGFloat = 60
let buttonYconstant: CGFloat = 50
let buttonXorigin = (screenWidth / 2) - (buttonSize / 2)
let buttonYorigin = screenHeight - buttonSize - buttonYconstant
let button = UIButton(type: .custom)
button.alpha = 0.7
button.backgroundColor = UIColor.black
button.setTitleColor(UIColor.white, for: UIControl.State())
button.setTitle("GO", for: UIControl.State())
button.frame = CGRect(x: buttonXorigin, y: buttonYorigin, width: buttonSize, height: buttonSize)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
view.addSubview(button)
}
}
// POD: Add Modal Extension
extension FromViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return FTBAnimationController(displayType: .present, direction: .up, speed: .moderate)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return FTBAnimationController(displayType: .dismiss, direction: .down, speed: .moderate)
}
}
| mit |
the-blue-alliance/the-blue-alliance-ios | Frameworks/TBAData/Tests/Event/EventRankingTests.swift | 1 | 22077 | import CoreData
import TBADataTesting
import TBAKit
import XCTest
@testable import TBAData
class EventRankingTestCase: TBADataTestCase {
func test_dq() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertNil(ranking.dq)
ranking.dqRaw = NSNumber(value: 1)
XCTAssertEqual(ranking.dq, 1)
}
func test_matchesPlayed() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertNil(ranking.matchesPlayed)
ranking.matchesPlayedRaw = NSNumber(value: 1)
XCTAssertEqual(ranking.matchesPlayed, 1)
}
func test_qualAverage() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertNil(ranking.qualAverage)
ranking.qualAverageRaw = NSNumber(value: 20.2)
XCTAssertEqual(ranking.qualAverage, 20.2)
}
func test_rank() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
ranking.rankRaw = NSNumber(value: 1)
XCTAssertEqual(ranking.rank, 1)
}
func test_record() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertNil(ranking.recordRaw)
let record = WLT(wins: 1, losses: 2, ties: 3)
ranking.recordRaw = record
XCTAssertEqual(ranking.record, record)
}
func test_event() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
let event = Event.init(entity: Event.entity(), insertInto: persistentContainer.viewContext)
ranking.eventRaw = event
XCTAssertEqual(ranking.event, event)
}
func test_extraStats() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertEqual(ranking.extraStats.array as! [EventRankingStat], [])
let stat = EventRankingStat.init(entity: EventRankingStat.entity(), insertInto: persistentContainer.viewContext)
ranking.extraStatsRaw = NSOrderedSet(array: [stat])
XCTAssertEqual(ranking.extraStats.array as! [EventRankingStat], [stat])
}
func test_extraStatsInfo() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertEqual(ranking.extraStatsInfo.array as! [EventRankingStatInfo], [])
let info = EventRankingStatInfo.init(entity: EventRankingStatInfo.entity(), insertInto: persistentContainer.viewContext)
ranking.extraStatsInfoRaw = NSOrderedSet(array: [info])
XCTAssertEqual(ranking.extraStatsInfo.array as! [EventRankingStatInfo], [info])
}
func test_qualStatus() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertNil(ranking.qualStatus)
let status = EventStatusQual.init(entity: EventStatusQual.entity(), insertInto: persistentContainer.viewContext)
ranking.qualStatusRaw = status
XCTAssertEqual(ranking.qualStatus, status)
}
func test_sortOrders() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertEqual(ranking.sortOrders.array as! [EventRankingStat], [])
let stat = EventRankingStat.init(entity: EventRankingStat.entity(), insertInto: persistentContainer.viewContext)
ranking.sortOrdersRaw = NSOrderedSet(array: [stat])
XCTAssertEqual(ranking.sortOrders.array as! [EventRankingStat], [stat])
}
func test_sortOrdersInfo() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertEqual(ranking.sortOrdersInfo.array as! [EventRankingStatInfo], [])
let info = EventRankingStatInfo.init(entity: EventRankingStatInfo.entity(), insertInto: persistentContainer.viewContext)
ranking.sortOrdersInfoRaw = NSOrderedSet(array: [info])
XCTAssertEqual(ranking.sortOrdersInfo.array as! [EventRankingStatInfo], [info])
}
func test_team() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
let team = Team.init(entity: Team.entity(), insertInto: persistentContainer.viewContext)
ranking.teamRaw = team
XCTAssertEqual(ranking.team, team)
}
func test_fetchRequest() {
let fr: NSFetchRequest<EventRanking> = EventRanking.fetchRequest()
XCTAssertEqual(fr.entityName, EventRanking.entityName)
}
func test_eventPredicate() {
let event = insertEvent()
let predicate = EventRanking.eventPredicate(eventKey: event.key)
XCTAssertEqual(predicate.predicateFormat, "eventRaw.keyRaw == \"2015qcmo\"")
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
ranking.eventRaw = event
_ = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
let results = EventRanking.fetch(in: persistentContainer.viewContext) { (fr) in
fr.predicate = predicate
}
XCTAssertEqual(results, [ranking])
}
func test_rankSortDescriptor() {
let sd = EventRanking.rankSortDescriptor()
XCTAssertEqual(sd.key, #keyPath(EventRanking.rankRaw))
XCTAssert(sd.ascending)
}
func test_insert() {
let event = insertDistrictEvent()
let extraStatsInfo = [TBAEventRankingSortOrder(name: "Total Ranking Points", precision: 0)]
let sortOrderInfo = [
TBAEventRankingSortOrder(name: "Ranking Score", precision: 2),
TBAEventRankingSortOrder(name: "First Ranking", precision: 0),
TBAEventRankingSortOrder(name: "Second Raking", precision: 0)
]
let model = TBAEventRanking(teamKey: "frc1", rank: 2, dq: 10, matchesPlayed: 6, qualAverage: 20, record: TBAWLT(wins: 1, losses: 2, ties: 3), extraStats: [25.0, 3], sortOrders: [2.08, 530.0, 3])
let ranking = EventRanking.insert(model, sortOrderInfo: sortOrderInfo, extraStatsInfo: extraStatsInfo, eventKey: event.key, in: persistentContainer.viewContext)
XCTAssertEqual(ranking.team.key, "frc1")
XCTAssertEqual(ranking.rank, 2)
XCTAssertEqual(ranking.dq, 10)
XCTAssertEqual(ranking.matchesPlayed, 6)
XCTAssertEqual(ranking.qualAverage, 20)
XCTAssertNotNil(ranking.record)
XCTAssertEqual(ranking.extraStatsInfoArray.map({ $0.name }), ["Total Ranking Points"])
XCTAssertEqual(ranking.extraStatsInfoArray.map({ $0.precision }), [0])
XCTAssertEqual(ranking.extraStatsArray.map({ $0.value }), [25.0, 3])
XCTAssertEqual(ranking.extraStatsArray.compactMap({ $0.extraStatsRanking }).count, 2)
XCTAssertEqual(ranking.extraStatsArray.compactMap({ $0.sortOrderRanking }).count, 0)
XCTAssertEqual(ranking.sortOrdersInfoArray.map({ $0.name }), ["Ranking Score", "First Ranking", "Second Raking"])
XCTAssertEqual(ranking.sortOrdersInfoArray.map({ $0.precision }), [2, 0, 0])
XCTAssertEqual(ranking.sortOrdersArray.map({ $0.value }), [2.08, 530.0, 3])
XCTAssertEqual(ranking.sortOrdersArray.compactMap({ $0.extraStatsRanking }).count, 0)
XCTAssertEqual(ranking.sortOrdersArray.compactMap({ $0.sortOrderRanking }).count, 3)
// Since we've setup a complicated extraStats/sortOrder, we'll test the string
XCTAssertEqual(ranking.rankingInfoString, "Total Ranking Points: 25, Ranking Score: 2.08, First Ranking: 530, Second Raking: 3")
// Should throw an error - must be attached to an Event
XCTAssertThrowsError(try persistentContainer.viewContext.save())
event.addToRankingsRaw(ranking)
XCTAssertNoThrow(try persistentContainer.viewContext.save())
}
func test_insertPredicate() {
let event = insertDistrictEvent()
let model = TBAEventRanking(teamKey: "frc1", rank: 2)
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
ranking.teamRaw = Team.insert("frc1", in: persistentContainer.viewContext)
// Test inserting a Ranking where EventRanking.qualStatus.eventStatus.event.key == eventKey
let qualStatus = EventStatusQual.init(entity: EventStatusQual.entity(), insertInto: persistentContainer.viewContext)
let eventStatus = EventStatus.init(entity: EventStatus.entity(), insertInto: persistentContainer.viewContext)
eventStatus.qualRaw = qualStatus
eventStatus.eventRaw = event
ranking.qualStatusRaw = qualStatus
let qualStatusRanking = EventRanking.insert(model, sortOrderInfo: nil, extraStatsInfo: nil, eventKey: event.key, in: persistentContainer.viewContext)
XCTAssertEqual(qualStatusRanking, ranking)
ranking.qualStatusRaw = nil
// Test inserting a Ranking where EventRanking.event.key == eventKey
ranking.eventRaw = event
let eventRanking = EventRanking.insert(model, sortOrderInfo: nil, extraStatsInfo: nil, eventKey: event.key, in: persistentContainer.viewContext)
XCTAssertEqual(eventRanking, ranking)
}
func test_update() {
let event = insertDistrictEvent()
let extraStatsInfo = [TBAEventRankingSortOrder(name: "Total Ranking Points", precision: 0)]
let sortOrderInfo = [
TBAEventRankingSortOrder(name: "Ranking Score", precision: 2),
TBAEventRankingSortOrder(name: "First Ranking", precision: 0),
TBAEventRankingSortOrder(name: "Second Raking", precision: 0)
]
let modelOne = TBAEventRanking(teamKey: "frc1", rank: 2, dq: 10, matchesPlayed: 6, qualAverage: 20, record: TBAWLT(wins: 1, losses: 2, ties: 3), extraStats: [25, 3.0], sortOrders: [2.08, 530.0, 2])
let rankingOne = EventRanking.insert(modelOne, sortOrderInfo: sortOrderInfo, extraStatsInfo: extraStatsInfo, eventKey: event.key, in: persistentContainer.viewContext)
event.addToRankingsRaw(rankingOne)
let modelTwo = TBAEventRanking(teamKey: "frc1", rank: 3, dq: 11, matchesPlayed: 7, qualAverage: 10, record: nil, extraStats: nil, sortOrders: nil)
let rankingTwo = EventRanking.insert(modelTwo, sortOrderInfo: nil, extraStatsInfo: nil, eventKey: event.key, in: persistentContainer.viewContext)
// Sanity check
XCTAssertEqual(rankingOne, rankingTwo)
// Make sure our values updated properly
XCTAssertEqual(rankingOne.rank, 3)
XCTAssertEqual(rankingOne.dq, 11)
XCTAssertEqual(rankingOne.matchesPlayed, 7)
XCTAssertEqual(rankingOne.qualAverage, 10)
XCTAssertNil(rankingOne.record)
XCTAssertEqual(rankingOne.sortOrdersArray.count, 0)
XCTAssertEqual(rankingOne.sortOrdersInfoArray.count, 0)
XCTAssertEqual(rankingOne.extraStatsArray.count, 0)
XCTAssertEqual(rankingOne.extraStatsInfoArray.count, 0)
XCTAssertNoThrow(try persistentContainer.viewContext.save())
}
func test_delete_orphan() {
let event = insertDistrictEvent()
let model = TBAEventRanking(teamKey: "frc1", rank: 2)
let qualStatusModel = TBAEventStatusQual(numTeams: nil, status: nil, ranking: nil, sortOrder: nil)
let ranking = EventRanking.insert(model, sortOrderInfo: nil, extraStatsInfo: nil, eventKey: event.key, in: persistentContainer.viewContext)
event.addToRankingsRaw(ranking)
let team = ranking.team
let qualStatus = EventStatusQual.insert(qualStatusModel, eventKey: event.key, teamKey: "frc1", in: persistentContainer.viewContext)
ranking.qualStatusRaw = qualStatus
// Should be able to delete
persistentContainer.viewContext.delete(ranking)
XCTAssertNoThrow(try persistentContainer.viewContext.save())
// Event and Team should not be deleted
XCTAssertNotNil(event.managedObjectContext)
XCTAssertNotNil(team.managedObjectContext)
// QualStatus is an orphan and should be deleted
XCTAssertNil(qualStatus.managedObjectContext)
}
func test_delete_orphan_statsInfo() {
let event = insertDistrictEvent()
let extraStatsInfoModel = [TBAEventRankingSortOrder(name: "Total Ranking Points", precision: 0)]
let sortOrderInfoModel = [
TBAEventRankingSortOrder(name: "Ranking Score", precision: 2),
TBAEventRankingSortOrder(name: "Total Ranking Points", precision: 0)
]
let model = TBAEventRanking(teamKey: "frc1", rank: 2, dq: 10, matchesPlayed: 6, qualAverage: 20, record: TBAWLT(wins: 1, losses: 2, ties: 3), extraStats: [25], sortOrders: [2.08])
let ranking = EventRanking.insert(model, sortOrderInfo: sortOrderInfoModel, extraStatsInfo: extraStatsInfoModel, eventKey: event.key, in: persistentContainer.viewContext)
event.addToRankingsRaw(ranking)
let extraStatsInfo = ranking.extraStatsInfoArray.first!
let firstSortOrderInfo = ranking.sortOrdersInfoArray.first(where: { $0.name == "Ranking Score" })!
let secondSortOrderInfo = ranking.sortOrdersInfoArray.first(where: { $0.name == "Total Ranking Points" })!
// Sanity check
XCTAssertEqual(secondSortOrderInfo.extraStatsRankings.count, 1)
XCTAssertEqual(secondSortOrderInfo.sortOrdersRankings.count, 1)
XCTAssertEqual(extraStatsInfo, secondSortOrderInfo)
// Connect a second ranking to the same extra stats - should not be deleted
let secondModel = TBAEventRanking(teamKey: "frc2", rank: 1, dq: 10, matchesPlayed: 6, qualAverage: 20, record: TBAWLT(wins: 1, losses: 2, ties: 3), extraStats: [25], sortOrders: nil)
let secondRanking = EventRanking.insert(secondModel, sortOrderInfo: nil, extraStatsInfo: extraStatsInfoModel, eventKey: event.key, in: persistentContainer.viewContext)
event.addToRankingsRaw(secondRanking)
// Sanity check
XCTAssertEqual(event.rankings.count, 2)
XCTAssertEqual(extraStatsInfo, secondSortOrderInfo)
XCTAssertEqual(extraStatsInfo.extraStatsRankings.count, 2)
XCTAssertEqual(extraStatsInfo.sortOrdersRankings.count, 1)
XCTAssertEqual(firstSortOrderInfo.extraStatsRankings.count, 0)
XCTAssertEqual(firstSortOrderInfo.sortOrdersRankings.count, 1)
// Should be able to delete
persistentContainer.viewContext.delete(ranking)
XCTAssertNoThrow(try persistentContainer.viewContext.save())
// extraStatsInfo and secondSortOrderInfo should not be deleted - both (same obj) connected to a different ranking
XCTAssertNotNil(extraStatsInfo.managedObjectContext)
XCTAssertNotNil(secondSortOrderInfo.managedObjectContext)
XCTAssertEqual(extraStatsInfo, secondSortOrderInfo)
XCTAssertEqual(extraStatsInfo.extraStatsRankings.count, 1)
XCTAssertEqual(extraStatsInfo.sortOrdersRankings.count, 0)
// firstSortOrderInfo is an orphan and should be deleted
XCTAssertNil(firstSortOrderInfo.managedObjectContext)
// Should be able to delete
persistentContainer.viewContext.delete(secondRanking)
XCTAssertNoThrow(try persistentContainer.viewContext.save())
// extraStatsInfo and secondSortOrderInfo are orphans and should be deleted
XCTAssertNil(extraStatsInfo.managedObjectContext)
XCTAssertNil(secondSortOrderInfo.managedObjectContext)
}
func test_delete_qualStatus() {
let event = insertDistrictEvent()
let model = TBAEventRanking(teamKey: "frc1", rank: 2)
let eventStatusModel = TBAEventStatus(teamKey: "frc1", eventKey: event.key)
let qualStatusModel = TBAEventStatusQual(numTeams: nil, status: nil, ranking: nil, sortOrder: nil)
let ranking = EventRanking.insert(model, sortOrderInfo: nil, extraStatsInfo: nil, eventKey: event.key, in: persistentContainer.viewContext)
event.addToRankingsRaw(ranking)
let eventStatus = EventStatus.insert(eventStatusModel, in: persistentContainer.viewContext)
let qualStatus = EventStatusQual.insert(qualStatusModel, eventKey: event.key, teamKey: "frc1", in: persistentContainer.viewContext)
eventStatus.qualRaw = qualStatus
eventStatus.eventRaw = event
ranking.qualStatusRaw = qualStatus
// Should be able to delete
persistentContainer.viewContext.delete(ranking)
XCTAssertNoThrow(try persistentContainer.viewContext.save())
// QualStatus should not be deleted, since it is not an orphan
XCTAssertNotNil(qualStatus.managedObjectContext)
}
func test_isOrphaned() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
// No Event or Status - should be orphaned
XCTAssert(ranking.isOrphaned)
let event = Event.init(entity: Event.entity(), insertInto: persistentContainer.viewContext)
event.addToRankingsRaw(ranking)
// Attached to an Event - should not be orphaned
XCTAssertFalse(ranking.isOrphaned)
event.removeFromRankingsRaw(ranking)
let status = EventStatusQual.init(entity: EventStatusQual.entity(), insertInto: persistentContainer.viewContext)
status.rankingRaw = ranking
// Attached to a Status - should not be orphaned
XCTAssertFalse(ranking.isOrphaned)
status.rankingRaw = nil
// Not attached to an Event or Status - should be orphaned
XCTAssert(ranking.isOrphaned)
}
func test_tiebreakerInfoString() {
let ranking = EventRanking.init(entity: EventRanking.entity(), insertInto: persistentContainer.viewContext)
XCTAssertNil(ranking.rankingInfoString)
let extraStats = [("Value 4", 0), ("Value 6", 1), ("Value 5", 3), ("Value Extra", 4)]
let extraStatsValues: [NSNumber] = [2, 3, 49.999]
let sortOrders = [("Value 1", 0), ("Value 2", 1), ("Value 3", 2)]
let sortOrderValues: [NSNumber] = [1.00, 2.2, 3.33, -1]
// Needs both keys and values
ranking.sortOrdersInfoRaw = NSOrderedSet(array: sortOrders.map {
let (name, precision) = $0
let info = EventRankingStatInfo(entity: EventRankingStatInfo.entity(), insertInto: persistentContainer.viewContext)
info.nameRaw = name
info.precisionRaw = NSNumber(value: precision)
return info
})
XCTAssertNil(ranking.rankingInfoString)
ranking.sortOrdersInfoRaw = nil
ranking.sortOrdersRaw = NSOrderedSet(array: sortOrderValues.map {
let stat = EventRankingStat(entity: EventRankingStat.entity(), insertInto: persistentContainer.viewContext)
stat.valueRaw = $0
return stat
})
XCTAssertNil(ranking.rankingInfoString)
ranking.sortOrdersRaw = nil
ranking.extraStatsInfoRaw = NSOrderedSet(array: extraStats.map {
let (name, precision) = $0
let info = EventRankingStatInfo(entity: EventRankingStatInfo.entity(), insertInto: persistentContainer.viewContext)
info.nameRaw = name
info.precisionRaw = NSNumber(value: precision)
return info
})
XCTAssertNil(ranking.rankingInfoString)
ranking.extraStatsInfoRaw = nil
ranking.extraStatsRaw = NSOrderedSet(array: extraStatsValues.map {
let stat = EventRankingStat(entity: EventRankingStat.entity(), insertInto: persistentContainer.viewContext)
stat.valueRaw = $0
return stat
})
XCTAssertNil(ranking.rankingInfoString)
// Only with extra stats
ranking.extraStatsInfoRaw = NSOrderedSet(array: extraStats.map {
let (name, precision) = $0
let info = EventRankingStatInfo(entity: EventRankingStatInfo.entity(), insertInto: persistentContainer.viewContext)
info.nameRaw = name
info.precisionRaw = NSNumber(value: precision)
return info
})
XCTAssertEqual(ranking.rankingInfoString, "Value 4: 2, Value 6: 3.0, Value 5: 49.999")
ranking.extraStatsRaw = nil
ranking.extraStatsInfoRaw = nil
// Only with tiebreaker info
ranking.sortOrdersInfoRaw = NSOrderedSet(array: sortOrders.map {
let (name, precision) = $0
let info = EventRankingStatInfo(entity: EventRankingStatInfo.entity(), insertInto: persistentContainer.viewContext)
info.nameRaw = name
info.precisionRaw = NSNumber(value: precision)
return info
})
ranking.sortOrdersRaw = NSOrderedSet(array: sortOrderValues.map {
let stat = EventRankingStat(entity: EventRankingStat.entity(), insertInto: persistentContainer.viewContext)
stat.valueRaw = $0
return stat
})
XCTAssertEqual(ranking.rankingInfoString, "Value 1: 1, Value 2: 2.2, Value 3: 3.33")
// Show with both
ranking.extraStatsInfoRaw = NSOrderedSet(array: extraStats.map {
let (name, precision) = $0
let info = EventRankingStatInfo(entity: EventRankingStatInfo.entity(), insertInto: persistentContainer.viewContext)
info.nameRaw = name
info.precisionRaw = NSNumber(value: precision)
return info
})
ranking.extraStatsRaw = NSOrderedSet(array: extraStatsValues.map {
let stat = EventRankingStat(entity: EventRankingStat.entity(), insertInto: persistentContainer.viewContext)
stat.valueRaw = $0
return stat
})
XCTAssertEqual(ranking.rankingInfoString, "Value 4: 2, Value 6: 3.0, Value 5: 49.999, Value 1: 1, Value 2: 2.2, Value 3: 3.33")
}
}
| mit |
jessesquires/swiftrsrc | swiftrsrc/Optional.swift | 2 | 627 | //
// Optional.swift
// swiftrsrc
//
// Created by Indragie on 1/28/15.
// Copyright (c) 2015 Indragie Karunaratne. All rights reserved.
//
extension Optional {
func chainMap<U>(f: T -> U?) -> U? {
if let current = self {
return f(current)
} else {
return nil
}
}
}
func mapSome<S: SequenceType, T>(source: S, transform: S.Generator.Element -> T?) -> [T] {
return reduce(source, []) { (var collection, element) in
if let x = transform(element) {
collection.append(x)
return collection
}
return collection
}
}
| mit |
itssofluffy/NanoMessage | Tests/NanoMessageTests/BusProtocolFamilyTests.swift | 1 | 4579 | /*
BusProtocolFamilyTests.swift
Copyright (c) 2016, 2017 Stephen Whittle All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
import XCTest
import Foundation
import NanoMessage
class BusProtocolFamilyTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testBus(address1: String, address2: String) {
guard let address1URL = URL(string: address1) else {
XCTAssert(false, "address1URL is invalid")
return
}
guard let address2URL = URL(string: address2) else {
XCTAssert(false, "address2URL is invalid")
return
}
var completed = false
do {
let node0 = try BusSocket(url: address1URL, type: .Bind)
let node1 = try BusSocket()
let node2 = try BusSocket(urls: [address1URL, address2URL], type: .Connect)
let _: Int = try node1.createEndPoint(url: address1URL, type: .Connect)
let _: Int = try node1.createEndPoint(url: address2URL, type: .Bind)
pauseForBind()
try node0.sendMessage(Message(value: "A"))
try node1.sendMessage(Message(value: "AB"))
try node2.sendMessage(Message(value: "ABC"))
let timeout = TimeInterval(seconds: 1)
for _ in 0 ... 1 {
let received = try node0.receiveMessage(timeout: timeout)
XCTAssertGreaterThanOrEqual(received.bytes, 0, "node0.received.bytes < 0")
let boolTest = (received.bytes == 2 || received.bytes == 3) ? true : false
XCTAssertEqual(boolTest, true, "node0.received.bytes != 2 && node0.received.bytes != 3")
}
for _ in 0 ... 1 {
let received = try node1.receiveMessage(timeout: timeout)
XCTAssertGreaterThanOrEqual(received.bytes, 0, "node1.received.bytes < 0")
let boolTest = (received.bytes == 1 || received.bytes == 3) ? true : false
XCTAssertEqual(boolTest, true, "node1.received.bytes != 2 && node1.received.bytes != 3")
}
for _ in 0 ... 1 {
let received = try node2.receiveMessage(timeout: timeout)
XCTAssertGreaterThanOrEqual(received.bytes, 0, "node2.received.bytes < 0")
let boolTest = (received.bytes == 1 || received.bytes == 2) ? true : false
XCTAssertEqual(boolTest, true, "node2.received.bytes != 2 && node2.received.bytes != 2")
}
completed = true
} catch let error as NanoMessageError {
XCTAssert(false, "\(error)")
} catch {
XCTAssert(false, "an unexpected error '\(error)' has occured in the library libNanoMessage.")
}
XCTAssert(completed, "test not completed")
}
func testInProcessBus() {
testBus(address1: "inproc:///tmp/bus_1.inproc", address2: "inproc:///tmp/bus_2.inproc")
}
func testInterProcessBus() {
testBus(address1: "ipc:///tmp/bus_1.ipc", address2: "ipc:///tmp/bus_2.ipc")
}
#if os(Linux)
static let allTests = [
("testInProcessBus", testInProcessBus),
("testInterProcessBus", testInterProcessBus)
]
#endif
}
| mit |
JockerLUO/ShiftLibra | ShiftLibra/ShiftLibra/Class/View/Option/View/SLCustomizeView.swift | 1 | 4521 | //
// SLCustomizeView.swift
// ShiftLibra
//
// Created by LUO on 2017/8/13.
// Copyright © 2017年 JockerLuo. All rights reserved.
//
import UIKit
import pop
class SLCustomizeView: UIView {
var closure : (()->())?
var currency : SLCurrency? {
didSet {
labInfo.text = "\(customExchange):\(currency?.code ?? "") → CNY"
labFrom.text = currency?.code ?? ""
textTo.text = String(format: "%.4f", currency?.exchange ?? 1.0)
}
}
@IBOutlet weak var labInfo: UILabel!
@IBOutlet weak var labFrom: UILabel!
@IBOutlet weak var labTo: UILabel!
@IBOutlet weak var textFrom: UITextField!
@IBOutlet weak var textTo: UITextField!
@IBOutlet weak var btnCancel: UIButton!
@IBOutlet weak var btnFinish: UIButton!
@IBAction func btnCancelClick(_ sender: Any) {
self.removeFromSuperview()
}
@IBAction func btnFinishClick(_ sender: Any) {
guard let toVulue = (textTo.text as NSString?)?.doubleValue else {
return
}
guard let fromVulue = (textFrom.text as NSString?)?.doubleValue else {
return
}
let customizeList = SLOptionViewModel().customizeList
var sql : String = "INSERT INTO T_Currency (name,code,query,exchange,name_English) VALUES('\(customCurrency)\(currency?.name! ?? "")','\(currency?.code! ?? "")★','customize',\(toVulue / fromVulue),'\(currency?.name_English ?? "")★')"
if (customizeList?.count)! > 0 {
for customizeCurrency in customizeList! {
if customizeCurrency.code! == ((currency?.code)! + "★") {
sql = "UPDATE T_Currency set exchange=\(toVulue / fromVulue) WHERE code='\(customizeCurrency)';"
}
}
}
SLSQLManager.shared.insertToSQL(sql: sql)
self.removeFromSuperview()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setupUI() -> () {
addSubview(bgView)
addSubview(settingView)
textTo.becomeFirstResponder()
btnCancel.setTitle(btnCancelText, for: .normal)
btnFinish.setTitle(btnFinishText, for: .normal)
anim()
}
fileprivate lazy var bgView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: SCREENH))
view.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
return view
}()
fileprivate lazy var settingView: UIView = {
let nib = UINib(nibName: "SLCustomizeView", bundle: nil)
let nibView = nib.instantiate(withOwner: self, options: [:]).first as! UIView
nibView.frame = CGRect(x: 0, y: -(homeHeaderHight + homeTableViewCellHight * 3), width: SCREENW, height: homeHeaderHight + homeTableViewCellHight * 3)
return nibView
}()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.first?.view == bgView {
removeFromSuperview()
}
}
}
extension SLCustomizeView {
@objc fileprivate func btnOtherClick() -> () {
closure?()
}
@objc fileprivate func btnCancelClick() -> () {
self.removeFromSuperview()
}
}
extension SLCustomizeView : POPAnimationDelegate{
fileprivate func anim() -> () {
let settingAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
settingAnimation?.toValue = CGPoint(x: settingView.center.x, y: homeHeaderHight + settingView.bounds.height * 0.5)
settingAnimation?.beginTime = CACurrentMediaTime()
settingAnimation?.springBounciness = 0
settingView.pop_add(settingAnimation, forKey: nil)
settingAnimation?.delegate = self
}
func pop_animationDidStop(_ anim: POPAnimation!, finished: Bool) {
}
}
| mit |
wyp767363905/GiftSay | GiftSay/GiftSay/classes/profile/setUp/view/SetCell.swift | 1 | 892 | //
// SetCell.swift
// GiftSay
//
// Created by qianfeng on 16/9/1.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class SetCell: UITableViewCell {
@IBOutlet weak var bgImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
func configModel(model: RecommendAppsModel){
let url = NSURL(string: model.icon_url!)
bgImageView.kf_setImageWithURL(url)
titleLabel.text = (model.title)!
descLabel.text = (model.subtitle)!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
wangyun-hero/sinaweibo-with-swift | sinaweibo/Classes/View/Compose/View/Emoticon/WYEmoticonToolBar.swift | 1 | 3306 | //
// WYEmoticonToolBar.swift
// sinaweibo
//
// Created by 王云 on 16/9/10.
// Copyright © 2016年 王云. All rights reserved.
//
import UIKit
/// 表情的类型
///
/// - RECENT: 最近
/// - DEFAULT: 默认
/// - EMOJI: emoji
/// - LXH: 浪小花
enum HMEmotionType: Int {
case RECENT = 0, DEFAULT, EMOJI, LXH
}
class WYEmoticonToolBar: UIView {
var currentSelectedButton: UIButton?
/// 表情类型切换按钮点击的时候执行的闭包
var emotionTypeChangedClosure: ((HMEmotionType)->())?
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
self.addSubview(stackView)
stackView.snp_makeConstraints { (make ) in
make.edges.equalTo(self)
}
//添加4个按钮
addChildBtns(imageName: "compose_emotion_table_left", title: "最近",type: .RECENT)
addChildBtns(imageName: "compose_emotion_table_mid", title: "默认",type:.DEFAULT)
addChildBtns(imageName: "compose_emotion_table_mid", title: "Emoji",type:.EMOJI)
addChildBtns(imageName: "compose_emotion_table_right", title: "浪小花",type:.LXH)
}
//添加按钮的方法
private func addChildBtns (imageName:String , title:String ,type:HMEmotionType) {
//初始化button
let button = UIButton()
//设置tag
button.tag = type.rawValue
//监听按钮的点击
button.addTarget(self, action: #selector(childButtonClick(btn:)), for: .touchUpInside)
//设置标题
button.setTitle(title, for: .normal)
//设置字体颜色
button.setTitleColor(UIColor.white, for: .normal)
button.setTitleColor(UIColor.gray, for: .selected)
//设置背景图片
button.setBackgroundImage(UIImage(named: "\(imageName)_normal"), for: UIControlState.normal)
button.setBackgroundImage(UIImage(named: "\(imageName)_selected"), for: UIControlState.selected)
stackView.addArrangedSubview(button)
}
// MARK: - 监听事件
@objc private func childButtonClick(btn: UIButton) {
// 判断当前点击的按钮与选中的按钮是同一个按钮的话,就不执行后面的代码
if currentSelectedButton == btn {
return
}
// 1. 让之前选中的按钮取消选中
currentSelectedButton?.isSelected = false
// 2. 让当前点击的按钮选中
btn.isSelected = true
// 3. 将当前选中的的按钮记录起来,记录起来原因是下次在点击其他按钮的时候,要取消当前按钮
currentSelectedButton = btn
// 4. 在这个地方通知外界去滚动collectionView
// 也就是说需要在此执行一个闭包
emotionTypeChangedClosure?(HMEmotionType(rawValue: btn.tag)!)
}
//MARK: - 懒加载控件
private lazy var stackView :UIStackView = {
let stackView = UIStackView()
//设置布局方向
stackView.distribution = .fillEqually
return stackView
}()
}
| mit |
soapyigu/LeetCode_Swift | DP/DifferentWaysAddParentheses.swift | 1 | 1559 | /**
* Question Link: https://leetcode.com/problems/different-ways-to-add-parentheses/
* Primary idea: Divide and Conquer, calculate left and right separately and union results
*
* Note: Keep a memo dictionary to avoid duplicate calculations
* Time Complexity: O(n^n), Space Complexity: O(n)
*
*/
class DifferentWaysAddParentheses {
var memo = [String: [Int]]()
func diffWaysToCompute(_ input: String) -> [Int] {
if let nums = memo[input] {
return nums
}
var res = [Int]()
let chars = Array(input.characters)
for (i, char) in chars.enumerated() {
if char == "+" || char == "*" || char == "-" {
let leftResults = diffWaysToCompute(String(chars[0..<i]))
let rightResults = diffWaysToCompute(String(chars[i + 1..<chars.count]))
for leftRes in leftResults {
for rightRes in rightResults {
if char == "+" {
res.append(leftRes + rightRes)
}
if char == "-" {
res.append(leftRes - rightRes)
}
if char == "*" {
res.append(leftRes * rightRes)
}
}
}
}
}
if res.count == 0 {
res.append(Int(input)!)
}
memo[input] = res
return res
}
} | mit |
HTWDD/HTWDresden-iOS | HTWDD/Components/Onboarding/Main/OnboardingMainViewController.swift | 1 | 716 | //
// OnboardingMainViewController.swift
// HTWDD
//
// Created by Mustafa Karademir on 05.08.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import UIKit
class OnboardingMainViewController: UIViewController {
// MARK: - Properties
weak var context: AppContext?
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let destinationViewController = segue.destination as? OnboardingPageViewController {
destinationViewController.context = context
}
}
}
| gpl-2.0 |
UncleJerry/Dailylife-with-a-fish | Fishing Days/RadioBox.swift | 1 | 1615 | //
// RadioBox.swift
// Fishing Days
//
// Created by 周建明 on 2017/4/1.
// Copyright © 2017年 Uncle Jerry. All rights reserved.
//
import UIKit
class RadioBox: FunctionButton {
var selectedButton: UIImage?
var selectedBG: UIImage = UIImage(named: "ButtonBG")!
var unSelecteButton: UIImage?
var image: String?
var doesSelected: Bool = false {
willSet{
// load the image name info if haven't loaded
guard image != nil else {
if self.currentImage?.size.width == CGFloat(22) {
image = "Female"
}else{
image = "Male"
}
return
}
}
didSet{
if doesSelected {
self.setImage(selectedButton ?? UIImage(named: image! + "S"), for: .normal)
self.setBackgroundImage(selectedBG, for: .normal)
// load the image if haven't loaded
guard selectedButton != nil else {
selectedButton = UIImage(named: image! + "S")
return
}
}else{
self.setImage(unSelecteButton ?? UIImage(named: image!), for: .normal)
self.setBackgroundImage(nil, for: .normal)
// load the image if haven't loaded
guard unSelecteButton != nil else {
unSelecteButton = UIImage(named: image!)
return
}
}
}
}
}
| mit |
nyin005/Forecast-App | Forecast/Forecast/HttpRequest/ViewModel/ReportViewModel.swift | 1 | 4494 | //
// ReportViewModel.swift
// Forecast
//
// Created by Perry Z Chen on 10/21/16.
// Copyright © 2016 Perry Z Chen. All rights reserved.
//
/**
TODO:
1. create a common request can receive a string value and returns the pie chart data or line chart data
*/
import Foundation
class ReportViewModel: BaseViewModel {
var results: String?
var losListModel: ReportLosModel?
var pieChartListModel: PieChartDataListModel? // 饼图数据
var lineChartRootModel: LineChartDataRootModel? // 线形图数据
var availableModel: AvailableModel?
}
extension ReportViewModel {
// get los report chart
func getLosReport(_ url: String,parameters: [String: AnyObject], success: @escaping ()->Void, failure:@escaping (_ str: String) -> Void) {
// let URL = HttpMacro.getRequestURL(.ReportLOS)
self.requestData(url: url, parameters: parameters, methods: .get) { (res: HttpResponseResult) in
if res.success {
self.results = res.resultString
let listModel = ReportLosModel(JSONString: res.resultString)! as ReportLosModel
if listModel.responseData != nil {
for model in listModel.responseData! {
model.LosValues?.sort(by: { (pre, after) -> Bool in
pre.label!.compare(after.label!) == .orderedAscending
})
}
self.losListModel = listModel
success()
} else {
failure((listModel.responseMsg)!)
}
} else {
failure(res.resultString)
}
}
}
// 获取饼图数据
func getPieChartReport(_ url: String, parameters: [String: AnyObject], success: @escaping ()->Void, failure:@escaping (_ str:String ) -> Void) -> Void {
// let URL = HttpMacro.Original.combineString(str: url)
self.requestData(url: url, parameters: parameters, methods: .get) { (res: HttpResponseResult) in
if res.success {
self.results = res.resultString
let listModel = PieChartDataListModel(JSONString: res.resultString)
if listModel?.responseData != nil {
self.pieChartListModel = listModel
success()
} else {
failure((listModel?.responseMsg)!)
}
} else {
failure(res.resultString)
}
}
}
// 获取线图数据
func getLineChartReport(_ url: String, parameters: [String: AnyObject], success: @escaping ()->Void, failure:@escaping (_ str:String ) -> Void) -> Void {
// let URL = HttpMacro.Original.combineString(str: url)
self.requestData(url: url, parameters: parameters, methods: .get) { (res: HttpResponseResult) in
if res.success {
self.results = res.resultString
let utListModel = LineChartDataRootModel(JSONString: res.resultString)
if utListModel?.responseData != nil {
self.lineChartRootModel = utListModel
success()
} else {
failure((utListModel?.responseMsg)!)
}
} else {
failure(res.resultString)
}
}
}
func getAvailableReport(_ url: String, parameters: [String: AnyObject], success: @escaping ()->Void, failure:@escaping (_ str:String ) -> Void) -> Void {
// let URL = HttpMacro.Original.combineString(str: url)
self.requestData(url: url, parameters: parameters, methods: .get) { (res: HttpResponseResult) in
if res.success {
self.results = res.resultString
let utListModel = AvailableModel(JSONString: res.resultString)
if utListModel?.data != nil {
self.availableModel = utListModel
success()
} else {
failure((utListModel?.msg)!)
}
} else {
failure(res.resultString)
}
}
}
func cancel() {
self.cancelRequest()
}
}
| gpl-3.0 |
ustwo/formvalidator-swift | Sources/Conditions/Logic/AndCondition.swift | 1 | 880 | //
// AndCondition.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 13/01/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
/**
* A condition that returns the result of either operands.
*/
public struct AndCondition: Condition {
// MARK: - Properties
public var localizedViolationString = ""
public let regex = ""
public var shouldAllowViolation = true
public let conditions: [Condition]
// MARK: - Initializers
public init() {
self.init(conditions: [AlphanumericCondition()])
}
public init(conditions: [Condition]) {
self.conditions = conditions
}
// MARK: - Check
public func check(_ text: String?) -> Bool {
return conditions.reduce(true, { $0 && $1.check(text) })
}
}
| mit |
Deliany/yaroslav_skorokhid_SimplePins | yaroslav_skorokhid_SimplePins/Pin+CoreDataProperties.swift | 1 | 548 | //
// Pin+CoreDataProperties.swift
// yaroslav_skorokhid_SimplePins
//
// Created by Yaroslav Skorokhid on 10/17/16.
// Copyright © 2016 CollateralBeauty. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension Pin {
@NSManaged var title: String
@NSManaged var formattedAddress: String
@NSManaged var latitude: Double
@NSManaged var longitude: Double
}
| mit |
sjchmiela/call-of-beacons | ios/CallOfBeacons/CallOfBeacons/COBBeacon.swift | 1 | 3606 | //
// COBBeacon.swift
// CallOfBeacons
//
// Created by Stanisław Chmiela on 02.06.2016.
// Copyright © 2016 Stanisław Chmiela, Rafał Żelazko. All rights reserved.
//
import Foundation
/// Beacon model with all the information we need
class COBBeacon: Equatable, CustomStringConvertible, Hashable, Comparable {
/// Major of the beacon
var major: Int?
/// Minor of the beacon
var minor: Int?
/// Name of the beacon (customizable in configuration.json)
var name: String?
/// Behavior of the beacon (based on which we'll decide how to handle it's proximity)
var behaviorName: String?
/// Proximity of the beacon to the gamer
var proximity: CLProximity?
/// Color of the beacon
var color: String?
/// toString of the beacon object
var description: String {
return "Beacon \(name ?? "")\n\t\(proximity?.description ?? "unknown") to \(behaviorName ?? "unknown")"
}
/// Behavior of the beacon
var behavior: COBBeaconBehavior.Type? {
if let behaviorName = behaviorName, let behaviorType = COBBeacon.behaviors[behaviorName] {
return behaviorType
} else {
return nil
}
}
var shouldPulse: Bool {
return behaviorName == "flag"
}
/// Initialize out of JSON
init(jsonData: JSON) {
self.major = jsonData["major"].int
self.minor = jsonData["minor"].int
self.behaviorName = jsonData["behavior"].string
self.name = jsonData["name"].string
self.color = jsonData["color"].string
}
/// Initialize out of a beacon of another type. Merges the beacon with any known beacon found.
init(beacon: CLBeacon) {
self.major = beacon.major.integerValue
self.minor = beacon.minor.integerValue
self.proximity = beacon.proximity
if let knownBeacon = COBBeacon.beaconWith(beacon.major.integerValue, minor: beacon.minor.integerValue) {
self.name = knownBeacon.name
self.behaviorName = knownBeacon.behaviorName
self.color = knownBeacon.color
}
}
var hashValue: Int {
return 65535 * major! + minor!
}
}
extension COBBeacon {
/// All the known behaviorNames and their behaviors
static let behaviors: [String: COBBeaconBehavior.Type] = {
return [
"flag": COBFlagBehavior.self,
"healthPoint": COBHealthPointBehavior.self
]
}()
/// All the known beacons
static var knownBeacons: [COBBeacon] {
return COBConfiguration.beacons.sort()
}
/// Find one beacon with these major and minor out of all the known beacons
static func beaconWith(major: Int, minor: Int) -> COBBeacon? {
if let index = knownBeacons.indexOf({$0.major == major && $0.minor == minor}) {
return knownBeacons[index]
}
return nil
}
/// Turn array of beacons to parameters sendable through HTTP request
static func beaconsToParameters(beacons: [COBBeacon]) -> [AnyObject] {
return beacons.map({ (beacon) -> AnyObject in
return [
"major": beacon.major!,
"minor": beacon.minor!,
"proximity": beacon.proximity?.rawValue ?? 0
]
})
}
}
/// Comparison implementation
func ==(lhs: COBBeacon, rhs: COBBeacon) -> Bool {
return lhs.major == rhs.major && lhs.minor == rhs.minor
}
func <(lhs: COBBeacon, rhs: COBBeacon) -> Bool {
return lhs.major == rhs.major ? lhs.minor < rhs.minor : lhs.major < rhs.major
} | mit |
kstaring/swift | test/DebugInfo/thunks.swift | 8 | 897 | // RUN: %target-swift-frontend -emit-ir -g %s -o - | %FileCheck %s
// RUN: %target-swift-frontend -emit-sil -emit-verbose-sil -g %s -o - | %FileCheck %s --check-prefix=SIL-CHECK
// REQUIRES: objc_interop
import Foundation
class Foo : NSObject {
dynamic func foo(_ f: (Int64) -> Int64, x: Int64) -> Int64 {
return f(x)
}
}
let foo = Foo()
let y = 3 as Int64
let i = foo.foo(-, x: y)
// CHECK: define {{.*}}@_TTRXFdCb_dVs5Int64_dS__XFo_dS__dS__
// CHECK-NOT: ret
// CHECK: call {{.*}}, !dbg ![[LOC:.*]]
// CHECK: ![[THUNK:.*]] = distinct !DISubprogram(linkageName: "_TTRXFdCb_dVs5Int64_dS__XFo_dS__dS__"
// CHECK-NOT: line:
// CHECK-SAME: ){{$}}
// CHECK: ![[LOC]] = !DILocation(line: 0, scope: ![[THUNK]])
// SIL-CHECK: sil shared {{.*}}@_TTRXFdCb_dVs5Int64_dS__XFo_dS__dS__
// SIL-CHECK-NOT: return
// SIL-CHECK: apply {{.*}}auto_gen
| apache-2.0 |
natecook1000/swift | stdlib/public/SDK/Foundation/NSCoder.swift | 2 | 8669 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
//===----------------------------------------------------------------------===//
// NSCoder
//===----------------------------------------------------------------------===//
@available(macOS 10.11, iOS 9.0, *)
internal func resolveError(_ error: NSError?) throws {
if let error = error, error.code != NSCoderValueNotFoundError {
throw error
}
}
extension NSCoder {
@available(*, unavailable, renamed: "decodeObject(of:forKey:)")
public func decodeObjectOfClass<DecodedObjectType>(
_ cls: DecodedObjectType.Type, forKey key: String
) -> DecodedObjectType?
where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
fatalError("This API has been renamed")
}
public func decodeObject<DecodedObjectType>(
of cls: DecodedObjectType.Type, forKey key: String
) -> DecodedObjectType?
where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
let result = __NSCoderDecodeObjectOfClassForKey(self, cls, key, nil)
return result as? DecodedObjectType
}
@available(*, unavailable, renamed: "decodeObject(of:forKey:)")
@nonobjc
public func decodeObjectOfClasses(_ classes: NSSet?, forKey key: String) -> AnyObject? {
fatalError("This API has been renamed")
}
@nonobjc
public func decodeObject(of classes: [AnyClass]?, forKey key: String) -> Any? {
var classesAsNSObjects: NSSet?
if let theClasses = classes {
classesAsNSObjects = NSSet(array: theClasses.map { $0 as AnyObject })
}
return __NSCoderDecodeObjectOfClassesForKey(self, classesAsNSObjects, key, nil).map { $0 as Any }
}
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject() throws -> Any? {
var error: NSError?
let result = __NSCoderDecodeObject(self, &error)
try resolveError(error)
return result.map { $0 as Any }
}
@available(*, unavailable, renamed: "decodeTopLevelObject(forKey:)")
public func decodeTopLevelObjectForKey(_ key: String) throws -> AnyObject? {
fatalError("This API has been renamed")
}
@nonobjc
@available(swift, obsoleted: 4)
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject(forKey key: String) throws -> AnyObject? {
var error: NSError?
let result = __NSCoderDecodeObjectForKey(self, key, &error)
try resolveError(error)
return result as AnyObject?
}
@nonobjc
@available(swift, introduced: 4)
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject(forKey key: String) throws -> Any? {
var error: NSError?
let result = __NSCoderDecodeObjectForKey(self, key, &error)
try resolveError(error)
return result
}
@available(*, unavailable, renamed: "decodeTopLevelObject(of:forKey:)")
public func decodeTopLevelObjectOfClass<DecodedObjectType>(
_ cls: DecodedObjectType.Type, forKey key: String
) throws -> DecodedObjectType?
where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
fatalError("This API has been renamed")
}
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject<DecodedObjectType>(
of cls: DecodedObjectType.Type, forKey key: String
) throws -> DecodedObjectType?
where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
var error: NSError?
let result = __NSCoderDecodeObjectOfClassForKey(self, cls, key, &error)
try resolveError(error)
return result as? DecodedObjectType
}
@nonobjc
@available(*, unavailable, renamed: "decodeTopLevelObject(of:forKey:)")
public func decodeTopLevelObjectOfClasses(_ classes: NSSet?, forKey key: String) throws -> AnyObject? {
fatalError("This API has been renamed")
}
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelObject(of classes: [AnyClass]?, forKey key: String) throws -> Any? {
var error: NSError?
var classesAsNSObjects: NSSet?
if let theClasses = classes {
classesAsNSObjects = NSSet(array: theClasses.map { $0 as AnyObject })
}
let result = __NSCoderDecodeObjectOfClassesForKey(self, classesAsNSObjects, key, &error)
try resolveError(error)
return result.map { $0 as Any }
}
}
//===----------------------------------------------------------------------===//
// NSKeyedArchiver
//===----------------------------------------------------------------------===//
extension NSKeyedArchiver {
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func encodeEncodable<T : Encodable>(_ value: T, forKey key: String) throws {
let plistEncoder = PropertyListEncoder()
let plist = try plistEncoder.encodeToTopLevelContainer(value)
self.encode(plist, forKey: key)
}
}
//===----------------------------------------------------------------------===//
// NSKeyedUnarchiver
//===----------------------------------------------------------------------===//
extension NSKeyedUnarchiver {
@nonobjc
@available(swift, obsoleted: 4)
@available(macOS 10.11, iOS 9.0, *)
public class func unarchiveTopLevelObjectWithData(_ data: NSData) throws -> AnyObject? {
var error: NSError?
let result = __NSKeyedUnarchiverUnarchiveObject(self, data, &error)
try resolveError(error)
return result as AnyObject?
}
@nonobjc
@available(swift, introduced: 4)
@available(macOS 10.11, iOS 9.0, *)
public class func unarchiveTopLevelObjectWithData(_ data: Data) throws -> Any? {
var error: NSError?
let result = __NSKeyedUnarchiverUnarchiveObject(self, data as NSData, &error)
try resolveError(error)
return result
}
@nonobjc
@available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
public static func unarchivedObject<DecodedObjectType>(ofClass cls: DecodedObjectType.Type, from data: Data) throws -> DecodedObjectType? where DecodedObjectType : NSCoding, DecodedObjectType : NSObject {
var error: NSError?
let result = __NSKeyedUnarchiverSecureUnarchiveObjectOfClass(cls as AnyClass, data, &error)
if let error = error { throw error }
return result as? DecodedObjectType
}
@nonobjc
@available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
public static func unarchivedObject(ofClasses classes: [AnyClass], from data: Data) throws -> Any? {
var error: NSError?
let classesAsNSObjects = NSSet(array: classes.map { $0 as AnyObject })
let result = __NSKeyedUnarchiverSecureUnarchiveObjectOfClasses(classesAsNSObjects, data, &error)
if let error = error { throw error }
return result
}
@nonobjc
private static let __plistClasses: [AnyClass] = [
NSArray.self,
NSData.self,
NSDate.self,
NSDictionary.self,
NSNumber.self,
NSString.self
]
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func decodeDecodable<T : Decodable>(_ type: T.Type, forKey key: String) -> T? {
guard let value = self.decodeObject(of: NSKeyedUnarchiver.__plistClasses, forKey: key) else {
return nil
}
let plistDecoder = PropertyListDecoder()
do {
return try plistDecoder.decode(T.self, fromTopLevel: value)
} catch {
self.failWithError(error)
return nil
}
}
@nonobjc
@available(macOS 10.11, iOS 9.0, *)
public func decodeTopLevelDecodable<T : Decodable>(_ type: T.Type, forKey key: String) throws -> T? {
guard let value = try self.decodeTopLevelObject(of: NSKeyedUnarchiver.__plistClasses, forKey: key) else {
return nil
}
let plistDecoder = PropertyListDecoder()
do {
return try plistDecoder.decode(T.self, fromTopLevel: value)
} catch {
self.failWithError(error)
throw error;
}
}
}
@available(*, deprecated, renamed:"NSCoding", message: "Please use NSCoding")
typealias Coding = NSCoding
@available(*, deprecated, renamed:"NSCoder", message: "Please use NSCoder")
typealias Coder = NSCoder
@available(*, deprecated, renamed:"NSKeyedUnarchiver", message: "Please use NSKeyedUnarchiver")
typealias KeyedUnarchiver = NSKeyedUnarchiver
@available(*, deprecated, renamed:"NSKeyedArchiver", message: "Please use NSKeyedArchiver")
typealias KeyedArchiver = NSKeyedArchiver
| apache-2.0 |
BellAppLab/Backgroundable | Sources/Backgroundable/Backgroundable+Functions.swift | 1 | 1969 | /*
Copyright (c) 2018 Bell App Lab <apps@bellapplab.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
//MARK: - Functions
/**
The easiest way to execute code in the background.
- parameters:
- closure: The closure to be executed in the background.
*/
public func inTheBackground(_ closure: @escaping () -> Swift.Void)
{
OperationQueue.background.addOperation(closure)
}
/**
The easiest way to excute code on the main thread.
- parameters:
- closure: The closure to be executed on the main thread.
*/
public func onTheMainThread(_ closure: @escaping () -> Swift.Void)
{
OperationQueue.main.addOperation(closure)
}
/**
The easiest way to excute code in the global background queue.
- parameters:
- closure: The closure to be executed in the global background queue.
*/
public func inTheGlobalQueue(_ closure: @escaping () -> Swift.Void)
{
DispatchQueue.global(qos: .background).async(execute: closure)
}
| mit |
russelhampton05/MenMew | App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/MessagePopupViewController.swift | 1 | 5283 | //
// MessagePopupViewController.swift
// App_Prototype_Alpha_001
//
// Created by Jon Calanio on 11/12/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import UIKit
class MessagePopupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//IBOutlets
@IBOutlet var requestLabel: UILabel!
@IBOutlet var messageTableView: UITableView!
@IBOutlet var confirmButton: UIButton!
@IBOutlet var cancelButton: UIButton!
@IBOutlet var popupView: UIView!
//Variables
var messages: [String] = []
var selectedMessage: String?
var didCancel: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
self.showAnimate()
loadMessages()
messageTableView.delegate = self
messageTableView.dataSource = self
loadTheme()
}
@IBAction func confirmButtonPressed(_ sender: Any) {
removeAnimate()
}
@IBAction func cancelButtonPressed(_ sender: Any) {
didCancel = true
removeAnimate()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell") as UITableViewCell!
cell?.textLabel!.text = messages[indexPath.row]
cell?.backgroundColor = currentTheme!.primary!
cell?.textLabel!.textColor = currentTheme!.highlight!
let bgView = UIView()
bgView.backgroundColor = currentTheme!.highlight!
cell?.selectedBackgroundView = bgView
cell?.textLabel?.highlightedTextColor = currentTheme!.primary!
cell?.detailTextLabel?.highlightedTextColor = currentTheme!.primary!
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedMessage = messages[indexPath.row]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Popup view animation
func showAnimate() {
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
UIView.animate(withDuration: 0.25, animations: {
self.view.alpha = 1.0
self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
}
//Popup remove animation
func removeAnimate() {
UIView.animate(withDuration: 0.25, animations: {
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
}, completion:{(finished : Bool) in
if (finished)
{
if !self.didCancel {
self.processMessage()
}
self.view.removeFromSuperview()
}
})
}
func processMessage() {
if let parent = self.parent as? OrderSummaryViewController {
if selectedMessage != nil {
if selectedMessage == "Request Refill" {
selectedMessage = "Requesting refill at Table \(currentUser!.ticket!.tableNum!)"
}
else if selectedMessage == "Request Seating" {
selectedMessage = "Requesting additional/change of seating at Table \(currentUser!.ticket!.tableNum!)"
}
else if selectedMessage == "Follow-up Order" {
selectedMessage = "Requesting a follow up on Ticket \(currentUser!.ticket!.desc!) at Table \(currentUser!.ticket!.tableNum!)"
}
else if selectedMessage == "Other Request" {
selectedMessage = "Requesting server assistance at Table \(currentUser!.ticket!.tableNum!)"
}
parent.sendMessage(message: selectedMessage!)
}
}
}
func loadMessages() {
self.messages.append("Request Refill")
self.messages.append("Request Seating")
self.messages.append("Follow-up Order")
self.messages.append("Other Request")
}
func loadTheme() {
//Background and Tint
view.tintColor = currentTheme!.highlight!
popupView.backgroundColor = currentTheme!.primary!
messageTableView.backgroundColor = currentTheme!.primary!
messageTableView.sectionIndexBackgroundColor = currentTheme!.primary!
//Labels
requestLabel.textColor = currentTheme!.highlight!
//Buttons
confirmButton.backgroundColor = currentTheme!.highlight!
confirmButton.setTitleColor(currentTheme!.primary!, for: .normal)
cancelButton.backgroundColor = currentTheme!.highlight!
cancelButton.setTitleColor(currentTheme!.primary!, for: .normal)
}
}
| mit |
mleiv/MEGameTracker | MEGameTracker/Views/Missions Tab/Mission/MissionController.swift | 1 | 13745 | //
// MissionController.swift
// MEGameTracker
//
// Created by Emily Ivie on 3/6/16.
// Copyright © 2016 urdnot. All rights reserved.
//
import UIKit
import SafariServices
// swiftlint:disable file_length
// TODO: Refactor
final public class MissionController: UIViewController,
UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
/// A list of all page components, later tracked by a LoadStatus struct.
enum MissionPageComponent: LoadStatusComponent {
case aliases
case availability
case unavailability
case conversationRewards
case decisions
case description
case mapLink
case notes
case objectives
case originHint
case relatedLinks
case relatedMissions
case sideEffects
static func all() -> [MissionPageComponent] {
return [
.aliases,
.availability,
.unavailability,
.conversationRewards,
.decisions,
.description,
.mapLink,
.notes,
.objectives,
.originHint,
.relatedLinks,
.relatedMissions,
.sideEffects,
]
}
}
var shepardUuid: UUID?
public var mission: Mission? {
didSet {
// TODO: fix this, I hate didSet
if oldValue != nil && oldValue != mission {
reloadDataOnChange()
}
}
}
public var originHint: String? { return mission?.name }
@IBOutlet weak var nameLabel: UILabel?
@IBOutlet weak var checkboxImageView: UIImageView?
// Aliasable
@IBOutlet weak var aliasesView: TextDataRow?
lazy var aliasesType: AliasesType = {
return AliasesType(controller: self, view: self.aliasesView)
}()
// Available
@IBOutlet weak var availabilityView: TextDataRow?
public var availabilityMessage: String?
lazy var availabilityRowType: AvailabilityRowType = {
return AvailabilityRowType(controller: self, view: self.availabilityView)
}()
// Unavailable
@IBOutlet weak var unavailabilityView: TextDataRow?
public var unavailabilityMessage: String?
lazy var unavailabilityRowType: UnavailabilityRowType = {
return UnavailabilityRowType(controller: self, view: self.unavailabilityView)
}()
// ConversationRewardsable
@IBOutlet weak var conversationRewardsView: ValueDataRow?
lazy var conversationRewardsType: ConversationRewardsRowType = {
return ConversationRewardsRowType(controller: self, view: self.conversationRewardsView)
}()
// Decisionsable
@IBOutlet public weak var decisionsView: DecisionsView?
public var decisions: [Decision] = [] {
didSet {
mission?.relatedDecisionIds = decisions.map { $0.id } // local changes only
}
}
// Describable
@IBOutlet public weak var descriptionView: TextDataRow?
lazy var descriptionType: DescriptionType = {
return DescriptionType(controller: self, view: self.descriptionView)
}()
// MapLinkable
@IBOutlet public weak var mapLinkView: ValueDataRow?
lazy var mapLinkType: MapLinkType = {
return MapLinkType(controller: self, view: self.mapLinkView)
}()
public var inMapId: String? {
didSet {
mission?.inMapId = inMapId // local changes only
}
}
// Notesable
@IBOutlet weak var notesView: NotesView?
public var notes: [Note] = []
// Objectivesable
@IBOutlet public weak var objectivesView: ObjectivesView?
public var objectives: [MapLocationable] = []
// OriginHintable
@IBOutlet public weak var originHintView: TextDataRow?
lazy var originHintType: OriginHintType = { return OriginHintType(controller: self, view: self.originHintView) }()
// RelatedLinksable
@IBOutlet public weak var relatedLinksView: RelatedLinksView?
public var relatedLinks: [String] = []
// RelatedMissionsable
@IBOutlet public weak var relatedMissionsView: RelatedMissionsView?
public var relatedMissions: [Mission] = []
// SideEffectsable
@IBOutlet weak var sideEffectsView: SideEffectsView?
public var sideEffects: [String]? = []
public var isMissionAvailable = false
@IBAction func onClickCheckbox(_ sender: UIButton) {
toggleCheckbox()
}
var isUpdating = false
var pageLoadStatus = LoadStatus<MissionPageComponent>()
override public func viewDidLoad() {
super.viewDidLoad()
setup()
startListeners()
}
deinit {
removeListeners()
}
func setup() {
guard nameLabel != nil else { return } // make sure all outlets are connected
pageLoadStatus.reset()
startSpinner(inView: view)
isUpdating = true
defer {
isUpdating = false
}
if mission?.inMissionId == nil, let missionId = mission?.id, let gameVersion = mission?.gameVersion {
App.current.addRecentlyViewedMission(missionId: missionId, gameVersion: gameVersion)
}
if UIWindow.isInterfaceBuilder { fetchDummyData() }
isMissionAvailable = mission?.isAvailableAndParentAvailable ?? false
nameLabel?.text = mission?.name ?? ""
if let type = mission?.missionType {
parent?.navigationItem.title = mission?.pageTitle ?? type.stringValue
}
guard !UIWindow.isInterfaceBuilder else { return }
shepardUuid = App.current.game?.shepard?.uuid
setupAliases()
setupAvailability()
setupUnavailability()
setCheckboxImage(isCompleted: mission?.isCompleted ?? false, isAvailable: isMissionAvailable)
setupConversationRewards()
setupDecisions()
setupDescription()
setupMapLink()
setupNotes()
setupObjectives()
setupOriginHint()
setupRelatedLinks()
setupRelatedMissions()
setupSideEffects()
}
func fetchDummyData() {
mission = Mission.getDummy()
}
func conditionalSpinnerStop() {
if pageLoadStatus.isComplete {
stopSpinner(inView: view)
}
}
func reloadDataOnChange() {
self.setup()
}
func reloadOnShepardChange(_ x: Bool = false) {
if shepardUuid != App.current.game?.shepard?.uuid {
shepardUuid = App.current.game?.shepard?.uuid
reloadDataOnChange()
}
}
func startListeners() {
guard !UIWindow.isInterfaceBuilder else { return }
App.onCurrentShepardChange.cancelSubscription(for: self)
_ = App.onCurrentShepardChange.subscribe(with: self) { [weak self] _ in
DispatchQueue.main.async {
self?.reloadOnShepardChange()
}
}
// listen for changes to mission data
Mission.onChange.cancelSubscription(for: self)
_ = Mission.onChange.subscribe(with: self) { [weak self] changed in
if self?.mission?.id == changed.id, let newMission = changed.object ?? Mission.get(id: changed.id) {
DispatchQueue.main.async {
self?.mission = newMission
self?.reloadDataOnChange()
// the didSet check will view these missions as identical and not fire
}
}
}
}
func removeListeners() {
guard !UIWindow.isInterfaceBuilder else { return }
App.onCurrentShepardChange.cancelSubscription(for: self)
Mission.onChange.cancelSubscription(for: self)
}
}
extension MissionController {
func toggleCheckbox() {
guard let mission = self.mission else { return }
let isCompleted = !mission.isCompleted
let spinnerController = self as Spinnerable?
DispatchQueue.main.async {
spinnerController?.startSpinner(inView: self.view)
// make UI changes now
self.nameLabel?.attributedText = self.nameLabel?.attributedText?.toggleStrikethrough(isCompleted)
self.setCheckboxImage(isCompleted: isCompleted, isAvailable: self.isMissionAvailable)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(1)) {
// save changes to DB
self.mission = mission.changed(isCompleted: isCompleted, isSave: true)
spinnerController?.stopSpinner(inView: self.view)
}
}
}
func setCheckboxImage(isCompleted: Bool, isAvailable: Bool) {
checkboxImageView?.image = isCompleted ? MissionCheckbox.filled.getImage() : MissionCheckbox.empty.getImage()
if !isAvailable {
checkboxImageView?.tintColor = MEGameTrackerColor.disabled
} else {
checkboxImageView?.tintColor = MEGameTrackerColor.renegade
}
}
}
extension MissionController: Aliasable {
public var currentName: String? { return mission?.name }
public var aliases: [String] { return mission?.aliases ?? [] }
func setupAliases() {
aliasesType.setupView()
pageLoadStatus.markIsDone(.aliases)
conditionalSpinnerStop()
}
}
extension MissionController: Available {
//public var availabilityMessage: String? // already declared
func setupAvailability() {
availabilityMessage = mission?.unavailabilityMessages.joined(separator: ", ")
availabilityRowType.setupView()
pageLoadStatus.markIsDone(.availability)
conditionalSpinnerStop()
}
}
extension MissionController: Unavailable {
//public var unavailabilityMessage: String? // already declared
func setupUnavailability() {
unavailabilityMessage = mission?.isAvailable == true
? mission?.unavailabilityAfterMessages.joined(separator: ", ")
: nil
unavailabilityRowType.setupView()
pageLoadStatus.markIsDone(.unavailability)
conditionalSpinnerStop()
}
}
extension MissionController: ConversationRewardsable {
//public var originHint: String? // already declared
//public var mission: Mission? // already declared
func setupConversationRewards() {
conversationRewardsType.setupView()
pageLoadStatus.markIsDone(.conversationRewards)
conditionalSpinnerStop()
}
}
extension MissionController: Decisionsable {
//public var originHint: String? // already declared
//public var decisions: [Decision] // already declared
func setupDecisions() {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
if let decisionIds = self?.mission?.relatedDecisionIds {
self?.decisions = Decision.getAll(ids: decisionIds)
self?.decisions = self?.decisions.sorted(by: Decision.sort) ?? []
} else {
self?.decisions = []
}
DispatchQueue.main.async {
self?.decisionsView?.controller = self
self?.decisionsView?.setup()
self?.pageLoadStatus.markIsDone(.decisions)
self?.conditionalSpinnerStop()
}
}
}
}
extension MissionController: Describable {
public var descriptionMessage: String? {
return mission?.description
}
func setupDescription() {
descriptionType.setupView()
pageLoadStatus.markIsDone(.description)
conditionalSpinnerStop()
}
}
extension MissionController: MapLinkable {
//public var originHint: String? // already declared
//public var inMapId: String? // already declared
public var mapLocation: MapLocationable? { return mission }
public var isShowInParentMap: Bool { return mission?.isShowInParentMap ?? false }
func setupMapLink() {
DispatchQueue.main.async { [weak self] in
self?.inMapId = self?.mission?.inMapId
self?.mapLinkType.setupView()
self?.pageLoadStatus.markIsDone(.mapLink)
self?.conditionalSpinnerStop()
}
}
}
extension MissionController: Notesable {
//public var originHint: String? // already declared
//public var notes: [Note] // already declared
func setupNotes() {
mission?.getNotes { [weak self] notes in
DispatchQueue.main.async {
self?.notes = notes
self?.notesView?.controller = self
self?.notesView?.setup()
self?.pageLoadStatus.markIsDone(.notes)
self?.conditionalSpinnerStop()
}
}
}
public func getBlankNote() -> Note? {
return mission?.newNote()
}
}
extension MissionController: Objectivesable {
//public var objectives: [MapLocationable] // already declared
func setupObjectives() {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
self?.objectives = self?.mission?.getObjectives() ?? []
DispatchQueue.main.async {
self?.objectivesView?.controller = self
self?.objectivesView?.setup()
self?.pageLoadStatus.markIsDone(.objectives)
self?.conditionalSpinnerStop()
}
}
}
}
extension MissionController: OriginHintable {
//public var originHint: String? // already declared
func setupOriginHint() {
DispatchQueue.main.async { [weak self] in
if let parentMission = self?.mission?.parentMission {
self?.originHintType.overrideOriginPrefix = "Under"
self?.originHintType.overrideOriginHint = parentMission.name
} else {
self?.originHintType.overrideOriginHint = "" // block other origin hint
}
self?.originHintType.setupView()
self?.pageLoadStatus.markIsDone(.originHint)
self?.conditionalSpinnerStop()
}
}
}
extension MissionController: RelatedLinksable {
//public var relatedLinks: [String] // already declared
func setupRelatedLinks() {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
self?.relatedLinks = self?.mission?.relatedLinks ?? []
DispatchQueue.main.async {
self?.relatedLinksView?.controller = self
self?.relatedLinksView?.setup()
self?.pageLoadStatus.markIsDone(.relatedLinks)
self?.conditionalSpinnerStop()
}
}
}
}
extension MissionController: RelatedMissionsable {
//public var relatedMissions: [Mission] // already declared
func setupRelatedMissions() {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
self?.mission?.getRelatedMissions { (missions: [Mission]) in
DispatchQueue.main.async {
self?.relatedMissions = missions
self?.relatedMissionsView?.controller = self
self?.relatedMissionsView?.setup()
self?.pageLoadStatus.markIsDone(.relatedMissions)
self?.conditionalSpinnerStop()
}
}
}
}
}
extension MissionController: SideEffectsable {
//public var sideEffects: [String] // already declared
func setupSideEffects() {
DispatchQueue.main.async { [weak self] in
self?.sideEffects = self?.mission?.sideEffects ?? []
self?.sideEffectsView?.controller = self
self?.sideEffectsView?.setup()
self?.pageLoadStatus.markIsDone(.sideEffects)
self?.conditionalSpinnerStop()
}
}
}
extension MissionController: Spinnerable {}
// swiftlint:enable file_length
| mit |
magicien/MMDSceneKit | Sample_swift/tvOS/AppDelegate.swift | 1 | 2178 | //
// AppDelegate.swift
// MMDSceneKitSample_tvOS
//
// Created by magicien on 11/10/16.
// Copyright © 2016 DarkHorse. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Tests/SwiftProtobufTests/Test_TextFormat_Map_proto3.swift | 10 | 5757 | // Tests/SwiftProtobufTests/Test_TextFormat_Map_proto3.swift - Exercise proto3 text format coding
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// This is a set of tests for text format protobuf files.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
import SwiftProtobuf
class Test_TextFormat_Map_proto3: XCTestCase, PBTestHelpers {
typealias MessageTestType = ProtobufUnittest_TestMap
func test_Int32Int32() {
assertTextFormatEncode("map_int32_int32 {\n key: 1\n value: 2\n}\n") {(o: inout MessageTestType) in
o.mapInt32Int32 = [1:2]
}
assertTextFormatDecodeSucceeds("map_int32_int32 {key: 1, value: 2}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("map_int32_int32 {key: 1; value: 2}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("map_int32_int32 {key:1 value:2}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("map_int32_int32 {key:1 value:2}\nmap_int32_int32 {key:3 value:4}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2, 3:4]
}
assertTextFormatDecodeSucceeds("map_int32_int32 [{key:1 value:2}, {key:3 value:4}]") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2, 3:4]
}
assertTextFormatDecodeSucceeds("map_int32_int32 [{key:1 value:2}];map_int32_int32 {key:3 value:4}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2, 3:4]
}
assertTextFormatDecodeFails("map_int32_int32 [{key:1 value:2},]")
assertTextFormatDecodeFails("map_int32_int32 [{key:1 value:2}")
assertTextFormatDecodeFails("map_int32_int32 [{key:1 value:2 nonsense:3}")
assertTextFormatDecodeFails("map_int32_int32 {key:1}")
}
func test_Int32Int32_numbers() {
assertTextFormatDecodeSucceeds("1 {\n key: 1\n value: 2\n}\n") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("1 {key: 1, value: 2}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("1 {key: 1; value: 2}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("1 {key:1 value:2}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("1 {key:1 value:2}\n1 {key:3 value:4}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2, 3:4]
}
assertTextFormatDecodeSucceeds("1 [{key:1 value:2}, {key:3 value:4}]") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2, 3:4]
}
assertTextFormatDecodeSucceeds("1 [{key:1 value:2}];1 {key:3 value:4}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2, 3:4]
}
assertTextFormatDecodeFails("1 [{key:1 value:2},]")
assertTextFormatDecodeFails("1 [{key:1 value:2}")
assertTextFormatDecodeFails("1 [{key:1 value:2 nonsense:3}")
assertTextFormatDecodeFails("1 {key:1}")
// Using numbers for "key" and "value" in the map entries.
assertTextFormatDecodeSucceeds("1 {\n 1: 1\n 2: 2\n}\n") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("1 {1: 1, 2: 2}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("1 {1: 1; 2: 2}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("1 {1:1 2:2}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2]
}
assertTextFormatDecodeSucceeds("1 {1:1 2:2}\n1 {1:3 2:4}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2, 3:4]
}
assertTextFormatDecodeSucceeds("1 [{1:1 2:2}, {1:3 2:4}]") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2, 3:4]
}
assertTextFormatDecodeSucceeds("1 [{1:1 2:2}];1 {1:3 2:4}") {(o: MessageTestType) in
return o.mapInt32Int32 == [1:2, 3:4]
}
assertTextFormatDecodeFails("1 [{1:1 2:2},]")
assertTextFormatDecodeFails("1 [{1:1 2:2}")
assertTextFormatDecodeFails("1 [{1:1 2:2 3:3}")
assertTextFormatDecodeFails("1 {1:1}")
}
func test_StringMessage() {
let foo = ProtobufUnittest_ForeignMessage.with {$0.c = 999}
assertTextFormatEncode("map_string_foreign_message {\n key: \"foo\"\n value {\n c: 999\n }\n}\n") {(o: inout MessageTestType) in
o.mapStringForeignMessage = ["foo": foo]
}
}
func test_StringMessage_numbers() {
let foo = ProtobufUnittest_ForeignMessage.with {$0.c = 999}
assertTextFormatDecodeSucceeds("18 {\n key: \"foo\"\n value {\n 1: 999\n }\n}\n") {(o: MessageTestType) in
o.mapStringForeignMessage == ["foo": foo]
}
// Using numbers for "key" and "value" in the map entries.
assertTextFormatDecodeSucceeds("18 {\n 1: \"foo\"\n 2 {\n 1: 999\n }\n}\n") {(o: MessageTestType) in
o.mapStringForeignMessage == ["foo": foo]
}
}
}
| gpl-3.0 |
MukeshKumarS/Swift | test/Sema/immutability.swift | 3 | 18237 | // RUN: %target-parse-verify-swift
func markUsed<T>(t: T) {}
let bad_property_1: Int { // expected-error {{'let' declarations cannot be computed properties}}
get {
return 42
}
}
let bad_property_2: Int = 0 {
get { // expected-error {{use of unresolved identifier 'get'}}
return 42
}
}
let no_initializer : Int
func foreach_variable() {
for i in 0..<42 {
i = 11 // expected-error {{cannot assign to value: 'i' is a 'let' constant}}
}
}
func takeClosure(fn : (Int)->Int) {}
func passClosure() {
takeClosure { a in
a = 42 // expected-error {{cannot assign to value: 'a' is a 'let' constant}}
return a
}
takeClosure {
$0 = 42 // expected-error{{cannot assign to value: '$0' is a 'let' constant}}
return 42
}
takeClosure { (a : Int) -> Int in
a = 42 // expected-error{{cannot assign to value: 'a' is a 'let' constant}}
return 42
}
}
class FooClass {
class let type_let = 5 // expected-error {{class stored properties not yet supported in classes}}
init() {
self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}}
}
func bar() {
self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}}
}
mutating init(a : Bool) {} // expected-error {{'mutating' may only be used on 'func' declarations}} {{3-12=}}
mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}}
func baz() {}
var x : Int {
get {
return 32
}
set(value) {
value = 42 // expected-error {{cannot assign to value: 'value' is a 'let' constant}}
}
}
subscript(i : Int) -> Int {
get {
i = 42 // expected-error {{cannot assign to value: 'i' is immutable}}
return 1
}
}
}
func let_decls() {
// <rdar://problem/16927246> provide a fixit to change "let" to "var" if needing to mutate a variable
let a = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
a = 17 // expected-error {{cannot assign to value: 'a' is a 'let' constant}}
let (b,c) = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
markUsed(b); markUsed(c)
b = 17 // expected-error {{cannot assign to value: 'b' is a 'let' constant}}
let d = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
markUsed(d.0); markUsed(d.1)
d.0 = 17 // expected-error {{cannot assign to property: 'd' is a 'let' constant}}
let e = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
++e // expected-error {{cannot pass immutable value to mutating operator: 'e' is a 'let' constant}}
// <rdar://problem/16306600> QoI: passing a 'let' value as an inout results in an unfriendly diagnostic
let f = 96 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
var v = 1
swap(&f, &v) // expected-error {{cannot pass immutable value as inout argument: 'f' is a 'let' constant}}
// <rdar://problem/19711233> QoI: poor diagnostic for operator-assignment involving immutable operand
let g = 14 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
g /= 2 // expected-error {{left side of mutating operator isn't mutable: 'g' is a 'let' constant}}
}
struct SomeStruct {
var iv = 32
static let type_let = 5 // expected-note {{change 'let' to 'var' to make it mutable}} {{10-13=var}}
mutating static func f() { // expected-error {{static functions may not be declared mutating}} {{3-12=}}
}
mutating func g() {
iv = 42
}
mutating func g2() {
iv = 42
}
func h() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }}
iv = 12 // expected-error {{cannot assign to property: 'self' is immutable}}
}
var p: Int {
// Getters default to non-mutating.
get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }}
iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}}
return 42
}
// Setters default to mutating.
set {
iv = newValue
}
}
// Defaults can be changed.
var q : Int {
mutating
get {
iv = 37
return 42
}
nonmutating
set { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }}
iv = newValue // expected-error {{cannot assign to property: 'self' is immutable}}
}
}
var r : Int {
get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }}
iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}}
return 42
}
mutating // Redundant but OK.
set {
iv = newValue
}
}
}
markUsed(SomeStruct.type_let) // ok
SomeStruct.type_let = 17 // expected-error {{cannot assign to property: 'type_let' is a 'let' constant}}
struct TestMutableStruct {
mutating
func f() {}
func g() {}
var mutating_property : Int {
mutating
get {}
set {}
}
var nonmutating_property : Int {
get {}
nonmutating
set {}
}
// This property has a mutating getter and !mutating setter.
var weird_property : Int {
mutating get {}
nonmutating set {}
}
@mutating func mutating_attr() {} // expected-error {{'mutating' is a declaration modifier, not an attribute}} {{3-4=}}
@nonmutating func nonmutating_attr() {} // expected-error {{'nonmutating' is a declaration modifier, not an attribute}} {{3-4=}}
}
func test_mutability() {
// Non-mutable method on rvalue is ok.
TestMutableStruct().g()
// Non-mutable method on let is ok.
let x = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
x.g()
// Mutable methods on let and rvalue are not ok.
x.f() // expected-error {{cannot use mutating member on immutable value: 'x' is a 'let' constant}}
TestMutableStruct().f() // expected-error {{cannot use mutating member on immutable value: function call returns immutable value}}
_ = TestMutableStruct().weird_property // expected-error {{cannot use mutating getter on immutable value: function call returns immutable value}}
let tms = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
_ = tms.weird_property // expected-error {{cannot use mutating getter on immutable value: 'tms' is a 'let' constant}}
}
func test_arguments(a : Int,
var b : Int, // expected-warning {{Use of 'var' binding here is deprecated and will be removed in a future version of Swift}} {{21-25=}}
let c : Int) { // expected-warning {{Use of 'let' binding here is deprecated and will be removed in a future version of Swift}} {{21-25=}}
a = 1 // expected-error {{cannot assign to value: 'a' is a 'let' constant}}
b = 2 // ok.
c = 3 // expected-error {{cannot assign to value: 'c' is a 'let' constant}}
}
protocol ClassBoundProtocolMutating : class {
mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}}
func f()
}
protocol MutatingTestProto {
mutating
func mutatingfunc()
func nonmutatingfunc() // expected-note {{protocol requires}}
}
class TestClass : MutatingTestProto {
func mutatingfunc() {} // Ok, doesn't need to be mutating.
func nonmutatingfunc() {}
}
struct TestStruct1 : MutatingTestProto {
func mutatingfunc() {} // Ok, doesn't need to be mutating.
func nonmutatingfunc() {}
}
struct TestStruct2 : MutatingTestProto {
mutating
func mutatingfunc() {} // Ok, can be mutating.
func nonmutatingfunc() {}
}
struct TestStruct3 : MutatingTestProto { // expected-error {{type 'TestStruct3' does not conform to protocol 'MutatingTestProto'}}
func mutatingfunc() {}
// This is not ok, "nonmutatingfunc" doesn't allow mutating functions.
mutating
func nonmutatingfunc() {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}}
}
// <rdar://problem/16722603> invalid conformance of mutating setter
protocol NonMutatingSubscriptable {
subscript(i: Int) -> Int {get nonmutating set} // expected-note {{protocol requires subscript with type '(Int) -> Int'}}
}
struct MutatingSubscriptor : NonMutatingSubscriptable { // expected-error {{type 'MutatingSubscriptor' does not conform to protocol 'NonMutatingSubscriptable'}}
subscript(i: Int) -> Int {
get { return 42 }
mutating set {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}}
}
}
protocol NonMutatingGet {
var a: Int { get } // expected-note {{protocol requires property 'a' with type 'Int'}}
}
struct MutatingGet : NonMutatingGet { // expected-error {{type 'MutatingGet' does not conform to protocol 'NonMutatingGet'}}
var a: Int { mutating get { return 0 } } // expected-note {{candidate is marked 'mutating' but protocol does not allow it}}
}
func test_properties() {
let rvalue = TestMutableStruct() // expected-note 4 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}}
markUsed(rvalue.nonmutating_property) // ok
markUsed(rvalue.mutating_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}}
markUsed(rvalue.weird_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}}
rvalue.nonmutating_property = 1 // ok
rvalue.mutating_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}}
rvalue.weird_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}}
var lvalue = TestMutableStruct()
markUsed(lvalue.mutating_property) // ok
markUsed(lvalue.nonmutating_property) // ok
markUsed(lvalue.weird_property) // ok
lvalue.mutating_property = 1 // ok
lvalue.nonmutating_property = 1 // ok
lvalue.weird_property = 1 // ok
}
struct DuplicateMutating {
mutating mutating func f() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
}
protocol SubscriptNoGetter {
subscript (i: Int) -> Int { get }
}
func testSubscriptNoGetter(iis: SubscriptNoGetter) {
var _: Int = iis[17]
}
func testSelectorStyleArguments1(x: Int, bar y: Int) {
var x = x
var y = y
++x; ++y
}
func testSelectorStyleArguments2(x: Int,
bar y: Int) {
++x // expected-error {{cannot pass immutable value to mutating operator: 'x' is a 'let' constant}}
++y // expected-error {{cannot pass immutable value to mutating operator: 'y' is a 'let' constant}}
}
func invalid_inout(inout var x : Int) { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{26-30=}}
}
func updateInt(inout x : Int) {}
// rdar://15785677 - allow 'let' declarations in structs/classes be initialized in init()
class LetClassMembers {
let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
init(arg : Int) {
a = arg // ok, a is mutable in init()
updateInt(&a) // ok, a is mutable in init() and has been initialized
b = 17 // ok, b is mutable in init()
}
func f() {
a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}}
b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}}
updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}}
}
}
struct LetStructMembers {
let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
init(arg : Int) {
a = arg // ok, a is mutable in init()
updateInt(&a) // ok, a is mutable in init() and has been initialized
b = 17 // ok, b is mutable in init()
}
func f() {
a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}}
b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}}
updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}}
}
}
func QoI() {
let x = 97 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
x = 17 // expected-error {{cannot assign to value: 'x' is a 'let' constant}}
var get_only: Int {
get { return 7 }
}
get_only = 92 // expected-error {{cannot assign to value: 'get_only' is a get-only property}}
}
// <rdar://problem/17051675> Structure initializers in an extension cannot assign to constant properties
struct rdar17051675_S {
let x : Int
init(newX: Int) {
x = 42
}
}
extension rdar17051675_S {
init(newY: Int) {
x = 42
}
}
struct rdar17051675_S2<T> {
let x : Int
init(newX: Int) {
x = 42
}
}
extension rdar17051675_S2 {
init(newY: Int) {
x = 42
}
}
// <rdar://problem/17400366> let properties should not be mutable in convenience initializers
class ClassWithConvenienceInit {
let x : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
init(newX: Int) {
x = 42
}
convenience init(newY: Int) {
self.init(newX: 19)
x = 67 // expected-error {{cannot assign to property: 'x' is a 'let' constant}}
}
}
struct StructWithDelegatingInit {
let x: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
init(x: Int) { self.x = x }
init() { self.init(x: 0); self.x = 22 } // expected-error {{cannot assign to property: 'x' is a 'let' constant}}
}
func test_recovery_missing_name_1(: Int) {} // expected-error {{expected ',' separator}} {{35-35=,}} expected-error {{expected parameter type following ':'}}
func test_recovery_missing_name_2(: Int) {} // expected-error {{expected ',' separator}} {{35-35=,}} expected-error {{expected parameter type following ':'}}
// <rdar://problem/16792027> compiler infinite loops on a really really mutating function
struct F {
mutating mutating mutating f() { // expected-error 2 {{duplicate modifier}} expected-note 2 {{modifier already specified here}} expected-error {{consecutive declarations on a line must be separated by ';'}} {{29-29=;}} expected-error 2 {{expected declaration}}
}
mutating nonmutating func g() { // expected-error {{method may not be declared both mutating and nonmutating}} {{12-24=}}
}
}
protocol SingleIntProperty {
var i: Int { get }
}
struct SingleIntStruct : SingleIntProperty {
let i: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
}
extension SingleIntStruct {
init(_ other: SingleIntStruct) {
other.i = 999 // expected-error {{cannot assign to property: 'i' is a 'let' constant}}
}
}
// <rdar://problem/19370429> QoI: fixit to add "mutating" when assigning to a member of self in a struct
// <rdar://problem/17632908> QoI: Modifying struct member in non-mutating function produces difficult to understand error message
struct TestSubscriptMutability {
let let_arr = [1,2,3] // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
var var_arr = [1,2,3]
func nonmutating1() {
let_arr[1] = 1 // expected-error {{cannot assign through subscript: 'let_arr' is a 'let' constant}}
}
func nonmutating2() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }}
var_arr[1] = 1 // expected-error {{cannot assign through subscript: 'self' is immutable}}
}
func nonmutating3() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }}
self = TestSubscriptMutability() // expected-error {{cannot assign to value: 'self' is immutable}}
}
subscript(a : Int) -> TestSubscriptMutability {
return TestSubscriptMutability()
}
func test() {
self[1] = TestSubscriptMutability() // expected-error {{cannot assign through subscript: subscript is get-only}}
self[1].var_arr = [] // expected-error {{cannot assign to property: subscript is get-only}}
self[1].let_arr = [] // expected-error {{cannot assign to property: 'let_arr' is a 'let' constant}}
}
}
func f(a : TestSubscriptMutability) {
a.var_arr = [] // expected-error {{cannot assign to property: 'a' is a 'let' constant}}
}
struct TestSubscriptMutability2 {
subscript(a : Int) -> Int {
get { return 42 }
set {}
}
func test() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }}
self[1] = 2 // expected-error {{cannot assign through subscript: 'self' is immutable}}
}
}
struct TestBangMutability {
let let_opt = Optional(1) // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
var var_opt = Optional(1)
func nonmutating1() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }}
let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}}
var_opt! = 1 // expected-error {{cannot assign through '!': 'self' is immutable}}
self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}}
}
mutating func nonmutating2() {
let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}}
var_opt! = 1 // ok
self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}}
}
subscript() -> Int? { return nil }
}
// <rdar://problem/21176945> mutation through ? not considered a mutation
func testBindOptional() {
var a : TestStruct2? = nil // Mutated through optional chaining.
a?.mutatingfunc()
}
| apache-2.0 |
segmentio/analytics-ios | Package.swift | 1 | 1249 | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Segment",
platforms: [
.iOS(.v10), .tvOS(.v10), .macOS(.v10_13)
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "Segment",
targets: ["Segment"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "Segment",
dependencies: [],
path: "Segment/",
sources: ["Classes", "Internal"],
publicHeadersPath: "Classes",
cSettings: [
.headerSearchPath("Internal"),
.headerSearchPath("Classes")
]
)
]
)
| mit |
illescasDaniel/Questions | Questions/Models/Topic.swift | 1 | 5421 | //
// Quiz.swift
// Questions
//
// Created by Daniel Illescas Romero on 24/05/2018.
// Copyright © 2018 Daniel Illescas Romero. All rights reserved.
//
import Foundation
struct Topic: Codable {
let options: Options?
let sets: [[Question]]
}
extension Topic {
struct Options: Codable {
let name: String?
let timePerSetInSeconds: TimeInterval?
let helpButtonEnabled: Bool?
let questionsInRandomOrder: Bool?
let showCorrectIncorrectAnswer: Bool?
let multipleCorrectAnswersAsMandatory: Bool?
// case displayFullResults // YET to implement
}
}
extension Topic: Equatable {
static func ==(lhs: Topic, rhs: Topic) -> Bool {
let flatLhs = lhs.sets.flatMap { return $0 }
let flatRhs = rhs.sets.flatMap { return $0 }
return flatLhs == flatRhs
}
}
extension Topic {
enum ValidationError: Error {
case emptySet(count: Int)
case emptyQuestion(set: Int, question: Int)
case emptyAnswer(set: Int, question: Int, answer: Int)
case incorrectAnswersCount(set: Int, question: Int)
case incorrectCorrectAnswersCount(set: Int, question: Int, count: Int?)
case incorrectCorrectAnswerIndex(set: Int, question: Int, badIndex: Int, maximum: Int)
}
func validate() -> ValidationError? {
guard !self.sets.contains(where: { $0.isEmpty }) else { return .emptySet(count: self.sets.count) }
for (indexSet, setOfQuestions) in self.sets.enumerated() {
// ~ Number of answers must be consistent in the same set of questions (otherwise don't make this restriction, you might need to make other changes too)
let fullQuestionAnswersCount = setOfQuestions.first?.answers.count ?? 4
for (indexQuestion, fullQuestion) in setOfQuestions.enumerated() {
if fullQuestion.correctAnswers == nil { fullQuestion.correctAnswers = [] }
guard !fullQuestion.question.isEmpty else { return .emptyQuestion(set: indexSet+1, question: indexQuestion+1) }
guard fullQuestion.answers.count == fullQuestionAnswersCount, Set(fullQuestion.answers).count == fullQuestionAnswersCount else {
return .incorrectAnswersCount(set: indexSet+1, question: indexQuestion+1)
}
guard !fullQuestion.correctAnswers.contains(where: { $0 >= fullQuestionAnswersCount }),
(fullQuestion.correctAnswers?.count ?? 0) < fullQuestionAnswersCount else {
return .incorrectCorrectAnswersCount(set: indexSet+1, question: indexQuestion+1, count: fullQuestion.correctAnswers?.count)
}
if let singleCorrectAnswer = fullQuestion.correct {
if singleCorrectAnswer >= fullQuestionAnswersCount {
return .incorrectCorrectAnswerIndex(set: indexSet+1, question: indexQuestion+1, badIndex: Int(singleCorrectAnswer)+1, maximum: fullQuestionAnswersCount)
} else {
fullQuestion.correctAnswers?.insert(singleCorrectAnswer)
}
}
guard let correctAnswers = fullQuestion.correctAnswers, correctAnswers.count < fullQuestionAnswersCount, correctAnswers.count > 0 else {
return .incorrectCorrectAnswersCount(set: indexSet+1, question: indexQuestion+1, count: fullQuestion.correctAnswers?.count)
}
for (indexAnswer, answer) in fullQuestion.answers.enumerated() {
if answer.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return .emptyAnswer(set: indexSet+1, question: indexQuestion+1, answer: indexAnswer+1)
}
}
}
}
return nil
}
}
extension Topic.ValidationError: LocalizedError {
var errorDescription: String? {
switch self {
case .emptySet:
return L10n.TopicsCreation_WebView_Validation_Sets_Empty
case .emptyQuestion:
return L10n.TopicsCreation_WebView_Validation_Questions_Empty
case .emptyAnswer:
return L10n.TopicsCreation_WebView_Validation_Answers_Empty
case .incorrectAnswersCount:
return L10n.TopicsCreation_WebView_Validation_Answers_IncorrectCount
case .incorrectCorrectAnswersCount:
return L10n.TopicsCreation_WebView_Validation_Answers_BadCorrectCount
case .incorrectCorrectAnswerIndex:
return L10n.TopicsCreation_WebView_Validation_Answers_BadCorrectIndex
}
}
var recoverySuggestion: String? {
switch self {
case .emptySet(let count):
return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Sets_Empty_Recovery, count)
case .emptyQuestion(let set, let question):
return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Questions_Empty_Recovery, set, question)
case .emptyAnswer(let set, let question, let answer):
return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Answers_Empty_Recovery, set, question, answer)
case .incorrectAnswersCount(let set, let question):
return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Answers_IncorrectCount_Recovery, set, question)
case .incorrectCorrectAnswersCount(let set, let question, let count):
return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Answers_BadCorrectCount_Recovery, set, question, count ?? 0)
case .incorrectCorrectAnswerIndex(let set, let question, let badIndex, let maximum):
return String.localizedStringWithFormat(L10n.TopicsCreation_WebView_Validation_Answers_BadCorrectIndex_Recovery, set, question, badIndex, maximum)
}
}
}
extension Topic {
var inJSON: String {
if let data = try? JSONEncoder().encode(self), let jsonQuiz = String(data: data, encoding: .utf8) {
return jsonQuiz
}
return ""
}
}
| mit |
naoyashiga/CatsForInstagram | Nekobu/UIButton+AnimationExtension.swift | 1 | 607 | //
// UIButton+AnimationExtension.swift
// Nekobu
//
// Created by naoyashiga on 2015/08/16.
// Copyright (c) 2015年 naoyashiga. All rights reserved.
//
import Foundation
import UIKit
extension UIButton {
func playBounceAnimation() {
let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
bounceAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0]
bounceAnimation.duration = NSTimeInterval(0.5)
bounceAnimation.calculationMode = kCAAnimationCubic
layer.addAnimation(bounceAnimation, forKey: "bounceAnimation")
}
}
| mit |
sarvex/SwiftRecepies | Data/Reading Data from Core Data/Reading Data from Core Data/Person.swift | 1 | 342 | //
// Person.swift
// Reading Data from Core Data
//
// Created by vandad on 167//14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
import Foundation
import CoreData
@objc(Person) class Person: NSManagedObject {
@NSManaged var firstName: String
@NSManaged var lastName: String
@NSManaged var age: NSNumber
}
| isc |
maxbritto/cours-ios11-swift4 | swift_4_cours_complet.playground/Pages/Intervalles.xcplaygroundpage/Contents.swift | 1 | 540 | //: [< Sommaire](Sommaire)
/*:
# Intervalles (Range)
---
### Maxime Britto - Swift 4
*/
for i in 0...10 {
print(i)
}
//: ## Intervalles et tableaux
let names = [ "Kelso", "Hyde", "Eric", "Fez"]
//: Les index du tableau **names** vont de 0 à 3
for name in names[1...] {
print(name)
}
//: ## Intervalles et chaînes de caractères
let redQuote = "You're a dumbass! - Red Forman"
let stopIndex:String.Index = redQuote.index(of: "-") ?? redQuote.endIndex
let shortQuote = redQuote[..<stopIndex]
/*:
[< Sommaire](Sommaire)
*/
| apache-2.0 |
stevewight/DetectorKit | DetectorKit/Models/Detectors/TextDetector.swift | 1 | 533 | //
// TextDetector.swift
// Sherlock
//
// Created by Steve on 12/6/16.
// Copyright © 2016 Steve Wight. All rights reserved.
//
import UIKit
public class TextDetector: BaseDetector {
public var textBlocks:[CIFeature]!
init(_ image:CIImage) {
super.init(image, type: CIDetectorTypeText)
}
override public func features()->[CIFeature] {
return textBlocks
}
override public func detect(_ image:CIImage) {
textBlocks = detector.features(in: image)
}
}
| mit |
skylib/SnapPageableArray | SnapPageableArrayTests/InitTests.swift | 1 | 1796 | import SnapPageableArray
import XCTest
class InitTests: PageableArrayTests {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testInitShouldSetPagesize() {
let capacity: UInt = 100
let pageSize: UInt = 10
let array = PageableArray<TestElement>(capacity: capacity, pageSize: pageSize)
XCTAssertEqual(pageSize, array.pageSize)
}
func testSetPagesizeShouldSetPagesize() {
let capacity: UInt = 100
var pageSize: UInt = 10
var array = PageableArray<TestElement>(capacity: capacity, pageSize: pageSize)
pageSize = 50
array.pageSize = pageSize
XCTAssertEqual(pageSize, array.pageSize)
}
func testInitShouldSetSize() {
let capacity: UInt = 100
let pageSize: UInt = 10
let array = PageableArray<TestElement>(capacity: capacity, pageSize: pageSize)
XCTAssertEqual(capacity, array.count)
}
func testInitShouldSetNumberOfItemsAhead() {
let capacity: UInt = 100
let pageSize: UInt = 10
let array = PageableArray<TestElement>(capacity: capacity, pageSize: pageSize)
XCTAssertNotEqual(0, array.numberOfItemsAheadOfLastToTriggerLoadMore)
}
func testSetNumberOfItemsAheadShouldSetNumberOfItemsAhead() {
let capacity: UInt = 100
let pageSize: UInt = 10
var array = PageableArray<TestElement>(capacity: capacity, pageSize: pageSize)
let numberOfItemsAhead: UInt = 10
array.numberOfItemsAheadOfLastToTriggerLoadMore = numberOfItemsAhead
XCTAssertEqual(numberOfItemsAhead, array.numberOfItemsAheadOfLastToTriggerLoadMore)
}
}
| bsd-3-clause |
zachwaugh/GIFKit | GIFKit/ApplicationExtension.swift | 1 | 603 | //
// ApplicationExtension.swift
// GIFKit
//
// Created by Zach Waugh on 11/12/15.
// Copyright © 2015 Zach Waugh. All rights reserved.
//
import Foundation
struct ApplicationExtension: CustomStringConvertible {
let identifier: String
let authenticationCode: [Byte]
init(bytes: [Byte]) {
identifier = String(bytes: bytes[0..<8], encoding: NSUTF8StringEncoding)!
authenticationCode = Array(bytes[8..<11])
}
var description: String {
return "<ApplicationExtension identifier: \(identifier), authentication code: \(authenticationCode)>"
}
} | mit |
benlangmuir/swift | test/Concurrency/Backdeploy/objc_actor.swift | 4 | 529 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -target %target-cpu-apple-macosx11 %s -o %t/test_backdeploy -Xfrontend -parse-as-library
// RUN: %target-run %t/test_backdeploy
// REQUIRES: OS=macosx
// REQUIRES: executable_test
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
import Foundation
@objc actor MyActor {
func f() -> String { "hello" }
}
@main
enum Main {
static func main() async {
let ma = MyActor()
let greeting = await ma.f()
assert(greeting == "hello")
}
}
| apache-2.0 |
IngmarStein/Monolingual | XPCService/Package.swift | 1 | 207 | import PackageDescription
let package = Package(
name: "XPCService",
dependencies: [
.Package(url: "https://github.com/IngmarStein/SMJobKit.git", versions: Version(0, 0, 16) ..< Version(1, 0, 0)),
]
)
| gpl-3.0 |
takeo-asai/math-puzzle | problems/05.swift | 1 | 356 | // 10x + 50y + 100z + 500w = 1000
// x + y + z + w + s == 15
// s >= 0 (s: slack variable)
var combinations: [(Int, Int, Int, Int)] = []
for w in 0 ... 2 {
for z in 0 ... 10 {
for y in 0 ... 15 { // 20
let x = 100 - 50*w - 10*z - 5*y
if x <= 15 - y - z - w && x >= 0 {
combinations += [(x, y, z, w)]
}
}
}
}
print(combinations.count)
| mit |
haawa799/WaniKani-iOS | WaniKani/ViewControllers/DataTypePickerController.swift | 1 | 694 | //
// DataTypePickerController.swift
// WaniKani
//
// Created by Andriy K. on 1/11/16.
// Copyright © 2016 Andriy K. All rights reserved.
//
import UIKit
class DataTypePickerController: UIViewController {
override func viewWillAppear(animated: Bool) {
navigationController?.navigationBarHidden = true
super.viewWillAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
if (navigationController?.topViewController != self) {
navigationController?.navigationBarHidden = false
}
super.viewWillDisappear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
addBackground(BackgroundOptions.Data.rawValue)
}
}
| gpl-3.0 |
BellAppLab/Closures | Closure/Closure/Closure.swift | 1 | 1044 | //
// Closure.swift
//
//
import Foundation
class Thing
{
let name: String
var size: Int?
init(name: String, size: Int?)
{
self.name = name
self.size = size
}
func giveNameIfSize() -> String?
{
if self.size != nil {
return self.name
}
return nil
}
}
typealias IterationBlock = (Thing) -> Bool
class Iterable
{
private let array: Array<Thing>
var count: Int {
return self.array.count
}
init(array: [Thing])
{
self.array = array
}
func iterate(block: IterationBlock)
{
if self.count == 0 {
return
}
for object in self.array {
if block(object) {
break
}
}
}
var description: String {
var result = "Description:"
self.iterate { (someThing) -> Bool in
result += " " + someThing.name + ", "
return false
}
return result
}
}
| mit |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Settings/CellDescriptors/SettingsCellDescriptorFactory+Options.swift | 1 | 17070 | //
// Wire
// Copyright (C) 2016 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 LocalAuthentication
import UIKit
import WireSyncEngine
import WireCommonComponents
extension SettingsCellDescriptorFactory {
// MARK: - Options Group
var optionsGroup: SettingsCellDescriptorType {
let descriptors = [
shareContactsDisabledSection,
clearHistorySection,
notificationVisibleSection,
chatHeadsSection,
soundAlertSection,
callKitSection,
muteCallSection,
SecurityFlags.forceConstantBitRateCalls.isEnabled ? nil : VBRSection,
soundsSection,
externalAppsSection,
popularDemandSendButtonSection,
popularDemandDarkThemeSection,
isAppLockAvailable ? appLockSection : nil,
SecurityFlags.generateLinkPreviews.isEnabled ? linkPreviewSection : nil
].compactMap { $0 }
return SettingsGroupCellDescriptor(
items: descriptors,
title: "self.settings.options_menu.title".localized,
icon: .settingsOptions,
accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description
)
}
// MARK: - Sections
private var shareContactsDisabledSection: SettingsSectionDescriptorType {
let settingsButton = SettingsButtonCellDescriptor(
title: "self.settings.privacy_contacts_menu.settings_button.title".localized,
isDestructive: false,
selectAction: { _ in
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
})
return SettingsSectionDescriptor(
cellDescriptors: [settingsButton],
header: "self.settings.privacy_contacts_section.title".localized,
footer: "self.settings.privacy_contacts_menu.description_disabled.title".localized,
visibilityAction: { _ in
return AddressBookHelper.sharedHelper.isAddressBookAccessDisabled
})
}
private var clearHistorySection: SettingsSectionDescriptorType {
let clearHistoryButton = SettingsButtonCellDescriptor(
title: "self.settings.privacy.clear_history.title".localized,
isDestructive: false,
selectAction: { _ in
// erase history is not supported yet
})
return SettingsSectionDescriptor(
cellDescriptors: [clearHistoryButton],
header: .none,
footer: "self.settings.privacy.clear_history.subtitle".localized,
visibilityAction: { _ in return false }
)
}
private var notificationVisibleSection: SettingsSectionDescriptorType {
let notificationToggle = SettingsPropertyToggleCellDescriptor(
settingsProperty: settingsPropertyFactory.property(.notificationContentVisible),
inverse: true
)
return SettingsSectionDescriptor(
cellDescriptors: [notificationToggle],
header: "self.settings.notifications.push_notification.title".localized,
footer: "self.settings.notifications.push_notification.footer".localized
)
}
private var chatHeadsSection: SettingsSectionDescriptorType {
let chatHeadsToggle = SettingsPropertyToggleCellDescriptor(
settingsProperty: settingsPropertyFactory.property(.chatHeadsDisabled),
inverse: true
)
return SettingsSectionDescriptor(
cellDescriptors: [chatHeadsToggle],
header: nil,
footer: "self.settings.notifications.chat_alerts.footer".localized
)
}
private var soundAlertSection: SettingsSectionDescriptorType {
return SettingsSectionDescriptor(cellDescriptors: [soundAlertGroup])
}
private var callKitSection: SettingsSectionDescriptorType {
let callKitToggle = SettingsPropertyToggleCellDescriptor(
settingsProperty: settingsPropertyFactory.property(.disableCallKit),
inverse: true
)
return SettingsSectionDescriptor(
cellDescriptors: [callKitToggle],
header: "self.settings.callkit.title".localized,
footer: "self.settings.callkit.description".localized,
visibilityAction: .none
)
}
private var muteCallSection: SettingsSectionDescriptorType {
let muteCallToggle = SettingsPropertyToggleCellDescriptor(
settingsProperty: settingsPropertyFactory.property(.muteIncomingCallsWhileInACall),
inverse: false
)
return SettingsSectionDescriptor(
cellDescriptors: [muteCallToggle],
footer: L10n.Localizable.Self.Settings.MuteOtherCall.description,
visibilityAction: .none
)
}
private var VBRSection: SettingsSectionDescriptorType {
let VBRToggle = SettingsPropertyToggleCellDescriptor(
settingsProperty: settingsPropertyFactory.property(.callingConstantBitRate),
inverse: true,
identifier: "VBRSwitch"
)
return SettingsSectionDescriptor(
cellDescriptors: [VBRToggle],
header: .none,
footer: "self.settings.vbr.description".localized,
visibilityAction: .none
)
}
private var soundsSection: SettingsSectionDescriptorType {
let callSoundProperty = settingsPropertyFactory.property(.callSoundName)
let callSoundGroup = soundGroupForSetting(
callSoundProperty,
title: callSoundProperty.propertyName.settingsPropertyLabelText,
customSounds: ZMSound.ringtones,
defaultSound: ZMSound.WireCall
)
let messageSoundProperty = settingsPropertyFactory.property(.messageSoundName)
let messageSoundGroup = soundGroupForSetting(
messageSoundProperty,
title: messageSoundProperty.propertyName.settingsPropertyLabelText,
customSounds: ZMSound.soundEffects,
defaultSound: ZMSound.WireText
)
let pingSoundProperty = settingsPropertyFactory.property(.pingSoundName)
let pingSoundGroup = soundGroupForSetting(
pingSoundProperty,
title: pingSoundProperty.propertyName.settingsPropertyLabelText,
customSounds: ZMSound.soundEffects,
defaultSound: ZMSound.WirePing
)
return SettingsSectionDescriptor(
cellDescriptors: [callSoundGroup, messageSoundGroup, pingSoundGroup],
header: "self.settings.sound_menu.sounds.title".localized
)
}
private var externalAppsSection: SettingsSectionDescriptorType? {
var descriptors = [SettingsCellDescriptorType]()
if BrowserOpeningOption.optionsAvailable {
descriptors.append(browserOpeningGroup(for: settingsPropertyFactory.property(.browserOpeningOption)))
}
if MapsOpeningOption.optionsAvailable {
descriptors.append(mapsOpeningGroup(for: settingsPropertyFactory.property(.mapsOpeningOption)))
}
if TweetOpeningOption.optionsAvailable {
descriptors.append(twitterOpeningGroup(for: settingsPropertyFactory.property(.tweetOpeningOption)))
}
guard descriptors.count > 0 else {
return nil
}
return SettingsSectionDescriptor(
cellDescriptors: descriptors,
header: "self.settings.external_apps.header".localized
)
}
private var popularDemandSendButtonSection: SettingsSectionDescriptorType {
let sendButtonToggle = SettingsPropertyToggleCellDescriptor(
settingsProperty: settingsPropertyFactory.property(.disableSendButton),
inverse: true
)
return SettingsSectionDescriptor(
cellDescriptors: [sendButtonToggle],
header: "self.settings.popular_demand.title".localized,
footer: "self.settings.popular_demand.send_button.footer".localized
)
}
private var popularDemandDarkThemeSection: SettingsSectionDescriptorType {
let darkThemeSection = SettingsCellDescriptorFactory.darkThemeGroup(for: settingsPropertyFactory.property(.darkMode))
return SettingsSectionDescriptor(
cellDescriptors: [darkThemeSection],
footer: "self.settings.popular_demand.dark_mode.footer".localized
)
}
private var appLockSection: SettingsSectionDescriptorType {
let appLockToggle = SettingsPropertyToggleCellDescriptor(settingsProperty: settingsPropertyFactory.property(.lockApp))
appLockToggle.settingsProperty.enabled = !settingsPropertyFactory.isAppLockForced
return SettingsSectionDescriptor(
cellDescriptors: [appLockToggle],
headerGenerator: { return nil },
footerGenerator: { return self.appLockSectionSubtitle }
)
}
private var linkPreviewSection: SettingsSectionDescriptorType {
let linkPreviewToggle = SettingsPropertyToggleCellDescriptor(
settingsProperty: settingsPropertyFactory.property(.disableLinkPreviews),
inverse: true
)
return SettingsSectionDescriptor(
cellDescriptors: [linkPreviewToggle],
header: nil,
footer: "self.settings.privacy_security.disable_link_previews.footer".localized
)
}
// MARK: - Helpers
static func darkThemeGroup(for property: SettingsProperty) -> SettingsCellDescriptorType {
let cells = SettingsColorScheme.allCases.map { option -> SettingsPropertySelectValueCellDescriptor in
return SettingsPropertySelectValueCellDescriptor(
settingsProperty: property,
value: SettingsPropertyValue(option.rawValue),
title: option.displayString
)
}
let section = SettingsSectionDescriptor(cellDescriptors: cells.map { $0 as SettingsCellDescriptorType })
let preview: PreviewGeneratorType = { _ in
let value = property.value().value() as? Int
guard let option = value.flatMap({ SettingsColorScheme(rawValue: $0) }) else { return .text(SettingsColorScheme.defaultPreference.displayString) }
return .text(option.displayString)
}
return SettingsGroupCellDescriptor(items: [section],
title: property.propertyName.settingsPropertyLabelText,
identifier: nil,
previewGenerator: preview,
accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description)
}
func twitterOpeningGroup(for property: SettingsProperty) -> SettingsCellDescriptorType {
let cells = TweetOpeningOption.availableOptions.map { option -> SettingsPropertySelectValueCellDescriptor in
return SettingsPropertySelectValueCellDescriptor(
settingsProperty: property,
value: SettingsPropertyValue(option.rawValue),
title: option.displayString
)
}
let section = SettingsSectionDescriptor(cellDescriptors: cells.map { $0 as SettingsCellDescriptorType })
let preview: PreviewGeneratorType = { _ in
let value = property.value().value() as? Int
guard let option = value.flatMap({ TweetOpeningOption(rawValue: $0) }) else { return .text(TweetOpeningOption.none.displayString) }
return .text(option.displayString)
}
return SettingsGroupCellDescriptor(items: [section],
title: property.propertyName.settingsPropertyLabelText,
identifier: nil,
previewGenerator: preview,
accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description)
}
func mapsOpeningGroup(for property: SettingsProperty) -> SettingsCellDescriptorType {
let cells = MapsOpeningOption.availableOptions.map { option -> SettingsPropertySelectValueCellDescriptor in
return SettingsPropertySelectValueCellDescriptor(
settingsProperty: property,
value: SettingsPropertyValue(option.rawValue),
title: option.displayString
)
}
let section = SettingsSectionDescriptor(cellDescriptors: cells.map { $0 as SettingsCellDescriptorType }, header: nil, footer: "open_link.maps.footer".localized, visibilityAction: nil)
let preview: PreviewGeneratorType = { _ in
let value = property.value().value() as? Int
guard let option = value.flatMap({ MapsOpeningOption(rawValue: $0) }) else { return .text(MapsOpeningOption.apple.displayString) }
return .text(option.displayString)
}
return SettingsGroupCellDescriptor(items: [section],
title: property.propertyName.settingsPropertyLabelText,
identifier: nil,
previewGenerator: preview,
accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description)
}
func browserOpeningGroup(for property: SettingsProperty) -> SettingsCellDescriptorType {
let cells = BrowserOpeningOption.availableOptions.map { option -> SettingsPropertySelectValueCellDescriptor in
return SettingsPropertySelectValueCellDescriptor(
settingsProperty: property,
value: SettingsPropertyValue(option.rawValue),
title: option.displayString
)
}
let section = SettingsSectionDescriptor(cellDescriptors: cells.map { $0 as SettingsCellDescriptorType })
let preview: PreviewGeneratorType = { _ in
let value = property.value().value() as? Int
guard let option = value.flatMap({ BrowserOpeningOption(rawValue: $0) }) else { return .text(BrowserOpeningOption.safari.displayString) }
return .text(option.displayString)
}
return SettingsGroupCellDescriptor(items: [section],
title: property.propertyName.settingsPropertyLabelText,
identifier: nil,
previewGenerator: preview,
accessibilityBackButtonText: L10n.Accessibility.OptionsSettings.BackButton.description)
}
static var appLockFormatter: DateComponentsFormatter {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.day, .hour, .minute, .second]
formatter.zeroFormattingBehavior = .dropAll
return formatter
}
private var appLockSectionSubtitle: String {
let timeout = TimeInterval(settingsPropertyFactory.timeout)
guard let amount = SettingsCellDescriptorFactory.appLockFormatter.string(from: timeout) else { return "" }
let lockDescription = "self.settings.privacy_security.lock_app.subtitle.lock_description".localized(args: amount)
let typeKey: String = {
switch AuthenticationType.current {
case .touchID: return "self.settings.privacy_security.lock_app.subtitle.touch_id"
case .faceID: return "self.settings.privacy_security.lock_app.subtitle.face_id"
default: return "self.settings.privacy_security.lock_app.subtitle.none"
}
}()
var components = [lockDescription, typeKey.localized]
if AuthenticationType.current == .unavailable {
let reminderKey = "self.settings.privacy_security.lock_app.subtitle.custom_app_lock_reminder"
components.append(reminderKey.localized)
}
return components.joined(separator: " ")
}
}
// MARK: - Helpers
extension SettingsCellDescriptorFactory {
// Encryption at rest will trigger its own variant of AppLock.
var isAppLockAvailable: Bool {
return !SecurityFlags.forceEncryptionAtRest.isEnabled && settingsPropertyFactory.isAppLockAvailable
}
}
| gpl-3.0 |
Ryce/HBRPagingView | HBRPagingView/HBRPagingView.swift | 1 | 7669 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Hamon Riazy
//
// 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
@objc public protocol HBRPagingViewDelegate : NSObjectProtocol, UIScrollViewDelegate {
@objc optional func pagingView(_ pagingView: HBRPagingView, shouldSelectPage page: UInt) -> Bool
@objc optional func pagingView(_ pagingView: HBRPagingView, didSelectPage page: UInt)
}
public protocol HBRPagingViewDataSource : NSObjectProtocol {
func pagingView(_ pagingView: HBRPagingView, viewForPage index: UInt) -> AnyObject
func numberOfPages(_ pagingView: HBRPagingView) -> UInt
}
public class HBRPagingView: UIScrollView, UIScrollViewDelegate {
public weak var pagingDelegate: HBRPagingViewDelegate?
public weak var dataSource: HBRPagingViewDataSource?
private var cachedPages = [UInt: AnyObject]()
private var registeredClasses = [String: AnyClass]()
override open func draw(_ rect: CGRect) {
super.draw(rect)
self.setupView()
}
open func reloadData() {
self.setupView()
}
private func setupView() {
self.isPagingEnabled = true
self.delegate = self
if self.dataSource == nil {
return // BAIL
}
let nop = self.dataSource!.numberOfPages(self)
if nop == 0 {
return // BAIL
}
self.contentSize = CGSize(width: self.bounds.size.width * CGFloat(nop), height: self.bounds.size.height)
let pageIndex = self.currentPage()
if self.dataSource?.numberOfPages(self) >= pageIndex {
if let page: AnyObject = self.dataSource?.pagingView(self, viewForPage: pageIndex) {
self.addPage(page, forIndex: pageIndex)
}
if pageIndex > 0 {
if let page: AnyObject = self.dataSource?.pagingView(self, viewForPage: pageIndex - 1) {
self.addPage(page, forIndex: pageIndex - 1)
}
}
if self.dataSource?.numberOfPages(self) > pageIndex {
if let page: AnyObject = self.dataSource?.pagingView(self, viewForPage: pageIndex + 1) {
self.addPage(page, forIndex: pageIndex + 1)
}
}
}
}
private func addPage(_ page: AnyObject, forIndex pageIndex: UInt) {
if let cachedPage: AnyObject = self.cachedPages[pageIndex] {
if !cachedPage.isEqual(page) {
self.cachedPages[pageIndex] = page
if page.superview != self {
self.addSubview(page as! UIView)
}
}
} else {
self.cachedPages[pageIndex] = page
if page.superview != self {
self.addSubview(page as! UIView)
}
}
(page as! UIView).frame = CGRect(x: CGFloat(pageIndex) * self.bounds.size.width, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
}
open func register(_ pageClass: AnyClass, forPageReuseIdentifier identifier: String) {
self.registeredClasses[identifier] = pageClass
}
open func dequeueReusablePage(with identifier: String, forIndex index: UInt) -> AnyObject {
if self.registeredClasses[identifier] == nil {
NSException(name: NSExceptionName(rawValue: "PageNotRegisteredException"), reason: "The identifier did not match any of the registered classes", userInfo: nil).raise()
return HBRPagingViewPage()
}
if let page: AnyObject = self.cachedPages[index] {
return page
} else {
for key: UInt in self.cachedPages.keys {
let distance = fabs(Double(key) - Double(self.currentPage()))
if distance > 1 && self.cachedPages[key]!.isKind(of: self.registeredClasses[identifier]!) {
// still have to check if that same object has been used somewhere else
let page: AnyObject = self.cachedPages[key]!
self.cachedPages.removeValue(forKey: key)
return page
}
}
HBRPagingViewPage.self
let objType = registeredClasses[identifier] as! HBRPagingViewPage.Type
let newInstance = objType.init()
newInstance.frame = self.bounds
newInstance.contentView.frame = newInstance.bounds
return newInstance
}
}
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let numberOfPages = self.dataSource?.numberOfPages(self) {
let offsetAmount = Int(fmin(fmax(0, self.contentOffset.x / self.bounds.size.width), CGFloat(numberOfPages)))
let direction = ((offsetAmount - Int(self.currentPage())) == 0 ? 1 : -1)
let index = Int(self.currentPage()) + direction
if index >= Int(numberOfPages) {
return
}
if let page: AnyObject = self.dataSource?.pagingView(self, viewForPage: UInt(index)) {
self.addPage(page, forIndex: UInt(index))
}
}
}
func currentPage() -> UInt {
return UInt(round(self.contentOffset.x/self.bounds.size.width))
}
}
import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
open class HBRPagingViewPage: UIView {
open let contentView = UIView()
open override func draw(_ rect: CGRect) {
super.draw(rect)
self.contentView.frame = self.bounds
self.addSubview(self.contentView)
}
}
| mit |
Constructor-io/constructorio-client-swift | AutocompleteClientTests/FW/Logic/Request/Mock/AbstractAutocompleteViewModel+Mock.swift | 1 | 2213 | //
// AbstractAutocompleteViewModel+Mock.swift
// AutocompleteClientTests
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import XCTest
@testable import ConstructorAutocomplete
public class MockAutocompleteViewModel: AbstractAutocompleteViewModel {
public private(set) var searchTerm: String
public var results: [AutocompleteViewModelSection]
public var screenTitle: String
public var modelSorter: (String, String) -> Bool = { return $0 < $1 }
public weak var delegate: AutocompleteViewModelDelegate?
public init() {
self.results = []
self.searchTerm = ""
self.screenTitle = "title"
}
public var lastResult: AutocompleteResult?
internal func setupDataFromResult(result: AutocompleteResult) {
self.searchTerm = result.query.query
self.setResultFromDictionary(dictionary: result.response?.sections)
self.lastResult = result
self.delegate?.viewModel(self, didSetResult: result)
}
internal func setResultFromDictionary(dictionary: [String: [CIOAutocompleteResult]]?) {
self.results = (dictionary ?? [:]).map { (section, items) in AutocompleteViewModelSection(items: items, sectionName: section) }
.sorted { (s1, s2) in self.modelSorter(s1.sectionName, s2.sectionName) }
}
public func set(searchResult: AutocompleteResult, completionHandler: @escaping () -> Void) {
if let lastResult = self.lastResult {
if searchResult.isInitiatedAfter(result: lastResult) {
self.setupDataFromResult(result: searchResult)
} else {
self.delegate?.viewModel(self, didIgnoreResult: searchResult)
}
} else {
// no previous result, this one must be valid
self.setupDataFromResult(result: searchResult)
}
DispatchQueue.main.async(execute: completionHandler)
}
public func getResult(atIndexPath indexPath: IndexPath) -> CIOAutocompleteResult {
return results[indexPath.section].items[indexPath.row]
}
public func getSectionName(atIndex index: Int) -> String {
return results[index].sectionName
}
}
| mit |
Holmusk/HMRequestFramework-iOS | HMRequestFramework-FullDemo/controller/profile/UserProfileVC.swift | 1 | 9791 | //
// UserProfileVC.swift
// HMRequestFramework-FullDemo
//
// Created by Hai Pham on 17/1/18.
// Copyright © 2018 Holmusk. All rights reserved.
//
import HMReactiveRedux
import HMRequestFramework
import RxDataSources
import RxSwift
import SwiftFP
import SwiftUIUtilities
import UIKit
public final class UserProfileVC: UIViewController {
public typealias Section = SectionModel<String,UserInformation>
public typealias DataSource = RxTableViewSectionedReloadDataSource<Section>
@IBOutlet fileprivate weak var nameLbl: UILabel!
@IBOutlet fileprivate weak var ageLbl: UILabel!
@IBOutlet fileprivate weak var visibleLbl: UILabel!
@IBOutlet fileprivate weak var tableView: UITableView!
@IBOutlet fileprivate weak var persistBtn: UIButton!
fileprivate var insertUserBtn: UIBarButtonItem? {
return navigationItem.rightBarButtonItem
}
fileprivate let disposeBag = DisposeBag()
fileprivate let decorator = UserProfileVCDecorator()
public var viewModel: UserProfileViewModel?
override public func viewDidLoad() {
super.viewDidLoad()
setupViews(self)
bindViewModel(self)
}
}
extension UserProfileVC: UITableViewDelegate {
public func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat {
return 1
}
public func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
public func tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = .black
return view
}
public func tableView(_ tableView: UITableView,
viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
}
public extension UserProfileVC {
fileprivate func setupViews(_ controller: UserProfileVC) {
guard let tableView = controller.tableView else { return }
tableView.registerNib(UserTextCell.self)
controller.navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Insert new user",
style: .done,
target: nil,
action: nil)
}
fileprivate func setupDataSource(_ controller: UserProfileVC) -> DataSource {
let dataSource = DataSource(configureCell: {[weak controller] in
if let controller = controller {
return controller.configureCells($0, $1, $2, $3, controller)
} else {
return UITableViewCell()
}
})
dataSource.canMoveRowAtIndexPath = {(_, _) in false}
dataSource.canEditRowAtIndexPath = {(_, _) in false}
return dataSource
}
fileprivate func configureCells(_ source: TableViewSectionedDataSource<Section>,
_ tableView: UITableView,
_ indexPath: IndexPath,
_ item: Section.Item,
_ controller: UserProfileVC)
-> UITableViewCell
{
guard let vm = controller.viewModel else { return UITableViewCell() }
let decorator = controller.decorator
if
let cell = tableView.deque(UserTextCell.self, at: indexPath),
let cm = vm.vmForUserTextCell(item)
{
cell.viewModel = cm
cell.decorate(decorator, item)
return cell
} else {
return UITableViewCell()
}
}
}
public extension UserProfileVC {
fileprivate func bindViewModel(_ controller: UserProfileVC) {
guard
let vm = controller.viewModel,
let tableView = controller.tableView,
let insertUserBtn = controller.insertUserBtn,
let persistBtn = controller.persistBtn,
let nameLbl = controller.nameLbl,
let ageLbl = controller.ageLbl,
let visibleLbl = controller.visibleLbl
else {
return
}
vm.setupBindings()
let disposeBag = controller.disposeBag
let dataSource = controller.setupDataSource(controller)
tableView.rx.setDelegate(controller).disposed(by: disposeBag)
Observable.just(UserInformation.allValues())
.map({SectionModel(model: "", items: $0)})
.map({[$0]})
.observeOnMain()
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
vm.userNameStream()
.mapNonNilOrElse({$0.value}, "No information yet")
.observeOnMain()
.bind(to: nameLbl.rx.text)
.disposed(by: disposeBag)
vm.userAgeStream()
.mapNonNilOrElse({$0.value}, "No information yet")
.observeOnMain()
.bind(to: ageLbl.rx.text)
.disposed(by: disposeBag)
vm.userVisibilityStream()
.mapNonNilOrElse({$0.value}, "No information yet")
.observeOnMain()
.bind(to: visibleLbl.rx.text)
.disposed(by: disposeBag)
insertUserBtn.rx.tap
.throttle(0.3, scheduler: MainScheduler.instance)
.bind(to: vm.insertUserTrigger())
.disposed(by: disposeBag)
persistBtn.rx.tap
.throttle(0.3, scheduler: MainScheduler.instance)
.bind(to: vm.persistDataTrigger())
.disposed(by: disposeBag)
}
}
public struct UserProfileVCDecorator: UserTextCellDecoratorType {
public func inputFieldKeyboard(_ info: UserInformation) -> UIKeyboardType {
switch info {
case .age: return .numberPad
case .name: return .default
}
}
}
public struct UserProfileModel {
fileprivate let provider: SingletonType
public init(_ provider: SingletonType) {
self.provider = provider
}
public func dbUserStream() -> Observable<Try<User>> {
return provider.trackedObjectManager.dbUserStream()
}
public func updateUserInDB(_ user: Try<User>) -> Observable<Try<Void>> {
let requestManager = provider.dbRequestManager
let prev = user.map({[$0]})
let qos: DispatchQoS.QoSClass = .background
return requestManager.upsertInMemory(prev, qos).map({$0.map({_ in})})
}
public func persistToDB<Prev>(_ prev: Try<Prev>) -> Observable<Try<Void>> {
let requestManager = provider.dbRequestManager
let qos: DispatchQoS.QoSClass = .background
return requestManager.persistToDB(prev, qos)
}
public func userName(_ user: User) -> String {
return "Name: \(user.name.getOrElse(""))"
}
public func userAge(_ user: User) -> String {
return "Age: \(user.age.getOrElse(0))"
}
public func userVisibility(_ user: User) -> String {
return "Visibility: \(user.visible.map({$0.boolValue}).getOrElse(false))"
}
}
public struct UserProfileViewModel {
fileprivate let provider: SingletonType
fileprivate let model: UserProfileModel
fileprivate let disposeBag: DisposeBag
fileprivate let insertUser: PublishSubject<Void>
fileprivate let persistData: PublishSubject<Void>
public init(_ provider: SingletonType, _ model: UserProfileModel) {
self.provider = provider
self.model = model
disposeBag = DisposeBag()
insertUser = PublishSubject()
persistData = PublishSubject()
}
public func setupBindings() {
let provider = self.provider
let disposeBag = self.disposeBag
let model = self.model
let actionTrigger = provider.reduxStore.actionTrigger()
let insertTriggered = userOnInsertTriggered().share(replay: 1)
let insertPerformed = insertTriggered
.map(Try.success)
.flatMapLatest({model.updateUserInDB($0)})
.share(replay: 1)
let persistTriggered = persistDataStream().share(replay: 1)
let persistPerformed = persistTriggered
.map(Try.success)
.flatMapLatest({model.persistToDB($0)})
.share(replay: 1)
Observable<Error>
.merge(insertPerformed.mapNonNilOrEmpty({$0.error}),
persistPerformed.mapNonNilOrEmpty({$0.error}))
.map(GeneralReduxAction.Error.Display.updateShowError)
.observeOnMain()
.bind(to: actionTrigger)
.disposed(by: disposeBag)
Observable<Bool>
.merge(insertTriggered.map({_ in true}),
insertPerformed.map({_ in false}),
persistTriggered.map({_ in true}),
persistPerformed.map({_ in false}))
.map(GeneralReduxAction.Progress.Display.updateShowProgress)
.observeOnMain()
.bind(to: actionTrigger)
.disposed(by: disposeBag)
}
public func vmForUserTextCell(_ info: UserInformation) -> UserTextCellViewModel? {
let provider = self.provider
switch info {
case .age:
let model = UserAgeTextCellModel(provider)
return UserTextCellViewModel(provider, model)
case .name:
let model = UserNameTextCellModel(provider)
return UserTextCellViewModel(provider, model)
}
}
public func userNameStream() -> Observable<Try<String>> {
let model = self.model
return model.dbUserStream().map({$0.map({model.userName($0)})})
}
public func userAgeStream() -> Observable<Try<String>> {
let model = self.model
return model.dbUserStream().map({$0.map({model.userAge($0)})})
}
public func userVisibilityStream() -> Observable<Try<String>> {
let model = self.model
return model.dbUserStream().map({$0.map({model.userVisibility($0)})})
}
public func insertUserTrigger() -> AnyObserver<Void> {
return insertUser.asObserver()
}
public func insertUserStream() -> Observable<Void> {
return insertUser.asObservable()
}
public func userOnInsertTriggered() -> Observable<User> {
return insertUserStream().map({User.builder()
.with(name: "Hai Pham - \(String.random(withLength: 5))")
.with(id: UUID().uuidString)
.with(age: NSNumber(value: Int.randomBetween(10, 99)))
.with(visible: NSNumber(value: true))
.build()
})
}
public func persistDataTrigger() -> AnyObserver<Void> {
return persistData.asObserver()
}
public func persistDataStream() -> Observable<Void> {
return persistData.asObservable()
}
}
| apache-2.0 |
rastogigaurav/mTV | mTV/mTVTests/ViewModels/HomeViewModelTest.swift | 1 | 1566 | //
// HomeViewModelTest.swift
// mTV
//
// Created by Gaurav Rastogi on 6/25/17.
// Copyright © 2017 Gaurav Rastogi. All rights reserved.
//
import XCTest
@testable import mTV
class HomeViewModelTest: XCTestCase {
let displayMovies:DisplayMoviesMock = DisplayMoviesMock()
var viewModel:HomeViewModel?
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
self.viewModel = HomeViewModel(with: displayMovies)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// func testFetchMovies(){
// let expectedResult:XCTestExpectation = expectation(description: "Expected to fetch various maovies from Server and Populate them")
// viewModel?.fetchMovies()
// viewModel?.reloadSection = {(section) in
// XCTAssertTrue(self.displayMovies.displayMoviesIsCalled)
// }
//
// self.waitForExpectations(timeout: 10.0) { (error) in
// if let _ = error{
// XCTFail("Failed to fetch movies from TMDB and display them")
// }
// }
// expectedResult.fulfill()
// }
func testTitleForSection(){
let indexPath = IndexPath(row: 0, section: MovieSections.topRated.rawValue)
let title = viewModel?.titleForSection(indexPath:indexPath)
XCTAssertEqual(title, "Top Rated")
}
}
| mit |
gbmksquare/SilentAPNS-Test | SilentAPNS-Test/SilentAPNS-Test/view controller/MainCell.swift | 1 | 479 | //
// MainCell.swift
// SilentAPNS-Test
//
// Created by 구범모 on 2015. 7. 21..
// Copyright (c) 2015년 gbmKSquare. All rights reserved.
//
import UIKit
class MainCell: UITableViewCell {
@IBOutlet weak var identifierLabel: UILabel!
@IBOutlet weak var intervalLabel: UILabel!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var sentLabel: UILabel!
@IBOutlet weak var receivedLabel: UILabel!
@IBOutlet weak var percentageLabel: UILabel!
}
| mit |
loganSims/wsdot-ios-app | wsdot/MyRouteCamerasViewController.swift | 2 | 2522 | //
// MyRouteCameras.swift
// WSDOT
//
// Copyright (c) 2019 Washington State Department of Transportation
//
// 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 UIKit
import RealmSwift
import SafariServices
class MyRouteCamerasViewController: CameraClusterViewController {
var route: MyRouteItem!
override func viewDidLoad() {
super.viewDidLoad()
loadCamerasOnRoute(force: true)
}
func loadCamerasOnRoute(force: Bool){
if route != nil {
let serviceGroup = DispatchGroup();
requestCamerasUpdate(force, serviceGroup: serviceGroup)
serviceGroup.notify(queue: DispatchQueue.main) {
if !self.route.foundCameras {
_ = MyRouteStore.getNearbyCameraIds(forRoute: self.route)
}
let nearbyCameras = CamerasStore.getCamerasByID(Array(self.route.cameraIds))
self.cameraItems.removeAll()
self.cameraItems.append(contentsOf: nearbyCameras)
self.tableView.reloadData()
if self.cameraItems.count == 0 {
self.tableView.isHidden = true
} else {
self.tableView.isHidden = false
}
}
}
}
fileprivate func requestCamerasUpdate(_ force: Bool, serviceGroup: DispatchGroup) {
serviceGroup.enter()
CamerasStore.updateCameras(force, completion: { error in
if (error != nil) {
serviceGroup.leave()
DispatchQueue.main.async {
AlertMessages.getConnectionAlert(backupURL: nil)
}
}
serviceGroup.leave()
})
}
}
| gpl-3.0 |
danieltskv/swift-memory-game | MemoryGame/MemoryGame/Model/MemoryGame.swift | 1 | 3602 | //
// MemoryGameController.swift
// MemoryGame
//
// Created by Daniel Tsirulnikov on 19.3.2016.
// Copyright © 2016 Daniel Tsirulnikov. All rights reserved.
//
import Foundation
import UIKit.UIImage
// MARK: - MemoryGameDelegate
protocol MemoryGameDelegate {
func memoryGameDidStart(game: MemoryGame)
func memoryGame(game: MemoryGame, showCards cards: [Card])
func memoryGame(game: MemoryGame, hideCards cards: [Card])
func memoryGameDidEnd(game: MemoryGame, elapsedTime: NSTimeInterval)
}
// MARK: - MemoryGame
class MemoryGame {
// MARK: - Properties
static var defaultCardImages:[UIImage] = [
UIImage(named: "brand1")!,
UIImage(named: "brand2")!,
UIImage(named: "brand3")!,
UIImage(named: "brand4")!,
UIImage(named: "brand5")!,
UIImage(named: "brand6")!
];
var cards:[Card] = [Card]()
var delegate: MemoryGameDelegate?
var isPlaying: Bool = false
private var cardsShown:[Card] = [Card]()
private var startTime:NSDate?
var numberOfCards: Int {
get {
return cards.count
}
}
var elapsedTime : NSTimeInterval {
get {
guard startTime != nil else {
return -1
}
return NSDate().timeIntervalSinceDate(startTime!)
}
}
// MARK: - Methods
func newGame(cardsData:[UIImage]) {
cards = randomCards(cardsData)
startTime = NSDate.init()
isPlaying = true
delegate?.memoryGameDidStart(self)
}
func stopGame() {
isPlaying = false
cards.removeAll()
cardsShown.removeAll()
startTime = nil
}
func didSelectCard(card: Card?) {
guard let card = card else { return }
delegate?.memoryGame(self, showCards: [card])
if unpairedCardShown() {
let unpaired = unpairedCard()!
if card.equals(unpaired) {
cardsShown.append(card)
} else {
let unpairedCard = cardsShown.removeLast()
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.delegate?.memoryGame(self, hideCards:[card, unpairedCard])
}
}
} else {
cardsShown.append(card)
}
if cardsShown.count == cards.count {
finishGame()
}
}
func cardAtIndex(index: Int) -> Card? {
if cards.count > index {
return cards[index]
} else {
return nil
}
}
func indexForCard(card: Card) -> Int? {
for index in 0...cards.count-1 {
if card === cards[index] {
return index
}
}
return nil
}
private func finishGame() {
isPlaying = false
delegate?.memoryGameDidEnd(self, elapsedTime: elapsedTime)
}
private func unpairedCardShown() -> Bool {
return cardsShown.count % 2 != 0
}
private func unpairedCard() -> Card? {
let unpairedCard = cardsShown.last
return unpairedCard
}
private func randomCards(cardsData:[UIImage]) -> [Card] {
var cards = [Card]()
for i in 0...cardsData.count-1 {
let card = Card.init(image: cardsData[i])
cards.appendContentsOf([card, Card.init(card: card)])
}
cards.shuffle()
return cards
}
} | apache-2.0 |
CleanCocoa/FatSidebar | FatSidebar/FatSidebarItem.swift | 1 | 19052 | // Copyright © 2017 Christian Tietze. All rights reserved. Distributed under the MIT License.
import Cocoa
extension NSLayoutConstraint {
func prioritized(_ priority: Float) -> NSLayoutConstraint {
self.priority = NSLayoutConstraint.Priority(rawValue: priority)
return self
}
}
extension NSScrollView {
var scrolledY: CGFloat { return self.contentView.bounds.origin.y }
}
public class FatSidebarItem: NSView {
public enum Style {
/// Displays label below image
case regular
/// Displays image only, label in overlay view on hover
case small(iconSize: CGFloat, padding: CGFloat)
public var supportsHovering: Bool {
switch self {
case .regular: return false
case .small: return true
}
}
}
public let callback: ((FatSidebarItem) -> Void)?
public var selectionHandler: ((FatSidebarItem) -> Void)?
public var editHandler: ((FatSidebarItem) -> Void)?
public var doubleClickHandler: ((FatSidebarItem) -> Void)?
public var animated: Bool
let label: NSTextField
public var title: String {
set { label.stringValue = newValue }
get { return label.stringValue }
}
let imageView: NSImageView
public var image: NSImage? {
set { imageView.image = newValue }
get { return imageView.image }
}
public internal(set) var style: Style {
didSet {
layoutSubviews(style: style)
redraw()
}
}
public internal(set) var theme: FatSidebarTheme = DefaultTheme() {
didSet {
adjustLabelFont()
redraw()
}
}
convenience public init(
title: String,
image: NSImage? = nil,
shadow: NSShadow? = nil,
animated: Bool = false,
style: Style = .regular,
callback: ((FatSidebarItem) -> Void)?) {
let configuration = FatSidebarItemConfiguration(
title: title,
image: image,
shadow: shadow,
animated: animated,
callback: callback)
self.init(configuration: configuration, style: style)
}
required public init(configuration: FatSidebarItemConfiguration, style: Style) {
self.style = style
self.label = NSTextField.newWrappingLabel(
title: configuration.title,
controlSize: .small)
self.label.alignment = .center
self.imageView = NSImageView()
self.imageView.wantsLayer = true
self.imageView.shadow = configuration.shadow
self.imageView.image = configuration.image
self.imageView.imageScaling = .scaleProportionallyUpOrDown
self.animated = configuration.animated
self.callback = configuration.callback
super.init(frame: NSZeroRect)
self.translatesAutoresizingMaskIntoConstraints = false
layoutSubviews(style: style)
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) not implemented")
}
fileprivate func layoutSubviews(style: Style) {
resetSubviews()
switch style {
case .regular: layoutRegularSubviews()
case let .small(iconSize: iconSize, padding: padding):
layoutSmallSubviews(iconSize: iconSize, padding: padding)
}
}
private var topSpacing: NSView?
private var bottomSpacing: NSView?
private var imageContainer: NSView?
private var styleLayoutConstraints: [NSLayoutConstraint] = []
private func resetSubviews() {
self.removeConstraints(styleLayoutConstraints)
styleLayoutConstraints = []
imageContainer?.removeFromSuperview()
imageView.removeFromSuperview()
label.removeFromSuperview()
topSpacing?.removeFromSuperview()
bottomSpacing?.removeFromSuperview()
}
fileprivate func layoutRegularSubviews() {
self.imageView.translatesAutoresizingMaskIntoConstraints = false
self.imageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
self.imageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
self.addSubview(self.imageView)
self.label.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.label)
let topSpacing = NSView()
topSpacing.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(topSpacing)
self.topSpacing = topSpacing
let topSpacingConstraints = [
// 1px width, horizontally centered
NSLayoutConstraint(item: topSpacing, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 1),
NSLayoutConstraint(item: topSpacing, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0),
// 20% size
NSLayoutConstraint(item: topSpacing, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0.2, constant: 1)
]
self.styleLayoutConstraints.append(contentsOf: topSpacingConstraints)
self.addConstraints(topSpacingConstraints)
let bottomSpacing = NSView()
bottomSpacing.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(bottomSpacing)
self.bottomSpacing = bottomSpacing
let bottomSpacingConstraints = [
// 1px width, horizontally centered
NSLayoutConstraint(item: bottomSpacing, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 1),
NSLayoutConstraint(item: bottomSpacing, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0),
// 30% size
NSLayoutConstraint(item: bottomSpacing, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0.3, constant: 1)
]
self.styleLayoutConstraints.append(contentsOf: bottomSpacingConstraints)
self.addConstraints(bottomSpacingConstraints)
let viewsDict: [String : Any] = [
"topSpace" : topSpacing,
"imageView" : self.imageView,
"label" : self.label,
"bottomSpace" : bottomSpacing
]
let mainConstraints = [
NSLayoutConstraint.constraints(
withVisualFormat: "V:|[topSpace][imageView][bottomSpace]|",
options: [], metrics: nil, views: viewsDict),
NSLayoutConstraint.constraints(
withVisualFormat: "V:[label]-(>=4@1000)-|",
options: [], metrics: nil, views: viewsDict),
NSLayoutConstraint.constraints(
withVisualFormat: "V:[label]-(4@250)-|",
options: [], metrics: nil, views: viewsDict),
]
.flattened()
.appending(NSLayoutConstraint(item: self.label, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
.appending(NSLayoutConstraint(item: self.label, attribute: .centerY, relatedBy: .equal, toItem: bottomSpacing, attribute: .centerY, multiplier: 0.95, constant: 0).prioritized(250))
.appending(NSLayoutConstraint(item: self.imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
self.addConstraints(mainConstraints)
self.styleLayoutConstraints.append(contentsOf: mainConstraints)
label.setNeedsDisplay()
}
public override func layout() {
if case .regular = self.style {
self.label.preferredMaxLayoutWidth = NSWidth(self.label.alignmentRect(forFrame: self.frame))
}
super.layout()
}
fileprivate func layoutSmallSubviews(iconSize: CGFloat, padding: CGFloat) {
self.label.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(label)
let imageContainer = NSView()
imageContainer.identifier = .init(rawValue: "imageContainer")
imageContainer.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(imageContainer)
self.imageContainer = imageContainer
self.imageView.translatesAutoresizingMaskIntoConstraints = false
self.imageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
self.imageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
imageContainer.addSubview(self.imageView)
let viewsDict: [String : Any] = [
"container" : imageContainer,
"imageView" : self.imageView,
"label" : self.label,
]
let mainConstraints: [NSLayoutConstraint] = [
NSLayoutConstraint.constraints(
withVisualFormat: "V:|[container]|",
options: [], metrics: nil, views: viewsDict),
NSLayoutConstraint.constraints(
withVisualFormat: "H:|[container]-1-[label]", // Open to the right
options: [], metrics: nil, views: viewsDict),
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-(\(padding))-[imageView]-(\(padding))-|",
options: [], metrics: nil, views: viewsDict)
]
.flattened()
.appending(NSLayoutConstraint(item: self.label, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
.appending(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: iconSize))
.appending(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1, constant: 0))
self.addConstraints(mainConstraints)
self.styleLayoutConstraints.append(contentsOf: mainConstraints)
imageContainer.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-(\(padding))-[imageView]-(\(padding))-|",
options: [], metrics: nil, views: viewsDict))
}
// MARK: - Custom Drawing
fileprivate func adjustLabelFont() {
self.label.font = theme.itemStyle.font ?? label.fittingSystemFont()
}
fileprivate func redraw() {
self.needsDisplay = true
self.label.textColor = theme.itemStyle.labelColor
.color(isHighlighted: self.isHighlighted, isSelected: self.isSelected)
self.label.cell?.backgroundStyle = theme.itemStyle.background.backgroundStyle
}
var borderWidth: CGFloat = 1
public override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
drawBackground(dirtyRect)
drawBorders(dirtyRect)
}
fileprivate func drawBackground(_ dirtyRect: NSRect) {
theme.itemStyle.background.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill()
dirtyRect.fill()
}
fileprivate func drawBorders(_ dirtyRect: NSRect) {
if let leftBorderColor = theme.itemStyle.borders.left {
let border = NSRect(x: 0, y: 0, width: borderWidth, height: dirtyRect.height)
leftBorderColor.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill()
border.fill()
}
if let topBorderColor = theme.itemStyle.borders.top {
let border = NSRect(x: 0, y: dirtyRect.maxY - borderWidth, width: dirtyRect.width, height: borderWidth)
topBorderColor.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill()
border.fill()
}
if let rightBorderColor = theme.itemStyle.borders.right {
let border = NSRect(x: dirtyRect.maxX - borderWidth, y: 0, width: borderWidth, height: dirtyRect.height)
rightBorderColor.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill()
border.fill()
}
if let bottomBorderColor = theme.itemStyle.borders.bottom {
let border = NSRect(x: 0, y: dirtyRect.minY, width: dirtyRect.width, height: borderWidth)
bottomBorderColor.color(isHighlighted: isHighlighted, isSelected: isSelected).setFill()
border.fill()
}
}
// MARK: - Interaction
public internal(set) var isSelected = false {
didSet {
redraw()
overlay?.isSelected = isSelected
}
}
public fileprivate(set) var isHighlighted = false {
didSet {
redraw()
}
}
// MARK: Dragging
/// Shared flag to make sure that when some item is being clicked, moving
/// the mouse does not trigger hover effects on adjacent items.
private static var startedDragging = false
struct Dragging {
static let threshold: TimeInterval = 0.4
let initialEvent: NSEvent
var dragTimer: Timer?
var isDragging = false
}
var dragging: Dragging?
public override func mouseDown(with event: NSEvent) {
isHighlighted = true
let dragTimer = Timer.scheduledTimer(
timeInterval: Dragging.threshold,
target: self,
selector: #selector(mouseHeld(_:)),
userInfo: event,
repeats: false)
self.dragging = Dragging(
initialEvent: event,
dragTimer: dragTimer,
isDragging: false)
FatSidebarItem.startedDragging = true
}
@objc func mouseHeld(_ timer: Timer) {
self.dragging?.isDragging = true
guard let event = timer.userInfo as? NSEvent,
let target = superview as? DragViewContainer
else { return }
target.reorder(subview: self, event: event)
}
public override func mouseUp(with event: NSEvent) {
FatSidebarItem.startedDragging = false
isHighlighted = false
defer {
dragging?.dragTimer?.invalidate()
dragging = nil
}
if event.clickCount == 2 {
doubleClickHandler?(self)
return
}
guard let dragging = dragging,
!dragging.isDragging
else { return }
selectionHandler?(self)
sendAction()
}
public func sendAction() {
callback?(self)
}
/// - note: Can be used as action from Interface Builder.
@IBAction public func editFatSidebarItem(_ sender: Any?) {
editHandler?(self)
}
/// - note: Can be used as action from Interface Builder.
@IBAction public func removeFatSidebarItem(_ sender: Any?) {
// Forward event from here because if the sidebar
// would receive the NSMenuItem action, it wouldn't
// be able to figure out the affected item.
guard let sidebar = self.superview as? FatSidebarView else {
preconditionFailure("Expected superview to be FatSidebarView")
}
sidebar.removeItem(self)
}
// MARK: - Mouse Hover
private var overlay: FatSidebarItemOverlay? {
didSet {
guard overlay == nil,
let oldOverlay = oldValue
else { return }
NotificationCenter.default.removeObserver(oldOverlay)
}
}
private var isDisplayingOverlay: Bool { return overlay != nil }
public override func mouseEntered(with event: NSEvent) {
if FatSidebarItem.startedDragging { return }
if isDisplayingOverlay { return }
NotificationCenter.default.post(
name: FatSidebarItemOverlay.hoverStarted,
object: self)
guard style.supportsHovering else { return }
showHoverItem()
}
private func showHoverItem() {
guard let superview = self.superview,
let windowContentView = self.window?.contentView
else { return }
self.overlay = {
let overlayFrame = superview.convert(self.frame, to: nil)
let overlay = FatSidebarItemOverlay(
title: self.title,
image: self.image,
style: self.style,
callback: self.callback)
overlay.wantsLayer = true
overlay.layer?.zPosition = CGFloat(Float.greatestFiniteMagnitude)
overlay.frame = overlayFrame
overlay.base = self
overlay.theme = self.theme
overlay.isSelected = self.isSelected
overlay.translatesAutoresizingMaskIntoConstraints = true
overlay.editHandler = { [weak self] _ in
guard let item = self else { return }
item.editHandler?(item)
}
overlay.doubleClickHandler = { [weak self] _ in
guard let item = self else { return }
item.doubleClickHandler?(item)
}
overlay.selectionHandler = { [weak self] _ in
guard let item = self else { return }
item.selectionHandler?(item)
}
overlay.overlayFinished = { [weak self] in self?.overlay = nil }
NotificationCenter.default.addObserver(
overlay,
selector: #selector(FatSidebarItemOverlay.hoverDidStart),
name: FatSidebarItemOverlay.hoverStarted,
object: nil)
if let scrollView = enclosingScrollView {
overlay.setupScrollSyncing(scrollView: scrollView)
}
windowContentView.addSubview(
overlay,
positioned: .above,
relativeTo: windowContentView.subviews.first ?? self)
(animated
? overlay.animator()
: overlay)
.frame = {
// Proportional right spacing looks best in all circumstances:
let rightPadding: CGFloat = self.frame.height * 0.1
var frame = overlayFrame
frame.size.width += self.label.frame.width + rightPadding
return frame
}()
return overlay
}()
}
private var trackingArea: NSTrackingArea?
public override func updateTrackingAreas() {
super.updateTrackingAreas()
if let oldTrackingArea = trackingArea { self.removeTrackingArea(oldTrackingArea) }
let newTrackingArea = NSTrackingArea(
rect: self.bounds,
options: [.mouseEnteredAndExited, .activeInKeyWindow],
owner: self,
userInfo: nil)
self.addTrackingArea(newTrackingArea)
self.trackingArea = newTrackingArea
}
}
extension Array {
func appending(_ newElement: Element) -> [Element] {
var result = self
result.append(newElement)
return result
}
}
extension Array where Element: Sequence {
func flattened() -> [Element.Element] {
return self.flatMap { $0 }
}
}
| mit |
OscarSwanros/swift | tools/SwiftSyntax/SwiftSyntax.swift | 5 | 2090 | //===--------------- SwiftLanguage.swift - Swift Syntax Library -----------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This file provides main entry point into the Syntax library.
//===----------------------------------------------------------------------===//
import Foundation
/// A list of possible errors that could be encountered while parsing a
/// Syntax tree.
public enum ParserError: Error {
case swiftcFailed(Int, String)
case invalidFile
}
extension Syntax {
/// Parses the Swift file at the provided URL into a full-fidelity `Syntax`
/// tree.
/// - Parameter url: The URL you wish to parse.
/// - Returns: A top-level Syntax node representing the contents of the tree,
/// if the parse was successful.
/// - Throws: `ParseError.couldNotFindSwiftc` if `swiftc` could not be
/// located, `ParseError.invalidFile` if the file is invalid.
/// FIXME: Fill this out with all error cases.
public static func parse(_ url: URL) throws -> SourceFileSyntax {
let swiftcRunner = try SwiftcRunner(sourceFile: url)
let result = try swiftcRunner.invoke()
guard result.wasSuccessful else {
throw ParserError.swiftcFailed(result.exitCode, result.stderr)
}
let decoder = JSONDecoder()
let raw = try decoder.decode([RawSyntax].self, from: result.stdoutData)
let topLevelNodes = raw.map { Syntax.fromRaw($0) }
let eof = topLevelNodes.last! as! TokenSyntax
let decls = Array(topLevelNodes.dropLast()) as! [DeclSyntax]
let declList = SyntaxFactory.makeDeclList(decls)
return SyntaxFactory.makeSourceFile(topLevelDecls: declList,
eofToken: eof)
}
}
| apache-2.0 |
OscarSwanros/swift | benchmark/single-source/DropWhile.swift | 2 | 7022 | //===--- DropWhile.swift --------------------------------------*- 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
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to DropWhile.swift.gyb and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
import TestsUtils
let sequenceCount = 4096
let dropCount = 1024
let suffixCount = sequenceCount - dropCount
let sumCount = suffixCount * (2 * sequenceCount - suffixCount - 1) / 2
public let DropWhile = [
BenchmarkInfo(
name: "DropWhileCountableRange",
runFunction: run_DropWhileCountableRange,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileSequence",
runFunction: run_DropWhileSequence,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySequence",
runFunction: run_DropWhileAnySequence,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySeqCntRange",
runFunction: run_DropWhileAnySeqCntRange,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySeqCRangeIter",
runFunction: run_DropWhileAnySeqCRangeIter,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnyCollection",
runFunction: run_DropWhileAnyCollection,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileArray",
runFunction: run_DropWhileArray,
tags: [.validation, .api, .Array]),
BenchmarkInfo(
name: "DropWhileCountableRangeLazy",
runFunction: run_DropWhileCountableRangeLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileSequenceLazy",
runFunction: run_DropWhileSequenceLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySequenceLazy",
runFunction: run_DropWhileAnySequenceLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySeqCntRangeLazy",
runFunction: run_DropWhileAnySeqCntRangeLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnySeqCRangeIterLazy",
runFunction: run_DropWhileAnySeqCRangeIterLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileAnyCollectionLazy",
runFunction: run_DropWhileAnyCollectionLazy,
tags: [.validation, .api]),
BenchmarkInfo(
name: "DropWhileArrayLazy",
runFunction: run_DropWhileArrayLazy,
tags: [.validation, .api]),
]
@inline(never)
public func run_DropWhileCountableRange(_ N: Int) {
let s = 0..<sequenceCount
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileSequence(_ N: Int) {
let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySequence(_ N: Int) {
let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySeqCntRange(_ N: Int) {
let s = AnySequence(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySeqCRangeIter(_ N: Int) {
let s = AnySequence((0..<sequenceCount).makeIterator())
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnyCollection(_ N: Int) {
let s = AnyCollection(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileArray(_ N: Int) {
let s = Array(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileCountableRangeLazy(_ N: Int) {
let s = (0..<sequenceCount).lazy
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileSequenceLazy(_ N: Int) {
let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySequenceLazy(_ N: Int) {
let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySeqCntRangeLazy(_ N: Int) {
let s = (AnySequence(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnySeqCRangeIterLazy(_ N: Int) {
let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileAnyCollectionLazy(_ N: Int) {
let s = (AnyCollection(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropWhileArrayLazy(_ N: Int) {
let s = (Array(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.drop(while: {$0 < dropCount} ) {
result += element
}
CheckResults(result == sumCount)
}
}
| apache-2.0 |
ShmilyLin/WarmImagePreview | WarmImagePreview/WarmImagePreview/Main/Sections/Windows/WIPSettingsWindowsController.swift | 1 | 446 | //
// WIPSettingsWindowsController.swift
// WarmImagePreview
//
// Created by LinJia on 2017/10/13.
// Copyright © 2017年 warm. All rights reserved.
//
import Cocoa
class WIPSettingsWindowsController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
}
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/00662-swift-typebase-isequal.swift | 1 | 205 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
( " " " "
protocol c {
func a<h : a
| mit |
RDCEP/ggcmi | bin/biascorr/biascorrect.swift | 1 | 683 | type file;
app (file o) get_inputs (string params) {
inputs params stdout = @o;
}
app (file o) biascorrect(string inputfile, string reffile, string agglvl, string outdir, string params) {
biascorrect "-i" inputfile "-r" reffile "-a" agglvl "-o" outdir "-p" params stdout = @o;
}
type Inputs {
string inputfile;
string reffile;
string agglvl;
string outdir;
}
file ff <"finder.out">;
string params = arg("params");
ff = get_inputs(params);
Inputs irao[] = readData(ff);
foreach i, idx in irao {
file logfile <single_file_mapper; file = strcat("logs/log_", idx, ".txt")>;
logfile = biascorrect(i.inputfile, i.reffile, i.agglvl, i.outdir, params);
}
| agpl-3.0 |
devroo/onTodo | Swift/OptionalChaining.playground/section-1.swift | 1 | 1219 | // Playground - noun: a place where people can play
import UIKit
/*
* 옵셔널 체인 (Optional Chaining)
*/
/*
스위프트(Swift)의 옵셔널 체인이 오브젝티브씨(Objective-C)에 있는 nil에 메시지 보내기와 유사하다. 그러나, 모든 타입(any type)에서 동작하고, 성공, 실패 여부를 확인할 수 있다는 점에서 차이가 있다.
*/
// 강제 랩핑 해제(Forced Unwrapping) 대안으로써 옵셔널 체인
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
let john = Person()
//let roomCount = john.residence!.numberOfRooms
// 강제 랩핑 에러 (nil이기떄문에)
if let roomCount = john.residence?.numberOfRooms {
println("John's residence has \(roomCount) room(s).")
} else {
println("Unable to retrieve the number of rooms.")
}
// prints "Unable to retrieve the number of rooms."
john.residence = Residence()
if let roomCount = john.residence?.numberOfRooms {
println("John's residence has \(roomCount) room(s).")
} else {
println("Unable to retrieve the number of rooms.")
}
// prints "John's residence has 1 room(s)."
// 옵셔널 체인을 위한 모델(Model) 클래스(Class) 선언
| gpl-2.0 |
bingoogolapple/SwiftNote-PartTwo | XML块代码解析/XML和JSON/ViewController.swift | 1 | 7260 | //
// ViewController.swift
// XML和JSON
//
// Created by bingoogol on 14/10/7.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
let CELL_ID = "MyCell"
var tableView:UITableView!
var model:Model = Model()
var dataList:NSMutableArray = NSMutableArray()
var currentVideo:Model!
override func loadView() {
self.view = UIView(frame: UIScreen.mainScreen().bounds)
var frame = UIScreen.mainScreen().applicationFrame
tableView = UITableView(frame: CGRectMake(0, frame.origin.y, frame.width, frame.height - 44), style: UITableViewStyle.Plain)!
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = 80
self.view.addSubview(tableView)
var toolBar = UIToolbar(frame: CGRectMake(0, tableView.bounds.height + frame.origin.y, frame.width, 44))
var item1 = UIBarButtonItem(title: "load JSON", style: UIBarButtonItemStyle.Done, target: self, action: Selector("loadJSON"))
var item2 = UIBarButtonItem(title: "load XML", style: UIBarButtonItemStyle.Done, target: self, action: Selector("loadXML"))
var item3 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
toolBar.items = [item3,item1,item3,item2,item3]
self.view.addSubview(toolBar)
}
func loadJSON() {
var urlStr = "http://localhost:7777/swift/test.json"
// 从web服务器直接加载数据
// 提示:NSData本身具有同步方法,但是在实际开发中,不要使用此方法。在使用NSData的同步方法时,无法指定超时时间,如果服务器连接不正常,会影响用户体验
// var data = NSData(contentsOfURL: NSURL(string: urlStr)!)
// var result = NSString(data: data!, encoding: NSUTF8StringEncoding)
// println(result)
// 1.建立NSURL
var url = NSURL(string: urlStr)
// 2.建立NSURLRequest
var request = NSURLRequest(URL: url!)
// 3.利用NSURLConnection的同步方法加载数据
var error : NSError?
var response : NSURLResponse?
var data = NSURLConnection.sendSynchronousRequest(request,returningResponse: &response,error: &error)
if data != nil {
handlerJsonData(data!)
} else if error == nil {
println("空数据")
} else {
println("错误\(error!.localizedDescription)")
}
}
func handlerJsonData(data:NSData) {
// 在处理网络数据时,不需要将NSData转换成NSString。仅用于跟踪处理
var result = NSString(data: data, encoding: NSUTF8StringEncoding)
// println(result!)
var error:NSError?
var array = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error) as NSArray
// 如果开发网络应用,可以将反序列化出来的对象保存到沙箱,以便后续开发使用
var docs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var path = (docs[0] as NSString).stringByAppendingPathComponent("json.plist")
array.writeToFile(path, atomically: true)
println(path)
}
func loadXML() {
// testExtension()
var urlStr = "http://localhost:7777/swift/test.xml"
// 1.建立NSURL
var url = NSURL(string: urlStr)
// 2.建立NSURLRequest
var request = NSURLRequest(URL: url!)
// 3.利用NSURLConnection的同步方法加载数据
var error : NSError?
var response : NSURLResponse?
var data = NSURLConnection.sendSynchronousRequest(request,returningResponse: &response,error: &error)
if data != nil {
handlerXmlDataXmlParser(data!)
} else if error == nil {
println("空数据")
} else {
println("错误\(error!.localizedDescription)")
}
}
func handlerXmlDataXmlParser(data:NSData) {
MyXMLParser().xmlParserWithData(data, startElementName: "video", startElementBlock: { (dict:NSDictionary) in
self.currentVideo = Model()
self.currentVideo.videoId = (dict["videoId"] as NSString).integerValue
}, endElementBlock: { (elementName:NSString, result:NSString) in
if elementName.isEqualToString("video") {
self.dataList.addObject(self.currentVideo)
} else if elementName.isEqualToString("name") {
self.currentVideo.name = result
} else if elementName.isEqualToString("length") {
self.currentVideo.length = result.integerValue
}
}, finishedParser: {
for model in self.dataList {
println("\((model as Model).name)")
}
}, errorParser: {
self.dataList.removeAllObjects()
self.currentVideo = nil
})
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID) as VideoCell!
if cell == nil {
cell = VideoCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: CELL_ID)
}
cell.textLabel?.text = "title"
cell.detailTextLabel?.text = "detail"
cell.label3.text = "11:11"
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
// 加载图片
// 正式开发时从数据集中获取获取model
var model = self.model
if model.cacheImage == nil {
// 异步加载时使用默认图片占位置,既能保证有图像,又能保证有地方
cell.imageView?.image = UIImage(named: "default.jpg")
loadImageAsync(indexPath)
} else {
cell.imageView?.image = model.cacheImage
}
// println("加载数据")
return cell
}
// 由于UITableViewCell是可重用的,为了避免用户频繁快速刷新表格,造成数据冲突,不能直接将UIImageView传入异步方法
// 正确地解决方法是:将表格行的indexPath传入异步方法,加载完成图像后,直接刷新指定行
func loadImageAsync(indexPath:NSIndexPath) {
// 正式开发时从数据集中获取mode,再获取url
var model = self.model
var imagePath = "http://localhost:7777/swift/hehe.jpg"
var imageUrl = NSURL(string: imagePath)!
var request = NSURLRequest(URL: imageUrl)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
model.cacheImage = UIImage(data: data)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Right)
}
}
} | apache-2.0 |
jkolb/midnightbacon | MidnightBacon/Modules/Submit/SegmentedControlHeader.swift | 1 | 3908 | //
// SegmentedControlHeader.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// 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 DrapierLayout
protocol SegmentedControlHeaderDelegate : class {
func numberOfSegmentsInSegmentedControlHeader(segmentedControlHeader: SegmentedControlHeader) -> Int
func selectedIndexOfSegmentedControlHeader(segmentedControlHeader: SegmentedControlHeader) -> Int
func segmentedControlHeader(segmentedControlHeader: SegmentedControlHeader, titleForSegmentAtIndex index: Int) -> String
}
class SegmentedControlHeader : UIView {
weak var delegate: SegmentedControlHeaderDelegate?
let segmentedControl = UISegmentedControl()
let insets = UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0)
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(segmentedControl)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubview(segmentedControl)
}
override func willMoveToWindow(newWindow: UIWindow?) {
super.willMoveToWindow(newWindow)
if newWindow == nil {
segmentedControl.removeAllSegments()
} else {
if let delegate = self.delegate {
let numberOfSegments = delegate.numberOfSegmentsInSegmentedControlHeader(self)
for var i = 0; i < numberOfSegments; ++i {
let title = delegate.segmentedControlHeader(self, titleForSegmentAtIndex: i)
segmentedControl.insertSegmentWithTitle(title, atIndex: i, animated: false)
}
segmentedControl.selectedSegmentIndex = delegate.selectedIndexOfSegmentedControlHeader(self)
addSubview(segmentedControl)
} else {
segmentedControl.removeAllSegments()
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = generateLayout(bounds)
segmentedControl.frame = layout.segmentedControlFrame
}
override func sizeThatFits(size: CGSize) -> CGSize {
let segmentedSize = segmentedControl.sizeThatFits(size)
let fitSize = CGSize(width: size.width, height: segmentedSize.height + insets.top + insets.bottom)
return fitSize
}
private struct ViewLayout {
let segmentedControlFrame: CGRect
}
private func generateLayout(bounds: CGRect) -> ViewLayout {
let segmentedControlFrame = segmentedControl.layout(
Left(equalTo: bounds.left(insets)),
Right(equalTo: bounds.right(insets)),
CenterY(equalTo: bounds.centerY(insets))
)
return ViewLayout(
segmentedControlFrame: segmentedControlFrame
)
}
}
| mit |
SoneeJohn/WWDC | WWDC/TrackColorView.swift | 2 | 1946 | //
// TrackColorView.swift
// WWDC
//
// Created by Guilherme Rambo on 11/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
final class TrackColorView: NSView {
private lazy var progressLayer: WWDCLayer = {
let l = WWDCLayer()
l.autoresizingMask = [.layerWidthSizable]
return l
}()
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
layer?.cornerRadius = 2
layer?.masksToBounds = true
progressLayer.frame = bounds
layer?.addSublayer(progressLayer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var hasValidProgress = false {
didSet {
needsLayout = true
}
}
var progress: Double = 0.5 {
didSet {
// hide when fully watched
alphaValue = progress >= Constants.watchedVideoRelativePosition ? 0 : 1
if hasValidProgress && progress < 1 {
layer?.borderWidth = 1
} else {
layer?.borderWidth = 0
}
needsLayout = true
}
}
var color: NSColor = .black {
didSet {
layer?.borderColor = color.cgColor
progressLayer.backgroundColor = color.cgColor
}
}
override var intrinsicContentSize: NSSize {
return NSSize(width: 4, height: -1)
}
override func layout() {
super.layout()
let progressHeight = hasValidProgress ? bounds.height * CGFloat(progress) : bounds.height
guard !progressHeight.isNaN && !progressHeight.isInfinite else { return }
let progressFrame = NSRect(x: 0, y: 0, width: bounds.width, height: progressHeight)
progressLayer.frame = progressFrame
}
override func makeBackingLayer() -> CALayer {
return WWDCLayer()
}
}
| bsd-2-clause |
v-andr/LakestoneCore | Source/AnyNumeric.swift | 1 | 1217 | //
// AnyNumeric
// LakestoneRealm
//
// Created by Taras Vozniuk on 10/13/16.
// Copyright © 2016 GeoThings. 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.
//
#if !COOPER
public protocol AnyNumeric {}
extension Int: AnyNumeric {}
extension UInt: AnyNumeric {}
extension Int8: AnyNumeric {}
extension UInt8: AnyNumeric {}
extension Int16: AnyNumeric {}
extension UInt16: AnyNumeric {}
extension Int32: AnyNumeric {}
extension UInt32: AnyNumeric {}
extension Int64: AnyNumeric {}
extension UInt64: AnyNumeric {}
extension Float: AnyNumeric {}
extension Double: AnyNumeric {}
extension Float80: AnyNumeric {}
#endif
| apache-2.0 |
rudkx/swift | test/IRGen/Inputs/resilient-class.swift | 1 | 84 | open class Base {
var x = 1
}
internal class SubClass : Base {
var y = 2
}
| apache-2.0 |
bamssong/ios-swift-sample | cocoapod/GoogleMap/GoogleMapUITests/GoogleMapUITests.swift | 1 | 1255 | //
// GoogleMapUITests.swift
// GoogleMapUITests
//
// Created by dev.bamssong on 2016. 1. 6..
// Copyright © 2016년 bamssong. All rights reserved.
//
import XCTest
class GoogleMapUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| apache-2.0 |
Onavoy/Torpedo | Torpedo/Classes/Runtime/Closures.swift | 1 | 976 | import Foundation
@inline(never) public func measureBlock(_ block: @escaping (() -> Void)) -> Double {
let begin = Date()
block()
let end = Date()
let timeTaken = end.timeIntervalSince1970 - begin.timeIntervalSince1970
return timeTaken
}
@inline(never) public func measureBlockAverage(repeatCount: Int, _ block: @escaping (() -> Void)) -> Double {
var results :[Double] = []
repeatCount.times { (currentIndex) in
results.append(measureBlock(block))
}
return DoubleUtils.average(results)
}
@discardableResult
@inline(never) public func measureBlockLog(_ closureName: String, _ block: @escaping (() -> Void)) -> Double {
let timeTaken = measureBlock(block)
if timeTaken < 1.0 {
let millsecondsTaken = timeTaken * 1000.0
print("\(closureName) took \(millsecondsTaken) milliseconds to execute")
} else {
print("\(closureName) took \(timeTaken) seconds to execute")
}
return timeTaken
}
| mit |
garywong89/PetStoreAPI | src/swift/SwaggerClient/Classes/Swaggers/APIs.swift | 2 | 2230 | // APIs.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class SwaggerClientAPI {
public static var basePath = "https://localhost"
public static var credential: NSURLCredential?
public static var customHeaders: [String:String] = [:]
static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
}
public class APIBase {
func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? {
let encoded: AnyObject? = encodable?.encodeToJSON()
if encoded! is [AnyObject] {
var dictionary = [String:AnyObject]()
for (index, item) in (encoded as! [AnyObject]).enumerate() {
dictionary["\(index)"] = item
}
return dictionary
} else {
return encoded as? [String:AnyObject]
}
}
}
public class RequestBuilder<T> {
var credential: NSURLCredential?
var headers: [String:String] = [:]
let parameters: [String:AnyObject]?
let isBody: Bool
let method: String
let URLString: String
/// Optional block to obtain a reference to the request's progress instance when available.
public var onProgressReady: ((NSProgress) -> ())?
required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) {
self.method = method
self.URLString = URLString
self.parameters = parameters
self.isBody = isBody
addHeaders(SwaggerClientAPI.customHeaders)
}
public func addHeaders(aHeaders:[String:String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}
public func execute(completion: (response: Response<T>?, error: ErrorType?) -> Void) { }
public func addHeader(name name: String, value: String) -> Self {
if !value.isEmpty {
headers[name] = value
}
return self
}
public func addCredential() -> Self {
self.credential = SwaggerClientAPI.credential
return self
}
}
protocol RequestBuilderFactory {
func getBuilder<T>() -> RequestBuilder<T>.Type
}
| apache-2.0 |
humeng12/DouYuZB | DouYuZB/DouYuZB/AppDelegate.swift | 1 | 2168 | //
// AppDelegate.swift
// DouYuZB
//
// Created by 胡猛 on 16/11/5.
// Copyright © 2016年 HuMeng. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UITabBar.appearance().tintColor = UIColor.orange;
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
rain2540/CustomActionSheet | Swift/CustomActionSheet/AppDelegate.swift | 1 | 2146 | //
// AppDelegate.swift
// CustomActionSheet
//
// Created by RAIN on 15/11/30.
// Copyright © 2015年 Smartech. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
dsonara/DSImageCache | DSImageCache/Classes/Core/ImagePrefetcher.swift | 1 | 10681 | //
// ImagePrefetcher.swift
// DSImageCache
//
// Created by Dipak Sonara on 29/03/17.
// Copyright © 2017 Dipak Sonara. All rights reserved.
import UIKit
/// Progress update block of prefetcher.
///
/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
/// - `completedResources`: An array of resources that are downloaded and cached successfully.
public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ())
/// Completion block of prefetcher.
///
/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
/// - `completedResources`: An array of resources that are downloaded and cached successfully.
public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ())
/// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
/// This is useful when you know a list of image resources and want to download them before showing.
public class ImagePrefetcher {
/// The maximum concurrent downloads to use when prefetching images. Default is 5.
public var maxConcurrentDownloads = 5
private let prefetchResources: [Resource]
private let optionsInfo: DSImageCacheOptionsInfo
private var progressBlock: PrefetcherProgressBlock?
private var completionHandler: PrefetcherCompletionHandler?
private var tasks = [URL: RetrieveImageDownloadTask]()
private var pendingResources: ArraySlice<Resource>
private var skippedResources = [Resource]()
private var completedResources = [Resource]()
private var failedResources = [Resource]()
private var stopped = false
// The created manager used for prefetch. We will use the helper method in manager.
private let manager: DSImageCacheManager
private var finished: Bool {
return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty
}
/**
Init an image prefetcher with an array of URLs.
The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
The images already cached will be skipped without downloading again.
- parameter urls: The URLs which should be prefetched.
- parameter options: A dictionary could control some behaviors. See `DSImageCacheOptionsInfo` for more.
- parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
- parameter completionHandler: Called when the whole prefetching process finished.
- returns: An `ImagePrefetcher` object.
- Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
the downloader and cache target respectively. You can specify another downloader or cache by using a customized `DSImageCacheOptionsInfo`.
Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
*/
public convenience init(urls: [URL],
options: DSImageCacheOptionsInfo? = nil,
progressBlock: PrefetcherProgressBlock? = nil,
completionHandler: PrefetcherCompletionHandler? = nil)
{
let resources: [Resource] = urls.map { $0 }
self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Init an image prefetcher with an array of resources.
The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable.
After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
The images already cached will be skipped without downloading again.
- parameter resources: The resources which should be prefetched. See `Resource` type for more.
- parameter options: A dictionary could control some behaviors. See `DSImageCacheOptionsInfo` for more.
- parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
- parameter completionHandler: Called when the whole prefetching process finished.
- returns: An `ImagePrefetcher` object.
- Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
the downloader and cache target respectively. You can specify another downloader or cache by using a customized `DSImageCacheOptionsInfo`.
Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
*/
public init(resources: [Resource],
options: DSImageCacheOptionsInfo? = nil,
progressBlock: PrefetcherProgressBlock? = nil,
completionHandler: PrefetcherCompletionHandler? = nil)
{
prefetchResources = resources
pendingResources = ArraySlice(resources)
// We want all callbacks from main queue, so we ignore the call back queue in options
let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil))
self.optionsInfo = optionsInfoWithoutQueue ?? DSImageCacheEmptyOptionsInfo
let cache = self.optionsInfo.targetCache
let downloader = self.optionsInfo.downloader
manager = DSImageCacheManager(downloader: downloader, cache: cache)
self.progressBlock = progressBlock
self.completionHandler = completionHandler
}
/**
Start to download the resources and cache them. This can be useful for background downloading
of assets that are required for later use in an app. This code will not try and update any UI
with the results of the process.
*/
public func start()
{
// Since we want to handle the resources cancellation in main thread only.
DispatchQueue.main.safeAsync {
guard !self.stopped else {
assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
self.handleComplete()
return
}
guard self.maxConcurrentDownloads > 0 else {
assertionFailure("There should be concurrent downloads value should be at least 1.")
self.handleComplete()
return
}
guard self.prefetchResources.count > 0 else {
self.handleComplete()
return
}
let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
for _ in 0 ..< initialConcurentDownloads {
if let resource = self.pendingResources.popFirst() {
self.startPrefetching(resource)
}
}
}
}
/**
Stop current downloading progress, and cancel any future prefetching activity that might be occuring.
*/
public func stop() {
DispatchQueue.main.safeAsync {
if self.finished { return }
self.stopped = true
self.tasks.forEach { (_, task) -> () in
task.cancel()
}
}
}
func downloadAndCache(_ resource: Resource) {
let downloadTaskCompletionHandler: CompletionHandler = { (image, error, _, _) -> () in
self.tasks.removeValue(forKey: resource.downloadURL)
if let _ = error {
self.failedResources.append(resource)
} else {
self.completedResources.append(resource)
}
self.reportProgress()
if self.stopped {
if self.tasks.isEmpty {
self.failedResources.append(contentsOf: self.pendingResources)
self.handleComplete()
}
} else {
self.reportCompletionOrStartNext()
}
}
let downloadTask = manager.downloadAndCacheImage(
with: resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: RetrieveImageTask(),
progressBlock: nil,
completionHandler: downloadTaskCompletionHandler,
options: optionsInfo)
if let downloadTask = downloadTask {
tasks[resource.downloadURL] = downloadTask
}
}
func append(cached resource: Resource) {
skippedResources.append(resource)
reportProgress()
reportCompletionOrStartNext()
}
func startPrefetching(_ resource: Resource)
{
if optionsInfo.forceRefresh {
downloadAndCache(resource)
} else {
let alreadyInCache = manager.cache.isImageCached(forKey: resource.cacheKey,
processorIdentifier: optionsInfo.processor.identifier).cached
if alreadyInCache {
append(cached: resource)
} else {
downloadAndCache(resource)
}
}
}
func reportProgress() {
progressBlock?(skippedResources, failedResources, completedResources)
}
func reportCompletionOrStartNext() {
if let resource = pendingResources.popFirst() {
startPrefetching(resource)
} else {
guard tasks.isEmpty else { return }
handleComplete()
}
}
func handleComplete() {
completionHandler?(skippedResources, failedResources, completedResources)
completionHandler = nil
progressBlock = nil
}
}
| mit |
AnirudhDas/AniruddhaDas.github.io | MVVMDataBindingRestAPICall/MVVMDataBindingRestAPICall/MoviesService.swift | 1 | 1280 | //
// FetchMoviesService.swift
// MVVMDataBindingRestAPICall
//
// Created by Anirudh Das on 7/26/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import Foundation
protocol MoviesProtocol {
func fetchMovies(completionBlock: @escaping (_ movies: [Movie]?) -> Void)
}
class MoviesService: NSObject, MoviesProtocol {
func fetchMovies(completionBlock: @escaping (_ movies: [Movie]?) -> Void) {
let url: URL = URL(string: "https://itunes.apple.com/us/rss/topmovies/limit=25/json")!
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error == nil, let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any], let feedDict = json?["feed"] as? [String: Any], let entryArray = feedDict["entry"] as? [[String: Any]] {
var movies: [Movie] = []
for item in entryArray {
if let name = item["im:name"] as? [String: Any], let label = name["label"] as? String {
movies.append(Movie(name: label))
}
}
completionBlock(movies)
} else {
completionBlock(nil)
}
}.resume()
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.