repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vector-im/vector-ios
|
refs/heads/master
|
CommonKit/Source/UserIndicators/UserIndicator.swift
|
apache-2.0
|
1
|
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
/// A `UserIndicator` represents the state of a temporary visual indicator, such as loading spinner, success notification or an error message. It does not directly manage the UI, instead it delegates to a `presenter`
/// whenever the UI should be shown or hidden.
///
/// More than one `UserIndicator` may be requested by the system at the same time (e.g. global syncing vs local refresh),
/// and the `UserIndicatorQueue` will ensure that only one indicator is shown at a given time, putting the other in a pending queue.
///
/// A client that requests an indicator can specify a default timeout after which the indicator is dismissed, or it has to be manually
/// responsible for dismissing it via `cancel` method, or by deallocating itself.
public class UserIndicator {
public enum State {
case pending
case executing
case completed
}
private let request: UserIndicatorRequest
private let completion: () -> Void
public private(set) var state: State
public init(request: UserIndicatorRequest, completion: @escaping () -> Void) {
self.request = request
self.completion = completion
state = .pending
}
deinit {
complete()
}
internal func start() {
guard state == .pending else {
return
}
state = .executing
request.presenter.present()
switch request.dismissal {
case .manual:
break
case .timeout(let interval):
Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { [weak self] _ in
self?.complete()
}
}
}
/// Cancel the indicator, triggering any dismissal action / animation
///
/// Note: clients can call this method directly, if they have access to the `UserIndicator`. Alternatively
/// deallocating the `UserIndicator` will call `cancel` automatically.
/// Once cancelled, `UserIndicatorQueue` will automatically start the next `UserIndicator` in the queue.
public func cancel() {
complete()
}
private func complete() {
guard state != .completed else {
return
}
if state == .executing {
request.presenter.dismiss()
}
state = .completed
completion()
}
}
public extension UserIndicator {
func store<C>(in collection: inout C) where C: RangeReplaceableCollection, C.Element == UserIndicator {
collection.append(self)
}
}
public extension Collection where Element == UserIndicator {
func cancelAll() {
forEach {
$0.cancel()
}
}
}
|
7cd449d0257411d1c3fa10c42f04eb36
| 31.378641 | 216 | 0.649175 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART
|
refs/heads/master
|
bluefruitconnect/Platform/OSX/Controllers/UartViewController.swift
|
mit
|
1
|
//
// UartViewController.swift
// bluefruitconnect
//
// Created by Antonio García on 26/09/15.
// Copyright © 2015 Adafruit. All rights reserved.
//
import Cocoa
class UartViewController: NSViewController {
// UI Outlets
@IBOutlet var baseTextView: NSTextView!
@IBOutlet weak var baseTextVisibilityView: NSScrollView!
@IBOutlet weak var baseTableView: NSTableView!
@IBOutlet weak var baseTableVisibilityView: NSScrollView!
@IBOutlet weak var hexModeSegmentedControl: NSSegmentedControl!
@IBOutlet weak var displayModeSegmentedControl: NSSegmentedControl!
@IBOutlet weak var mqttStatusButton: NSButton!
@IBOutlet weak var inputTextField: NSTextField!
@IBOutlet weak var echoButton: NSButton!
@IBOutlet weak var eolButton: NSButton!
@IBOutlet weak var sentBytesLabel: NSTextField!
@IBOutlet weak var receivedBytesLabel: NSTextField!
@IBOutlet var saveDialogCustomView: NSView!
@IBOutlet weak var saveDialogPopupButton: NSPopUpButton!
// Data
private let uartData = UartModuleManager()
// UI
private static var dataFont = Font(name: "CourierNewPSMT", size: 13)!
private var txColor = Preferences.uartSentDataColor
private var rxColor = Preferences.uartReceveivedDataColor
private let timestampDateFormatter = NSDateFormatter()
private var tableCachedDataBuffer : [UartDataChunk]?
private var tableModeDataMaxWidth : CGFloat = 0
// Export
private var exportFileDialog : NSSavePanel?
// MARK:
override func viewDidLoad() {
super.viewDidLoad()
// Init Data
uartData.delegate = self
timestampDateFormatter.setLocalizedDateFormatFromTemplate("HH:mm:ss:SSSS")
// Init UI
hexModeSegmentedControl.selectedSegment = Preferences.uartIsInHexMode ? 1:0
displayModeSegmentedControl.selectedSegment = Preferences.uartIsDisplayModeTimestamp ? 1:0
echoButton.state = Preferences.uartIsEchoEnabled ? NSOnState:NSOffState
eolButton.state = Preferences.uartIsAutomaticEolEnabled ? NSOnState:NSOffState
// UI
baseTableVisibilityView.scrollerStyle = NSScrollerStyle.Legacy // To avoid autohide behaviour
reloadDataUI()
// Mqtt init
let mqttManager = MqttManager.sharedInstance
if (MqttSettings.sharedInstance.isConnected) {
mqttManager.delegate = uartData
mqttManager.connectFromSavedSettings()
}
}
override func viewWillAppear() {
super.viewWillAppear()
registerNotifications(true)
mqttUpdateStatusUI()
}
override func viewDidDisappear() {
super.viewDidDisappear()
registerNotifications(false)
}
deinit {
let mqttManager = MqttManager.sharedInstance
mqttManager.disconnect()
}
// MARK: - Preferences
func registerNotifications(register : Bool) {
let notificationCenter = NSNotificationCenter.defaultCenter()
if (register) {
notificationCenter.addObserver(self, selector: #selector(UartViewController.preferencesUpdated(_:)), name: Preferences.PreferencesNotifications.DidUpdatePreferences.rawValue, object: nil)
}
else {
notificationCenter.removeObserver(self, name: Preferences.PreferencesNotifications.DidUpdatePreferences.rawValue, object: nil)
}
}
func preferencesUpdated(notification : NSNotification) {
txColor = Preferences.uartSentDataColor
rxColor = Preferences.uartReceveivedDataColor
reloadDataUI()
}
// MARK: - UI Updates
func reloadDataUI() {
let displayMode = Preferences.uartIsDisplayModeTimestamp ? UartModuleManager.DisplayMode.Table : UartModuleManager.DisplayMode.Text
baseTableVisibilityView.hidden = displayMode == .Text
baseTextVisibilityView.hidden = displayMode == .Table
switch(displayMode) {
case .Text:
if let textStorage = self.baseTextView.textStorage {
let isScrollAtTheBottom = baseTextView.enclosingScrollView?.verticalScroller?.floatValue == 1
textStorage.beginEditing()
textStorage.replaceCharactersInRange(NSMakeRange(0, textStorage.length), withAttributedString: NSAttributedString()) // Clear text
for dataChunk in uartData.dataBuffer {
addChunkToUIText(dataChunk)
}
textStorage .endEditing()
if isScrollAtTheBottom {
baseTextView.scrollRangeToVisible(NSMakeRange(textStorage.length, 0))
}
}
case .Table:
//let isScrollAtTheBottom = tableCachedDataBuffer == nil || tableCachedDataBuffer!.isEmpty || baseTableView.enclosingScrollView?.verticalScroller?.floatValue == 1
let isScrollAtTheBottom = tableCachedDataBuffer == nil || tableCachedDataBuffer!.isEmpty || NSLocationInRange(tableCachedDataBuffer!.count-1, baseTableView.rowsInRect(baseTableView.visibleRect))
baseTableView.sizeLastColumnToFit()
baseTableView.reloadData()
if isScrollAtTheBottom {
baseTableView.scrollToEndOfDocument(nil)
}
}
updateBytesUI()
}
func updateBytesUI() {
if let blePeripheral = uartData.blePeripheral {
let localizationManager = LocalizationManager.sharedInstance
sentBytesLabel.stringValue = String(format: localizationManager.localizedString("uart_sentbytes_format"), arguments: [blePeripheral.uartData.sentBytes])
receivedBytesLabel.stringValue = String(format: localizationManager.localizedString("uart_recievedbytes_format"), arguments: [blePeripheral.uartData.receivedBytes])
}
}
// MARK: - UI Actions
@IBAction func onClickEcho(sender: NSButton) {
Preferences.uartIsEchoEnabled = echoButton.state == NSOnState
reloadDataUI()
}
@IBAction func onClickEol(sender: NSButton) {
Preferences.uartIsAutomaticEolEnabled = eolButton.state == NSOnState
}
@IBAction func onChangeHexMode(sender: AnyObject) {
Preferences.uartIsInHexMode = sender.selectedSegment == 1
reloadDataUI()
}
@IBAction func onChangeDisplayMode(sender: NSSegmentedControl) {
Preferences.uartIsDisplayModeTimestamp = sender.selectedSegment == 1
reloadDataUI()
}
@IBAction func onClickClear(sender: NSButton) {
uartData.clearData()
tableModeDataMaxWidth = 0
reloadDataUI()
}
@IBAction func onClickSend(sender: AnyObject) {
let text = inputTextField.stringValue
var newText = text
// Eol
if (Preferences.uartIsAutomaticEolEnabled) {
newText += "\n"
}
uartData.sendMessageToUart(newText)
inputTextField.stringValue = ""
}
@IBAction func onClickExport(sender: AnyObject) {
exportData()
}
@IBAction func onClickMqtt(sender: AnyObject) {
let mqttManager = MqttManager.sharedInstance
let status = mqttManager.status
if status != .Connected && status != .Connecting {
if let serverAddress = MqttSettings.sharedInstance.serverAddress where !serverAddress.isEmpty {
// Server address is defined. Start connection
mqttManager.delegate = uartData
mqttManager.connectFromSavedSettings()
}
else {
// Server address not defined
let localizationManager = LocalizationManager.sharedInstance
let alert = NSAlert()
alert.messageText = localizationManager.localizedString("uart_mqtt_undefinedserver")
alert.addButtonWithTitle(localizationManager.localizedString("dialog_ok"))
alert.addButtonWithTitle(localizationManager.localizedString("uart_mqtt_editsettings"))
alert.alertStyle = .WarningAlertStyle
alert.beginSheetModalForWindow(self.view.window!) { [unowned self] (returnCode) -> Void in
if returnCode == NSAlertSecondButtonReturn {
let preferencesViewController = self.storyboard?.instantiateControllerWithIdentifier("PreferencesViewController") as! PreferencesViewController
self.presentViewControllerAsModalWindow(preferencesViewController)
}
}
}
}
else {
mqttManager.disconnect()
}
mqttUpdateStatusUI()
}
// MARK: - Export
private func exportData() {
let localizationManager = LocalizationManager.sharedInstance
// Check if data is empty
guard uartData.dataBuffer.count > 0 else {
let alert = NSAlert()
alert.messageText = localizationManager.localizedString("uart_export_nodata")
alert.addButtonWithTitle(localizationManager.localizedString("dialog_ok"))
alert.alertStyle = .WarningAlertStyle
alert.beginSheetModalForWindow(self.view.window!, completionHandler: nil)
return
}
// Show save dialog
exportFileDialog = NSSavePanel()
exportFileDialog!.delegate = self
exportFileDialog!.message = localizationManager.localizedString("uart_export_save_message")
exportFileDialog!.prompt = localizationManager.localizedString("uart_export_save_prompt")
exportFileDialog!.canCreateDirectories = true
exportFileDialog!.accessoryView = saveDialogCustomView
for exportFormat in uartData.exportFormats {
saveDialogPopupButton.addItemWithTitle(exportFormat.rawValue)
}
updateSaveFileName()
if let window = self.view.window {
exportFileDialog!.beginSheetModalForWindow(window) {[unowned self] (result) -> Void in
if result == NSFileHandlingPanelOKButton {
if let url = self.exportFileDialog!.URL {
// Save
var text : String?
let exportFormatSelected = self.uartData.exportFormats[self.saveDialogPopupButton.indexOfSelectedItem]
let dataBuffer = self.uartData.dataBuffer
switch(exportFormatSelected) {
case .txt:
text = UartDataExport.dataAsText(dataBuffer)
case .csv:
text = UartDataExport.dataAsCsv(dataBuffer)
case .json:
text = UartDataExport.dataAsJson(dataBuffer)
break
case .xml:
text = UartDataExport.dataAsXml(dataBuffer)
break
}
// Write data
do {
try text?.writeToURL(url, atomically: true, encoding: NSUTF8StringEncoding)
}
catch let error {
DLog("Error exporting file \(url.absoluteString): \(error)")
}
}
}
}
}
}
@IBAction func onExportFormatChanged(sender: AnyObject) {
updateSaveFileName()
}
private func updateSaveFileName() {
if let exportFileDialog = exportFileDialog {
let isInHexMode = Preferences.uartIsInHexMode
let exportFormatSelected = uartData.exportFormats[saveDialogPopupButton.indexOfSelectedItem]
exportFileDialog.nameFieldStringValue = "uart\(isInHexMode ? ".hex" : "").\(exportFormatSelected.rawValue)"
}
}
}
// MARK: - DetailTab
extension UartViewController : DetailTab {
func tabWillAppear() {
reloadDataUI()
// Check if characteristics are ready
let isUartReady = uartData.isReady()
inputTextField.enabled = isUartReady
inputTextField.backgroundColor = isUartReady ? NSColor.whiteColor() : NSColor.blackColor().colorWithAlphaComponent(0.1)
}
func tabWillDissapear() {
if !Config.uartShowAllUartCommunication {
uartData.dataBufferEnabled = false
}
}
func tabReset() {
// Peripheral should be connected
uartData.dataBufferEnabled = true
uartData.blePeripheral = BleManager.sharedInstance.blePeripheralConnected // Note: this will start the service discovery
}
}
// MARK: - NSOpenSavePanelDelegate
extension UartViewController: NSOpenSavePanelDelegate {
}
// MARK: - NSTableViewDataSource
extension UartViewController: NSTableViewDataSource {
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if (Preferences.uartIsEchoEnabled) {
tableCachedDataBuffer = uartData.dataBuffer
}
else {
tableCachedDataBuffer = uartData.dataBuffer.filter({ (dataChunk : UartDataChunk) -> Bool in
dataChunk.mode == .RX
})
}
return tableCachedDataBuffer!.count
}
}
// MARK: NSTableViewDelegate
extension UartViewController: NSTableViewDelegate {
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
var cell : NSTableCellView?
let dataChunk = tableCachedDataBuffer![row]
if let columnIdentifier = tableColumn?.identifier {
switch(columnIdentifier) {
case "TimestampColumn":
cell = tableView.makeViewWithIdentifier("TimestampCell", owner: self) as? NSTableCellView
let date = NSDate(timeIntervalSinceReferenceDate: dataChunk.timestamp)
let dateString = timestampDateFormatter.stringFromDate(date)
cell!.textField!.stringValue = dateString
case "DirectionColumn":
cell = tableView.makeViewWithIdentifier("DirectionCell", owner: self) as? NSTableCellView
cell!.textField!.stringValue = dataChunk.mode == .RX ? "RX" : "TX"
case "DataColumn":
cell = tableView.makeViewWithIdentifier("DataCell", owner: self) as? NSTableCellView
let color = dataChunk.mode == .TX ? txColor : rxColor
if let attributedText = UartModuleManager.attributeTextFromData(dataChunk.data, useHexMode: Preferences.uartIsInHexMode, color: color, font: UartViewController.dataFont) {
//DLog("row \(row): \(attributedText.string)")
// Display
cell!.textField!.attributedStringValue = attributedText
// Update column width (if needed)
let width = attributedText.size().width
tableModeDataMaxWidth = max(tableColumn!.width, width)
dispatch_async(dispatch_get_main_queue(), { // Important: Execute async. This change should be done outside the delegate method to avoid weird reuse cell problems (reused cell shows old data and cant be changed).
if (tableColumn!.width < self.tableModeDataMaxWidth) {
tableColumn!.width = self.tableModeDataMaxWidth
}
});
}
else {
//DLog("row \(row): <empty>")
cell!.textField!.attributedStringValue = NSAttributedString()
}
default:
cell = nil
}
}
return cell;
}
func tableViewSelectionDidChange(notification: NSNotification) {
}
func tableViewColumnDidResize(notification: NSNotification) {
if let tableColumn = notification.userInfo?["NSTableColumn"] as? NSTableColumn {
if (tableColumn.identifier == "DataColumn") {
// If the window is resized, maintain the column width
if (tableColumn.width < tableModeDataMaxWidth) {
tableColumn.width = tableModeDataMaxWidth
}
//DLog("column: \(tableColumn), width: \(tableColumn.width)")
}
}
}
}
// MARK: - UartModuleDelegate
extension UartViewController: UartModuleDelegate {
func addChunkToUI(dataChunk : UartDataChunk) {
// Check that the view has been initialized before updating UI
guard baseTableView != nil else {
return;
}
let displayMode = Preferences.uartIsDisplayModeTimestamp ? UartModuleManager.DisplayMode.Table : UartModuleManager.DisplayMode.Text
switch(displayMode) {
case .Text:
if let textStorage = self.baseTextView.textStorage {
let isScrollAtTheBottom = baseTextView.enclosingScrollView?.verticalScroller?.floatValue == 1
addChunkToUIText(dataChunk)
if isScrollAtTheBottom {
// if scroll was at the bottom then autoscroll to the new bottom
baseTextView.scrollRangeToVisible(NSMakeRange(textStorage.length, 0))
}
}
case .Table:
let isScrollAtTheBottom = tableCachedDataBuffer == nil || tableCachedDataBuffer!.isEmpty || NSLocationInRange(tableCachedDataBuffer!.count-1, baseTableView.rowsInRect(baseTableView.visibleRect))
//let isScrollAtTheBottom = tableCachedDataBuffer == nil || tableCachedDataBuffer!.isEmpty || baseTableView.enclosingScrollView?.verticalScroller?.floatValue == 1
baseTableView.reloadData()
if isScrollAtTheBottom {
// if scroll was at the bottom then autoscroll to the new bottom
baseTableView.scrollToEndOfDocument(nil)
}
}
updateBytesUI()
}
private func addChunkToUIText(dataChunk : UartDataChunk) {
if (Preferences.uartIsEchoEnabled || dataChunk.mode == .RX) {
let color = dataChunk.mode == .TX ? txColor : rxColor
let attributedString = UartModuleManager.attributeTextFromData(dataChunk.data, useHexMode: Preferences.uartIsInHexMode, color: color, font: UartViewController.dataFont)
if let textStorage = self.baseTextView.textStorage, attributedString = attributedString {
textStorage.appendAttributedString(attributedString)
}
}
}
func mqttUpdateStatusUI() {
let status = MqttManager.sharedInstance.status
let localizationManager = LocalizationManager.sharedInstance
var buttonTitle = localizationManager.localizedString("uart_mqtt_status_default")
switch (status) {
case .Connecting:
buttonTitle = localizationManager.localizedString("uart_mqtt_status_connecting")
case .Connected:
buttonTitle = localizationManager.localizedString("uart_mqtt_status_connected")
default:
buttonTitle = localizationManager.localizedString("uart_mqtt_status_disconnected")
}
mqttStatusButton.title = buttonTitle
}
func mqttError(message: String, isConnectionError: Bool) {
let localizationManager = LocalizationManager.sharedInstance
let alert = NSAlert()
alert.messageText = isConnectionError ? localizationManager.localizedString("uart_mqtt_connectionerror_title"): message
alert.addButtonWithTitle(localizationManager.localizedString("dialog_ok"))
if (isConnectionError) {
alert.addButtonWithTitle(localizationManager.localizedString("uart_mqtt_editsettings_action"))
alert.informativeText = message
}
alert.alertStyle = .WarningAlertStyle
alert.beginSheetModalForWindow(self.view.window!) { [unowned self] (returnCode) -> Void in
if isConnectionError && returnCode == NSAlertSecondButtonReturn {
let preferencesViewController = self.storyboard?.instantiateControllerWithIdentifier("PreferencesViewController") as! PreferencesViewController
self.presentViewControllerAsModalWindow(preferencesViewController)
}
}
}
}
// MARK: - CBPeripheralDelegate
extension UartViewController: CBPeripheralDelegate {
// Pass peripheral callbacks to UartData
func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
uartData.peripheral(peripheral, didModifyServices: invalidatedServices)
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
uartData.peripheral(peripheral, didDiscoverServices:error)
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
uartData.peripheral(peripheral, didDiscoverCharacteristicsForService: service, error: error)
// Check if ready
if uartData.isReady() {
// Enable input
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
if self.inputTextField != nil { // could be nil if the viewdidload has not been executed yet
self.inputTextField.enabled = true
self.inputTextField.backgroundColor = NSColor.whiteColor()
}
});
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
uartData.peripheral(peripheral, didUpdateValueForCharacteristic: characteristic, error: error)
}
}
|
648abc27181863ecf692b26714d037e4
| 39.494585 | 236 | 0.624588 | false | false | false | false |
pman215/ToastNotifications
|
refs/heads/master
|
ToastNotifications/ViewAnimationTaskQueue.swift
|
mit
|
1
|
//
// ViewAnimationTaskQueue.swift
// ToastNotifications
//
// Created by pman215 on 6/6/16.
// Copyright © 2016 pman215. All rights reserved.
//
import Foundation
/**
Describes the possible states of a `ViewAnimationTaskQueue`
+ New: Queue was initialized and is ready to queue tasks and start processing
them
+ Processing: Queue started processing tasks. Queueing more tasks is not
allowed
+ Finished: Queue processed all tasks in the queue.
*/
internal enum ViewAnimationTaskQueueState {
case new
case processing
case finished
}
internal protocol ViewAnimationTaskQueueDelegate: class {
/**
Called when a `ViewAnimationTaskQueue` finished processing all queued tasks
*/
func queueDidFinishProcessing(_ queue: ViewAnimationTaskQueue)
}
/**
A `ViewAnimationTaskQueue` coordinates the execution of `ViewAnimationTask`
objects. When a task is added to the queue it will start execution immediately
as long as there are no other task being processed. Tasks are processed in a
FIFO order
A queue is a single-shot object, once it has finished processing all its tasks,
the queue should be disposed.
*/
internal class ViewAnimationTaskQueue {
fileprivate var queue = [ViewAnimationTask]()
fileprivate(set) var state: ViewAnimationTaskQueueState
var tasks: [ViewAnimationTask] {
return queue
}
weak var delegate: ViewAnimationTaskQueueDelegate?
init() {
state = .new
}
func queue(task: ViewAnimationTask) {
task.queue = self
queue.append(task)
}
func dequeue(task: ViewAnimationTask) {
switch state {
case .processing:
remove(task)
processTask()
case .new:
assertionFailure("ViewAnimationTaskQueue should be processing")
case .finished:
assertionFailure("ViewAnimationTaskQueue can't process tasks after finishing")
}
}
func process() {
switch state {
case .new:
state = .processing
processTask()
case .processing:
assertionFailure("ViewAnimationTaskQueue is already processing")
case .finished:
assertionFailure("ViewAnimationTaskQueue is done processing.")
}
}
func cancel() {
switch state {
case .new, .processing:
cancelAllTasks()
state = .finished
case .finished:
assertionFailure("ViewAnimationTaskQueue is done processing.")
}
}
}
private extension ViewAnimationTaskQueue {
func processTask() {
if let firstTask = queue.first {
firstTask.animate()
} else {
state = .finished
delegate?.queueDidFinishProcessing(self)
}
}
func cancelAllTasks() {
queue.forEach {
$0.cancel()
$0.queue = nil
}
queue.removeAll()
}
func remove(_ task: ViewAnimationTask) {
if let _task = queue.first , _task === task {
let dequeueTask = queue.removeFirst()
dequeueTask.queue = nil
} else {
assertionFailure("Trying to dequeue unrecognized task \(task)")
}
}
}
|
343a037dc7c9cd87fdf46298513fd295
| 21.887324 | 90 | 0.632308 | false | false | false | false |
jigneshsheth/multi-collectionview-flowlayout
|
refs/heads/master
|
MultiCollectionView/CustomCollectionViewFlowLayout.swift
|
mit
|
1
|
//
// CustomCollectionViewFlowLayout.swift
// MultiCollectionView
//
// Created by Jigs Sheth on 1/20/15.
// Copyright (c) 2015 Jigs Sheth. All rights reserved.
//
import UIKit
import QuartzCore
class CustomCollectionViewFlowLayout: UICollectionViewFlowLayout {
var indexPathsToAnimate:[AnyObject] = [AnyObject]()
private class func flowlayout(itemSize:CGSize,minLineSpacing:CGFloat, minItemSpacing:CGFloat) -> CustomCollectionViewFlowLayout{
var flowlayout = CustomCollectionViewFlowLayout()
flowlayout.itemSize = itemSize
flowlayout.minimumInteritemSpacing = minItemSpacing
flowlayout.minimumLineSpacing = minLineSpacing
flowlayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
return flowlayout
}
class func smallListLayout(viewWidth:CGFloat) -> CustomCollectionViewFlowLayout{
return flowlayout(CGSizeMake(viewWidth - 30 ,80), minLineSpacing: 5, minItemSpacing: 5)
}
class func mediumListLayout(viewWidth:CGFloat) -> CustomCollectionViewFlowLayout{
return flowlayout(CGSizeMake(viewWidth - 30,280), minLineSpacing: 5, minItemSpacing: 5)
}
class func gridLayout(viewWidth:CGFloat) -> CustomCollectionViewFlowLayout{
let itemWidth = (viewWidth - 30) / 2
return flowlayout(CGSizeMake(itemWidth, itemWidth), minLineSpacing: 5, minItemSpacing: 5)
}
override func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?{
var att = self.layoutAttributesForItemAtIndexPath(itemIndexPath)
if self.indexPathsToAnimate.count > 0 {
var obj:AnyObject? = self.indexPathsToAnimate[itemIndexPath.row]
if let o: AnyObject = obj {
att.transform = CGAffineTransformRotate(CGAffineTransformMakeScale(0.2, 0.2), CGFloat(M_PI))
att.center = CGPointMake(CGRectGetMaxX(self.collectionView!.bounds), CGRectGetMaxX(self.collectionView!.bounds))
self.indexPathsToAnimate.removeAtIndex(itemIndexPath.row)
}}
return att
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
var oldBounds = self.collectionView?.bounds
if let oldBounds = oldBounds {
if !CGSizeEqualToSize(oldBounds.size, newBounds.size) {
return true
}
}
return false
}
override func prepareForCollectionViewUpdates(updateItems: [AnyObject]!) {
super.prepareForCollectionViewUpdates(updateItems)
var indexPaths = [AnyObject]()
for updateItem in updateItems {
var item:UICollectionViewUpdateItem = updateItem as! UICollectionViewUpdateItem
switch item.updateAction {
case UICollectionUpdateAction.Insert:
indexPaths.append(item.indexPathAfterUpdate!)
break
case UICollectionUpdateAction.Delete:
indexPaths.append(item.indexPathBeforeUpdate!)
break
case UICollectionUpdateAction.Move:
indexPaths.append(item.indexPathBeforeUpdate!)
indexPaths.append(item.indexPathAfterUpdate!)
break
default:
println("Unhandled case:: \(updateItems)")
break
}
}
self.indexPathsToAnimate = indexPaths
}
}
|
7f24427a2f1f62a421585de104f1e2f0
| 34.177778 | 132 | 0.734997 | false | false | false | false |
TifaTsubasa/TTReflect
|
refs/heads/master
|
TTReflect/ReflectJson.swift
|
mit
|
1
|
//
// ReflectJson.swift
// TTReflect
//
// Created by Tsuf on 2017/12/15.
// Copyright © 2017年 tifatsubasa. All rights reserved.
//
import UIKit
protocol ReflectJson {
func toJSONModel() -> AnyObject?
func toJSONString() -> String?
}
extension ReflectJson {
func getMirrorKeyValues(_ mirror: Mirror?) -> [String: Any] { // iOS8+
var keyValues = [String: Any]()
guard let mirror = mirror else { return keyValues }
for case let (label?, value) in mirror.children {
keyValues[label] = value
}
if mirror.superclassMirror?.subjectType != NSObject.self {
getMirrorKeyValues(mirror.superclassMirror).forEach({ (key, value) in
keyValues[key] = value
})
}
return keyValues
}
//将数据转成可用的JSON模型
func toJSONModel() -> AnyObject? {
let replacePropertys = (self as? TTReflectProtocol)?.setupMappingReplaceProperty?() ?? [:]
let mirror = Mirror(reflecting: self)
let keyValues = getMirrorKeyValues(mirror)
if mirror.children.count > 0 {
var result: [String: AnyObject] = [:]
for (label, value) in keyValues {
let sourceLabel = replacePropertys.keys.contains(label) ? replacePropertys[label]! : label
debugPrint("source label: ", sourceLabel)
if let jsonValue = value as? ReflectJson {
if let hasResult = jsonValue.toJSONModel() {
// debugPrint("has result: ", label, "-", hasResult)
result[sourceLabel] = hasResult
} else {
let valueMirror = Mirror(reflecting: value)
if valueMirror.superclassMirror?.subjectType != NSObject.self {
// debugPrint("not object: ", label, "-", value)
result[sourceLabel] = value as AnyObject
}
}
}
}
return result as AnyObject
}
return nil
}
//将数据转成JSON字符串
func toJSONString() -> String? {
guard let jsonModel = self.toJSONModel() else {
return ""
}
// debugPrint(jsonModel)
//利用OC的json库转换成Data,
let data = try? JSONSerialization.data(withJSONObject: jsonModel,
options: [])
//Data转换成String打印输出
let str = String(data: data!, encoding: .utf8)
return str
}
}
extension NSObject: ReflectJson { }
extension String: ReflectJson { }
extension Int: ReflectJson { }
extension Double: ReflectJson { }
extension Bool: ReflectJson { }
extension Dictionary: ReflectJson { }
//扩展Array,格式化输出
extension Array: ReflectJson {
//将数据转成可用的JSON模型
func toJSONModel() -> AnyObject? {
var result: [AnyObject] = []
for value in self {
if let jsonValue = value as? ReflectJson , let jsonModel = jsonValue.toJSONModel(){
result.append(jsonModel)
}
}
return result as AnyObject
}
}
|
966cde699ea27d4f2b56895bf183e84e
| 28.574468 | 98 | 0.627338 | false | false | false | false |
bnickel/SEUICollectionViewLayout
|
refs/heads/master
|
Code Survey/Code Survey/HeadingView.swift
|
mit
|
1
|
//
// HeadingView.swift
// Code Survey
//
// Created by Brian Nickel on 11/5/14.
// Copyright (c) 2014 Brian Nickel. All rights reserved.
//
import UIKit
private let SizingHeadingView:HeadingView = HeadingView.nib!.instantiateWithOwner(nil, options: nil)[0] as! HeadingView
class HeadingView: UICollectionReusableView {
@IBOutlet weak var label: UILabel!
override var bounds:CGRect {
didSet {
label?.preferredMaxLayoutWidth = CGRectGetWidth(bounds)
}
}
override var frame:CGRect {
didSet {
label?.preferredMaxLayoutWidth = CGRectGetWidth(frame)
}
}
var text:String {
get {
return label.text ?? ""
}
set(value) {
label.text = value
}
}
class var nib:UINib? {
return UINib(nibName: "HeadingView", bundle: nil)
}
class func heightForText(text:String, width:CGFloat) -> CGFloat {
SizingHeadingView.label.text = text
return SizingHeadingView.label.sizeThatFits(CGSizeMake(width, 0)).height + 1
}
}
|
f7b732333c0df4199a1d129f92ff165b
| 22.808511 | 119 | 0.603217 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015
|
refs/heads/master
|
04-App Architecture/Swift 3/Playgrounds/Enumerated Types.playground/Pages/Methods.xcplaygroundpage/Contents.swift
|
mit
|
2
|
//: 
//:
//: [Previous](@previous)
//:
//: ## Methods
//:
//: As we saw in the previous section, enumerated types (like classes and structures) can also have methods and therefore computed properties.
//:
//: - **instance methods** - functions that a concerned with an instance of the enum, have access to `self` and can mutate `self` (known as *mutating* methods). You need an instance of a enum to use these.
//: - **type methods** - belong to the type and no particular instance. You can call these without an instance of an enum.
//:
//: Here is a simple example:
enum ToggleSwitch : String {
//These are the two possible cases with raw types "on" and "off"
case on
case off
//The following instance method simply returns another instance (note the name is an adjective)
func toggled() -> ToggleSwitch {
switch (self)
{
case .on:
return .off
case .off:
return .on
}
}
//Where a function name is a verb, by convention this suggests self-modification. Such methods change `self` (the instance), so must be marked as `mutating`
mutating func toggle() {
//The instance is replaced with a completely new instance (with a different case in this example)
self = self.toggled()
}
//This type function does not operate on a particular instance, but is part of the Enumerated Type itself
static func & (lhs: ToggleSwitch, rhs: ToggleSwitch) -> ToggleSwitch {
//Here comes that pattern matching again - matching a tuple is always handy
let tuple = (lhs, rhs)
switch tuple {
case (.on, .on):
return .on
default:
return .off
}
}
//Calculated properties are allowed (stored are not for enum) - they are a type of instance method
var description : String {
get {
if self == .on {
return "SWITCH IS ON"
} else {
return "SWITCH IS OFF"
}
}
}
//The initialiser can also be defined. This one ensures the default to always be off. This is not mutating as it's involved in creation, not change
init() {
self = .off
}
//You can also write other initialisers
init(isOn n : Bool) {
if (n) {
self = .on
} else {
self = .off
}
}
}
//: The enum has a number of methods. The initialisers `init()` and `init(isOn n : Bool)` are useful for safely setting the default state. You can therefore initialise this enum in various ways.
//:
//: 1. Simple assignment
let toggle0 : ToggleSwitch = .off
//: 2. Invoke the initialiser
let toggle1 = ToggleSwitch()
//: 3. Alternative initialiser (similar to a convenience initialiser)
let toggle2 = ToggleSwitch(isOn: true)
//: 4. Using a raw value
if let toggle3 = ToggleSwitch(rawValue: "on") { //With raw values, it could fail, so the return is Optional....
toggle3
}
if let toggle4 = ToggleSwitch(rawValue: "ON") { //...as shown here
toggle4
} else {
print("That failed - wrong case?")
}
//: In this example, `toggle3` and `toggle4` are Optional types (remember that initialisation with raw values can fail). `toggle3` has a wrapped value whereas `toggle4` is `nil`.
//:
//: The enum has a number of methods. Starting with the initialiser `init()` we first set the default state to `.off`.
var sw1 = ToggleSwitch()
sw1.description
//: We can obtain another instance with the opposite state (original unmodified). Note the value semantics and the method naming convention used here (it's an adjective, not a verb).
let sw2 = sw1.toggled()
sw1.description
//: We can change the state of an instance (mutating). Note again the method naming convention is to use a verb in an imperative tense. This is an in-place modification.
sw1.toggle()
sw1.description
//: The custom operator & is a type-method (`self` is the Type, not an instance)
ToggleSwitch.on & ToggleSwitch.on
ToggleSwitch.on & ToggleSwitch.off
//:
//: Notes:
//:
//: - enums are value types
//: - enums cannot have stored properties
//: - enums can have computed properties and methods
//: - enums can have instance methods with access to the instance value self
//: - a method that changes self must be marked as mutating
//: - enums can have type methods where self refers to the type
//:
//: ## Extensions
//: Let's now add some further methods to the enum from outside the original definition. We use an *extension* to do this
extension ToggleSwitch {
//Add an initialiser
init(withString s : String) {
if s.lowercased() == "on" {
self = .on
} else {
self = .off
}
}
}
//: Note - an initialiser does not need `mutating` as `self` being initialised, not changed.
//:
//: Initialise with the new initialiser
let sw3 = ToggleSwitch(withString: "ON")
sw3.description
//: ## Value Semantics
//: Like structures, enumerated types are *value types*
var v1 = ToggleSwitch.on
var v2 = v1
//: `v2` is now a logical and independent copy of `v1`
v2.toggle()
//: `v2` is mutated by the `toggle` method while leaving `v1` unaffected.
v1.description
v2.description
//:By default, properties of value types are not mutated from within an instance method [\[1\]](References). The `toggle` method has the keyword `mutating` to override this.
//:
//: ### Subscripts
//: You can even define what it means to use a subscript
enum FemaleShoeSize {
case uk(Int)
case usa(Int)
func ukSize() -> FemaleShoeSize {
switch self {
case .uk:
return self
case .usa(let s):
return .uk(s-2)
}
}
func usSize() -> FemaleShoeSize {
switch self {
case .uk(let s):
return .usa(s+2)
case .usa:
return self
}
}
subscript(index : Int) -> Int? {
get {
switch self {
case .uk(1...10) where (index > 0 && index <= 10):
return index
case .usa(3...12):
return index+2
default:
return nil
}
}
}
}
//: Let's create an instance of this type with value `uk` and associated data (size) 8.
let shoe = FemaleShoeSize.uk(8)
shoe[0]
shoe[1]
shoe[2]
//: We can calculate the equivalent size in the USA
shoe.usSize()
//: We can then use subscripts to see all the sizes converted to the USA system
shoe.usSize()[1]
shoe.usSize()[2]
//: - Note: Just because this type has a subscript does not mean you can iterate over it. The following code will not compile as `FemaleShoeSize` does not conform to the `Sequence` protocol.
//: ````
//: for m in shoe {
//: m
//: }
//: ````
//: [Next - Advanced Topics](@next)
|
000dc8dc953cf9c4ab7fda1fa2483938
| 31.497561 | 205 | 0.648004 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
Scripts/BuildPhases/LintAppLocalizedStringsUsage.swift
|
gpl-2.0
|
1
|
import Foundation
// MARK: Xcodeproj entry point type
/// The main entry point type to parse `.xcodeproj` files
class Xcodeproj {
let projectURL: URL // points to the "<projectDirectory>/<projectName>.xcodeproj/project.pbxproj" file
private let pbxproj: PBXProjFile
/// Semantic type for strings that correspond to an object' UUID in the `pbxproj` file
typealias ObjectUUID = String
/// Builds an `Xcodeproj` instance by parsing the `.xcodeproj` or `.pbxproj` file at the provided URL.
init(url: URL) throws {
projectURL = url.pathExtension == "xcodeproj" ? URL(fileURLWithPath: "project.pbxproj", relativeTo: url) : url
let data = try Data(contentsOf: projectURL)
let decoder = PropertyListDecoder()
pbxproj = try decoder.decode(PBXProjFile.self, from: data)
}
/// An internal mapping listing the parent ObjectUUID for each ObjectUUID.
/// - Built by recursing top-to-bottom in the various `PBXGroup` objects of the project to visit all the children objects,
/// and storing which parent object they belong to.
/// - Used by the `resolveURL` method to find the real path of a `PBXReference`, as we need to navigate from the `PBXReference` object
/// up into the chain of parent `PBXGroup` containers to construct the successive relative paths of groups using `sourceTree = "<group>"`
private lazy var referrers: [ObjectUUID: ObjectUUID] = {
var referrers: [ObjectUUID: ObjectUUID] = [:]
func recurseIfGroup(objectID: ObjectUUID) {
guard let group = try? (self.pbxproj.object(id: objectID) as PBXGroup) else { return }
for childID in group.children {
referrers[childID] = objectID
recurseIfGroup(objectID: childID)
}
}
recurseIfGroup(objectID: self.pbxproj.rootProject.mainGroup)
return referrers
}()
}
// Convenience methods and properties
extension Xcodeproj {
/// Builds an `Xcodeproj` instance by parsing the `.xcodeproj` or `pbxproj` file at the provided path
convenience init(path: String) throws {
try self.init(url: URL(fileURLWithPath: path))
}
/// The directory where the `.xcodeproj` resides.
var projectDirectory: URL { projectURL.deletingLastPathComponent().deletingLastPathComponent() }
/// The list of `PBXNativeTarget` targets in the project. Convenience getter for `PBXProjFile.nativeTargets`
var nativeTargets: [PBXNativeTarget] { pbxproj.nativeTargets }
/// The list of `PBXBuildFile` files a given `PBXNativeTarget` will build. Convenience getter for `PBXProjFile.buildFiles(for:)`
func buildFiles(for target: PBXNativeTarget) -> [PBXBuildFile] { pbxproj.buildFiles(for: target) }
/// Finds the full path / URL of a `PBXBuildFile` based on the groups it belongs to and their `sourceTree` attribute
func resolveURL(to buildFile: PBXBuildFile) throws -> URL? {
if let fileRefID = buildFile.fileRef, let fileRefObject = try? self.pbxproj.object(id: fileRefID) as PBXFileReference {
return try resolveURL(objectUUID: fileRefID, object: fileRefObject)
} else {
// If the `PBXBuildFile` is pointing to `XCVersionGroup` (like `*.xcdatamodel`) and `PBXVariantGroup` (like `*.strings`)
// (instead of a `PBXFileReference`), then in practice each file in the group's `children` will be built by the Build Phase.
// In practice we can skip parsing those in our case and save some CPU, as we don't have a need to lint those non-source-code files.
return nil // just skip those (but don't throw — those are valid use cases in any pbxproj, just ones we don't care about)
}
}
/// Finds the full path / URL of a PBXReference (`PBXFileReference` of `PBXGroup`) based on the groups it belongs to and their `sourceTree` attribute
private func resolveURL<T: PBXReference>(objectUUID: ObjectUUID, object: T) throws -> URL? {
if objectUUID == self.pbxproj.rootProject.mainGroup { return URL(fileURLWithPath: ".", relativeTo: projectDirectory) }
switch object.sourceTree {
case .absolute:
guard let path = object.path else { throw ProjectInconsistencyError.incorrectAbsolutePath(id: objectUUID) }
return URL(fileURLWithPath: path)
case .group:
guard let parentUUID = referrers[objectUUID] else { throw ProjectInconsistencyError.orphanObject(id: objectUUID, object: object) }
let parentGroup = try self.pbxproj.object(id: parentUUID) as PBXGroup
guard let groupURL = try resolveURL(objectUUID: parentUUID, object: parentGroup) else { return nil }
return object.path.map { groupURL.appendingPathComponent($0) } ?? groupURL
case .projectRoot:
return object.path.map { URL(fileURLWithPath: $0, relativeTo: projectDirectory) } ?? projectDirectory
case .buildProductsDir, .devDir, .sdkDir:
print("\(self.projectURL.path): warning: Reference \(objectUUID) is relative to \(object.sourceTree.rawValue), which is not supported by the linter")
return nil
}
}
}
// MARK: - Implementation Details
/// "Parent" type for all the PBX... types of objects encountered in a pbxproj
protocol PBXObject: Decodable {
static var isa: String { get }
}
extension PBXObject {
static var isa: String { String(describing: self) }
}
/// "Parent" type for PBXObjects referencing relative path information (`PBXFileReference`, `PBXGroup`)
protocol PBXReference: PBXObject {
var name: String? { get }
var path: String? { get }
var sourceTree: Xcodeproj.SourceTree { get }
}
/// Types used to parse and decode the internals of a `*.xcodeproj/project.pbxproj` file
extension Xcodeproj {
/// An error `thrown` when an inconsistency is found while parsing the `.pbxproj` file.
enum ProjectInconsistencyError: Swift.Error, CustomStringConvertible {
case objectNotFound(id: ObjectUUID)
case unexpectedObjectType(id: ObjectUUID, expectedType: Any.Type, found: PBXObject)
case incorrectAbsolutePath(id: ObjectUUID)
case orphanObject(id: ObjectUUID, object: PBXObject)
var description: String {
switch self {
case .objectNotFound(id: let id):
return "Unable to find object with UUID `\(id)`"
case .unexpectedObjectType(id: let id, expectedType: let expectedType, found: let found):
return "Object with UUID `\(id)` was expected to be of type \(expectedType) but found \(found) instead"
case .incorrectAbsolutePath(id: let id):
return "Object `\(id)` has `sourceTree = \(Xcodeproj.SourceTree.absolute)` but no `path`"
case .orphanObject(id: let id, object: let object):
return "Unable to find parent group of \(object) (`\(id)`) during file path resolution"
}
}
}
/// Type used to represent and decode the root object of a `.pbxproj` file.
struct PBXProjFile: Decodable {
let rootObject: ObjectUUID
let objects: [String: PBXObjectWrapper]
// Convenience methods
/// Returns the `PBXObject` instance with the given `ObjectUUID`, by looking it up in the list of `objects` registered in the project.
func object<T: PBXObject>(id: ObjectUUID) throws -> T {
guard let wrapped = objects[id] else { throw ProjectInconsistencyError.objectNotFound(id: id) }
guard let obj = wrapped.wrappedValue as? T else {
throw ProjectInconsistencyError.unexpectedObjectType(id: id, expectedType: T.self, found: wrapped.wrappedValue)
}
return obj
}
/// Returns the `PBXObject` instance with the given `ObjectUUID`, by looking it up in the list of `objects` registered in the project.
func object<T: PBXObject>(id: ObjectUUID) -> T? {
try? object(id: id) as T
}
/// The `PBXProject` corresponding to the `rootObject` of the project file.
var rootProject: PBXProject { try! object(id: rootObject) }
/// The `PBXGroup` corresponding to the main groop serving as root for the whole hierarchy of files and groups in the project.
var mainGroup: PBXGroup { try! object(id: rootProject.mainGroup) }
/// The list of `PBXNativeTarget` targets found in the project.
var nativeTargets: [PBXNativeTarget] { rootProject.targets.compactMap(object(id:)) }
/// The list of `PBXBuildFile` build file references included in a given target.
func buildFiles(for target: PBXNativeTarget) -> [PBXBuildFile] {
guard let sourceBuildPhase: PBXSourcesBuildPhase = target.buildPhases.lazy.compactMap(object(id:)).first else { return [] }
return sourceBuildPhase.files.compactMap(object(id:)) as [PBXBuildFile]
}
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents the root project object.
struct PBXProject: PBXObject {
let mainGroup: ObjectUUID
let targets: [ObjectUUID]
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a native target (i.e. a target building an app, app extension, bundle...).
/// - note: Does not represent other types of targets like `PBXAggregateTarget`, only native ones.
struct PBXNativeTarget: PBXObject {
let name: String
let buildPhases: [ObjectUUID]
let productType: String
var knownProductType: ProductType? { ProductType(rawValue: productType) }
enum ProductType: String, Decodable {
case app = "com.apple.product-type.application"
case appExtension = "com.apple.product-type.app-extension"
case unitTest = "com.apple.product-type.bundle.unit-test"
case uiTest = "com.apple.product-type.bundle.ui-testing"
case framework = "com.apple.product-type.framework"
}
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a "Compile Sources" build phase containing a list of files to compile.
/// - note: Does not represent other types of Build Phases that could exist in the project, only "Compile Sources" one
struct PBXSourcesBuildPhase: PBXObject {
let files: [ObjectUUID]
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a single build file in a `PBXSourcesBuildPhase` build phase.
struct PBXBuildFile: PBXObject {
let fileRef: ObjectUUID?
}
/// This type is used to indicate what a file reference in the project is actually relative to
enum SourceTree: String, Decodable, CustomStringConvertible {
case absolute = "<absolute>"
case group = "<group>"
case projectRoot = "SOURCE_ROOT"
case buildProductsDir = "BUILT_PRODUCTS_DIR"
case devDir = "DEVELOPER_DIR"
case sdkDir = "SDKROOT"
var description: String { rawValue }
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a reference to a file contained in the project tree.
struct PBXFileReference: PBXReference {
let name: String?
let path: String?
let sourceTree: SourceTree
}
/// One of the many `PBXObject` types encountered in the `.pbxproj` file format.
/// Represents a group (aka "folder") contained in the project tree.
struct PBXGroup: PBXReference {
let name: String?
let path: String?
let sourceTree: SourceTree
let children: [ObjectUUID]
}
/// Fallback type for any unknown `PBXObject` type.
struct UnknownPBXObject: PBXObject {
let isa: String
}
/// Wrapper helper to decode any `PBXObject` based on the value of their `isa` field
@propertyWrapper
struct PBXObjectWrapper: Decodable, CustomDebugStringConvertible {
let wrappedValue: PBXObject
static let knownTypes: [PBXObject.Type] = [
PBXProject.self,
PBXGroup.self,
PBXFileReference.self,
PBXNativeTarget.self,
PBXSourcesBuildPhase.self,
PBXBuildFile.self
]
init(from decoder: Decoder) throws {
let untypedObject = try UnknownPBXObject(from: decoder)
if let objectType = Self.knownTypes.first(where: { $0.isa == untypedObject.isa }) {
self.wrappedValue = try objectType.init(from: decoder)
} else {
self.wrappedValue = untypedObject
}
}
var debugDescription: String { String(describing: wrappedValue) }
}
}
// MARK: - Lint method
/// The outcome of running our lint logic on a file
enum LintResult { case ok, skipped, violationsFound([(line: Int, col: Int)]) }
/// Lint a given file for usages of `NSLocalizedString` instead of `AppLocalizedString`
func lint(fileAt url: URL, targetName: String) throws -> LintResult {
guard ["m", "swift"].contains(url.pathExtension) else { return .skipped }
let content = try String(contentsOf: url)
var lineNo = 0
var violations: [(line: Int, col: Int)] = []
content.enumerateLines { line, _ in
lineNo += 1
guard line.range(of: "\\s*//", options: .regularExpression) == nil else { return } // Skip commented lines
guard let range = line.range(of: "NSLocalizedString") else { return }
// Violation found, report it
let colNo = line.distance(from: line.startIndex, to: range.lowerBound)
let message = "Use `AppLocalizedString` instead of `NSLocalizedString` in source files that are used in the `\(targetName)` extension target. See paNNhX-nP-p2 for more info."
print("\(url.path):\(lineNo):\(colNo): error: \(message)")
violations.append((lineNo, colNo))
}
return violations.isEmpty ? .ok : .violationsFound(violations)
}
// MARK: - Main (Script Code entry point)
// 1st arg = project path
let args = CommandLine.arguments.dropFirst()
guard let projectPath = args.first, !projectPath.isEmpty else { print("You must provide the path to the xcodeproj as first argument."); exit(1) }
do {
let project = try Xcodeproj(path: projectPath)
// 2nd arg (optional) = name of target to lint
let targetsToLint: [Xcodeproj.PBXNativeTarget]
if let targetName = args.dropFirst().first, !targetName.isEmpty {
print("Selected target: \(targetName)")
targetsToLint = project.nativeTargets.filter { $0.name == targetName }
} else {
print("Linting all app extension targets")
targetsToLint = project.nativeTargets.filter { $0.knownProductType == .appExtension }
}
// Lint each requested target
var violationsFound = 0
for target in targetsToLint {
let buildFiles: [Xcodeproj.PBXBuildFile] = project.buildFiles(for: target)
print("Linting the Build Files for \(target.name):")
for buildFile in buildFiles {
guard let fileURL = try project.resolveURL(to: buildFile) else { continue }
let result = try lint(fileAt: fileURL.absoluteURL, targetName: target.name)
print(" - \(fileURL.relativePath) [\(result)]")
if case .violationsFound(let list) = result { violationsFound += list.count }
}
}
print("Done! \(violationsFound) violation(s) found.")
exit(violationsFound > 0 ? 1 : 0)
} catch let error {
print("\(projectPath): error: Error while parsing the project file \(projectPath): \(error.localizedDescription)")
exit(2)
}
|
b5faf4468f3f63632817077e9027911b
| 47.766871 | 182 | 0.659957 | false | false | false | false |
brokenhandsio/SteamPress
|
refs/heads/master
|
Sources/SteamPress/Services/NumericPostFormatter.swift
|
mit
|
1
|
import Foundation
import Vapor
struct NumericPostDateFormatter: ServiceType {
static func makeService(for container: Container) throws -> NumericPostDateFormatter {
return .init()
}
let formatter: DateFormatter
init() {
self.formatter = DateFormatter()
self.formatter.calendar = Calendar(identifier: .iso8601)
self.formatter.locale = Locale(identifier: "en_US_POSIX")
self.formatter.timeZone = TimeZone(secondsFromGMT: 0)
self.formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
}
}
|
a248e7834719cdaef00da47b00c063b5
| 28.842105 | 90 | 0.679012 | false | false | false | false |
mrdepth/EVEUniverse
|
refs/heads/master
|
Legacy/Neocom/Neocom/NCFleetConfiguration.swift
|
lgpl-2.1
|
2
|
//
// NCFleetConfiguration.swift
// Neocom
//
// Created by Artem Shimanski on 15.02.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
public class NCFleetConfiguration: NSObject, NSCoding {
var pilots: [Int: String]?
var links: [Int: Int]?
override init() {
super.init()
}
public required init?(coder aDecoder: NSCoder) {
if let d = aDecoder.decodeObject(forKey: "pilots") as? [String: String] {
pilots = Dictionary(d.map{ (Int($0) ?? $0.hashValue, $1) },
uniquingKeysWith: { (first, _) in first})
}
else {
pilots = aDecoder.decodeObject(forKey: "pilots") as? [Int: String]
}
if let d = aDecoder.decodeObject(forKey: "links") as? [String: String] {
links = Dictionary(d.map{ (Int($0) ?? $0.hashValue, Int($1) ?? $1.hashValue) },
uniquingKeysWith: { (first, _) in first})
}
else {
links = aDecoder.decodeObject(forKey: "links") as? [Int: Int]
}
super.init()
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(pilots, forKey: "pilots")
aCoder.encode(links, forKey: "links")
}
}
|
b2ac09d9a4ddefe41983820cc60bd29a
| 25.585366 | 82 | 0.644037 | false | false | false | false |
PekanMmd/Pokemon-XD-Code
|
refs/heads/master
|
GoDToolOSX/View Controllers/GoDTextureImporterViewController.swift
|
gpl-2.0
|
1
|
//
// GoDTextureImporterViewController.swift
// GoD Tool
//
// Created by The Steez on 07/03/2019.
//
import Cocoa
class GoDTextureImporterViewController: GoDTableViewController {
@IBOutlet var filenameField: NSTextField!
@IBOutlet var detailsField: NSTextField!
var currentFile : XGFiles?
var importer : GoDTextureImporter?
@IBOutlet var imageView: NSImageView!
@IBOutlet var thresholdSlider: NSSlider!
@IBAction func setColourThreshold(_ sender: NSSlider) {
XGColour.colourThreshold = sender.integerValue
self.loadImage()
}
@IBAction func save(_ sender: Any) {
self.saveImage()
}
var fileList: [XGFiles] = {
var allSupportedImages = [XGFiles]()
for folder in XGFolders.ISOExport("").subfolders {
allSupportedImages += folder.files.filter({ (file) -> Bool in
let gtxFile = XGFiles.nameAndFolder(file.fileName.replacingOccurrences(of: file.fileExtension, with: ""), file.folder)
return XGFileTypes.imageFormats.contains(file.fileType)
&& gtxFile.exists && gtxFile.fileType == .gtx
})
}
return allSupportedImages
}()
func loadImage() {
if let current = currentFile, current.exists {
let gtxFile = XGFiles.nameAndFolder(current.fileName.replacingOccurrences(of: current.fileExtension, with: ""), current.folder)
if let data = gtxFile.data {
let textureData = GoDTexture(data: data)
importer = GoDTextureImporter(oldTextureData: textureData, newImage: XGImage(nsImage: current.image))
importer?.replaceTextureData()
imageView.image = importer?.texture.image.nsImage
detailsField.stringValue = "Texture Format: \(textureData.format.name)"
+ (textureData.isIndexed ? "\nPalette Format: \(textureData.paletteFormat.name)" : "")
+ "\nMax Colours: \(textureData.isIndexed ? textureData.format.paletteCount.string : "None")"
+ "\nColours in image: \(XGImage.loadImageData(fromFile: current)?.colourCount.string ?? "Unknowm")"
}
}
}
func saveImage() {
if let imp = self.importer {
imp.texture.save()
}
}
override func numberOfRows(in tableView: NSTableView) -> Int {
return max(fileList.count, 1)
}
override func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 50
}
override func tableView(_ tableView: GoDTableView, didSelectRow row: Int) {
super.tableView(tableView, didSelectRow: row)
if row == -1 {
return
}
let list = fileList
if row < list.count {
let file = list[row]
self.filenameField.stringValue = file.fileName
if file.exists {
self.currentFile = file
self.loadImage()
}
} else {
self.table.reloadData()
}
}
override func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = super.tableView(tableView, viewFor: tableColumn, row: row) as? GoDTableCellView
cell?.setBackgroundColour(GoDDesign.colourWhite())
if fileList.count == 0 {
cell?.setTitle("No images to import. Export and decode some texture files from the ISO.")
}
let list = fileList
if row < list.count, list[row].exists {
let file = list[row]
cell?.setTitle(file.fileName)
} else {
self.table.reloadData()
}
if self.table.selectedRow == row {
cell?.addBorder(colour: GoDDesign.colourBlack(), width: 1)
} else {
cell?.removeBorder()
}
return cell
}
}
|
ec160a663204a1b23633eaacfb9d5fc6
| 26.636364 | 130 | 0.702452 | false | false | false | false |
mcudich/TemplateKit
|
refs/heads/master
|
Examples/TodoMVC/Source/CountText.swift
|
mit
|
1
|
//
// CountText.swift
// Example
//
// Created by Matias Cudich on 10/8/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
import TemplateKit
struct CountTextProperties: Properties {
static var tagName = "CountText"
var core = CoreProperties()
var textStyle = TextStyleProperties()
var count: String?
init() {}
init(_ properties: [String: Any]) {
core = CoreProperties(properties)
textStyle = TextStyleProperties(properties)
count = properties.cast("count")
}
mutating func merge(_ other: CountTextProperties) {
core.merge(other.core)
textStyle.merge(other.textStyle)
merge(&count, other.count)
}
}
func ==(lhs: CountTextProperties, rhs: CountTextProperties) -> Bool {
return lhs.count == rhs.count && lhs.equals(otherProperties: rhs)
}
class CountText: Component<EmptyState, CountTextProperties, UIView> {
override func render() -> Template {
var properties = TextProperties()
properties.text = self.properties.count
properties.textStyle = self.properties.textStyle
return Template(text(properties))
}
}
|
7e25eb724f31989733abcc94dc0b8187
| 21.755102 | 69 | 0.707623 | false | false | false | false |
OscarSwanros/swift
|
refs/heads/master
|
test/SILGen/protocol_optional.swift
|
apache-2.0
|
3
|
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
@objc protocol P1 {
@objc optional func method(_ x: Int)
@objc optional var prop: Int { get }
@objc optional subscript (i: Int) -> Int { get }
}
// CHECK-LABEL: sil hidden @_T017protocol_optional0B13MethodGenericyx1t_tAA2P1RzlF : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalMethodGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @owned $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_BORROW:%.*]] = begin_borrow [[T]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T_BORROW]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: end_borrow [[T_BORROW]] from [[T]]
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_owned (Int) -> ()> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: alloc_stack $Optional<@callee_owned (Int) -> ()>
// CHECK: dynamic_method_br [[T]] : $T, #P1.method!1.foreign
var methodRef = t.method
}
// CHECK: } // end sil function '_T017protocol_optional0B13MethodGenericyx1t_tAA2P1RzlF'
// CHECK-LABEL: sil hidden @_T017protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalPropertyGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @owned $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_BORROW:%.*]] = begin_borrow [[T]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T_BORROW]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: end_borrow [[T_BORROW]] from [[T]]
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[T]] : $T, #P1.prop!getter.1.foreign
var propertyRef = t.prop
}
// CHECK: } // end sil function '_T017protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @_T017protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalSubscriptGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @owned $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_BORROW:%.*]] = begin_borrow [[T]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T_BORROW]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: end_borrow [[T_BORROW]] from [[T]]
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: [[INTCONV:%[0-9]+]] = function_ref @_T0S2i{{[_0-9a-zA-Z]*}}fC
// CHECK: [[INT64:%[0-9]+]] = metatype $@thin Int.Type
// CHECK: [[FIVELIT:%[0-9]+]] = integer_literal $Builtin.Int2048, 5
// CHECK: [[FIVE:%[0-9]+]] = apply [[INTCONV]]([[FIVELIT]], [[INT64]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK: alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[T]] : $T, #P1.subscript!getter.1.foreign
var subscriptRef = t[5]
}
// CHECK: } // end sil function '_T017protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F'
|
f4d76e20fda61defb24fe034a080c20a
| 52.205479 | 148 | 0.55484 | false | false | false | false |
RedRoster/rr-ios
|
refs/heads/master
|
RedRoster/Login/NewUserViewController.swift
|
apache-2.0
|
1
|
//
// NewUserViewController.swift
// RedRoster
//
// Created by Daniel Li on 4/3/16.
// Copyright © 2016 dantheli. All rights reserved.
//
import UIKit
class NewUserViewController: UIPageViewController {
fileprivate(set) var pages: [UIViewController] = []
func createNewUserPage(_ topText: String?, bottomText: String?, imageName: String?, isLastPage: Bool = false) -> NewUserPage? {
guard let newUserPage = storyboard?.instantiateViewController(withIdentifier: "NewUserPage") as? NewUserPage else { return nil }
newUserPage.topText = topText
newUserPage.bottomText = bottomText
newUserPage.imageName = imageName
newUserPage.isLastPage = isLastPage
return newUserPage
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
view.backgroundColor = UIColor.rosterRed()
// Instantiate pages
pages = [createNewUserPage("View courses and add them to your schedule",
bottomText: "See reviews by former students or write your own",
imageName: nil) ?? NewUserPage(),
createNewUserPage("Edit your profile and view your schedules",
bottomText: "Swipe to the right on any screen to get to the menu",
imageName: nil,
isLastPage: true) ?? NewUserPage()]
// Set first page
if let firstPage = pages.first {
setViewControllers([firstPage], direction: .forward, animated: true, completion: nil)
}
}
}
extension NewUserViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let currentIndex = pages.index(of: viewController) else { return nil }
let previousIndex = currentIndex - 1
guard previousIndex >= 0 && previousIndex < pages.count else { return nil }
return pages[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let currentIndex = pages.index(of: viewController) else { return nil }
let nextIndex = currentIndex + 1
guard nextIndex >= 0 && nextIndex < pages.count else { return nil }
return pages[nextIndex]
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return pages.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first,
let firstViewControllerIndex = pages.index(of: firstViewController) else {
return 0
}
return firstViewControllerIndex
}
}
|
8cebdb081e61824ab9f85bfe816b279d
| 38.723684 | 149 | 0.636635 | false | false | false | false |
paidy/paidy-ios
|
refs/heads/master
|
PaidyCheckoutSDK/PaidyCheckoutSDK/AuthorizeSuccessViewController.swift
|
mit
|
1
|
//
// AuthorizeSuccessViewController.swift
// Paidycheckoutsdk
//
// Copyright (c) 2015 Paidy. All rights reserved.
//
import UIKit
class AuthorizeSuccessViewController: UIViewController {
@IBOutlet var countdownTime: UILabel!
@IBOutlet var completedButton: UIButton!
var countTime = 8
var timer = NSTimer()
// default init
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
let frameworkBundle = NSBundle(identifier: "com.paidy.PaidyCheckoutSDK")
super.init(nibName: "AuthorizeSuccessViewController", bundle: frameworkBundle)
}
// requried init
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// create countdown
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("countDown:"), userInfo: nil, repeats: true)
// button style
completedButton.layer.cornerRadius = 5
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// OK button pressed
@IBAction func okButton(sender: UIButton) {
timer.invalidate()
close()
}
func countDown(timer: NSTimer) {
// count down 8 seconds
countTime--
countdownTime.text = "\(countTime)"
// close on reaching 0
if(countTime == 0) {
timer.invalidate()
close()
}
}
func close() {
let paidyCheckoutViewController: PaidyCheckOutViewController = self.parentViewController as! PaidyCheckOutViewController
paidyCheckoutViewController.sendResult()
}
}
|
6c98c97925710fb2cd09411fb0a55bfe
| 26.53125 | 135 | 0.646992 | false | false | false | false |
dvxiaofan/Pro-Swift-Learning
|
refs/heads/master
|
Part-01/01-PatternMatching/09-Where.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
let numbers = [1, 2, 3, 4, 5]
for num in numbers where num % 2 == 0 {
print(num)
}
let names: [String?] = ["xiaofan", nil, "xiaoming", nil, "hahha"]
for name in names where name != nil {
print(name)
}
for case let name? in names {
print(name)
}
|
33789e5107b31a99b0d304724cb71c8b
| 16.315789 | 65 | 0.613982 | false | false | false | false |
ivygulch/IVGFoundation
|
refs/heads/master
|
IVGFoundation/source/common/NextResponderHelper.swift
|
mit
|
1
|
//
// NextResponderHelper.swift
// IVGFoundation
//
// Created by Douglas Sjoquist on 11/28/17.
// Copyright © 2017 Ivy Gulch. All rights reserved.
//
import UIKit
public protocol UITextInputTraitsWithReturnKeyType : UITextInputTraits {
// redeclare the returnKeyType property of the parent protocol, but this time as mandatory
var returnKeyType: UIReturnKeyType { get set }
}
extension UITextField: UITextInputTraitsWithReturnKeyType {}
extension UITextView: UITextInputTraitsWithReturnKeyType {}
public class NextResponderHelper {
private var values: [UIResponder: UIResponder] = [:]
private var automaticallySetReturnKeyType: Bool
private var textFieldDelegate: UITextFieldDelegate!
public init(automaticallySetReturnKeyType: Bool = true, textFieldDelegate: UITextFieldDelegate? = nil) {
self.automaticallySetReturnKeyType = automaticallySetReturnKeyType
self.textFieldDelegate = NextResponderHelperTextFieldDelegate(nextResponderHelper: self, textFieldDelegate: textFieldDelegate)
}
public func register(responder: UIResponder?, next nextResponder: UIResponder?) {
guard let responder = responder else { return }
values[responder] = nextResponder
if automaticallySetReturnKeyType {
if let textInputTraits = responder as? UITextInputTraitsWithReturnKeyType {
textInputTraits.returnKeyType = (nextResponder == nil) ? .default : .next
}
}
if let textField = responder as? UITextField {
textField.delegate = textFieldDelegate
}
}
@discardableResult public func finish(responder: UIResponder?) -> Bool {
guard let responder = responder else { return false }
guard let nextResponder = values[responder] else {
responder.resignFirstResponder()
return false
}
if Thread.isMainThread {
nextResponder.becomeFirstResponder()
} else {
DispatchQueue.main.async {
nextResponder.becomeFirstResponder()
}
}
return true
}
}
fileprivate class NextResponderHelperTextFieldDelegate: NSObject, UITextFieldDelegate {
let nextResponderHelper: NextResponderHelper
let textFieldDelegate: UITextFieldDelegate?
init(nextResponderHelper: NextResponderHelper, textFieldDelegate: UITextFieldDelegate?) {
self.nextResponderHelper = nextResponderHelper
self.textFieldDelegate = textFieldDelegate
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
nextResponderHelper.finish(responder: textField)
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return textFieldDelegate?.textFieldShouldBeginEditing?(textField) ?? true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
textFieldDelegate?.textFieldDidBeginEditing?(textField)
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return textFieldDelegate?.textFieldShouldEndEditing?(textField) ?? true
}
func textFieldDidEndEditing(_ textField: UITextField){
textFieldDelegate?.textFieldDidEndEditing?(textField)
}
@available(iOS 10.0, *)
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
textFieldDelegate?.textFieldDidEndEditing?(textField, reason: reason)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return textFieldDelegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return textFieldDelegate?.textFieldShouldClear?(textField) ?? true
}
}
|
07e656dbb4c09bfa471613ac7d660106
| 35.838095 | 134 | 0.717166 | false | false | false | false |
buyiyang/iosstar
|
refs/heads/master
|
iOSStar/Scenes/Market/Controller/MarketViewController.swift
|
gpl-3.0
|
4
|
//
// MarketViewController.swift
// iOSStar
//
// Created by J-bb on 17/4/20.
// Copyright © 2017年 sum. All rights reserved.
//
import UIKit
class MarketViewController: UIViewController, SubViewItemSelectDelegate{
var menuView:MarketMenuView?
override func viewDidLoad() {
super.viewDidLoad()
YD_CountDownHelper.shared.start()
setCustomTitle(title: "明星热度")
translucent(clear: true)
let color = UIColor.white
navigationController?.navigationBar.setBackgroundImage(color.imageWithColor(), for: .default)
automaticallyAdjustsScrollViewInsets = false
menuView = MarketMenuView(frame: CGRect(x: 0, y: 64, width: kScreenWidth, height: kScreenHeight))
menuView?.items = ["明星"]
menuView?.menuView?.isScreenWidth = true
menuView?.delegate = self
view.addSubview(menuView!)
perform(#selector(setTypes), with: nil, afterDelay: 0.5)
}
func selectItem(starModel: MarketListModel) {
if checkLogin() {
let storyBoard = UIStoryboard(name: "Market", bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "MarketDetail") as! MarketDetailViewController
vc.starModel = starModel
navigationController?.pushViewController(vc, animated: true)
}
}
func setTypes() {
menuView?.types = [MarketClassifyModel]()
}
func requestTypeList() {
AppAPIHelper.marketAPI().requestTypeList(complete: { (response) in
if let models = response as? [MarketClassifyModel] {
var titles = [String]()
// let customModel = MarketClassifyModel()
//customModel.name = "自选"
//models.insert(customModel, at: 0)
for model in models {
titles.append(model.name)
}
self.menuView?.items = titles
self.menuView?.types = models
}
}, error: errorBlockFunc())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func searchAction() {
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
YD_CountDownHelper.shared.marketListRefresh = nil
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
YD_CountDownHelper.shared.marketListRefresh = { [weak self] (result)in
self?.menuView?.requestDataWithIndexPath()
}
}
}
|
3a72d5d9dd2d10b83104032db93d22ab
| 31.123457 | 120 | 0.616449 | false | false | false | false |
optimizely/swift-sdk
|
refs/heads/master
|
Sources/Data Model/ProjectConfig.swift
|
apache-2.0
|
1
|
//
// Copyright 2019-2022, Optimizely, Inc. and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class ProjectConfig {
var project: Project! {
didSet {
updateProjectDependentProps()
}
}
let logger = OPTLoggerFactory.getLogger()
// local runtime forcedVariations [UserId: [ExperimentId: VariationId]]
// NOTE: experiment.forcedVariations use [ExperimentKey: VariationKey] instead of ids
var whitelistUsers = AtomicProperty(property: [String: [String: String]]())
var experimentKeyMap = [String: Experiment]()
var experimentIdMap = [String: Experiment]()
var experimentFeatureMap = [String: [String]]()
var eventKeyMap = [String: Event]()
var attributeKeyMap = [String: Attribute]()
var featureFlagKeyMap = [String: FeatureFlag]()
var featureFlagKeys = [String]()
var rolloutIdMap = [String: Rollout]()
var allExperiments = [Experiment]()
var flagVariationsMap = [String: [Variation]]()
var allSegments = [String]()
// MARK: - Init
init(datafile: Data) throws {
var project: Project
do {
project = try JSONDecoder().decode(Project.self, from: datafile)
} catch {
throw OptimizelyError.dataFileInvalid
}
if !isValidVersion(version: project.version) {
throw OptimizelyError.dataFileVersionInvalid(project.version)
}
self.project = project
updateProjectDependentProps() // project:didSet is not fired in init. explicitly called.
}
convenience init(datafile: String) throws {
try self.init(datafile: Data(datafile.utf8))
}
init() {}
func updateProjectDependentProps() {
self.allExperiments = project.experiments + project.groups.map { $0.experiments }.flatMap { $0 }
self.experimentKeyMap = {
var map = [String: Experiment]()
allExperiments.forEach { exp in
map[exp.key] = exp
}
return map
}()
self.experimentIdMap = {
var map = [String: Experiment]()
allExperiments.forEach { map[$0.id] = $0 }
return map
}()
self.experimentFeatureMap = {
var experimentFeatureMap = [String: [String]]()
project.featureFlags.forEach { (ff) in
ff.experimentIds.forEach {
if var arr = experimentFeatureMap[$0] {
arr.append(ff.id)
experimentFeatureMap[$0] = arr
} else {
experimentFeatureMap[$0] = [ff.id]
}
}
}
return experimentFeatureMap
}()
self.eventKeyMap = {
var eventKeyMap = [String: Event]()
project.events.forEach { eventKeyMap[$0.key] = $0 }
return eventKeyMap
}()
self.attributeKeyMap = {
var map = [String: Attribute]()
project.attributes.forEach { map[$0.key] = $0 }
return map
}()
self.featureFlagKeyMap = {
var map = [String: FeatureFlag]()
project.featureFlags.forEach { map[$0.key] = $0 }
return map
}()
self.featureFlagKeys = {
return project.featureFlags.map { $0.key }
}()
self.rolloutIdMap = {
var map = [String: Rollout]()
project.rollouts.forEach { map[$0.id] = $0 }
return map
}()
// all variations for each flag
// - datafile does not contain a separate entity for this.
// - we collect variations used in each rule (experiment rules and delivery rules)
self.flagVariationsMap = {
var map = [String: [Variation]]()
project.featureFlags.forEach { flag in
var variations = [Variation]()
getAllRulesForFlag(flag).forEach { rule in
rule.variations.forEach { variation in
if variations.filter({ $0.id == variation.id }).first == nil {
variations.append(variation)
}
}
}
map[flag.key] = variations
}
return map
}()
self.allSegments = {
let audiences = project.typedAudiences ?? []
return Array(Set(audiences.flatMap { $0.getSegments() }))
}()
}
func getAllRulesForFlag(_ flag: FeatureFlag) -> [Experiment] {
var rules = flag.experimentIds.compactMap { experimentIdMap[$0] }
let rollout = self.rolloutIdMap[flag.rolloutId]
rules.append(contentsOf: rollout?.experiments ?? [])
return rules
}
}
// MARK: - Persistent Data
extension ProjectConfig {
func whitelistUser(userId: String, experimentId: String, variationId: String) {
whitelistUsers.performAtomic { whitelist in
var dict = whitelist[userId] ?? [String: String]()
dict[experimentId] = variationId
whitelist[userId] = dict
}
}
func removeFromWhitelist(userId: String, experimentId: String) {
whitelistUsers.performAtomic { whitelist in
whitelist[userId]?.removeValue(forKey: experimentId)
}
}
func getWhitelistedVariationId(userId: String, experimentId: String) -> String? {
if let dict = whitelistUsers.property?[userId] {
return dict[experimentId]
}
logger.d(.userHasNoForcedVariation(userId))
return nil
}
func isValidVersion(version: String) -> Bool {
// old versions (< 4) of datafiles not supported
return ["4"].contains(version)
}
}
// MARK: - Project Access
extension ProjectConfig {
/**
* Get sendFlagDecisions value.
*/
var sendFlagDecisions: Bool {
return project.sendFlagDecisions ?? false
}
/**
* ODP API server publicKey.
*/
var publicKeyForODP: String? {
return project.integrations?.filter { $0.key == "odp" }.first?.publicKey
}
/**
* ODP API server host.
*/
var hostForODP: String? {
return project.integrations?.filter { $0.key == "odp" }.first?.host
}
/**
* Get an Experiment object for a key.
*/
func getExperiment(key: String) -> Experiment? {
return experimentKeyMap[key]
}
/**
* Get an Experiment object for an Id.
*/
func getExperiment(id: String) -> Experiment? {
return experimentIdMap[id]
}
/**
* Get an experiment Id for the human readable experiment key
**/
func getExperimentId(key: String) -> String? {
return getExperiment(key: key)?.id
}
/**
* Get a Group object for an Id.
*/
func getGroup(id: String) -> Group? {
return project.groups.filter { $0.id == id }.first
}
/**
* Get a Feature Flag object for a key.
*/
func getFeatureFlag(key: String) -> FeatureFlag? {
return featureFlagKeyMap[key]
}
/**
* Get all Feature Flag objects.
*/
func getFeatureFlags() -> [FeatureFlag] {
return project.featureFlags
}
/**
* Get a Rollout object for an Id.
*/
func getRollout(id: String) -> Rollout? {
return rolloutIdMap[id]
}
/**
* Gets an event for a corresponding event key
*/
func getEvent(key: String) -> Event? {
return eventKeyMap[key]
}
/**
* Gets an event id for a corresponding event key
*/
func getEventId(key: String) -> String? {
return getEvent(key: key)?.id
}
/**
* Get an attribute for a given key.
*/
func getAttribute(key: String) -> Attribute? {
return attributeKeyMap[key]
}
/**
* Get an attribute Id for a given key.
**/
func getAttributeId(key: String) -> String? {
return getAttribute(key: key)?.id
}
/**
* Get an audience for a given audience id.
*/
func getAudience(id: String) -> Audience? {
return project.getAudience(id: id)
}
/**
* Returns true if experiment belongs to any feature, false otherwise.
*/
func isFeatureExperiment(id: String) -> Bool {
return !(experimentFeatureMap[id]?.isEmpty ?? true)
}
/**
* Get forced variation for a given experiment key and user id.
*/
func getForcedVariation(experimentKey: String, userId: String) -> DecisionResponse<Variation> {
let reasons = DecisionReasons()
guard let experiment = getExperiment(key: experimentKey) else {
return DecisionResponse(result: nil, reasons: reasons)
}
if let id = getWhitelistedVariationId(userId: userId, experimentId: experiment.id) {
if let variation = experiment.getVariation(id: id) {
let info = LogMessage.userHasForcedVariation(userId, experiment.key, variation.key)
logger.d(info)
reasons.addInfo(info)
return DecisionResponse(result: variation, reasons: reasons)
}
let info = LogMessage.userHasForcedVariationButInvalid(userId, experiment.key)
logger.d(info)
reasons.addInfo(info)
return DecisionResponse(result: nil, reasons: reasons)
}
logger.d(.userHasNoForcedVariationForExperiment(userId, experiment.key))
return DecisionResponse(result: nil, reasons: reasons)
}
/**
* Set forced variation for a given experiment key and user id according to a given variation key.
*/
func setForcedVariation(experimentKey: String, userId: String, variationKey: String?) -> Bool {
guard let experiment = getExperiment(key: experimentKey) else {
return false
}
guard var variationKey = variationKey else {
logger.d(.variationRemovedForUser(userId, experimentKey))
self.removeFromWhitelist(userId: userId, experimentId: experiment.id)
return true
}
// TODO: common function to trim all keys
variationKey = variationKey.trimmingCharacters(in: NSCharacterSet.whitespaces)
guard !variationKey.isEmpty else {
logger.e(.variationKeyInvalid(experimentKey, variationKey))
return false
}
guard let variation = experiment.getVariation(key: variationKey) else {
logger.e(.variationKeyInvalid(experimentKey, variationKey))
return false
}
self.whitelistUser(userId: userId, experimentId: experiment.id, variationId: variation.id)
logger.d(.userMappedToForcedVariation(userId, experiment.id, variation.id))
return true
}
func getFlagVariationByKey(flagKey: String, variationKey: String) -> Variation? {
if let variations = flagVariationsMap[flagKey] {
return variations.filter { $0.key == variationKey }.first
}
return nil
}
}
|
fd0b71ebd4985df1a7fc9e52bc98f42b
| 30.135065 | 104 | 0.573872 | false | false | false | false |
WickedColdfront/Slide-iOS
|
refs/heads/master
|
Pods/SAHistoryNavigationViewController/SAHistoryNavigationViewController/SAHistoryNavigationTransitionController.swift
|
apache-2.0
|
2
|
//
// SAHistoryNavigationTransitionController.swift
// SAHistoryNavigationViewController
//
// Created by 鈴木大貴 on 2015/05/26.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
class SAHistoryNavigationTransitionController: NSObject, UIViewControllerAnimatedTransitioning {
//MARK: - Static constants
fileprivate struct Const {
static let defaultDuration: TimeInterval = 0.3
}
//MARK: - Properties
fileprivate(set) var navigationControllerOperation: UINavigationControllerOperation
fileprivate var currentTransitionContext: UIViewControllerContextTransitioning?
fileprivate var backgroundView: UIView?
fileprivate var alphaView: UIView?
//MARK: - Initializers
required init(operation: UINavigationControllerOperation) {
navigationControllerOperation = operation
super.init()
}
//MARK: Life cycle
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return Const.defaultDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let fromView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)?.view,
let toView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)?.view
else { return }
let containerView = transitionContext.containerView
currentTransitionContext = transitionContext
switch navigationControllerOperation {
case .push:
pushAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView)
case .pop:
popAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView)
case .none:
let cancelled = transitionContext.transitionWasCancelled
transitionContext.completeTransition(!cancelled)
}
}
func forceFinish() {
let navigationControllerOperation = self.navigationControllerOperation
guard let backgroundView = backgroundView, let alphaView = alphaView else { return }
let dispatchTime = DispatchTime.now() + Double(Int64((Const.defaultDuration + 0.1) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime) { [weak self] in
guard let currentTransitionContext = self?.currentTransitionContext else { return }
let toViewContoller = currentTransitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
let fromViewContoller = currentTransitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
guard let fromView = fromViewContoller?.view, let toView = toViewContoller?.view else { return }
switch navigationControllerOperation {
case .push:
self?.pushAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
case .pop:
self?.popAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
case .none:
let cancelled = currentTransitionContext.transitionWasCancelled
currentTransitionContext.completeTransition(!cancelled)
}
self?.currentTransitionContext = nil
self?.backgroundView = nil
self?.alphaView = nil
}
}
//MARK: - Pop animations
fileprivate func popAnimation(_ transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) {
let backgroundView = UIView(frame: containerView.bounds)
backgroundView.backgroundColor = .black
containerView.addSubview(backgroundView)
self.backgroundView = backgroundView
toView.frame = containerView.bounds
containerView.addSubview(toView)
let alphaView = UIView(frame: containerView.bounds)
alphaView.backgroundColor = .black
containerView.addSubview(alphaView)
self.alphaView = alphaView
fromView.frame = containerView.bounds
containerView.addSubview(fromView)
let completion: (Bool) -> Void = { [weak self] finished in
if finished {
self?.popAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
}
}
toView.frame.origin.x = -(toView.frame.size.width / 4.0)
alphaView.alpha = 0.4
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: .curveEaseOut, animations: {
toView.frame.origin.x = 0
fromView.frame.origin.x = containerView.frame.size.width
alphaView.alpha = 0.0
}, completion: completion)
}
fileprivate func popAniamtionCompletion(_ transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) {
let cancelled = transitionContext.transitionWasCancelled
if cancelled {
toView.transform = CGAffineTransform.identity
toView.removeFromSuperview()
} else {
fromView.removeFromSuperview()
}
backgroundView.removeFromSuperview()
alphaView.removeFromSuperview()
transitionContext.completeTransition(!cancelled)
currentTransitionContext = nil
self.backgroundView = nil
self.alphaView = nil
}
//MARK: - pushAnimations
fileprivate func pushAnimation(_ transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) {
let backgroundView = UIView(frame: containerView.bounds)
backgroundView.backgroundColor = .black
containerView.addSubview(backgroundView)
self.backgroundView = backgroundView
fromView.frame = containerView.bounds
containerView.addSubview(fromView)
let alphaView = UIView(frame: containerView.bounds)
alphaView.backgroundColor = .black
alphaView.alpha = 0.0
containerView.addSubview(alphaView)
self.alphaView = alphaView
toView.frame = containerView.bounds
toView.frame.origin.x = containerView.frame.size.width
containerView.addSubview(toView)
let completion: (Bool) -> Void = { [weak self] finished in
if finished {
self?.pushAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
}
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: .curveEaseOut, animations: {
fromView.frame.origin.x = -(fromView.frame.size.width / 4.0)
toView.frame.origin.x = 0.0
alphaView.alpha = 0.4
}, completion: completion)
}
fileprivate func pushAniamtionCompletion(_ transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) {
let cancelled = transitionContext.transitionWasCancelled
if cancelled {
toView.removeFromSuperview()
}
fromView.transform = CGAffineTransform.identity
backgroundView.removeFromSuperview()
fromView.removeFromSuperview()
alphaView.removeFromSuperview()
transitionContext.completeTransition(!cancelled)
currentTransitionContext = nil
self.backgroundView = nil
self.alphaView = nil
}
}
|
6480a833fccca05cb86981937eff4571
| 43.718232 | 182 | 0.678404 | false | false | false | false |
schluchter/berlin-transport
|
refs/heads/master
|
berlin-transport/berlin-trnsprt/BTMapUtilities.swift
|
mit
|
1
|
//
// BTMapUtilities.swift
// berlin-transport
//
// Created by Thomas Schluchter on 10/27/14.
// Copyright (c) 2014 Thomas Schluchter. All rights reserved.
//
import Foundation
import MapKit
import CoreLocation
public class BTMapUtils {
public class func centerBetweenPoints(one: CLLocationCoordinate2D, _ two: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
let latitudeDelta = abs(one.latitude - two.latitude) / 2.0
let longitudeDelta = abs(one.longitude - two.longitude) / 2.0
let latNew = latitudeDelta + min(one.latitude, two.latitude)
let longNew = longitudeDelta + min(one.longitude, two.longitude)
return CLLocationCoordinate2DMake(latNew, longNew)
}
public class func formatDistance(distance: Int) -> String {
let formatter = MKDistanceFormatter()
formatter.units = MKDistanceFormatterUnits.Metric
formatter.unitStyle = MKDistanceFormatterUnitStyle.Abbreviated
return formatter.stringFromDistance(CLLocationDistance(distance))
}
}
|
ed0eafb8cdcc8eb21692efae24045064
| 32 | 129 | 0.694215 | false | false | false | false |
tarrencev/BitWallet
|
refs/heads/master
|
BitWallet/TransactionsTableViewController.swift
|
mit
|
1
|
//
// TransactionsTableViewController.swift
// BitWallet
//
// Created by Tarrence van As on 8/15/14.
// Copyright (c) 2014 tva. All rights reserved.
//
import UIKit
class TransactionsTableViewController: UITableViewController {
var transactions: Array<Transaction> = []
override func viewDidLoad() {
super.viewDidLoad()
let sendInitiatorCellNib = UINib(nibName: "TransactionsTableViewCell", bundle: nil)
tableView.registerNib(sendInitiatorCellNib, forCellReuseIdentifier: "transactionsCell")
self.tableView.backgroundColor = .clearColor()
Chain.sharedInstance().getAddressTransactions(UserInfoManager.getPublicAddress(), limit: 2, completionHandler: { (response, error) -> Void in
if response != nil {
let responseDictionary = response as NSDictionary,
resultsArray = responseDictionary["results"] as Array<NSDictionary>
for transactionData in resultsArray {
let transaction = Transaction(rawData: transactionData)
self.transactions.append(transaction)
}
self.tableView.reloadData()
} else {
println(error)
}
})
}
func viewIsScrollingOnScreen() {
println("scrolling on screen")
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactions.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("transactionsCell", forIndexPath: indexPath) as TransactionsTableViewCell
let transaction = transactions[indexPath.row],
addresses = transaction.amount
cell.setUser(transaction.outputs[0].addresses[0])
cell.setAmount(String(transaction.amount))
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65
}
}
|
91e82c04f192db80f0a226dcf244f565
| 32.539474 | 149 | 0.640643 | false | false | false | false |
SereivoanYong/Charts
|
refs/heads/master
|
Source/Charts/Data/Implementations/Standard/BarEntry.swift
|
apache-2.0
|
1
|
//
// BarEntry.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class BarEntry: Entry {
/// the values the stacked barchart holds
fileprivate var _yVals: [CGFloat]?
/// the ranges for the individual stack values - automatically calculated
fileprivate var _ranges: [Range]?
/// the sum of all negative values this entry (if stacked) contains
fileprivate var _negativeSum: CGFloat = 0.0
/// the sum of all positive values this entry (if stacked) contains
fileprivate var _positiveSum: CGFloat = 0.0
/// Constructor for normal bars (not stacked).
public override init(x: CGFloat, y: CGFloat, icon: UIImage? = nil, data: Any? = nil) {
super.init(x: x, y: y, icon: icon, data: data)
}
/// Constructor for stacked bar entries. One data object for whole stack
public init(x: CGFloat, yValues: [CGFloat], icon: UIImage? = nil, data: Any? = nil) {
super.init(x: x, y: BarEntry.calcSum(values: yValues), icon: icon, data: data)
self._yVals = yValues
calcPosNegSum()
calcRanges()
}
open func sumBelow(stackIndex :Int) -> CGFloat
{
if _yVals == nil
{
return 0
}
var remainder = 0.0 as CGFloat
var index = _yVals!.count - 1
while (index > stackIndex && index >= 0)
{
remainder += _yVals![index]
index -= 1
}
return remainder
}
/// - returns: The sum of all negative values this entry (if stacked) contains. (this is a positive number)
open var negativeSum: CGFloat {
return _negativeSum
}
/// - returns: The sum of all positive values this entry (if stacked) contains.
open var positiveSum: CGFloat {
return _positiveSum
}
open func calcPosNegSum()
{
if _yVals == nil
{
_positiveSum = 0.0
_negativeSum = 0.0
return
}
var sumNeg = 0.0 as CGFloat
var sumPos = 0.0 as CGFloat
for f in _yVals!
{
if f < 0.0
{
sumNeg += -f
}
else
{
sumPos += f
}
}
_negativeSum = sumNeg
_positiveSum = sumPos
}
/// Splits up the stack-values of the given bar-entry into Range objects.
/// - parameter entry:
/// - returns:
open func calcRanges()
{
let values = yValues
if values?.isEmpty != false
{
return
}
if _ranges == nil
{
_ranges = [Range]()
}
else
{
_ranges?.removeAll()
}
_ranges?.reserveCapacity(values!.count)
var negRemain = -negativeSum
var posRemain = 0.0 as CGFloat
for i in 0 ..< values!.count
{
let value = values![i]
if value < 0
{
_ranges?.append(Range(from: negRemain, to: negRemain - value))
negRemain -= value
}
else
{
_ranges?.append(Range(from: posRemain, to: posRemain + value))
posRemain += value
}
}
}
// MARK: Accessors
/// the values the stacked barchart holds
open var isStacked: Bool { return _yVals != nil }
/// the values the stacked barchart holds
open var yValues: [CGFloat]?
{
get { return self._yVals }
set
{
self.y = BarEntry.calcSum(values: newValue)
self._yVals = newValue
calcPosNegSum()
calcRanges()
}
}
/// - returns: The ranges of the individual stack-entries. Will return null if this entry is not stacked.
open var ranges: [Range]?
{
return _ranges
}
/// Calculates the sum across all values of the given stack.
///
/// - parameter vals:
/// - returns:
fileprivate static func calcSum(values: [CGFloat]?) -> CGFloat
{
guard let values = values
else { return 0.0 }
var sum = 0.0 as CGFloat
for f in values
{
sum += f
}
return sum
}
}
|
68c61c710effa43ea90715ef8e797266
| 20.802198 | 109 | 0.585938 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/URLSession/URLSession/UICopyLabel.swift
|
mit
|
1
|
//
// UICopyLabel.swift
// URLSession
//
// Created by 黄伯驹 on 2017/9/11.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
// http://www.hangge.com/blog/cache/detail_1085.html
// http://www.jianshu.com/p/10a6900cc904
class UICopyLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
func sharedInit() {
isUserInteractionEnabled = true
addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(showMenu)))
}
@objc func showMenu(sender: UILongPressGestureRecognizer) {
switch sender.state {
case .began:
becomeFirstResponder()
let menu = UIMenuController.shared
if !menu.isMenuVisible {
menu.setTargetRect(bounds, in: self)
menu.setMenuVisible(true, animated: true)
}
default:
break
}
}
//复制
override func copy(_ sender: Any?) {
let board = UIPasteboard.general
board.string = text
let menu = UIMenuController.shared
menu.setMenuVisible(false, animated: true)
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(UIResponderStandardEditActions.copy(_:)) {
return true
}
return false
}
}
|
a4a539c56db5add4f618197e582a4a3e
| 24.412698 | 101 | 0.598376 | false | false | false | false |
alirsamar/BiOS
|
refs/heads/master
|
Stage_5/beginning-ios-pirate-fleet-pirate-fleet-1-init/Pirate Fleet/Settings.swift
|
mit
|
2
|
//
// Settings.swift
// Pirate Fleet
//
// Created by Jarrod Parkes on 8/25/15.
// Copyright © 2015 Udacity, Inc. All rights reserved.
//
// MARK: - ReadyState: String
enum ReadyState: String {
case ShipsNotReady = "You do not have the correct amount of ships. Check the Debug Area for more specific details."
case ShipsMinesNotReady = "You do not have the correct amount of ships/mines. Check the Debug Area for more specific details."
case ReadyToPlay = "All Ready!"
case Invalid = "Invalid Ready State!"
}
// MARK: - Settings
struct Settings {
static let DefaultGridSize = GridSize(width: 8, height: 8)
static let ComputerDifficulty = Difficulty.Advanced
static let RequiredShips: [ShipSize:Int] = [
.Small: 1,
.Medium: 2,
.Large: 1,
.XLarge: 1
]
static let RequiredMines = 2
static let DefaultMineText = "Boom!"
struct Messages {
static let GameOverTitle = "Game Over"
static let GameOverWin = "You won! Congrats!"
static let GameOverLose = "You've been defeated by the computer."
static let UnableToStartTitle = "Cannot Start Game"
static let ShipsNotReady = "NOTE: You need one small ship (size 2), two medium ships (size 3), one large ship (size 4), one x-large ship (size 5)."
static let ShipsMinesNotReady = "NOTE: You need one small ship (size 2), two medium ships (size 3), one large ship (size 4), one x-large ship (size 5), and two mines."
static let HumanHitMine = "You've hit a mine! The computer has been rewarded an extra move on their next turn."
static let ComputerHitMine = "The computer has hit a mine! You've been awarded an extra move on your next turn."
static let ResetAction = "Reset Game"
static let DismissAction = "Continue"
}
struct Images {
static let Water = "Water"
static let Hit = "Hit"
static let Miss = "Miss"
static let ShipEndRight = "ShipEndRight"
static let ShipEndLeft = "ShipEndLeft"
static let ShipEndDown = "ShipEndDown"
static let ShipEndUp = "ShipEndUp"
static let ShipBodyHorz = "ShipBodyHorz"
static let ShipBodyVert = "ShipBodyVert"
static let WoodenShipPlaceholder = "WoodenShipPlaceholder"
static let Mine = "Mine"
static let MineHit = "MineHit"
}
}
|
a9f40ee70ef86d4f83d525a4a40b4f4f
| 36.015152 | 175 | 0.642916 | false | false | false | false |
xdliu002/TAC_communication
|
refs/heads/master
|
PodsDemo/PodsDemo/MainTableViewController.swift
|
mit
|
1
|
//
// MainTableViewController.swift
// PodsDemo
//
// Created by Harold LIU on 3/16/16.
// Copyright © 2016 Tongji Apple Club. All rights reserved.
//
import UIKit
import LTNavigationBar
class MainTableViewController: UITableViewController {
let NAVBAR_CHANGE_POINT:CGFloat = 50
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.clearColor())
tableView.dataSource = self
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
let color = UIColor.lxd_BlueColor()
let offsetY = scrollView.contentOffset.y
if offsetY > NAVBAR_CHANGE_POINT
{
let alpha = min(1, 1-((NAVBAR_CHANGE_POINT+64-offsetY)/64))
navigationController?.navigationBar.lt_setBackgroundColor(color.colorWithAlphaComponent(alpha))
}
else
{
navigationController?.navigationBar.lt_setBackgroundColor(color.colorWithAlphaComponent(0))
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
scrollViewDidScroll(tableView)
tableView.delegate = self
navigationController?.navigationBar.shadowImage = UIImage()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
tableView.delegate = nil
navigationController?.navigationBar.lt_reset()
}
//MARK:- Delegate && Datasource
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Header"
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 5
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
cell.textLabel?.text = "balalala"
return cell
}
func injected() {
print("I've been injected: (self)")
}
}
|
db7520376dd45b53f8cf50947aae7fb5
| 27.686047 | 125 | 0.651398 | false | false | false | false |
irfanlone/Collection-View-in-a-collection-view-cell
|
refs/heads/master
|
Collections-CollectionView/MainCollectionViewCell.swift
|
mit
|
1
|
//
// MainCollectionViewCell.swift
// Collections-CollectionView
//
// Created by Irfan Lone on 4/8/16.
// Copyright © 2016 Ilone Labs. All rights reserved.
//
import UIKit
protocol CollectionViewSelectedProtocol {
func collectionViewSelected(_ collectionViewItem : Int)
}
class MainCollectionViewCell: UICollectionViewCell {
var collectionViewDataSource : UICollectionViewDataSource!
var collectionViewDelegate : UICollectionViewDelegate!
var collectionView : UICollectionView!
var delegate : CollectionViewSelectedProtocol!
var collectionViewOffset: CGFloat {
set {
collectionView.contentOffset.x = newValue
}
get {
return collectionView.contentOffset.x
}
}
func initializeCollectionViewWithDataSource<D: UICollectionViewDataSource,E: UICollectionViewDelegate>(_ dataSource: D, delegate :E, forRow row: Int) {
self.collectionViewDataSource = dataSource
self.collectionViewDelegate = delegate
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: flowLayout)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseChildCollectionViewCellIdentifier)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self.collectionViewDataSource
collectionView.delegate = self.collectionViewDelegate
collectionView.tag = row
self.addSubview(collectionView)
self.collectionView = collectionView
var frame = self.bounds
frame.size.width = 80
frame.size.height = 25
let button = UIButton(frame: frame)
button.setTitle("Details >", for: UIControlState())
button.setTitleColor(UIColor.purple, for: UIControlState())
button.titleLabel?.font = UIFont(name: "Gillsans", size: 14)
button.addTarget(self, action: #selector(MainCollectionViewCell.buttonAction(_:)), for: UIControlEvents.touchUpInside)
self.addSubview(button)
collectionView.reloadData()
}
func buttonAction(_ sender: UIButton!) {
self.delegate.collectionViewSelected(collectionView.tag)
}
}
|
1bf2c6efe3da6cea54d55f91d9401942
| 30.868421 | 155 | 0.682494 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet
|
refs/heads/good
|
NoteOptionTableViewController.swift
|
mit
|
1
|
//
// NoteOptionTableViewController.swift
// SwiftGL
//
// Created by jerry on 2016/2/19.
// Copyright © 2016年 Jerry Chan. All rights reserved.
//
import UIKit
enum NoteOptionAction{
case drawRevision
case none
}
class NoteOptionTableViewController: UITableViewController {
weak var delegate:PaintViewController!
override func viewWillAppear(_ animated: Bool) {
view.layer.cornerRadius = 0
}
@IBOutlet weak var enterRevisionModeButton: UITableViewCell!
var action:NoteOptionAction = .none
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.cellForRow(at: indexPath) ==
enterRevisionModeButton
{
//delegate.
action = .drawRevision
dismiss(animated: true, completion: {})
delegate.noteOptionDrawRevisionTouched()
}
}
}
|
2670bc4569ca591e3cfc25fbd1bdbf34
| 26.757576 | 92 | 0.665939 | false | false | false | false |
CodaFi/swift-compiler-crashes
|
refs/heads/master
|
crashes-fuzzing/19114-clang-namespacedecl-namespacedecl.swift
|
mit
|
11
|
// 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 B : a {
case c,
typealias e = [ {
struct g<d<T where k.a<T>: b {
class A {
println( 1 )
class
let a {
case c,
struct A {
protocol a {
struct g<d where B : b = j
var d = a<T> (v: e.b { func e
typealias e = [ {
{
i>: e
func a<T>: b {
case ,
func b
{
struct g<T>: b {
func < {
func < {
class
protocol B : e
let end = [ {
let end = 0 as a
protocol a {
{
struct A<T>: a {
class
class
{
case c,
class A {
i>: d<T>: e
let f = [Void{
println( 1 )
var d = [Void{
let end = [Void{
deinit {
case c,
class B? {
struct A {
class
class B : e.h
typealias e : a {
case ,
protocol B : e
var d where k.b = [ {
func b
case c,
let end = [ {
typealias e = B? {
}
let f = 0 as a
case c,
struct g<T>
case ,
class
class
class A {
case c,
let a {
class
class
deinit {
class
func a<T where B {
class
func a<d<T where B : B, leng
var d where B : a {
class
struct A {
class A {
case c,
func a
typealias e : B<T>
let f = [Void{
let f = [ {
struct A<T> (v: d<d where k.a<T where k.b {
let end = 0 as a
"
func a<T where k.h
let end = [Void{
func a
case c,
class
let end = [Void{
println( 1 )
deinit {
func a
class
func a"
let end = [ {
let end = a<d: B, leng
protocol B : B<T> (v: B, leng
var b {
case c,
case c,
case c,
var d where k.h
protocol B : b {
struct A {
protocol A {
typealias e : d: e
let end = [Void{
let end = B<T> (v: e
case c,
class B : d<T>
{
class a {
case c,
let a {
case c,
{
let a {
struct A<T>: e
class B : e
struct A {
case c,
case c,
{
"
class
func a<d
case c,
typealias e = j
func a
class B<T>
let a {
class
class
func a<d where B : d
class
let end = [Void{
{
let a {
case c,
protocol a {
var b = [Void{
0.b = a<T> (v: a {
class
let f = [Void{
var b {
case c,
class a {
case ,
case c,
protocol a {
class B {
case c,
}
typealias e = B? {
func a
typealias e = [ {
let end = B? {
class
class d
func b
let a {
func e.a
0.b {
let end = [Void{
0.b {
}
{
var b {
let end = [ {
class B<T>
var d where k.h
func b
func e
typealias e = 0 as a
class A {
protocol a {
let end = [ {
{
deinit {
let a {
case c,
class
let end = [ {
"
class
let end = j
let a {
let end = a
class a {
"
func e.h
let end = j
class
protocol B : b = [ {
func b
typealias e : b { func b
func < {
struct A<d where B {
struct A<T> (v: b {
class
"
protocol c {
func a<d = [Void{
|
104f26c9bf871d1eca3cdc7d10b0fd3e
| 10.637681 | 87 | 0.601494 | false | false | false | false |
kingka/SwiftWeiBo
|
refs/heads/master
|
SwiftWeiBo/SwiftWeiBo/Classes/Home/StatusesCell.swift
|
mit
|
1
|
//
// StatusesCell.swift
// SwiftWeiBo
//
// Created by Imanol on 16/4/18.
// Copyright © 2016年 imanol. All rights reserved.
//
import UIKit
import SDWebImage
class StatusesCell: UITableViewCell {
var widthConstraint : NSLayoutConstraint?
var heightConstraint : NSLayoutConstraint?
///topConstraint是用来控制当没有配图的时候,去除顶部的10像素约束
var topConstraint : NSLayoutConstraint?
var statuses : Statuses?
{
didSet{
context.attributedText = EmoticonPackage.changeText2AttributeText(statuses?.text ?? "")
topView.statuses = statuses
//计算配图尺寸
picView.statuses = statuses?.retweeted_status != nil ? statuses?.retweeted_status : statuses
let caculateSize = picView.calculateSize()
//picView的总体大小
widthConstraint?.constant = caculateSize.width
heightConstraint?.constant = caculateSize.height
topConstraint?.constant = caculateSize.height==1 ? 0 : 10
}
}
func rowHeight(status : Statuses) ->CGFloat{
//为了计算行高
self.statuses = status
//刷新 cell
self.layoutIfNeeded()
//返回底部最大的Y值
return CGRectGetMaxY(bottomView.frame)
}
func setupUI(){
topView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.top.equalTo(contentView)
make.height.lessThanOrEqualTo(100)
}
context.snp_makeConstraints { (make) -> Void in
make.top.equalTo(topView.snp_bottom).offset(10)
make.left.equalTo(topView).offset(10)
make.right.equalTo(contentView).offset(-15)
}
bottomView.snp_makeConstraints { (make) -> Void in
make.width.equalTo(contentView)
make.left.equalTo(contentView)
make.top.equalTo(picView.snp_bottom).offset(10)
make.height.equalTo(35)
//make.bottom.equalTo(contentView.snp_bottom).offset(-10)
}
}
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
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(context)
contentView.addSubview(bottomView)
contentView.addSubview(picView)
contentView.addSubview(topView)
//bottomView.backgroundColor = UIColor.grayColor()
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
///MARK: - LAZY LOADING
lazy var topView : statusTopView = statusTopView()
lazy var context : UILabel = {
let label = UILabel.createLabel(UIColor.darkGrayColor(), fontSize: 15)
label.numberOfLines = 0
return label
}()
lazy var bottomView : statusBottomView = statusBottomView()
lazy var picView : picViews = picViews()
}
|
bdd77571c4960e62a19ecceeed458947
| 28.616071 | 105 | 0.612903 | false | false | false | false |
troystribling/BlueCap
|
refs/heads/master
|
Examples/BlueCap/BlueCap/Utils/ConfigStore.swift
|
mit
|
1
|
//
// ConfigStore.swift
// BlueCap
//
// Created by Troy Stribling on 8/29/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
import BlueCapKit
import CoreBluetooth
import CoreLocation
// MARK: Defaults
struct Defaults {
static let serviceScanMode: ServiceScanMode = .promiscuous
static let peripheralSortOrder: PeripheralSortOrder = .discoveryDate
}
// MARK: Service Scan Mode
enum ServiceScanMode: Int {
case promiscuous = 0
case service = 1
init?(_ stringValue: String) {
switch stringValue {
case "Promiscuous":
self = .promiscuous
case "Service":
self = .service
default:
return nil
}
}
init?(_ rawValue: Int) {
switch rawValue {
case 0:
self = .promiscuous
case 1:
self = .service
default:
return nil
}
}
var stringValue: String {
switch self {
case .promiscuous:
return "Promiscuous"
case .service:
return "Service"
}
}
}
// MARK: Peripheral Sort Order
enum PeripheralSortOrder: Int {
case discoveryDate = 0
case rssi = 1
init?(_ stringValue: String) {
switch stringValue {
case "Discovery Date":
self = .discoveryDate
case "RSSI":
self = .rssi
default:
return nil
}
}
init?(_ rawValue: Int) {
switch rawValue {
case 0:
self = .discoveryDate
case 1:
self = .rssi
default:
return nil
}
}
var stringValue: String {
switch self {
case .discoveryDate:
return "Discovery Date"
case .rssi:
return "RSSI"
}
}
}
// MARK: - ConfigStore -
class ConfigStore {
// MARK: Scan Mode
class func getScanMode() -> ServiceScanMode {
let rawValue = UserDefaults.standard.integer(forKey: "scanMode")
if let serviceScanMode = ServiceScanMode(rawValue) {
return serviceScanMode
} else {
return Defaults.serviceScanMode
}
}
class func setScanMode(_ scanMode: ServiceScanMode) {
UserDefaults.standard.set(scanMode.rawValue, forKey:"scanMode")
}
// MARK: Scan Duration
class func getScanDurationEnabled() -> Bool {
return UserDefaults.standard.bool(forKey: "scanDurationEnabled")
}
class func setScanDurationEnabled(_ timeoutEnabled: Bool) {
UserDefaults.standard.set(timeoutEnabled, forKey:"scanDurationEnabled")
}
class func getScanDuration() -> UInt {
let timeout = UserDefaults.standard.integer(forKey: "scanDuration")
return UInt(timeout)
}
class func setScanDuration(_ duration: UInt) {
UserDefaults.standard.set(Int(duration), forKey:"scanDuration")
}
// MARK: Peripheral Connection Timeout
class func getPeripheralConnectionTimeoutEnabled() -> Bool {
return UserDefaults.standard.bool(forKey: "peripheralConnectionTimeoutEnabled")
}
class func setPeripheralConnectionTimeoutEnabled(_ timeoutEnabled: Bool) {
UserDefaults.standard.set(timeoutEnabled, forKey:"peripheralConnectionTimeoutEnabled")
}
class func getPeripheralConnectionTimeout () -> UInt {
let timeout = UserDefaults.standard.integer(forKey: "peripheralConnectionTimeout")
return UInt(timeout)
}
class func setPeripheralConnectionTimeout(_ peripheralConnectionTimeout: UInt) {
UserDefaults.standard.set(Int(peripheralConnectionTimeout), forKey:"peripheralConnectionTimeout")
}
// MARK: Characteristic Read Write Timeout
class func getCharacteristicReadWriteTimeout() -> UInt {
let characteristicReadWriteTimeout = UserDefaults.standard.integer(forKey: "characteristicReadWriteTimeout")
return UInt(characteristicReadWriteTimeout)
}
class func setCharacteristicReadWriteTimeout(_ characteristicReadWriteTimeout: UInt) {
UserDefaults.standard.set(Int(characteristicReadWriteTimeout), forKey:"characteristicReadWriteTimeout")
}
// MARK: Maximum Disconnections
class func getPeripheralMaximumDisconnectionsEnabled() -> Bool {
return UserDefaults.standard.bool(forKey: "peripheralMaximumDisconnectionsEnabled")
}
class func setPeripheralMaximumDisconnectionsEnabled(_ timeoutEnabled: Bool) {
UserDefaults.standard.set(timeoutEnabled, forKey:"peripheralMaximumDisconnectionsEnabled")
}
class func getPeripheralMaximumDisconnections() -> UInt {
let maximumDisconnections = UserDefaults.standard.integer(forKey: "peripheralMaximumDisconnections")
return UInt(maximumDisconnections)
}
class func setPeripheralMaximumDisconnections(_ maximumDisconnections: UInt) {
UserDefaults.standard.set(Int(maximumDisconnections), forKey:"peripheralMaximumDisconnections")
}
// MARK: Maximum Timeouts
class func getPeripheralMaximumTimeoutsEnabled() -> Bool {
return UserDefaults.standard.bool(forKey: "peripheralMaximumTimeoutsEnabled")
}
class func setPeripheralMaximumTimeoutsEnabled(_ timeoutEnabled: Bool) {
UserDefaults.standard.set(timeoutEnabled, forKey:"peripheralMaximumTimeoutsEnabled")
}
class func getPeripheralMaximumTimeouts() -> UInt {
let maximumTimeouts = UserDefaults.standard.integer(forKey: "peripheralMaximumTimeouts")
return UInt(maximumTimeouts)
}
class func setPeripheralMaximumTimeouts(_ maximumTimeouts: UInt) {
UserDefaults.standard.set(Int(maximumTimeouts), forKey:"peripheralMaximumTimeouts")
}
// MARK: Maximum Peripherals Connected
class func getMaximumPeripheralsConnected() -> Int {
return UserDefaults.standard.integer(forKey: "maximumPeripheralsConnected")
}
class func setMaximumPeripheralsConnected(_ maximumConnections: Int) {
UserDefaults.standard.set(maximumConnections, forKey:"maximumPeripheralsConnected")
}
// MARK: Maximum Discovered Peripherals
class func getMaximumPeripheralsDiscovered() -> Int {
return UserDefaults.standard.integer(forKey: "maximumPeripheralsDiscovered")
}
class func setMaximumPeripheralsDiscovered(_ maximumPeripherals: Int) {
UserDefaults.standard.set(maximumPeripherals, forKey:"maximumPeripheralsDiscovered")
}
// MARK: Peripheral Sort Order
class func getPeripheralSortOrder() -> PeripheralSortOrder {
let rawValue = UserDefaults.standard.integer(forKey: "peripheralSortOrder")
if let peripheralSortOrder = PeripheralSortOrder(rawValue) {
return peripheralSortOrder
} else {
return Defaults.peripheralSortOrder
}
}
class func setPeripheralSortOrder(_ sortOrder: PeripheralSortOrder) {
UserDefaults.standard.set(sortOrder.rawValue, forKey:"peripheralSortOrder")
}
// MARK: Scanned Services
class func getScannedServices() -> [String : CBUUID] {
if let storedServices = UserDefaults.standard.dictionary(forKey: "services") {
var services = [String: CBUUID]()
for (name, uuid) in storedServices {
if let uuid = uuid as? String {
services[name] = CBUUID(string: uuid)
}
}
return services
} else {
return [:]
}
}
class func getScannedServiceNames() -> [String] {
return Array(self.getScannedServices().keys)
}
class func getScannedServiceUUIDs() -> [CBUUID] {
return Array(self.getScannedServices().values)
}
class func getScannedServiceUUID(_ name: String) -> CBUUID? {
let services = self.getScannedServices()
if let uuid = services[name] {
return uuid
} else {
return nil
}
}
class func setScannedServices(_ services:[String: CBUUID]) {
var storedServices = [String:String]()
for (name, uuid) in services {
storedServices[name] = uuid.uuidString
}
UserDefaults.standard.set(storedServices, forKey:"services")
}
class func addScannedService(_ name :String, uuid: CBUUID) {
var services = self.getScannedServices()
services[name] = uuid
self.setScannedServices(services)
}
class func removeScannedService(_ name: String) {
var beacons = self.getScannedServices()
beacons.removeValue(forKey: name)
self.setScannedServices(beacons)
}
}
|
3661130d569508965e2e9ad597fae10c
| 30.381295 | 116 | 0.654746 | false | false | false | false |
miletliyusuf/MakeItHybrid
|
refs/heads/master
|
Pod/Classes/MakeItHybrid.swift
|
mit
|
1
|
import UIKit
import Foundation
public class MakeItHybrid:NSObject,UIWebViewDelegate {
public var superView:UIView
var webView = UIWebView()
var loadingView = UIActivityIndicatorView()
public override init() {
superView = UIView()
}
public func makeHybridWithUrlString(urlString:NSString) {
let url = NSURL(string: urlString as String)
let requestObject = NSURLRequest(URL: url!)
webView.delegate = self
superView.addSubview(webView)
webView.setTranslatesAutoresizingMaskIntoConstraints(false)
let view:Dictionary = ["webView":webView]
let hConst:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[webView]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: view)
let vConst:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[webView]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: view)
superView.addConstraints(hConst)
superView.addConstraints(vConst)
webView.loadRequest(requestObject)
}
public func webViewDidFinishLoad(webView: UIWebView) {
loadingView.hidden = true
}
public func webViewDidStartLoad(webView: UIWebView) {
loadingView.setTranslatesAutoresizingMaskIntoConstraints(false)
loadingView.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
superView.addSubview(loadingView)
let view:Dictionary = ["loadingView":loadingView]
let hConst:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[loadingView]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: view)
let vConst:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[loadingView]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: view)
superView.addConstraints(hConst)
superView.addConstraints(vConst)
loadingView.startAnimating()
}
}
|
b00a1a7fffc5365e20a213501468ed7f
| 36.083333 | 152 | 0.782462 | false | false | false | false |
jamesjmtaylor/weg-ios
|
refs/heads/master
|
weg-ios/Extensions/UIColor+AppColors.swift
|
mit
|
1
|
//
// UIColor+AppColors.swift
// weg-ios
//
// Created by Taylor, James on 4/28/18.
// Copyright © 2018 James JM Taylor. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
static func clear() -> UIColor {return UIColor.init(hex: "00000000")}
static func sixtyAlpa() -> UIColor {return UIColor.init(hex: "99000000")}
static func fiftyAlpa() -> UIColor {return UIColor.init(hex: "80000000")}
static func fortyAlpa() -> UIColor {return UIColor.init(hex: "66000000")}
static func colorPrimary() -> UIColor {return UIColor.init(hex: "FF000000")}
static func colorPrimaryDark() -> UIColor {return UIColor.init(hex: "FF000000")}
static func colorAccent() -> UIColor {return UIColor.init(hex: "FFFF0000")}
static func gray() -> UIColor {return UIColor.init(hex: "FFAAAAAA")}
convenience init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 0
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let a = (rgbValue & 0xff000000) >> 24
let r = (rgbValue & 0xff0000) >> 16
let g = (rgbValue & 0xff00) >> 8
let b = rgbValue & 0xff
self.init(
red: CGFloat(r) / 0xff,
green: CGFloat(g) / 0xff,
blue: CGFloat(b) / 0xff,
alpha: CGFloat(a) / 0xff
)
}
}
|
0a4f5e9f47dd397ca356b8165efc57dc
| 33 | 84 | 0.605452 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/CIFilter/issue-21-core-image-explorer-master/Core Image Explorer/FilterDetailViewController.swift
|
mit
|
1
|
//
// FilterDetailViewController.swift
// Core Image Explorer
//
// Created by Warren Moore on 1/6/15.
// Copyright (c) 2015 objc.io. All rights reserved.
//
import UIKit
class FilterDetailViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var filterName: String!
var filter: CIFilter!
var filteredImageView: FilteredImageView!
var parameterAdjustmentView: ParameterAdjustmentView!
var constraints = [NSLayoutConstraint]()
override func viewDidLoad() {
super.viewDidLoad()
filter = CIFilter(name: filterName)
navigationItem.title = filter.attributes[kCIAttributeFilterDisplayName] as? String
addSubviews()
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.setStatusBarStyle(.lightContent, animated: animated)
navigationController?.navigationBar.barStyle = .black
tabBarController?.tabBar.barStyle = .black
applyConstraintsForInterfaceOrientation(UIApplication.shared.statusBarOrientation)
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval)
{
applyConstraintsForInterfaceOrientation(toInterfaceOrientation)
}
func filterParameterDescriptors() -> [ScalarFilterParameter] {
let inputNames = (filter.inputKeys as [String]).filter { (parameterName) -> Bool in
return (parameterName as String) != "inputImage"
}
let attributes = filter.attributes
return inputNames.compactMap { (inputName: String) -> ScalarFilterParameter? in
let attribute = attributes[inputName] as! [String : AnyObject]
guard attribute[kCIAttributeSliderMin] != nil else { return nil }
// strip "input" from the start of the parameter name to make it more presentation-friendly
let displayName = String(inputName.dropFirst(5))
let minValue = (attribute[kCIAttributeSliderMin] as! NSNumber).floatValue
let maxValue = (attribute[kCIAttributeSliderMax] as! NSNumber).floatValue
let defaultValue = (attribute[kCIAttributeDefault] as! NSNumber).floatValue
return ScalarFilterParameter(name: displayName, key: inputName,
minimumValue: minValue, maximumValue: maxValue, currentValue: defaultValue)
}
}
func addSubviews() {
filteredImageView = FilteredImageView(frame: view.bounds)
filteredImageView.inputImage = UIImage(named: kSampleImageName)
filteredImageView.filter = filter
filteredImageView.contentMode = .scaleAspectFit
filteredImageView.clipsToBounds = true
filteredImageView.backgroundColor = view.backgroundColor
filteredImageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(filteredImageView)
parameterAdjustmentView = ParameterAdjustmentView(frame: view.bounds, parameters: filterParameterDescriptors())
parameterAdjustmentView.translatesAutoresizingMaskIntoConstraints = false
parameterAdjustmentView.setAdjustmentDelegate(filteredImageView)
view.addSubview(parameterAdjustmentView)
}
func applyConstraintsForInterfaceOrientation(_ interfaceOrientation: UIInterfaceOrientation) {
view.removeConstraints(constraints)
constraints.removeAll(keepingCapacity: true)
if interfaceOrientation.isLandscape {
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .width, relatedBy: .equal,
toItem: view, attribute: .width, multiplier: 0.5, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height, multiplier: 1, constant: -66))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .top, relatedBy: .equal,
toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .leading, relatedBy: .equal,
toItem: view, attribute: .leading, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .top, relatedBy: .equal,
toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .trailing, relatedBy: .equal,
toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .width, relatedBy: .equal,
toItem: view, attribute: .width, multiplier: 0.5, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height, multiplier: 1, constant: 0))
} else {
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .width, relatedBy: .equal,
toItem: view, attribute: .width, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height, multiplier: 0.5, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .top, relatedBy: .equal,
toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: filteredImageView, attribute: .leading, relatedBy: .equal,
toItem: view, attribute: .leading, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .bottom, relatedBy: .equal,
toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .leading, relatedBy: .equal,
toItem: view, attribute: .leading, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .width, relatedBy: .equal,
toItem: view, attribute: .width, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: parameterAdjustmentView, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height, multiplier: 0.5, constant: -88))
}
self.view.addConstraints(constraints)
}
}
|
b54ff6b7a199166903f200b42564c802
| 53.869919 | 121 | 0.700104 | false | false | false | false |
Zglove/DouYu
|
refs/heads/master
|
DYTV/DYTV/Classes/Home/Controller/FunnyViewController.swift
|
mit
|
1
|
//
// FunnyViewController.swift
// DYTV
//
// Created by people on 2016/11/9.
// Copyright © 2016年 people2000. All rights reserved.
//
import UIKit
//MARK:- 定义常量
private let kTopMargin: CGFloat = 8
class FunnyViewController: BaseAnchorViewController {
//MARK:- 懒加载属性
fileprivate lazy var funnyVM: FunnyViewModel = FunnyViewModel()
}
//MARK:- 设置UI界面
extension FunnyViewController {
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: 0, bottom: 0, right: 0)
}
}
//MARK:- 请求数据
extension FunnyViewController {
override func loadData(){
//1.给父类中的viewmodel进行赋值
baseVM = funnyVM
//2.请求数据
funnyVM.loadFunnyData{
//2.1刷新表格
self.collectionView.reloadData()
//2.2.数据请求完成
self.loadDataFinished()
}
}
}
|
d490c5ad4d73a4e3524d3ffc30ed79ff
| 18.071429 | 97 | 0.626404 | false | false | false | false |
LiuXingCode/LXScollContentViewSwift
|
refs/heads/master
|
LXScrollContentView/LXScrollContentViewLib/LXSegmentBarStyle.swift
|
mit
|
1
|
//
// LXSegmentBarStyle.swift
// LXScrollContentView
//
// Created by 刘行 on 2017/5/23.
// Copyright © 2017年 刘行. All rights reserved.
//
import UIKit
public class LXSegmentBarStyle {
var backgroundColor : UIColor = UIColor.white
var normalTitleColor : UIColor = UIColor.black
var selectedTitleColor : UIColor = UIColor.red
var titleFont : UIFont = UIFont.systemFont(ofSize: 14)
var indicatorColor : UIColor = UIColor.red
var indicatorHeight : CGFloat = 2.0
// var indicatorExtraW : CGFloat = 5.0
var indicatorBottomMargin : CGFloat = 0
var itemMinMargin : CGFloat = 24.0
}
|
ebfbaa13b38dccbd2d649482606febd9
| 19.75 | 58 | 0.653614 | false | false | false | false |
loiwu/SCoreData
|
refs/heads/master
|
Dog Walk/Dog Walk/CoreDataStack.swift
|
mit
|
1
|
//
// CoreDataStack.swift
// Dog Walk
//
// Created by loi on 1/26/15.
// Copyright (c) 2015 GWrabbit. All rights reserved.
//
import CoreData
class CoreDataStack {
let context:NSManagedObjectContext
let psc:NSPersistentStoreCoordinator
let model:NSManagedObjectModel
let store:NSPersistentStore?
init() {
// 1 - load the managed object model from disk into a NSManagedObjectModel object.
// getting a URL to the momd directory that contains the compiled version of the .xcdatamodeld file.
let bundle = NSBundle.mainBundle()
let modelURL = bundle.URLForResource("Dog Walk", withExtension: "momd")
model = NSManagedObjectModel(contentsOfURL: modelURL!)!
// 2 - the persistent store coordinator mediates between the persistent store and NSManagedObjectModel
psc = NSPersistentStoreCoordinator(managedObjectModel: model)
// 3 - The NSManagedObjectContext takes no arguments to initialize.
context = NSManagedObjectContext()
context.persistentStoreCoordinator = psc
// 4 - the persistent store coordinator hands you an NSPersistentStore object as a side effect of attaching a persistent store type.
// simply have to specify the store type (NSSQLiteStoreType in this case), the URL location of the store file and some configuration options.
let documentURL = applicationDocumentsDirectory()
let storeURL = documentURL.URLByAppendingPathComponent("Dog Walk")
let options = [NSMigratePersistentStoresAutomaticallyOption: true]
var error: NSError? = nil
store = psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options, error: &error)
if store == nil {
println("Error adding persistent store: \(error)")
abort()
}
}
func saveContext() {
var error: NSError? = nil
if context.hasChanges && !context.save(&error) {
println("Could not save: \(error), \(error?.userInfo)")
}
}
func applicationDocumentsDirectory() -> NSURL {
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) as [NSURL]
return urls[0]
}
}
|
2c6533438a1a246cd04bbca3e45a6abb
| 38.295082 | 149 | 0.665832 | false | false | false | false |
fengweiru/FWRClassifyChooseView
|
refs/heads/master
|
swift/FWRClassifyChooseViewDemo/FWRClassifyChooseViewDemo/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// FWRClassifyChooseViewDemo
//
// Created by medzone on 15/11/12.
// Copyright © 2015 medzone. All rights reserved.
//
import UIKit
class ViewController: UIViewController,ClassifyChooseViewProtocol {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "例子"
self.view.backgroundColor = UIColor.whiteColor()
self.automaticallyAdjustsScrollViewInsets = false
let categoryArray:Array<String> = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"]
var detailArray = [NSArray]()
detailArray.append(["0","1","2","3","4","5","6","7","8"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1","2","3","4"])
detailArray.append(["0","1"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
detailArray.append(["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"])
let chooseView = ClassifyChooseView.init(frame: CGRectMake(0, 64, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height-64), sectionArray: categoryArray, itemArray: detailArray)
chooseView!.delegate = self
self.view.addSubview(chooseView!)
}
//MARK:-ClassifyChooseView
func didSelectItemAtIndexPath(indexPath: NSIndexPath) {
let message = String.stringByAppendingFormat("第\(indexPath.section)组第\(indexPath.item)个")
let alert = UIAlertController.init(title: "你点击了", message: "\(message)", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
let cancelAction = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(cancelAction)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
8ff9577d3b7427cddde0840295f58e00
| 51.650794 | 269 | 0.540549 | false | false | false | false |
brunopinheiro/sabadinho
|
refs/heads/master
|
Sabadinho/Controllers/MonthViewController.swift
|
mit
|
1
|
//
// MonthViewController.swift
// Sabadinho
//
// Created by Bruno Pinheiro on 14/02/18.
// Copyright © 2018 Bruno Pinheiro. All rights reserved.
//
import Foundation
import UIKit
class MonthViewController: UITableViewController {
private var monthViewModel: MonthViewModel?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.Palette.gray
tableView.separatorStyle = .none
}
func bind(_ monthViewModel: MonthViewModel) {
self.monthViewModel = monthViewModel
tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return monthViewModel?.weeksCount ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return monthViewModel?.daysWithin(week: MonthViewController.weekFrom(section: section)).count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let viewModel = monthViewModel?.day(indexPath.row, ofWeek: MonthViewController.weekFrom(section: indexPath.section)) else {
return UITableViewCell()
}
let cell = MonthTableViewCell()
cell.bind(viewModel)
return cell
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = MonthSectionHeaderView()
header.titleLabel?.text = DayViewModel.titleFor(week: MonthViewController.weekFrom(section: section))
return header
}
}
private extension MonthViewController {
static func weekFrom(section: Int) -> Int {
return section + 1
}
}
|
7a2a44837eff26e5e7fab0009a446d3e
| 28.053571 | 133 | 0.736325 | false | false | false | false |
maicki/plank
|
refs/heads/master
|
Tests/CoreTests/StringExtensionsTests.swift
|
apache-2.0
|
1
|
//
// StringExtensionsTests.swift
// plank
//
// Created by Michael Schneider on 6/16/17.
//
//
import XCTest
@testable import Core
class StringExtensionsTests: XCTestCase {
func testUppercaseFirst() {
XCTAssert("plank".uppercaseFirst == "Plank")
XCTAssert("Plank".uppercaseFirst == "Plank")
XCTAssert("plAnK".uppercaseFirst == "PlAnK")
}
func testLowercaseFirst() {
XCTAssert("Plank".lowercaseFirst == "plank")
XCTAssert("PlAnK".lowercaseFirst == "plAnK")
}
func testSuffixSubstring() {
XCTAssert("plank".suffixSubstring(2) == "nk")
}
func testSnakeCaseToCamelCase() {
XCTAssert("created_at".snakeCaseToCamelCase() == "CreatedAt")
XCTAssert("created_aT".snakeCaseToCamelCase() == "CreatedAT")
XCTAssert("CreatedAt".snakeCaseToCamelCase() == "CreatedAt")
}
func testSnakeCaseToPropertyName() {
XCTAssert("created_at".snakeCaseToPropertyName() == "createdAt")
XCTAssert("CreatedAt".snakeCaseToPropertyName() == "createdAt")
XCTAssert("created_At".snakeCaseToPropertyName() == "createdAt")
XCTAssert("CreatedAt".snakeCaseToPropertyName() == "createdAt")
XCTAssert("CreaTedAt".snakeCaseToPropertyName() == "creaTedAt")
XCTAssert("Created_At".snakeCaseToPropertyName() == "createdAt")
XCTAssert("Test_url".snakeCaseToPropertyName() == "testURL")
XCTAssert("url_test".snakeCaseToPropertyName() == "urlTest")
}
func testSnakeCaseToCapitalizedPropertyName() {
XCTAssert("created_at".snakeCaseToCapitalizedPropertyName() == "CreatedAt")
XCTAssert("CreatedAt".snakeCaseToCapitalizedPropertyName() == "CreatedAt")
}
func testReservedKeywordSubstitution() {
XCTAssert("nil".snakeCaseToCapitalizedPropertyName() == "NilProperty")
}
}
|
a44dccd9c4c9afab91b915d79ebed39c
| 32.071429 | 83 | 0.670086 | false | true | false | false |
gerbot150/SwiftyFire
|
refs/heads/master
|
swift/SwiftyFire/main.swift
|
mit
|
1
|
//
// main.swift
// SwiftyJSONModelMaker
//
// Created by Gregory Bateman on 2017-03-03.
// Copyright © 2017 Gregory Bateman. All rights reserved.
//
import Foundation
func main() {
var name: String?
let tokenizer = Tokenizer()
let parser = Parser()
let swiftifier = Swiftifier()
do {
let input: (name: String?, text: String)
try input = getInput()
name = input.name
let text = input.text
try tokenizer.tokenize(text)
try parser.parse(tokens: tokenizer.tokens)
try swiftifier.swiftifyJSON(parser.topLevelNode, with: name)
} catch {
print("ERROR: \(error), program will exit\n")
return
}
printHeader(with: name)
printImports()
print(swiftifier.swiftifiedJSON)
}
func getInput() throws -> (String?, String) {
var name: String? = nil
var text = ""
let arguments = CommandLine.arguments
if arguments.count < 2 { // Input from standard input
while let line = readLine(strippingNewline: true) {
text += line
}
let ignorableCharacters = CharacterSet.controlCharacters.union(CharacterSet.whitespacesAndNewlines)
text = text.trimmingCharacters(in: ignorableCharacters)
} else { // Input from file
do {
try text = String(contentsOfFile: arguments[1], encoding: .utf8)
// These commands are apparently not usable in the current version of
// Swift on linux - or I couldn't find the library to link them properly
// but the characters are handled accordingly in the tokenizer
// text = text.components(separatedBy: "\r").joined(separator: "")
// text = text.components(separatedBy: "\n").joined(separator: "")
// text = text.components(separatedBy: "\t").joined(separator: " ")
name = arguments[1]
while let range = name?.range(of: "/") {
name = name?.substring(from: range.upperBound)
}
if let range = name?.range(of: ".") {
name = name?.substring(to: range.lowerBound)
}
name = name?.capitalCased
} catch {
throw error
}
}
return (name, text)
}
func printHeader(with name: String?) {
print("//")
print("// \(name ?? "Object").swift")
print("//")
print("// Created by SwiftyFire on \(getDate())")
print("// SwiftyFire is a development tool made by Greg Bateman")
print("// It was created to reduce the tedious amount of time required to create")
print("// model classes when using SwiftyJSON to parse JSON in swift")
print("//")
print()
}
func printImports() {
print("import SwiftyJSON")
print()
}
func getDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: Date())
}
main()
|
13f65019bed869b6d9bbf8176df4e206
| 30.365591 | 107 | 0.605074 | false | false | false | false |
domenicosolazzo/practice-swift
|
refs/heads/master
|
CoreData/Writing to CoreData/Writing to CoreData/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Writing to CoreData
//
// Created by Domenico Solazzo on 17/05/15.
// License MIT
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let entityName = NSStringFromClass(Person.classForCoder())
let person = NSEntityDescription.insertNewObject(
forEntityName: entityName,
into: managedObjectContext!) as! Person
// Current year
let now = Date()
let calendar = Calendar.current
let calendarComponents = (calendar as NSCalendar).components(NSCalendar.Unit.year, from: now)
let year = calendarComponents.year
print("Year \(year)")
person.firstName = "Domenico"
person.lastName = "Solazzo"
person.age = NSNumber(value: (UInt(year!) - UInt(1982)))
print("Current age: \((year! - 1982))")
var savingError: NSError?
do {
try managedObjectContext!.save()
print("Successfully saved the person")
} catch var error1 as NSError {
savingError = error1
if savingError != nil{
print("Error saving the person. Error: \(savingError)")
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.Writing_to_CoreData" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "Writing_to_CoreData", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("Writing_to_CoreData.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
|
f743784880dbef25d1f7034c6cd07abe
| 49.04698 | 290 | 0.678423 | false | false | false | false |
OctMon/OMExtension
|
refs/heads/master
|
OMExtension/OMExtension/Source/UIKit/OMFont.swift
|
mit
|
1
|
//
// OMFont.swift
// OMExtension
//
// The MIT License (MIT)
//
// Copyright (c) 2016 OctMon
//
// 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
#if !os(macOS)
import UIKit
public extension UIFont {
struct OM {
public enum Family: String {
case academyEngravedLET = "Academy Engraved LET"
case alNile = "Al Nile"
case americanTypewriter = "American Typewriter"
case appleColorEmoji = "Apple Color Emoji"
case appleSDGothicNeo = "Apple SD Gothic Neo"
case arial = "Arial"
case arialHebrew = "Arial Hebrew"
case arialRoundedMTBold = "Arial Rounded MT Bold"
case avenir = "Avenir"
case avenirNext = "Avenir Next"
case avenirNextCondensed = "Avenir Next Condensed"
case banglaSangamMN = "Bangla Sangam MN" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case baskerville = "Baskerville"
case bodoni72 = "Bodoni 72"
case bodoni72Oldstyle = "Bodoni 72 Oldstyle"
case bodoni72Smallcaps = "Bodoni 72 Smallcaps"
case bodoniOrnaments = "Bodoni Ornaments"
case bradleyHand = "Bradley Hand"
case chalkboardSE = "Chalkboard SE"
case chalkduster = "Chalkduster"
case cochin = "Cochin"
case copperplate = "Copperplate"
case courier = "Courier"
case courierNew = "Courier New"
case damascus = "Damascus"
case devanagariSangamMN = "Devanagari Sangam MN"
case didot = "Didot"
case dINAlternate = "DIN Alternate" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case dINCondensed = "DIN Condensed" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case euphemiaUCAS = "Euphemia UCAS"
case farah = "Farah"
case futura = "Futura"
case geezaPro = "Geeza Pro"
case georgia = "Georgia"
case gillSans = "Gill Sans"
case gujaratiSangamMN = "Gujarati Sangam MN"
case gurmukhiMN = "Gurmukhi MN"
case heitiSC = "Heiti SC"
case heitiTC = "Heiti TC"
case helvetica = "Helvetica"
case helveticaNeue = "Helvetica Neue"
case hiraginoKakuGothicProN = "Hiragino Kaku Gothic ProN"
case hiraginoMinchoProN = "Hiragino Mincho ProN"
case hoeflerText = "Hoefler Text"
case iowanOldStyle = "Iowan Old Style" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case kailasa = "Kailasa"
case kannadaSangamMN = "Kannada Sangam MN"
case khmerSangamMN = "Khmer Sangam MN" /*@available(*, introduced=8.0)*/
case kohinoorBangla = "Kohinoor Bangla" /*@available(*, introduced=8.0)*/
case kohinoorDevanagari = "Kohinoor Devanagari" /*@available(*, introduced=8.0)*/
case laoSangamMN = "Lao Sangam MN" /*@available(*, introduced=8.0)*/
case malayalamSangamMN = "Malayalam Sangam MN"
case marion = "Marion" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case markerFelt = "Marker Felt"
case menlo = "Menlo"
case mishafi = "Mishafi"
case noteworthy = "Noteworthy"
case optima = "Optima"
case oriyaSangamMN = "Oriya Sangam MN"
case palatino = "Palatino"
case papyrus = "Papyrus"
case partyLET = "Party LET"
case savoyeLET = "Savoye LET"
case sinhalaSangamMN = "Sinhala Sangam MN"
case snellRoundhand = "Snell Roundhand"
case superclarendon = "Superclarendon" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case symbol = "Symbol"
case tamilSangamMN = "Tamil Sangam MN"
case teluguSangamMN = "Telugu Sangam MN"
case thonburi = "Thonburi"
case timesNewRoman = "Times New Roman"
case trebuchetMS = "Trebuchet MS"
case verdana = "Verdana"
case zapfDingbats = "Zapf Dingbats"
case zapfino = "Zapfino"
}
public enum Font : String {
case academyEngravedLetPlain = "AcademyEngravedLetPlain"
case alNile = "AlNile"
case alNileBold = "AlNile-Bold"
case americanTypewriter = "AmericanTypewriter"
case americanTypewriterBold = "AmericanTypewriter-Bold"
case americanTypewriterCondensed = "AmericanTypewriter-Condensed"
case americanTypewriterCondensedBold = "AmericanTypewriter-CondensedBold"
case americanTypewriterCondensedLight = "AmericanTypewriter-CondensedLight"
case americanTypewriterLight = "AmericanTypewriter-Light"
case appleColorEmoji = "AppleColorEmoji"
case appleSDGothicNeoBold = "AppleSDGothicNeo-Bold"
case appleSDGothicNeoLight = "AppleSDGothicNeo-Light"
case appleSDGothicNeoMedium = "AppleSDGothicNeo-Medium"
case appleSDGothicNeoRegular = "AppleSDGothicNeo-Regular"
case appleSDGothicNeoSemiBold = "AppleSDGothicNeo-SemiBold"
case appleSDGothicNeoThin = "AppleSDGothicNeo-Thin"
case appleSDGothicNeoUltraLight = "AppleSDGothicNeo-UltraLight" /*@available(*, introduced=9.0)*/
case arialBoldItalicMT = "Arial-BoldItalicMT"
case arialBoldMT = "Arial-BoldMT"
case arialHebrew = "ArialHebrew"
case arialHebrewBold = "ArialHebrew-Bold"
case arialHebrewLight = "ArialHebrew-Light"
case arialItalicMT = "Arial-ItalicMT"
case arialMT = "ArialMT"
case arialRoundedMTBold = "ArialRoundedMTBold"
case aSTHeitiLight = "ASTHeiti-Light"
case aSTHeitiMedium = "ASTHeiti-Medium"
case avenirBlack = "Avenir-Black"
case avenirBlackOblique = "Avenir-BlackOblique"
case avenirBook = "Avenir-Book"
case avenirBookOblique = "Avenir-BookOblique"
case avenirHeavyOblique = "Avenir-HeavyOblique"
case avenirHeavy = "Avenir-Heavy"
case avenirLight = "Avenir-Light"
case avenirLightOblique = "Avenir-LightOblique"
case avenirMedium = "Avenir-Medium"
case avenirMediumOblique = "Avenir-MediumOblique"
case avenirNextBold = "AvenirNext-Bold"
case avenirNextBoldItalic = "AvenirNext-BoldItalic"
case avenirNextCondensedBold = "AvenirNextCondensed-Bold"
case avenirNextCondensedBoldItalic = "AvenirNextCondensed-BoldItalic"
case avenirNextCondensedDemiBold = "AvenirNextCondensed-DemiBold"
case avenirNextCondensedDemiBoldItalic = "AvenirNextCondensed-DemiBoldItalic"
case avenirNextCondensedHeavy = "AvenirNextCondensed-Heavy"
case avenirNextCondensedHeavyItalic = "AvenirNextCondensed-HeavyItalic"
case avenirNextCondensedItalic = "AvenirNextCondensed-Italic"
case avenirNextCondensedMedium = "AvenirNextCondensed-Medium"
case avenirNextCondensedMediumItalic = "AvenirNextCondensed-MediumItalic"
case avenirNextCondensedRegular = "AvenirNextCondensed-Regular"
case avenirNextCondensedUltraLight = "AvenirNextCondensed-UltraLight"
case avenirNextCondensedUltraLightItalic = "AvenirNextCondensed-UltraLightItalic"
case avenirNextDemiBold = "AvenirNext-DemiBold"
case avenirNextDemiBoldItalic = "AvenirNext-DemiBoldItalic"
case avenirNextHeavy = "AvenirNext-Heavy"
case avenirNextItalic = "AvenirNext-Italic"
case avenirNextMedium = "AvenirNext-Medium"
case avenirNextMediumItalic = "AvenirNext-MediumItalic"
case avenirNextRegular = "AvenirNext-Regular"
case avenirNextUltraLight = "AvenirNext-UltraLight"
case avenirNextUltraLightItalic = "AvenirNext-UltraLightItalic"
case avenirOblique = "Avenir-Oblique"
case avenirRoman = "Avenir-Roman"
case banglaSangamMN = "BanglaSangamMN" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case banglaSangamMNBold = "BanglaSangamMN-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case baskerville = "Baskerville"
case baskervilleBold = "Baskerville-Bold"
case baskervilleBoldItalic = "Baskerville-BoldItalic"
case baskervilleItalic = "Baskerville-Italic"
case baskervilleSemiBold = "Baskerville-SemiBold"
case baskervilleSemiBoldItalic = "Baskerville-SemiBoldItalic"
case bodoniOrnamentsITCTT = "BodoniOrnamentsITCTT"
case bodoniSvtyTwoITCTTBold = "BodoniSvtyTwoITCTT-Bold"
case bodoniSvtyTwoITCTTBook = "BodoniSvtyTwoITCTT-Book"
case bodoniSvtyTwoITCTTBookIta = "BodoniSvtyTwoITCTT-BookIta"
case bodoniSvtyTwoOSITCTTBold = "BodoniSvtyTwoOSITCTT-Bold"
case bodoniSvtyTwoOSITCTTBook = "BodoniSvtyTwoOSITCTT-Book"
case bodoniSvtyTwoOSITCTTBookIt = "BodoniSvtyTwoOSITCTT-BookIt"
case bodoniSvtyTwoSCITCTTBook = "BodoniSvtyTwoSCITCTT-Book"
case bradleyHandITCTTBold = "BradleyHandITCTT-Bold"
case chalkboardSEBold = "ChalkboardSE-Bold"
case chalkboardSELight = "ChalkboardSE-Light"
case chalkboardSERegular = "ChalkboardSE-Regular"
case chalkduster = "Chalkduster"
case cochin = "Cochin"
case cochinBold = "Cochin-Bold"
case cochinBoldItalic = "Cochin-BoldItalic"
case cochinItalic = "Cochin-Italic"
case copperplate = "Copperplate"
case copperplateBold = "Copperplate-Bold"
case copperplateLight = "Copperplate-Light"
case courier = "Courier"
case courierBold = "Courier-Bold"
case courierBoldOblique = "Courier-BoldOblique"
case courierNewPSBoldItalicMT = "CourierNewPS-BoldItalicMT"
case courierNewPSBoldMT = "CourierNewPS-BoldMT"
case courierNewPSItalicMT = "CourierNewPS-ItalicMT"
case courierNewPSMT = "CourierNewPSMT"
case courierOblique = "Courier-Oblique"
case damascus = "Damascus"
case damascusBold = "DamascusBold"
case damascusMedium = "DamascusMedium"
case damascusSemiBold = "DamascusSemiBold"
case devanagariSangamMN = "DevanagariSangamMN"
case devanagariSangamMNBold = "DevanagariSangamMN-Bold"
case didot = "Didot"
case didotBold = "Didot-Bold"
case didotItalic = "Didot-Italic"
case dINAlternateBold = "DINAlternate-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case dINCondensedBold = "DINCondensed-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case diwanMishafi = "DiwanMishafi"
case euphemiaUCAS = "EuphemiaUCAS"
case euphemiaUCASBold = "EuphemiaUCAS-Bold"
case euphemiaUCASItalic = "EuphemiaUCAS-Italic"
case farah = "Farah"
case futuraCondensedExtraBold = "Futura-ExtraBold"
case futuraCondensedMedium = "Futura-CondensedMedium"
case futuraMedium = "Futura-Medium"
case futuraMediumItalicm = "Futura-MediumItalic"
case geezaPro = "GeezaPro"
case geezaProBold = "GeezaPro-Bold"
case geezaProLight = "GeezaPro-Light"
case georgia = "Georgia"
case georgiaBold = "Georgia-Bold"
case georgiaBoldItalic = "Georgia-BoldItalic"
case georgiaItalic = "Georgia-Italic"
case gillSans = "GillSans"
case gillSansBold = "GillSans-Bold"
case gillSansBoldItalic = "GillSans-BoldItalic"
case gillSansItalic = "GillSans-Italic"
case gillSansLight = "GillSans-Light"
case gillSansLightItalic = "GillSans-LightItalic"
case gujaratiSangamMN = "GujaratiSangamMN"
case gujaratiSangamMNBold = "GujaratiSangamMN-Bold"
case gurmukhiMN = "GurmukhiMN"
case gurmukhiMNBold = "GurmukhiMN-Bold"
case helvetica = "Helvetica"
case helveticaBold = "Helvetica-Bold"
case helveticaBoldOblique = "Helvetica-BoldOblique"
case helveticaLight = "Helvetica-Light"
case helveticaLightOblique = "Helvetica-LightOblique"
case helveticaNeue = "HelveticaNeue"
case helveticaNeueBold = "HelveticaNeue-Bold"
case helveticaNeueBoldItalic = "HelveticaNeue-BoldItalic"
case helveticaNeueCondensedBlack = "HelveticaNeue-CondensedBlack"
case helveticaNeueCondensedBold = "HelveticaNeue-CondensedBold"
case helveticaNeueItalic = "HelveticaNeue-Italic"
case helveticaNeueLight = "HelveticaNeue-Light"
case helveticaNeueMedium = "HelveticaNeue-Medium"
case helveticaNeueMediumItalic = "HelveticaNeue-MediumItalic"
case helveticaNeueThin = "HelveticaNeue-Thin"
case helveticaNeueThinItalic = "HelveticaNeue-ThinItalic"
case helveticaNeueUltraLight = "HelveticaNeue-UltraLight"
case helveticaNeueUltraLightItalic = "HelveticaNeue-UltraLightItalic"
case helveticaOblique = "Helvetica-Oblique"
case hiraKakuProNW3 = "HiraKakuProN-W3"
case hiraKakuProNW6 = "HiraKakuProN-W6"
case hiraMinProNW3 = "HiraMinProN-W3"
case hiraMinProNW6 = "HiraMinProN-W6"
case hoeflerTextBlack = "HoeflerText-Black"
case hoeflerTextBlackItalic = "HoeflerText-BlackItalic"
case hoeflerTextItalic = "HoeflerText-Italic"
case hoeflerTextRegular = "HoeflerText-Regular"
case iowanOldStyleBold = "IowanOldStyle-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case iowanOldStyleBoldItalic = "IowanOldStyle-BoldItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case iowanOldStyleItalic = "IowanOldStyle-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case iowanOldStyleRoman = "IowanOldStyle-Roman" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case kailasa = "Kailasa"
case kailasaBold = "Kailasa-Bold"
case kannadaSangamMN = "KannadaSangamMN"
case kannadaSangamMNBold = "KannadaSangamMN-Bold"
case khmerSangamMN = "KhmerSangamMN" /*@available(*, introduced=8.0)*/
case kohinoorBanglaLight = "KohinoorBangla-Light" /*@available(*, introduced=9.0)*/
case kohinoorBanglaMedium = "KohinoorBangla-Medium" /*@available(*, introduced=9.0)*/
case kohinoorBanglaRegular = "KohinoorBangla-Regular" /*@available(*, introduced=9.0)*/
case kohinoorDevanagariLight = "KohinoorDevanagari-Light" /*@available(*, introduced=8.0)*/
case kohinoorDevanagariMedium = "KohinoorDevanagari-Medium" /*@available(*, introduced=8.0)*/
case kohinoorDevanagariBook = "KohinoorDevanagari-Book" /*@available(*, introduced=8.0)*/
case laoSangamMN = "LaoSangamMN" /*@available(*, introduced=8.0)*/
case malayalamSangamMN = "MalayalamSangamMN"
case malayalamSangamMNBold = "MalayalamSangamMN-Bold"
case marionBold = "Marion-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case marionItalic = "Marion-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case marionRegular = "Marion-Regular" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case markerFeltThin = "MarkerFelt-Thin"
case markerFeltWide = "MarkerFelt-Wide"
case menloBold = "Menlo-Bold"
case menloBoldItalic = "Menlo-BoldItalic"
case menloItalic = "Menlo-Italic"
case menloRegular = "Menlo-Regular"
case noteworthyBold = "Noteworthy-Bold"
case noteworthyLight = "Noteworthy-Light"
case optimaBold = "Optima-Bold"
case optimaBoldItalic = "Optima-BoldItalic"
case optimaExtraBlack = "Optima-ExtraBold"
case optimaItalic = "Optima-Italic"
case optimaRegular = "Optima-Regular"
case oriyaSangamMN = "OriyaSangamMN"
case oriyaSangamMNBold = "OriyaSangamMN-Bold"
case palatinoBold = "Palatino-Bold"
case palatinoBoldItalic = "Palatino-BoldItalic"
case palatinoItalic = "Palatino-Italic"
case palatinoRoman = "Palatino-Roman"
case papyrus = "Papyrus"
case papyrusCondensed = "Papyrus-Condensed"
case partyLetPlain = "PartyLetPlain"
case savoyeLetPlain = "SavoyeLetPlain"
case sinhalaSangamMN = "SinhalaSangamMN"
case sinhalaSangamMNBold = "SinhalaSangamMN-Bold"
case snellRoundhand = "SnellRoundhand"
case snellRoundhandBlack = "SnellRoundhand-Black"
case snellRoundhandBold = "SnellRoundhand-Bold"
case sTHeitiSCLight = "STHeitiSC-Light"
case sTHeitiSCMedium = "STHeitiSC-Medium"
case sTHeitiTCLight = "STHeitiTC-Light"
case sTHeitiTCMedium = "STHeitiTC-Medium"
case superclarendonBlack = "Superclarendon-Black" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonBlackItalic = "Superclarendon-BalckItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonBold = "Superclarendon-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonBoldItalic = "Superclarendon-BoldItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonItalic = "Superclarendon-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonLight = "Superclarendon-Light" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonLightItalic = "Superclarendon-LightItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case superclarendonRegular = "Superclarendon-Regular" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case symbol = "Symbol"
case tamilSangamMN = "TamilSangamMN"
case tamilSangamMNBold = "TamilSangamMN-Bold"
case teluguSangamMN = "TeluguSangamMN"
case teluguSangamMNBold = "TeluguSangamMN-Bold"
case thonburi = "Thonburi"
case thonburiBold = "Thonburi-Bold"
case thonburiLight = "Thonburi-Light"
case timesNewRomanPSBoldItalicMT = "TimesNewRomanPS-BoldItalic"
case timesNewRomanPSBoldMT = "TimesNewRomanPS-Bold"
case timesNewRomanPSItalicMT = "TimesNewRomanPS-ItalicMT"
case timesNewRomanPSMT = "TimesNewRomanPSMT"
case trebuchetBoldItalic = "Trebuchet-BoldItalic"
case trebuchetMS = "TrebuchetMS"
case trebuchetMSBold = "TrebuchetMS-Bold"
case trebuchetMSItalic = "TrebuchetMS-Italic"
case verdana = "Verdana"
case verdanaBold = "Verdana-Bold"
case verdanaBoldItalic = "Verdana-BoldItalic"
case verdanaItalic = "Verdana-Italic"
}
}
convenience init?(omFontName: OM.Font, size: CGFloat) {
self.init(name: omFontName.rawValue, size: size)
}
}
#endif
|
b0ee49b18ce7f7fccb43b6e4450c0485
| 58.817439 | 173 | 0.651073 | false | false | false | false |
cliffpanos/True-Pass-iOS
|
refs/heads/master
|
iOSApp/CheckIn/Managers/PassManager.swift
|
apache-2.0
|
1
|
//
// PassManager.swift
// True Pass
//
// Created by Cliff Panos on 8/6/17.
// Copyright © 2017 Clifford Panos. All rights reserved.
//
import UIKit
import CoreData
class PassManager {
//MARK: - Handle Guest Pass Functionality with Core Data
static func save(pass: TPPass?, firstName: String, lastName: String, andEmail email: String, andImage imageData: Data?, from startTime: Date, to endTime: Date, forLocation locationID: String) -> TPPass {
let managedContext = C.appDelegate.persistentContainer.viewContext
let pass = pass ?? TPPass(.TPPass)
pass.firstName = firstName
pass.lastName = lastName
pass.email = email
pass.startDate = startTime
pass.endDate = endTime
pass.accessCodeQR = "\(Date().addingTimeInterval(TimeInterval(arc4random())).timeIntervalSince1970)"
pass.isActive = true
pass.didCheckIn = false
pass.locationIdentifier = locationID
pass.phoneNumber = ""
if let data = imageData, let image = UIImage(data: data) {
print("OLD IMAGE SIZE: \(data.count)")
let resizedImage = image.drawAspectFill(in: CGRect(x: 0, y: 0, width: 240, height: 240))
let reducedData = UIImagePNGRepresentation(resizedImage)
print("NEW IMAGE SIZE: \(reducedData!.count)")
pass.imageData = data
}
let passService = FirebaseService(entity: .TPPass)
let identifier = passService.newIdentifierKey
passService.enterData(forIdentifier: identifier, data: pass)
passService.addChildData(forIdentifier: identifier, key: "startDate", value: pass.startDate!.timeIntervalSince1970)
passService.addChildData(forIdentifier: identifier, key: "endDate", value: pass.endDate!.timeIntervalSince1970)
let passListService = FirebaseService(entity: .TPPassList)
passListService.addChildData(forIdentifier: Accounts.userIdentifier, key: identifier, value: locationID)
passListService.addChildData(forIdentifier: locationID, key: identifier, value: Accounts.userIdentifier)
//passListService.reference.child(Accounts.userIdentifier).setValue(locationID)
//passListService.reference.child(locationID).setValue(Accounts.userIdentifier)
guard let data = pass.imageData as Data? else { return pass }
FirebaseStorage.shared.uploadImage(data: data, for: .TPPass, withIdentifier: identifier) { metadata, error in
if let error = error { print("Error uploading pass image!!") }
}
defer {
let passData = PassManager.preparedData(forPass: pass)
let newPassInfo = [WCD.KEY: WCD.singleNewPass, WCD.passPayload: passData] as [String : Any]
C.session?.transferUserInfo(newPassInfo)
}
return pass
}
static func delete(pass: TPPass, andInformWatchKitApp sendMessage: Bool = true) -> Bool {
//DELETE PASS FROM FIREBASE
let passListService = FirebaseService(entity: .TPPassList)
//Remove from TPPassList/locationIdentifier/passIdentifier
passListService.reference.child(pass.locationIdentifier!).child(pass.identifier!).removeValue()
//Remove from TPPassList/userIdentifier/passIdentifier
passListService.reference.child(Accounts.userIdentifier).child(pass.identifier!).removeValue()
let passService = FirebaseService(entity: .TPPass)
passService.reference.child(pass.identifier!).removeValue()
FirebaseStorage.shared.deleteImage(forEntity: .TPPass, withIdentifier: pass.identifier!)
let data = PassManager.preparedData(forPass: pass, includingImage: false) //Do NOT include image
defer {
if sendMessage {
let deletePassInfo = [WCD.KEY: WCD.deletePass, WCD.passPayload: data] as [String : Any]
C.session?.transferUserInfo(deletePassInfo)
}
}
if let vc = UIWindow.presented.viewController as? PassDetailViewController {
vc.navigationController?.popViewController(animated: true)
}
return true
}
static func preparedData(forPass pass: TPPass, includingImage: Bool = true) -> Data {
var dictionary = pass.dictionaryWithValues(forKeys: ["name", "email", "startDate", "endDate", "didCheckIn"])
if includingImage, let imageData = pass.imageData as Data?, let image = UIImage(data: imageData) {
let res = 60.0
let resizedImage = image.drawAspectFill(in: CGRect(x: 0, y: 0, width: res, height: res))
let reducedData = UIImagePNGRepresentation(resizedImage)
print("Contact Image Message Size: \(reducedData?.count ?? 0)")
dictionary["image"] = reducedData
} else {
dictionary["image"] = nil
}
return NSKeyedArchiver.archivedData(withRootObject: dictionary) //Binary data
}
}
|
f860dd07085bf6fcc4db6c846ff10953
| 41.154472 | 207 | 0.641273 | false | false | false | false |
robconrad/fledger-common
|
refs/heads/master
|
FledgerCommon/LoginViewHelper.swift
|
mit
|
1
|
//
// LoginViewControllerUtils.swift
// FledgerCommon
//
// Created by Robert Conrad on 8/16/15.
// Copyright (c) 2015 Robert Conrad. All rights reserved.
//
import Foundation
public protocol LoginViewHelperDataSource {
func getEmail() -> String
func getPassword() -> String
}
public protocol LoginViewHelperDelegate {
func notifyEmailValidity(valid: Bool)
func notifyPasswordValidity(valid: Bool)
func notifyLoginResult(valid: Bool)
}
public class LoginViewHelper {
private let dataSource: LoginViewHelperDataSource
private let delegate: LoginViewHelperDelegate
public required init(_ dataSource: LoginViewHelperDataSource, _ delegate: LoginViewHelperDelegate) {
self.dataSource = dataSource
self.delegate = delegate
}
public func loginFromCache() {
if ParseSvc().isLoggedIn() {
handleSuccess()
}
}
public func login() {
if !validateFields() {
return
}
ParseSvc().login(dataSource.getEmail(), dataSource.getPassword(), { success in
if success {
self.handleSuccess()
}
else {
self.delegate.notifyLoginResult(false)
}
})
}
public func signup() {
if !validateFields() {
return
}
ParseSvc().signup(dataSource.getEmail(), dataSource.getPassword(), { success in
if success {
self.handleSuccess()
}
else {
self.delegate.notifyEmailValidity(false)
}
})
}
public func validateFields() -> Bool {
var valid = true
delegate.notifyEmailValidity(true)
if dataSource.getEmail().characters.count < 5 {
delegate.notifyEmailValidity(false)
valid = false
}
delegate.notifyPasswordValidity(true)
if dataSource.getPassword().characters.count < 3 {
delegate.notifyPasswordValidity(false)
valid = false
}
return valid
}
private func handleSuccess() {
// services can't be registered until a User is logged in
ServiceBootstrap.register()
delegate.notifyLoginResult(true)
}
}
|
28b4de44de674945f1d83fc7b4a13c74
| 23.43299 | 104 | 0.576192 | false | false | false | false |
Codility-BMSTU/Codility
|
refs/heads/master
|
Codility/Codility/OBMyCardBalanceResponse.swift
|
apache-2.0
|
1
|
//
// OBMyCardBalanceResponse.swift
// Codility
//
// Created by Кирилл Володин on 16.09.17.
// Copyright © 2017 Кирилл Володин. All rights reserved.
//
import Foundation
import SwiftyJSON
class OBMyCardBalanceResponse {
var card: OBMyCard!
var json: JSON!
var errorCode: String = ""
var errorDescription: String = ""
init(json: JSON) {
self.json = json
self.errorCode = json["ErrorCode"].string ?? ""
self.errorDescription = json["ErrorDescription"].string ?? ""
let card = OBMyCard()
card.id = json["CardId"].int! // временная строчка
for item in json["CardBalance"].arrayValue {
let newBalance = OBCardBalance()
newBalance.value = item["Value"].int ?? 0
newBalance.cur = item["Cur"].string ?? ""
card.balances.append(newBalance)
}
self.card = card
}
}
|
78ae573501d08f2b6f55c1bd23c440a7
| 23.435897 | 69 | 0.570829 | false | false | false | false |
GenerallyHelpfulSoftware/Scalar2D
|
refs/heads/master
|
Styling/Sources/GraphicStyle.swift
|
mit
|
1
|
//
// GraphicStyle.swift
// Scalar2D
//
// Created by Glenn Howes on 8/27/16.
// Copyright © 2016-2019 Generally Helpful Software. All rights reserved.
//
//
//
// The MIT License (MIT)
// Copyright (c) 2016-2019 Generally Helpful Software
// 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 Scalar2D_Colour
import Scalar2D_FontDescription
#if os(iOS) || os(tvOS) || os(OSX) || os(watchOS)
import CoreGraphics
public typealias NativeDimension = CGFloat
#else
public typealias NativeDimension = Double
#endif
extension String
{
public var asStyleUnit : StyleUnit?
{
switch self.lowercased()
{
case "px":
return .pixel
case "%":
return .percent
case "em":
return .em
case "pt":
return .point
case "cm":
return .centimeter
default:
return nil
}
}
}
public struct UnitDimension : Equatable
{
public let dimension: NativeDimension
public let unit : StyleUnit
public init(dimension: NativeDimension, unit: StyleUnit)
{
self.dimension = dimension
self.unit = unit
}
}
public enum StyleProperty
{
case string(String)
case unitNumber(UnitDimension)
case number(Double)
case colour(Colour, NativeColour?)
case boolean(Bool)
// half of any graphics library is dealing with drawing text
case fontStyle(FontStyle)
case fontVariant(FontVariant)
case fontFamilies([FontFamily])
case fontWeight(FontWeight)
case fontStretch(FontStretch)
case fontDecorations(Set<TextDecoration>)
case distance(Distance)
case fontSize(FontSize)
// stroke properties
case lineCap(LineCap)
case lineJoin(LineJoin)
// view properties
case border([BorderRecord])
case cornerRadius(CornerRadius)
indirect case array([StyleProperty])
indirect case dimensionArray([UnitDimension])
// remember to update Equatable extension below if you add another case
}
public struct PropertyKey : RawRepresentable
{
public let rawValue : String
public init?(rawValue: String)
{
self.rawValue = rawValue
}
}
extension PropertyKey : Hashable
{
}
public struct GraphicStyle
{
public let key: PropertyKey
public let value: StyleProperty
public let important: Bool
public init(key: PropertyKey, value: StyleProperty, important: Bool = false)
{
self.key = key
self.value = value
self.important = important
}
public init(key: PropertyKey, value: String, important: Bool = false)
{
self.init(key: key, value: StyleProperty.string(value), important: important)
}
/**
convenient alternate init for creating a graphic style from a constant # style colour description
**/
public init(key: PropertyKey, hexColour: String, important: Bool = false)
{
let colour = try! HexColourParser().deserializeString(source: hexColour)!
self.init(key: key, value: StyleProperty.colour(colour, colour.nativeColour), important: important)
}
/**
convenient alternate init for creating a graphic style from a constant named web colour description
**/
public init(key: PropertyKey, webColour: String, important: Bool = false)
{
let colour = try! WebColourParser().deserializeString(source: webColour)!
self.init(key: key, value: StyleProperty.colour(colour, colour.nativeColour), important: important)
}
}
/**
Such a context will be able to resolve an inherited property (for example by looking up the style chain)
**/
public protocol StyleContext
{
func resolve(property : GraphicStyle) -> StyleProperty?
func points(fromUnit unit: StyleUnit) -> NativeDimension?
var hairlineWidth : NativeDimension {get}
}
public extension StyleContext
{
// default implementation
func resolve(property : GraphicStyle) -> StyleProperty?
{
return property.value
}
// default implementation
func points(value: NativeDimension, fromUnit unit: StyleUnit) -> NativeDimension?
{
switch unit
{
case .point:
return value
default:
return nil
}
}
}
extension StyleProperty : Equatable
{
public static func == (lhs: StyleProperty, rhs: StyleProperty) -> Bool {
switch(lhs, rhs)
{
case (.string(let lhsString), .string(let rhsString)):
return lhsString == rhsString
case (.unitNumber(let lhsDimension), .unitNumber(let rhsDimension)):
return lhsDimension == rhsDimension
case (.number(let lhsNumber), .number(let rhsNumber)):
return lhsNumber == rhsNumber
case (.colour(let lhsColour, let lhsNative), .colour(let rhsColour, let rhsNative)):
return lhsColour == rhsColour && lhsNative == rhsNative
case (.boolean(let lhsBool), .boolean(let rhsBool)):
return lhsBool == rhsBool
case (.array(let lhsArray), .array(let rhsArray)):
return lhsArray == rhsArray
case (.fontStyle(let lhsStyle), .fontStyle(let rhsStyle)):
return lhsStyle == rhsStyle
case (.fontVariant(let lhsVariant), .fontVariant(let rhsVariant)):
return lhsVariant == rhsVariant
case (.fontFamilies(let lhsFamilies), .fontFamilies(let rhsFamilies)):
return lhsFamilies == rhsFamilies
case (.fontWeight(let lhsWeight), .fontWeight(let rhsWeight)):
return lhsWeight == rhsWeight
case (.fontDecorations(let lhsDecorations), .fontDecorations(let rhsDecorations)):
return lhsDecorations == rhsDecorations
case (.distance(let lhsHeight), .distance(let rhsHeight)):
return lhsHeight == rhsHeight
case (.fontSize(let lhsSize), .fontSize(let rhsSize)):
return lhsSize == rhsSize
case (.fontStretch(let lhsStretch), .fontStretch(let rhsStretch)):
return lhsStretch == rhsStretch
case (.lineCap(let lhsCap), .lineCap(let rhsCap)):
return lhsCap == rhsCap
case (.lineJoin(let lhsJoin), .lineJoin(let rhsJoin)):
return lhsJoin == rhsJoin
case (.dimensionArray(let lhsArray), .dimensionArray(let rhsArray)):
return lhsArray == rhsArray
case (.border(let lhsTypes), .border(let rhsTypes)):
return lhsTypes == rhsTypes
case (.cornerRadius(let lhsCorner), .cornerRadius(let rhsCorner)):
return lhsCorner == rhsCorner
default:
return false
}
}
}
extension GraphicStyle : Equatable
{
public static func == (lhs: GraphicStyle, rhs: GraphicStyle) -> Bool {
return lhs.important == rhs.important && lhs.key == rhs.key && lhs.value == rhs.value
}
}
public extension FontDescription
{
init(properties : [StyleProperty])
{
var fontSize : FontSize? = nil
var families : [FontFamily]? = nil
var weight : FontWeight? = nil
var stretch : FontStretch? = nil
var decorations : Set<TextDecoration>? = nil
var style : FontStyle? = nil
var variant : FontVariant? = nil
var lineHeight : Distance? = nil
for aProperty in properties
{
switch aProperty
{
case .fontDecorations(let newDecorations):
if let oldDecorations = decorations
{
decorations = oldDecorations.union(newDecorations)
}
else
{
decorations = newDecorations
}
case .fontFamilies(let newFamilies):
families = newFamilies
case .fontSize(let newSize):
fontSize = newSize
case .fontStretch(let newStretch):
stretch = newStretch
case .fontStyle(let newStyle):
style = newStyle
case .distance(let newLineHeight):
lineHeight = newLineHeight
case .fontVariant(let newVariant):
variant = newVariant
case .fontWeight(let newWeight):
weight = newWeight
default:
break
}
}
self.init(families: families ?? [.inherit],
size: fontSize ?? .inherit,
weight: weight ?? .inherit,
stretch: stretch ?? .inherit,
decorations: decorations ?? [.inherit],
style: style ?? .inherit,
variant: variant ?? .inherit,
lineHeight: lineHeight ?? .inherit)
}
}
|
c4d67f3754ae84fc13619980f8612d6f
| 31.816129 | 108 | 0.607097 | false | false | false | false |
rnystrom/GitHawk
|
refs/heads/master
|
Classes/Milestones/MilestoneViewModel.swift
|
mit
|
1
|
//
// MilestoneViewModel.swift
// Freetime
//
// Created by Ryan Nystrom on 6/3/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
struct MilestoneViewModel: ListSwiftDiffable {
let title: String
let due: String
let selected: Bool
// MARK: ListSwiftDiffable
var identifier: String {
return title
}
func isEqual(to value: ListSwiftDiffable) -> Bool {
guard let value = value as? MilestoneViewModel else { return false }
return due == value.due
&& selected == value.selected
}
}
|
7ed71fcb70495caf22f83bec040aa841
| 19.586207 | 76 | 0.656616 | false | false | false | false |
hironytic/Eventitic
|
refs/heads/master
|
Sources/Eventitic/EventSource.swift
|
mit
|
1
|
//
// EventSource.swift
// Eventitic
//
// Copyright (c) 2016-2018 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
private class UnlistenPool<T> {
var listeners: [Listener<T>] = []
}
///
/// This class represents a source of events.
///
public class EventSource<T> {
private var listeners: [Listener<T>]
private var unlistenPools: [UnlistenPool<T>]
///
/// Initializes an event source.
///
public init() {
listeners = []
unlistenPools = []
}
///
/// Begins listening to events.
///
/// - Parameter handler: A closure which handles events.
/// - Returns: A listener object.
///
public func listen(_ handler: @escaping (T) -> Void) -> Listener<T> {
let listener = Listener(eventSource: self, handler: handler)
listeners.append(listener)
return listener
}
func unlisten(_ listener: Listener<T>) {
if let pool = unlistenPools.last {
pool.listeners.append(listener)
} else {
if let index = listeners.firstIndex(of: listener) {
listeners.remove(at: index)
}
}
}
///
/// Dispaches an event to its listeners.
///
/// - Parameter value: An event value.
///
public func fire(_ value: T) {
unlistenPools.append(UnlistenPool<T>())
listeners.forEach { listener in
listener.handleEvent(value)
}
let pool = unlistenPools.removeLast()
if pool.listeners.count > 0 {
listeners = listeners.filter { !pool.listeners.contains($0) }
}
}
}
|
4921158de9a1f338d323097e7e2fd8f2
| 30.436782 | 80 | 0.64351 | false | false | false | false |
rheinfabrik/Dobby
|
refs/heads/master
|
Dobby/Stub.swift
|
apache-2.0
|
2
|
/// A matcher-based behavior with closure-based handling.
fileprivate struct Behavior<Interaction, ReturnValue> {
/// The matcher of this behavior.
fileprivate let matcher: Matcher<Interaction>
/// The handler of this behavior.
fileprivate let handler: (Interaction) -> ReturnValue
/// Initializes a new behavior with the given matcher and handler.
fileprivate init<M: MatcherConvertible>(matcher: M, handler: @escaping (Interaction) -> ReturnValue) where M.ValueType == Interaction {
self.matcher = matcher.matcher()
self.handler = handler
}
}
/// A stub error.
public enum StubError<Interaction, ReturnValue>: Error {
/// The associated interaction was unexpected.
case unexpectedInteraction(Interaction)
}
/// A stub that, when invoked, returns a value based on the set up behavior, or,
/// if an interaction is unexpected, throws an error.
public final class Stub<Interaction, ReturnValue> {
/// The current (next) identifier for behaviors.
private var currentIdentifier: UInt = 0
/// The behaviors of this stub.
private var behaviors: [(identifier: UInt, behavior: Behavior<Interaction, ReturnValue>)] = []
/// Initializes a new stub.
public init() {
}
/// Modifies the behavior of this stub, forwarding invocations to the given
/// function and returning its return value if the given matcher does match
/// an interaction.
///
/// Returns a disposable that, when disposed, removes this behavior.
@discardableResult
public func on<M: MatcherConvertible>(_ matcher: M, invoke handler: @escaping (Interaction) -> ReturnValue) -> Disposable where M.ValueType == Interaction {
currentIdentifier += 1
let identifier = currentIdentifier
let behavior = Behavior(matcher: matcher, handler: handler)
behaviors.append((identifier: identifier, behavior: behavior))
return Disposable { [weak self] in
let index = self?.behaviors.index { otherIdentifier, _ in
return otherIdentifier == identifier
}
if let index = index {
self?.behaviors.remove(at: index)
}
}
}
/// Modifies the behavior of this stub, returning the given value upon
/// invocation if the given matcher does match an interaction.
///
/// Returns a disposable that, when disposed, removes this behavior.
///
/// - SeeAlso: `Stub.on<M>(matcher: M, invoke: Interaction -> ReturnValue) -> Disposable`
@discardableResult
public func on<M: MatcherConvertible>(_ matcher: M, return value: ReturnValue) -> Disposable where M.ValueType == Interaction {
return on(matcher) { _ in value }
}
/// Invokes this stub, returning a value based on the set up behavior, or,
/// if the given interaction is unexpected, throwing an error.
///
/// Behavior is matched in order, i.e., the function associated with the
/// first matcher that matches the given interaction is invoked.
///
/// - Throws: `StubError.unexpectedInteraction(Interaction)` if the given
/// interaction is unexpected.
@discardableResult
public func invoke(_ interaction: Interaction) throws -> ReturnValue {
for (_, behavior) in behaviors {
if behavior.matcher.matches(interaction) {
return behavior.handler(interaction)
}
}
throw StubError<Interaction, ReturnValue>.unexpectedInteraction(interaction)
}
}
|
4e55f5902bc85621b00e556e91344bd4
| 38.707865 | 160 | 0.667516 | false | false | false | false |
guidomb/Portal
|
refs/heads/master
|
Portal/Middlewares/TimeLogger.swift
|
mit
|
1
|
//
// TimeLogger.swift
// Portal
//
// Created by Guido Marucci Blas on 4/12/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import Foundation
public final class TimeLogger<StateType, MessageType, CommandType>: MiddlewareProtocol {
public typealias Transition = (StateType, CommandType?)?
public typealias NextMiddleware = (StateType, MessageType, CommandType?) -> Transition
public typealias Logger = (String) -> Void
public var log: Logger
public var isEnabled: Bool = true
public init(log: @escaping Logger = { print($0) }) {
self.log = log
}
public func call(
state: StateType,
message: MessageType,
command: CommandType?,
next: NextMiddleware) -> Transition {
let timestamp = Date.timeIntervalSinceReferenceDate
let result = next(state, message, command)
let dispatchTime = ((Date.timeIntervalSinceReferenceDate - timestamp) * 100000).rounded() / 100
if isEnabled {
log("Dispatch time \(dispatchTime)ms")
}
return result
}
}
|
ecc331403cebef729f97585ae9143722
| 26.902439 | 103 | 0.628497 | false | false | false | false |
CatchChat/Yep
|
refs/heads/master
|
Yep/Views/SkillHomeHeaderView/SkillHomeHeaderView.swift
|
mit
|
1
|
//
// SkillHomeHeaderView.swift
// Yep
//
// Created by kevinzhow on 15/5/6.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import Kingfisher
final class SkillHomeHeaderView: UIView {
var skillCategory: SkillCellSkill.Category = .Art
var skillCoverURLString: String? {
willSet {
// if let coverURLString = newValue, URL = NSURL(string: coverURLString) {
// headerImageView.kf_setImageWithURL(URL, placeholderImage: skillCategory.gradientImage)
//
// } else {
// headerImageView.image = skillCategory.gradientImage
// }
}
}
lazy var headerImageView: UIImageView = {
let tempImageView = UIImageView(frame: CGRectZero)
tempImageView.contentMode = .ScaleAspectFill
tempImageView.clipsToBounds = true
tempImageView.backgroundColor = UIColor.whiteColor()
return tempImageView;
}()
lazy var masterButton: SkillHomeSectionButton = {
let button = createSkillHomeButtonWithText(SkillSet.Master.name, width: 100, height: YepConfig.skillHomeHeaderButtonHeight)
return button
}()
lazy var learningButton: SkillHomeSectionButton = {
let button = createSkillHomeButtonWithText(SkillSet.Learning.name, width: 100, height: YepConfig.skillHomeHeaderButtonHeight)
return button
}()
var changeCoverAction: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
addSubview(headerImageView)
addSubview(masterButton)
addSubview(learningButton)
backgroundColor = UIColor.lightGrayColor()
headerImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(SkillHomeHeaderView.tap))
headerImageView.addGestureRecognizer(tap)
}
func tap() {
changeCoverAction?()
}
override func layoutSubviews() {
super.layoutSubviews()
headerImageView.frame = self.bounds
masterButton.frame = CGRectMake(0, self.frame.height - YepConfig.skillHomeHeaderButtonHeight, self.frame.size.width/2.0, YepConfig.skillHomeHeaderButtonHeight)
masterButton.updateHightLightBounce()
learningButton.frame = CGRectMake(masterButton.frame.size.width, self.frame.height - YepConfig.skillHomeHeaderButtonHeight, self.frame.size.width/2.0, YepConfig.skillHomeHeaderButtonHeight)
learningButton.updateHightLightBounce()
}
}
|
9d2cfe638a87458f93b69782ae31a91f
| 29.144444 | 197 | 0.670107 | false | true | false | false |
jpsim/SourceKitten
|
refs/heads/main
|
Source/SourceKittenFramework/String+SourceKitten.swift
|
mit
|
1
|
import Foundation
/**
* For "wall of asterisk" comment blocks, such as this one.
*/
private let commentLinePrefixCharacterSet: CharacterSet = {
var characterSet = CharacterSet.whitespacesAndNewlines
characterSet.insert(charactersIn: "*")
return characterSet
}()
// swiftlint:disable:next line_length
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/swift/grammar/line-break
private let newlinesCharacterSet = CharacterSet(charactersIn: "\u{000A}\u{000D}")
extension String {
internal var isFile: Bool {
var isDirectory: ObjCBool = false
let exists = FileManager.default.fileExists(atPath: self, isDirectory: &isDirectory)
return exists && !isDirectory.boolValue
}
/**
Returns true if self is an Objective-C header file.
*/
public func isObjectiveCHeaderFile() -> Bool {
return ["h", "hpp", "hh"].contains(bridge().pathExtension)
}
/// A version of the string with backslash escapes removed.
public var unescaped: String {
struct UnescapingSequence: Sequence, IteratorProtocol {
var iterator: String.Iterator
mutating func next() -> Character? {
guard let char = iterator.next() else { return nil }
guard char == "\\" else { return char }
return iterator.next()
}
}
return String(UnescapingSequence(iterator: makeIterator()))
}
/**
Returns true if self is a Swift file.
*/
public func isSwiftFile() -> Bool {
return bridge().pathExtension == "swift"
}
/**
Returns the body of the comment if the string is a comment.
- parameter range: Range to restrict the search for a comment body.
*/
public func commentBody(range: NSRange? = nil) -> String? {
let nsString = bridge()
let patterns: [(pattern: String, options: NSRegularExpression.Options)] = [
("^\\s*\\/\\*\\*\\s*(.*?)\\*\\/", [.anchorsMatchLines, .dotMatchesLineSeparators]), // multi: ^\s*\/\*\*\s*(.*?)\*\/
("^\\s*\\/\\/\\/(.+)?", .anchorsMatchLines) // single: ^\s*\/\/\/(.+)?
// swiftlint:disable:previous comma
]
let range = range ?? NSRange(location: 0, length: nsString.length)
for pattern in patterns {
let regex = try! NSRegularExpression(pattern: pattern.pattern, options: pattern.options) // Safe to force try
let matches = regex.matches(in: self, options: [], range: range)
let bodyParts = matches.flatMap { match -> [String] in
let numberOfRanges = match.numberOfRanges
if numberOfRanges < 1 {
return []
}
return (1..<numberOfRanges).map { rangeIndex in
let range = match.range(at: rangeIndex)
if range.location == NSNotFound {
return "" // empty capture group, return empty string
}
var lineStart = 0
var lineEnd = nsString.length
let indexRange = NSRange(location: range.location, length: 0)
nsString.getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: indexRange)
let leadingWhitespaceCountToAdd = nsString.substring(with: NSRange(location: lineStart, length: lineEnd - lineStart))
.countOfLeadingCharacters(in: .whitespacesAndNewlines)
let leadingWhitespaceToAdd = String(repeating: " ", count: leadingWhitespaceCountToAdd)
let bodySubstring = nsString.substring(with: range)
if bodySubstring.contains("@name") {
return "" // appledoc directive, return empty string
}
return leadingWhitespaceToAdd + bodySubstring
}
}
if !bodyParts.isEmpty {
return bodyParts.joined(separator: "\n").bridge()
.trimmingTrailingCharacters(in: .whitespacesAndNewlines)
.removingCommonLeadingWhitespaceFromLines()
}
}
return nil
}
/**
Returns the number of contiguous characters at the start of `self` belonging to `characterSet`.
- parameter characterSet: Character set to check for membership.
*/
public func countOfLeadingCharacters(in characterSet: CharacterSet) -> Int {
let characterSet = characterSet.bridge()
var count = 0
for char in utf16 {
if !characterSet.characterIsMember(char) {
break
}
count += 1
}
return count
}
/**
Returns a copy of `self` with the trailing contiguous characters belonging to `characterSet`
removed.
- parameter characterSet: Character set to check for membership.
*/
public func trimmingTrailingCharacters(in characterSet: CharacterSet) -> String {
guard !isEmpty else {
return ""
}
var unicodeScalars = self.bridge().unicodeScalars
while let scalar = unicodeScalars.last {
if !characterSet.contains(scalar) {
return String(unicodeScalars)
}
unicodeScalars.removeLast()
}
return ""
}
/// Returns a copy of `self` with the leading whitespace common in each line removed.
public func removingCommonLeadingWhitespaceFromLines() -> String {
var minLeadingCharacters = Int.max
let lineComponents = components(separatedBy: newlinesCharacterSet)
for line in lineComponents {
let lineLeadingWhitespace = line.countOfLeadingCharacters(in: .whitespacesAndNewlines)
let lineLeadingCharacters = line.countOfLeadingCharacters(in: commentLinePrefixCharacterSet)
// Is this prefix smaller than our last and not entirely whitespace?
if lineLeadingCharacters < minLeadingCharacters && lineLeadingWhitespace != line.count {
minLeadingCharacters = lineLeadingCharacters
}
}
return lineComponents.map { line in
if line.count >= minLeadingCharacters {
return String(line[line.index(line.startIndex, offsetBy: minLeadingCharacters)...])
}
return line
}.joined(separator: "\n")
}
internal func capitalizingFirstLetter() -> String {
return String(prefix(1)).capitalized + String(dropFirst())
}
}
extension NSString {
/**
Returns self represented as an absolute path.
- parameter rootDirectory: Absolute parent path if not already an absolute path.
*/
public func absolutePathRepresentation(rootDirectory: String = FileManager.default.currentDirectoryPath) -> String {
if isAbsolutePath { return bridge() }
#if os(Linux)
return NSURL(fileURLWithPath: NSURL.fileURL(withPathComponents: [rootDirectory, bridge()])!.path).standardizingPath!.path
#else
return NSString.path(withComponents: [rootDirectory, bridge()]).bridge().standardizingPath
#endif
}
}
extension Array where Element == String {
/// Return the full list of compiler arguments, replacing any response files with their contents.
var expandingResponseFiles: [String] {
return flatMap { arg -> [String] in
guard arg.starts(with: "@") else {
return [arg]
}
let responseFile = String(arg.dropFirst())
return (try? String(contentsOf: URL(fileURLWithPath: responseFile))).flatMap {
$0.trimmingCharacters(in: .newlines)
.components(separatedBy: "\n")
.map { $0.unescaped }
.expandingResponseFiles
} ?? [arg]
}
}
}
extension String {
/// Returns a copy of the string by trimming whitespace and the opening curly brace (`{`).
internal func trimmingWhitespaceAndOpeningCurlyBrace() -> String? {
var unwantedSet = CharacterSet.whitespacesAndNewlines
unwantedSet.insert(charactersIn: "{")
return trimmingCharacters(in: unwantedSet)
}
/// Returns the byte offset of the section of the string following the last dot ".", or 0 if no dots.
internal func byteOffsetOfInnerTypeName() -> ByteCount {
return range(of: ".", options: .backwards).map { range in
return ByteCount(self[...range.lowerBound].lengthOfBytes(using: .utf8))
} ?? 0
}
}
|
9136164524f832c253e2db16dc667096
| 39.170507 | 163 | 0.606975 | false | false | false | false |
jihun-kang/ios_a2big_sdk
|
refs/heads/master
|
A2bigSDK/GIFAnimatable.swift
|
apache-2.0
|
1
|
import UIKit
/// The protocol that view classes need to conform to to enable animated GIF support.
public protocol GIFAnimatable: class {
/// Responsible for managing the animation frames.
var animator: Animator? { get set }
/// Notifies the instance that it needs display.
var layer: CALayer { get }
/// View frame used for resizing the frames.
var frame: CGRect { get set }
/// Content mode used for resizing the frames.
var contentMode: UIViewContentMode { get set }
}
/// A single-property protocol that animatable classes can optionally conform to.
public protocol ImageContainer {
/// Used for displaying the animation frames.
var image: UIImage? { get set }
}
extension GIFAnimatable where Self: ImageContainer {
/// Returns the intrinsic content size based on the size of the image.
public var intrinsicContentSize: CGSize {
return image?.size ?? CGSize.zero
}
}
extension GIFAnimatable {
/// Returns the active frame if available.
public var activeFrame: UIImage? {
return animator?.activeFrame()
}
/// Total frame count of the GIF.
public var frameCount: Int {
return animator?.frameCount ?? 0
}
/// Introspect whether the instance is animating.
public var isAnimatingGIF: Bool {
return animator?.isAnimating ?? false
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageName: The file name of the GIF in the main bundle.
public func animate(withGIFNamed imageName: String) {
animator?.animate(withGIFNamed: imageName, size: frame.size, contentMode: contentMode)
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageData: GIF image data.
public func animate(withGIFData imageData: Data) {
animator?.animate(withGIFData: imageData, size: frame.size, contentMode: contentMode)
}
/// Prepares the animator instance for animation.
///
/// - parameter imageName: The file name of the GIF in the main bundle.
public func prepareForAnimation(withGIFNamed imageName: String) {
animator?.prepareForAnimation(withGIFNamed: imageName, size: frame.size, contentMode: contentMode)
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageData: GIF image data.
public func prepareForAnimation(withGIFData imageData: Data) {
if var imageContainer = self as? ImageContainer {
imageContainer.image = UIImage(data: imageData)
}
animator?.prepareForAnimation(withGIFData: imageData, size: frame.size, contentMode: contentMode)
}
/// Stop animating and free up GIF data from memory.
public func prepareForReuse() {
animator?.prepareForReuse()
}
/// Start animating GIF.
public func startAnimatingGIF() {
animator?.startAnimating()
}
/// Stop animating GIF.
public func stopAnimatingGIF() {
animator?.stopAnimating()
}
/// Whether the frame images should be resized or not. The default is `false`, which means that the frame images retain their original size.
///
/// - parameter resize: Boolean value indicating whether individual frames should be resized.
public func setShouldResizeFrames(_ resize: Bool) {
animator?.shouldResizeFrames = resize
}
/// Sets the number of frames that should be buffered. Default is 50. A high number will result in more memory usage and less CPU load, and vice versa.
///
/// - parameter frames: The number of frames to buffer.
public func setFrameBufferCount(_ frames: Int) {
animator?.frameBufferCount = frames
}
/// Updates the image with a new frame if necessary.
public func updateImageIfNeeded() {
if var imageContainer = self as? ImageContainer {
imageContainer.image = activeFrame ?? imageContainer.image
} else {
layer.contents = activeFrame?.cgImage
}
}
}
extension GIFAnimatable {
/// Calls setNeedsDisplay on the layer whenever the animator has a new frame. Should *not* be called directly.
func animatorHasNewFrame() {
layer.setNeedsDisplay()
}
}
|
5204808a49192b3a03210c4a4dacef82
| 31.232 | 153 | 0.719037 | false | false | false | false |
huangboju/QMUI.swift
|
refs/heads/master
|
QMUI.swift/Demo/Modules/Demos/UIKit/QDSearchViewController.swift
|
mit
|
1
|
//
// QDSearchViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/19.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDSearchViewController: QDCommonTableViewController {
private let keywords = ["Helps", "Maintain", "Liver", "Health", "Function", "Supports", "Healthy", "Fat", "Metabolism", "Nuturally"]
private var searchResultsKeywords: [String] = []
private lazy var mySearchController: QMUISearchController = {
// QMUISearchController 有两种使用方式,一种是独立使用,一种是集成到 QMUICommonTableViewController 里使用。为了展示它的使用方式,这里使用第一种,不理会 QMUICommonTableViewController 内部自带的 QMUISearchController
let mySearchController = QMUISearchController(contentsViewController: self)
mySearchController.searchResultsDelegate = self
mySearchController.launchView = QDRecentSearchView() // launchView 会自动布局,无需处理 frame
mySearchController.searchBar?.qmui_usedAsTableHeaderView = true // 以 tableHeaderView 的方式使用 searchBar 的话,将其置为 YES,以辅助兼容一些系统 bug
return mySearchController
}()
override init(style: UITableView.Style) {
super.init(style: style)
// 这个属性默认就是 false,这里依然写出来只是为了提醒 QMUICommonTableViewController 默认就集成了 QMUISearchController,如果你的界面本身就是 QMUICommonTableViewController 的子类,则也可以直接通过将这个属性改为 true 来创建 QMUISearchController
shouldShowSearchBar = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableHeaderView = mySearchController.searchBar
}
}
extension QDSearchViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection _: Int) -> Int {
if tableView == self.tableView {
return keywords.count
}
return searchResultsKeywords.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "cell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if cell == nil {
cell = QMUITableViewCell(tableView: self.tableView, reuseIdentifier: identifier)
}
if tableView == self.tableView {
cell?.textLabel?.text = keywords[indexPath.row]
} else {
let keyword = searchResultsKeywords[indexPath.row]
let attributedString = NSMutableAttributedString(string: keyword, attributes: [NSAttributedString.Key.foregroundColor: UIColorBlack])
if let string = mySearchController.searchBar?.text, let range = keyword.range(of: string), let color = QDThemeManager.shared.currentTheme?.themeTintColor {
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(range, in: string))
}
cell?.textLabel?.attributedText = attributedString
}
(cell as? QMUITableViewCell)?.updateCellAppearance(indexPath)
return cell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension QDSearchViewController {
override func searchController(_ searchController: QMUISearchController, updateResultsFor searchString: String?) {
searchResultsKeywords.removeAll()
for key in keywords {
if searchString != nil && key.contains(searchString!) {
searchResultsKeywords.append(key)
}
}
searchController.tableView?.reloadData()
if searchResultsKeywords.count == 0 {
searchController.showEmptyViewWith(text: "没有匹配结果", detailText: nil, buttonTitle: nil, buttonAction: nil)
} else {
searchController.hideEmptyView()
}
}
func willPresent(_ searchController: QMUISearchController) {
QMUIHelper.renderStatusBarStyleDark()
}
func willDismiss(_: QMUISearchController) {
var oldStatusbarLight = false
oldStatusbarLight = shouldSetStatusBarStyleLight
if oldStatusbarLight {
QMUIHelper.renderStatusBarStyleLight()
} else {
QMUIHelper.renderStatusBarStyleDark()
}
}
}
class QDRecentSearchView: UIView {
private lazy var titleLabel: QMUILabel = {
let label = QMUILabel(with: UIFontMake(14), textColor: UIColorGray2)
label.text = "最近搜索"
label.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
label.sizeToFit()
label.qmui_borderPosition = .bottom
return label
}()
private lazy var floatLayoutView: QMUIFloatLayoutView = {
let floatLayoutView = QMUIFloatLayoutView()
floatLayoutView.padding = .zero
floatLayoutView.itemMargins = UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)
floatLayoutView.minimumItemSize = CGSize(width: 69, height: 29)
return floatLayoutView
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColorWhite
addSubview(titleLabel)
addSubview(floatLayoutView)
let suggestions = ["Helps", "Maintain", "Liver", "Health", "Function", "Supports", "Healthy", "Fat"]
suggestions.forEach {
let button = QMUIGhostButton(ghostType: .gray)
button.setTitle($0, for: .normal)
button.titleLabel?.font = UIFontMake(14)
button.contentEdgeInsets = UIEdgeInsets(top: 6, left: 20, bottom: 6, right: 20)
floatLayoutView.addSubview(button)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let padding = UIEdgeInsets(top: 26, left: 26, bottom: 26, right: 26).concat(insets: qmui_safeAreaInsets)
let titleLabelMarginTop: CGFloat = 20
titleLabel.frame = CGRect(x: padding.left, y: padding.top, width: bounds.width - padding.horizontalValue, height: titleLabel.frame.height)
let minY = titleLabel.frame.maxY + titleLabelMarginTop
floatLayoutView.frame = CGRect(x: padding.left, y: minY, width: bounds.width - padding.horizontalValue, height: bounds.height - minY)
}
}
|
3c9d0358fdd6fba6e32c0aefb12f7519
| 39.223602 | 188 | 0.669549 | false | false | false | false |
b-andris/Authenticate
|
refs/heads/master
|
Authenticate/LockViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Authenticate
//
// Created by Benjamin Andris Suter-Dörig on 09/05/15.
// Copyright (c) 2015 Benjamin Andris Suter-Dörig. All rights reserved.
//
import UIKit
import LocalAuthentication
import Dispatch
import CoreImage
@objc public protocol LockViewControllerDelegate {
func lockViewControllerAuthentication(_ controller: LockViewController, didSucced success: Bool)
func lockViewControllerDidSetup(_ controller: LockViewController, code: String)
}
private enum CodeValidationResult {
case ok
case tooShort
case wrong
}
@objc public enum LockScreenMode: Int {
case setup
case authenticate
}
private class Keypad: UIView {
var enterPrompt = "Enter PIN" {
didSet {
updateTextField()
}
}
var wrongCodeMessage = "Wrong PIN" {
didSet {
updateTextField()
}
}
var callback: (String) -> (CodeValidationResult) = {code -> CodeValidationResult in return .wrong}
var timeUnits = ["Sec", "Min", "Hours", "Days", "Months", "Years"]
var wait: UInt = 0 {
didSet {
if wait > 0 {
for button in digitButtons {
button.isEnabled = false
}
deleteButton.isEnabled = false
if wait < 60 {
textField.placeholder = "\(wait) \(timeUnits[0])"
} else if wait < 60 * 60 {
textField.placeholder = "\(wait / 60) \(timeUnits[1])"
} else if wait < 60 * 60 * 24 {
textField.placeholder = "\(wait / 60 / 60) \(timeUnits[2])"
} else if wait < 60 * 60 * 24 * 30 {
textField.placeholder = "\(wait / 60 / 60 / 24) \(timeUnits[3])"
} else if wait < 60 * 60 * 24 * 365 {
textField.placeholder = "\(wait / 60 / 60 / 24 / 30) \(timeUnits[4])"
} else {
textField.placeholder = "\(wait / 60 / 60 / 24 / 365) \(timeUnits[5])"
}
textField.text = ""
} else {
for button in digitButtons {
button.isEnabled = true
}
deleteButton.isEnabled = true
updateTextField()
}
}
}
private var digitButtons: [UIButton] = []
private let deleteButton = UIButton(type: .system) as UIButton
private var enteredCode = ""
private let textField = UITextField()
private var showWrongPINMessage = false
init() {
super.init(frame: CGRect.zero)
let chars = ["⓪", "①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⌫"]
for i in 0 ... 9 {
digitButtons.append(UIButton(type: .system) as UIButton)
digitButtons[i].setTitle(chars[i], for: UIControlState())
digitButtons[i].tag = i
digitButtons[i].addTarget(self, action: #selector(Keypad.digitButtonPressed(_:)), for: .touchUpInside)
addSubview(digitButtons[i])
}
deleteButton.setTitle(chars[10], for: UIControlState())
deleteButton.addTarget(self, action: #selector(Keypad.deleteButtonPressed(_:)), for: .touchUpInside)
addSubview(textField)
textField.isUserInteractionEnabled = false
textField.textAlignment = .center
updateTextField()
addSubview(deleteButton)
layout()
}
@IBAction func digitButtonPressed(_ button: UIButton) {
enteredCode += "\(button.tag)"
if callback(enteredCode) == .wrong {
enteredCode = ""
showWrongPINMessage = true
} else {
showWrongPINMessage = false
}
updateTextField()
}
@IBAction func deleteButtonPressed(_ button: UIButton) {
if enteredCode.count > 0 {
let index = enteredCode.index(enteredCode.endIndex, offsetBy: -1)
enteredCode = String(enteredCode[..<index])
updateTextField()
}
}
func reset() {
enteredCode = ""
showWrongPINMessage = false
updateTextField()
}
private func updateTextField() {
if wait > 0 {
return
}
if showWrongPINMessage {
textField.placeholder = wrongCodeMessage
} else {
textField.placeholder = enterPrompt
}
var code = ""
for _ in 0 ..< enteredCode.count {
code += " ●"
}
textField.text = code
}
private func layout() {
let elementWidth = bounds.width / 3
let elementHeight = bounds.height / 5
textField.frame = CGRect(x: 0, y: 0, width: bounds.width, height: elementHeight)
textField.font = UIFont.systemFont(ofSize: min(elementWidth, elementHeight) * 0.5)
for i in 1 ... 9 {
digitButtons[i].frame = CGRect(x: (CGFloat(i) + 2).truncatingRemainder(dividingBy: 3) * elementWidth, y: floor((CGFloat(i) + 2) / 3) * elementHeight, width: elementWidth, height: elementHeight)
digitButtons[i].titleLabel?.font = UIFont.systemFont(ofSize: min(elementWidth, elementHeight) * 0.9)
}
digitButtons[0].frame = CGRect(x: elementWidth, y: 4 * elementHeight, width: elementWidth, height: elementHeight)
digitButtons[0].titleLabel?.font = UIFont.systemFont(ofSize: min(elementWidth, elementHeight) * 0.9)
deleteButton.frame = CGRect(x: 2 * elementWidth, y: 4 * elementHeight, width: elementWidth, height: elementHeight)
deleteButton.titleLabel?.font = UIFont.systemFont(ofSize: min(elementWidth, elementHeight) * 0.5)
}
override func layoutSubviews() {
layout()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
public class LockViewController: UIViewController, UIViewControllerTransitioningDelegate {
private var keypad: Keypad = Keypad()
private var isVerifying = false
private var isUpdatingWait = false
private var waitTime = 0.16
private var background = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light))
private var upBackground = UIView()
private var downBackground = UIView()
private var rightBackground = UIView()
private var leftBackground = UIView()
private var wait: UInt {
get {
return keypad.wait
}
set(wait) {
keypad.wait = wait
if (!isUpdatingWait) {
updateWait()
}
}
}
@objc public var code: String = "0000"
@objc public var reason: String = "Unlock " + (Bundle.main.infoDictionary!["CFBundleName"] as! String)
@objc public var allowsTouchID = true
@objc public var mode = LockScreenMode.authenticate
@objc public var codeLength = 4
@objc public var remainingAttempts = -1
@objc public var maxWait: UInt = 30
@objc public var delegate: LockViewControllerDelegate?
@objc public var wrongCodeMessage: String {
get {
return keypad.wrongCodeMessage
}
set(wrongCodeMessage) {
keypad.wrongCodeMessage = wrongCodeMessage
}
}
@objc public var enterPrompt = "Enter PIN" {
didSet {
if !isVerifying {
keypad.enterPrompt = enterPrompt
}
}
}
@objc public var verifyPrompt = "Verify" {
didSet {
if isVerifying {
keypad.enterPrompt = verifyPrompt
}
}
}
@objc public var timeUnits: [String] {
get {
return keypad.timeUnits
}
set(timeUnits) {
keypad.timeUnits = timeUnits
}
}
private func updateWait() {
if wait > 0 {
isUpdatingWait = true
weak var weakSelf = self
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
if let strongSelf = weakSelf {
strongSelf.wait -= 1
strongSelf.updateWait()
}
}
} else {
isUpdatingWait = false
}
}
private func validate(code: String) -> CodeValidationResult {
if mode == .authenticate {
if code.count < self.code.count {
return .tooShort
} else if code == self.code {
if let del = delegate {
del.lockViewControllerAuthentication(self, didSucced: true)
} else {
dismiss(animated: true, completion: nil)
}
return .ok
} else {
if remainingAttempts > 0 {
remainingAttempts -= 1
}
if remainingAttempts == 0 {
if let del = delegate {
del.lockViewControllerAuthentication(self, didSucced: false)
} else {
dismiss(animated: true, completion: nil)
}
return .wrong
}
if maxWait > 0 {
waitTime *= 2
if UInt(waitTime) > maxWait {
wait = maxWait
} else {
wait = UInt(waitTime)
}
}
return .wrong
}
} else {
if code.count < codeLength {
return .tooShort
} else if isVerifying && code == self.code {
if let del = delegate {
del.lockViewControllerDidSetup(self, code: code)
} else {
dismiss(animated: true, completion: nil)
}
return .ok
} else if isVerifying {
isVerifying = false
keypad.enterPrompt = enterPrompt
return .wrong
} else {
isVerifying = true
self.code = code
keypad.enterPrompt = verifyPrompt
keypad.reset()
return .ok
}
}
}
init() {
super.init(nibName: nil, bundle: nil)
transitioningDelegate = self
modalPresentationStyle = .custom
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
transitioningDelegate = self
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
keypad.callback = validate(code:)
let context = LAContext()
if allowsTouchID && mode == .authenticate {
context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error:nil)
weak var weakSelf = self
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply: { (success, error) ->Void in
if success {
if let strongSelf = weakSelf {
if let del = strongSelf.delegate {
del.lockViewControllerAuthentication(self, didSucced: true)
} else {
strongSelf.dismiss(animated: true, completion: nil)
}
}
}
})
}
view.addSubview(background)
view.addSubview(keypad)
leftBackground.backgroundColor = UIColor.black
rightBackground.backgroundColor = UIColor.black
upBackground.backgroundColor = UIColor.black
downBackground.backgroundColor = UIColor.black
view.addSubview(leftBackground)
view.addSubview(rightBackground)
view.addSubview(upBackground)
view.addSubview(downBackground)
setupView(view.bounds.size)
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
setupView(size)
}
private func setupView(_ size: CGSize) {
let elementSize = min(min(size.width / 3, size.height / 5), 100)
keypad.frame = CGRect(x: 0, y: 0, width: 3 * elementSize, height: 5 * elementSize)
keypad.center = CGPoint(x: size.width / 2, y: size.height / 2)
background.frame.size = size
let maxSize = max(size.width, size.height)
leftBackground.frame = CGRect(x: -maxSize, y: -maxSize, width: maxSize, height: 3 * maxSize)
rightBackground.frame = CGRect(x: size.width, y: -maxSize, width: maxSize, height: 3 * maxSize)
upBackground.frame = CGRect(x: -maxSize, y: -maxSize, width: 3 * maxSize, height: maxSize)
downBackground.frame = CGRect(x: -maxSize, y: size.height, width: 3 * maxSize, height: maxSize)
}
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PresentController()
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return DismissController()
}
}
private class PresentController: NSObject, UIViewControllerAnimatedTransitioning {
@objc func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
@objc func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let vc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
transitionContext.containerView.addSubview(vc.view)
vc.view.alpha = 0
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
vc.view.alpha = 1
}, completion: { (finished) -> Void in transitionContext.completeTransition(finished)})
}
}
private class DismissController: NSObject, UIViewControllerAnimatedTransitioning {
@objc func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
@objc func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let vc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
vc.view.alpha = 1
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
vc.view.alpha = 0
}, completion: { (finished) -> Void in
vc.view.removeFromSuperview()
transitionContext.completeTransition(finished)
})
}
}
|
46c0af05f8a4ed8fb868a25f698db76e
| 28.820639 | 196 | 0.70075 | false | false | false | false |
aptyr/-github-iOS
|
refs/heads/master
|
#github-ios/models/AccessToken.swift
|
apache-2.0
|
1
|
//
// AccessToken.swift
// #github-ios
//
// Created by Artur on 09/03/2017.
// Copyright © 2017 Artur Matusiak. All rights reserved.
//
import Foundation
final class AccessToken: HTTPRequestResult {
private(set) var accessTokenKey: String?
private(set) var scope: String?
private(set) var tokenType: String?
private var params: [String : String]?
init(withDictionary params: [String : String]) {
self.params = params
self.accessTokenKey = params["access_token"]
self.scope = params["scope"]
self.tokenType = params["token_type"]
}
convenience init(withString params: String){
self.init(withDictionary: params.dictionary)
}
convenience init(withApiData data: Data) throws {
let params = try JSONSerialization.jsonObject(with: data, options: []) as! [String: String]
self.init(withDictionary: params)
}
}
|
15c1d70da8777230de32a9c6e5aa70f1
| 25.222222 | 99 | 0.64089 | false | false | false | false |
MattLewin/Interview-Prep
|
refs/heads/master
|
Data Structures.playground/Pages/Binary Heap.xcplaygroundpage/Contents.swift
|
unlicense
|
1
|
//: [Previous](@previous)
import Foundation
class MinHeap {
private(set) var heap: [Int]
private(set) var elementCount = 0
init(size: Int = 3) {
heap = Array<Int>(repeatElement(Int.max, count: size))
}
private func resizeHeap() {
var newHeap = Array<Int>(repeatElement(Int.max, count: (2 * heap.count)))
newHeap[0..<heap.count] = heap[...]
heap = newHeap
}
private func swap(_ index1: Int, _ index2: Int) {
let temp = heap[index1]
heap[index1] = heap[index2]
heap[index2] = temp
}
private func bubbleUp(_ index: Int) {
var currentIndex = index
var parentIndex = currentIndex / 2
while parentIndex > 0 &&
(heap[parentIndex] > heap[currentIndex]) {
swap(parentIndex, currentIndex)
currentIndex = parentIndex
parentIndex = currentIndex / 2
}
}
private func bubbleDown(_ index: Int) {
var currentIndex = index
var leftIndex = currentIndex * 2
var rightIndex = leftIndex + 1
while currentIndex <= elementCount {
if leftIndex <= elementCount &&
(heap[currentIndex] > heap[leftIndex]) {
swap(currentIndex, leftIndex)
currentIndex = leftIndex
}
else if rightIndex < elementCount &&
(heap[currentIndex] > heap[rightIndex]) {
swap(currentIndex, rightIndex)
currentIndex = rightIndex
}
else {
break
}
leftIndex = currentIndex * 2
rightIndex = leftIndex + 1
}
}
public func insert(_ element: Int) {
elementCount += 1
if elementCount >= heap.count {
resizeHeap()
}
heap[elementCount] = element
bubbleUp(elementCount)
}
public func removeMin() -> Int {
let retVal = heap[1]
heap[1] = heap[elementCount]
heap[elementCount] = Int.max
elementCount -= 1
bubbleDown(1)
return retVal
}
}
let minHeap = MinHeap()
minHeap.insert(4)
minHeap.insert(50)
minHeap.insert(7)
minHeap.insert(55)
minHeap.insert(90)
minHeap.insert(87)
minHeap.insert(2)
minHeap.removeMin()
minHeap
//: [Next](@next)
|
dfb408f608445358a769526114f0b094
| 23.684211 | 81 | 0.549254 | false | false | false | false |
Pstoppani/swipe
|
refs/heads/master
|
core/SwipeList.swift
|
mit
|
4
|
//
// SwipeList.swift
//
// Created by Pete Stoppani on 5/26/16.
//
import Foundation
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
class SwipeList: SwipeView, UITableViewDelegate, UITableViewDataSource {
let TAG = "SWList"
private var items = [[String:Any]]()
private var itemHeights = [CGFloat]()
private var defaultItemHeight: CGFloat = 40
private let scale:CGSize
private var screenDimension = CGSize(width: 0, height: 0)
weak var delegate:SwipeElementDelegate!
var tableView: UITableView
init(parent: SwipeNode, info: [String:Any], scale: CGSize, frame: CGRect, screenDimension: CGSize, delegate:SwipeElementDelegate) {
self.scale = scale
self.screenDimension = screenDimension
self.delegate = delegate
self.tableView = UITableView(frame: frame, style: .plain)
super.init(parent: parent, info: info)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
#if !os(tvOS)
self.tableView.separatorStyle = .none
#endif
self.tableView.allowsSelection = true
self.tableView.backgroundColor = UIColor.clear
if let value = info["itemH"] as? CGFloat {
defaultItemHeight = value
} else if let value = info["itemH"] as? String {
defaultItemHeight = SwipeParser.parsePercent(value, full: screenDimension.height, defaultValue: defaultItemHeight)
}
if let itemsInfo = info["items"] as? [[String:Any]] {
items = itemsInfo
for _ in items {
itemHeights.append(defaultItemHeight)
}
}
if let scrollEnabled = self.info["scrollEnabled"] as? Bool {
self.tableView.isScrollEnabled = scrollEnabled
}
self.tableView.reloadData()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
if let selectedIndex = self.info["selectedItem"] as? Int {
self.tableView.selectRow(at: IndexPath(row: selectedIndex, section: 0), animated: true, scrollPosition: .middle)
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// UITableViewDataDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return itemHeights[indexPath.row]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let actions = parent!.eventHandler.actionsFor("rowSelected") {
parent!.execute(self, actions: actions)
}
}
// UITableViewDataSource
var cellIndexPath: IndexPath?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let subviewTag = 999
self.cellIndexPath = indexPath
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
if let subView = cell.contentView.viewWithTag(subviewTag) {
subView.removeFromSuperview()
}
var cellError: String?
let item = self.items[indexPath.row]
if let itemH = item["h"] as? CGFloat {
self.itemHeights[indexPath.row] = itemH
}
let itemHeight = self.itemHeights[indexPath.row]
if let elementsInfo = item["elements"] as? [[String:Any]] {
for elementInfo in elementsInfo {
let element = SwipeElement(info: elementInfo, scale:self.scale, parent:self, delegate:self.delegate!)
if let subview = element.loadViewInternal(CGSize(width: self.tableView.bounds.size.width, height: itemHeight), screenDimension: self.screenDimension) {
subview.tag = subviewTag
cell.contentView.addSubview(subview)
children.append(element)
} else {
cellError = "can't load"
}
}
} else {
cellError = "no elements"
}
if cellError != nil {
let v = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: itemHeight))
let l = UILabel(frame: CGRect(x:0, y:0, width: v.bounds.size.width, height: v.bounds.size.height))
v.addSubview(l)
cell.contentView.addSubview(v)
l.text = "row \(indexPath.row) error " + cellError!
}
cell.selectionStyle = .none
self.cellIndexPath = nil
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
// SwipeView
override func appendList(_ originator: SwipeNode, info: [String:Any]) {
if let itemsInfoArray = info["items"] as? [[String:Any]] {
var itemInfos = [[String:Any]]()
for itemInfo in itemsInfoArray {
if let _ = itemInfo["data"] as? [String:Any] {
var eval = originator.evaluate(itemInfo)
// if 'data' is a JSON string, use it, otherwise, use the info as is
if let dataStr = eval["data"] as? String, let data = dataStr.data(using: .utf8) {
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String:Any] else {
// 'data' is a plain String
itemInfos.append(eval)
break
}
// 'data' is a JSON string so use the JSON object
if (json["elements"] as? [[String:Any]]) != nil {
// 'data' is a redefinition of the item
itemInfos.append(json)
} else {
// 'data' is just data
eval["data"] = json
itemInfos.append(eval)
}
} catch {
// 'data' is a plain String
itemInfos.append(eval)
}
} else {
// 'data' is a 'valueOf' JSON object
itemInfos.append(eval)
}
} else {
itemInfos.append(itemInfo)
}
}
var urls = [URL:String]()
for itemInfo in itemInfos {
if let elementsInfo = itemInfo["elements"] as? [[String:Any]] {
let scaleDummy = CGSize(width: 0.1, height: 0.1)
for e in elementsInfo {
let element = SwipeElement(info: e, scale:scaleDummy, parent:self, delegate:self.delegate!)
for (url, prefix) in element.resourceURLs {
urls[url] = prefix
}
}
}
}
self.delegate.addedResourceURLs(urls) {
for itemInfo in itemInfos {
self.items.append(itemInfo)
self.itemHeights.append(self.defaultItemHeight)
}
self.tableView.reloadData()
self.tableView.scrollToRow(at: IndexPath(row: self.items.count - 1, section: 0), at: .bottom, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
self.tableView.scrollToRow(at: IndexPath(row: self.items.count - 1, section: 0), at: .bottom, animated: true)
}
}
}
}
override func appendList(_ originator: SwipeNode, name: String, up: Bool, info: [String:Any]) -> Bool {
if (name == "*" || self.name.caseInsensitiveCompare(name) == .orderedSame) {
appendList(originator, info: info)
return true
}
var node: SwipeNode? = self
if up {
while node?.parent != nil {
if let viewNode = node?.parent as? SwipeView {
for c in viewNode.children {
if let e = c as? SwipeElement {
if e.name.caseInsensitiveCompare(name) == .orderedSame {
e.appendList(originator, info: info)
return true
}
}
}
node = node?.parent
} else {
return false
}
}
} else {
for c in children {
if let e = c as? SwipeElement {
if e.updateElement(originator, name:name, up:up, info:info) {
return true
}
}
}
}
return false
}
// SwipeNode
override func getPropertyValue(_ originator: SwipeNode, property: String) -> Any? {
switch (property) {
case "selectedItem":
if let indexPath = self.tableView.indexPathForSelectedRow {
return "\(indexPath.row)"
} else {
return "none"
}
default:
return nil
}
}
override func getPropertiesValue(_ originator: SwipeNode, info: [String:Any]) -> Any? {
let prop = info.keys.first!
switch (prop) {
case "items":
if let indexPath = self.cellIndexPath {
var item = items[indexPath.row]
if let itemStr = info["items"] as? String {
// ie "property":{"items":"data"}}
if let val = item[itemStr] as? String {
// ie "data":String
return val
} else if let valInfo = item[itemStr] as? [String:Any] {
// ie "data":{...}
return originator.evaluate(valInfo)
}
}
// ie "property":{"items":{"data":{...}}}
var path = info["items"] as! [String:Any]
var property = path.keys.first!
while (true) {
if let next = path[property] as? String {
if let sub = item[property] as? [String:Any] {
return sub[next]
} else {
return nil
}
} else if let next = path[property] as? [String:Any] {
if let sub = item[property] as? [String:Any] {
path = next
property = path.keys.first!
item = sub
} else {
return nil
}
} else {
return nil
}
}
// loop on properties in info until get to a String
} else {
print("no cellIndexPath")
}
break;
default:
return nil
}
return nil
}
}
|
8b6d233377517b955881b1114af25cd9
| 37.511475 | 167 | 0.486719 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
refs/heads/develop
|
Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/RoundCornersSelectionTableViewCell.swift
|
apache-2.0
|
3
|
//
// RoundCornersSelectionTableViewCell.swift
// SwiftEntryKit_Example
//
// Created by Daniel Huri on 4/25/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import SwiftEntryKit
class RoundCornersSelectionTableViewCell: SelectionTableViewCell {
override func configure(attributesWrapper: EntryAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "Round Corners"
descriptionValue = "The entry's corners can be rounded in one of the following manner"
insertSegments(by: ["None", "Top", "Bottom", "All"])
selectSegment()
}
private func selectSegment() {
switch attributesWrapper.attributes.roundCorners {
case .none:
segmentedControl.selectedSegmentIndex = 0
case .top(radius: _):
segmentedControl.selectedSegmentIndex = 1
case .bottom(radius: _):
segmentedControl.selectedSegmentIndex = 2
case .all(radius: _):
segmentedControl.selectedSegmentIndex = 3
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
attributesWrapper.attributes.roundCorners = .none
case 1:
attributesWrapper.attributes.roundCorners = .top(radius: 10)
case 2:
attributesWrapper.attributes.roundCorners = .bottom(radius: 10)
case 3:
attributesWrapper.attributes.roundCorners = .all(radius: 10)
default:
break
}
}
}
|
f488fa5b4bd2726dbf5cfd780a3883ae
| 31.55102 | 94 | 0.647022 | false | false | false | false |
904388172/-TV
|
refs/heads/master
|
DouYuTV/DouYuTV/Classes/Home/View/MenuView.swift
|
mit
|
1
|
//
// MenuView.swift
// DouYuTV
//
// Created by GS on 2017/10/26.
// Copyright © 2017年 Demo. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class MenuView: UIView {
//MARK: - 定义属性
var groups: [AnchorGroup]? {
didSet {
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
//MARK: - 从xib中加载出来
override func awakeFromNib() {
super.awakeFromNib()
//xib方式注册cell
collectionView.register(UINib(nibName: "CollectionMenuCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
//必须在这个方法里面布局
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
// 行间距
layout.minimumLineSpacing = 0
//item之间的间距
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
}
}
//MARK: - 从xib中快速创建的类方法
extension MenuView {
class func menuView() -> MenuView {
return Bundle.main.loadNibNamed("MenuView", owner: nil, options: nil)?.first as! MenuView
}
}
//MARK: - UICollectionView dataSource
extension MenuView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups == nil {
return 0
}
let pageNum = (groups!.count - 1) / 8 + 1
if pageNum <= 1 {
pageControl.isHidden = true
} else {
//只显示两个
// pageNum = 2
//显示多个
pageControl.numberOfPages = pageNum
}
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! CollectionMenuCell
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
//像里面的cell传递数据
private func setupCellDataWithCell(cell: CollectionMenuCell, indexPath: IndexPath) {
//0页:0~7
//1页:8~15
//2页:16~23
//1.取出起始位置,终点位置
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
//2.判断越界问题
if endIndex > (groups?.count)! - 1 {
endIndex = (groups?.count)! - 1
}
//3.取出数据,赋值给cell
cell.groups = Array(groups![startIndex...endIndex])
}
}
//MARK: - UICollectionView Delegate
extension MenuView: UICollectionViewDelegate {
//监听滚动
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//计算pageControl的currentIndex
pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
}
}
|
0cbdf4fa74b2e0e4050939229ae562f5
| 24.878049 | 126 | 0.612001 | false | false | false | false |
kamawshuang/iOS---Animation
|
refs/heads/master
|
3D动画(八)/3Dstart/3DSlideMenu/3DSlideMenu/MenuButton.swift
|
apache-2.0
|
2
|
////
//// MenuButton.swift
//// 3DSlideMenu
////
//// Created by 51Testing on 15/12/9.
//// Copyright © 2015年 HHW. All rights reserved.
////
////
//import UIKit
//
//
////自定义按钮
//class MenuButton: UIView {
//
// var imageView: UIImageView!
// var tapHandler: (()->())?
//
// //当视图移动完成后调用
// override func didMoveToSuperview() {
// frame = CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0)
// imageView = UIImageView(image: UIImage(named: "menu.png"))
// imageView.userInteractionEnabled = true
// imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTap")))
// addSubview(imageView)
// }
//
// func didTap() {
// tapHandler?()
// }
//
//}
import UIKit
class MenuButton: UIView {
var imageView: UIImageView!
var tapHandler: (()->())?
override func didMoveToSuperview() {
frame = CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0)
imageView = UIImageView(image:UIImage(named:"menu.png"))
imageView.userInteractionEnabled = true
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTap")))
addSubview(imageView)
}
func didTap() {
tapHandler?()
}
}
|
3983cb6727d5347daefd33b5935c690a
| 23.415094 | 106 | 0.589327 | false | false | false | false |
wangjwchn/MetalAcc
|
refs/heads/master
|
MetalAcc/AccImage.swift
|
mit
|
1
|
//
// AccImage.swift
// MetalAcc
//
// Created by 王佳玮 on 16/4/19.
// Copyright © 2016年 wangjwchn. All rights reserved.
//
import MetalKit
import ImageIO
public class AccImage{
private var commandQueue:MTLCommandQueue
private var textures = [MTLTexture]()
public var filter:AccImageFilter?
init(){
self.commandQueue = MTLCreateSystemDefaultDevice()!.newCommandQueue()
}
public func Input(image:UIImage){
let texture = image.toMTLTexture()
if(textures.isEmpty==true){
textures.append(texture.sameSizeEmptyTexture())//outTexture
}
textures.append(texture)
}
public func AddProcessor(filter:AccImageFilter){
self.filter = filter
}
public func Processing(){
self.commandQueue.addAccCommand((self.filter!.pipelineState!), textures: textures, factors: self.filter!.getFactors())
}
public func Output()->UIImage{
let image = textures[0].toImage()
return image
}
}
|
eb09ae86771f7e1e071325c25f67edfa
| 24.45 | 126 | 0.649312 | false | false | false | false |
snazzware/HexMatch
|
refs/heads/master
|
HexMatch/Scenes/LevelScene.swift
|
gpl-3.0
|
2
|
//
// LevelScene.swift
// HexMatch
//
// Created by Josh McKee on 1/28/16.
// Copyright © 2016 Josh McKee. All rights reserved.
//
import SpriteKit
import SNZSpriteKitUI
class LevelScene: SNZScene {
var checkboxMobilePieces: SNZCheckButtonWidget?
var checkboxEnemyPieces: SNZCheckButtonWidget?
var checkboxSoundEffects: SNZCheckButtonWidget?
override func didMove(to view: SKView) {
super.didMove(to: view)
self.updateGui()
}
func updateGui() {
self.removeAllChildren()
self.widgets.removeAll()
// Set background
self.backgroundColor = UIColor(red: 0x69/255, green: 0x65/255, blue: 0x6f/255, alpha: 1.0)
// Create primary header
let header = SNZSceneHeaderWidget()
header.caption = "Menu"
self.addWidget(header)
// Add copyright
let copyrightLabel = SKLabelNode(fontNamed: "Avenir-Black")
copyrightLabel.text = "Mergel ©2016 Josh M. McKee"
copyrightLabel.fontColor = UIColor.white
copyrightLabel.fontSize = 12
copyrightLabel.horizontalAlignmentMode = .center
copyrightLabel.verticalAlignmentMode = .center
copyrightLabel.position = CGPoint(x: self.size.width / 2, y: 8)
copyrightLabel.ignoreTouches = true
self.addChild(copyrightLabel)
var verticalOffset:CGFloat = self.frame.height - 60
// Create and position option buttons
let horizontalOffset:CGFloat = self.frame.width < 500 ? 20 : 300
verticalOffset = self.frame.width < 500 ? verticalOffset - 60 : self.frame.height - 120
self.checkboxSoundEffects = MergelCheckButtonWidget(parentNode: self)
self.checkboxSoundEffects!.isChecked = GameState.instance!.getIntForKey("enable_sound_effects", 1) == 1
self.checkboxSoundEffects!.caption = "Sound Effects"
self.checkboxSoundEffects!.position = CGPoint(x: horizontalOffset,y: verticalOffset)
self.addWidget(self.checkboxSoundEffects!)
/*self.checkboxMobilePieces = MergelCheckButtonWidget(parentNode: self)
self.checkboxMobilePieces!.isChecked = GameState.instance!.getIntForKey("include_mobile_pieces", 1) == 1
self.checkboxMobilePieces!.caption = "Moving Shapes"
self.checkboxMobilePieces!.position = CGPointMake(horizontalOffset,verticalOffset)
self.addWidget(self.checkboxMobilePieces!)*/
verticalOffset -= 120
/*self.checkboxEnemyPieces = MergelCheckButtonWidget(parentNode: self)
self.checkboxEnemyPieces!.isChecked = GameState.instance!.getIntForKey("include_enemy_pieces", 1) == 1
self.checkboxEnemyPieces!.caption = "Vanilla Gel"
self.checkboxEnemyPieces!.position = CGPointMake(horizontalOffset,verticalOffset)
self.addWidget(self.checkboxEnemyPieces!)*/
// Add the New Game button
let newGameButton = MergelButtonWidget(parentNode: self)
newGameButton.position = CGPoint(x: horizontalOffset,y: verticalOffset)
newGameButton.caption = "New Game"
newGameButton.bind("tap",{
self.view?.presentScene(SceneHelper.instance.newGameScene, transition: SKTransition.push(with: SKTransitionDirection.up, duration: 0.4))
});
self.addWidget(newGameButton)
verticalOffset -= 60
// Add the Help button
let helpButton = MergelButtonWidget(parentNode: self)
helpButton.position = CGPoint(x: horizontalOffset,y: verticalOffset)
helpButton.caption = "How to Play"
helpButton.bind("tap",{
UIApplication.shared.openURL(URL(string:"https://github.com/snazzware/Mergel/blob/master/HELP.md")!)
});
self.addWidget(helpButton)
verticalOffset -= 60
// Add the About button
let aboutButton = MergelButtonWidget(parentNode: self)
aboutButton.position = CGPoint(x: horizontalOffset,y: verticalOffset)
aboutButton.caption = "About Mergel"
aboutButton.bind("tap",{
UIApplication.shared.openURL(URL(string:"https://github.com/snazzware/Mergel/blob/master/ABOUT.md")!)
});
self.addWidget(aboutButton)
verticalOffset -= 60
// Add the Issues button
let issuesButton = MergelButtonWidget(parentNode: self)
issuesButton.position = CGPoint(x: horizontalOffset,y: verticalOffset)
issuesButton.caption = "Bugs & Requests"
issuesButton.bind("tap",{
UIApplication.shared.openURL(URL(string:"https://github.com/snazzware/Mergel/issues")!)
});
self.addWidget(issuesButton)
// Add the close button
let closeButton = MergelButtonWidget(parentNode: self)
closeButton.anchorPoint = CGPoint(x: 0,y: 0)
closeButton.caption = "Back"
closeButton.bind("tap",{
self.captureSettings()
self.close()
});
self.addWidget(closeButton)
// Render the widgets
self.renderWidgets()
}
func captureSettings() {
//GameState.instance!.setIntForKey("include_mobile_pieces", self.checkboxMobilePieces!.isChecked ? 1 : 0 )
//GameState.instance!.setIntForKey("include_enemy_pieces", self.checkboxEnemyPieces!.isChecked ? 1 : 0 )
GameState.instance!.setIntForKey("enable_sound_effects", self.checkboxSoundEffects!.isChecked ? 1 : 0 )
if (GameState.instance!.getIntForKey("enable_sound_effects", 1) == 1) {
SoundHelper.instance.enableSoundEffects()
} else {
SoundHelper.instance.disableSoundEffects()
}
}
func close() {
self.view?.presentScene(SceneHelper.instance.gameScene, transition: SKTransition.push(with: SKTransitionDirection.down, duration: 0.4))
}
}
|
04967a82deca02952450fe88ebffef07
| 39.739726 | 148 | 0.652824 | false | false | false | false |
Sorix/CloudCore
|
refs/heads/master
|
Source/Classes/Setup Operation/SubscribeOperation.swift
|
mit
|
1
|
//
// SubscribeOperation.swift
// CloudCore
//
// Created by Vasily Ulianov on 12/12/2017.
// Copyright © 2017 Vasily Ulianov. All rights reserved.
//
import Foundation
import CloudKit
#if !os(watchOS)
@available(watchOS, unavailable)
class SubscribeOperation: AsynchronousOperation {
var errorBlock: ErrorBlock?
private let queue = OperationQueue()
override func main() {
super.main()
let container = CloudCore.config.container
// Subscribe operation
let subcribeToPrivate = self.makeRecordZoneSubscriptionOperation(for: container.privateCloudDatabase, id: CloudCore.config.subscriptionIDForPrivateDB)
// Fetch subscriptions and cancel subscription operation if subscription is already exists
let fetchPrivateSubscriptions = makeFetchSubscriptionOperation(for: container.privateCloudDatabase,
searchForSubscriptionID: CloudCore.config.subscriptionIDForPrivateDB,
operationToCancelIfSubcriptionExists: subcribeToPrivate)
subcribeToPrivate.addDependency(fetchPrivateSubscriptions)
// Finish operation
let finishOperation = BlockOperation {
self.state = .finished
}
finishOperation.addDependency(subcribeToPrivate)
finishOperation.addDependency(fetchPrivateSubscriptions)
queue.addOperations([subcribeToPrivate, fetchPrivateSubscriptions, finishOperation], waitUntilFinished: false)
}
private func makeRecordZoneSubscriptionOperation(for database: CKDatabase, id: String) -> CKModifySubscriptionsOperation {
let notificationInfo = CKNotificationInfo()
notificationInfo.shouldSendContentAvailable = true
let subscription = CKRecordZoneSubscription(zoneID: CloudCore.config.zoneID, subscriptionID: id)
subscription.notificationInfo = notificationInfo
let operation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: [])
operation.modifySubscriptionsCompletionBlock = {
if let error = $2 {
// Cancellation is not an error
if case CKError.operationCancelled = error { return }
self.errorBlock?(error)
}
}
operation.database = database
return operation
}
private func makeFetchSubscriptionOperation(for database: CKDatabase, searchForSubscriptionID subscriptionID: String, operationToCancelIfSubcriptionExists operationToCancel: CKModifySubscriptionsOperation) -> CKFetchSubscriptionsOperation {
let fetchSubscriptions = CKFetchSubscriptionsOperation(subscriptionIDs: [subscriptionID])
fetchSubscriptions.database = database
fetchSubscriptions.fetchSubscriptionCompletionBlock = { subscriptions, error in
// If no errors = subscription is found and we don't need to subscribe again
if error == nil {
operationToCancel.cancel()
}
}
return fetchSubscriptions
}
}
#endif
|
a9639a9a3cc2260d5eb2755b0556dec6
| 33.493827 | 241 | 0.78418 | false | false | false | false |
garygriswold/Bible.js
|
refs/heads/master
|
OBSOLETE/YourBible/plugins/com-shortsands-utility/src/ios/Utility/Sqlite3.swift
|
mit
|
1
|
//
// Sqlite3.swift
// Utility
//
// Created by Gary Griswold on 4/19/2019.
// Copyright © 2018 ShortSands. All rights reserved.
//
// Documentation of the sqlite3 C interface
// https://www.sqlite.org/cintro.html
//
import Foundation
import SQLite3
public enum Sqlite3Error: Error {
case databaseNotOpenError(name: String)
case directoryCreateError(name: String, srcError: Error)
case databaseNotFound(name: String)
case databaseNotInBundle(name: String)
case databaseCopyError(name: String, srcError: Error)
case databaseOpenError(name: String, sqliteError: String)
case databaseColBindError(value: Any)
case statementPrepareFailed(sql: String, sqliteError: String)
case statementExecuteFailed(sql: String, sqliteError: String)
}
public class Sqlite3 {
private static var openDatabases = Dictionary<String, Sqlite3>()
public static func findDB(dbname: String) throws -> Sqlite3 {
if let openDB: Sqlite3 = openDatabases[dbname] {
return openDB
} else {
throw Sqlite3Error.databaseNotOpenError(name: dbname)
}
}
public static func openDB(dbname: String, copyIfAbsent: Bool) throws -> Sqlite3 {
if let openDB: Sqlite3 = openDatabases[dbname] {
return openDB
} else {
let newDB = Sqlite3()
try newDB.open(dbname: dbname, copyIfAbsent: copyIfAbsent)
openDatabases[dbname] = newDB
return newDB
}
}
public static func closeDB(dbname: String) {
if let openDB: Sqlite3 = openDatabases[dbname] {
openDB.close()
openDatabases.removeValue(forKey: dbname)
}
}
public static func listDB() throws -> [String] {
var results = [String]()
let db = Sqlite3()
let files = try FileManager.default.contentsOfDirectory(atPath: db.databaseDir.path)
for file in files {
if file.hasSuffix(".db") {
results.append(file)
}
}
return results
}
public static func deleteDB(dbname: String) throws {
let db = Sqlite3()
let fullPath: URL = db.databaseDir.appendingPathComponent(dbname)
try FileManager.default.removeItem(at: fullPath)
}
private var databaseDir: URL
private var database: OpaquePointer?
public init() {
print("****** Init Sqlite3 ******")
let homeDir: URL = URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)
let libDir: URL = homeDir.appendingPathComponent("Library")
let dbDir: URL = libDir.appendingPathComponent("LocalDatabase")
self.databaseDir = dbDir
self.database = nil
}
// Could introduce alternate init that introduces different databaseDir
deinit {
print("****** Deinit Sqlite3 ******")
}
public var isOpen: Bool {
get {
return self.database != nil
}
}
public func open(dbname: String, copyIfAbsent: Bool) throws {
self.database = nil
let fullPath = try self.ensureDatabase(dbname: dbname, copyIfAbsent: copyIfAbsent)
var db: OpaquePointer? = nil
let result = sqlite3_open(fullPath.path, &db)
if result == SQLITE_OK {
print("Successfully opened connection to database at \(fullPath)")
self.database = db!
} else {
print("SQLITE Result Code = \(result)")
let openMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.databaseOpenError(name: dbname, sqliteError: openMsg)
}
}
/** This open method is used by command line or other programs that open the database at a
* specified path, not in the bundle.
*/
public func openLocal(dbname: String) throws {
self.database = nil
var db: OpaquePointer? = nil
let result = sqlite3_open(dbname, &db)
if result == SQLITE_OK {
print("Successfully opened connection to database at \(dbname)")
self.database = db!
} else {
print("SQLITE Result Code = \(result)")
let openMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.databaseOpenError(name: dbname, sqliteError: openMsg)
}
}
private func ensureDatabase(dbname: String, copyIfAbsent: Bool) throws -> URL {
let fullPath: URL = self.databaseDir.appendingPathComponent(dbname)
print("Opening Database at \(fullPath.path)")
if FileManager.default.isReadableFile(atPath: fullPath.path) {
return fullPath
} else if !copyIfAbsent {
try self.ensureDirectory()
return fullPath
} else {
print("Copy Bundle at \(dbname)")
try self.ensureDirectory()
let parts = dbname.split(separator: ".")
let name = String(parts[0])
let ext = String(parts[1])
let bundle = Bundle.main
print("bundle \(bundle.bundlePath)")
var bundlePath = bundle.url(forResource: name, withExtension: ext, subdirectory: "www")
if bundlePath == nil {
// This option is here only because I have not been able to get databases in www in my projects
bundlePath = bundle.url(forResource: name, withExtension: ext)
}
if bundlePath != nil {
do {
try FileManager.default.copyItem(at: bundlePath!, to: fullPath)
return fullPath
} catch let err {
throw Sqlite3Error.databaseCopyError(name: dbname, srcError: err)
}
} else {
throw Sqlite3Error.databaseNotInBundle(name: dbname)
}
}
}
private func ensureDirectory() throws {
let file = FileManager.default
if !file.fileExists(atPath: self.databaseDir.path) {
do {
try file.createDirectory(at: self.databaseDir, withIntermediateDirectories: true, attributes: nil)
} catch let err {
throw Sqlite3Error.directoryCreateError(name: self.databaseDir.path, srcError: err)
}
}
}
public func close() {
if database != nil {
sqlite3_close(database)
database = nil
}
}
/**
* This is the single statement execute
*/
public func executeV1(sql: String, values: [Any?]) throws -> Int {
if database != nil {
var statement: OpaquePointer? = nil
let prepareOut = sqlite3_prepare_v2(database, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
if prepareOut == SQLITE_OK {
try self.bindStatement(statement: statement!, values: values)
let stepOut = sqlite3_step(statement)
if stepOut == SQLITE_DONE {
let rowCount = Int(sqlite3_changes(database))
return rowCount
} else {
let execMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementExecuteFailed(sql: sql, sqliteError: execMsg)
}
} else {
let prepareMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementPrepareFailed(sql: sql, sqliteError: prepareMsg)
}
} else {
throw Sqlite3Error.databaseNotFound(name: "unknown")
}
}
/*
* This method executes an array of values against one prepared statement
*/
public func bulkExecuteV1(sql: String, values: [[Any?]]) throws -> Int {
var totalRowCount = 0
if database != nil {
var statement: OpaquePointer? = nil
let prepareOut = sqlite3_prepare_v2(database, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
if prepareOut == SQLITE_OK {
for row: [Any?] in values {
try self.bindStatement(statement: statement!, values: row)
if sqlite3_step(statement) == SQLITE_DONE {
let rowCount = Int(sqlite3_changes(database))
totalRowCount += rowCount
sqlite3_reset(statement);
} else {
let execMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementExecuteFailed(sql: sql, sqliteError: execMsg)
}
}
return totalRowCount
} else {
let prepareMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementPrepareFailed(sql: sql, sqliteError: prepareMsg)
}
} else {
throw Sqlite3Error.databaseNotFound(name: "unknown")
}
}
/**
* This one is written to conform to the query interface of the cordova sqlite plugin. It returns
* a JSON array that can be serialized and sent back to Javascript. It supports both String and Int
* results, because that is what are used in the current databases.
*/
public func queryJS(sql: String, values: [Any?]) throws -> Data {
let results: [Dictionary<String,Any?>] = try self.queryV0(sql: sql, values: values)
var message: Data
do {
message = try JSONSerialization.data(withJSONObject: results)
} catch let jsonError {
print("ERROR while converting resultSet to JSON \(jsonError)")
let errorMessage = "{\"Error\": \"Sqlite3.queryJS \(jsonError.localizedDescription)\"}"
message = errorMessage.data(using: String.Encoding.utf8)!
}
return message
}
/**
* This returns a classic sql result set as an array of dictionaries. It is probably not a good choice
* if a large number of rows are returned. It returns types: String, Int, Double, and nil because JSON
* will accept these types.
*/
public func queryV0(sql: String, values: [Any?]) throws -> [Dictionary<String,Any?>] {
if database != nil {
var resultSet = [Dictionary<String,Any?>]()
var statement: OpaquePointer? = nil
let prepareOut = sqlite3_prepare_v2(database, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
if prepareOut == SQLITE_OK {
try self.bindStatement(statement: statement!, values: values)
let colCount = Int(sqlite3_column_count(statement))
while (sqlite3_step(statement) == SQLITE_ROW) {
var row = Dictionary<String, Any?>()
for i in 0..<colCount {
let col = Int32(i)
let name = String(cString: sqlite3_column_name(statement, col))
let type: Int32 = sqlite3_column_type(statement, col)
switch type {
case 1: // INT
row[name] = Int(sqlite3_column_int(statement, col))
break
case 2: // Double
row[name] = sqlite3_column_double(statement, col)
break
case 3: // TEXT
row[name] = String(cString: sqlite3_column_text(statement, col))
break
case 5: // NULL
row[name] = nil
break
default:
row[name] = String(cString: sqlite3_column_text(statement, col))
break
}
}
resultSet.append(row)
}
return resultSet
} else {
let prepareMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementPrepareFailed(sql: sql, sqliteError: prepareMsg)
}
} else {
throw Sqlite3Error.databaseNotFound(name: "unknown")
}
}
/**
* This execute accepts only strings on the understanding that sqlite will convert data into the type
* that is correct based on the affinity of the type in the database.
*
* Also, this query method returns a resultset that is an array of an array of Strings.
*/
public func queryV1(sql: String, values: [Any?]) throws -> [[String?]] {
if database != nil {
var resultSet: [[String?]] = []
var statement: OpaquePointer? = nil
let prepareOut = sqlite3_prepare_v2(database, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
if prepareOut == SQLITE_OK {
try self.bindStatement(statement: statement!, values: values)
let colCount = Int(sqlite3_column_count(statement))
while (sqlite3_step(statement) == SQLITE_ROW) {
var row: [String?] = [String?] (repeating: nil, count: colCount)
for i in 0..<colCount {
if let cValue = sqlite3_column_text(statement, Int32(i)) {
row[i] = String(cString: cValue)
} else {
row[i] = nil
}
}
resultSet.append(row)
}
return resultSet
} else {
let prepareMsg = String.init(cString: sqlite3_errmsg(database))
throw Sqlite3Error.statementPrepareFailed(sql: sql, sqliteError: prepareMsg)
}
} else {
throw Sqlite3Error.databaseNotFound(name: "unknown")
}
}
private func bindStatement(statement: OpaquePointer, values: [Any?]) throws {
for i in 0..<values.count {
let col = Int32(i + 1)
let value = values[i];
if value is String {
sqlite3_bind_text(statement, col, (value as! NSString).utf8String, -1, nil)
} else if value is Int {
sqlite3_bind_int(statement, col, Int32(value as! Int))
} else if value is Double {
sqlite3_bind_double(statement, col, (value as! Double))
} else if value == nil {
sqlite3_bind_null(statement, col)
} else {
throw Sqlite3Error.databaseColBindError(value: value!)
}
}
}
public static func errorDescription(error: Error) -> String {
if error is Sqlite3Error {
switch error {
case Sqlite3Error.databaseNotOpenError(let name) :
return "DatabaseNotOpen: \(name)"
case Sqlite3Error.directoryCreateError(let name, let srcError) :
return "DirectoryCreateError \(srcError) at \(name)"
case Sqlite3Error.databaseNotFound(let name) :
return "DatabaseNotFound: \(name)"
case Sqlite3Error.databaseNotInBundle(let name) :
return "DatabaseNotInBundle: \(name)"
case Sqlite3Error.databaseCopyError(let name, let srcError) :
return "DatabaseCopyError: \(srcError.localizedDescription) \(name)"
case Sqlite3Error.databaseOpenError(let name, let sqliteError) :
return "SqliteOpenError: \(sqliteError) on database: \(name)"
case Sqlite3Error.databaseColBindError(let value) :
return "DatabaseBindError: value: \(value)"
case Sqlite3Error.statementPrepareFailed(let sql, let sqliteError) :
return "StatementPrepareFailed: \(sqliteError) on stmt: \(sql)"
case Sqlite3Error.statementExecuteFailed(let sql, let sqliteError) :
return "StatementExecuteFailed: \(sqliteError) on stmt: \(sql)"
default:
return "Unknown Sqlite3Error"
}
} else {
return "Unknown Error Type"
}
}
}
/*
One person's recommendation to make sqlite threadsafe.
+(sqlite3*) getInstance {
if (instance == NULL) {
sqlite3_shutdown();
sqlite3_config(SQLITE_CONFIG_SERIALIZED);
sqlite3_initialize();
NSLog(@"isThreadSafe %d", sqlite3_threadsafe());
const char *path = [@"./path/to/db/db.sqlite" cStringUsingEncoding:NSUTF8StringEncoding];
if (sqlite3_open_v2(path, &database, SQLITE_OPEN_READWRITE|SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) {
NSLog(@"Database opening failed!");
}
}
return instance;
}
*/
|
d4785a1d93eb32c3a63c8fc617d1a9e7
| 39.929612 | 114 | 0.565736 | false | false | false | false |
necrowman/CRLAlamofireFuture
|
refs/heads/master
|
Examples/SimpleIOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleIOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Tests/CRLAlamofireFuture/SimpleTest.swift
|
mit
|
18
|
//
// CRLAlamofireFuture_iOSTests.swift
// CRLAlamofireFuture iOSTests
//
// Created by Ruslan Yupyn on 7/4/16.
//
//
import XCTest
import Alamofire
import Future
import CRLAlamofireFuture
class CRLAlamofireFuture_iOSTests: XCTestCase {
let correctURLBase = "https://raw.githubusercontent.com/necrowman/CRLAlomofireFeature/master/"
let uncorrectURLBase = "https://raw.githubusercontent12.com/necrowman/CRLAlomofireFeature/master/"
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()
}
//MARK: - responseString() -> Future<String> testing
func testSimpleString() {
let asyncExpectation = expectationWithDescription("AlamofireResponseString")
let urlString = "\(correctURLBase)simpleTestURL.txt"
let future = Alamofire.request(.GET, urlString).responseString()
future.onSuccess { value in
print("RESULT VALUE -> ", value)
XCTAssertEqual(value, "Test String")
asyncExpectation.fulfill()
}
future.onFailure { error in
print("ERROR VALUE -> ", error)
XCTFail("Whoops, error \(error)")
asyncExpectation.fulfill()
}
self.waitForExpectationsWithTimeout(5) { error in
XCTAssertNil(error)
}
}
func testExample() {
XCTAssertEqual(CRLAlamofireFuture.instance.frameworkFunctionExample(), "This is test framework function example")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
|
b3ea06b2418edf2b91938a3e7231a60e
| 31.016393 | 121 | 0.645161 | false | true | false | false |
Xiomara7/Apps
|
refs/heads/master
|
Apps/AppDetailsController.swift
|
mit
|
1
|
//
// AppDetailsController.swift
// Apps
//
// Created by Xiomara on 2/14/17.
// Copyright © 2017 Xiomara. All rights reserved.
//
import UIKit
class AppDetailsController: UIViewController {
var appShown: App!
@IBOutlet weak var circle: UIImageView!
@IBOutlet weak var appImageView: UIImageView!
@IBOutlet weak var appSummary: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
appImageView.layer.borderColor = UIColor.white.cgColor
appImageView.layer.borderWidth = 1.0
appImageView.layer.cornerRadius = 15.0
appImageView.layer.masksToBounds = true
UIView.animate(withDuration: 1.5, animations: {
let scaleTransform = CGAffineTransform(scaleX: 0.5, y: 0.5)
self.circle.transform = scaleTransform
self.circle.frame.origin.y = 64.0
self.appImageView.setImageWith(URL(string: self.appShown.imageURL)!)
self.appImageView.center = self.circle.center
}, completion: { (finished: Bool) in
self.appSummary.isHidden = false
self.appSummary.text = self.appShown.summary
})
}
@IBAction func onCloseButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
|
f74b8455efae30cbc8d77cbc99ad08d9
| 29.627907 | 80 | 0.634017 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
refs/heads/develop
|
Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/BackgroundStyleSelectionTableViewCell.swift
|
apache-2.0
|
3
|
//
// ScreenBackgroundStyleSelectionTableViewCell.swift
// SwiftEntryKit_Example
//
// Created by Daniel Huri on 4/25/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import SwiftEntryKit
class BackgroundStyleSelectionTableViewCell: SelectionTableViewCell {
private var focus: Focus = .entry
private var backgroundStyle: EKAttributes.BackgroundStyle {
get {
switch focus {
case .entry:
return attributesWrapper.attributes.entryBackground
case .screen:
return attributesWrapper.attributes.screenBackground
}
}
set {
switch focus {
case .entry:
attributesWrapper.attributes.entryBackground = newValue
case .screen:
attributesWrapper.attributes.screenBackground = newValue
}
}
}
func configure(attributesWrapper: EntryAttributeWrapper, focus: Focus) {
self.focus = focus
configure(attributesWrapper: attributesWrapper)
}
override func configure(attributesWrapper: EntryAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "\(focus.rawValue.capitalized) Background Style"
descriptionValue = "The style of the \(focus.rawValue)'s background can be one of the following options"
insertSegments(by: ["Clear", "Blur", "Gradient", "Color"])
selectSegment()
}
private func selectSegment() {
switch backgroundStyle {
case .clear:
segmentedControl.selectedSegmentIndex = 0
case .visualEffect(style: _):
segmentedControl.selectedSegmentIndex = 1
case .gradient(gradient: _):
segmentedControl.selectedSegmentIndex = 2
case .color(color: _):
segmentedControl.selectedSegmentIndex = 3
default:
// TODO: Image isn't handled yet
break
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
backgroundStyle = .clear
case 1:
backgroundStyle = .visualEffect(style: .light)
case 2:
let gradient = EKAttributes.BackgroundStyle.Gradient(colors: [EKColor.BlueGray.c100, EKColor.BlueGray.c300], startPoint: .zero, endPoint: CGPoint(x: 1, y: 1))
backgroundStyle = .gradient(gradient: gradient)
case 3:
let color: UIColor
switch focus {
case .entry:
color = .amber
case .screen:
color = UIColor.black.withAlphaComponent(0.5)
}
backgroundStyle = .color(color: color)
default:
break
}
}
}
|
7a38d398d215a6338f6a37a307ffd939
| 31.443182 | 170 | 0.602102 | false | false | false | false |
git-hushuai/MOMO
|
refs/heads/master
|
MMHSMeterialProject/UINavigationController/BusinessFile/简历库Item/TKOptimizeResumeBaseController.swift
|
mit
|
1
|
//
// TKOptimizeResumeBaseController.swift
// MMHSMeterialProject
//
// Created by hushuaike on 16/4/12.
// Copyright © 2016年 hushuaike. All rights reserved.
//
import UIKit
class TKOptimizeResumeBaseController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var TKTableView = UITableView.init(frame: CGRectZero, style: UITableViewStyle.Plain);
var dataSourceLists = NSMutableArray();
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0);
self.setUpUI();
self.performSelectorInBackground(Selector.init("loadLocalOptimizeResumeBaseInfo"), withObject: self);
}
func loadLocalOptimizeResumeBaseInfo(){
// 将本地数据取出
let dbCacheModel = TKResumeDataCacheTool();
let nowDate = NSDate.init();
let timeInterval = nowDate.timeIntervalSince1970;
let timeIntervalStr = String.init(format: "%i", Int(timeInterval) - 1);
let localResumeLists = dbCacheModel.loadLocalAllResumeInfoWithResumeCateInfo("简历库优选", timeStampInfo: timeIntervalStr);
print("localoptimizebaseResume lists info :\(localResumeLists)");
let itemModelLists : NSArray = TKJobItemModel.parses(arr: localResumeLists) as! [TKJobItemModel];
print("optimizebasefirst item Model lists:\(itemModelLists)");
self.dataSourceLists.removeAllObjects();
self.dataSourceLists.addObjectsFromArray(itemModelLists as [AnyObject]);
self.TKTableView.reloadData();
}
func setUpUI(){
self.view.addSubview(self.TKTableView);
self.TKTableView.sd_layout().spaceToSuperView(UIEdgeInsetsMake(0, 0, 50, 0));
self.TKTableView.tableFooterView = UIView.init();
self.TKTableView.separatorStyle = .None;
self.TKTableView.backgroundColor = RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0);
self.TKTableView.delegate = self;
self.TKTableView.dataSource = self;
self.TKTableView.registerClass(ClassFromString("TKOptimizeCell"), forCellReuseIdentifier: "TKOptimizeCell");
let loadingView = DGElasticPullToRefreshLoadingViewCircle()
loadingView.tintColor = UIColor(red: 78/255.0, green: 221/255.0, blue: 200/255.0, alpha: 1.0)
self.TKTableView.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in
self?.loadNewResumeItemInfo();
}, loadingView: loadingView)
self.TKTableView.dg_setPullToRefreshFillColor(UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0))
self.TKTableView.dg_setPullToRefreshBackgroundColor(RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0));
self.TKTableView.addFootRefresh(self, action: "loadMoreResumeItemInfo")
}
// MARK: 加载最新数据
func loadNewResumeItemInfo(){
self.pullRequestLoadingResumeInfoWithParam(true);
}
// MARK: 加载历史数据
func loadMoreResumeItemInfo(){
self.pullRequestLoadingResumeInfoWithParam(false);
}
// MARK: 发起网络请求
func pullRequestLoadingResumeInfoWithParam(isfresh:Bool){
let reqDict = NSMutableDictionary();
if isfresh == true{
reqDict.setValue("0", forKey: "lastTime")
}else{
if self.dataSourceLists.count > 0{
let resuemModel = self.dataSourceLists.lastObject as! TKJobItemModel;
reqDict.setValue(resuemModel.ts, forKey: "lastTime")
}else{
// reqDict.setValue("0", forKey: "lastTime");
}
}
GNNetworkCenter.userLoadResumeItemBaseInfoWithReqObject(reqDict, andFunName: KAppUserLoadResumeBaseInfoFunc) { (response : YWResponse!) -> Void in
print("resume base info :response:\(response)---data:\(response.data)");
if (Int(response.retCode) == ERROR_NOERROR){
let responseDict:Dictionary<String,AnyObject> = response.data as! Dictionary;
let keyValueArr = responseDict.keys;
if keyValueArr.contains("data") == true{
let itemArr : NSArray = responseDict["data"]! as! NSArray;
print("order job item array :\(itemArr)");
if itemArr.count > 0{
if isfresh==true{self.clearLocalResumeInfo();}
let itemModel : NSArray = TKJobItemModel.parses(arr: itemArr) as! [TKJobItemModel];
for i in 0...(itemModel.count-1){
let dict = itemModel[i] as! TKJobItemModel;
dict.cellItemInfo = "简历库优选";
print("dict cell item info :\(dict)");
let dbItem = TKResumeDataCacheTool();
// 先判断本地是否有该条记录
let job_id = String.init(format: "%@", dict.id);
let cellItemCateInfo = dict.cellItemInfo;
let queryData = dbItem.checkResumeItemIsAlreadySaveInLocal(job_id, resumeItemInfo: cellItemCateInfo);
print("queryData inf0 :\(queryData)");
if(queryData.count > 0){
print("本地已经有该条记录");
}else{
// 本地没有该条数据需要缓存
dbItem.setDBItemInfoWithResumeModel(dict);
dbItem.save();
}
}
// 展示数据
print("item model info:\(itemModel)");
self.showItemInfoWithArray(itemModel,isfresh:isfresh);
}
}else{
print("数据加载出错");
let errorInfo = response.msg;
SVProgressHUD.showErrorWithStatus(String.init(format: "%@", errorInfo));
dispatch_after(UInt64(1.5), dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss();
});
self.stopWithParamIsFresh(isfresh);
}
}else{
self.stopWithParamIsFresh(isfresh);
}
}
}
func showItemInfoWithArray(itemArr : NSArray,isfresh:Bool){
if isfresh == true{
print("current THREADinfo:\(NSThread.currentThread())");
self.dataSourceLists.removeAllObjects();
self.dataSourceLists.addObjectsFromArray(itemArr as [AnyObject]);
print("self dataSourceList info:\(self.dataSourceLists)");
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.reloadData();
self.TKTableView.tableHeadStopRefreshing();
self.TKTableView.dg_stopLoading();
})
}else{
self.dataSourceLists.addObjectsFromArray(itemArr as [AnyObject]);
if itemArr.count >= 20{
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.tableFootStopRefreshing();
self.TKTableView.reloadData();
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.tableFootShowNomore();
self.TKTableView.reloadData();
});
})
}
}
}
//MARK: 将本地数据清空
func clearLocalResumeInfo(){
let cityInfo = self.getUserSelectCityName();
let deleDBModel = TKResumeDataCacheTool();
deleDBModel.clearTableResumeInfoWithParms("简历库优选", cityCateInfo: cityInfo)
// 加载数据成功之后将本地数据清空
}
// MARK: 返回用户选择的城市信息
func getUserSelectCityName()->String{
var cityInfo = NSUserDefaults.standardUserDefaults().stringForKey("kUserDidSelectCityInfoKey");
if( cityInfo == nil) {
cityInfo = "广州";
}
return cityInfo as String!;
}
// MARK: 停止刷新
func stopWithParamIsFresh(isfresh:Bool){
if isfresh == true{
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.dg_stopLoading();
self.TKTableView.tableHeadStopRefreshing();
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.tableFootShowNomore();
self.TKTableView.reloadData();
});
})
}
}
// MARK: rgb color
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) }
// MARK: tableview delegate 和 datasource 方法
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
print("dataSourceList count :\(self.dataSourceLists.count)");
self.TKTableView.foot?.hidden = self.dataSourceLists.count > 0 ? false : true;
self.TKTableView.foot?.userInteractionEnabled = self.dataSourceLists.count > 0 ? true : false;
return self.dataSourceLists.count;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10.0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headView = UIView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 10.0));
headView.backgroundColor = UIColor.clearColor();
return headView;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TKOptimizeCell") as? TKOptimizeCell;
let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section);
cell!.resumeModel = resumeModel as? TKJobItemModel;
cell!.sd_tableView = tableView;
cell!.sd_indexPath = indexPath;
return cell!;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section);
return self.TKTableView.cellHeightForIndexPath(indexPath,model: resumeModel, keyPath:"resumeModel", cellClass: ClassFromString("TKOptimizeCell"), contentViewWidth:UIScreen.mainScreen().bounds.size.width);
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true);
print("indexPath info:\(indexPath)");
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
// 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.
}
*/
}
|
b34792e934a61c26cf1796af999406f2
| 39.456835 | 212 | 0.611897 | false | false | false | false |
netguru/inbbbox-ios
|
refs/heads/develop
|
Inbbbox/Source Files/ViewModels/LikesViewModel.swift
|
gpl-3.0
|
1
|
//
// LikesViewModel.swift
// Inbbbox
//
// Created by Aleksander Popko on 29.02.2016.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import PromiseKit
class LikesViewModel: SimpleShotsViewModel {
weak var delegate: BaseCollectionViewViewModelDelegate?
let title = Localized("LikesViewModel.Title", comment:"Title of Likes screen")
var shots = [ShotType]()
fileprivate let shotsProvider = ShotsProvider()
fileprivate var userMode: UserMode
var itemsCount: Int {
return shots.count
}
init() {
userMode = UserStorage.isUserSignedIn ? .loggedUser : .demoUser
}
func downloadInitialItems() {
firstly {
shotsProvider.provideMyLikedShots()
}.then { shots -> Void in
if let shots = shots?.map({ $0.shot }), shots != self.shots || shots.count == 0 {
self.shots = shots
self.delegate?.viewModelDidLoadInitialItems()
}
}.catch { error in
self.delegate?.viewModelDidFailToLoadInitialItems(error)
}
}
func downloadItemsForNextPage() {
guard UserStorage.isUserSignedIn else {
return
}
firstly {
shotsProvider.nextPageForLikedShots()
}.then { shots -> Void in
if let shots = shots?.map({ $0.shot }), shots.count > 0 {
let indexes = shots.enumerated().map { index, _ in
return index + self.shots.count
}
self.shots.append(contentsOf: shots)
let indexPaths = indexes.map {
IndexPath(row:($0), section: 0)
}
self.delegate?.viewModel(self, didLoadItemsAtIndexPaths: indexPaths)
}
}.catch { error in
self.notifyDelegateAboutFailure(error)
}
}
func downloadItem(at index: Int) { /* empty */ }
func emptyCollectionDescriptionAttributes() -> EmptyCollectionViewDescription {
let description = EmptyCollectionViewDescription(
firstLocalizedString: Localized("LikesCollectionView.EmptyData.FirstLocalizedString",
comment: "LikesCollectionView, empty data set view"),
attachmentImageName: "ic-like-emptystate",
imageOffset: CGPoint(x: 0, y: -2),
lastLocalizedString: Localized("LikesCollectionView.EmptyData.LastLocalizedString",
comment: "LikesCollectionView, empty data set view")
)
return description
}
func shotCollectionViewCellViewData(_ indexPath: IndexPath) -> (shotImage: ShotImageType, animated: Bool) {
let shotImage = shots[indexPath.row].shotImage
let animated = shots[indexPath.row].animated
return (shotImage, animated)
}
func clearViewModelIfNeeded() {
let currentUserMode = UserStorage.isUserSignedIn ? UserMode.loggedUser : .demoUser
if userMode != currentUserMode {
shots = []
userMode = currentUserMode
delegate?.viewModelDidLoadInitialItems()
}
}
}
|
86e371623a2f35a893ea9928bdf3c8ea
| 33.163043 | 111 | 0.610881 | false | false | false | false |
alecgorge/AGAudioPlayer
|
refs/heads/master
|
AGAudioPlayer/UI/AGAudioPlayerViewController.swift
|
mit
|
1
|
//
// AGAudioPlayerViewController.swift
// AGAudioPlayer
//
// Created by Alec Gorge on 1/19/17.
// Copyright © 2017 Alec Gorge. All rights reserved.
//
import UIKit
import QuartzCore
import MediaPlayer
import Interpolate
import MarqueeLabel
import NapySlider
public struct AGAudioPlayerColors {
let main: UIColor
let accent: UIColor
let accentWeak: UIColor
let barNothing: UIColor
let barDownloads: UIColor
let barPlaybackElapsed: UIColor
let scrubberHandle: UIColor
public init() {
let main = UIColor(red:0.149, green:0.608, blue:0.737, alpha:1)
let accent = UIColor.white
self.init(main: main, accent: accent)
}
public init(main: UIColor, accent: UIColor) {
self.main = main
self.accent = accent
accentWeak = accent.withAlphaComponent(0.7)
barNothing = accent.withAlphaComponent(0.3)
barDownloads = accent.withAlphaComponent(0.4)
barPlaybackElapsed = accent
scrubberHandle = accent
}
}
@objc public class AGAudioPlayerViewController: UIViewController {
@IBOutlet var uiPanGestureClose: VerticalPanDirectionGestureRecognizer!
@IBOutlet var uiPanGestureOpen: VerticalPanDirectionGestureRecognizer!
@IBOutlet weak var uiTable: UITableView!
@IBOutlet weak var uiHeaderView: UIView!
@IBOutlet weak var uiFooterView: UIView!
@IBOutlet weak var uiProgressDownload: UIView!
@IBOutlet weak var uiProgressDownloadCompleted: UIView!
@IBOutlet weak var uiScrubber: ScrubberBar!
@IBOutlet weak var uiProgressDownloadCompletedContraint: NSLayoutConstraint!
@IBOutlet weak var uiLabelTitle: MarqueeLabel!
@IBOutlet weak var uiLabelSubtitle: MarqueeLabel!
@IBOutlet weak var uiLabelElapsed: UILabel!
@IBOutlet weak var uiLabelDuration: UILabel!
@IBOutlet weak var uiButtonShuffle: UIButton!
@IBOutlet weak var uiButtonPrevious: UIButton!
@IBOutlet weak var uiButtonPlay: UIButton!
@IBOutlet weak var uiButtonPause: UIButton!
@IBOutlet weak var uiButtonNext: UIButton!
@IBOutlet weak var uiButtonLoop: UIButton!
@IBOutlet weak var uiButtonDots: UIButton!
@IBOutlet weak var uiButtonPlus: UIButton!
@IBOutlet weak var uiSliderVolume: MPVolumeView!
@IBOutlet weak var uiSpinnerBuffering: UIActivityIndicatorView!
@IBOutlet weak var uiButtonStack: UIStackView!
@IBOutlet weak var uiWrapperEq: UIView!
@IBOutlet weak var uiSliderEqBass: NapySlider!
@IBOutlet weak var uiConstraintTopTitleSpace: NSLayoutConstraint!
@IBOutlet weak var uiConstraintSpaceBetweenPlayers: NSLayoutConstraint!
@IBOutlet weak var uiConstraintBottomBarHeight: NSLayoutConstraint!
// mini player
@IBOutlet weak var uiMiniPlayerContainerView: UIView!
public var barHeight : CGFloat {
get {
if let c = uiMiniPlayerContainerView {
let extra: CGFloat = UIApplication.shared.keyWindow!.rootViewController!.view.safeAreaInsets.bottom
return c.bounds.height + extra
}
return 64.0
}
}
@IBOutlet weak var uiMiniPlayerTopOffsetConstraint: NSLayoutConstraint!
@IBOutlet weak var uiMiniProgressDownloadCompletedView: UIView!
@IBOutlet weak var uiMiniProgressDownloadCompletedConstraint: NSLayoutConstraint!
@IBOutlet weak var uiMiniProgressPlayback: UIProgressView!
@IBOutlet weak var uiMiniButtonPlay: UIButton!
@IBOutlet weak var uiMiniButtonPause: UIButton!
@IBOutlet weak var uiMiniLabelTitle: MarqueeLabel!
@IBOutlet weak var uiMiniLabelSubtitle: MarqueeLabel!
@IBOutlet weak var uiMiniButtonStack: UIStackView!
@IBOutlet public weak var uiMiniButtonDots: UIButton!
@IBOutlet weak var uiMiniButtonPlus: UIButton!
@IBOutlet weak var uiMiniSpinnerBuffering: UIActivityIndicatorView!
// end mini player
public var presentationDelegate: AGAudioPlayerViewControllerPresentationDelegate? = nil
public var cellDataSource: AGAudioPlayerViewControllerCellDataSource? = nil
public var delegate: AGAudioPlayerViewControllerDelegate? = nil
public var shouldPublishToNowPlayingCenter: Bool = true
var remoteCommandManager : RemoteCommandManager? = nil
var dismissInteractor: DismissInteractor = DismissInteractor()
var openInteractor: OpenInteractor = OpenInteractor()
// colors
var colors = AGAudioPlayerColors()
// constants
let SectionQueue = 0
// bouncy header
var headerInterpolate: Interpolate?
var interpolateBlock: ((_ scale: Double) -> Void)?
// swipe to dismiss
static let defaultTransitionDelegate = AGAudioPlayerViewControllerTransitioningDelegate()
// non-jumpy seeking
var isCurrentlyScrubbing = false
// for delegate notifications
var lastSeenProgress: Float? = nil
let player: AGAudioPlayer
@objc required public init(player: AGAudioPlayer) {
self.player = player
let bundle = Bundle(path: Bundle(for: AGAudioPlayerViewController.self).path(forResource: "AGAudioPlayer", ofType: "bundle")!)
super.init(nibName: String(describing: AGAudioPlayerViewController.self), bundle: bundle)
self.transitioningDelegate = AGAudioPlayerViewController.defaultTransitionDelegate
setupPlayer()
dismissInteractor.viewController = self
openInteractor.viewController = self
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
uiMiniButtonStack.removeArrangedSubview(uiMiniButtonPlus)
uiMiniButtonPlus.isHidden = true
uiButtonPlus.alpha = 0.0
setupTable()
setupStretchyHeader()
setupColors()
setupPlayerUiActions()
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewWillAppear_StretchyHeader()
viewWillAppear_Table()
updateUI()
uiSliderVolume.isHidden = false
}
public override func viewDidDisappear(_ animated: Bool) {
uiSliderVolume.isHidden = true
}
}
extension AGAudioPlayerViewController : UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let pt = touch.location(in: uiHeaderView)
return uiHeaderView.frame.contains(pt);
}
}
extension AGAudioPlayerViewController : AGAudioPlayerDelegate {
func setupPlayer() {
player.delegate = self
player.prepareAudioSession()
publishToNowPlayingCenter()
}
public func audioPlayerAudioSessionSetUp(_ audioPlayer: AGAudioPlayer) {
remoteCommandManager = RemoteCommandManager(player: audioPlayer)
remoteCommandManager?.activatePlaybackCommands(true)
}
func updateUI() {
updatePlayPauseButtons()
updateShuffleLoopButtons()
updateNonTimeLabels()
updateTimeLabels()
updatePlaybackProgress()
updatePreviousNextButtons()
}
func updatePlayPauseButtons() {
guard uiButtonPause != nil, uiButtonPlay != nil,
uiMiniButtonPause != nil, uiMiniButtonPlay != nil,
uiSpinnerBuffering != nil, uiMiniSpinnerBuffering != nil else {
return
}
if player.isBuffering {
uiButtonPause.isHidden = true
uiButtonPlay.isHidden = true
uiMiniButtonPause.isHidden = true
uiMiniButtonPlay.isHidden = true
uiMiniSpinnerBuffering.isHidden = false
uiSpinnerBuffering.isHidden = false
return
}
uiMiniSpinnerBuffering.isHidden = true
uiSpinnerBuffering.isHidden = true
uiButtonPause.isHidden = !player.isPlaying && !player.isBuffering
uiButtonPlay.isHidden = player.isPlaying
uiMiniButtonPause.isHidden = uiButtonPause.isHidden
uiMiniButtonPlay.isHidden = uiButtonPlay.isHidden
}
func updatePreviousNextButtons() {
guard uiButtonPrevious != nil, uiButtonNext != nil else {
return
}
uiButtonPrevious.isEnabled = !player.isPlayingFirstItem
uiButtonNext.isEnabled = !player.isPlayingLastItem
}
func updateShuffleLoopButtons() {
guard uiButtonShuffle != nil, uiButtonLoop != nil else {
return
}
uiButtonLoop.alpha = player.loopItem ? 1.0 : 0.7
uiButtonShuffle.alpha = player.shuffle ? 1.0 : 0.7
}
func updateNonTimeLabels() {
guard uiLabelTitle != nil, uiLabelSubtitle != nil, uiMiniLabelTitle != nil, uiLabelSubtitle != nil else {
return
}
if let cur = player.currentItem {
uiLabelTitle.text = cur.displayText
uiLabelSubtitle.text = cur.displaySubtext
uiMiniLabelTitle.text = cur.displayText
uiMiniLabelSubtitle.text = cur.displaySubtext
}
else {
uiLabelTitle.text = " "
uiLabelSubtitle.text = " "
uiMiniLabelTitle.text = " "
uiMiniLabelSubtitle.text = " "
}
}
func updateTimeLabels() {
guard uiLabelElapsed != nil, uiLabelDuration != nil else {
return
}
if player.duration == 0.0 {
uiLabelElapsed.text = " "
uiLabelDuration.text = " "
}
else {
uiLabelElapsed.text = player.elapsed.formatted()
uiLabelDuration.text = player.duration.formatted()
}
}
func updatePlaybackProgress() {
guard uiScrubber != nil, uiMiniProgressPlayback != nil else {
return
}
if !isCurrentlyScrubbing {
let floatProgress = Float(player.percentElapsed)
uiScrubber.setProgress(progress: floatProgress)
uiMiniProgressPlayback.progress = floatProgress
updateTimeLabels()
// send this delegate once when it goes past 50%
if let lastProgress = lastSeenProgress, lastProgress < 0.5, floatProgress >= 0.5, let item = player.currentItem {
delegate?.audioPlayerViewController(self, passedHalfWayFor: item)
}
lastSeenProgress = floatProgress
}
}
func updateDownloadProgress(pct: Double) {
guard uiProgressDownloadCompletedContraint != nil, uiMiniProgressDownloadCompletedConstraint != nil else {
return
}
var p = pct
if p > 0.98 {
p = 1.0
}
uiProgressDownloadCompletedContraint = uiProgressDownloadCompletedContraint.setMultiplier(multiplier: CGFloat(p))
uiProgressDownload.layoutIfNeeded()
uiMiniProgressDownloadCompletedConstraint = uiMiniProgressDownloadCompletedConstraint.setMultiplier(multiplier: CGFloat(p))
uiMiniPlayerContainerView.layoutIfNeeded()
uiMiniProgressDownloadCompletedView.isHidden = p == 0.0
}
public func audioPlayer(_ audioPlayer: AGAudioPlayer, uiNeedsRedrawFor reason: AGAudioPlayerRedrawReason) {
publishToNowPlayingCenter()
switch reason {
case .buffering, .playing:
updatePlayPauseButtons()
delegate?.audioPlayerViewController(self, trackChangedState: player.currentItem)
uiTable.reloadData()
case .stopped:
uiLabelTitle.text = ""
uiLabelSubtitle.text = ""
uiMiniLabelTitle.text = ""
uiMiniLabelSubtitle.text = ""
fallthrough
case .paused, .error:
updatePlayPauseButtons()
delegate?.audioPlayerViewController(self, trackChangedState: player.currentItem)
uiTable.reloadData()
case .trackChanged:
updatePreviousNextButtons()
updateNonTimeLabels()
updateTimeLabels()
uiTable.reloadData()
delegate?.audioPlayerViewController(self, changedTrackTo: player.currentItem)
case .queueChanged:
uiTable.reloadData()
default:
break
}
self.scrollQueueToPlayingTrack()
}
public func audioPlayer(_ audioPlayer: AGAudioPlayer, errorRaised error: Error, for url: URL) {
print("CRAP")
print(error)
print(url)
publishToNowPlayingCenter()
}
public func audioPlayer(_ audioPlayer: AGAudioPlayer, downloadedBytesForActiveTrack downloadedBytes: UInt64, totalBytes: UInt64) {
guard uiProgressDownloadCompleted != nil else {
return
}
let progress = Double(downloadedBytes) / Double(totalBytes)
updateDownloadProgress(pct: progress)
}
public func audioPlayer(_ audioPlayer: AGAudioPlayer, progressChanged elapsed: TimeInterval, withTotalDuration totalDuration: TimeInterval) {
updatePlaybackProgress()
publishToNowPlayingCenter()
}
public func publishToNowPlayingCenter() {
guard shouldPublishToNowPlayingCenter else {
return
}
var nowPlayingInfo : [String : Any]? = nil
if let item = player.currentItem {
nowPlayingInfo = [
MPMediaItemPropertyMediaType : NSNumber(value: MPMediaType.music.rawValue),
MPMediaItemPropertyTitle : item.title,
MPMediaItemPropertyAlbumArtist : item.artist,
MPMediaItemPropertyArtist : item.artist,
MPMediaItemPropertyAlbumTitle : item.album,
MPMediaItemPropertyPlaybackDuration : NSNumber(value: item.duration),
MPMediaItemPropertyAlbumTrackNumber : NSNumber(value: item.trackNumber),
// MPNowPlayingInfoPropertyDefaultPlaybackRate : NSNumber(value: 1.0),
MPNowPlayingInfoPropertyElapsedPlaybackTime : NSNumber(value: player.elapsed),
MPNowPlayingInfoPropertyPlaybackProgress : NSNumber(value: Float(player.percentElapsed)),
MPNowPlayingInfoPropertyPlaybackQueueCount : NSNumber(value: player.queue.count),
MPNowPlayingInfoPropertyPlaybackQueueIndex : NSNumber(value: player.currentIndex),
MPNowPlayingInfoPropertyPlaybackRate : NSNumber(value: player.isPlaying ? 1.0 : 0.0)
]
if let albumArt = item.albumArt {
nowPlayingInfo![MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: albumArt.size, requestHandler: { (_) -> UIImage in
return albumArt
})
}
}
//print("Updating now playing info to \(nowPlayingInfo)")
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
}
extension AGAudioPlayerViewController : ScrubberBarDelegate {
func setupPlayerUiActions() {
uiScrubber.delegate = self
uiLabelTitle.isUserInteractionEnabled = true
uiLabelSubtitle.isUserInteractionEnabled = true
uiMiniLabelTitle.isUserInteractionEnabled = true
uiMiniLabelSubtitle.isUserInteractionEnabled = true
updateDownloadProgress(pct: 0.0)
updatePlaybackProgress()
/*
Assign in XIB as per MarqueeLabel docs
uiLabelTitle.scrollRate = 25
uiLabelTitle.trailingBuffer = 32
uiLabelTitle.animationDelay = 5
uiLabelSubtitle.scrollRate = 25
uiLabelSubtitle.trailingBuffer = 24
uiLabelSubtitle.animationDelay = 5
uiMiniLabelTitle.scrollRate = 16
uiMiniLabelTitle.trailingBuffer = 24
uiMiniLabelTitle.animationDelay = 5
uiMiniLabelSubtitle.scrollRate = 16
uiMiniLabelSubtitle.trailingBuffer = 16
uiMiniLabelSubtitle.animationDelay = 5
*/
}
public func scrubberBar(bar: ScrubberBar, didScrubToProgress: Float, finished: Bool) {
isCurrentlyScrubbing = !finished
if let elapsed = uiLabelElapsed, let mp = uiMiniProgressPlayback {
elapsed.text = TimeInterval(player.duration * Double(didScrubToProgress)).formatted()
mp.progress = didScrubToProgress
}
if finished {
player.seek(toPercent: CGFloat(didScrubToProgress))
}
}
@IBAction func uiActionToggleShuffle(_ sender: UIButton) {
player.shuffle = !player.shuffle
updateShuffleLoopButtons()
uiTable.reloadData()
updatePreviousNextButtons()
}
@IBAction func uiActionToggleLoop(_ sender: UIButton) {
player.loopItem = !player.loopItem
updateShuffleLoopButtons()
}
@IBAction func uiActionPrevious(_ sender: UIButton) {
player.backward()
}
@IBAction func uiActionPlay(_ sender: UIButton) {
player.resume()
}
@IBAction func uiActionPause(_ sender: UIButton) {
player.pause()
}
@IBAction func uiActionNext(_ sender: UIButton) {
player.forward()
}
@IBAction func uiActionDots(_ sender: UIButton) {
if let item = self.player.currentItem {
delegate?.audioPlayerViewController(self, pressedDotsForAudioItem: item)
}
}
@IBAction func uiActionPlus(_ sender: UIButton) {
if let item = self.player.currentItem {
delegate?.audioPlayerViewController(self, pressedPlusForAudioItem: item)
}
}
@IBAction func uiOpenFullUi(_ sender: UIButton) {
self.presentationDelegate?.fullPlayerRequested()
}
}
public protocol AGAudioPlayerViewControllerPresentationDelegate {
func fullPlayerRequested()
func fullPlayerDismissRequested(fromProgress: CGFloat)
func fullPlayerStartedDismissing()
func fullPlayerDismissUpdatedProgress(_ progress: CGFloat)
func fullPlayerDismissCancelled(fromProgress: CGFloat)
func fullPlayerOpenUpdatedProgress(_ progress: CGFloat)
func fullPlayerOpenCancelled(fromProgress: CGFloat)
func fullPlayerOpenRequested(fromProgress: CGFloat)
}
public protocol AGAudioPlayerViewControllerCellDataSource {
func cell(inTableView tableView: UITableView, basedOnCell cell: UITableViewCell, atIndexPath: IndexPath, forPlaybackItem playbackItem: AGAudioItem, isCurrentlyPlaying: Bool) -> UITableViewCell
func heightForCell(inTableView tableView: UITableView, atIndexPath: IndexPath, forPlaybackItem playbackItem: AGAudioItem, isCurrentlyPlaying: Bool) -> CGFloat
}
public protocol AGAudioPlayerViewControllerDelegate {
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, trackChangedState audioItem: AGAudioItem?)
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, changedTrackTo audioItem: AGAudioItem?)
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, passedHalfWayFor audioItem: AGAudioItem)
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, pressedDotsForAudioItem audioItem: AGAudioItem)
func audioPlayerViewController(_ agAudio: AGAudioPlayerViewController, pressedPlusForAudioItem audioItem: AGAudioItem)
}
extension AGAudioPlayerViewController {
public func switchToMiniPlayer(animated: Bool) {
view.layoutIfNeeded()
UIView.animate(withDuration: 0.3) {
self.switchToMiniPlayerProgress(1.0)
}
}
public func switchToFullPlayer(animated: Bool) {
view.layoutIfNeeded()
UIView.animate(withDuration: 0.3) {
self.switchToMiniPlayerProgress(0.0)
}
self.scrollQueueToPlayingTrack()
}
public func switchToMiniPlayerProgress(_ progress: CGFloat) {
let maxHeight = self.uiMiniPlayerContainerView.frame.height
self.uiMiniPlayerTopOffsetConstraint.constant = -1.0 * maxHeight * (1.0 - progress)
self.view.layoutIfNeeded()
}
}
extension AGAudioPlayerViewController {
@IBAction func handlePanToClose(_ sender: UIPanGestureRecognizer) {
let percentThreshold:CGFloat = 0.3
let inView = uiHeaderView
// convert y-position to downward pull progress (percentage)
let translation = sender.translation(in: inView)
let verticalMovement = translation.y / view.bounds.height
let downwardMovement = fmaxf(Float(verticalMovement), 0.0)
let downwardMovementPercent = fminf(downwardMovement, 1.0)
let progress = CGFloat(downwardMovementPercent)
let interactor = dismissInteractor
switch sender.state {
case .began:
uiScrubber.scrubbingEnabled = false
interactor.hasStarted = true
case .changed:
interactor.shouldFinish = progress > percentThreshold
interactor.update(progress)
case .cancelled:
uiScrubber.scrubbingEnabled = true
interactor.hasStarted = false
interactor.cancel(progress)
case .ended:
uiScrubber.scrubbingEnabled = true
interactor.hasStarted = false
if interactor.shouldFinish {
interactor.finish(progress)
}
else {
interactor.cancel(progress)
}
default:
break
}
}
@IBAction func handlePanToOpen(_ sender: UIPanGestureRecognizer) {
let percentThreshold:CGFloat = 0.15
let inView = uiMiniPlayerContainerView
// convert y-position to downward pull progress (percentage)
let translation = sender.translation(in: inView)
let verticalMovement = (-1.0 * translation.y) / view.bounds.height
let upwardMovement = fmaxf(Float(verticalMovement), 0.0)
let upwardMovementPercent = fminf(upwardMovement, 1.0)
let progress = CGFloat(upwardMovementPercent)
let interactor = openInteractor
switch sender.state {
case .began:
interactor.hasStarted = true
case .changed:
interactor.shouldFinish = progress > percentThreshold
interactor.update(progress)
case .cancelled:
interactor.hasStarted = false
interactor.cancel(progress)
case .ended:
interactor.hasStarted = false
if interactor.shouldFinish {
interactor.finish(progress)
}
else {
interactor.cancel(progress)
}
default:
break
}
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive press: UIPress) -> Bool {
return !isCurrentlyScrubbing
}
@IBAction func handleChevronTapped(_ sender: UIButton) {
dismissInteractor.finish(1.0)
}
}
class DismissInteractor {
var hasStarted = false
var shouldFinish = false
var viewController: AGAudioPlayerViewController? = nil
var delegate: AGAudioPlayerViewControllerPresentationDelegate? {
get {
return viewController?.presentationDelegate
}
}
public func update(_ progress: CGFloat) {
delegate?.fullPlayerDismissUpdatedProgress(progress)
}
// restore
public func cancel(_ progress: CGFloat) {
delegate?.fullPlayerDismissCancelled(fromProgress: progress)
}
// dismiss
public func finish(_ progress: CGFloat) {
delegate?.fullPlayerDismissRequested(fromProgress: progress)
}
}
class OpenInteractor : DismissInteractor {
public override func update(_ progress: CGFloat) {
delegate?.fullPlayerOpenUpdatedProgress(progress)
}
// restore
public override func cancel(_ progress: CGFloat) {
delegate?.fullPlayerOpenCancelled(fromProgress: progress)
}
// dismiss
public override func finish(_ progress: CGFloat) {
delegate?.fullPlayerOpenRequested(fromProgress: progress)
}
}
extension AGAudioPlayerViewController {
func setupStretchyHeader() {
let blk = { [weak self] (fontScale: Double) in
if let s = self {
s.uiHeaderView.transform = CGAffineTransform(scaleX: CGFloat(fontScale), y: CGFloat(fontScale))
let h = s.uiHeaderView.bounds.height * CGFloat(fontScale)
s.uiTable.scrollIndicatorInsets = UIEdgeInsets.init(top: h, left: 0, bottom: 0, right: 0)
}
}
headerInterpolate = Interpolate(from: 1.0, to: 1.3, function: BasicInterpolation.easeOut, apply: blk)
interpolateBlock = blk
let insets = UIApplication.shared.keyWindow!.rootViewController!.view.safeAreaInsets
self.uiConstraintSpaceBetweenPlayers.constant = insets.top
self.view.layoutIfNeeded()
self.uiConstraintBottomBarHeight.constant += insets.bottom * 2
self.uiFooterView.layoutIfNeeded()
}
func viewWillAppear_StretchyHeader() {
interpolateBlock?(1.0)
let h = self.uiHeaderView.bounds.height
self.uiTable.contentInset = UIEdgeInsets.init(top: h, left: 0, bottom: 0, right: 0)
self.uiTable.contentOffset = CGPoint(x: 0, y: -h)
self.scrollQueueToPlayingTrack()
}
func scrollViewDidScroll_StretchyHeader(_ scrollView: UIScrollView) {
let y = scrollView.contentOffset.y + uiHeaderView.bounds.height
let base = view.safeAreaInsets.top
let np = CGFloat(abs(y).clamped(lower: CGFloat(base + 0), upper: CGFloat(base + 150))) / CGFloat(base + 150)
if y < 0 && headerInterpolate?.progress != np {
// headerInterpolate?.progress = np
}
}
}
extension AGAudioPlayerViewController {
func setupColors() {
applyColors(colors)
}
public func applyColors(_ colors: AGAudioPlayerColors) {
self.colors = colors
view.backgroundColor = colors.main
uiMiniPlayerContainerView.backgroundColor = colors.main
uiMiniLabelTitle.textColor = colors.accent
uiMiniLabelSubtitle.textColor = colors.accent
uiHeaderView.backgroundColor = colors.main
uiFooterView.backgroundColor = colors.main
uiLabelTitle.textColor = colors.accent
uiLabelSubtitle.textColor = colors.accent
uiLabelElapsed.textColor = colors.accentWeak
uiLabelDuration.textColor = colors.accentWeak
uiProgressDownload.backgroundColor = colors.barNothing
uiProgressDownloadCompleted.backgroundColor = colors.barDownloads
uiScrubber.elapsedColor = colors.barPlaybackElapsed
uiScrubber.dragIndicatorColor = colors.scrubberHandle
uiWrapperEq.isHidden = true
uiWrapperEq.backgroundColor = colors.main.darkenByPercentage(0.05)
uiSliderVolume.tintColor = colors.accent
/*
view.layer.masksToBounds = true
view.layer.cornerRadius = 4
*/
uiSliderEqBass.tintColor = colors.barPlaybackElapsed
uiSliderEqBass.sliderUnselectedColor = colors.barDownloads
}
public override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension AGAudioPlayerViewController {
func setupTable() {
uiTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// uiTable.backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: uiHeaderView.bounds.size.height + 44 * 2))
// uiTable.backgroundView?.backgroundColor = ColorMain
uiTable.allowsSelection = true
uiTable.allowsSelectionDuringEditing = true
uiTable.allowsMultipleSelectionDuringEditing = false
uiTable.setEditing(true, animated: false)
uiTable.reloadData()
}
func viewWillAppear_Table() {
}
public func tableReloadData() {
if let t = uiTable {
t.reloadData()
}
}
}
extension AGAudioPlayerViewController : UITableViewDelegate {
/*
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
dismissInteractor.hasStarted = true
}
*/
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollViewDidScroll_StretchyHeader(scrollView)
// let progress = (scrollView.contentOffset.y - scrollView.contentOffset.y) / view.frame.size.height
//
// dismissInteractor.update(progress)
}
// public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// dismissInteractor.hasStarted = false
//
// let progress = (scrollView.contentOffset.y - scrollView.contentOffset.y) / view.frame.size.height
//
// if progress > 0.1 {
// dismissInteractor.finish(progress)
// }
// else {
// dismissInteractor.cancel(progress)
// }
// }
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
player.currentIndex = indexPath.row
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
print("\(indexPath) deselected")
}
public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == SectionQueue
}
public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if sourceIndexPath != destinationIndexPath {
player.queue.moveItem(at: sourceIndexPath.row, to: destinationIndexPath.row)
tableView.reloadData()
}
}
public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
}
extension AGAudioPlayerViewController : UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return player.queue.count
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Queue"
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
guard indexPath.row < player.queue.count else {
cell.textLabel?.text = "Error"
return cell
}
let q = player.queue.properQueue(forShuffleEnabled: player.shuffle)
let item = q[indexPath.row]
let currentlyPlaying = item.playbackGUID == player.currentItem?.playbackGUID
if let d = cellDataSource {
return d.cell(inTableView: tableView, basedOnCell: cell, atIndexPath: indexPath, forPlaybackItem: item, isCurrentlyPlaying: currentlyPlaying)
}
cell.textLabel?.text = (currentlyPlaying ? "* " : "") + item.title
return cell
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard indexPath.row < player.queue.count else {
return UITableView.automaticDimension
}
let q = player.queue.properQueue(forShuffleEnabled: player.shuffle)
let item = q[indexPath.row]
let currentlyPlaying = item.playbackGUID == player.currentItem?.playbackGUID
if let d = cellDataSource {
return d.heightForCell(inTableView: tableView, atIndexPath: indexPath, forPlaybackItem: item, isCurrentlyPlaying: currentlyPlaying)
}
return UITableView.automaticDimension
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableView.performBatchUpdates({
player.queue.removeItem(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}, completion: nil)
}
}
fileprivate func scrollQueueToPlayingTrack() {
var itemRow = -1
let q = player.queue.properQueue(forShuffleEnabled: player.shuffle)
var curItemIndex = 0
for item in q {
if item.playbackGUID == player.currentItem?.playbackGUID {
itemRow = curItemIndex
break
}
curItemIndex += 1
}
if itemRow > -1 && itemRow < uiTable.numberOfRows(inSection: 0) {
uiTable.scrollToRow(at: IndexPath(row: max(0, itemRow-1), section: 0), at: .top, animated: true)
}
}
}
|
bf5eeee1d27993b5bbcf2c109d8d5c99
| 33.455927 | 196 | 0.645378 | false | false | false | false |
moyazi/SwiftDayList
|
refs/heads/master
|
SwiftDayList/Days/Day7/Day7MainViewController.swift
|
mit
|
1
|
//
// Day7MainViewController.swift
// SwiftDayList
//
// Created by leoo on 2017/6/28.
// Copyright © 2017年 Het. All rights reserved.
//
import UIKit
import CoreLocation
class Day7MainViewController: UIViewController ,CLLocationManagerDelegate{
@IBOutlet weak var locationLB: UILabel!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "CLLocation"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Private Func
@IBAction func myLocationButtonDidTouch(_ sender: UIButton) {
self.locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.locationLB.text = "Error while updating location " + error.localizedDescription
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
self.locationLB.text = "Reverse geocoder failed with error" + error!.localizedDescription
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
self.displayLocationInfo(pm)
} else {
self.locationLB.text = "Problem with the data received from geocoder"
}
})
}
func displayLocationInfo(_ placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
self.locationLB.text = postalCode! + " " + locality!
self.locationLB.text?.append("\n" + administrativeArea! + ", " + country!)
}
}
}
|
9f907439c94b67303d368e0ee0d32f1b
| 37.144928 | 126 | 0.647796 | false | false | false | false |
rlisle/Patriot-iOS
|
refs/heads/master
|
Patriot/ConfigViewController.swift
|
bsd-3-clause
|
1
|
//
// ConfigViewController.swift
// Patriot
//
// Created by Ron Lisle on 5/29/17.
// Copyright © 2017 Ron Lisle. All rights reserved.
//
import UIKit
class ConfigViewController: UITableViewController
{
@IBOutlet weak var particleUser: UITextField!
@IBOutlet weak var particlePassword: UITextField!
@IBOutlet weak var loginStatus: UILabel!
let settings = Settings(store: UserDefaultsSettingsStore())
fileprivate let swipeInteractionController = InteractiveTransition()
var screenEdgeRecognizer: UIScreenEdgePanGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
print("config viewDidLoad")
screenEdgeRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleUnwindRecognizer))
screenEdgeRecognizer.edges = .right
view.addGestureRecognizer(screenEdgeRecognizer)
}
override func viewDidAppear(_ animated: Bool)
{
registerForNotifications()
initializeDisplayValues()
}
override func viewWillDisappear(_ animated: Bool)
{
unregisterForNotifications()
}
func registerForNotifications()
{
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(self.textFieldDidChange),
name: NSNotification.Name.UITextFieldTextDidChange,
object: nil)
}
func initializeDisplayValues()
{
particleUser.text = settings.particleUser
particlePassword.text = settings.particlePassword
}
func unregisterForNotifications()
{
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self)
}
@objc func handleUnwindRecognizer(_ recognizer: UIScreenEdgePanGestureRecognizer)
{
if recognizer.state == .began
{
let transition: CATransition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionReveal
transition.subtype = kCATransitionFromRight
view.window!.layer.add(transition, forKey: nil)
dismiss(animated: false, completion: nil)
}
}
@objc func textFieldDidChange(sender : AnyObject) {
guard let notification = sender as? NSNotification,
let textFieldChanged = notification.object as? UITextField else
{
return
}
if let textString = textFieldChanged.text
{
print("text changed = \(textString)")
switch textFieldChanged
{
case self.particleUser:
userDidChange(string: textString)
break
case self.particlePassword:
passwordDidChange(string: textString)
break
default:
print("unknown text field")
break
}
}
}
fileprivate func userDidChange(string: String)
{
print("User changed")
settings.particleUser = string
loginIfDataIsValid()
}
fileprivate func passwordDidChange(string: String)
{
print("Password changed")
settings.particlePassword = string
loginIfDataIsValid()
}
fileprivate func loginIfDataIsValid()
{
print("particle login")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let appFactory = appDelegate.appFactory!
appFactory.loginToParticle()
}
}
|
4439661596c45ceb845f0c2821200d45
| 28.183206 | 120 | 0.617316 | false | false | false | false |
urbn/URBNValidator
|
refs/heads/master
|
Pod/Classes/ObjC/URBNLengthRulesCompat.swift
|
mit
|
1
|
//
// URBNLengthRulesCompat.swift
// URBNValidator
//
// Created by Nick DiStefano on 12/21/15.
//
//
import Foundation
@objc open class URBNCompatMinLengthRule: URBNCompatRequirementRule {
public init(minLength: Int, inclusive: Bool = false, localizationKey: String? = nil) {
super.init()
backingRule = URBNMinLengthRule(minLength: minLength, inclusive: inclusive, localizationKey: localizationKey)
}
}
@objc open class URBNCompatMaxLengthRule: URBNCompatRequirementRule {
public init(maxLength: Int, inclusive: Bool = false, localizationKey: String? = nil) {
super.init()
backingRule = URBNMaxLengthRule(maxLength: maxLength, inclusive: inclusive, localizationKey: localizationKey)
}
}
|
f644cae0f7f2086f4d0ee1639e45000e
| 29.958333 | 117 | 0.728129 | false | false | false | false |
silence0201/Swift-Study
|
refs/heads/master
|
AdvancedSwift/协议/Indices/Indices - Stacks.playgroundpage/Contents.swift
|
mit
|
1
|
/*:
#### Stacks
This list is a stack, with consing as push, and unwrapping the next element as
pop. As we've mentioned before, arrays are also stacks. Let's define a common
protocol for stacks, as we did with queues:
*/
//#-editable-code
/// A LIFO stack type with constant-time push and pop operations
protocol Stack {
/// The type of element held stored in the stack
associatedtype Element
/// Pushes `x` onto the top of `self`
/// - Complexity: Amortized O(1).
mutating func push(_: Element)
/// Removes the topmost element of `self` and returns it,
/// or `nil` if `self` is empty.
/// - Complexity: O(1)
mutating func pop() -> Element?
}
//#-end-editable-code
/*:
We've been a bit more proscriptive in the documentation comments about what it
means to conform to `Stack`, including giving some minimum performance
guarantees.
`Array` can be made to conform to `Stack`, like this:
*/
//#-editable-code
extension Array: Stack {
mutating func push(_ x: Element) { append(x) }
mutating func pop() -> Element? { return popLast() }
}
//#-end-editable-code
/*:
So can `List`:
*/
//#-hidden-code
/// A simple linked list enum
enum List<Element> {
case end
indirect case node(Element, next: List<Element>)
}
//#-end-hidden-code
//#-hidden-code
extension List {
/// Return a new list by prepending a node with value `x` to the
/// front of a list.
func cons(_ x: Element) -> List {
return .node(x, next: self)
}
}
//#-end-hidden-code
//#-hidden-code
extension List: ExpressibleByArrayLiteral {
init(arrayLiteral elements: Element...) {
self = elements.reversed().reduce(.end) { partialList, element in
partialList.cons(element)
}
}
}
//#-end-hidden-code
//#-editable-code
extension List: Stack {
mutating func push(_ x: Element) {
self = self.cons(x)
}
mutating func pop() -> Element? {
switch self {
case .end: return nil
case let .node(x, next: xs):
self = xs
return x
}
}
}
//#-end-editable-code
/*:
But didn't we just say that the list had to be immutable for the persistence to
work? How can it have mutating methods?
These mutating methods don't change the list. Instead, they just change the part
of the list the variables refer to:
*/
//#-editable-code
var stack: List<Int> = [3,2,1]
var a = stack
var b = stack
a.pop()
a.pop()
a.pop()
stack.pop()
stack.push(4)
b.pop()
b.pop()
b.pop()
stack.pop()
stack.pop()
stack.pop()
//#-end-editable-code
/*:
This shows us the difference between values and variables. The nodes of the list
are values; they can't change. A node of three and a reference to the next node
can't become some other value; it'll be that value forever, just like the number
three can't change. It just is. Just because these values in question are
structures with references to each other doesn't make them less value-like.
A variable `a`, on the other hand, can change the value it holds. It can be set
to hold a value of an indirect reference to any of the nodes, or to the value
`end`. But changing `a` doesn't change these nodes; it just changes which node
`a` refers to.
This is what these mutating methods on structs do — they take an implicit
`inout` argument of `self`, and they can change the value `self` holds. This
doesn't change the list, but rather which part of the list the variable
currently represents. In this sense, through `indirect`, the variables have
become iterators into the list:

You can, of course, declare your variables with `let` instead of `var`, in which
case the variables will be constant (i.e. you can't change the value they hold
once they're set). But `let` is about the variables, not the values. Values are
constant by definition.
Now this is all just a logical model of how things work. In reality, the nodes
are actually places in memory that point to each other. And they take up space,
which we want back if it's no longer needed. Swift uses automated reference
counting (ARC) to manage this and frees the memory for the nodes that are no
longer used:

We'll discuss `inout` in more detail in the chapter on functions, and we'll
cover mutating methods as well as ARC in the structs and classes chapter.
*/
|
dc60a0296d88235276c0999223e8c3be
| 26.591195 | 80 | 0.692956 | false | false | false | false |
tnantoka/AppBoard
|
refs/heads/master
|
AppBoard/Models/Software.swift
|
mit
|
1
|
//
// Software.swift
// AppBoard
//
// Created by Tatsuya Tobioka on 3/13/16.
// Copyright © 2016 Tatsuya Tobioka. All rights reserved.
//
import UIKit
import Himotoki
struct Software: Decodable {
let name: String
let description: String
let iconURL: NSURL?
let viewURL: NSURL?
let releaseDate: NSDate?
let thumbnail: UIImage?
static func decode(e: Extractor) throws -> Software {
return try Software(
name: e.value("trackName"),
description: e.value("description"),
iconURL: e.valueOptional("artworkUrl512").flatMap { NSURL(string: $0) },
viewURL: e.valueOptional("trackViewUrl").flatMap { NSURL(string: $0) },
releaseDate: e.valueOptional("releaseDate").flatMap { parseDate($0) },
thumbnail: e.valueOptional("artworkUrl60").flatMap { NSURL(string: $0) }.flatMap { NSData(contentsOfURL: $0) }.flatMap { UIImage(data: $0) }
)
}
static func parseDate(string: String) -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter.dateFromString(string)
}
var app: App {
let app = App()
app.name = name
app.desc = description
app.icon = iconURL?.absoluteString ?? ""
app.url = viewURL?.absoluteString ?? ""
app.releasedAt = releaseDate ?? NSDate()
return app
}
}
|
f156ef0b78e085acc27657ee9e6a2e6b
| 30.456522 | 152 | 0.609537 | false | false | false | false |
TheBrewery/Hikes
|
refs/heads/master
|
WorldHeritage/Components/TBLocationManager.swift
|
mit
|
1
|
import CoreLocation
import UIKit
extension CLLocationCoordinate2D {
func coordinatesSeparatedByComma() -> String {
return "\(self.latitude),\(self.longitude)"
}
}
enum TBLocationServicesStatus {
case Authorized
case Unauthorized
case Disabled
}
class TBLocationManager: CLLocationManager, CLLocationManagerDelegate {
private static let sharedInstance = TBLocationManager()
private var didChangeAuthorizationStatus: ((CLAuthorizationStatus) -> ())?
private var didUpdateLocations: ((CLLocation?, NSError?) -> ())?
private override init() {
super.init()
desiredAccuracy = kCLLocationAccuracyNearestTenMeters
distanceFilter = 500
delegate = self
}
class func unauthorizedAlertController() -> UIViewController {
let appName = NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
let title = "Allow \"\(appName)\" to access your location while you use the app?"
let message = NSBundle.mainBundle().infoDictionary!["NSLocationWhenInUseUsageDescription"] as! String
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Don't Allow", style: .Default, handler: nil))
alertController.addAction(UIAlertAction(title: "Allow", style: .Default, handler: { (action) in ()
let url = NSURL(string: UIApplicationOpenSettingsURLString)!
UIApplication.sharedApplication().openURL(url)
}))
return alertController
}
class func disabledAlertController() -> UIViewController {
let title = "Location Services is disabled"
let message = NSBundle.mainBundle().infoDictionary!["NSLocationWhenInUseUsageDescription"] as! String
let alertController = UIAlertController(title: title, message: message + " Please turn on Location Services in the Privacy section of your device settings.", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "No Thanks", style: .Default, handler: nil))
alertController.addAction(UIAlertAction(title: "Go to Settings", style: .Default, handler: { (action) in ()
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}))
return alertController
}
class var currentLocation: CLLocation? {
return sharedInstance.location
}
class var isAvailable: Bool {
return isEnabled && isAuthorized
}
class var isAuthorized: Bool {
return authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse
}
class var isEnabled: Bool {
return locationServicesEnabled()
}
class func authorize(completion: ((CLAuthorizationStatus) -> ())? = nil) {
sharedInstance.didChangeAuthorizationStatus = completion
sharedInstance.requestWhenInUseAuthorization()
}
class func updateLocation() {
sharedInstance.startUpdatingLocation()
}
class func getGeolocation(completion: ((CLLocation?, NSError?) -> ())?) {
guard let location = sharedInstance.location else {
sharedInstance.didUpdateLocations = completion
updateLocation()
return
}
completion?(location, nil)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
stopUpdatingLocation()
didUpdateLocations?(locations.first, nil)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
stopUpdatingLocation()
didUpdateLocations?(nil, error)
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
didChangeAuthorizationStatus?(status)
}
}
|
23251d7356cf82855bc61f8a0632719e
| 36.475728 | 189 | 0.698187 | false | false | false | false |
h-n-y/BigNerdRanch-SwiftProgramming
|
refs/heads/master
|
chapter-24/silver-challenge/CyclicalAssets/Person.swift
|
mit
|
1
|
//
// Person.swift
// CyclicalAssets
//
// Created by Hans Yelek on 1/28/16.
// Copyright © 2016 Hans Yelek. All rights reserved.
//
import Foundation
class Person: CustomStringConvertible {
let name: String
let accountant = Accountant()
var assets = [Asset]()
var description: String {
return "Person(\(name))"
}
init(name: String) {
self.name = name
accountant.netWorthChangedHandler = {
[weak self]( netWorth ) in
self?.netWorthDidChange(netWorth)
return
}
}
deinit {
print("\(self) is being deallocated")
}
func takeOwnershipOfAsset(asset: Asset) {
// SILVER CHALLENGE
//
// prevent asset from being assigned to a second owner if
// it is already owned
guard asset.owner == nil else {
print("Cannot take ownership - asset is already owned!")
return
}
asset.owner = self
assets.append(asset)
accountant.gainedNewAsset(asset)
}
func netWorthDidChange(netWorth: Double) {
print("The net worth of \(self) is now \(netWorth)")
}
}
|
415159b982181035bc98095964e697e3
| 21.87037 | 68 | 0.550607 | false | false | false | false |
tomboates/BrilliantSDK
|
refs/heads/master
|
Pod/Classes/CommentsViewController.swift
|
mit
|
1
|
//
// CommentsViewController.swift
// Pods
//
// Created by Phillip Connaughton on 1/24/16.
//
//
import Foundation
protocol CommentsViewControllerDelegate: class{
func closePressed(_ state: SurveyViewControllerState)
func submitFeedbackPressed()
func doNotSubmitFeedbackPressed()
}
class CommentsViewController: UIViewController
{
@IBOutlet var closeButton: UIButton!
@IBOutlet var comments: UITextView!
@IBOutlet var noThanksButton: UIButton!
@IBOutlet var submitButton: UIButton!
@IBOutlet var commentDescriptionLabel: UILabel!
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var keyboardToolbar: UIToolbar!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
internal weak var delegate : CommentsViewControllerDelegate?
override func viewDidLoad() {
let image = UIImage(named: "brilliant-icon-close", in:Brilliant.imageBundle(), compatibleWith: nil)
self.closeButton.setImage(image, for: UIControlState())
self.closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 25, right: 25)
self.commentDescriptionLabel.textColor = Brilliant.sharedInstance().mainLabelColor()
self.commentDescriptionLabel.font = Brilliant.sharedInstance().mainLabelFont()
self.comments.layer.cornerRadius = 4;
self.comments.inputAccessoryView = self.keyboardToolbar
self.comments.font = Brilliant.sharedInstance().commentBoxFont()
let npsNumber: Int! = Brilliant.sharedInstance().completedSurvey?.npsRating!
if(npsNumber >= 7)
{
self.commentDescriptionLabel.text = Brilliant.sharedInstance().positiveFeedbackText(npsNumber)
}
else
{
self.commentDescriptionLabel.text = Brilliant.sharedInstance().negativeFeedbackText(npsNumber)
}
Brilliant.sharedInstance().styleButton(self.submitButton)
self.noThanksButton.tintColor = Brilliant.sharedInstance().noThanksButtonColor()
self.submitButton.titleLabel?.font = Brilliant.sharedInstance().submitButtonFont()
self.noThanksButton.titleLabel?.font = Brilliant.sharedInstance().submitButtonFont()
NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboard), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboard), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func adjustForKeyboard(_ notification: Notification) {
var userInfo = (notification as NSNotification).userInfo!
let keyboardScreenEndFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, to: view.window)
self.view.translatesAutoresizingMaskIntoConstraints = true
let screenHeight = UIScreen.main.bounds.height
let height = self.comments.frame.height + self.comments.frame.origin.y
let diffHeight = CGFloat(screenHeight) - height
var moveHeight : CGFloat? = 0
if (diffHeight < keyboardViewEndFrame.height) {
moveHeight = diffHeight - keyboardViewEndFrame.height
}
var offset : CGFloat? = 0
if comments.frame.origin.y < abs(moveHeight!) {
offset = abs(moveHeight!) - comments.frame.origin.y - 5
}
if notification.name == NSNotification.Name.UIKeyboardWillHide {
UIView.animate(withDuration: 1.0, animations: {
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
})
} else {
UIView.animate(withDuration: 1.0, animations: {
self.view.frame = CGRect(x: 0, y: moveHeight! + offset! - 5, width: self.view.frame.width, height: self.view.frame.height)
})
}
}
func textFieldValue(_ notification: Notification){
if comments.text.isEmpty {
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.noThanksButton.alpha = 1
self.submitButton.alpha = 0
}, completion: nil)
} else {
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.noThanksButton.alpha = 0
self.submitButton.alpha = 1
}, completion: nil)
}
}
func textView(_ textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
if comments.text.isEmpty {
textView.resignFirstResponder()
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.noThanksButton.alpha = 1
self.submitButton.alpha = 0
}, completion: nil)
return false
} else {
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.noThanksButton.alpha = 0
self.submitButton.alpha = 1
}, completion: nil)
}
textView.resignFirstResponder()
return false
}
return true
}
func textFieldDidReturn(_ textField: UITextField!) {
textField.resignFirstResponder()
// Execute additional code
}
func keyboardWasShown(_ notification: Notification)
{
//Need to calculate keyboard exact size due to Apple suggestions
// npsView.scrollEnabled = true
// let info : NSDictionary = notification.userInfo!
// var keyboardSize : CGRect = ((info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue())!
// keyboardSize = comments.convertRect(keyboardSize, toView: nil)
// let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
//
// npsView.contentInset = contentInsets
// npsView.scrollIndicatorInsets = contentInsets
//
// var aRect : CGRect = self.view.frame
// aRect.size.height -= (keyboardSize.height + 100)
// var fieldOrigin : CGPoint = comments.frame.origin;
// fieldOrigin.y -= npsView.contentOffset.y;
// fieldOrigin = comments.convertPoint(fieldOrigin, toView: self.view.superview)
// originalOffset = npsView.contentOffset;
//
// if (!CGRectContainsPoint(aRect, fieldOrigin))
// {
// npsView.scrollRectToVisible(comments.frame, animated: true)
// }
}
func keyboardWillBeHidden(_ notification: Notification)
{
//Once keyboard disappears, restore original positions
// let info : NSDictionary = notification.userInfo!
// let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
// let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
// npsView.contentInset = contentInsets
// npsView.scrollIndicatorInsets = contentInsets
// npsView.setContentOffset(originalOffset, animated: true)
// self.view.endEditing(true)
// npsView.scrollEnabled = false
}
@IBAction func submitPressed(_ sender: AnyObject) {
Brilliant.sharedInstance().completedSurvey!.comment = self.comments.text
self.delegate?.submitFeedbackPressed()
}
@IBAction func noThanksPressed(_ sender: AnyObject) {
self.delegate?.doNotSubmitFeedbackPressed()
}
@IBAction func closePressed(_ sender: AnyObject) {
self.delegate?.closePressed(.commentScreen)
}
@IBAction func keyboardDoneClicked(_ sender: AnyObject) {
self.comments.resignFirstResponder()
}
}
|
7c77d44a003a8ffee28111b7cd01c57a
| 39.910448 | 151 | 0.640399 | false | false | false | false |
heptorsj/Design-Patterns-Swftly
|
refs/heads/master
|
Builder.swift
|
gpl-3.0
|
1
|
// Builder Desing Pattern
/*
Separate the construction of a complex object from
its representation so that the same construction
process can create different representations.
*/
// We need:
// A Director, A Builder , A Client and Product
// Example: A Burger Fast Food Restaurant
// We define tipes for project
enum Burger { // A burger can be one of these
case chessBurger
case chickernBurger
case beefBurger
}
enum Drink { // A coke can be one ot these
case cocaCola
case pepsiCola
}
enum Complement { // Second item of package
case frenchFries
case wings
}
enum Toy{ // Two types of toys
case forBoy
case forGirl
}
// Structure of a generic package
class BurgerPackage{
var burger: Burger = Burger.chessBurger
var drink: Drink = Drink.pepsiCola
var complement:Complement = Complement.frenchFries
var toy: Toy = Toy.forGirl
}
// Build abstract protocol to create all of possible packages
protocol builderBurgers{
var customerPackage: BurgerPackage {get} // Creates a new packages
// Now the functions that creates all the variations
func setBurger(burger:Burger)-> Burger
func setDrink(drink:Drink)-> Drink
func setComplement(complement:Complement)-> Complement
func setToy(toy:Toy)-> Toy
}
// Define concrete package Builder
class PackageMaker : builderBurgers {
var customerPackage: BurgerPackage
// functions that makes custome packages
func setBurger(burger:Burger) -> Burger {
switch burger {
case .chickernBurger:
customerPackage.burger = Burger.chickernBurger
return Burger.chickernBurger
case .beefBurger:
customerPackage.burger = Burger.beefBurger
return Burger.beefBurger
default:
return Burger.chessBurger
}
}
func setDrink(drink: Drink)-> Drink {
switch drink {
case .cocaCola:
customerPackage.drink = Drink.cocaCola
return Drink.cocaCola
default:
return Drink.pepsiCola
}
}
func setComplement(complement:Complement)-> Complement {
switch complement {
case .wings:
customerPackage.complement = Complement.wings
return Complement.wings
default:
return Complement.frenchFries
}
}
func setToy(toy:Toy)->Toy{
switch toy {
case .forBoy:
customerPackage.toy = Toy.forBoy
return Toy.forBoy
default:
return Toy.forGirl
}
}
init(burger:Burger,drink:Drink,complement:Complement,toy:Toy){
self.customerPackage = BurgerPackage()
setBurger(burger:burger)
setDrink(drink:drink)
setComplement(complement:complement)
setToy(toy:toy)
}
}
// Now make some packages
let client = PackageMaker(burger:Burger.beefBurger,drink:Drink.pepsiCola,complement:Complement.wings,toy:Toy.forBoy)
print("Burger: \(client.customerPackage.burger)")
print("Drink: \(client.customerPackage.drink)")
print("Complement: \(client.customerPackage.complement)")
print("Toy: \(client.customerPackage.toy)")
|
8aeeed10a98029a0b69837c8d7c48fe7
| 26.570093 | 118 | 0.718644 | false | false | false | false |
AllenConquest/emonIOS
|
refs/heads/master
|
emonIOSTests/FeedSpec.swift
|
gpl-2.0
|
1
|
//
// FeedSpec.swift
// emonIOS
//
// Created by Allen Conquest on 25/07/2015.
// Copyright (c) 2015 Allen Conquest. All rights reserved.
//
import Quick
import Nimble
import emonIOS
import SwiftyJSON
class FeedSpec: QuickSpec {
override func spec() {
// var feed: Feed!
//
// beforeEach() {
// feed = Feed()
// feed.id = 1
// feed.userid = 2
// feed.name = "Test"
// }
//
// describe("intial state") {
// it("has id") {
// expect(feed.id).to(beGreaterThanOrEqualTo(1))
// }
// it("has userid") {
// expect(feed.userid).to(beGreaterThanOrEqualTo(1))
// }
// it("has name") {
// expect(feed.name).to(equal("Test"))
// }
//
// }
it("can be encode and decoded") {
let json = JSON(["id":"101","userid":"202","name":"fred","datatype":"1","tag":"","public":"0","size":"12345","engine":"5","server":"1","time":"123","value":"123.456"])
let test = Feed(item: json)
NSKeyedArchiver.archiveRootObject(test, toFile: "/feed/data")
let y = NSKeyedUnarchiver.unarchiveObjectWithFile("/feed/data") as? Feed
print (y)
}
}
}
|
31cec87107d3bc5ac3e9803af2bf4772
| 26.8125 | 179 | 0.481648 | false | true | false | false |
Piwigo/Piwigo-Mobile
|
refs/heads/master
|
piwigoKit/Network/NetworkUtilities.swift
|
mit
|
1
|
//
// NetworkUtilities.swift
// piwigoKit
//
// Created by Eddy Lelièvre-Berna on 08/06/2021.
// Copyright © 2021 Piwigo.org. All rights reserved.
//
import Foundation
public class NetworkUtilities: NSObject {
// MARK: - UTF-8 encoding on 3 and 4 bytes
public class
func utf8mb4String(from string: String?) -> String {
// Return empty string if nothing provided
guard let strToConvert = string, strToConvert.isEmpty == false else {
return ""
}
// Convert string to UTF-8 encoding
let serverEncoding = String.Encoding(rawValue: NetworkVars.stringEncoding )
if let strData = strToConvert.data(using: serverEncoding, allowLossyConversion: true) {
return String(data: strData, encoding: .utf8) ?? strToConvert
}
return ""
}
// Piwigo supports the 3-byte UTF-8, not the standard UTF-8 (4 bytes)
// See https://github.com/Piwigo/Piwigo-Mobile/issues/429, https://github.com/Piwigo/Piwigo/issues/750
public class
func utf8mb3String(from string: String?) -> String {
// Return empty string is nothing provided
guard let strToFilter = string, strToFilter.isEmpty == false else {
return ""
}
// Replace characters encoded on 4 bytes
var utf8mb3String = ""
for char in strToFilter {
if char.utf8.count > 3 {
// 4-byte char => Not handled by Piwigo Server
utf8mb3String.append("\u{FFFD}") // Use the Unicode replacement character
} else {
// Up to 3-byte char
utf8mb3String.append(char)
}
}
return utf8mb3String
}
// MARK: - Clean URLs of Images
public class
func encodedImageURL(_ originalURL:String?) -> String? {
// Return nil if originalURL is nil and a placeholder will be used
guard let okURL = originalURL else { return nil }
// TEMPORARY PATCH for case where $conf['original_url_protection'] = 'images';
/// See https://github.com/Piwigo/Piwigo-Mobile/issues/503
var serverURL: NSURL? = NSURL(string: okURL.replacingOccurrences(of: "&part=", with: "&part="))
// Servers may return incorrect URLs
// See https://tools.ietf.org/html/rfc3986#section-2
if serverURL == nil {
// URL not RFC compliant!
var leftURL = okURL
// Remove protocol header
if okURL.hasPrefix("http://") { leftURL.removeFirst(7) }
if okURL.hasPrefix("https://") { leftURL.removeFirst(8) }
// Retrieve authority
guard let endAuthority = leftURL.firstIndex(of: "/") else {
// No path, incomplete URL —> return image.jpg but should never happen
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
let authority = String(leftURL.prefix(upTo: endAuthority))
leftURL.removeFirst(authority.count)
// The Piwigo server may not be in the root e.g. example.com/piwigo/…
// So we remove the path to avoid a duplicate if necessary
if let loginURL = URL(string: "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)"),
loginURL.path.count > 0, leftURL.hasPrefix(loginURL.path) {
leftURL.removeFirst(loginURL.path.count)
}
// Retrieve path
if let endQuery = leftURL.firstIndex(of: "?") {
// URL contains a query
let query = (String(leftURL.prefix(upTo: endQuery)) + "?").replacingOccurrences(of: "??", with: "?")
guard let newQuery = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
// Could not apply percent encoding —> return image.jpg but should never happen
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
leftURL.removeFirst(query.count)
guard let newPath = leftURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
// Could not apply percent encoding —> return image.jpg but should never happen
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
serverURL = NSURL(string: "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)\(newQuery)\(newPath)")
} else {
// No query -> remaining string is a path
let newPath = String(leftURL.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)
serverURL = NSURL(string: "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)\(newPath)")
}
// Last check
if serverURL == nil {
// Could not apply percent encoding —> return image.jpg but should never happen
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
}
// Servers may return image URLs different from those used to login (e.g. wrong server settings)
// We only keep the path+query because we only accept to download images from the same server.
guard var cleanPath = serverURL?.path else {
return "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)/image.jpg"
}
if let paramStr = serverURL?.parameterString {
cleanPath.append(paramStr)
}
if let query = serverURL?.query {
cleanPath.append("?" + query)
}
if let fragment = serverURL?.fragment {
cleanPath.append("#" + fragment)
}
// The Piwigo server may not be in the root e.g. example.com/piwigo/…
// So we remove the path to avoid a duplicate if necessary
if let loginURL = URL(string: "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)"),
loginURL.path.count > 0, cleanPath.hasPrefix(loginURL.path) {
cleanPath.removeFirst(loginURL.path.count)
}
// Remove the .php?, i? prefixes if any
var prefix = ""
if let pos = cleanPath.range(of: "?") {
// The path contains .php? or i?
prefix = String(cleanPath.prefix(upTo: pos.upperBound))
cleanPath.removeFirst(prefix.count)
}
// Path may not be encoded
if let decodedPath = cleanPath.removingPercentEncoding, cleanPath == decodedPath,
let test = cleanPath.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) {
cleanPath = test
}
// Compile final URL using the one provided at login
let encodedImageURL = "\(NetworkVars.serverProtocol)\(NetworkVars.serverPath)\(prefix)\(cleanPath)"
#if DEBUG
if encodedImageURL != originalURL {
print("=> originalURL:\(String(describing: originalURL))")
print(" encodedURL:\(encodedImageURL)")
print(" path=\(String(describing: serverURL?.path)), parameterString=\(String(describing: serverURL?.parameterString)), query:\(String(describing: serverURL?.query)), fragment:\(String(describing: serverURL?.fragment))")
}
#endif
return encodedImageURL;
}
}
// MARK: - RFC 3986 allowed characters
extension CharacterSet {
/// Creates a CharacterSet from RFC 3986 allowed characters.
///
/// https://datatracker.ietf.org/doc/html/rfc3986/#section-2.2
/// Section 2.2 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// https://datatracker.ietf.org/doc/html/rfc3986/#section-3.4
/// Section 3.4 states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
public static let pwgURLQueryAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@"
let subDelimitersToEncode = "!$&'()*+,;="
let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
}()
}
|
5bb7d6efad916cebf039c6b602adf930
| 44.700535 | 235 | 0.604844 | false | false | false | false |
apple/swift-nio
|
refs/heads/main
|
Tests/NIOPosixTests/EventLoopFutureTest.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import Dispatch
@testable import NIOCore
import NIOEmbedded
import NIOPosix
enum EventLoopFutureTestError : Error {
case example
}
class EventLoopFutureTest : XCTestCase {
func testFutureFulfilledIfHasResult() throws {
let eventLoop = EmbeddedEventLoop()
let f = EventLoopFuture(eventLoop: eventLoop, value: 5)
XCTAssertTrue(f.isFulfilled)
}
func testFutureFulfilledIfHasError() throws {
let eventLoop = EmbeddedEventLoop()
let f = EventLoopFuture<Void>(eventLoop: eventLoop, error: EventLoopFutureTestError.example)
XCTAssertTrue(f.isFulfilled)
}
func testFoldWithMultipleEventLoops() throws {
let nThreads = 3
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: nThreads)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
}
let eventLoop0 = eventLoopGroup.next()
let eventLoop1 = eventLoopGroup.next()
let eventLoop2 = eventLoopGroup.next()
XCTAssert(eventLoop0 !== eventLoop1)
XCTAssert(eventLoop1 !== eventLoop2)
XCTAssert(eventLoop0 !== eventLoop2)
let f0: EventLoopFuture<[Int]> = eventLoop0.submit { [0] }
let f1s: [EventLoopFuture<Int>] = (1...4).map { id in eventLoop1.submit { id } }
let f2s: [EventLoopFuture<Int>] = (5...8).map { id in eventLoop2.submit { id } }
var fN = f0.fold(f1s) { (f1Value: [Int], f2Value: Int) -> EventLoopFuture<[Int]> in
XCTAssert(eventLoop0.inEventLoop)
return eventLoop1.makeSucceededFuture(f1Value + [f2Value])
}
fN = fN.fold(f2s) { (f1Value: [Int], f2Value: Int) -> EventLoopFuture<[Int]> in
XCTAssert(eventLoop0.inEventLoop)
return eventLoop2.makeSucceededFuture(f1Value + [f2Value])
}
let allValues = try fN.wait()
XCTAssert(fN.eventLoop === f0.eventLoop)
XCTAssert(fN.isFulfilled)
XCTAssertEqual(allValues, [0, 1, 2, 3, 4, 5, 6, 7, 8])
}
func testFoldWithSuccessAndAllSuccesses() throws {
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0 = eventLoop.makeSucceededFuture([0])
let futures: [EventLoopFuture<Int>] = (1...5).map { (id: Int) in secondEventLoop.makeSucceededFuture(id) }
let fN = f0.fold(futures) { (f1Value: [Int], f2Value: Int) -> EventLoopFuture<[Int]> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + [f2Value])
}
let allValues = try fN.wait()
XCTAssert(fN.eventLoop === f0.eventLoop)
XCTAssert(fN.isFulfilled)
XCTAssertEqual(allValues, [0, 1, 2, 3, 4, 5])
}
func testFoldWithSuccessAndOneFailure() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeSucceededFuture(0)
let promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in secondEventLoop.makePromise() }
var futures = promises.map { $0.futureResult }
let failedFuture: EventLoopFuture<Int> = secondEventLoop.makeFailedFuture(E())
futures.insert(failedFuture, at: futures.startIndex)
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + f2Value)
}
_ = promises.map { $0.succeed(0) }
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testFoldWithSuccessAndEmptyFutureList() throws {
let eventLoop = EmbeddedEventLoop()
let f0 = eventLoop.makeSucceededFuture(0)
let futures: [EventLoopFuture<Int>] = []
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return eventLoop.makeSucceededFuture(f1Value + f2Value)
}
let summationResult = try fN.wait()
XCTAssert(fN.isFulfilled)
XCTAssertEqual(summationResult, 0)
}
func testFoldWithFailureAndEmptyFutureList() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeFailedFuture(E())
let futures: [EventLoopFuture<Int>] = []
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return eventLoop.makeSucceededFuture(f1Value + f2Value)
}
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testFoldWithFailureAndAllSuccesses() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeFailedFuture(E())
let promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in secondEventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + f2Value)
}
_ = promises.map { $0.succeed(1) }
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testFoldWithFailureAndAllUnfulfilled() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeFailedFuture(E())
let promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in secondEventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + f2Value)
}
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testFoldWithFailureAndAllFailures() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let secondEventLoop = EmbeddedEventLoop()
let f0: EventLoopFuture<Int> = eventLoop.makeFailedFuture(E())
let futures: [EventLoopFuture<Int>] = (0..<100).map { (_: Int) in secondEventLoop.makeFailedFuture(E()) }
let fN = f0.fold(futures) { (f1Value: Int, f2Value: Int) -> EventLoopFuture<Int> in
XCTAssert(eventLoop.inEventLoop)
return secondEventLoop.makeSucceededFuture(f1Value + f2Value)
}
XCTAssert(fN.isFulfilled)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testAndAllWithEmptyFutureList() throws {
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Void>] = []
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
XCTAssert(fN.isFulfilled)
}
func testAndAllWithAllSuccesses() throws {
let eventLoop = EmbeddedEventLoop()
let promises: [EventLoopPromise<Void>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
_ = promises.map { $0.succeed(()) }
() = try fN.wait()
}
func testAndAllWithAllFailures() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let promises: [EventLoopPromise<Void>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
_ = promises.map { $0.fail(E()) }
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testAndAllWithOneFailure() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
var promises: [EventLoopPromise<Void>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
_ = promises.map { $0.succeed(()) }
let failedPromise = eventLoop.makePromise(of: Void.self)
failedPromise.fail(E())
promises.append(failedPromise)
let futures = promises.map { $0.futureResult }
let fN = EventLoopFuture.andAllSucceed(futures, on: eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceWithAllSuccesses() throws {
let eventLoop = EmbeddedEventLoop()
let promises: [EventLoopPromise<Int>] = (0..<5).map { (_: Int) in eventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN: EventLoopFuture<[Int]> = EventLoopFuture<[Int]>.reduce(into: [], futures, on: eventLoop) {
$0.append($1)
}
for i in 1...5 {
promises[i - 1].succeed((i))
}
let results = try fN.wait()
XCTAssertEqual(results, [1, 2, 3, 4, 5])
XCTAssert(fN.eventLoop === eventLoop)
}
func testReduceWithOnlyInitialValue() throws {
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Int>] = []
let fN: EventLoopFuture<[Int]> = EventLoopFuture<[Int]>.reduce(into: [], futures, on: eventLoop) {
$0.append($1)
}
let results = try fN.wait()
XCTAssertEqual(results, [])
XCTAssert(fN.eventLoop === eventLoop)
}
func testReduceWithAllFailures() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
let futures = promises.map { $0.futureResult }
let fN: EventLoopFuture<Int> = EventLoopFuture<Int>.reduce(0, futures, on: eventLoop, +)
_ = promises.map { $0.fail(E()) }
XCTAssert(fN.eventLoop === eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceWithOneFailure() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
var promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
_ = promises.map { $0.succeed((1)) }
let failedPromise = eventLoop.makePromise(of: Int.self)
failedPromise.fail(E())
promises.append(failedPromise)
let futures = promises.map { $0.futureResult }
let fN: EventLoopFuture<Int> = EventLoopFuture<Int>.reduce(0, futures, on: eventLoop, +)
XCTAssert(fN.eventLoop === eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceWhichDoesFailFast() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
var promises: [EventLoopPromise<Int>] = (0..<100).map { (_: Int) in eventLoop.makePromise() }
let failedPromise = eventLoop.makePromise(of: Int.self)
promises.insert(failedPromise, at: promises.startIndex)
let futures = promises.map { $0.futureResult }
let fN: EventLoopFuture<Int> = EventLoopFuture<Int>.reduce(0, futures, on: eventLoop, +)
failedPromise.fail(E())
XCTAssertTrue(fN.isFulfilled)
XCTAssert(fN.eventLoop === eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceIntoWithAllSuccesses() throws {
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Int>] = [1, 2, 2, 3, 3, 3].map { (id: Int) in eventLoop.makeSucceededFuture(id) }
let fN: EventLoopFuture<[Int: Int]> = EventLoopFuture<[Int: Int]>.reduce(into: [:], futures, on: eventLoop) { (freqs, elem) in
if let value = freqs[elem] {
freqs[elem] = value + 1
} else {
freqs[elem] = 1
}
}
let results = try fN.wait()
XCTAssertEqual(results, [1: 1, 2: 2, 3: 3])
XCTAssert(fN.eventLoop === eventLoop)
}
func testReduceIntoWithEmptyFutureList() throws {
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Int>] = []
let fN: EventLoopFuture<[Int: Int]> = EventLoopFuture<[Int: Int]>.reduce(into: [:], futures, on: eventLoop) { (freqs, elem) in
if let value = freqs[elem] {
freqs[elem] = value + 1
} else {
freqs[elem] = 1
}
}
let results = try fN.wait()
XCTAssert(results.isEmpty)
XCTAssert(fN.eventLoop === eventLoop)
}
func testReduceIntoWithAllFailure() throws {
struct E: Error {}
let eventLoop = EmbeddedEventLoop()
let futures: [EventLoopFuture<Int>] = [1, 2, 2, 3, 3, 3].map { (id: Int) in eventLoop.makeFailedFuture(E()) }
let fN: EventLoopFuture<[Int: Int]> = EventLoopFuture<[Int: Int]>.reduce(into: [:], futures, on: eventLoop) { (freqs, elem) in
if let value = freqs[elem] {
freqs[elem] = value + 1
} else {
freqs[elem] = 1
}
}
XCTAssert(fN.isFulfilled)
XCTAssert(fN.eventLoop === eventLoop)
XCTAssertThrowsError(try fN.wait()) { error in
XCTAssertNotNil(error as? E)
}
}
func testReduceIntoWithMultipleEventLoops() throws {
let nThreads = 3
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: nThreads)
defer {
XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully())
}
let eventLoop0 = eventLoopGroup.next()
let eventLoop1 = eventLoopGroup.next()
let eventLoop2 = eventLoopGroup.next()
XCTAssert(eventLoop0 !== eventLoop1)
XCTAssert(eventLoop1 !== eventLoop2)
XCTAssert(eventLoop0 !== eventLoop2)
let f0: EventLoopFuture<[Int:Int]> = eventLoop0.submit { [:] }
let f1s: [EventLoopFuture<Int>] = (1...4).map { id in eventLoop1.submit { id / 2 } }
let f2s: [EventLoopFuture<Int>] = (5...8).map { id in eventLoop2.submit { id / 2 } }
let fN = EventLoopFuture<[Int:Int]>.reduce(into: [:], f1s + f2s, on: eventLoop0) { (freqs, elem) in
XCTAssert(eventLoop0.inEventLoop)
if let value = freqs[elem] {
freqs[elem] = value + 1
} else {
freqs[elem] = 1
}
}
let allValues = try fN.wait()
XCTAssert(fN.eventLoop === f0.eventLoop)
XCTAssert(fN.isFulfilled)
XCTAssertEqual(allValues, [0: 1, 1: 2, 2: 2, 3: 2, 4: 1])
}
func testThenThrowingWhichDoesNotThrow() {
let eventLoop = EmbeddedEventLoop()
var ran = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.map {
$0.count
}.flatMapThrowing {
1 + $0
}.whenSuccess {
ran = true
XCTAssertEqual($0, 6)
}
p.succeed("hello")
XCTAssertTrue(ran)
}
func testThenThrowingWhichDoesThrow() {
enum DummyError: Error, Equatable {
case dummyError
}
let eventLoop = EmbeddedEventLoop()
var ran = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.map {
$0.count
}.flatMapThrowing { (x: Int) throws -> Int in
XCTAssertEqual(5, x)
throw DummyError.dummyError
}.map { (x: Int) -> Int in
XCTFail("shouldn't have been called")
return x
}.whenFailure {
ran = true
XCTAssertEqual(.some(DummyError.dummyError), $0 as? DummyError)
}
p.succeed("hello")
XCTAssertTrue(ran)
}
func testflatMapErrorThrowingWhichDoesNotThrow() {
enum DummyError: Error, Equatable {
case dummyError
}
let eventLoop = EmbeddedEventLoop()
var ran = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.map {
$0.count
}.flatMapErrorThrowing {
XCTAssertEqual(.some(DummyError.dummyError), $0 as? DummyError)
return 5
}.flatMapErrorThrowing { (_: Error) in
XCTFail("shouldn't have been called")
return 5
}.whenSuccess {
ran = true
XCTAssertEqual($0, 5)
}
p.fail(DummyError.dummyError)
XCTAssertTrue(ran)
}
func testflatMapErrorThrowingWhichDoesThrow() {
enum DummyError: Error, Equatable {
case dummyError1
case dummyError2
}
let eventLoop = EmbeddedEventLoop()
var ran = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.map {
$0.count
}.flatMapErrorThrowing { (x: Error) throws -> Int in
XCTAssertEqual(.some(DummyError.dummyError1), x as? DummyError)
throw DummyError.dummyError2
}.map { (x: Int) -> Int in
XCTFail("shouldn't have been called")
return x
}.whenFailure {
ran = true
XCTAssertEqual(.some(DummyError.dummyError2), $0 as? DummyError)
}
p.fail(DummyError.dummyError1)
XCTAssertTrue(ran)
}
func testOrderOfFutureCompletion() throws {
let eventLoop = EmbeddedEventLoop()
var state = 0
let p: EventLoopPromise<Void> = EventLoopPromise(eventLoop: eventLoop, file: #filePath, line: #line)
p.futureResult.map {
XCTAssertEqual(state, 0)
state += 1
}.map {
XCTAssertEqual(state, 1)
state += 1
}.whenSuccess {
XCTAssertEqual(state, 2)
state += 1
}
p.succeed(())
XCTAssertTrue(p.futureResult.isFulfilled)
XCTAssertEqual(state, 3)
}
func testEventLoopHoppingInThen() throws {
let n = 20
let elg = MultiThreadedEventLoopGroup(numberOfThreads: n)
var prev: EventLoopFuture<Int> = elg.next().makeSucceededFuture(0)
(1..<20).forEach { (i: Int) in
let p = elg.next().makePromise(of: Int.self)
prev.flatMap { (i2: Int) -> EventLoopFuture<Int> in
XCTAssertEqual(i - 1, i2)
p.succeed(i)
return p.futureResult
}.whenSuccess { i2 in
XCTAssertEqual(i, i2)
}
prev = p.futureResult
}
XCTAssertEqual(n-1, try prev.wait())
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
func testEventLoopHoppingInThenWithFailures() throws {
enum DummyError: Error {
case dummy
}
let n = 20
let elg = MultiThreadedEventLoopGroup(numberOfThreads: n)
var prev: EventLoopFuture<Int> = elg.next().makeSucceededFuture(0)
(1..<n).forEach { (i: Int) in
let p = elg.next().makePromise(of: Int.self)
prev.flatMap { (i2: Int) -> EventLoopFuture<Int> in
XCTAssertEqual(i - 1, i2)
if i == n/2 {
p.fail(DummyError.dummy)
} else {
p.succeed(i)
}
return p.futureResult
}.flatMapError { error in
p.fail(error)
return p.futureResult
}.whenSuccess { i2 in
XCTAssertEqual(i, i2)
}
prev = p.futureResult
}
XCTAssertThrowsError(try prev.wait()) { error in
XCTAssertNotNil(error as? DummyError)
}
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
func testEventLoopHoppingAndAll() throws {
let n = 20
let elg = MultiThreadedEventLoopGroup(numberOfThreads: n)
let ps = (0..<n).map { (_: Int) -> EventLoopPromise<Void> in
elg.next().makePromise()
}
let allOfEm = EventLoopFuture.andAllSucceed(ps.map { $0.futureResult }, on: elg.next())
ps.reversed().forEach { p in
DispatchQueue.global().async {
p.succeed(())
}
}
try allOfEm.wait()
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
func testEventLoopHoppingAndAllWithFailures() throws {
enum DummyError: Error { case dummy }
let n = 20
let fireBackEl = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let elg = MultiThreadedEventLoopGroup(numberOfThreads: n)
let ps = (0..<n).map { (_: Int) -> EventLoopPromise<Void> in
elg.next().makePromise()
}
let allOfEm = EventLoopFuture.andAllSucceed(ps.map { $0.futureResult }, on: fireBackEl.next())
ps.reversed().enumerated().forEach { idx, p in
DispatchQueue.global().async {
if idx == n / 2 {
p.fail(DummyError.dummy)
} else {
p.succeed(())
}
}
}
XCTAssertThrowsError(try allOfEm.wait()) { error in
XCTAssertNotNil(error as? DummyError)
}
XCTAssertNoThrow(try elg.syncShutdownGracefully())
XCTAssertNoThrow(try fireBackEl.syncShutdownGracefully())
}
func testFutureInVariousScenarios() throws {
enum DummyError: Error { case dummy0; case dummy1 }
let elg = MultiThreadedEventLoopGroup(numberOfThreads: 2)
let el1 = elg.next()
let el2 = elg.next()
precondition(el1 !== el2)
let q1 = DispatchQueue(label: "q1")
let q2 = DispatchQueue(label: "q2")
// this determines which promise is fulfilled first (and (true, true) meaning they race)
for whoGoesFirst in [(false, true), (true, false), (true, true)] {
// this determines what EventLoops the Promises are created on
for eventLoops in [(el1, el1), (el1, el2), (el2, el1), (el2, el2)] {
// this determines if the promises fail or succeed
for whoSucceeds in [(false, false), (false, true), (true, false), (true, true)] {
let p0 = eventLoops.0.makePromise(of: Int.self)
let p1 = eventLoops.1.makePromise(of: String.self)
let fAll = p0.futureResult.and(p1.futureResult)
// preheat both queues so we have a better chance of racing
let sem1 = DispatchSemaphore(value: 0)
let sem2 = DispatchSemaphore(value: 0)
let g = DispatchGroup()
q1.async(group: g) {
sem2.signal()
sem1.wait()
}
q2.async(group: g) {
sem1.signal()
sem2.wait()
}
g.wait()
if whoGoesFirst.0 {
q1.async {
if whoSucceeds.0 {
p0.succeed(7)
} else {
p0.fail(DummyError.dummy0)
}
if !whoGoesFirst.1 {
q2.asyncAfter(deadline: .now() + 0.1) {
if whoSucceeds.1 {
p1.succeed("hello")
} else {
p1.fail(DummyError.dummy1)
}
}
}
}
}
if whoGoesFirst.1 {
q2.async {
if whoSucceeds.1 {
p1.succeed("hello")
} else {
p1.fail(DummyError.dummy1)
}
if !whoGoesFirst.0 {
q1.asyncAfter(deadline: .now() + 0.1) {
if whoSucceeds.0 {
p0.succeed(7)
} else {
p0.fail(DummyError.dummy0)
}
}
}
}
}
do {
let result = try fAll.wait()
if !whoSucceeds.0 || !whoSucceeds.1 {
XCTFail("unexpected success")
} else {
XCTAssert((7, "hello") == result)
}
} catch let e as DummyError {
switch e {
case .dummy0:
XCTAssertFalse(whoSucceeds.0)
case .dummy1:
XCTAssertFalse(whoSucceeds.1)
}
} catch {
XCTFail("unexpected error: \(error)")
}
}
}
}
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
func testLoopHoppingHelperSuccess() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let loop1 = group.next()
let loop2 = group.next()
XCTAssertFalse(loop1 === loop2)
let succeedingPromise = loop1.makePromise(of: Void.self)
let succeedingFuture = succeedingPromise.futureResult.map {
XCTAssertTrue(loop1.inEventLoop)
}.hop(to: loop2).map {
XCTAssertTrue(loop2.inEventLoop)
}
succeedingPromise.succeed(())
XCTAssertNoThrow(try succeedingFuture.wait())
}
func testLoopHoppingHelperFailure() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let loop1 = group.next()
let loop2 = group.next()
XCTAssertFalse(loop1 === loop2)
let failingPromise = loop2.makePromise(of: Void.self)
let failingFuture = failingPromise.futureResult.flatMapErrorThrowing { error in
XCTAssertEqual(error as? EventLoopFutureTestError, EventLoopFutureTestError.example)
XCTAssertTrue(loop2.inEventLoop)
throw error
}.hop(to: loop1).recover { error in
XCTAssertEqual(error as? EventLoopFutureTestError, EventLoopFutureTestError.example)
XCTAssertTrue(loop1.inEventLoop)
}
failingPromise.fail(EventLoopFutureTestError.example)
XCTAssertNoThrow(try failingFuture.wait())
}
func testLoopHoppingHelperNoHopping() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let loop1 = group.next()
let loop2 = group.next()
XCTAssertFalse(loop1 === loop2)
let noHoppingPromise = loop1.makePromise(of: Void.self)
let noHoppingFuture = noHoppingPromise.futureResult.hop(to: loop1)
XCTAssertTrue(noHoppingFuture === noHoppingPromise.futureResult)
noHoppingPromise.succeed(())
}
func testFlatMapResultHappyPath() {
let el = EmbeddedEventLoop()
defer {
XCTAssertNoThrow(try el.syncShutdownGracefully())
}
let p = el.makePromise(of: Int.self)
let f = p.futureResult.flatMapResult { (_: Int) in
return Result<String, Never>.success("hello world")
}
p.succeed(1)
XCTAssertNoThrow(XCTAssertEqual("hello world", try f.wait()))
}
func testFlatMapResultFailurePath() {
struct DummyError: Error {}
let el = EmbeddedEventLoop()
defer {
XCTAssertNoThrow(try el.syncShutdownGracefully())
}
let p = el.makePromise(of: Int.self)
let f = p.futureResult.flatMapResult { (_: Int) in
return Result<Int, Error>.failure(DummyError())
}
p.succeed(1)
XCTAssertThrowsError(try f.wait()) { error in
XCTAssert(type(of: error) == DummyError.self)
}
}
func testWhenAllSucceedFailsImmediately() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Int]>?) {
let promises = [group.next().makePromise(of: Int.self),
group.next().makePromise(of: Int.self)]
let futures = promises.map { $0.futureResult }
let futureResult: EventLoopFuture<[Int]>
if let promise = promise {
futureResult = promise.futureResult
EventLoopFuture.whenAllSucceed(futures, promise: promise)
} else {
futureResult = EventLoopFuture.whenAllSucceed(futures, on: group.next())
}
promises[0].fail(EventLoopFutureTestError.example)
XCTAssertThrowsError(try futureResult.wait()) { error in
XCTAssert(type(of: error) == EventLoopFutureTestError.self)
}
}
doTest(promise: nil)
doTest(promise: group.next().makePromise())
}
func testWhenAllSucceedResolvesAfterFutures() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 6)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Int]>?) throws {
let promises = (0..<5).map { _ in group.next().makePromise(of: Int.self) }
let futures = promises.map { $0.futureResult }
var succeeded = false
var completedPromises = false
let mainFuture: EventLoopFuture<[Int]>
if let promise = promise {
mainFuture = promise.futureResult
EventLoopFuture.whenAllSucceed(futures, promise: promise)
} else {
mainFuture = EventLoopFuture.whenAllSucceed(futures, on: group.next())
}
mainFuture.whenSuccess { _ in
XCTAssertTrue(completedPromises)
XCTAssertFalse(succeeded)
succeeded = true
}
// Should be false, as none of the promises have completed yet
XCTAssertFalse(succeeded)
// complete the first four promises
for (index, promise) in promises.dropLast().enumerated() {
promise.succeed(index)
}
// Should still be false, as one promise hasn't completed yet
XCTAssertFalse(succeeded)
// Complete the last promise
completedPromises = true
promises.last!.succeed(4)
let results = try assertNoThrowWithValue(mainFuture.wait())
XCTAssertEqual(results, [0, 1, 2, 3, 4])
}
XCTAssertNoThrow(try doTest(promise: nil))
XCTAssertNoThrow(try doTest(promise: group.next().makePromise()))
}
func testWhenAllSucceedIsIndependentOfFulfillmentOrder() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 6)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Int]>?) throws {
let expected = Array(0..<1000)
let promises = expected.map { _ in group.next().makePromise(of: Int.self) }
let futures = promises.map { $0.futureResult }
var succeeded = false
var completedPromises = false
let mainFuture: EventLoopFuture<[Int]>
if let promise = promise {
mainFuture = promise.futureResult
EventLoopFuture.whenAllSucceed(futures, promise: promise)
} else {
mainFuture = EventLoopFuture.whenAllSucceed(futures, on: group.next())
}
mainFuture.whenSuccess { _ in
XCTAssertTrue(completedPromises)
XCTAssertFalse(succeeded)
succeeded = true
}
for index in expected.reversed() {
if index == 0 {
completedPromises = true
}
promises[index].succeed(index)
}
let results = try assertNoThrowWithValue(mainFuture.wait())
XCTAssertEqual(results, expected)
}
XCTAssertNoThrow(try doTest(promise: nil))
XCTAssertNoThrow(try doTest(promise: group.next().makePromise()))
}
func testWhenAllCompleteResultsWithFailuresStillSucceed() {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Result<Bool, Error>]>?) {
let futures: [EventLoopFuture<Bool>] = [
group.next().makeFailedFuture(EventLoopFutureTestError.example),
group.next().makeSucceededFuture(true)
]
let future: EventLoopFuture<[Result<Bool, Error>]>
if let promise = promise {
future = promise.futureResult
EventLoopFuture.whenAllComplete(futures, promise: promise)
} else {
future = EventLoopFuture.whenAllComplete(futures, on: group.next())
}
XCTAssertNoThrow(try future.wait())
}
doTest(promise: nil)
doTest(promise: group.next().makePromise())
}
func testWhenAllCompleteResults() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Result<Int, Error>]>?) throws {
let futures: [EventLoopFuture<Int>] = [
group.next().makeSucceededFuture(3),
group.next().makeFailedFuture(EventLoopFutureTestError.example),
group.next().makeSucceededFuture(10),
group.next().makeFailedFuture(EventLoopFutureTestError.example),
group.next().makeSucceededFuture(5)
]
let future: EventLoopFuture<[Result<Int, Error>]>
if let promise = promise {
future = promise.futureResult
EventLoopFuture.whenAllComplete(futures, promise: promise)
} else {
future = EventLoopFuture.whenAllComplete(futures, on: group.next())
}
let results = try assertNoThrowWithValue(future.wait())
XCTAssertEqual(try results[0].get(), 3)
XCTAssertThrowsError(try results[1].get())
XCTAssertEqual(try results[2].get(), 10)
XCTAssertThrowsError(try results[3].get())
XCTAssertEqual(try results[4].get(), 5)
}
XCTAssertNoThrow(try doTest(promise: nil))
XCTAssertNoThrow(try doTest(promise: group.next().makePromise()))
}
func testWhenAllCompleteResolvesAfterFutures() throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 6)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
func doTest(promise: EventLoopPromise<[Result<Int, Error>]>?) throws {
let promises = (0..<5).map { _ in group.next().makePromise(of: Int.self) }
let futures = promises.map { $0.futureResult }
var succeeded = false
var completedPromises = false
let mainFuture: EventLoopFuture<[Result<Int, Error>]>
if let promise = promise {
mainFuture = promise.futureResult
EventLoopFuture.whenAllComplete(futures, promise: promise)
} else {
mainFuture = EventLoopFuture.whenAllComplete(futures, on: group.next())
}
mainFuture.whenSuccess { _ in
XCTAssertTrue(completedPromises)
XCTAssertFalse(succeeded)
succeeded = true
}
// Should be false, as none of the promises have completed yet
XCTAssertFalse(succeeded)
// complete the first four promises
for (index, promise) in promises.dropLast().enumerated() {
promise.succeed(index)
}
// Should still be false, as one promise hasn't completed yet
XCTAssertFalse(succeeded)
// Complete the last promise
completedPromises = true
promises.last!.succeed(4)
let results = try assertNoThrowWithValue(mainFuture.wait().map { try $0.get() })
XCTAssertEqual(results, [0, 1, 2, 3, 4])
}
XCTAssertNoThrow(try doTest(promise: nil))
XCTAssertNoThrow(try doTest(promise: group.next().makePromise()))
}
struct DatabaseError: Error {}
struct Database {
let query: () -> EventLoopFuture<[String]>
var closed = false
init(query: @escaping () -> EventLoopFuture<[String]>) {
self.query = query
}
func runQuery() -> EventLoopFuture<[String]> {
return query()
}
mutating func close() {
self.closed = true
}
}
func testAlways() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
var db = Database { loop.makeSucceededFuture(["Item 1", "Item 2", "Item 3"]) }
XCTAssertFalse(db.closed)
let _ = try assertNoThrowWithValue(db.runQuery().always { result in
assertSuccess(result)
db.close()
}.map { $0.map { $0.uppercased() }}.wait())
XCTAssertTrue(db.closed)
}
func testAlwaysWithFailingPromise() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
var db = Database { loop.makeFailedFuture(DatabaseError()) }
XCTAssertFalse(db.closed)
let _ = try XCTAssertThrowsError(db.runQuery().always { result in
assertFailure(result)
db.close()
}.map { $0.map { $0.uppercased() }}.wait()) { XCTAssertTrue($0 is DatabaseError) }
XCTAssertTrue(db.closed)
}
func testPromiseCompletedWithSuccessfulFuture() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
let future = loop.makeSucceededFuture("yay")
let promise = loop.makePromise(of: String.self)
promise.completeWith(future)
XCTAssertEqual(try promise.futureResult.wait(), "yay")
}
func testPromiseCompletedWithFailedFuture() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
let future: EventLoopFuture<EventLoopFutureTestError> = loop.makeFailedFuture(EventLoopFutureTestError.example)
let promise = loop.makePromise(of: EventLoopFutureTestError.self)
promise.completeWith(future)
XCTAssertThrowsError(try promise.futureResult.wait()) { error in
XCTAssert(type(of: error) == EventLoopFutureTestError.self)
}
}
func testPromiseCompletedWithSuccessfulResult() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
let promise = loop.makePromise(of: Void.self)
let result: Result<Void, Error> = .success(())
promise.completeWith(result)
XCTAssertNoThrow(try promise.futureResult.wait())
}
func testPromiseCompletedWithFailedResult() throws {
let group = EmbeddedEventLoop()
let loop = group.next()
let promise = loop.makePromise(of: Void.self)
let result: Result<Void, Error> = .failure(EventLoopFutureTestError.example)
promise.completeWith(result)
XCTAssertThrowsError(try promise.futureResult.wait()) { error in
XCTAssert(type(of: error) == EventLoopFutureTestError.self)
}
}
func testAndAllCompleteWithZeroFutures() {
let eventLoop = EmbeddedEventLoop()
let done = DispatchWorkItem {}
EventLoopFuture<Void>.andAllComplete([], on: eventLoop).whenComplete { (result: Result<Void, Error>) in
_ = result.mapError { error -> Error in
XCTFail("unexpected error \(error)")
return error
}
done.perform()
}
done.wait()
}
func testAndAllSucceedWithZeroFutures() {
let eventLoop = EmbeddedEventLoop()
let done = DispatchWorkItem {}
EventLoopFuture<Void>.andAllSucceed([], on: eventLoop).whenComplete { result in
_ = result.mapError { error -> Error in
XCTFail("unexpected error \(error)")
return error
}
done.perform()
}
done.wait()
}
func testAndAllCompleteWithPreSucceededFutures() {
let eventLoop = EmbeddedEventLoop()
let succeeded = eventLoop.makeSucceededFuture(())
for i in 0..<10 {
XCTAssertNoThrow(try EventLoopFuture<Void>.andAllComplete(Array(repeating: succeeded, count: i),
on: eventLoop).wait())
}
}
func testAndAllCompleteWithPreFailedFutures() {
struct Dummy: Error {}
let eventLoop = EmbeddedEventLoop()
let failed: EventLoopFuture<Void> = eventLoop.makeFailedFuture(Dummy())
for i in 0..<10 {
XCTAssertNoThrow(try EventLoopFuture<Void>.andAllComplete(Array(repeating: failed, count: i),
on: eventLoop).wait())
}
}
func testAndAllCompleteWithMixOfPreSuccededAndNotYetCompletedFutures() {
struct Dummy: Error {}
let eventLoop = EmbeddedEventLoop()
let succeeded = eventLoop.makeSucceededFuture(())
let incompletes = [eventLoop.makePromise(of: Void.self), eventLoop.makePromise(of: Void.self),
eventLoop.makePromise(of: Void.self), eventLoop.makePromise(of: Void.self),
eventLoop.makePromise(of: Void.self)]
var futures: [EventLoopFuture<Void>] = []
for i in 0..<10 {
if i % 2 == 0 {
futures.append(succeeded)
} else {
futures.append(incompletes[i/2].futureResult)
}
}
let overall = EventLoopFuture<Void>.andAllComplete(futures, on: eventLoop)
XCTAssertFalse(overall.isFulfilled)
for (idx, incomplete) in incompletes.enumerated() {
XCTAssertFalse(overall.isFulfilled)
if idx % 2 == 0 {
incomplete.succeed(())
} else {
incomplete.fail(Dummy())
}
}
XCTAssertNoThrow(try overall.wait())
}
func testWhenAllCompleteWithMixOfPreSuccededAndNotYetCompletedFutures() {
struct Dummy: Error {}
let eventLoop = EmbeddedEventLoop()
let succeeded = eventLoop.makeSucceededFuture(())
let incompletes = [eventLoop.makePromise(of: Void.self), eventLoop.makePromise(of: Void.self),
eventLoop.makePromise(of: Void.self), eventLoop.makePromise(of: Void.self),
eventLoop.makePromise(of: Void.self)]
var futures: [EventLoopFuture<Void>] = []
for i in 0..<10 {
if i % 2 == 0 {
futures.append(succeeded)
} else {
futures.append(incompletes[i/2].futureResult)
}
}
let overall = EventLoopFuture<Void>.whenAllComplete(futures, on: eventLoop)
XCTAssertFalse(overall.isFulfilled)
for (idx, incomplete) in incompletes.enumerated() {
XCTAssertFalse(overall.isFulfilled)
if idx % 2 == 0 {
incomplete.succeed(())
} else {
incomplete.fail(Dummy())
}
}
let expected: [Result<Void, Error>] = [.success(()), .success(()),
.success(()), .failure(Dummy()),
.success(()), .success(()),
.success(()), .failure(Dummy()),
.success(()), .success(())]
func assertIsEqual(_ expecteds: [Result<Void, Error>], _ actuals: [Result<Void, Error>]) {
XCTAssertEqual(expecteds.count, actuals.count, "counts not equal")
for i in expecteds.indices {
let expected = expecteds[i]
let actual = actuals[i]
switch (expected, actual) {
case (.success(()), .success(())):
()
case (.failure(let le), .failure(let re)):
XCTAssert(le is Dummy)
XCTAssert(re is Dummy)
default:
XCTFail("\(expecteds) and \(actuals) not equal")
}
}
}
XCTAssertNoThrow(assertIsEqual(expected, try overall.wait()))
}
func testRepeatedTaskOffEventLoopGroupFuture() throws {
let elg1: EventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try elg1.syncShutdownGracefully())
}
let elg2: EventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try elg2.syncShutdownGracefully())
}
let exitPromise: EventLoopPromise<Void> = elg1.next().makePromise()
var callNumber = 0
_ = elg1.next().scheduleRepeatedAsyncTask(initialDelay: .nanoseconds(0), delay: .nanoseconds(0)) { task in
struct Dummy: Error {}
callNumber += 1
switch callNumber {
case 1:
return elg2.next().makeSucceededFuture(())
case 2:
task.cancel(promise: exitPromise)
return elg2.next().makeFailedFuture(Dummy())
default:
XCTFail("shouldn't be called \(callNumber)")
return elg2.next().makeFailedFuture(Dummy())
}
}
try exitPromise.futureResult.wait()
}
func testEventLoopFutureOrErrorNoThrow() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(42)
promise.completeWith(result)
XCTAssertEqual(try promise.futureResult.unwrap(orError: EventLoopFutureTestError.example).wait(), 42)
}
func testEventLoopFutureOrThrows() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(nil)
promise.completeWith(result)
XCTAssertThrowsError(try _ = promise.futureResult.unwrap(orError: EventLoopFutureTestError.example).wait()) { (error) -> Void in
XCTAssertEqual(error as! EventLoopFutureTestError, EventLoopFutureTestError.example)
}
}
func testEventLoopFutureOrNoReplacement() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(42)
promise.completeWith(result)
XCTAssertEqual(try! promise.futureResult.unwrap(orReplace: 41).wait(), 42)
}
func testEventLoopFutureOrReplacement() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(nil)
promise.completeWith(result)
XCTAssertEqual(try! promise.futureResult.unwrap(orReplace: 42).wait(), 42)
}
func testEventLoopFutureOrNoElse() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(42)
promise.completeWith(result)
XCTAssertEqual(try! promise.futureResult.unwrap(orElse: { 41 } ).wait(), 42)
}
func testEventLoopFutureOrElse() {
let eventLoop = EmbeddedEventLoop()
let promise = eventLoop.makePromise(of: Int?.self)
let result: Result<Int?, Error> = .success(4)
promise.completeWith(result)
let x = 2
XCTAssertEqual(try! promise.futureResult.unwrap(orElse: { x * 2 } ).wait(), 4)
}
func testFlatBlockingMapOnto() {
let eventLoop = EmbeddedEventLoop()
let p = eventLoop.makePromise(of: String.self)
let sem = DispatchSemaphore(value: 0)
var blockingRan = false
var nonBlockingRan = false
p.futureResult.map {
$0.count
}.flatMapBlocking(onto: DispatchQueue.global()) { value -> Int in
sem.wait() // Block in chained EventLoopFuture
blockingRan = true
return 1 + value
}.whenSuccess {
XCTAssertEqual($0, 6)
XCTAssertTrue(blockingRan)
XCTAssertTrue(nonBlockingRan)
}
p.succeed("hello")
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testWhenSuccessBlocking() {
let eventLoop = EmbeddedEventLoop()
let sem = DispatchSemaphore(value: 0)
var nonBlockingRan = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.whenSuccessBlocking(onto: DispatchQueue.global()) {
sem.wait() // Block in callback
XCTAssertEqual($0, "hello")
XCTAssertTrue(nonBlockingRan)
}
p.succeed("hello")
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testWhenFailureBlocking() {
let eventLoop = EmbeddedEventLoop()
let sem = DispatchSemaphore(value: 0)
var nonBlockingRan = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.whenFailureBlocking (onto: DispatchQueue.global()) { err in
sem.wait() // Block in callback
XCTAssertEqual(err as! EventLoopFutureTestError, EventLoopFutureTestError.example)
XCTAssertTrue(nonBlockingRan)
}
p.fail(EventLoopFutureTestError.example)
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testWhenCompleteBlockingSuccess() {
let eventLoop = EmbeddedEventLoop()
let sem = DispatchSemaphore(value: 0)
var nonBlockingRan = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.whenCompleteBlocking (onto: DispatchQueue.global()) { _ in
sem.wait() // Block in callback
XCTAssertTrue(nonBlockingRan)
}
p.succeed("hello")
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testWhenCompleteBlockingFailure() {
let eventLoop = EmbeddedEventLoop()
let sem = DispatchSemaphore(value: 0)
var nonBlockingRan = false
let p = eventLoop.makePromise(of: String.self)
p.futureResult.whenCompleteBlocking (onto: DispatchQueue.global()) { _ in
sem.wait() // Block in callback
XCTAssertTrue(nonBlockingRan)
}
p.fail(EventLoopFutureTestError.example)
let p2 = eventLoop.makePromise(of: Bool.self)
p2.futureResult.whenSuccess { _ in
nonBlockingRan = true
}
p2.succeed(true)
sem.signal()
}
func testFlatMapWithEL() {
let el = EmbeddedEventLoop()
XCTAssertEqual(2,
try el.makeSucceededFuture(1).flatMapWithEventLoop { one, el2 in
XCTAssert(el === el2)
return el2.makeSucceededFuture(one + 1)
}.wait())
}
func testFlatMapErrorWithEL() {
let el = EmbeddedEventLoop()
struct E: Error {}
XCTAssertEqual(1,
try el.makeFailedFuture(E()).flatMapErrorWithEventLoop { error, el2 in
XCTAssert(error is E)
return el2.makeSucceededFuture(1)
}.wait())
}
func testFoldWithEL() {
let el = EmbeddedEventLoop()
let futures = (1...10).map { el.makeSucceededFuture($0) }
var calls = 0
let all = el.makeSucceededFuture(0).foldWithEventLoop(futures) { l, r, el2 in
calls += 1
XCTAssert(el === el2)
XCTAssertEqual(calls, r)
return el2.makeSucceededFuture(l + r)
}
XCTAssertEqual((1...10).reduce(0, +), try all.wait())
}
}
|
86841dc9c034ea629727a15f002131af
| 35.594396 | 136 | 0.570212 | false | true | false | false |
valitovaza/IntervalReminder
|
refs/heads/master
|
IntervalReminderTests/AppDelegateTests.swift
|
mit
|
1
|
import XCTest
@testable import IntervalReminder
class AppDelegateTests: XCTestCase {
// MARK: - Test variables
private var sut: AppDelegate!
// MARK: - Set up and tear down
override func setUp() {
super.setUp()
sut = AppDelegate()
}
override func tearDown() {
sut = nil
super.tearDown()
}
// MARK: - Tests
func testHasConfigurator() {
XCTAssertNotNil(sut.configurator)
}
func testTheAppWasConfiguredInApplicationDidFinishLaunching() {
let mock = MockConfigurator()
sut.configurator = mock
sut.applicationDidFinishLaunching(Notification(name: NSNotification.Name.NSApplicationDidFinishLaunching))
XCTAssertTrue(mock.configureWasInvoked)
}
}
extension AppDelegateTests {
class MockConfigurator: Configurator{
var configureWasInvoked = false
func configure() {
configureWasInvoked = true
}
}
}
|
288bc53f7e712d5dfd914fc2fd88034e
| 26.571429 | 114 | 0.65285 | false | true | false | false |
ivygulch/IVGRouter
|
refs/heads/master
|
IVGRouterTests/tests/router/RouterHistorySpec.swift
|
mit
|
1
|
//
// RouterHistorySpec.swift
// IVGRouter
//
// Created by Douglas Sjoquist on 7/24/16.
// Copyright © 2016 Ivy Gulch LLC. All rights reserved.
//
import UIKit
import Quick
import Nimble
@testable import IVGRouter
class RouterHistorySpec: QuickSpec {
override func spec() {
describe("Router") {
let mockRouteHistoryItemA = RouteHistoryItem(routeSequence: RouteSequence(source: ["A"]), title: "title A")
let mockRouteHistoryItemB = RouteHistoryItem(routeSequence: RouteSequence(source: ["B"]), title: "title B")
let mockRouteHistoryItemC = RouteHistoryItem(routeSequence: RouteSequence(source: ["C"]), title: "title C")
let mockRouteHistoryItemD = RouteHistoryItem(routeSequence: RouteSequence(source: ["D"]), title: "title D")
let mockRouteHistoryItemE = RouteHistoryItem(routeSequence: RouteSequence(source: ["E"]), title: "title E")
var routerHistory: RouterHistory!
beforeEach {
routerHistory = RouterHistory(historySize: 10)
}
context("when initialized") {
it("should return nil for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem).to(beNil())
}
}
context("after moving forward one step") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
}
it("should return nil for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem).to(beNil())
}
}
context("after moving forward two steps") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
}
it("should return A for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem as? RouteHistoryItem).to(equal(mockRouteHistoryItemA))
}
}
context("after moving forward two steps, then back one") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
routerHistory.moveBackward()
}
it("should return nil for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem).to(beNil())
}
}
context("after moving forward three steps, then back one") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemC, ignoreDuplicates: false)
routerHistory.moveBackward()
}
it("should return A for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem as? RouteHistoryItem).to(equal(mockRouteHistoryItemA))
}
}
context("after moving forward four steps, then back two, then forward with same as before") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemC, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemD, ignoreDuplicates: false)
routerHistory.moveBackward()
routerHistory.moveBackward()
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemC, ignoreDuplicates: false)
}
it("should return B for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem as? RouteHistoryItem).to(equal(mockRouteHistoryItemB))
}
}
context("after moving forward four steps, then back two, then forward with different from before") {
beforeEach {
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemA, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemB, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemC, ignoreDuplicates: false)
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemD, ignoreDuplicates: false)
routerHistory.moveBackward()
routerHistory.moveBackward()
routerHistory.recordRouteHistoryItem(mockRouteHistoryItemE, ignoreDuplicates: false)
}
it("should return B for previousRouteHistoryItem") {
expect(routerHistory.previousRouteHistoryItem as? RouteHistoryItem).to(equal(mockRouteHistoryItemB))
}
}
}
}
}
|
07775f395aaafe89fd6efa38693b0778
| 40.886364 | 120 | 0.623802 | false | false | false | false |
wireapp/wire-ios-data-model
|
refs/heads/develop
|
Source/Utilis/CryptoBox.swift
|
gpl-3.0
|
1
|
//
// 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 WireCryptobox
extension NSManagedObjectContext {
fileprivate static let ZMUserClientKeysStoreKey = "ZMUserClientKeysStore"
@objc(setupUserKeyStoreInAccountDirectory:applicationContainer:)
public func setupUserKeyStore(accountDirectory: URL, applicationContainer: URL) {
if !self.zm_isSyncContext {
fatal("Can't initiliazie crypto box on non-sync context")
}
let newKeyStore = UserClientKeysStore(accountDirectory: accountDirectory, applicationContainer: applicationContainer)
self.userInfo[NSManagedObjectContext.ZMUserClientKeysStoreKey] = newKeyStore
}
/// Returns the cryptobox instance associated with this managed object context
@objc public var zm_cryptKeyStore: UserClientKeysStore! {
if !self.zm_isSyncContext {
fatal("Can't access key store: Currently not on sync context")
}
let keyStore = self.userInfo.object(forKey: NSManagedObjectContext.ZMUserClientKeysStoreKey)
if let keyStore = keyStore as? UserClientKeysStore {
return keyStore
} else {
fatal("Can't access key store: not keystore found.")
}
}
@objc public func zm_tearDownCryptKeyStore() {
self.userInfo.removeObject(forKey: NSManagedObjectContext.ZMUserClientKeysStoreKey)
}
}
public extension FileManager {
@objc static let keyStoreFolderPrefix = "otr"
/// Returns the URL for the keyStore
@objc(keyStoreURLForAccountInDirectory:createParentIfNeeded:)
static func keyStoreURL(accountDirectory: URL, createParentIfNeeded: Bool) -> URL {
if createParentIfNeeded {
FileManager.default.createAndProtectDirectory(at: accountDirectory)
}
let keyStoreDirectory = accountDirectory.appendingPathComponent(FileManager.keyStoreFolderPrefix)
return keyStoreDirectory
}
}
public enum UserClientKeyStoreError: Error {
case canNotGeneratePreKeys
case preKeysCountNeedsToBePositive
}
/// A storage for cryptographic keys material
@objc(UserClientKeysStore) @objcMembers
open class UserClientKeysStore: NSObject {
/// Maximum possible ID for prekey
public static let MaxPreKeyID: UInt16 = UInt16.max-1
public var encryptionContext: EncryptionContext
/// Fallback prekeys (when no other prekey is available, this will always work)
fileprivate var internalLastPreKey: String?
/// Folder where the material is stored (managed by Cryptobox)
public private(set) var cryptoboxDirectory: URL
public private(set) var applicationContainer: URL
/// Loads new key store (if not present) or load an existing one
public init(accountDirectory: URL, applicationContainer: URL) {
self.cryptoboxDirectory = FileManager.keyStoreURL(accountDirectory: accountDirectory, createParentIfNeeded: true)
self.applicationContainer = applicationContainer
self.encryptionContext = UserClientKeysStore.setupContext(in: self.cryptoboxDirectory)!
}
private static func setupContext(in directory: URL) -> EncryptionContext? {
FileManager.default.createAndProtectDirectory(at: directory)
return EncryptionContext(path: directory)
}
open func deleteAndCreateNewBox() {
_ = try? FileManager.default.removeItem(at: cryptoboxDirectory)
self.encryptionContext = UserClientKeysStore.setupContext(in: cryptoboxDirectory)!
self.internalLastPreKey = nil
}
open func lastPreKey() throws -> String {
var error: NSError?
if internalLastPreKey == nil {
encryptionContext.perform({ [weak self] (sessionsDirectory) in
guard let strongSelf = self else { return }
do {
strongSelf.internalLastPreKey = try sessionsDirectory.generateLastPrekey()
} catch let anError as NSError {
error = anError
}
})
}
if let error = error {
throw error
}
return internalLastPreKey!
}
open func generateMoreKeys(_ count: UInt16 = 1, start: UInt16 = 0) throws -> [(id: UInt16, prekey: String)] {
if count > 0 {
var error: Error?
var newPreKeys : [(id: UInt16, prekey: String)] = []
let range = preKeysRange(count, start: start)
encryptionContext.perform({(sessionsDirectory) in
do {
newPreKeys = try sessionsDirectory.generatePrekeys(range)
if newPreKeys.count == 0 {
error = UserClientKeyStoreError.canNotGeneratePreKeys
}
}
catch let anError as NSError {
error = anError
}
})
if let error = error {
throw error
}
return newPreKeys
}
throw UserClientKeyStoreError.preKeysCountNeedsToBePositive
}
fileprivate func preKeysRange(_ count: UInt16, start: UInt16) -> CountableRange<UInt16> {
if start >= UserClientKeysStore.MaxPreKeyID-count {
return 0 ..< count
}
return start ..< (start + count)
}
}
|
0a7b9f6f954027d00d3a5a864bd60881
| 36.2375 | 125 | 0.670023 | false | false | false | false |
mmrmmlrr/ModelsTreeKit
|
refs/heads/master
|
ModelsTreeKit/Classes/UIKit/CollectionViewAdapter.swift
|
mit
|
1
|
//
// CollectionViewAdapter.swift
// ModelsTreeKit
//
// Created by aleksey on 06.12.15.
// Copyright © 2015 aleksey chernish. All rights reserved.
//
import Foundation
import UIKit
public class CollectionViewAdapter <ObjectType>: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
typealias DataSourceType = ObjectsDataSource<ObjectType>
typealias UpdateAction = (Void) -> Void
public var nibNameForObjectMatching: ((ObjectType, IndexPath) -> String)!
public var typeForSupplementaryViewOfKindMatching: ((String, IndexPath) -> UICollectionReusableView.Type)?
public var userInfoForCellSizeMatching: ((IndexPath) -> [String: AnyObject]?) = { _ in return nil }
public let didSelectCell = Pipe<(UICollectionViewCell, IndexPath, ObjectType)>()
public let willDisplayCell = Pipe<(UICollectionViewCell, IndexPath)>()
public let willCalculateSize = Pipe<(UICollectionViewCell, IndexPath)>()
public let didEndDisplayingCell = Pipe<(UICollectionViewCell, IndexPath)>()
public let willSetObject = Pipe<(UICollectionViewCell, IndexPath)>()
public let didSetObject = Pipe<(UICollectionViewCell, IndexPath)>()
public let didScroll = Pipe<UICollectionView>()
public let didEndDecelerating = Pipe<UICollectionView>()
public let didEndDragging = Pipe<UICollectionView>()
public let willEndDragging = Pipe<(UICollectionView, CGPoint, UnsafeMutablePointer<CGPoint>)>()
public let willDisplaySupplementaryView = Pipe<(UICollectionReusableView, String, IndexPath)>()
public let didEndDisplayingSupplementaryView = Pipe<(UICollectionReusableView, String, IndexPath)>()
public var checkedIndexPaths = [IndexPath]() {
didSet {
collectionView.indexPathsForVisibleItems.forEach {
if var checkable = collectionView.cellForItem(at: $0) as? Checkable {
checkable.checked = checkedIndexPaths.contains($0)
}
}
}
}
private weak var collectionView: UICollectionView!
private var dataSource: ObjectsDataSource<ObjectType>!
private var instances = [String: UICollectionViewCell]()
private var identifiersForIndexPaths = [IndexPath: String]()
private var mappings: [String: (ObjectType, UICollectionViewCell, IndexPath) -> Void] = [:]
private var updateActions = [UpdateAction]()
public init(dataSource: ObjectsDataSource<ObjectType>, collectionView: UICollectionView) {
super.init()
self.collectionView = collectionView
collectionView.dataSource = self
collectionView.delegate = self
self.dataSource = dataSource
dataSource.beginUpdatesSignal.subscribeNext { [weak self] in
self?.updateActions.removeAll()
}.putInto(pool)
dataSource.endUpdatesSignal.subscribeNext { [weak self] in
guard let strongSelf = self else { return }
strongSelf.updateActions.forEach { $0() }
}.putInto(pool)
dataSource.reloadDataSignal.subscribeNext { [weak self] in
guard let strongSelf = self else { return }
UIView.animate(withDuration: 0.1, animations: {
strongSelf.collectionView.alpha = 0},
completion: { completed in
strongSelf.collectionView.reloadData()
UIView.animate(withDuration: 0.2, animations: {
strongSelf.collectionView.alpha = 1
})
})
}.putInto(pool)
dataSource.didChangeObjectSignal.subscribeNext { [weak self] object, changeType, fromIndexPath, toIndexPath in
guard let strongSelf = self else {
return
}
switch changeType {
case .Insertion:
if let toIndexPath = toIndexPath {
strongSelf.updateActions.append() { [weak strongSelf] in
strongSelf?.collectionView.insertItems(at: [toIndexPath])
}
}
case .Deletion:
strongSelf.updateActions.append() { [weak strongSelf] in
if let fromIndexPath = fromIndexPath {
strongSelf?.collectionView.deleteItems(at: [fromIndexPath])
}
}
case .Update:
strongSelf.updateActions.append() { [weak strongSelf] in
if let indexPath = toIndexPath {
strongSelf?.collectionView.reloadItems(at: [indexPath])
}
}
case .Move:
strongSelf.updateActions.append() { [weak strongSelf] in
if let fromIndexPath = fromIndexPath, let toIndexPath = toIndexPath {
strongSelf?.collectionView.moveItem(at: fromIndexPath, to: toIndexPath)
}
}
}
}.putInto(pool)
dataSource.didChangeSectionSignal.subscribeNext { [weak self] changeType, fromIndex, toIndex in
guard let strongSelf = self else { return }
switch changeType {
case .Insertion:
strongSelf.updateActions.append() { [weak strongSelf] in
if let toIndex = toIndex {
strongSelf?.collectionView.insertSections(IndexSet(integer: toIndex))
}
}
case .Deletion:
if let fromIndex = fromIndex {
strongSelf.updateActions.append() { [weak strongSelf] in
strongSelf?.collectionView.deleteSections(IndexSet(integer: fromIndex))
}
}
default:
break
}
}.putInto(pool)
}
public func registerCellClass<U: ObjectConsuming>(_ cellClass: U.Type) where U.ObjectType == ObjectType {
let identifier = String(describing: cellClass)
let nib = UINib(nibName: identifier, bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: identifier)
instances[identifier] = nib.instantiate(withOwner: self, options: nil).last as? UICollectionViewCell
mappings[identifier] = { object, cell, _ in
if let consumer = cell as? U {
consumer.applyObject(object)
}
}
}
//UICollectionViewDataSource
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.numberOfSections()
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.numberOfObjectsInSection(section)
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let object = dataSource.objectAtIndexPath(indexPath)!;
let identifier = nibNameForObjectMatching(object, indexPath)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
identifiersForIndexPaths[indexPath] = identifier
willSetObject.sendNext((cell, indexPath))
let mapping = mappings[identifier]!
mapping(object, cell, indexPath)
didSetObject.sendNext((cell, indexPath))
return cell
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if var checkable = cell as? Checkable {
checkable.checked = checkedIndexPaths.contains(indexPath)
}
willDisplayCell.sendNext((cell, indexPath))
}
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let identifier = String(describing: typeForSupplementaryViewOfKindMatching!(kind, indexPath))
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath)
return view
}
public func collectiolnView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
didEndDisplayingCell.sendNext((cell, indexPath))
}
public func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
willDisplaySupplementaryView.sendNext((view, elementKind, indexPath))
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
didEndDisplayingSupplementaryView.sendNext((view, elementKind, indexPath))
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let identifier = nibNameForObjectMatching(dataSource.objectAtIndexPath(indexPath)!, indexPath)
if let cell = instances[identifier] as? SizeCalculatingCell {
willCalculateSize.sendNext((instances[identifier]!, indexPath))
return cell.size(forObject: dataSource.objectAtIndexPath(indexPath), userInfo: userInfoForCellSizeMatching(indexPath))
}
if let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout {
return flowLayout.itemSize
}
return CGSize.zero;
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
didScroll.sendNext(collectionView)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
didEndDecelerating.sendNext(collectionView)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
didEndDragging.sendNext(collectionView)
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
willEndDragging.sendNext((collectionView, velocity, targetContentOffset))
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
didSelectCell.sendNext((
collectionView.cellForItem(at: indexPath)!,
indexPath,
dataSource.objectAtIndexPath(indexPath)!)
)
}
}
|
351e008764cc64ab1e18d258793030ce
| 43.995885 | 197 | 0.647704 | false | false | false | false |
zerozheng/ZZQRCode
|
refs/heads/master
|
QRCode/ScanVC.swift
|
mit
|
1
|
//
// ScanVC.swift
// QRCode
//
// Created by zero on 17/2/7.
// Copyright © 2017年 zero. All rights reserved.
//
import UIKit
@objc protocol ScanVCDelegate: NSObjectProtocol {
func scanVC(vc:ScanVC, didFoundResult result: String)
}
class ScanVC: UIViewController {
weak var delegate: ScanVCDelegate?
var qrScaner: QRScaner?
override func viewDidLoad() {
super.viewDidLoad()
let qrScanView: QRScanView = QRScanView(frame: self.view.bounds)
self.qrScaner = QRScaner(view: qrScanView, didFoundResultHandle: { [unowned self] (string) in
let _ = self.navigationController?.popViewController(animated: true)
if let delegate = self.delegate, delegate.responds(to: #selector(ScanVCDelegate.scanVC(vc:didFoundResult:))) {
delegate.scanVC(vc: self, didFoundResult: string)
}
})
if let qrScaner = self.qrScaner {
self.view.addSubview(qrScanView)
qrScaner.startScanning()
}
}
}
|
ecb129cd977b025b6ea8f25114c726e5
| 24.880952 | 122 | 0.610856 | false | false | false | false |
mcgraw/dojo-pop-animation
|
refs/heads/master
|
dojo-pop-animation/XMCSpringViewController.swift
|
mit
|
1
|
//
// XMCSpringViewController.swift
// dojo-pop-animation
//
// Created by David McGraw on 1/14/15.
// Copyright (c) 2015 David McGraw. All rights reserved.
//
import UIKit
class XMCSpringViewController: UIViewController {
@IBOutlet weak var ballView: UIView!
@IBOutlet weak var ballCenterYConstraint: NSLayoutConstraint!
var bounciness: CGFloat = 8.0
var atTop = false
override func viewDidLoad() {
super.viewDidLoad()
ballView.layer.cornerRadius = ballView.frame.size.width/2
ballView.layer.masksToBounds = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
@IBAction func toggleActionPressed(sender: AnyObject) {
if atTop {
animateBottom()
} else {
animateTop()
}
atTop = !atTop
}
@IBAction func valueSlideChanged(sender: AnyObject) {
let slider = sender as UISlider
bounciness = CGFloat(slider.value)
}
func animateTop() {
let spring = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant)
spring.toValue = 200
spring.springBounciness = bounciness
spring.springSpeed = 8
ballCenterYConstraint.pop_addAnimation(spring, forKey: "moveUp")
}
func animateBottom() {
let spring = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant)
spring.toValue = -200
spring.springBounciness = bounciness
spring.springSpeed = 8
ballCenterYConstraint.pop_addAnimation(spring, forKey: "moveDown")
}
}
|
47474a04c95ce8eeaa5e9f04094b066c
| 25.629032 | 84 | 0.644458 | false | false | false | false |
samodom/TestSwagger
|
refs/heads/master
|
TestSwagger/Spying/SpyCoselectors.swift
|
mit
|
1
|
//
// SpyCoselectors.swift
// TestSwagger
//
// Created by Sam Odom on 2/19/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import FoundationSwagger
/// Convenience type used to create method surrogates for spying.
public struct SpyCoselectors {
let methodType: MethodType
let original: Selector
let spy: Selector
/// Creates a new spy co-selector.
/// - parameter methodType: The method type of the methods implemented by the selectors.
/// - parameter original: The selector of the original method defined by the root
/// spyable class that is spied upon.
/// - parameter spy: The selector of the spy method defined for the purposes of spying
/// on calls to the original method
public init(methodType: MethodType,
original: Selector,
spy: Selector) {
self.methodType = methodType
self.original = original
self.spy = spy
}
}
extension SpyCoselectors: Equatable {}
public func ==(lhs: SpyCoselectors, rhs: SpyCoselectors) -> Bool {
return lhs.methodType == rhs.methodType &&
lhs.original == rhs.original &&
lhs.spy == rhs.spy
}
extension SpyCoselectors: Hashable {
public var hashValue: Int {
return original.hashValue + spy.hashValue
}
}
|
7f0bb6d11f45fc578816474d1929f1b4
| 25.392157 | 92 | 0.64636 | false | false | false | false |
alienorb/Vectorized
|
refs/heads/master
|
Vectorized/Core/SVGGraphic.swift
|
mit
|
1
|
//---------------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Created by Austin Fitzpatrick on 3/19/15 (the "SwiftVG" project)
// Modified by Brian Christensen <[email protected]>
//
// Copyright (c) 2015 Seedling
// Copyright (c) 2016 Alien Orb Software LLC
//
// 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
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/// An SVGGraphic is used by a SVGView to display an SVG to the screen.
public class SVGGraphic: SVGGroup {
private(set) var size: CGSize //the size of the SVG's at "100%"
/// initializes an SVGGraphic with a list of drawables and a size
///
/// :param: drawables The list of drawables at the root level - can be nested
/// :param: size The size of the vector image at "100%"
/// :returns: An SVGGraphic ready for display in an SVGView
public init(drawables: [SVGDrawable], size: CGSize) {
self.size = size
super.init(drawables: drawables)
}
/// initializes an SVGGraphic with the contents of another SVGGraphic
///
/// :param: graphic another vector image to take the contents of
/// :returns: an SVGGraphic ready for display in an SVGView
public init(graphic: SVGGraphic) {
self.size = graphic.size
super.init(drawables: graphic.drawables)
}
/// Initializes an SVGGraphic with the contents of the file at the
/// given path
///
/// :param: path A file path to the SVG file
/// :returns: an SVGGraphic ready for display in an SVGView
public convenience init?(path: String) {
do {
if let parser = SVGParser(path: path) {
let (drawables, size) = try parser.coreParse()
self.init(drawables: drawables, size: size)
return
}
} catch {
print("The SVG parser encountered an error: \(error)")
return nil
}
return nil
}
/// Initializes an SVGGraphic with the data provided (should be an XML String)
///
/// :param: path A file path to the SVG file
/// :returns: an SVGGraphic ready for display in an SVGView
public convenience init?(data: NSData) {
do {
let (drawables, size) = try SVGParser(data: data).coreParse()
self.init(drawables: drawables, size: size)
} catch {
print("The SVG parser encountered an error: \(error)")
return nil
}
}
/// Optionally initialies an SVGGraphic with the given name in the main bundle
///
/// :param: name The name of the vector image file (without the .svg extension)
/// :returns: an SVGGraphic ready for display in an SVGView or nil if no svg exists
/// at the given path
public convenience init?(named name: String) {
if let path = NSBundle.mainBundle().pathForResource(name, ofType: "svg"), parser = SVGParser(path: path) {
do {
let graphic = try parser.parse()
self.init(graphic: graphic)
} catch {
print("The SVG parser encountered an error: \(error)")
return nil
}
return
}
return nil
}
/// Renders the vector image to a raster UIImage
///
/// :param: size the size of the UIImage to be returned
/// :param: contentMode the contentMode to use for rendering, some values may effect the output size
/// :returns: a UIImage containing a raster representation of the SVGGraphic
public func renderToImage(size size: CGSize, contentMode: SVGContentMode = .ScaleToFill) -> SVGImage {
let targetSize = sizeWithTargetSize(size, contentMode: contentMode)
let scale = scaleWithTargetSize(size, contentMode: contentMode)
let image: SVGImage
#if os(OSX)
let representation = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(targetSize.width), pixelsHigh: Int(targetSize.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)
image = NSImage(size: targetSize)
image.addRepresentation(representation!)
image.lockFocus()
#else
UIGraphicsBeginImageContext(targetSize)
#endif
let context = SVGGraphicsGetCurrentContext()
CGContextScaleCTM(context, scale.width, scale.height)
draw()
#if os(OSX)
image.unlockFocus()
#else
image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
#endif
return image
}
/// Returns the size of the vector image when scaled to fit in the size parameter using
/// the given content mode
///
/// :param: size The size to render at
/// :param: contentMode the contentMode to use for rendering
/// :returns: the size to render at
internal func sizeWithTargetSize(size: CGSize, contentMode: SVGContentMode) -> CGSize {
let targetSize = self.size
let bounds = size
switch contentMode {
case .ScaleAspectFit:
let scaleFactor = min(bounds.width / targetSize.width, bounds.height / targetSize.height)
let scale = CGSizeMake(scaleFactor, scaleFactor)
return CGSize(width: targetSize.width * scale.width, height: targetSize.height * scale.height)
case .ScaleAspectFill:
let scaleFactor = max(bounds.width / targetSize.width, bounds.height / targetSize.height)
let scale = CGSizeMake(scaleFactor, scaleFactor)
return CGSize(width: targetSize.width * scale.width, height: targetSize.height * scale.height)
case .ScaleToFill:
return size
case .Center:
return size
default:
return size
}
}
/// Returns the size of the translation to apply when rendering the SVG at the given size with the given contentMode
///
/// :param: size The size to render at
/// :param: contentMode the contentMode to use for rendering
/// :returns: the translation to apply when rendering
internal func translationWithTargetSize(size: CGSize, contentMode: SVGContentMode) -> CGPoint {
let targetSize = self.size
let bounds = size
var newSize: CGSize
switch contentMode {
case .ScaleAspectFit:
let scaleFactor = min(bounds.width / targetSize.width, bounds.height / targetSize.height)
let scale = CGSizeMake(scaleFactor, scaleFactor)
newSize = CGSize(width: targetSize.width * scale.width, height: targetSize.height * scale.height)
let xTranslation = (bounds.width - newSize.width) / 2.0
let yTranslation = (bounds.height - newSize.height) / 2.0
return CGPoint(x: xTranslation, y: yTranslation)
case .ScaleAspectFill:
let scaleFactor = max(bounds.width / targetSize.width, bounds.height / targetSize.height)
let scale = CGSizeMake(scaleFactor, scaleFactor)
newSize = CGSize(width: targetSize.width * scale.width, height: targetSize.height * scale.height)
let xTranslation = (bounds.width - newSize.width) / 2.0
let yTranslation = (bounds.height - newSize.height) / 2.0
return CGPoint(x: xTranslation, y: yTranslation)
case .ScaleToFill:
newSize = size
//??? WTF
//let scaleFactor = CGSize(width: bounds.width / targetSize.width, height: bounds.height / targetSize.height)
return CGPointZero
case .Center:
newSize = targetSize
let xTranslation = (bounds.width - newSize.width) / 2.0
let yTranslation = (bounds.height - newSize.height) / 2.0
return CGPoint(x: xTranslation, y: yTranslation)
default:
return CGPointZero
}
}
/// Returns the scale of the translation to apply when rendering the SVG at the given size with the given contentMode
///
/// :param: size The size to render at
/// :param: contentMode the contentMode to use for rendering
/// :returns: the scale to apply to the context when rendering
internal func scaleWithTargetSize(size: CGSize, contentMode: SVGContentMode) -> CGSize {
let targetSize = self.size
let bounds = size
switch contentMode {
case .ScaleAspectFit:
let scaleFactor = min(bounds.width / targetSize.width, bounds.height / targetSize.height)
return CGSizeMake(scaleFactor, scaleFactor)
case .ScaleAspectFill:
let scaleFactor = max(bounds.width / targetSize.width, bounds.height / targetSize.height)
return CGSizeMake(scaleFactor, scaleFactor)
case .ScaleToFill:
return CGSize(width:bounds.width / targetSize.width, height: bounds.height / targetSize.height)
case .Center:
return CGSize(width: 1, height: 1)
default:
return CGSize(width: 1, height: 1)
}
}
}
|
f55e19b89a740687c187d8aac968fea4
| 33.63197 | 280 | 0.704272 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS
|
refs/heads/master
|
source/Core/Classes/RSEnhancedTextScaleAnswerFormat.swift
|
apache-2.0
|
1
|
//
// RSEnhancedTextScaleAnswerFormat.swift
// Pods
//
// Created by James Kizer on 8/6/17.
//
//
import UIKit
import ResearchKit
open class RSEnhancedTextScaleAnswerFormat: ORKTextScaleAnswerFormat {
public let maxValueLabel: String?
public let minValueLabel: String?
public let maximumValueDescription: String?
public let neutralValueDescription: String?
public let minimumValueDescription: String?
public let valueLabelHeight: Int?
public init(
textChoices: [ORKTextChoice],
defaultIndex: Int,
vertical: Bool,
maxValueLabel: String?,
minValueLabel: String?,
maximumValueDescription: String?,
neutralValueDescription: String?,
minimumValueDescription: String?,
valueLabelHeight: Int?
) {
self.maxValueLabel = maxValueLabel
self.minValueLabel = minValueLabel
self.maximumValueDescription = maximumValueDescription
self.neutralValueDescription = neutralValueDescription
self.minimumValueDescription = minimumValueDescription
self.valueLabelHeight = valueLabelHeight
super.init(textChoices: textChoices, defaultIndex: defaultIndex, vertical: vertical)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
5c857572df097e4b6dff889402a36bcc
| 28.913043 | 92 | 0.694041 | false | false | false | false |
nickplee/A-E-S-T-H-E-T-I-C-A-M
|
refs/heads/master
|
Aestheticam/Sources/Other Sources/ImageDownloader.swift
|
mit
|
1
|
//
// ImageDownloader.swift
// A E S T H E T I C A M
//
// Created by Nick Lee on 5/21/16.
// Copyright © 2016 Nick Lee. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireImage
import RealmSwift
import RandomKit
final class ImageDownloader {
// MARK: Singleton
static let sharedInstance = ImageDownloader()
// MARK: Private Properties
private static let saveQueue = DispatchQueue(label: "com.nicholasleedesigns.aestheticam.save", attributes: [])
// MARK: Initialiaztion
private init() {}
// MARK: DB
private class func ImageRealm() throws -> Realm {
let folder = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as NSString
let realmPath = folder.appendingPathComponent("data.realm")
var realmURL = URL(fileURLWithPath: realmPath)
var config = Realm.Configuration()
config.fileURL = realmURL
let realm = try Realm(configuration: config)
defer {
do {
var values = URLResourceValues()
values.isExcludedFromBackup = true
try realmURL.setResourceValues(values)
}
catch {}
}
return realm
}
// MARK: Download
func download() {
guard Globals.needsDownload else {
return
}
let url = Globals.apiURL
request(url).responseJSON { result in
guard let v = result.result.value as? [String: AnyObject], let images = v["images"] as? [String] else {
return
}
let urls = images.flatMap(URL.init(string:))
self.getImages(urls)
Globals.lastDownloadDate = Date()
}
}
private func getImages(_ urls: [URL]) {
let requests = urls.map({ request($0) })
requests.forEach {
$0.responseImage { result in
guard let image = result.result.value else {
return
}
ImageDownloader.saveQueue.async {
let realm = try! type(of: self).ImageRealm()
guard let data = UIImagePNGRepresentation(image) else {
return
}
do {
let urlString = result.request!.url!.absoluteString
let pred = NSPredicate(format: "%K = %@", argumentArray: ["url", urlString])
guard realm.objects(Image.self).filter(pred).first == nil else {
return
}
try realm.write {
let img = Image()
img.data = data
img.url = urlString
realm.add(img)
}
}
catch {}
}
}
}
}
// MARK: Random
func getRandomImage() -> UIImage? {
guard let realm = try? type(of: self).ImageRealm(), let entry = realm.objects(Image.self).random else {
return nil
}
return UIImage(data: entry.data)
}
}
|
080cbd64a708e97caf779d964cf83727
| 28.042017 | 115 | 0.481771 | false | false | false | false |
hilen/TSWeChat
|
refs/heads/master
|
TSWeChat/Classes/CoreModule/Models/TSModelTransformer.swift
|
mit
|
1
|
//
// TSModelTransformer.swift
// TSWeChat
//
// Created by Hilen on 2/22/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import ObjectMapper
//转换器:把 1423094023323 微秒时间转换成 几天前,几小时前
let TransformerTimestampToTimeAgo = TransformOf<String, NSNumber>(fromJSON: { (value: AnyObject?) -> String? in
guard let value = value else {
return ""
}
let seconds = Double(value as! NSNumber)/1000
let timeInterval: TimeInterval = TimeInterval(seconds)
let date = Date(timeIntervalSince1970: timeInterval)
let string = Date.messageAgoSinceDate(date)
return string
}, toJSON: { (value: String?) -> NSNumber? in
return nil
})
//把字符串转换为 Float
let TransformerStringToFloat = TransformOf<Float, String>(fromJSON: { (value: String?) -> Float? in
guard let value = value else {
return 0
}
let intValue: Float? = Float(value)
return intValue
}, toJSON: { (value: Float?) -> String? in
// transform value from Int? to String?
if let value = value {
return String(value)
}
return nil
})
//把字符串转换为 Int
let TransformerStringToInt = TransformOf<Int, String>(fromJSON: { (value: String?) -> Int? in
guard let value = value else {
return 0
}
let intValue: Int? = Int(value)
return intValue
}, toJSON: { (value: Int?) -> String? in
// transform value from Int? to String?
if let value = value {
return String(value)
}
return nil
})
//把字符串转换为 CGFloat
let TransformerStringToCGFloat = TransformOf<CGFloat, String>(fromJSON: { (value: String?) -> CGFloat? in
guard let value = value else {
return nil
}
let intValue: CGFloat? = CGFloat(Int(value)!)
return intValue
}, toJSON: { (value: CGFloat?) -> String? in
if let value = value {
return String(describing: value)
}
return nil
})
//数组的坐标转换为 CLLocation
let TransformerArrayToLocation = TransformOf<CLLocation, [Double]>(fromJSON: { (value: [Double]?) -> CLLocation? in
if let coordList = value, coordList.count == 2 {
return CLLocation(latitude: coordList[1], longitude: coordList[0])
}
return nil
}, toJSON: { (value: CLLocation?) -> [Double]? in
if let location = value {
return [Double(location.coordinate.longitude), Double(location.coordinate.latitude)]
}
return nil
})
|
077372ae3d4c74db1bb4fd46d088d12d
| 27.823529 | 115 | 0.628571 | false | false | false | false |
danielpi/Swift-Playgrounds
|
refs/heads/master
|
Swift-Playgrounds/The Swift Programming Language/LanguageGuide/01-TheBasics.playground/Contents.swift
|
mit
|
1
|
// The Basics Chapter of “The Swift Programming Language.” iBooks. https://itun.es/au/jEUH0.l
//: # The Basics
//: ## Constants and Variables
//: ### Declaring Constants and Variables
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
var x = 0.0, y = 0.0, z = 0.0
//: ### Type Annotations
var welcomeMessage: String
welcomeMessage = "Hello"
var red, green, blue: Double
//: ### Naming Constants and Variables
let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"
var friendlyWelcome = "Hello!"
friendlyWelcome = "Bonjour!"
let languageName = "Swift"
//languageName = "Swift++" // Compile time error
//: Printing Constants and Variables
print(friendlyWelcome)
print(π, 你好, 🐶🐮, separator: ", ", terminator: "")
print("The current value of friendlyWelcome is \(friendlyWelcome)")
//: ## Comments
// this is a comment
/* this is also a comment,
but written over multiple lines*/
/* this is the start of the first multiline comment
/* this is the second, nested multiline comment */
this is the end of the first multiline comment */
//: ## Semicolons
let cat = "🐱"; print(cat)
//: ## Integers
//: ### Integer Bounds
let minValue = UInt8.min
let maxValue = UInt8.max
//: ## Floating-Point Numbers
var w = [1, 1.2]
//: ## Type Safety and Type Inference
var meaningOfLife = 42
// inferred to be of type Int
// meaningOfLife = 35.0 //Type Error
let pi = 3.14159
let anotherPi = 3 + 0.14159
//: ## Numeric Literals
let descimalInteger = 17
let binaryInteger = 0b10001
let octalInteger = 0o21
let hexadecimalInteger = 0x11
//let hexFloat = 0x1234.0x5678
1.25e2
1.25e-2
0xFp2
0x8p4
let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecialDouble = 0xC.3p0
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
//: ## Numeric Conversion
//: ### Integer Conversion
//let cannotBeNegative: UInt8 = -1
//let tooBig: Int8 = Int8.max + 1
let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)
//: ### Integer and Floating Point Conversion
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi2 = Double(three) + pointOneFourOneFiveNine
let integerPi = Int(pi)
// Floats are always truncated when cast to Integers
let integerFourPointSeven = Int(4.75)
let integerNegativeThreePointNine = Int(-3.9)
// Literals can be cross type combined because they have no type until they are evaluated
3 + 0.14159
//: ## Type Aliases
// Type aliases are useful when you want to refer to an existing type by a name that is contextually more appropriate, such as when working with data of a specific size from an external source:
typealias AudioSample = UInt16
var macAmplitudeFound = AudioSample.min
//: ## Booleans
let orangesAreOrange = true
let turnipsAreDelicious = false
if turnipsAreDelicious {
print("Mmm, tasty turnips!")
} else {
print("Eww, turnips are horrible.")
}
// Non-Bool types can't be used for flow control
let i = 1
/*
if i {
}
*/
if i == 1 {
}
//: ## Tuples
let http404Error = (404, "Not Found")
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
print("The status message is \(statusMessage)")
// use _ if you don't want to decompose one of the values of a tuple
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// You can access the values of the tuple using index numbers
print("The status code is \(http404Error.0)")
print("The status message is \(http404Error.1)")
// You can name the elements of a tuple when it is defined
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")
print("The status message is \(http200Status.description)")
// “Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple. For more information”
//: ## Optionals
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be ot type "Int?" (optional Int)
// nil
var serverResponseCode: Int? = 404
serverResponseCode = nil
var surveyAnswer: String?
// surveyAnswer is automatically set to nil
// If statements and forced Unwrapping
if convertedNumber != nil {
print("convertedNumber contains some integer value.")
}
if convertedNumber != nil {
print("convertedNumber has an integer value of \(convertedNumber!)")
}
//: ### Optional Binding
if let actualNumber = Int(possibleNumber) {
print("\'\(possibleNumber)\' has a value of \(actualNumber)")
} else {
print("\'\(possibleNumber)\' could not be converted to an Int")
}
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
if let firstNumber = Int("4") {
if let secondNumber = Int("42") {
if firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
}
}
//: ### Implicitly Unwrapped Optionals
//: Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization
let possibleString: String? = "An optional string."
let forcedString: String = possibleString!
let assumedString: String! = "An implicitly unwrapped optional string"
let implicitString: String = assumedString
if assumedString != nil {
print(assumedString)
}
if let definiteString = assumedString {
print(definiteString)
}
//: Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.
//: ## Error Handling
//: In contrast to optionals, which can use the presence or absence of a value to signify success or failure of a function, error handling allows you to determine the underlying cause of failure and if necessary propagate the error to another part of your program.
func canThrowError() throws {
// This function may or may not throw an error.
}
do {
try canThrowError()
// no error was thrown
} catch {
// an error was thrown
}
enum SandwichError: Error {
case OutOfCleanDishes
case MissingIngredients([String])
}
func makeASandwich() throws {
throw SandwichError.MissingIngredients(["butter","ham","bread"])
}
func eatASandwich() {
print("yum yum yum")
}
func washDishes() {
print("Wash the dishes")
}
func buyGroceries(ingredients: [String]) {
ingredients.forEach{ i in print(i) }
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.OutOfCleanDishes {
washDishes()
} catch SandwichError.MissingIngredients(let ingredients) {
buyGroceries(ingredients: ingredients)
} catch {
print("Why did I fail")
}
//: ## Assertions and Preconditions
//: ### Debugging with Assertions
//: Use an assertion whenever a condition has the potential to be false, but must definitely be true in order for your code to continue execution.
let age = -3
//assert(age >= 0, "A person's age cannot be less than zero")
// Left this out as it stops the REPL from continuing
//: ### Enforcing Preconditions
var index = -3
precondition(index > 0, "Index must be greater than zero.")
|
e2eb173e9f708861042b4cf25f1c8c7a
| 26.806569 | 296 | 0.720173 | false | false | false | false |
box/box-ios-sdk
|
refs/heads/main
|
Tests/Modules/SearchModuleSpecs.swift
|
apache-2.0
|
1
|
//
// SearchModuleSpecs
// BoxSDK
//
// Created by Matt Willer on 5/3/2019.
// Copyright © 2019 Box. All rights reserved.
//
@testable import BoxSDK
import Nimble
import OHHTTPStubs
import Quick
class SearchModuleSpecs: QuickSpec {
var client: BoxClient!
override func spec() {
describe("SearchModule") {
beforeEach {
self.client = BoxSDK.getClient(token: "asdf")
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
context("query()") {
it("should make request with simple search query when only query is provided") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["query": "test"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let iterator = self.client.search.query(query: "test")
iterator.next { result in
switch result {
case let .success(page):
let item = page.entries[0]
guard case let .file(file) = item else {
fail("Expected test item to be a file")
done()
return
}
expect(file).toNot(beNil())
expect(file.id).to(equal("11111"))
expect(file.name).to(equal("test file.txt"))
expect(file.description).to(equal(""))
expect(file.size).to(equal(16))
case let .failure(error):
fail("Expected search request to succeed, but it failed: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with greater than relation") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"global\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"date\":{\"gt\":\"2019-07-24T12:00:00Z\"}}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "date", fieldValue: "2019-07-24T12:00:00Z", scope: MetadataScope.global, relation: MetadataFilterBound.greaterThan)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with less than relation") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"enterprise\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"date\":{\"lt\":\"2019-07-24T12:00:00Z\"}}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "date", fieldValue: "2019-07-24T12:00:00Z", scope: MetadataScope.enterprise, relation: MetadataFilterBound.lessThan)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with enterprise scope.") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"enterprise\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"documentType\":\"dataSheet\"}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "documentType", fieldValue: "dataSheet", scope: MetadataScope.enterprise)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with global scope.") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"global\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"documentType\":\"dataSheet\"}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "documentType", fieldValue: "dataSheet", scope: MetadataScope.global)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with query parameters populated when optional parameters are provided") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams([
"query": "test",
"scope": "user_content",
"file_extensions": "pdf,docx",
"created_at_range": "2019-05-15T21:52:15Z,2019-05-15T21:53:00Z",
"updated_at_range": "2019-05-15T21:53:27Z,2019-05-15T21:53:44Z",
"size_range": "1024,4096",
"owner_user_ids": "11111,22222",
"ancestor_folder_ids": "33333,44444",
"content_types": "name,description,comments,file_content,tags",
"type": "file",
"trash_content": "non_trashed_only"
])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let iterator = self.client.search.query(
query: "test",
scope: .user,
fileExtensions: ["pdf", "docx"],
createdAfter: Date(timeIntervalSince1970: 1_557_957_135), // 2019-05-15T21:52:15Z
createdBefore: Date(timeIntervalSince1970: 1_557_957_180), // 2019-05-15T21:53:00Z
updatedAfter: Date(timeIntervalSince1970: 1_557_957_207), // 2019-05-15T21:53:27Z
updatedBefore: Date(timeIntervalSince1970: 1_557_957_224), // 2019-05-15T21:53:44Z
sizeAtLeast: 1024,
sizeAtMost: 4096,
ownerUserIDs: ["11111", "22222"],
ancestorFolderIDs: ["33333", "44444"],
searchIn: [.name, .description, .comments, .fileContents, .tags],
itemType: .file,
searchTrash: false
)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Expected request to succeed, but instead got \(error)")
}
done()
}
}
}
}
context("queryWithSharedLinks()") {
it("should make request with simple search query and shared links query parameter when only query is provided") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams([
"query": "test",
"created_at_range": "2019-05-15T21:52:15Z,2019-05-15T21:53:00Z",
"updated_at_range": "2019-05-15T21:53:27Z,2019-05-15T21:53:44Z",
"size_range": "1024,4096",
"include_recent_shared_links": "true"
])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("SearchResult200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let iterator = self.client.search.queryWithSharedLinks(
query: "test",
createdAfter: Date(timeIntervalSince1970: 1_557_957_135), // 2019-05-15T21:52:15Z
createdBefore: Date(timeIntervalSince1970: 1_557_957_180), // 2019-05-15T21:53:00Z
updatedAfter: Date(timeIntervalSince1970: 1_557_957_207), // 2019-05-15T21:53:27Z
updatedBefore: Date(timeIntervalSince1970: 1_557_957_224), // 2019-05-15T21:53:44Z
sizeAtLeast: 1024,
sizeAtMost: 4096
)
iterator.next { result in
switch result {
case let .success(page):
let searchResult = page.entries[0]
let item = searchResult.item
guard case let .file(file) = item else {
fail("Expected test item to be a file")
done()
return
}
expect(file).toNot(beNil())
expect(file.id).to(equal("11111"))
expect(file.name).to(equal("test file.txt"))
expect(file.description).to(equal(""))
expect(file.size).to(equal(16))
expect(searchResult.accessibleViaSharedLink?.absoluteString).to(equal("https://www.box.com/s/vspke7y05sb214wjokpk"))
case let .failure(error):
fail("Expected search request to succeed, but it failed: \(error)")
}
done()
}
}
}
}
context("SearchScope") {
describe("init()") {
it("should correctly create an enum value from it's string representation") {
expect(SearchScope.user).to(equal(SearchScope(SearchScope.user.description)))
expect(SearchScope.enterprise).to(equal(SearchScope(SearchScope.enterprise.description)))
expect(SearchScope.customValue("custom value")).to(equal(SearchScope("custom value")))
}
}
}
context("SearchContentType") {
describe("init()") {
it("should correctly create an enum value from it's string representation") {
expect(SearchContentType.name).to(equal(SearchContentType(SearchContentType.name.description)))
expect(SearchContentType.description).to(equal(SearchContentType(SearchContentType.description.description)))
expect(SearchContentType.fileContents).to(equal(SearchContentType(SearchContentType.fileContents.description)))
expect(SearchContentType.comments).to(equal(SearchContentType(SearchContentType.comments.description)))
expect(SearchContentType.tags).to(equal(SearchContentType(SearchContentType.tags.description)))
expect(SearchContentType.customValue("custom value")).to(equal(SearchContentType("custom value")))
}
}
}
context("SearchItemType") {
describe("init()") {
it("should correctly create an enum value from it's string representation") {
expect(SearchItemType.file).to(equal(SearchItemType(SearchItemType.file.description)))
expect(SearchItemType.folder).to(equal(SearchItemType(SearchItemType.folder.description)))
expect(SearchItemType.webLink).to(equal(SearchItemType(SearchItemType.webLink.description)))
expect(SearchItemType.customValue("custom value")).to(equal(SearchItemType("custom value")))
}
}
}
}
}
}
|
0a6652163b9858e6c0ae14a3959a4751
| 50.93617 | 209 | 0.43536 | false | false | false | false |
grpc/grpc-swift
|
refs/heads/main
|
Sources/GRPC/Compression/MessageEncoding.swift
|
apache-2.0
|
1
|
/*
* Copyright 2020, gRPC Authors 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.
*/
/// Whether compression should be enabled for the message.
public struct Compression: Hashable, GRPCSendable {
@usableFromInline
internal enum _Wrapped: Hashable, GRPCSendable {
case enabled
case disabled
case deferToCallDefault
}
@usableFromInline
internal var _wrapped: _Wrapped
private init(_ wrapped: _Wrapped) {
self._wrapped = wrapped
}
/// Enable compression. Note that this will be ignored if compression has not been enabled or is
/// not supported on the call.
public static let enabled = Compression(.enabled)
/// Disable compression.
public static let disabled = Compression(.disabled)
/// Defer to the call (the ``CallOptions`` for the client, and the context for the server) to
/// determine whether compression should be used for the message.
public static let deferToCallDefault = Compression(.deferToCallDefault)
}
extension Compression {
@inlinable
internal func isEnabled(callDefault: Bool) -> Bool {
switch self._wrapped {
case .enabled:
return callDefault
case .disabled:
return false
case .deferToCallDefault:
return callDefault
}
}
}
/// Whether compression is enabled or disabled for a client.
public enum ClientMessageEncoding: GRPCSendable {
/// Compression is enabled with the given configuration.
case enabled(Configuration)
/// Compression is disabled.
case disabled
}
extension ClientMessageEncoding {
internal var enabledForRequests: Bool {
switch self {
case let .enabled(configuration):
return configuration.outbound != nil
case .disabled:
return false
}
}
}
extension ClientMessageEncoding {
public struct Configuration: GRPCSendable {
public init(
forRequests outbound: CompressionAlgorithm?,
acceptableForResponses inbound: [CompressionAlgorithm] = CompressionAlgorithm.all,
decompressionLimit: DecompressionLimit
) {
self.outbound = outbound
self.inbound = inbound
self.decompressionLimit = decompressionLimit
}
/// The compression algorithm used for outbound messages.
public var outbound: CompressionAlgorithm?
/// The set of compression algorithms advertised to the remote peer that they may use.
public var inbound: [CompressionAlgorithm]
/// The decompression limit acceptable for responses. RPCs which receive a message whose
/// decompressed size exceeds the limit will be cancelled.
public var decompressionLimit: DecompressionLimit
/// Accept all supported compression on responses, do not compress requests.
public static func responsesOnly(
acceptable: [CompressionAlgorithm] = CompressionAlgorithm.all,
decompressionLimit: DecompressionLimit
) -> Configuration {
return Configuration(
forRequests: .identity,
acceptableForResponses: acceptable,
decompressionLimit: decompressionLimit
)
}
internal var acceptEncodingHeader: String {
return self.inbound.map { $0.name }.joined(separator: ",")
}
}
}
/// Whether compression is enabled or disabled on the server.
public enum ServerMessageEncoding {
/// Compression is supported with this configuration.
case enabled(Configuration)
/// Compression is not enabled. However, 'identity' compression is still supported.
case disabled
@usableFromInline
internal var isEnabled: Bool {
switch self {
case .enabled:
return true
case .disabled:
return false
}
}
}
extension ServerMessageEncoding {
public struct Configuration {
/// The set of compression algorithms advertised that we will accept from clients for requests.
/// Note that clients may send us messages compressed with algorithms not included in this list;
/// if we support it then we still accept the message.
///
/// All cases of `CompressionAlgorithm` are supported.
public var enabledAlgorithms: [CompressionAlgorithm]
/// The decompression limit acceptable for requests. RPCs which receive a message whose
/// decompressed size exceeds the limit will be cancelled.
public var decompressionLimit: DecompressionLimit
/// Create a configuration for server message encoding.
///
/// - Parameters:
/// - enabledAlgorithms: The list of algorithms which are enabled.
/// - decompressionLimit: Decompression limit acceptable for requests.
public init(
enabledAlgorithms: [CompressionAlgorithm] = CompressionAlgorithm.all,
decompressionLimit: DecompressionLimit
) {
self.enabledAlgorithms = enabledAlgorithms
self.decompressionLimit = decompressionLimit
}
}
}
|
cb0f1f4ed553377ca3af0334f31e9753
| 31.555556 | 100 | 0.723929 | false | true | false | false |
VadimPavlov/Swifty
|
refs/heads/master
|
Sources/Swifty/Common/Foundation/Dictionary.swift
|
mit
|
1
|
//
// Collection.swift
// Created by Vadim Pavlov on 4/27/16.
import Foundation
public extension Dictionary {
init(_ pairs: [Element]) {
self.init()
for (k, v) in pairs {
self[k] = v
}
}
func mapPairs<OutKey: Hashable, OutValue>(_ transform: (Element) throws -> (OutKey, OutValue)) rethrows -> [OutKey: OutValue] {
return Dictionary<OutKey, OutValue>(try map(transform))
}
func mapKeys<OutKey: Hashable>(_ transform: @escaping (Key) -> OutKey) -> [OutKey : Value] {
return self.mapPairs { (transform($0), $1) }
}
func mapValues<OutValue>(_ transform: (Value) -> OutValue) -> [Key : OutValue] {
return self.mapPairs { ($0, transform($1)) }
}
func filterPairs(_ includeElement: (Element) throws -> Bool) rethrows -> [Key: Value] {
return Dictionary(try filter(includeElement))
}
}
public extension Dictionary where Value: Equatable {
func allKeys(forValue val: Value) -> [Key] {
return self.filter { $1 == val }.map { $0.0 }
}
}
// MARK: - Combining operators
public extension Dictionary {
static func +=(lhs: inout [Key: Value], rhs: [Key: Value]) {
rhs.forEach({ lhs[$0] = $1})
}
static func +(lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
var combined = lhs
combined += rhs
return combined
}
}
|
d01c3d7721c6c4eb4c969d0f57ccc453
| 27.02 | 131 | 0.581014 | false | false | false | false |
erikmartens/NearbyWeather
|
refs/heads/develop
|
NearbyWeather/Commons/Extensions/MKMapView+Focus.swift
|
mit
|
1
|
//
// MKMapView+Focus.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 05.03.22.
// Copyright © 2022 Erik Maximilian Martens. All rights reserved.
//
import MapKit.MKMapView
extension MKMapView {
func focus(onCoordinate coordinate: CLLocationCoordinate2D?, latitudinalMeters: CLLocationDistance = 1500, longitudinalMeters: CLLocationDistance = 1500, animated: Bool = false) {
guard let coordinate = coordinate else {
return
}
let region = MKCoordinateRegion(center: coordinate, latitudinalMeters: latitudinalMeters, longitudinalMeters: longitudinalMeters)
setRegion(region, animated: animated)
}
}
|
e9b891aaaa0a23ef0bf48bd5879163af
| 33.105263 | 181 | 0.757716 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.