repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wangyaqing/LeetCode-swift | Solutions/19. Remove Nth Node From End of List.playground/Contents.swift | 1 | 937 | import UIKit
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
class Solution {
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
let pre:ListNode? = ListNode(0)
pre?.next = head
var lastNode = pre
var nNode = pre
var count = -1
while lastNode != nil {
if count < n {
count += 1
} else {
nNode = nNode?.next
}
lastNode = lastNode?.next
}
nNode?.next = nNode?.next?.next
return pre?.next
}
}
var lastNode: ListNode?
for i in 0...0 {
let node = ListNode(i)
node.next = lastNode
lastNode = node
}
var node = Solution().removeNthFromEnd(lastNode, 1)
while node != nil {
print(node!.val)
node = node?.next
}
| mit | 765873f9aa1dcff75ccdafc90d89077c | 18.93617 | 69 | 0.510139 | 3.808943 | false | false | false | false |
malcommac/Hydra | Sources/Hydra/Promise+Timeout.swift | 1 | 2776 | /*
* Hydra
* Fullfeatured lightweight Promise & Await Library for Swift
*
* Created by: Daniele Margutti
* Email: hello@danielemargutti.com
* Web: http://www.danielemargutti.com
* Twitter: @danielemargutti
*
* Copyright © 2017 Daniele Margutti
*
*
* 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
public extension Promise {
/// Reject the receiving Promise if it does not resolve or reject after a given number of seconds
///
/// - Parameters:
/// - context: context in which the nextPromise will be executed (if not specified `background` is used)
/// - timeout: timeout expressed in seconds
/// - error: error to report, if nil `PromiseError.timeout` is used instead
/// - Returns: promise
func timeout(in context: Context? = nil, timeout: TimeInterval, error: Error? = nil) -> Promise<Value> {
let ctx = context ?? .background
let nextPromise = Promise<Value>(in: ctx, token: self.invalidationToken) { resolve, reject, operation in
// Dispatch the result of self promise to the nextPromise
// If self promise does not resolve or reject in given amount of time
// nextPromise is rejected with passed error or generic timeout error
// and any other result of the self promise is ignored
let timer = DispatchTimerWrapper(queue: ctx.queue)
timer.setEventHandler {
let errorToPass = (error ?? PromiseError.timeout)
reject(errorToPass)
}
timer.scheduleOneShot(deadline: .now() + timeout)
timer.resume()
// Observe resolve
self.add(onResolve: { v in
resolve(v) // resolve with value
timer.cancel() // cancel timeout timer and release promise
}, onReject: reject, onCancel: operation.cancel)
}
nextPromise.runBody()
self.runBody()
return nextPromise
}
}
| mit | 8970be790dd6a734dbcbbb430deff56e | 38.084507 | 107 | 0.736577 | 4.051095 | false | false | false | false |
rajmuhar/iosbridge-rottentomatoes | RottenTomatoesSwift/RottenTomatoesSwift/Downloader.swift | 7 | 1604 | //
// Downloader.swift
// RottenTomatoesSwift
//
// Created by Jeffrey Bergier on 9/12/15.
// Copyright © 2015 MobileBridge. All rights reserved.
//
import Foundation
protocol DownloaderDelegate: class {
func downloadFinishedForURL(finishedURL: NSURL)
}
class Downloader {
weak var delegate: DownloaderDelegate?
private let session: NSURLSession = {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
return NSURLSession(configuration: config)
}()
private var downloaded = [NSURL : NSData]()
func beginDownloadingURL(downloadURL: NSURL) {
self.session.dataTaskWithRequest(NSURLRequest(URL: downloadURL)) { (downloadedData, response, error) in
guard let downloadedData = downloadedData else {
NSLog("Downloader: Downloaded Data was NIL for URL: \(downloadURL)")
return
}
guard let response = response as? NSHTTPURLResponse else {
NSLog("Downloader: Response was not an HTTP Response for URL: \(downloadURL)")
return
}
switch response.statusCode {
case 200:
self.downloaded[downloadURL] = downloadedData
self.delegate?.downloadFinishedForURL(downloadURL)
default:
NSLog("Downloader: Received Response Code: \(response.statusCode) for URL: \(downloadURL)")
}
}.resume()
}
func dataForURL(requestURL: NSURL) -> NSData? {
return self.downloaded[requestURL]
}
}
| mit | 00add93a3b347e4a0b27f0d6c32831b7 | 31.06 | 111 | 0.623206 | 5.307947 | false | true | false | false |
barteljan/VISPER | Example/VISPER-Wireframe-Tests/Mocks/MockRoutingHandlerContainer.swift | 1 | 2505 | //
// MockRoutingHandlerContainer.swift
// VISPER-Wireframe_Example
//
// Created by bartel on 02.12.17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import VISPER_Wireframe
import VISPER_Core
class MockRoutingHandlerContainer: NSObject, RoutingHandlerContainer {
var invokedAdd = false
var invokedAddCount = 0
var invokedAddParameters: (priority: Int, Void)?
var invokedAddResponsibleForParam: ((_ routeResult: RouteResult) -> Bool)?
var invokedAddHandlerParam: ((_ routeResult: RouteResult) -> Void)?
var invokedAddParametersList = [(priority: Int, Void)]()
var stubbedAddResponsibleForResult: (RouteResult, Void)?
var stubbedAddHandlerResult: (RouteResult, Void)?
func add(priority: Int, responsibleFor: @escaping (_ routeResult: RouteResult) -> Bool, handler: @escaping RoutingHandler) {
invokedAdd = true
invokedAddCount += 1
invokedAddResponsibleForParam = responsibleFor
invokedAddHandlerParam = handler
invokedAddParameters = (priority, ())
invokedAddParametersList.append((priority, ()))
}
var invokedPriorityOfHighestResponsibleProvider = false
var invokedPriorityOfHighestResponsibleProviderCount = 0
var invokedPriorityOfHighestResponsibleProviderParameters: (routeResult: RouteResult, Void)?
var invokedPriorityOfHighestResponsibleProviderParametersList = [(routeResult: RouteResult, Void)]()
var stubbedPriorityOfHighestResponsibleProviderResult: Int!
func priorityOfHighestResponsibleProvider(routeResult: RouteResult) -> Int? {
invokedPriorityOfHighestResponsibleProvider = true
invokedPriorityOfHighestResponsibleProviderCount += 1
invokedPriorityOfHighestResponsibleProviderParameters = (routeResult, ())
invokedPriorityOfHighestResponsibleProviderParametersList.append((routeResult, ()))
return stubbedPriorityOfHighestResponsibleProviderResult
}
var invokedHandler = false
var invokedHandlerCount = 0
var invokedHandlerParameters: (routeResult: RouteResult, Void)?
var invokedHandlerParametersList = [(routeResult: RouteResult, Void)]()
var stubbedHandlerResult: (RoutingHandler)!
func handler(routeResult: RouteResult) -> RoutingHandler? {
invokedHandler = true
invokedHandlerCount += 1
invokedHandlerParameters = (routeResult, ())
invokedHandlerParametersList.append((routeResult, ()))
return stubbedHandlerResult
}
}
| mit | 92d301d4820c6a69c5a80541b6780821 | 40.733333 | 128 | 0.748003 | 5.260504 | false | false | false | false |
dflax/Anagrams | Anagrams/TileView.swift | 1 | 2895 | //
// TileView.swift
// Anagrams
//
// Created by Daniel Flax on 4/29/15.
// Copyright (c) 2015 Caroline. All rights reserved.
//
import UIKit
// Delegate protocol to inform Game Controller that tile has dropped.
protocol TileDragDelegateProtocol {
func tileView(tileView: TileView, didDragToPoint: CGPoint)
}
//1
class TileView:UIImageView {
// Touch Offsets
private var xOffset: CGFloat = 0.0
private var yOffset: CGFloat = 0.0
//2
var letter: Character
//3
var isMatched: Bool = false
// Delegate protocol property
var dragDelegate: TileDragDelegateProtocol?
// 4 this should never be called
required init(coder aDecoder:NSCoder) {
fatalError("use init(letter:, sideLength:")
}
//5 create a new tile for a given letter
init(letter:Character, sideLength:CGFloat) {
self.letter = letter
// the tile background
let image = UIImage(named: "tile")!
// superclass initializer
// references to superview's "self" must take place after super.init
super.init(image:image)
// Enable touch movement
self.userInteractionEnabled = true
// 6 resize the tile
let scale = sideLength / image.size.width
self.frame = CGRect(x: 0, y: 0, width: image.size.width * scale, height: image.size.height * scale)
//add a letter on top
let letterLabel = UILabel(frame: self.bounds)
letterLabel.textAlignment = NSTextAlignment.Center
letterLabel.textColor = UIColor.whiteColor()
letterLabel.backgroundColor = UIColor.clearColor()
letterLabel.text = String(letter).uppercaseString
letterLabel.font = UIFont(name: "Verdana-Bold", size: 78.0*scale)
self.addSubview(letterLabel)
}
// Generate randomness in the tiles
func randomize() {
// 1
// set random rotation of the tile
// anywhere between -0.2 and 0.3 radians
let rotation = CGFloat(randomNumber(minX:0, maxX:50)) / 100.0 - 0.2
self.transform = CGAffineTransformMakeRotation(rotation)
// 2
// move randomly up or down -10 to 0 points
let yOffset = CGFloat(randomNumber(minX: 0, maxX: TileYOffset) - Int(TileYOffset))
self.center = CGPointMake(self.center.x, self.center.y + yOffset)
}
//1
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches.first as? UITouch {
let point = touch.locationInView(self.superview)
xOffset = point.x - self.center.x
yOffset = point.y - self.center.y
}
}
//2
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches.first as? UITouch {
let point = touch.locationInView(self.superview)
self.center = CGPointMake(point.x - xOffset, point.y - yOffset)
}
}
//3
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
self.touchesMoved(touches, withEvent: event)
// Inform the delegate that the drag and drop has completed
dragDelegate?.tileView(self, didDragToPoint: self.center)
}
}
| mit | e6739246768cc4a621701902e615a743 | 26.056075 | 101 | 0.720898 | 3.560886 | false | false | false | false |
xu6148152/binea_project_for_ios | ListerforAppleWatchiOSandOSX/Swift/ListerOSX/AppDelegate.swift | 1 | 2899 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The application delegate.
*/
import Cocoa
import ListerKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: Properties
@IBOutlet weak var todayListMenuItem: NSMenuItem!
var ubiquityIdentityDidChangeNotificationToken: NSObjectProtocol?
// MARK: NSApplicationDelegate
func applicationDidFinishLaunching(notification: NSNotification) {
AppConfiguration.sharedConfiguration.runHandlerOnFirstLaunch {
// If iCloud is enabled and it's the first launch, we'll show the Today document initially.
if AppConfiguration.sharedConfiguration.isCloudAvailable {
// Make sure that no other documents are visible except for the Today document.
NSDocumentController.sharedDocumentController().closeAllDocumentsWithDelegate(nil, didCloseAllSelector: nil, contextInfo: nil)
self.openTodayDocument()
}
}
// Update the menu item at app launch.
updateTodayListMenuItemForCloudAvailability()
ubiquityIdentityDidChangeNotificationToken = NSNotificationCenter.defaultCenter().addObserverForName(NSUbiquityIdentityDidChangeNotification, object: nil, queue: nil) { [weak self] _ in
// Update the menu item once the iCloud account changes.
self?.updateTodayListMenuItemForCloudAvailability()
return
}
}
// MARK: IBActions
/**
Note that there are two possibile callers for this method. The first is the application delegate if
it's the first launch. The other possibility is if you use the keyboard shortcut (Command-T) to open
your Today document.
*/
@IBAction func openTodayDocument(_: AnyObject? = nil) {
TodayListManager.fetchTodayDocumentURLWithCompletionHandler { url in
if let url = url {
dispatch_async(dispatch_get_main_queue()) {
let documentController = NSDocumentController.sharedDocumentController() as NSDocumentController
documentController.openDocumentWithContentsOfURL(url, display: true) { _ in
// Configuration of the document can go here...
}
}
}
}
}
// MARK: Convenience
func updateTodayListMenuItemForCloudAvailability() {
if AppConfiguration.sharedConfiguration.isCloudAvailable {
todayListMenuItem.action = "openTodayDocument:"
todayListMenuItem.target = self
}
else {
todayListMenuItem.action = nil
todayListMenuItem.target = nil
}
}
}
| mit | bbfb45544f2c692de87a86f4619f5d03 | 35.670886 | 193 | 0.645841 | 5.852525 | false | true | false | false |
SuPair/firefox-ios | Client/Frontend/Browser/PrintHelper.swift | 16 | 968 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
class PrintHelper: TabContentScript {
fileprivate weak var tab: Tab?
class func name() -> String {
return "PrintHelper"
}
required init(tab: Tab) {
self.tab = tab
}
func scriptMessageHandlerName() -> String? {
return "printHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let tab = tab, let webView = tab.webView {
let printController = UIPrintInteractionController.shared
printController.printFormatter = webView.viewPrintFormatter()
printController.present(animated: true, completionHandler: nil)
}
}
}
| mpl-2.0 | 80699f12c188962494ada6ec2205d4f5 | 30.225806 | 132 | 0.683884 | 4.792079 | false | false | false | false |
codergaolf/DouYuTV | DouYuTV/DouYuTV/Classes/Tools/Extension/UIBarButtonItem-Extension.swift | 1 | 1357 | //
// UIBarButtonItem-Extension.swift
// DouYuTV
//
// Created by 高立发 on 2016/11/12.
// Copyright © 2016年 GG. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/*
class func creatItem(imgName : String, highLighted : String, size : CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named:imgName), for: .normal)
btn.setImage(UIImage(named:highLighted), for: .selected)
btn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return UIBarButtonItem(customView: btn)
}
*/
//便利构造函数 : 1>必须以convenience开头 2>在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imgName : String, highLighted : String = "", size : CGSize = CGSize.zero) {
//1,创建UIButton
let btn = UIButton()
//2,设置button图片
btn.setImage(UIImage(named:imgName), for: .normal)
if highLighted != "" {
btn.setImage(UIImage(named:highLighted), for: .selected)
}
//3,设置button尺寸
if size != CGSize.zero {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
} else {
btn.sizeToFit()
}
self.init(customView : btn)
}
}
| mit | f71783229e1b1930a55944b99bb123e3 | 26.478261 | 100 | 0.56962 | 3.95 | false | false | false | false |
Vadim-Yelagin/ImageLoading | ImageLoading/FadeInImageLoadingView.swift | 1 | 868 | //
// FadeInImageLoadingView.swift
//
// Created by Vadim Yelagin on 20/06/15.
// Copyright (c) 2015 Fueled. All rights reserved.
//
import Foundation
import UIKit
open class FadeInImageLoadingView: ImageLoadingView {
open override func transition(
from oldState: Task.State,
ofTask oldTask: Task?,
to newState: Task.State,
ofTask newTask: Task?)
{
var fade = false
if let oldTask = oldTask, let newTask = newTask , oldTask === newTask {
switch (oldState, newState) {
case (.loading, .success):
fade = true
default:
break
}
}
func callSuper() {
super.transition(from: oldState, ofTask: oldTask, to: newState, ofTask: newTask)
}
if fade {
UIView.transition(
with: self,
duration: 0.25,
options: .transitionCrossDissolve,
animations: callSuper,
completion: nil)
} else {
callSuper()
}
}
}
| mit | 4e2b93f5c0469775b47eb6d88e2e8507 | 20.170732 | 83 | 0.669355 | 3.214815 | false | false | false | false |
jm-schaeffer/JMWebImageView | JMWebImageView/JMWebImageView.swift | 1 | 5598 | //
// JMWebImageView.swift
// JMWebImageView
//
// Copyright (c) 2016 J.M. Schaeffer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class JMWebImageView: UIImageView {
private weak var loadingView: UIView?
weak var delegate: JMWebImageViewDelegate?
var url: NSURL? {
didSet {
if let oldValue = oldValue where oldValue != url {
WebImageDownloaderManager.sharedManager.cancel(oldValue, key: hashString)
}
if url == nil {
setState(.Initial)
} else if superview != nil {
load()
}
}
}
var useCache: Bool = true
var cacheDuration: NSTimeInterval = 86400 // 1 day
var placeholderImage: UIImage? // Displayed when the image cannot be loaded or if the url is set to nil
var hashString: String {
return String(ObjectIdentifier(self).uintValue)
}
private func load() {
guard let url = url else {
return
}
let size = max(bounds.width, bounds.height) * UIScreen.mainScreen().scale
let download = {
self.setState(.Loading)
WebImageDownloaderManager.sharedManager.request(url, key: self.hashString, size: size, useCache: self.useCache, cacheDuration: self.cacheDuration, completion: { error, image, progress in
self.setImage(image, animated: true)
})
}
if useCache {
WebImageCacheManager.imageForURL(url, size: size, cacheDuration: self.cacheDuration) { error, image in
if let image = image where error == nil {
self.setImage(image, animated: false)
} else {
download()
}
}
} else {
download()
}
}
private let dissolveAnimationDuration = 0.5
private func setImage(image: UIImage?, animated: Bool) {
delegate?.webImageView(self, willUpdateImage: animated, duration: dissolveAnimationDuration)
UIView.transitionWithView(
self,
duration: animated ? dissolveAnimationDuration : 0.0,
options: [.TransitionCrossDissolve],
animations: {
self.setState(.Complete, image: image)
},
completion: { finished in
self.delegate?.webImageView(self, didUpdateImage: animated)
})
}
// MARK: - State
private enum State {
case Initial
case Loading
case Complete
}
private func setState(state: State, image: UIImage? = nil) {
switch state {
case .Initial:
self.image = placeholderImage
layer.removeAllAnimations()
removeLoadingView()
case .Loading:
self.image = nil
layer.removeAllAnimations()
showLoadingView()
case .Complete:
removeLoadingView()
self.image = image ?? placeholderImage
if image == nil { // When the image couldn't be loaded we need to reset the url
url = nil
}
}
}
// MARK: - Loading View
private func showLoadingView() {
if loadingView == nil {
if let loadingView = loadLoadingView() {
loadingView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
loadingView.frame = CGRect(x: 0.0, y: 0.0, width: bounds.width, height: bounds.height)
addSubview(loadingView)
self.loadingView = loadingView
}
}
}
private func removeLoadingView() {
loadingView?.removeFromSuperview()
}
// MARK: - Methods that can be overriden
// Don't call the super implementation
func loadLoadingView() -> UIView? {
if bounds.width >= 30.0 && bounds.height >= 30.0 {
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
activityIndicatorView.startAnimating()
return activityIndicatorView
} else {
return nil
}
}
func setProgress(progress: Float) {
}
}
protocol JMWebImageViewDelegate: NSObjectProtocol {
func webImageView(webImageView: JMWebImageView, willUpdateImage animated: Bool, duration: NSTimeInterval)
func webImageView(webImageView: JMWebImageView, didUpdateImage animated: Bool)
}
| mit | e9473c2dc3a28834d7c2b6589b386f80 | 33.343558 | 198 | 0.605395 | 5.084469 | false | false | false | false |
RobotPajamas/ble113-ota-ios | ble113-ota/BaseBluetoothPeripheral.swift | 1 | 6238 | //
// BaseBluetoothPeripheral.swift
// ble113-ota
//
// Created by Suresh Joshi on 2016-06-13.
// Copyright © 2016 Robot Pajamas. All rights reserved.
//
import LGBluetooth
class BaseBluetoothPeripheral {
enum StandardServices {
static let deviceInformation: String = "180A";
}
enum StandardCharacteristics {
static let manufacturerModel: String = "2A24";
static let serialNumber: String = "2A25";
static let firmwareVersion: String = "2A26";
static let hardwareVersion: String = "2A27";
static let softwareVersion: String = "2A28";
static let manufacturerName: String = "2A29";
}
var peripheral: LGPeripheral!
var name: String?
var rssi: Int?
// Properties for the standard services
var manufacturerModel: String?
var serialNumber: String?
var firmwareRevision: String?
var hardwareRevision: String?
var softwareRevision: String?
var manufacturerName: String?
/**
* Constructor
* @param peripheral LGPeripheral instance representing this device
*/
init(fromPeripheral peripheral: LGPeripheral) {
self.peripheral = peripheral
self.name = self.peripheral.name
self.rssi = self.peripheral.RSSI
}
/**
* Determines if this peripheral is currently connected or not
*/
func isConnected() -> Bool {
return peripheral.cbPeripheral.state == .Connected
}
/**
* Opens connection with a timeout to this device
* @param timeout Timeout after which, connection will be closed (if it was in stage isConnecting)
* @param callback Will be called after connection success/failure
*/
func connect(withTimeout timeout: UInt, callback: (NSError!) -> Void) {
peripheral.connectWithTimeout(timeout, completion: callback)
}
/**
* Disconnects from device
* @param callback Will be called after disconnection success/failure
*/
func disconnect(callback: (NSError?) -> Void) {
peripheral.disconnectWithCompletion(callback)
}
/**
* Reads all standard BLE information from device (manufacturer, firmware, hardware, serial number, etc...)
* @param callback Will be called when all information is ready (or failed to gather data)
*/
func readDeviceInformation(callback: () -> Void) {
// Using RxSwift would be great to clean up this super messy nested block business...
// self.readSoftwareRevision({ <-- not implemented in firmawre
self.readManufacturerModel({
// self.readSerialNumber({
self.readFirmwareRevision({
self.readHardwareRevision({
self.readManufacturerName(callback)
})
})
// })
})
}
/**
* Read in the manufacturer name
* @param callback Will be called when the call returns with success or error
*/
private func readManufacturerName(callback: (() -> ())?) {
let cb: LGCharacteristicReadCallback = {
data, error in
self.manufacturerName = String(data: data, encoding: NSUTF8StringEncoding)
callback?()
}
LGUtils.readDataFromCharactUUID(StandardCharacteristics.manufacturerName, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb)
}
/**
* Read in the manufacturer model
* @param callback Will be called when the call returns with success or error
*/
private func readManufacturerModel(callback: (() -> ())?) {
let cb: LGCharacteristicReadCallback = {
data, error in
self.manufacturerModel = String(data: data, encoding: NSUTF8StringEncoding)
callback?()
}
LGUtils.readDataFromCharactUUID(StandardCharacteristics.manufacturerModel, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb)
}
/**
* Read in the hardware revision
* @param callback Will be called when the call returns with success or error
*/
private func readHardwareRevision(callback: (() -> ())?) {
let cb: LGCharacteristicReadCallback = {
data, error in
self.hardwareRevision = String(data: data, encoding: NSUTF8StringEncoding)
callback?()
}
LGUtils.readDataFromCharactUUID(StandardCharacteristics.hardwareVersion, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb)
}
/**
* Read in the firmware version
* @param callback Will be called when the call returns with success or error
*/
private func readFirmwareRevision(callback: (() -> ())?) {
let cb: LGCharacteristicReadCallback = {
data, error in
self.firmwareRevision = String(data: data, encoding: NSUTF8StringEncoding)
callback?()
}
LGUtils.readDataFromCharactUUID(StandardCharacteristics.firmwareVersion, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb)
}
/**
* Read in the software version
* @param callback Will be called when the call returns with success or error
*/
private func readSoftwareRevision(callback: (() -> ())?) {
let cb: LGCharacteristicReadCallback = {
data, error in
self.softwareRevision = String(data: data, encoding: NSUTF8StringEncoding)
callback?()
}
LGUtils.readDataFromCharactUUID(StandardCharacteristics.softwareVersion, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb)
}
/**
* Read in the serial number
* @param callback Will be called when the call returns with success or error
*/
private func readSerialNumber(callback: (() -> ())?) {
let cb: LGCharacteristicReadCallback = {
data, error in
self.serialNumber = String(data: data, encoding: NSUTF8StringEncoding)
callback?()
}
LGUtils.readDataFromCharactUUID(StandardCharacteristics.serialNumber, serviceUUID: StandardServices.deviceInformation, peripheral: peripheral, completion: cb)
}
}
| mit | 4f1886b57a347e726bc27720b4464f6f | 34.844828 | 171 | 0.65865 | 4.946075 | false | false | false | false |
justindaigle/grogapp-ios | GroGApp/GroGApp/DetailViewController.swift | 1 | 4637 | //
// DetailViewController.swift
// GroGApp
//
// Created by Justin Daigle on 3/26/15.
// Copyright (c) 2015 Justin Daigle (.com). All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet var displayNameLabel:UILabel!
@IBOutlet var userNameLabel:UILabel!
@IBOutlet var avaView:UIImageView!
@IBOutlet var statusesLabel:UILabel!
@IBOutlet var bioLabel:UILabel!
@IBOutlet var locLabel:UILabel!
@IBOutlet var blockButton:UIButton!
@IBOutlet var contentLabel:UITextView!
@IBOutlet var groupLabel:UILabel!
@IBOutlet var dateLabel:UILabel!
@IBOutlet var imgDetailIndicator:UIButton!
var statusId = -1
var username = ""
var blocked:Bool = false
var status:JSON!
var profile:JSON!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func blockUnblock() {
if (blocked) {
blockButton.setTitle("Block", forState: UIControlState.Normal)
blockButton.setTitle("Block", forState: UIControlState.Selected)
var defaults = NSUserDefaults.standardUserDefaults()
var lUsername = defaults.valueForKey("username") as! String
var password = defaults.valueForKey("password") as! String
DataMethods.Unblock(lUsername, password, username)
} else {
blockButton.setTitle("Unblock", forState: UIControlState.Normal)
blockButton.setTitle("Unblock", forState: UIControlState.Selected)
var defaults = NSUserDefaults.standardUserDefaults()
var lUsername = defaults.valueForKey("username") as! String
var password = defaults.valueForKey("password") as! String
DataMethods.Block(lUsername, password, username)
}
}
override func viewDidAppear(animated: Bool) {
var defaults = NSUserDefaults.standardUserDefaults()
var lUsername = defaults.valueForKey("username") as! String
var password = defaults.valueForKey("password") as! String
status = DataMethods.GetStatus(lUsername, password, statusId)
profile = DataMethods.GetProfile(username)
blocked = DataMethods.GetBlocked(lUsername, password, username)
if (blocked) {
blockButton.setTitle("Unblock", forState: UIControlState.Normal)
blockButton.setTitle("Unblock", forState: UIControlState.Selected)
} else {
blockButton.setTitle("Block", forState: UIControlState.Normal)
blockButton.setTitle("Block", forState: UIControlState.Selected)
}
displayNameLabel.text = profile["displayname"].stringValue
userNameLabel.text = "@" + profile["username"].stringValue
if (profile["avaurl"].stringValue != "") {
var avaUrl = NSURL(string:profile["avaurl"].stringValue)
if let avUrl = avaUrl {
var avaData = NSData(contentsOfURL: avUrl)
var img = UIImage(data: avaData!)!
avaView.image = UIImage(data: avaData!)
avaView.layer.cornerRadius = avaView.frame.size.width / 2
avaView.clipsToBounds = true
}
}
bioLabel.text = profile["bio"].stringValue
locLabel.text = profile["location"].stringValue
statusesLabel.text = profile["statusid"].stringValue
contentLabel.text = status["content"].stringValue
groupLabel.text = "posted to: " + status["group"].stringValue
dateLabel.text = status["time"].stringValue
// debug
println(status)
println(profile)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "iDetail") {
var dest = segue.destinationViewController as! ImageDetailTableViewController
dest.status = contentLabel.text!
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | ac2ef46ad82f28a6d4fc01ced50f1074 | 34.669231 | 106 | 0.634246 | 5.135105 | false | false | false | false |
BlurredSoftware/BSWInterfaceKit | Sources/BSWInterfaceKit/ViewControllers/Presentations/CardPresentation.swift | 1 | 11509 | //
// Copyright © 2018 TheLeftBit SL. All rights reserved.
// Created by Pierluigi Cifani.
//
#if canImport(UIKit)
import UIKit
/**
This abstraction will create the appropiate `UIViewControllerAnimatedTransitioning`
instance for a card-like modal animation.
- Attention: To use it:
```
extension FooVC: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let properties = CardPresentation.AnimationProperties(kind: .presentation(cardHeight: .intrinsicHeight), animationDuration: 2)
return CardPresentation.transitioningFor(properties: properties)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let properties = CardPresentation.AnimationProperties(kind: .dismissal, animationDuration: 2)
return CardPresentation.transitioningFor(properties: properties)
}
}
```
- note: For an example on how it [looks](http://i.giphy.com/l0EwZqcEkc15D6XOo.gif)
*/
public enum CardPresentation {
/**
These are the properties you can edit of the card-like modal presentation.
*/
public struct AnimationProperties: Equatable {
/// The Kind of this animation
public let kind: Kind
/// The duration of this animation
public let animationDuration: TimeInterval
/// If true, the presented VC will be layout inside the safeArea of the presenting VC
public let presentationInsideSafeArea: Bool
/// The background color for the view below the presented VC
public let backgroundColor: UIColor
/// If true, the alpha of the VC will be animated from 0 to 1
public let shouldAnimateNewVCAlpha: Bool
/// Any traits to set to the presented VC
public let overridenTraits: UITraitCollection?
/// The corner radius for the presented VC
public let roundCornerRadius: CGFloat?
/// Any additional offset to add to the presentation
public let initialYOffset: CGFloat?
public enum CardHeight: Equatable { // swiftlint:disable:this nesting
case fixed(CGFloat)
case intrinsicHeight
}
public enum Position: Equatable { // swiftlint:disable:this nesting
case top
case bottom
}
public enum Kind: Equatable { // swiftlint:disable:this nesting
case dismissal
case presentation(cardHeight: CardHeight = .intrinsicHeight, position: Position = .bottom)
}
public init(kind: Kind, animationDuration: TimeInterval = 0.6, presentationInsideSafeArea: Bool = false, backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.7), shouldAnimateNewVCAlpha: Bool = true, overridenTraits: UITraitCollection? = nil, roundCornerRadius: CGFloat? = nil, initialYOffset: CGFloat? = nil) {
self.kind = kind
self.animationDuration = animationDuration
self.presentationInsideSafeArea = presentationInsideSafeArea
self.backgroundColor = backgroundColor
self.shouldAnimateNewVCAlpha = shouldAnimateNewVCAlpha
self.overridenTraits = overridenTraits
self.roundCornerRadius = roundCornerRadius
self.initialYOffset = initialYOffset
}
}
/**
This method will return a `UIViewControllerAnimatedTransitioning` with default `AnimationProperties`
for the given `Kind`
- Parameter kind: A value that represents the kind of transition you need.
*/
static public func transitioningFor(kind: AnimationProperties.Kind) -> UIViewControllerAnimatedTransitioning {
return transitioningFor(properties: CardPresentation.AnimationProperties(kind: kind))
}
/**
This method will return a `UIViewControllerAnimatedTransitioning` with the given `AnimationProperties`
- Parameter properties: The properties for the desired animation.
*/
static public func transitioningFor(properties: AnimationProperties) -> UIViewControllerAnimatedTransitioning {
switch properties.kind {
case .dismissal:
return CardDismissAnimationController(properties: properties)
case .presentation:
return CardPresentAnimationController(properties: properties)
}
}
}
private class CardPresentAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
let properties: CardPresentation.AnimationProperties
init(properties: CardPresentation.AnimationProperties) {
self.properties = properties
super.init()
}
// MARK: - UIViewControllerAnimatedTransitioning
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return properties.animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
guard var fromViewController = transitionContext.viewController(forKey: .from) else { return }
if let containerVC = fromViewController as? ContainerViewController {
fromViewController = containerVC.containedViewController
}
if let tabBarController = fromViewController as? UITabBarController {
fromViewController = tabBarController.selectedViewController ?? fromViewController
}
if let navController = fromViewController as? UINavigationController {
fromViewController = navController.topViewController ?? fromViewController
}
guard case .presentation(let cardHeight, let position) = properties.kind else { fatalError() }
let containerView = transitionContext.containerView
let duration = self.transitionDuration(using: transitionContext)
let safeAreaOffset: CGFloat = {
guard properties.presentationInsideSafeArea else {
return 0
}
switch position {
case .top:
return fromViewController.view.safeAreaInsets.top
case .bottom:
return fromViewController.view.safeAreaInsets.bottom
}
}()
/// Add background view
let bgView = PresentationBackgroundView(frame: containerView.bounds)
bgView.backgroundColor = properties.backgroundColor
bgView.tag = Constants.BackgroundViewTag
containerView.addSubview(bgView)
bgView.context = .init(parentViewController: toViewController, position: position, offset: safeAreaOffset)
if let radius = properties.roundCornerRadius {
toViewController.view.roundCorners(radius: radius)
}
/// Add VC's view
containerView.addAutolayoutSubview(toViewController.view)
/// Override size classes if required
toViewController.presentationController?.overrideTraitCollection = properties.overridenTraits
/// Pin to the bottom or top
let anchorConstraint: NSLayoutConstraint = {
switch (position) {
case .bottom:
return toViewController.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: safeAreaOffset)
case .top:
return toViewController.view.topAnchor.constraint(equalTo: containerView.topAnchor, constant: safeAreaOffset)
}
}()
NSLayoutConstraint.activate([
toViewController.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
toViewController.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
anchorConstraint,
])
/// If it's a fixed height, add that constraint
switch cardHeight {
case .fixed(let height):
toViewController.view.heightAnchor.constraint(equalToConstant: height).isActive = true
case .intrinsicHeight:
break
}
/// Perform the first layout pass
containerView.layoutIfNeeded()
/// Now move this view offscreen
let distanceToMove = toViewController.view.frame.height + safeAreaOffset
let distanceToMoveWithPosition = (position == .bottom) ? distanceToMove : -distanceToMove
let offScreenTransform = CGAffineTransform(translationX: 0, y: distanceToMoveWithPosition)
toViewController.view.transform = offScreenTransform
/// Prepare the alpha animation
toViewController.view.alpha = properties.shouldAnimateNewVCAlpha ? 0.0 : 1.0
bgView.alpha = 0.0
/// And bring it back on screen
let animator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1.0) {
toViewController.view.transform = {
if let offset = self.properties.initialYOffset {
return CGAffineTransform(translationX: 0, y: offset)
} else {
return .identity
}
}()
toViewController.view.alpha = 1
bgView.alpha = 1.0
}
animator.addCompletion { (position) in
guard position == .end else { return }
transitionContext.completeTransition(true)
}
animator.startAnimation()
}
}
private class CardDismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
let properties: CardPresentation.AnimationProperties
init(properties: CardPresentation.AnimationProperties) {
self.properties = properties
super.init()
}
// MARK: UIViewControllerAnimatedTransitioning
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return properties.animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
guard let fromViewController = transitionContext.viewController(forKey: .from) else { return }
guard let bgView = containerView.subviews.first(where: { $0.tag == Constants.BackgroundViewTag}) as? PresentationBackgroundView, let context = bgView.context else { fatalError() }
let distanceToMove = fromViewController.view.frame.height + (context.offset ?? 0)
let distanceToMoveWithPosition = (context.position == .bottom) ? distanceToMove : -distanceToMove
let offScreenTransform = CGAffineTransform(translationX: 0, y: distanceToMoveWithPosition)
/// And bring it off screen
let animator = UIViewPropertyAnimator(duration: properties.animationDuration, dampingRatio: 1.0) {
fromViewController.view.transform = offScreenTransform
fromViewController.view.alpha = self.properties.shouldAnimateNewVCAlpha ? 0 : 1
bgView.alpha = 0
}
animator.addCompletion { (position) in
guard position == .end else { return }
fromViewController.view.removeFromSuperview()
transitionContext.completeTransition(true)
}
animator.startAnimation()
}
}
private enum Constants {
static let BackgroundViewTag = 78
}
#endif
| mit | 443b6acef827e0e7cc57d4fbfaed0eb2 | 41.780669 | 328 | 0.686044 | 5.944215 | false | false | false | false |
KailinLi/LeetCode-Solutions | 328. Odd Even Linked List/solution.swift | 1 | 1033 | /**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func oddEvenList(_ head: ListNode?) -> ListNode? {
if head == nil || head!.next == nil {
return head;
}
var ping = true
let save: ListNode = head!.next!
var odd: ListNode = head!.next!
var even: ListNode = head!;
while odd.next != nil && even.next != nil {
if ping {
even.next = odd.next
even = odd.next!
ping = false
}
else {
odd.next = even.next
odd = even.next!
ping = true
}
}
if ping {
even.next = nil
}
else {
odd.next = nil
}
even.next = save
return head
}
} | mit | 79cf38957e57960f548b51189e096efe | 23.046512 | 54 | 0.418199 | 4.322176 | false | false | false | false |
mdmsua/Ausgaben.iOS | Ausgaben/Ausgaben/AppDelegate.swift | 1 | 4847 | //
// AppDelegate.swift
// Ausgaben
//
// Created by Dmytro Morozov on 11.01.16.
// Copyright © 2016 Dmytro Morozov. All rights reserved.
//
import UIKit
import CoreData
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var client: MSClient?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Fabric.with([Crashlytics.self])
let appServiceUrl = NSBundle.mainBundle().objectForInfoDictionaryKey("APP_SERVICE_URL") as! String
client = MSClient(applicationURLString: appServiceUrl)
return true
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.mdmsua.Ausgaben" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .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 = NSBundle.mainBundle().URLForResource("Ausgaben", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns 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
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = 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 \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// 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.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | ea78e0e6867dfbc0d54d3da1d06d3e2b | 48.958763 | 291 | 0.705324 | 5.748517 | false | false | false | false |
francisykl/PagingMenuController | Example/PagingMenuControllerDemo/GistsViewController.swift | 4 | 2018 | //
// GistsViewController.swift
// PagingMenuControllerDemo
//
// Created by Yusuke Kita on 5/10/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import UIKit
class GistsViewController: UITableViewController {
var gists = [[String: AnyObject]]()
class func instantiateFromStoryboard() -> GistsViewController {
let storyboard = UIStoryboard(name: "MenuViewController", bundle: nil)
return storyboard.instantiateViewController(withIdentifier: String(describing: self)) as! GistsViewController
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://api.github.com/gists/public")
let request = URLRequest(url: url!)
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: request) { [weak self] data, response, error in
let result = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String: AnyObject]]
self?.gists = result ?? []
DispatchQueue.main.async(execute: { () -> Void in
self?.tableView.reloadData()
})
}
task.resume()
}
}
extension GistsViewController {
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gists.count
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let gist = gists[(indexPath as NSIndexPath).row]
cell.textLabel?.text = gist["description"] as? String
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
}
| mit | 75cef7213f8331c5c3f5b2b1904de5c1 | 32.633333 | 123 | 0.643707 | 5.09596 | false | false | false | false |
verloop/verloop_ios | VerloopSDK/Verloop/VerloopChatViewController.swift | 1 | 2175 | //
// VerloopChatViewController.swift
// VerloopSDK
//
// Created by Prashanta Kumar Nayak on 24/05/17.
// Copyright © 2017 Verloop. All rights reserved.
//
import Foundation
import UIKit
class VerloopChatViewController: UIViewController {
var urlString:String?
var webView:UIWebView?
var cancelButton:UIButton?
var chatTile:String?
public var viewIsOutOfFocusBlock:((Void) -> Void)?
init(chatUrl url:String, title:String, viewOutOfFocusBlock:((Void) -> Void)?) {
super.init(nibName: nil, bundle: nil)
self.urlString = url
self.chatTile = title;
self.viewIsOutOfFocusBlock = viewOutOfFocusBlock;
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupLayout();
let url:URL = URL.init(string: self.urlString!)!
let urlRequest:URLRequest = URLRequest.init(url:url)
self.webView!.loadRequest(urlRequest);
self.title = self.chatTile
}
func setupLayout() {
self.webView = UIWebView.init()
self.webView?.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.webView!)
self.webView?.scrollView.isScrollEnabled = false;
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[webView]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["webView" : self.webView!]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[webView]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["webView" : self.webView!]))
let closeButton = UIBarButtonItem.init(title: "Close", style: UIBarButtonItemStyle.done, target: self, action: #selector(VerloopChatViewController.cancelButtonTapped(button:)))
self.navigationItem.leftBarButtonItem = closeButton;
}
func cancelButtonTapped(button:UIBarButtonItem) {
self.dismiss(animated: true) {
self.viewIsOutOfFocusBlock!()
}
}
}
| mit | a0215da87be7f47cf11a7032edf71bac | 34.639344 | 199 | 0.674793 | 4.596195 | false | false | false | false |
P0ed/SWLABR | SWLABR/Model/Components/InputComponent.swift | 1 | 731 | import Foundation
final class InputComponent: ControlComponent {
let inputController: InputController
var thrusters = 0.0
init(_ inputController: InputController) {
self.inputController = inputController
}
func update(node: EntityNode, inEngine engine: GameEngine) {
let input = inputController.currentInput()
let shipBehavior = node.behaviorComponent as! ShipBehavior
if thrusters > 0.7 {
thrusters -= 0.01
}
thrusters = min(max(thrusters + 0.02 * input.throttle, 0), 1)
shipBehavior.control(node: node,
fwd: thrusters * 0.02,
roll: input.stick.dx * 0.01,
pitch: input.stick.dy * 0.01,
yaw: input.rudder * 0.01
)
if input.fireBlaster {
shipBehavior.fireBlaster(node: node)
}
}
}
| mit | 53737b2a8c28ff43847408a9f84a4fcb | 21.84375 | 63 | 0.708618 | 3.020661 | false | false | false | false |
sufangliang/LiangDYZB | LiangDYZB/Classes/Main/View/PageContentView.swift | 1 | 5811 | //
// PageContentView.swift
// LiangDYZB
//
// Created by qu on 2017/1/12.
// Copyright © 2017年 qu. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(_ contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}
private let identycollectCell = "collectCell"
class PageContentView: UIView {
//MARK:- 定义属性
fileprivate var childVcs:[UIViewController]
fileprivate var parentVc:UIViewController
fileprivate var startOffsetX:CGFloat = 0
fileprivate var isForbidScrollDelegate : Bool = false
weak var delegate:PageContentViewDelegate?
fileprivate lazy var colletctView:UICollectionView = {
//创建布局对象
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.frame.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//创建collectView
let collectView = UICollectionView(frame:CGRect.zero, collectionViewLayout: layout)
collectView.backgroundColor = UIColor.lightGray
collectView.isPagingEnabled = true
collectView.bounces = false
collectView.dataSource = self
collectView.delegate = self
collectView.scrollsToTop = false
collectView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: identycollectCell)
return collectView
}()
//初始化创建View
init(frame: CGRect,childVcs:[UIViewController],parentVc:UIViewController) {
self.childVcs = childVcs // 属性初始化 必须在super.init 之前
self.parentVc = parentVc
super.init(frame: frame)
setUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//设置UI
extension PageContentView{
func setUI(){
for childVc in childVcs {
self.parentVc.addChildViewController(childVc)
}
addSubview(colletctView)
colletctView.frame = bounds
}
}
//MARK: - collectView 代理
extension PageContentView:UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView .dequeueReusableCell(withReuseIdentifier: identycollectCell, for: indexPath)
for view in cell.contentView.subviews {
view .removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView .addSubview(childVc.view)
//随机色
// let red = CGFloat(arc4random_uniform(255))/CGFloat(255.0)
// let green = CGFloat( arc4random_uniform(255))/CGFloat(255.0)
// let blue = CGFloat(arc4random_uniform(255))/CGFloat(255.0)
// let colorRun = UIColor.init(red:red, green:green, blue:blue , alpha: 1)
// cell.contentView.backgroundColor = colorRun
return cell
}
}
//MARK: - contentView - 滑动代理
extension PageContentView:UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
print("startOffsetX:%f",startOffsetX)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 0.判断是否是点击事件
if isForbidScrollDelegate { return }
// 1.定义获取需要的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
// 2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { // 左滑
// 1.计算progress floor 最大整数
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2.计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
// 3.计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
print("\(currentOffsetX)")
// 4.如果完全划过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
} else { // 右滑
// 1.计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2.计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
// 3.计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
// 3.将progress/sourceIndex/targetIndex传递给titleView
delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//设置page的当前页
extension PageContentView {
func setcurrentIndex (currentIndex:NSInteger){
// 1.记录需要进制执行代理方法
isForbidScrollDelegate = true
// 2.滚动正确的位置
let offsetX = CGFloat (currentIndex)*colletctView.frame.width
colletctView.setContentOffset(CGPoint(x:offsetX,y:0), animated: true)
}
}
| mit | aa8bc3d2e8dc53fb3a25f452b3cb2636 | 31.17341 | 121 | 0.636903 | 5.182495 | false | false | false | false |
alisidd/iOS-WeJ | WeJ/Play Tracks/HubViewController.swift | 1 | 7424 | //
// LyricsViewController.swift
// WeJ
//
// Created by Mohammad Ali Siddiqui on 3/15/17.
// Copyright © 2017 Mohammad Ali Siddiqui. All rights reserved.
//
import UIKit
class HubViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
weak var delegate: PartyViewControllerInfoDelegate?
weak var tracksTableModifierDelegate: TracksTableModifierDelegate?
fileprivate var minHeight: CGFloat {
return HubAndQueuePageViewController.minHeight
}
fileprivate var maxHeight: CGFloat {
return HubAndQueuePageViewController.maxHeight
}
fileprivate var previousScrollOffset: CGFloat = 0
@IBOutlet weak var hubTitle: UILabel?
private let hubOptions = [NSLocalizedString("View Lyrics", comment: ""), NSLocalizedString("Leave Party", comment: "")]
private let hubIcons = [#imageLiteral(resourceName: "lyricsIcon"), #imageLiteral(resourceName: "leavePartyIcon")]
@IBOutlet weak var hubTableView: UITableView!
@IBOutlet weak var hubLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setDelegates()
adjustViews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
changeFontSizeForHub()
}
private func setDelegates() {
hubTableView.delegate = self
hubTableView.dataSource = self
}
func adjustViews() {
updateHubTitle()
hubTableView.tableFooterView = UIView()
}
// MARK: - Table
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hubOptions.count
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = .zero
cell.layoutMargins = .zero
cell.backgroundColor = .clear
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Hub Cell") as! HubTableViewCell
cell.hubLabel.text = hubOptions[indexPath.row]
cell.iconView?.image = hubIcons[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if hubOptions[indexPath.row] == NSLocalizedString("Leave Party", comment: "") {
leaveParty()
} else if let position = delegate?.currentTrackPosition, !Party.tracksQueue.isEmpty {
MXMLyricsAction.sharedExtension().findLyricsForSong(
withTitle: Party.tracksQueue[0].name,
artist: Party.tracksQueue[0].artist,
album: "",
artWork: Party.tracksQueue[0].highResArtwork,
currentProgress: position,
trackDuration: Party.tracksQueue[0].length!,
for: self,
sender: tableView.dequeueReusableCell(withIdentifier: "Hub Cell")!,
competionHandler: nil)
} else {
postAlertForNoTracks()
}
}
private func postAlertForNoTracks() {
let alert = UIAlertController(title: NSLocalizedString("No Track Playing", comment: ""), message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil))
present(alert, animated: true)
}
// MARK: = Navigation
private func leaveParty() {
let _ = navigationController?.popToRootViewController(animated: true)
}
}
extension HubViewController {
private var headerHeightConstraint: CGFloat {
get {
return delegate!.tableHeight
}
set {
delegate?.tableHeight = newValue
}
}
// Code taken from https://michiganlabs.com/ios/development/2016/05/31/ios-animating-uitableview-header/
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let scrollDiff = scrollView.contentOffset.y - previousScrollOffset
let absoluteTop: CGFloat = 0
let isScrollingDown = scrollDiff > 0 && scrollView.contentOffset.y > absoluteTop
let isScrollingUp = scrollDiff < 0 && scrollView.contentOffset.y < absoluteTop && !Party.tracksQueue.isEmpty
var newHeight = headerHeightConstraint
if isScrollingDown {
newHeight = max(maxHeight, headerHeightConstraint - abs(scrollDiff))
if newHeight != headerHeightConstraint {
headerHeightConstraint = newHeight
changeFontSizeForHub()
setScrollPosition(forOffset: previousScrollOffset)
}
} else if isScrollingUp {
newHeight = min(minHeight, headerHeightConstraint + abs(scrollDiff))
if newHeight != headerHeightConstraint && hubTableView.contentOffset.y < 2 {
headerHeightConstraint = newHeight
changeFontSizeForHub()
setScrollPosition(forOffset: previousScrollOffset)
}
}
previousScrollOffset = scrollView.contentOffset.y
}
fileprivate func changeFontSizeForHub() {
UIView.animate(withDuration: 0.3) {
self.hubLabel.font = self.hubLabel.font.withSize(20 - UILabel.smallerTitleFontSize * (self.headerHeightConstraint / self.minHeight))
}
}
private func setScrollPosition(forOffset offset: CGFloat) {
hubTableView.contentOffset = CGPoint(x: hubTableView.contentOffset.x, y: offset)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewDidStopScrolling()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollViewDidStopScrolling()
}
}
private func scrollViewDidStopScrolling() {
let range = maxHeight - minHeight
let midPoint = minHeight + (range / 2)
delegate?.layout()
if headerHeightConstraint > midPoint {
tracksTableModifierDelegate?.showAddButton()
makeTracksTableShorter()
} else {
makeTracksTableTaller()
}
}
func makeTracksTableShorter() {
DispatchQueue.main.async {
self.delegate?.layout()
UIView.animate(withDuration: 0.2, animations: {
self.headerHeightConstraint = self.minHeight
self.changeFontSizeForHub()
self.delegate?.layout()
})
}
}
func makeTracksTableTaller() {
DispatchQueue.main.async {
self.delegate?.layout()
UIView.animate(withDuration: 0.2, animations: {
self.headerHeightConstraint = self.maxHeight
self.changeFontSizeForHub()
self.delegate?.layout()
})
}
}
func updateHubTitle() {
DispatchQueue.main.async {
self.hubTitle?.text = Party.name ?? NSLocalizedString("Party", comment: "")
}
}
}
| gpl-3.0 | 63816e9c1f1d3dba41eed7cbd114351a | 33.207373 | 144 | 0.624411 | 5.351839 | false | false | false | false |
vmanot/swift-package-manager | Sources/Utility/BuildFlags.swift | 1 | 1156 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// Build-tool independent flags.
//
// FIXME: This belongs somewhere else, but we don't have a layer specifically
// for BuildSupport style logic yet.
public struct BuildFlags {
/// Flags to pass to the C compiler.
public var cCompilerFlags: [String]
/// Flags to pass to the C++ compiler.
public var cxxCompilerFlags: [String]
/// Flags to pass to the linker.
public var linkerFlags: [String]
/// Flags to pass to the Swift compiler.
public var swiftCompilerFlags: [String]
public init(
xcc: [String]? = nil,
xcxx: [String]? = nil,
xswiftc: [String]? = nil,
xlinker: [String]? = nil
) {
cCompilerFlags = xcc ?? []
cxxCompilerFlags = xcxx ?? []
linkerFlags = xlinker ?? []
swiftCompilerFlags = xswiftc ?? []
}
}
| apache-2.0 | 1f50eab5bcc2452596a397bb1cff7530 | 27.9 | 77 | 0.654844 | 4.173285 | false | false | false | false |
nodekit-io/nodekit-darwin | src/samples/sample-nodekit/platform-darwin/SamplePlugin.swift | 1 | 2602 | /*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import Cocoa
import WebKit
import NodeKit
protocol SamplePluginProtocol: NKScriptExport {
func logconsole(text: AnyObject?) -> Void
func alertSync(text: AnyObject?) -> String
}
class SamplePlugin: NSObject, SamplePluginProtocol {
class func attachTo(context: NKScriptContext) {
context.loadPlugin(SamplePlugin(), namespace: "io.nodekit.test", options: ["PluginBridge": NKScriptExportType.NKScriptExport.rawValue])
}
func logconsole(text: AnyObject?) -> Void {
NKLogging.log(text as? String! ?? "")
}
func alertSync(text: AnyObject?) -> String {
dispatch_async(dispatch_get_main_queue()) {
self._alert(title: text as? String, message: nil)
}
return "OK"
}
private func _alert(title title: String?, message: String?) {
let myPopup: NSAlert = NSAlert()
myPopup.messageText = message ?? "NodeKit"
myPopup.informativeText = title ?? ""
myPopup.alertStyle = NSAlertStyle.Warning
myPopup.addButtonWithTitle("OK")
myPopup.runModal()
}
}
/*
extension WKWebView: WKUIDelegate {
private func _alert(title title: String?, message: String?) {
let myPopup: NSAlert = NSAlert()
myPopup.messageText = message ?? "NodeKit"
myPopup.informativeText = title!
myPopup.alertStyle = NSAlertStyle.WarningAlertStyle
myPopup.addButtonWithTitle("OK")
myPopup.runModal()
}
public func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) {
_alert(title: self.title, message: message)
}
public func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) {
completionHandler("hello from native; you sent: " + prompt)
}
} */
| apache-2.0 | c4cad24f2800a92a0f43038052d28a84 | 32.358974 | 196 | 0.694466 | 4.525217 | false | false | false | false |
sarvex/SwiftRecepies | Concurrency/Playing Audio in the Background/Playing Audio in the Background/AppDelegate.swift | 1 | 3763 | //
// AppDelegate.swift
// Playing Audio in the Background
//
// Created by Vandad Nahavandipoor on 7/7/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at vandad.np@gmail.com
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, AVAudioPlayerDelegate {
var window: UIWindow?
var audioPlayer: AVAudioPlayer?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let dispatchQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatchQueue, {[weak self] in
var audioSessionError: NSError?
let audioSession = AVAudioSession.sharedInstance()
NSNotificationCenter.defaultCenter().addObserver(self!,
selector: "handleInterruption:",
name: AVAudioSessionInterruptionNotification,
object: nil)
audioSession.setActive(true, error: nil)
if audioSession.setCategory(AVAudioSessionCategoryPlayback,
error: &audioSessionError){
println("Successfully set the audio session")
} else {
println("Could not set the audio session")
}
let filePath = NSBundle.mainBundle().pathForResource("MySong",
ofType:"mp3")
let fileData = NSData(contentsOfFile: filePath!,
options: .DataReadingMappedIfSafe,
error: nil)
var error:NSError?
/* Start the audio player */
self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error)
/* Did we get an instance of AVAudioPlayer? */
if let theAudioPlayer = self!.audioPlayer{
theAudioPlayer.delegate = self;
if theAudioPlayer.prepareToPlay() &&
theAudioPlayer.play(){
println("Successfully started playing")
} else {
println("Failed to play")
}
} else {
/* Handle the failure of instantiating the audio player */
}
})
return true
}
func handleInterruption(notification: NSNotification){
/* Audio Session is interrupted. The player will be paused here */
let interruptionTypeAsObject =
notification.userInfo![AVAudioSessionInterruptionTypeKey] as! NSNumber
let interruptionType = AVAudioSessionInterruptionType(rawValue:
interruptionTypeAsObject.unsignedLongValue)
if let type = interruptionType{
if type == .Ended{
/* resume the audio if needed */
}
}
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!,
successfully flag: Bool){
println("Finished playing the song")
/* The flag parameter tells us if the playback was successfully
finished or not */
if player == audioPlayer{
audioPlayer = nil
}
}
}
| isc | 21eac957465dd70bbd597e33ce915938 | 30.621849 | 83 | 0.650545 | 5.255587 | false | false | false | false |
peferron/algo | EPI/Hash Tables/Implement an ISBN cache/swift/main.swift | 1 | 1976 | private struct CachedValue {
let price: Int
var olderISBN: String?
var newerISBN: String?
}
public struct ISBNCache {
public let capacity: Int
private var cache: [String: CachedValue]
private var oldestISBN: String?
private var newestISBN: String?
public init(capacity: Int) {
self.capacity = capacity
self.cache = [String: CachedValue](minimumCapacity: capacity)
}
public mutating func lookup(_ ISBN: String) -> Int? {
if let price = cache[ISBN]?.price {
// Removing then inserting is the easiest way to bump the ISBN to newest, but it also
// performs unnecessary work and could be optimized.
self.remove(ISBN)
self.insert(ISBN, price: price)
return price
}
return nil
}
public mutating func insert(_ ISBN: String, price: Int) {
self.remove(ISBN)
// Remove oldest ISBN if necessary.
if cache.count >= capacity {
self.remove(self.oldestISBN!)
}
// Insert as newest ISBN.
cache[ISBN] = CachedValue(price: price, olderISBN: self.newestISBN, newerISBN: nil)
if let newestISBN = self.newestISBN {
cache[newestISBN]!.newerISBN = ISBN
}
self.newestISBN = ISBN
self.oldestISBN = self.oldestISBN ?? ISBN
}
public mutating func remove(_ ISBN: String) {
if let value = cache[ISBN] {
cache.removeValue(forKey: ISBN)
if let olderISBN = value.olderISBN {
cache[olderISBN]!.newerISBN = value.newerISBN
}
if let newerISBN = value.newerISBN {
cache[newerISBN]!.olderISBN = value.olderISBN
}
if ISBN == self.oldestISBN {
self.oldestISBN = value.newerISBN
}
if ISBN == self.newestISBN {
self.newestISBN = value.olderISBN
}
}
}
}
| mit | a44b96747ae9bd9ad26e546ca1451d50 | 28.058824 | 97 | 0.574393 | 4.420582 | false | false | false | false |
peferron/algo | EPI/Sorting/Count the frequencies of characters in a sentence/swift/test.swift | 1 | 1116 | import Darwin
func == <T: Equatable, U: Equatable>(lhs: [(T, U)], rhs: [(T, U)]) -> Bool {
guard lhs.count == rhs.count else {
return false
}
for (i, lt) in lhs.enumerated() {
let rt = rhs[i]
guard lt.0 == rt.0 && lt.1 == rt.1 else {
return false
}
}
return true
}
let tests: [(string: String, occurrences: [Occurrences])] = [
(
string: "",
occurrences: []
),
(
string: "a",
occurrences: [("a", 1)]
),
(
string: "aa",
occurrences: [("a", 2)]
),
(
string: "ab",
occurrences: [("a", 1), ("b", 1)]
),
(
string: "ba",
occurrences: [("a", 1), ("b", 1)]
),
(
string: "bcdacebe",
occurrences: [("a", 1), ("b", 2), ("c", 2), ("d", 1), ("e", 2)]
),
]
for test in tests {
let actual = occurrences(test.string)
guard actual == test.occurrences else {
print("For test string \(test.string), expected occurrences to be \(test.occurrences), " +
"but were \(actual)")
exit(1)
}
}
| mit | a5830712171c0a41a9e020b037a685ff | 21.32 | 98 | 0.445341 | 3.4875 | false | true | false | false |
sshams/puremvc-swift-standard-framework | PureMVC/org/puremvc/swift/patterns/observer/Notification.swift | 1 | 2831 | //
// Notification.swift
// PureMVC SWIFT Standard
//
// Copyright(c) 2015-2025 Saad Shams <saad.shams@puremvc.org>
// Your reuse is governed by the Creative Commons Attribution 3.0 License
//
/**
A base `INotification` implementation.
PureMVC does not rely upon underlying event models such
as the one provided with Flash, and ActionScript 3 does
not have an inherent event model.
The Observer Pattern as implemented within PureMVC exists
to support event-driven communication between the
application and the actors of the MVC triad.
Notifications are not meant to be a replacement for Events
in Flex/Flash/Apollo. Generally, `IMediator` implementors
place event listeners on their view components, which they
then handle in the usual way. This may lead to the broadcast of `Notification`s to
trigger `ICommand`s or to communicate with other `IMediators`. `IProxy` and `ICommand`
instances communicate with each other and `IMediator`s
by broadcasting `INotification`s.
A key difference between Flash `Event`s and PureMVC
`Notification`s is that `Event`s follow the
'Chain of Responsibility' pattern, 'bubbling' up the display hierarchy
until some parent component handles the `Event`, while
PureMVC `Notification`s follow a 'Publish/Subscribe'
pattern. PureMVC classes need not be related to each other in a
parent/child relationship in order to communicate with one another
using `Notification`s.
`@see org.puremvc.swift.patterns.observer.Observer Observer`
*
*/
public class Notification : INotification {
// the name of the notification instance
private var _name: String
// the body of the notification instance
private var _body: Any?
// the type of the notification instance
private var _type: String?
/**
Constructor.
- parameter name: name of the `Notification` instance. (required)
- parameter body: the `Notification` body. (optional)
- parameter type: the type of the `Notification` (optional)
*/
public init(name: String, body: Any?=nil, type: String?=nil) {
_name = name
_body = body
_type = type
}
/// Get the name of notification instance
public var name: String {
return _name
}
/// Get or set the body of notification instance
public var body: Any? {
get { return _body }
set { _body = newValue }
}
/// Get or set the type of notification instance
public var type: String? {
get { return _type }
set { _type = newValue }
}
/**
Get the string representation of the `Notification` instance.
- returns: the string representation of the `Notification` instance.
*/
public func description() -> String {
return "Notification Name: \(self.name) \(self.body) \(self.type)"
}
}
| bsd-3-clause | df7d7f165e30ace057de4048733c45ea | 31.170455 | 86 | 0.697987 | 4.263554 | false | false | false | false |
marcelganczak/swift-js-transpiler | test/types/tuple.swift | 1 | 594 | let unnamedUntypedTuple = (4, 25)
print(unnamedUntypedTuple.0)
print(unnamedUntypedTuple.1)
let unnamedTypedTuple:(Int, Int) = (4, 25)
print(unnamedTypedTuple.0)
print(unnamedTypedTuple.1)
let unnamedUntypedVariadicTuple = (4, "string")
print(unnamedUntypedVariadicTuple.0)
print(unnamedUntypedVariadicTuple.1)
let namedUntypedTuple = (a:4, count:25)
print(namedUntypedTuple.a)
print(namedUntypedTuple.count)
let namedTypedTuple:(a:Int, count:Int) = (4, 25)
print(namedTypedTuple.a)
print(namedTypedTuple.count)
let nestedTuple = (4, (12, 25))
print(nestedTuple.1.0)
print(nestedTuple.1.1) | mit | 5a9c27b54eff70d4741be928b4776b87 | 24.869565 | 48 | 0.784512 | 2.911765 | false | false | false | false |
gregomni/swift | test/refactoring/ConvertAsync/convert_function.swift | 10 | 32579 | // REQUIRES: concurrency
// RUN: %empty-directory(%t)
enum CustomError : Error {
case Bad
}
func run(block: () -> Bool) -> Bool { return false }
func makeOptionalError() -> Error? { return nil }
func makeOptionalString() -> String? { return nil }
func simple(_ completion: @escaping (String) -> Void) { }
func simple() async -> String { }
func simple2(arg: String, _ completion: @escaping (String) -> Void) { }
func simple2(arg: String) async -> String { }
func simpleErr(arg: String, _ completion: @escaping (String?, Error?) -> Void) { }
func simpleErr(arg: String) async throws -> String { }
func simpleRes(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) { }
func simpleRes(arg: String) async throws -> String { }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ALREADY-ASYNC %s
func alreadyAsync() async {
simple {
print($0)
}
}
// ALREADY-ASYNC: func alreadyAsync() async {
// ALREADY-ASYNC-NEXT: let val0 = await simple()
// ALREADY-ASYNC-NEXT: print(val0)
// ALREADY-ASYNC-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTED %s
func nested() {
simple {
simple2(arg: $0) { str2 in
print(str2)
}
}
}
// NESTED: func nested() async {
// NESTED-NEXT: let val0 = await simple()
// NESTED-NEXT: let str2 = await simple2(arg: val0)
// NESTED-NEXT: print(str2)
// NESTED-NEXT: }
// Can't check for compilation since throws isn't added
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NO-THROWS %s
func noThrowsAdded() {
simpleErr(arg: "") { _, _ in }
}
// NO-THROWS: func noThrowsAdded() async {
// NO-THROWS-NEXT: let _ = try await simpleErr(arg: "")
// NO-THROWS-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):9 | %FileCheck -check-prefix=ATTRIBUTES %s
@available(*, deprecated, message: "Deprecated")
private func functionWithAttributes() {
simple { str in
print(str)
}
}
// ATTRIBUTES: convert_function.swift [[# @LINE-6]]:1 -> [[# @LINE-1]]:2
// ATTRIBUTES-NEXT: @available(*, deprecated, message: "Deprecated")
// ATTRIBUTES-NEXT: private func functionWithAttributes() async {
// ATTRIBUTES-NEXT: let str = await simple()
// ATTRIBUTES-NEXT: print(str)
// ATTRIBUTES-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MANY-NESTED %s
func manyNested() throws {
simple { str1 in
print("simple")
simple2(arg: str1) { str2 in
print("simple2")
simpleErr(arg: str2) { str3, err in
print("simpleErr")
guard let str3 = str3, err == nil else {
return
}
simpleRes(arg: str3) { res in
print("simpleRes")
if case .success(let str4) = res {
print("\(str1) \(str2) \(str3) \(str4)")
print("after")
}
}
}
}
}
}
// MANY-NESTED: func manyNested() async throws {
// MANY-NESTED-NEXT: let str1 = await simple()
// MANY-NESTED-NEXT: print("simple")
// MANY-NESTED-NEXT: let str2 = await simple2(arg: str1)
// MANY-NESTED-NEXT: print("simple2")
// MANY-NESTED-NEXT: let str3 = try await simpleErr(arg: str2)
// MANY-NESTED-NEXT: print("simpleErr")
// MANY-NESTED-NEXT: let str4 = try await simpleRes(arg: str3)
// MANY-NESTED-NEXT: print("simpleRes")
// MANY-NESTED-NEXT: print("\(str1) \(str2) \(str3) \(str4)")
// MANY-NESTED-NEXT: print("after")
// MANY-NESTED-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s
func asyncParams(arg: String, _ completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: arg) { str, err in
print("simpleErr")
guard let str = str, err == nil else {
completion(nil, err!)
return
}
completion(str, nil)
print("after")
}
}
// ASYNC-SIMPLE: func {{[a-zA-Z_]+}}(arg: String) async throws -> String {
// ASYNC-SIMPLE-NEXT: let str = try await simpleErr(arg: arg)
// ASYNC-SIMPLE-NEXT: print("simpleErr")
// ASYNC-SIMPLE-NEXT: {{^}}return str{{$}}
// ASYNC-SIMPLE-NEXT: print("after")
// ASYNC-SIMPLE-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s
func asyncResErrPassed(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) {
simpleErr(arg: arg) { str, err in
print("simpleErr")
guard let str = str, err == nil else {
completion(.failure(err!))
return
}
completion(.success(str))
print("after")
}
}
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERR %s
func asyncResNewErr(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) {
simpleErr(arg: arg) { str, err in
print("simpleErr")
guard let str = str, err == nil else {
completion(.failure(CustomError.Bad))
return
}
completion(.success(str))
print("after")
}
}
// ASYNC-ERR: func asyncResNewErr(arg: String) async throws -> String {
// ASYNC-ERR-NEXT: do {
// ASYNC-ERR-NEXT: let str = try await simpleErr(arg: arg)
// ASYNC-ERR-NEXT: print("simpleErr")
// ASYNC-ERR-NEXT: {{^}}return str{{$}}
// ASYNC-ERR-NEXT: print("after")
// ASYNC-ERR-NEXT: } catch let err {
// ASYNC-ERR-NEXT: throw CustomError.Bad
// ASYNC-ERR-NEXT: }
// ASYNC-ERR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NON-ASYNC-IN-ASYNC %s
func callNonAsyncInAsync(_ completion: @escaping (String) -> Void) {
simple { str in
let success = run {
completion(str)
return true
}
if !success {
completion("bad")
}
}
}
// CALL-NON-ASYNC-IN-ASYNC: func callNonAsyncInAsync() async -> String {
// CALL-NON-ASYNC-IN-ASYNC-NEXT: let str = await simple()
// CALL-NON-ASYNC-IN-ASYNC-NEXT: return await withCheckedContinuation { continuation in
// CALL-NON-ASYNC-IN-ASYNC-NEXT: let success = run {
// CALL-NON-ASYNC-IN-ASYNC-NEXT: continuation.resume(returning: str)
// CALL-NON-ASYNC-IN-ASYNC-NEXT: {{^}} return true{{$}}
// CALL-NON-ASYNC-IN-ASYNC-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-NEXT: if !success {
// CALL-NON-ASYNC-IN-ASYNC-NEXT: continuation.resume(returning: "bad")
// CALL-NON-ASYNC-IN-ASYNC-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NON-ASYNC-IN-ASYNC-COMMENT %s
func callNonAsyncInAsyncComment(_ completion: @escaping (String) -> Void) {
// a
simple { str in // b
// c
let success = run {
// d
completion(str)
// e
return true
// f
}
// g
if !success {
// h
completion("bad")
// i
}
// j
}
// k
}
// CALL-NON-ASYNC-IN-ASYNC-COMMENT: func callNonAsyncInAsyncComment() async -> String {
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // a
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: let str = await simple()
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // b
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // c
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: return await withCheckedContinuation { continuation in
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: let success = run {
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // d
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: continuation.resume(returning: str)
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // e
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: {{^}} return true{{$}}
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // f
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // g
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: if !success {
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // h
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: continuation.resume(returning: "bad")
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // i
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // j
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // k
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-AND-ERROR-HANDLER %s
func voidAndErrorCompletion(completion: @escaping (Void?, Error?) -> Void) {
if .random() {
completion((), nil) // Make sure we drop the ()
} else {
completion(nil, CustomError.Bad)
}
}
// VOID-AND-ERROR-HANDLER: func voidAndErrorCompletion() async throws {
// VOID-AND-ERROR-HANDLER-NEXT: if .random() {
// VOID-AND-ERROR-HANDLER-NEXT: return // Make sure we drop the ()
// VOID-AND-ERROR-HANDLER-NEXT: } else {
// VOID-AND-ERROR-HANDLER-NEXT: throw CustomError.Bad
// VOID-AND-ERROR-HANDLER-NEXT: }
// VOID-AND-ERROR-HANDLER-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix TOO-MUCH-VOID-AND-ERROR-HANDLER %s
func tooMuchVoidAndErrorCompletion(completion: @escaping (Void?, Void?, Error?) -> Void) {
if .random() {
completion((), (), nil) // Make sure we drop the ()s
} else {
completion(nil, nil, CustomError.Bad)
}
}
// TOO-MUCH-VOID-AND-ERROR-HANDLER: func tooMuchVoidAndErrorCompletion() async throws {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: if .random() {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: return // Make sure we drop the ()s
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } else {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: throw CustomError.Bad
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: }
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-RESULT-HANDLER %s
func voidResultCompletion(completion: @escaping (Result<Void, Error>) -> Void) {
if .random() {
completion(.success(())) // Make sure we drop the .success(())
} else {
completion(.failure(CustomError.Bad))
}
}
// VOID-RESULT-HANDLER: func voidResultCompletion() async throws {
// VOID-RESULT-HANDLER-NEXT: if .random() {
// VOID-RESULT-HANDLER-NEXT: return // Make sure we drop the .success(())
// VOID-RESULT-HANDLER-NEXT: } else {
// VOID-RESULT-HANDLER-NEXT: throw CustomError.Bad
// VOID-RESULT-HANDLER-NEXT: }
// VOID-RESULT-HANDLER-NEXT: }
// rdar://77789360 Make sure we don't print a double return statement.
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING %s
func testReturnHandling(_ completion: @escaping (String?, Error?) -> Void) {
return completion("", nil)
}
// RETURN-HANDLING: func testReturnHandling() async throws -> String {
// RETURN-HANDLING-NEXT: {{^}} return ""{{$}}
// RETURN-HANDLING-NEXT: }
// rdar://77789360 Make sure we don't print a double return statement and don't
// completely drop completion(a).
// Note we cannot use refactor-check-compiles here, as the placeholders mean we
// don't form valid AST.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING2 %s
func testReturnHandling2(completion: @escaping (String) -> ()) {
simpleErr(arg: "") { x, err in
guard let _ = x else {
let a = ""
return completion(a)
}
let b = ""
return completion(b)
}
}
// RETURN-HANDLING2: func testReturnHandling2() async -> String {
// RETURN-HANDLING2-NEXT: do {
// RETURN-HANDLING2-NEXT: let x = try await simpleErr(arg: "")
// RETURN-HANDLING2-NEXT: let b = ""
// RETURN-HANDLING2-NEXT: {{^}}<#return#> b{{$}}
// RETURN-HANDLING2-NEXT: } catch let err {
// RETURN-HANDLING2-NEXT: let a = ""
// RETURN-HANDLING2-NEXT: {{^}}<#return#> a{{$}}
// RETURN-HANDLING2-NEXT: }
// RETURN-HANDLING2-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING3 %s
func testReturnHandling3(_ completion: @escaping (String?, Error?) -> Void) {
return (completion("", nil))
}
// RETURN-HANDLING3: func testReturnHandling3() async throws -> String {
// RETURN-HANDLING3-NEXT: {{^}} return ""{{$}}
// RETURN-HANDLING3-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING4 %s
func testReturnHandling4(_ completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "xxx") { str, err in
if str != nil {
completion(str, err)
return
}
print("some error stuff")
completion(str, err)
}
}
// RETURN-HANDLING4: func testReturnHandling4() async throws -> String {
// RETURN-HANDLING4-NEXT: do {
// RETURN-HANDLING4-NEXT: let str = try await simpleErr(arg: "xxx")
// RETURN-HANDLING4-NEXT: return str
// RETURN-HANDLING4-NEXT: } catch let err {
// RETURN-HANDLING4-NEXT: print("some error stuff")
// RETURN-HANDLING4-NEXT: throw err
// RETURN-HANDLING4-NEXT: }
// RETURN-HANDLING4-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RDAR78693050 %s
func rdar78693050(_ completion: @escaping () -> Void) {
simple { str in
print(str)
}
if .random() {
return completion()
}
completion()
}
// RDAR78693050: func rdar78693050() async {
// RDAR78693050-NEXT: let str = await simple()
// RDAR78693050-NEXT: print(str)
// RDAR78693050-NEXT: if .random() {
// RDAR78693050-NEXT: return
// RDAR78693050-NEXT: }
// RDAR78693050-NEXT: return
// RDAR78693050-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DISCARDABLE-RESULT %s
func withDefaultedCompletion(arg: String, completion: @escaping (String) -> Void = {_ in}) {
completion(arg)
}
// DISCARDABLE-RESULT: @discardableResult
// DISCARDABLE-RESULT-NEXT: func withDefaultedCompletion(arg: String) async -> String {
// DISCARDABLE-RESULT-NEXT: return arg
// DISCARDABLE-RESULT-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT-ARG %s
func withDefaultArg(x: String = "") {
}
// DEFAULT-ARG: convert_function.swift [[# @LINE-2]]:1 -> [[# @LINE-1]]:2
// DEFAULT-ARG-NOT: @discardableResult
// DEFAULT-ARG-NEXT: {{^}}func withDefaultArg(x: String = "") async
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=IMPLICIT-RETURN %s
func withImplicitReturn(completionHandler: @escaping (String) -> Void) {
simple {
completionHandler($0)
}
}
// IMPLICIT-RETURN: func withImplicitReturn() async -> String {
// IMPLICIT-RETURN-NEXT: let val0 = await simple()
// IMPLICIT-RETURN-NEXT: return val0
// IMPLICIT-RETURN-NEXT: }
// This code doesn't compile after refactoring because we can't return `nil` from the async function.
// But there's not much else we can do here.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-NIL-ERROR %s
func nilResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
completion(nil, nil)
}
// NIL-RESULT-AND-NIL-ERROR: func nilResultAndNilError() async throws -> String {
// NIL-RESULT-AND-NIL-ERROR-NEXT: return nil
// NIL-RESULT-AND-NIL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR %s
func nilResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(nil, err)
}
}
// NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR: func nilResultAndOptionalRelayedError() async throws -> String {
// NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-EMPTY:
// NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: }
// This code doesn't compile after refactoring because we can't throw an optional error returned from makeOptionalError().
// But it's not clear what the intended result should be either.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func nilResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
completion(nil, makeOptionalError())
}
// NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nilResultAndOptionalComplexError() async throws -> String {
// NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw makeOptionalError()
// NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-NON-OPTIONAL-ERROR %s
func nilResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
completion(nil, CustomError.Bad)
}
// NIL-RESULT-AND-NON-OPTIONAL-ERROR: func nilResultAndNonOptionalError() async throws -> String {
// NIL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// NIL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// In this case, we are previously ignoring the error returned from simpleErr but are rethrowing it in the refactored case.
// That's probably fine although it changes semantics.
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR %s
func optionalRelayedResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, nil)
}
}
// OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR: func optionalRelayedResultAndNilError() async throws -> String {
// OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: return res
// OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR %s
func optionalRelayedResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, err)
}
}
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR: func optionalRelayedResultAndOptionalRelayedError() async throws -> String {
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return res
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func optionalRelayedResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, makeOptionalError())
}
}
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func optionalRelayedResultAndOptionalComplexError() async throws -> String {
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() {
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else {
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return res
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR %s
func optionalRelayedResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, CustomError.Bad)
}
}
// OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR: func optionalRelayedResultAndNonOptionalError() async throws -> String {
// OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR %s
func nonOptionalRelayedResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
simple { res in
completion(res, nil)
}
}
// NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR: func nonOptionalRelayedResultAndNilError() async throws -> String {
// NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: let res = await simple()
// NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: return res
// NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func nonOptionalRelayedResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
simple { res in
completion(res, makeOptionalError())
}
}
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nonOptionalRelayedResultAndOptionalComplexError() async throws -> String {
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: let res = await simple()
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() {
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else {
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return res
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR %s
func nonOptionalRelayedResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
simple { res in
completion(res, CustomError.Bad)
}
}
// NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR: func nonOptionalRelayedResultAndNonOptionalError() async throws -> String {
// NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: let res = await simple()
// NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// The refactored code doesn't compile because we can't return an optional String from the async function.
// But it's not clear what the intended result should be either, because `error` is always `nil`.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR %s
func optionalComplexResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
completion(makeOptionalString(), nil)
}
// OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR: func optionalComplexResultAndNilError() async throws -> String {
// OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR-NEXT: return makeOptionalString()
// OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR-NEXT: }
// The refactored code doesn't compile because we can't return an optional
// String from the async function.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR %s
func optionalComplexResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(makeOptionalString(), err)
}
}
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR: func optionalComplexResultAndOptionalRelayedError() async throws -> String {
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return makeOptionalString()
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: }
// The refactored code doesn't compile because we can't return an optional
// String or throw an optional Error from the async function.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func optionalComplexResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
completion(makeOptionalString(), makeOptionalError())
}
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func optionalComplexResultAndOptionalComplexError() async throws -> String {
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() {
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else {
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return makeOptionalString()
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR %s
func optionalComplexResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
completion(makeOptionalString(), CustomError.Bad)
}
// OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR: func optionalComplexResultAndNonOptionalError() async throws -> String {
// OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-NIL-ERROR %s
func nonOptionalResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
completion("abc", nil)
}
// NON-OPTIONAL-RESULT-AND-NIL-ERROR: func nonOptionalResultAndNilError() async throws -> String {
// NON-OPTIONAL-RESULT-AND-NIL-ERROR-NEXT: return "abc"
// NON-OPTIONAL-RESULT-AND-NIL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR %s
func nonOptionalResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion("abc", err)
}
}
// NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR: func nonOptionalResultAndOptionalRelayedError() async throws -> String {
// NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return "abc"
// NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func nonOptionalResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
completion("abc", makeOptionalError())
}
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nonOptionalResultAndOptionalComplexError() async throws -> String {
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() {
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else {
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return "abc"
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR %s
func nonOptionalResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
completion("abc", CustomError.Bad)
}
// NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR: func nonOptionalResultAndNonOptionalError() async throws -> String {
// NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=WRAP-COMPLETION-CALL-IN-PARENS %s
func wrapCompletionCallInParenthesis(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
(completion(res, err))
}
}
// WRAP-COMPLETION-CALL-IN-PARENS: func wrapCompletionCallInParenthesis() async throws -> String {
// WRAP-COMPLETION-CALL-IN-PARENS-NEXT: let res = try await simpleErr(arg: "test")
// WRAP-COMPLETION-CALL-IN-PARENS-NEXT: return res
// WRAP-COMPLETION-CALL-IN-PARENS-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=WRAP-RESULT-IN-PARENS %s
func wrapResultInParenthesis(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion((res).self, err)
}
}
// WRAP-RESULT-IN-PARENS: func wrapResultInParenthesis() async throws -> String {
// WRAP-RESULT-IN-PARENS-NEXT: let res = try await simpleErr(arg: "test")
// WRAP-RESULT-IN-PARENS-NEXT: return res
// WRAP-RESULT-IN-PARENS-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TWO-COMPLETION-HANDLER-CALLS %s
func twoCompletionHandlerCalls(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, err)
completion(res, err)
}
}
// TWO-COMPLETION-HANDLER-CALLS: func twoCompletionHandlerCalls() async throws -> String {
// TWO-COMPLETION-HANDLER-CALLS-NEXT: let res = try await simpleErr(arg: "test")
// TWO-COMPLETION-HANDLER-CALLS-NEXT: return res
// TWO-COMPLETION-HANDLER-CALLS-NEXT: return res
// TWO-COMPLETION-HANDLER-CALLS-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTED-IGNORED %s
func nestedIgnored() throws {
simple { _ in
print("done")
simple { _ in
print("done")
}
}
}
// NESTED-IGNORED: func nestedIgnored() async throws {
// NESTED-IGNORED-NEXT: let _ = await simple()
// NESTED-IGNORED-NEXT: print("done")
// NESTED-IGNORED-NEXT: let _ = await simple()
// NESTED-IGNORED-NEXT: print("done")
// NESTED-IGNORED-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=IGNORED-ERR %s
func nestedIgnoredErr() throws {
simpleErr(arg: "") { str, _ in
if str == nil {
print("error")
}
simpleErr(arg: "") { str, _ in
if str == nil {
print("error")
}
}
}
}
// IGNORED-ERR: func nestedIgnoredErr() async throws {
// IGNORED-ERR-NEXT: do {
// IGNORED-ERR-NEXT: let str = try await simpleErr(arg: "")
// IGNORED-ERR-NEXT: do {
// IGNORED-ERR-NEXT: let str1 = try await simpleErr(arg: "")
// IGNORED-ERR-NEXT: } catch {
// IGNORED-ERR-NEXT: print("error")
// IGNORED-ERR-NEXT: }
// IGNORED-ERR-NEXT: } catch {
// IGNORED-ERR-NEXT: print("error")
// IGNORED-ERR-NEXT: }
// IGNORED-ERR-NEXT: }
| apache-2.0 | fd1481d93638407dfe14b2a8bff580b6 | 46.980854 | 183 | 0.695202 | 3.200609 | false | false | false | false |
firebase/quickstart-ios | database/DatabaseExampleSwift/SignInViewController.swift | 1 | 4970 | //
// Copyright (c) 2015 Google Inc.
//
// 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 UIKit
import FirebaseDatabase
import FirebaseAuth
@objc(SignInViewController)
class SignInViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var emailField: UITextField!
@IBOutlet var passwordField: UITextField!
var ref: DatabaseReference!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if Auth.auth().currentUser != nil {
performSegue(withIdentifier: "signIn", sender: nil)
}
ref = Database.database().reference()
}
// Saves user profile information to user database
func saveUserInfo(_ user: FirebaseAuth.User, withUsername username: String) {
// Create a change request
showSpinner {}
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = username
// Commit profile changes to server
changeRequest?.commitChanges { error in
self.hideSpinner {}
if let error = error {
self.showMessagePrompt(error.localizedDescription)
return
}
// [START basic_write]
self.ref.child("users").child(user.uid).setValue(["username": username])
// [END basic_write]
self.performSegue(withIdentifier: "signIn", sender: nil)
}
}
@IBAction func didTapEmailLogin(_ sender: AnyObject) {
guard let email = emailField.text, let password = passwordField.text else {
showMessagePrompt("email/password can't be empty")
return
}
showSpinner {}
// Sign user in
Auth.auth().signIn(withEmail: email, password: password, completion: { authResult, error in
self.hideSpinner {}
guard let user = authResult?.user, error == nil else {
self.showMessagePrompt(error!.localizedDescription)
return
}
self.ref.child("users").child(user.uid).observeSingleEvent(of: .value, with: { snapshot in
// Check if user already exists
guard !snapshot.exists() else {
self.performSegue(withIdentifier: "signIn", sender: nil)
return
}
// Otherwise, create the new user account
self.showTextInputPrompt(withMessage: "Username:") { userPressedOK, username in
guard let username = username else {
self.showMessagePrompt("Username can't be empty")
return
}
self.saveUserInfo(user, withUsername: username)
}
}) // End of observeSingleEvent
}) // End of signIn
}
@IBAction func didTapSignUp(_ sender: AnyObject) {
func getEmail(completion: @escaping (String) -> Void) {
showTextInputPrompt(withMessage: "Email:") { userPressedOK, email in
guard let email = email else {
self.showMessagePrompt("Email can't be empty.")
return
}
completion(email)
}
}
func getUsername(completion: @escaping (String) -> Void) {
showTextInputPrompt(withMessage: "Username:") { userPressedOK, username in
guard let username = username else {
self.showMessagePrompt("Username can't be empty.")
return
}
completion(username)
}
}
func getPassword(completion: @escaping (String) -> Void) {
showTextInputPrompt(withMessage: "Password:") { userPressedOK, password in
guard let password = password else {
self.showMessagePrompt("Password can't be empty.")
return
}
completion(password)
}
}
// Get the credentials of the user
getEmail { email in
getUsername { username in
getPassword { password in
// Create the user with the provided credentials
Auth.auth()
.createUser(withEmail: email, password: password, completion: { authResult, error in
guard let user = authResult?.user, error == nil else {
self.showMessagePrompt(error!.localizedDescription)
return
}
// Finally, save their profile
self.saveUserInfo(user, withUsername: username)
})
}
}
}
}
// MARK: - UITextFieldDelegate protocol methods
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
didTapEmailLogin(textField)
return true
}
}
| apache-2.0 | 2d784a410c67a9a389897f41f1e1dcf9 | 29.490798 | 96 | 0.649095 | 4.774256 | false | false | false | false |
firebase/firebase-ios-sdk | FirebaseMLModelDownloader/Sources/ModelDownloader.swift | 1 | 27475 | // Copyright 2021 Google LLC
//
// 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 FirebaseCore
import FirebaseInstallations
/// Possible ways to get a custom model.
public enum ModelDownloadType {
/// Get local model stored on device if available. If no local model on device, this is the same as `latestModel`.
case localModel
/// Get local model on device if available and update to latest model from server in the background. If no local model on device, this is the same as `latestModel`.
case localModelUpdateInBackground
/// Get latest model from server. Does not make a network call for model file download if local model matches the latest version on server.
case latestModel
}
/// Downloader to manage custom model downloads.
public class ModelDownloader {
/// Name of the app associated with this instance of ModelDownloader.
private let appName: String
/// Current Firebase app options.
private let options: FirebaseOptions
/// Installations instance for current Firebase app.
private let installations: Installations
/// User defaults for model info.
private let userDefaults: UserDefaults
/// Telemetry logger tied to this instance of model downloader.
let telemetryLogger: TelemetryLogger?
/// Number of retries in case of model download URL expiry.
var numberOfRetries: Int = 1
/// Shared dictionary mapping app name to a specific instance of model downloader.
// TODO: Switch to using Firebase components.
private static var modelDownloaderDictionary: [String: ModelDownloader] = [:]
/// Download task associated with the model currently being downloaded.
private var currentDownloadTask: [String: ModelDownloadTask] = [:]
/// DispatchQueue to manage download task dictionary.
let taskSerialQueue = DispatchQueue(label: "downloadtask.serial.queue")
/// Re-dispatch a function on the main queue.
func asyncOnMainQueue(_ work: @autoclosure @escaping () -> Void) {
DispatchQueue.main.async {
work()
}
}
/// Private init for model downloader.
private init(app: FirebaseApp, defaults: UserDefaults = .firebaseMLDefaults) {
appName = app.name
options = app.options
installations = Installations.installations(app: app)
userDefaults = defaults
// Respect Firebase-wide data collection setting.
telemetryLogger = TelemetryLogger(app: app)
// Notification of app deletion.
let notificationName = "FIRAppDeleteNotification"
NotificationCenter.default.addObserver(
self,
selector: #selector(deleteModelDownloader),
name: Notification.Name(notificationName),
object: nil
)
}
/// Handles app deletion notification.
@objc private func deleteModelDownloader(notification: Notification) {
let userInfoKey = "FIRAppNameKey"
if let userInfo = notification.userInfo,
let appName = userInfo[userInfoKey] as? String {
ModelDownloader.modelDownloaderDictionary.removeValue(forKey: appName)
// TODO: Clean up user defaults.
// TODO: Clean up local instances of app.
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription.deleteModelDownloader,
messageCode: .downloaderInstanceDeleted)
}
}
/// Model downloader with default app.
public static func modelDownloader() -> ModelDownloader {
guard let defaultApp = FirebaseApp.app() else {
fatalError(ModelDownloader.ErrorDescription.defaultAppNotConfigured)
}
return modelDownloader(app: defaultApp)
}
/// Model Downloader with custom app.
public static func modelDownloader(app: FirebaseApp) -> ModelDownloader {
if let downloader = modelDownloaderDictionary[app.name] {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription.retrieveModelDownloader,
messageCode: .downloaderInstanceRetrieved)
return downloader
} else {
let downloader = ModelDownloader(app: app)
modelDownloaderDictionary[app.name] = downloader
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription.createModelDownloader,
messageCode: .downloaderInstanceCreated)
return downloader
}
}
/// Downloads a custom model to device or gets a custom model already on device, with an optional handler for progress.
/// - Parameters:
/// - modelName: The name of the model, matching Firebase console.
/// - downloadType: ModelDownloadType used to get the model.
/// - conditions: Conditions needed to perform a model download.
/// - progressHandler: Optional. Returns a float in [0.0, 1.0] that can be used to monitor model download progress.
/// - completion: Returns either a `CustomModel` on success, or a `DownloadError` on failure, at the end of a model download.
public func getModel(name modelName: String,
downloadType: ModelDownloadType,
conditions: ModelDownloadConditions,
progressHandler: ((Float) -> Void)? = nil,
completion: @escaping (Result<CustomModel, DownloadError>) -> Void) {
guard !modelName.isEmpty else {
asyncOnMainQueue(completion(.failure(.emptyModelName)))
return
}
switch downloadType {
case .localModel:
if let localModel = getLocalModel(modelName: modelName) {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription.localModelFound,
messageCode: .localModelFound)
asyncOnMainQueue(completion(.success(localModel)))
} else {
getRemoteModel(
modelName: modelName,
conditions: conditions,
progressHandler: progressHandler,
completion: completion
)
}
case .localModelUpdateInBackground:
if let localModel = getLocalModel(modelName: modelName) {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription.localModelFound,
messageCode: .localModelFound)
asyncOnMainQueue(completion(.success(localModel)))
telemetryLogger?.logModelDownloadEvent(
eventName: .modelDownload,
status: .scheduled,
model: CustomModel(name: modelName, size: 0, path: "", hash: ""),
downloadErrorCode: .noError
)
// Update local model in the background.
DispatchQueue.global(qos: .utility).async { [weak self] in
self?.getRemoteModel(
modelName: modelName,
conditions: conditions,
progressHandler: nil,
completion: { result in
switch result {
case let .success(model):
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription
.backgroundModelDownloaded,
messageCode: .backgroundModelDownloaded)
self?.telemetryLogger?.logModelDownloadEvent(
eventName: .modelDownload,
status: .succeeded,
model: model,
downloadErrorCode: .noError
)
case .failure:
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.ErrorDescription
.backgroundModelDownload,
messageCode: .backgroundDownloadError)
self?.telemetryLogger?.logModelDownloadEvent(
eventName: .modelDownload,
status: .failed,
model: CustomModel(name: modelName, size: 0, path: "", hash: ""),
downloadErrorCode: .downloadFailed
)
}
}
)
}
} else {
getRemoteModel(
modelName: modelName,
conditions: conditions,
progressHandler: progressHandler,
completion: completion
)
}
case .latestModel:
getRemoteModel(
modelName: modelName,
conditions: conditions,
progressHandler: progressHandler,
completion: completion
)
}
}
/// Gets the set of all downloaded models saved on device.
/// - Parameter completion: Returns either a set of `CustomModel` models on success, or a `DownloadedModelError` on failure.
public func listDownloadedModels(completion: @escaping (Result<Set<CustomModel>,
DownloadedModelError>) -> Void) {
do {
let modelURLs = try ModelFileManager.contentsOfModelsDirectory()
var customModels = Set<CustomModel>()
// Retrieve model name from URL.
for url in modelURLs {
guard let modelName = ModelFileManager.getModelNameFromFilePath(url) else {
let description = ModelDownloader.ErrorDescription.parseModelName(url.path)
DeviceLogger.logEvent(level: .debug,
message: description,
messageCode: .modelNameParseError)
asyncOnMainQueue(completion(.failure(.internalError(description: description))))
return
}
// Check if model information corresponding to model is stored in UserDefaults.
guard let modelInfo = getLocalModelInfo(modelName: modelName) else {
let description = ModelDownloader.ErrorDescription.noLocalModelInfo(modelName)
DeviceLogger.logEvent(level: .debug,
message: description,
messageCode: .noLocalModelInfo)
asyncOnMainQueue(completion(.failure(.internalError(description: description))))
return
}
// Ensure that local model path is as expected, and reachable.
guard let modelURL = ModelFileManager.getDownloadedModelFileURL(
appName: appName,
modelName: modelName
),
ModelFileManager.isFileReachable(at: modelURL) else {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.ErrorDescription.outdatedModelPath,
messageCode: .outdatedModelPathError)
asyncOnMainQueue(completion(.failure(.internalError(description: ModelDownloader
.ErrorDescription.outdatedModelPath))))
return
}
let model = CustomModel(localModelInfo: modelInfo, path: modelURL.path)
// Add model to result set.
customModels.insert(model)
}
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription.allLocalModelsFound,
messageCode: .allLocalModelsFound)
completion(.success(customModels))
} catch let error as DownloadedModelError {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.ErrorDescription.listModelsFailed(error),
messageCode: .listModelsError)
asyncOnMainQueue(completion(.failure(error)))
} catch {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.ErrorDescription.listModelsFailed(error),
messageCode: .listModelsError)
asyncOnMainQueue(completion(.failure(.internalError(description: error
.localizedDescription))))
}
}
/// Deletes a custom model file from device as well as corresponding model information saved in UserDefaults.
/// - Parameters:
/// - modelName: The name of the model, matching Firebase console and already downloaded to device.
/// - completion: Returns a `DownloadedModelError` on failure.
public func deleteDownloadedModel(name modelName: String,
completion: @escaping (Result<Void, DownloadedModelError>)
-> Void) {
// Ensure that there is a matching model file on device, with corresponding model information in UserDefaults.
guard let modelURL = ModelFileManager.getDownloadedModelFileURL(
appName: appName,
modelName: modelName
),
let localModelInfo = getLocalModelInfo(modelName: modelName),
ModelFileManager.isFileReachable(at: modelURL)
else {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.ErrorDescription.modelNotFound(modelName),
messageCode: .modelNotFound)
asyncOnMainQueue(completion(.failure(.notFound)))
return
}
do {
// Remove model file from device.
try ModelFileManager.removeFile(at: modelURL)
// Clear out corresponding local model info.
localModelInfo.removeFromDefaults(userDefaults, appName: appName)
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription.modelDeleted,
messageCode: .modelDeleted)
telemetryLogger?.logModelDeletedEvent(
eventName: .remoteModelDeleteOnDevice,
isSuccessful: true
)
asyncOnMainQueue(completion(.success(())))
} catch let error as DownloadedModelError {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.ErrorDescription.modelDeletionFailed(error),
messageCode: .modelDeletionFailed)
telemetryLogger?.logModelDeletedEvent(
eventName: .remoteModelDeleteOnDevice,
isSuccessful: false
)
asyncOnMainQueue(completion(.failure(error)))
} catch {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.ErrorDescription.modelDeletionFailed(error),
messageCode: .modelDeletionFailed)
telemetryLogger?.logModelDeletedEvent(
eventName: .remoteModelDeleteOnDevice,
isSuccessful: false
)
asyncOnMainQueue(completion(.failure(.internalError(description: error
.localizedDescription))))
}
}
}
extension ModelDownloader {
/// Get model information for model saved on device, if available.
private func getLocalModelInfo(modelName: String) -> LocalModelInfo? {
guard let localModelInfo = LocalModelInfo(
fromDefaults: userDefaults,
name: modelName,
appName: appName
) else {
let description = ModelDownloader.DebugDescription.noLocalModelInfo(modelName)
DeviceLogger.logEvent(level: .debug,
message: description,
messageCode: .noLocalModelInfo)
return nil
}
/// Local model info is only considered valid if there is a corresponding model file on device.
guard let modelURL = ModelFileManager.getDownloadedModelFileURL(
appName: appName,
modelName: modelName
), ModelFileManager.isFileReachable(at: modelURL) else {
let description = ModelDownloader.DebugDescription.noLocalModelFile(modelName)
DeviceLogger.logEvent(level: .debug,
message: description,
messageCode: .noLocalModelFile)
return nil
}
return localModelInfo
}
/// Get model saved on device, if available.
private func getLocalModel(modelName: String) -> CustomModel? {
guard let modelURL = ModelFileManager.getDownloadedModelFileURL(
appName: appName,
modelName: modelName
), let localModelInfo = getLocalModelInfo(modelName: modelName) else { return nil }
let model = CustomModel(localModelInfo: localModelInfo, path: modelURL.path)
return model
}
/// Download and get model from server, unless the latest model is already available on device.
private func getRemoteModel(modelName: String,
conditions: ModelDownloadConditions,
progressHandler: ((Float) -> Void)? = nil,
completion: @escaping (Result<CustomModel, DownloadError>) -> Void) {
let localModelInfo = getLocalModelInfo(modelName: modelName)
guard let projectID = options.projectID, let apiKey = options.apiKey else {
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.ErrorDescription.invalidOptions,
messageCode: .invalidOptions)
completion(.failure(.internalError(description: ModelDownloader.ErrorDescription
.invalidOptions)))
return
}
let modelInfoRetriever = ModelInfoRetriever(
modelName: modelName,
projectID: projectID,
apiKey: apiKey,
appName: appName, installations: installations,
localModelInfo: localModelInfo,
telemetryLogger: telemetryLogger
)
let downloader = ModelFileDownloader(conditions: conditions)
downloadInfoAndModel(
modelName: modelName,
modelInfoRetriever: modelInfoRetriever,
downloader: downloader,
conditions: conditions,
progressHandler: progressHandler,
completion: completion
)
}
/// Get model info and model file from server.
func downloadInfoAndModel(modelName: String,
modelInfoRetriever: ModelInfoRetriever,
downloader: FileDownloader,
conditions: ModelDownloadConditions,
progressHandler: ((Float) -> Void)? = nil,
completion: @escaping (Result<CustomModel, DownloadError>)
-> Void) {
modelInfoRetriever.downloadModelInfo { result in
switch result {
case let .success(downloadModelInfoResult):
switch downloadModelInfoResult {
// New model info was downloaded from server.
case let .modelInfo(remoteModelInfo):
// Progress handler for model file download.
let taskProgressHandler: ModelDownloadTask.ProgressHandler = { progress in
if let progressHandler = progressHandler {
self.asyncOnMainQueue(progressHandler(progress))
}
}
// Completion handler for model file download.
let taskCompletion: ModelDownloadTask.Completion = { result in
switch result {
case let .success(model):
self.asyncOnMainQueue(completion(.success(model)))
case let .failure(error):
switch error {
case .notFound:
self.asyncOnMainQueue(completion(.failure(.notFound)))
case .invalidArgument:
self.asyncOnMainQueue(completion(.failure(.invalidArgument)))
case .permissionDenied:
self.asyncOnMainQueue(completion(.failure(.permissionDenied)))
// This is the error returned when model download URL has expired.
case .expiredDownloadURL:
// Retry model info and model file download, if allowed.
guard self.numberOfRetries > 0 else {
self
.asyncOnMainQueue(
completion(.failure(.internalError(description: ModelDownloader
.ErrorDescription
.expiredModelInfo)))
)
return
}
self.numberOfRetries -= 1
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription.retryDownload,
messageCode: .retryDownload)
self.downloadInfoAndModel(
modelName: modelName,
modelInfoRetriever: modelInfoRetriever,
downloader: downloader,
conditions: conditions,
progressHandler: progressHandler,
completion: completion
)
default:
self.asyncOnMainQueue(completion(.failure(error)))
}
}
self.taskSerialQueue.async {
// Stop keeping track of current download task.
self.currentDownloadTask.removeValue(forKey: modelName)
}
}
self.taskSerialQueue.sync {
// Merge duplicate requests if there is already a download in progress for the same model.
if let downloadTask = self.currentDownloadTask[modelName],
downloadTask.canMergeRequests() {
downloadTask.merge(
newProgressHandler: taskProgressHandler,
newCompletion: taskCompletion
)
DeviceLogger.logEvent(level: .debug,
message: ModelDownloader.DebugDescription.mergingRequests,
messageCode: .mergeRequests)
if downloadTask.canResume() {
downloadTask.resume()
}
// TODO: Handle else.
} else {
// Create download task for model file download.
let downloadTask = ModelDownloadTask(
remoteModelInfo: remoteModelInfo,
appName: self.appName,
defaults: self.userDefaults,
downloader: downloader,
progressHandler: taskProgressHandler,
completion: taskCompletion,
telemetryLogger: self.telemetryLogger
)
// Keep track of current download task to allow for merging duplicate requests.
self.currentDownloadTask[modelName] = downloadTask
downloadTask.resume()
}
}
/// Local model info is the latest model info.
case .notModified:
guard let localModel = self.getLocalModel(modelName: modelName) else {
// This can only happen if either local model info or the model file was wiped out after model info request but before server response.
self
.asyncOnMainQueue(completion(.failure(.internalError(description: ModelDownloader
.ErrorDescription.deletedLocalModelInfoOrFile))))
return
}
self.asyncOnMainQueue(completion(.success(localModel)))
}
// Error retrieving model info.
case let .failure(error):
self.asyncOnMainQueue(completion(.failure(error)))
}
}
}
}
/// Possible errors with model downloading.
public enum DownloadError: Error, Equatable {
/// No model with this name exists on server.
case notFound
/// Invalid, incomplete, or missing permissions for model download.
case permissionDenied
/// Conditions not met to perform download.
case failedPrecondition
/// Requests quota exhausted.
case resourceExhausted
/// Not enough space for model on device.
case notEnoughSpace
/// Malformed model name or Firebase app options.
case invalidArgument
/// Model name is empty.
case emptyModelName
/// Other errors with description.
case internalError(description: String)
}
/// Possible errors with locating a model file on device.
public enum DownloadedModelError: Error {
/// No model with this name exists on device.
case notFound
/// File system error.
case fileIOError(description: String)
/// Other errors with description.
case internalError(description: String)
}
/// Extension to handle internally meaningful errors.
extension DownloadError {
/// Model download URL expired before model download.
// Model info retrieval and download is retried `numberOfRetries` times before failing.
static let expiredDownloadURL: DownloadError = DownloadError
.internalError(description: "Expired model download URL.")
}
/// Possible debug and error messages while using model downloader.
extension ModelDownloader {
/// Debug descriptions.
private enum DebugDescription {
static let createModelDownloader =
"Initialized with new downloader instance associated with this app."
static let retrieveModelDownloader =
"Initialized with existing downloader instance associated with this app."
static let deleteModelDownloader = "Model downloader instance deleted due to app deletion."
static let localModelFound = "Found local model on device."
static let allLocalModelsFound = "Found and listed all local models."
static let noLocalModelInfo = { (name: String) in
"No local model info for model named: \(name)."
}
static let noLocalModelFile = { (name: String) in
"No local model file for model named: \(name)."
}
static let backgroundModelDownloaded = "Downloaded latest model in the background."
static let modelDeleted = "Model deleted successfully."
static let mergingRequests = "Merging duplicate download requests."
static let retryDownload = "Retrying download."
}
/// Error descriptions.
private enum ErrorDescription {
static let defaultAppNotConfigured = "Default Firebase app not configured."
static let invalidOptions = "Unable to retrieve project ID and/or API key for Firebase app."
static let modelDownloadFailed = { (error: Error) in
"Model download failed with error: \(error)"
}
static let modelNotFound = { (name: String) in
"Model deletion failed due to no model found with name: \(name)"
}
static let modelInfoRetrievalFailed = { (error: Error) in
"Model info retrieval failed with error: \(error)"
}
static let backgroundModelDownload = "Failed to update model in background."
static let expiredModelInfo = "Unable to update expired model info."
static let listModelsFailed = { (error: Error) in
"Unable to list models, failed with error: \(error)"
}
static let parseModelName = { (path: String) in
"List models failed due to unexpected model file name at \(path)."
}
static let noLocalModelInfo = { (name: String) in
"List models failed due to no local model info for model file named: \(name)."
}
static let deletedLocalModelInfoOrFile =
"Model unavailable due to deleted local model info or model file."
static let outdatedModelPath =
"List models failed due to outdated model paths in local storage."
static let modelDeletionFailed = { (error: Error) in
"Model deletion failed with error: \(error)"
}
}
}
/// Model downloader extension for testing.
extension ModelDownloader {
/// Model downloader instance for testing.
static func modelDownloaderWithDefaults(_ defaults: UserDefaults,
app: FirebaseApp) -> ModelDownloader {
let downloader = ModelDownloader(app: app, defaults: defaults)
return downloader
}
}
| apache-2.0 | d9f31fea2755e7a6983c73f2d46638c4 | 42.131868 | 166 | 0.643094 | 5.479657 | false | false | false | false |
nixzhu/MonkeyKing | Sources/MonkeyKing/MonkeyKing+handleOpenURL.swift | 1 | 18661 |
import UIKit
import Security
extension MonkeyKing {
public class func handleOpenUserActivity(_ userActivity: NSUserActivity) -> Bool {
guard
userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let url = userActivity.webpageURL
else {
return false
}
var isHandled = false
shared.accountSet.forEach { account in
switch account {
case .weChat(_, _, _, let wxUL):
if let wxUL = wxUL, url.absoluteString.hasPrefix(wxUL) {
isHandled = handleWechatUniversalLink(url)
}
case .qq(_, let qqUL):
if let qqUL = qqUL, url.absoluteString.hasPrefix(qqUL) {
isHandled = handleQQUniversalLink(url)
}
case .weibo(_, _, _, let wbUL):
if let wbURL = wbUL, url.absoluteString.hasPrefix(wbURL) {
isHandled = handleWeiboUniversalLink(url)
}
default:
()
}
}
lastMessage = nil
return isHandled
}
// MARK: - Wechat Universal Links
@discardableResult
private class func handleWechatUniversalLink(_ url: URL) -> Bool {
guard let comps = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return false
}
// MARK: - update token
if let authToken = comps.valueOfQueryItem("wechat_auth_token"), !authToken.isEmpty {
wechatAuthToken = authToken
}
// MARK: - refreshToken
if comps.path.hasSuffix("refreshToken") {
if let msg = lastMessage {
deliver(msg, completionHandler: shared.deliverCompletionHandler ?? { _ in })
}
return true
}
// MARK: - oauth
if comps.path.hasSuffix("oauth"), let code = comps.valueOfQueryItem("code") {
return handleWechatOAuth(code: code)
}
// MARK: - pay
if comps.path.hasSuffix("pay"), let ret = comps.valueOfQueryItem("ret"), let retIntValue = Int(ret) {
if retIntValue == 0 {
shared.payCompletionHandler?(.success(()))
return true
} else {
let response: [String: String] = [
"ret": ret,
"returnKey": comps.valueOfQueryItem("returnKey") ?? "",
"notifyStr": comps.valueOfQueryItem("notifyStr") ?? ""
]
shared.payCompletionHandler?(.failure(.apiRequest(.unrecognizedError(response: response))))
return false
}
}
// TODO: handle `resendContextReqByScheme`
// TODO: handle `jointpay`
// TODO: handle `offlinepay`
// TODO: handle `cardPackage`
// TODO: handle `choosecard`
// TODO: handle `chooseinvoice`
// TODO: handle `openwebview`
// TODO: handle `openbusinesswebview`
// TODO: handle `openranklist`
// TODO: handle `opentypewebview`
return handleWechatCallbackResultViaPasteboard()
}
private class func handleWechatOAuth(code: String) -> Bool {
if code == "authdeny" {
shared.oauthFromWeChatCodeCompletionHandler = nil
return false
}
// Login succeed
if let halfOauthCompletion = shared.oauthFromWeChatCodeCompletionHandler {
halfOauthCompletion(.success(code))
shared.oauthFromWeChatCodeCompletionHandler = nil
} else {
fetchWeChatOAuthInfoByCode(code: code) { result in
shared.oauthCompletionHandler?(result)
}
}
return true
}
private class func handleWechatCallbackResultViaPasteboard() -> Bool {
guard
let data = UIPasteboard.general.data(forPasteboardType: "content"),
let dict = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]
else {
return false
}
guard
let account = shared.accountSet[.weChat],
let info = dict[account.appID] as? [String: Any],
let result = info["result"] as? String,
let resultCode = Int(result)
else {
return false
}
// OAuth Failed
if let state = info["state"] as? String, state == "Weixinauth", resultCode != 0 {
let error: Error = resultCode == -2
? .userCancelled
: .sdk(.other(code: result))
shared.oauthCompletionHandler?(.failure(error))
return false
}
let succeed = (resultCode == 0)
// Share or Launch Mini App
let messageExtKey = "messageExt"
if succeed {
if let messageExt = info[messageExtKey] as? String {
shared.launchFromWeChatMiniAppCompletionHandler?(.success(messageExt))
} else {
shared.deliverCompletionHandler?(.success(nil))
}
} else {
if let messageExt = info[messageExtKey] as? String {
shared.launchFromWeChatMiniAppCompletionHandler?(.success(messageExt))
return true
} else {
let error: Error = resultCode == -2
? .userCancelled
: .sdk(.other(code: result))
shared.deliverCompletionHandler?(.failure(error))
}
}
return succeed
}
// MARK: - QQ Universal Links
@discardableResult
private class func handleQQUniversalLink(_ url: URL) -> Bool {
guard let comps = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return false
}
var error: Error?
if
let actionInfoString = comps.queryItems?.first(where: { $0.name == "sdkactioninfo" })?.value,
let data = Data(base64Encoded: actionInfoString),
let actionInfo = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: Any] {
// What for?
// sck_action_query=appsign_bundlenull=2&source=qq&source_scheme=mqqapi&error=0&version=1
// sdk_action_path=
// sdk_action_scheme=tencent101******8
// sdk_action_host=response_from_qq
if let query = actionInfo["sdk_action_query"] as? String {
if query.contains("error=0") {
error = nil
} else if query.contains("error=-4") {
error = .userCancelled
} else {
// TODO: handle error_description=dGhlIHVzZXIgZ2l2ZSB1cCB0aGUgY3VycmVudCBvcGVyYXRpb24=
error = .noAccount
}
}
}
guard handleQQCallbackResult(url: url, error: error) else {
return false
}
return true
}
private class func handleQQCallbackResult(url: URL, error: Error?) -> Bool {
guard let account = shared.accountSet[.qq] else { return false }
// Share
// Pasteboard is empty
if
let ul = account.universalLink,
url.absoluteString.hasPrefix(ul),
url.path.contains("response_from_qq") {
let result = error.map(Result<ResponseJSON?, Error>.failure) ?? .success(nil)
shared.deliverCompletionHandler?(result)
return true
}
// OpenApi.m:131 getDictionaryFromGeneralPasteBoard
guard
let data = UIPasteboard.general.data(forPasteboardType: "com.tencent.tencent\(account.appID)"),
let info = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: Any]
else {
shared.oauthCompletionHandler?(.failure(.sdk(.deserializeFailed)))
return false
}
if url.path.contains("mqqsignapp") && url.query?.contains("generalpastboard=1") == true {
// OpenApi.m:680 start universallink signature.
guard
let token = info["appsign_token"] as? String,
let appSignRedirect = info["appsign_redirect"] as? String,
var redirectComps = URLComponents(string: appSignRedirect)
else {
return false
}
qqAppSignToken = token
redirectComps.queryItems?.append(.init(name: "appsign_token", value: qqAppSignToken))
if let callbackName = redirectComps.queryItems?.first(where: { $0.name == "callback_name" })?.value {
qqAppSignTxid = callbackName
redirectComps.queryItems?.append(.init(name: "appsign_txid", value: qqAppSignTxid))
}
if let ul = account.universalLink, url.absoluteString.hasPrefix(ul) {
redirectComps.scheme = "https"
redirectComps.host = "qm.qq.com"
redirectComps.path = "/opensdkul/mqqapi/share/to_fri"
}
// Try to open the redirect url provided above
if let redirectUrl = redirectComps.url, UIApplication.shared.canOpenURL(redirectUrl) {
UIApplication.shared.open(redirectUrl)
}
// Otherwise we just send last message again
else if let msg = lastMessage {
deliver(msg, completionHandler: shared.deliverCompletionHandler ?? { _ in })
}
// The dictionary also contains "appsign_retcode=25105" and "appsign_bundlenull=2"
// We don't have to handle them yet.
return true
}
// OAuth is the only leftover
guard let result = info["ret"] as? Int, result == 0 else {
let error: Error
if let errorDomatin = info["user_cancelled"] as? String, errorDomatin.uppercased() == "YES" {
error = .userCancelled
} else {
error = .apiRequest(.unrecognizedError(response: nil))
}
shared.oauthCompletionHandler?(.failure(error))
return false
}
shared.oauthCompletionHandler?(.success(info))
return true
}
// MARK: - Weibo Universal Links
@discardableResult
private class func handleWeiboUniversalLink(_ url: URL) -> Bool {
guard let comps = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return false
}
if comps.path.hasSuffix("response") {
return handleWeiboCallbackResultViaPasteboard()
}
return false
}
private class func handleWeiboCallbackResultViaPasteboard() -> Bool {
let items = UIPasteboard.general.items
var results = [String: Any]()
for item in items {
for (key, value) in item {
if let valueData = value as? Data, key == "transferObject" {
results[key] = NSKeyedUnarchiver.unarchiveObject(with: valueData)
}
}
}
guard
let responseInfo = results["transferObject"] as? [String: Any],
let type = responseInfo["__class"] as? String else {
return false
}
guard let statusCode = responseInfo["statusCode"] as? Int else {
return false
}
switch type {
// OAuth
case "WBAuthorizeResponse":
if statusCode != 0 {
shared.oauthCompletionHandler?(.failure(.apiRequest(.unrecognizedError(response: responseInfo))))
return false
}
shared.oauthCompletionHandler?(.success(responseInfo))
return true
// Share
case "WBSendMessageToWeiboResponse":
let success = (statusCode == 0)
if success {
shared.deliverCompletionHandler?(.success(nil))
} else {
let error: Error = statusCode == -1
? .userCancelled
: .sdk(.other(code: String(statusCode)))
shared.deliverCompletionHandler?(.failure(error))
}
return success
default:
return false
}
}
// MARK: - OpenURL
public class func handleOpenURL(_ url: URL) -> Bool {
guard let urlScheme = url.scheme else { return false }
// WeChat
if urlScheme.hasPrefix("wx") {
let urlString = url.absoluteString
// OAuth
if urlString.contains("state=") {
let queryDictionary = url.monkeyking_queryDictionary
guard let code = queryDictionary["code"] else {
shared.oauthFromWeChatCodeCompletionHandler = nil
return false
}
if handleWechatOAuth(code: code) {
return true
}
}
// SMS OAuth
if urlString.contains("wapoauth") {
let queryDictionary = url.monkeyking_queryDictionary
guard let m = queryDictionary["m"] else { return false }
guard let t = queryDictionary["t"] else { return false }
guard let account = shared.accountSet[.weChat] else { return false }
let appID = account.appID
let urlString = "https://open.weixin.qq.com/connect/smsauthorize?appid=\(appID)&redirect_uri=\(appID)%3A%2F%2Foauth&response_type=code&scope=snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact&state=xxx&uid=1926559385&m=\(m)&t=\(t)"
addWebView(withURLString: urlString)
return true
}
// Pay
if urlString.contains("://pay/") {
let queryDictionary = url.monkeyking_queryDictionary
guard let ret = queryDictionary["ret"] else {
shared.payCompletionHandler?(.failure(.apiRequest(.missingParameter)))
return false
}
let result = (ret == "0")
if result {
shared.payCompletionHandler?(.success(()))
} else {
shared.payCompletionHandler?(.failure(.apiRequest(.unrecognizedError(response: queryDictionary))))
}
return result
}
return handleWechatCallbackResultViaPasteboard()
}
// QQ
if urlScheme.lowercased().hasPrefix("qq") || urlScheme.hasPrefix("tencent") {
let errorDescription = url.monkeyking_queryDictionary["error"] ?? url.lastPathComponent
var error: Error?
var success = (errorDescription == "0")
if success {
error = nil
} else {
error = errorDescription == "-4"
? .userCancelled
: .sdk(.other(code: errorDescription))
}
// OAuth
if url.path.contains("mqzone") {
success = handleQQCallbackResult(url: url, error: error)
}
// Share
else {
if let error = error {
shared.deliverCompletionHandler?(.failure(error))
} else {
shared.deliverCompletionHandler?(.success(nil))
}
}
return success
}
// Weibo
if urlScheme.hasPrefix("wb") {
return handleWeiboCallbackResultViaPasteboard()
}
// Pocket OAuth
if urlScheme.hasPrefix("pocketapp") {
shared.oauthCompletionHandler?(.success(nil))
return true
}
// Alipay
let account = shared.accountSet[.alipay]
if let appID = account?.appID, urlScheme == "ap" + appID || urlScheme == "apoauth" + appID {
let urlString = url.absoluteString
if urlString.contains("//safepay/?") {
guard
let query = url.query,
let response = query.monkeyking_urlDecodedString?.data(using: .utf8),
let json = response.monkeyking_json,
let memo = json["memo"] as? [String: Any],
let status = memo["ResultStatus"] as? String
else {
shared.oauthCompletionHandler?(.failure(.apiRequest(.missingParameter)))
shared.payCompletionHandler?(.failure(.apiRequest(.missingParameter)))
return false
}
if status != "9000" {
shared.oauthCompletionHandler?(.failure(.apiRequest(.invalidParameter)))
shared.payCompletionHandler?(.failure(.apiRequest(.invalidParameter)))
return false
}
if urlScheme == "apoauth" + appID { // OAuth
let resultStr = memo["result"] as? String ?? ""
let urlStr = "https://www.example.com?" + resultStr
let resultDic = URL(string: urlStr)?.monkeyking_queryDictionary ?? [:]
if let _ = resultDic["auth_code"], let _ = resultDic["scope"] {
shared.oauthCompletionHandler?(.success(resultDic))
return true
}
shared.oauthCompletionHandler?(.failure(.apiRequest(.unrecognizedError(response: resultDic))))
return false
} else { // Pay
shared.payCompletionHandler?(.success(()))
}
return true
} else { // Share
guard
let data = UIPasteboard.general.data(forPasteboardType: "com.alipay.openapi.pb.resp.\(appID)"),
let dict = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
let objects = dict["$objects"] as? NSArray,
let result = objects[12] as? Int else {
return false
}
let success = (result == 0)
if success {
shared.deliverCompletionHandler?(.success(nil))
} else {
shared.deliverCompletionHandler?(.failure(.sdk(.other(code: String(result))))) // TODO: user cancelled
}
return success
}
}
if let handler = shared.openSchemeCompletionHandler {
handler(.success(url))
return true
}
return false
}
}
| mit | c75fe251e98b20267941209541581a5e | 35.662083 | 256 | 0.536734 | 5.187934 | false | false | false | false |
givingjan/SMTagView | TagViewSample/ViewController.swift | 1 | 2137 | //
// ViewController.swift
// TagViewSample
//
// Created by JaN on 2017/7/5.
// Copyright © 2017年 givingjan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var m_tagViewSingle: SMTagView!
@IBOutlet var m_tagViewMultiple: SMTagView!
@IBOutlet var m_btnChange: UIButton!
var m_bIsMultiple : Bool = true
var tags : [String] = ["咖啡Q","聰明奶茶","笑笑乒乓","下雨天的紅茶","明天的綠茶","笨豆漿","過期的茶葉蛋","雲端奶茶","國際的小鳳梨","黑胡椒樹皮"]
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.initView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK:Init
private func initMultiple() {
self.m_tagViewMultiple.layer.cornerRadius = 15.0
self.m_tagViewMultiple.tagMainColor = UIColor.orange
self.m_tagViewMultiple.setTagForMultiple(title: "選幾個喜歡的吧 ! (多選)", tagType: .fill, tags: tags, maximumSelect: 3, minimumSelect: 2) { (indexes) in
print("done:\(indexes)")
}
}
private func initSingle() {
self.m_tagViewSingle.layer.cornerRadius = 15.0
self.m_tagViewSingle.tagMainColor = UIColor.orange
self.m_tagViewSingle.setTagForSingle(title: "你要選哪個呢 ? (單選)", tagType: .border, tags: tags) { (index) in
print(index)
}
}
private func initView() {
initMultiple()
initSingle()
updateView()
}
private func updateView() {
self.m_tagViewSingle.isHidden = self.m_bIsMultiple
self.m_tagViewMultiple.isHidden = !self.m_bIsMultiple
}
@IBAction func handleChange(_ sender: Any) {
self.m_bIsMultiple = !self.m_bIsMultiple
let title = self.m_bIsMultiple == true ? "Change to Single" : "Change to Multiple"
self.m_btnChange.setTitle(title, for: .normal)
self.updateView()
}
}
| mit | d295e3904708646d7c2addf28672ab11 | 28.130435 | 152 | 0.620398 | 3.465517 | false | false | false | false |
ksco/swift-algorithm-club-cn | Combinatorics/Combinatorics.swift | 1 | 2660 | /* Calculates n! */
func factorial(n: Int) -> Int {
var n = n
var result = 1
while n > 1 {
result *= n
n -= 1
}
return result
}
/*
Calculates P(n, k), the number of permutations of n distinct symbols
in groups of size k.
*/
func permutations(n: Int, _ k: Int) -> Int {
var n = n
var answer = n
for _ in 1..<k {
n -= 1
answer *= n
}
return answer
}
/*
Prints out all the permutations of the given array.
Original algorithm by Niklaus Wirth.
See also Dr.Dobb's Magazine June 1993, Algorithm Alley
*/
func permuteWirth<T>(a: [T], _ n: Int) {
if n == 0 {
print(a) // display the current permutation
} else {
var a = a
permuteWirth(a, n - 1)
for i in 0..<n {
swap(&a[i], &a[n])
permuteWirth(a, n - 1)
swap(&a[i], &a[n])
}
}
}
/*
Prints out all the permutations of an n-element collection.
The initial array must be initialized with all zeros. The algorithm
uses 0 as a flag that indicates more work to be done on each level
of the recursion.
Original algorithm by Robert Sedgewick.
See also Dr.Dobb's Magazine June 1993, Algorithm Alley
*/
func permuteSedgewick(a: [Int], _ n: Int, inout _ pos: Int) {
var a = a
pos += 1
a[n] = pos
if pos == a.count - 1 {
print(a) // display the current permutation
} else {
for i in 0..<a.count {
if a[i] == 0 {
permuteSedgewick(a, i, &pos)
}
}
}
pos -= 1
a[n] = 0
}
/*
Calculates C(n, k), or "n-choose-k", i.e. how many different selections
of size k out of a total number of distinct elements (n) you can make.
Doesn't work very well for large numbers.
*/
func combinations(n: Int, _ k: Int) -> Int {
return permutations(n, k) / factorial(k)
}
/*
Calculates C(n, k), or "n-choose-k", i.e. the number of ways to choose
k things out of n possibilities.
*/
func quickBinomialCoefficient(n: Int, _ k: Int) -> Int {
var result = 1
for i in 0..<k {
result *= (n - i)
result /= (i + 1)
}
return result
}
/*
Calculates C(n, k), or "n-choose-k", i.e. the number of ways to choose
k things out of n possibilities.
Thanks to the dynamic programming, this algorithm from Skiena allows for
the calculation of much larger numbers, at the cost of temporary storage
space for the cached values.
*/
func binomialCoefficient(n: Int, _ k: Int) -> Int {
var bc = Array2D(columns: n + 1, rows: n + 1, initialValue: 0)
for i in 0...n {
bc[i, 0] = 1
bc[i, i] = 1
}
if n > 0 {
for i in 1...n {
for j in 1..<i {
bc[i, j] = bc[i - 1, j - 1] + bc[i - 1, j]
}
}
}
return bc[n, k]
}
| mit | 6f60291ffd46f473fefc63abe8b601b0 | 21.166667 | 74 | 0.586466 | 3.133098 | false | false | false | false |
LoopKit/LoopKit | LoopKitUI/View Controllers/SingleValueScheduleTableViewController.swift | 1 | 11387 | //
// SingleValueScheduleTableViewController.swift
// Naterade
//
// Created by Nathan Racklyeft on 2/13/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
import LoopKit
public enum RepeatingScheduleValueResult<T: RawRepresentable> {
case success(scheduleItems: [RepeatingScheduleValue<T>], timeZone: TimeZone)
case failure(Error)
}
public protocol SingleValueScheduleTableViewControllerSyncSource: AnyObject {
func syncScheduleValues(for viewController: SingleValueScheduleTableViewController, completion: @escaping (_ result: RepeatingScheduleValueResult<Double>) -> Void)
func syncButtonTitle(for viewController: SingleValueScheduleTableViewController) -> String
func syncButtonDetailText(for viewController: SingleValueScheduleTableViewController) -> String?
func singleValueScheduleTableViewControllerIsReadOnly(_ viewController: SingleValueScheduleTableViewController) -> Bool
}
open class SingleValueScheduleTableViewController: DailyValueScheduleTableViewController, RepeatingScheduleValueTableViewCellDelegate {
open override func viewDidLoad() {
super.viewDidLoad()
tableView.register(RepeatingScheduleValueTableViewCell.nib(), forCellReuseIdentifier: RepeatingScheduleValueTableViewCell.className)
tableView.register(TextButtonTableViewCell.self, forCellReuseIdentifier: TextButtonTableViewCell.className)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if syncSource == nil {
delegate?.dailyValueScheduleTableViewControllerWillFinishUpdating(self)
}
}
// MARK: - State
public var scheduleItems: [RepeatingScheduleValue<Double>] = []
override func addScheduleItem(_ sender: Any?) {
guard !isReadOnly && !isSyncInProgress else {
return
}
tableView.endEditing(false)
var startTime = TimeInterval(0)
var value = 0.0
if scheduleItems.count > 0, let cell = tableView.cellForRow(at: IndexPath(row: scheduleItems.count - 1, section: 0)) as? RepeatingScheduleValueTableViewCell {
let lastItem = scheduleItems.last!
let interval = cell.datePickerInterval
startTime = lastItem.startTime + interval
value = lastItem.value
if startTime >= TimeInterval(hours: 24) {
return
}
}
scheduleItems.append(
RepeatingScheduleValue(
startTime: min(TimeInterval(hours: 23.5), startTime),
value: value
)
)
super.addScheduleItem(sender)
}
override func insertableIndiciesByRemovingRow(_ row: Int, withInterval timeInterval: TimeInterval) -> [Bool] {
return insertableIndices(for: scheduleItems, removing: row, with: timeInterval)
}
var preferredValueFractionDigits: Int {
return 1
}
public weak var syncSource: SingleValueScheduleTableViewControllerSyncSource? {
didSet {
isReadOnly = syncSource?.singleValueScheduleTableViewControllerIsReadOnly(self) ?? false
if isViewLoaded {
tableView.reloadData()
}
}
}
private var isSyncInProgress = false {
didSet {
for cell in tableView.visibleCells {
switch cell {
case let cell as TextButtonTableViewCell:
cell.isEnabled = !isSyncInProgress
cell.isLoading = isSyncInProgress
case let cell as RepeatingScheduleValueTableViewCell:
cell.isReadOnly = isReadOnly || isSyncInProgress
default:
break
}
}
for item in navigationItem.rightBarButtonItems ?? [] {
item.isEnabled = !isSyncInProgress
}
navigationItem.hidesBackButton = isSyncInProgress
}
}
// MARK: - UITableViewDataSource
private enum Section: Int {
case schedule
case sync
}
open override func numberOfSections(in tableView: UITableView) -> Int {
if syncSource != nil {
return 2
}
return 1
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .schedule:
return scheduleItems.count
case .sync:
return 1
}
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .schedule:
let cell = tableView.dequeueReusableCell(withIdentifier: RepeatingScheduleValueTableViewCell.className, for: indexPath) as! RepeatingScheduleValueTableViewCell
let item = scheduleItems[indexPath.row]
let interval = cell.datePickerInterval
cell.timeZone = timeZone
cell.date = midnight.addingTimeInterval(item.startTime)
cell.valueNumberFormatter.minimumFractionDigits = preferredValueFractionDigits
cell.value = item.value
cell.unitString = unitDisplayString
cell.isReadOnly = isReadOnly || isSyncInProgress
cell.delegate = self
if indexPath.row > 0 {
let lastItem = scheduleItems[indexPath.row - 1]
cell.datePicker.minimumDate = midnight.addingTimeInterval(lastItem.startTime).addingTimeInterval(interval)
}
if indexPath.row < scheduleItems.endIndex - 1 {
let nextItem = scheduleItems[indexPath.row + 1]
cell.datePicker.maximumDate = midnight.addingTimeInterval(nextItem.startTime).addingTimeInterval(-interval)
} else {
cell.datePicker.maximumDate = midnight.addingTimeInterval(TimeInterval(hours: 24) - interval)
}
return cell
case .sync:
let cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath) as! TextButtonTableViewCell
cell.textLabel?.text = syncSource?.syncButtonTitle(for: self)
cell.isEnabled = !isSyncInProgress
cell.isLoading = isSyncInProgress
return cell
}
}
open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch Section(rawValue: section)! {
case .schedule:
return nil
case .sync:
return syncSource?.syncButtonDetailText(for: self)
}
}
open override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
scheduleItems.remove(at: indexPath.row)
super.tableView(tableView, commit: editingStyle, forRowAt: indexPath)
}
}
open override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if sourceIndexPath != destinationIndexPath {
let item = scheduleItems.remove(at: sourceIndexPath.row)
scheduleItems.insert(item, at: destinationIndexPath.row)
guard destinationIndexPath.row > 0, let cell = tableView.cellForRow(at: destinationIndexPath) as? RepeatingScheduleValueTableViewCell else {
return
}
let interval = cell.datePickerInterval
let startTime = scheduleItems[destinationIndexPath.row - 1].startTime + interval
scheduleItems[destinationIndexPath.row] = RepeatingScheduleValue(startTime: startTime, value: scheduleItems[destinationIndexPath.row].value)
// Since the valid date ranges of neighboring cells are affected, the lazy solution is to just reload the entire table view
DispatchQueue.main.async {
tableView.reloadData()
}
}
}
// MARK: - UITableViewDelegate
open override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return super.tableView(tableView, canEditRowAt: indexPath) && !isSyncInProgress
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
switch Section(rawValue: indexPath.section)! {
case .schedule:
break
case .sync:
if let syncSource = syncSource, !isSyncInProgress {
isSyncInProgress = true
syncSource.syncScheduleValues(for: self) { (result) in
DispatchQueue.main.async {
switch result {
case .success(let items, let timeZone):
self.scheduleItems = items
self.timeZone = timeZone
self.tableView.reloadSections([Section.schedule.rawValue], with: .fade)
self.isSyncInProgress = false
self.delegate?.dailyValueScheduleTableViewControllerWillFinishUpdating(self)
case .failure(let error):
self.present(UIAlertController(with: error), animated: true) {
self.isSyncInProgress = false
}
}
}
}
}
}
}
open override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
guard sourceIndexPath != proposedDestinationIndexPath, let cell = tableView.cellForRow(at: sourceIndexPath) as? RepeatingScheduleValueTableViewCell else {
return proposedDestinationIndexPath
}
let interval = cell.datePickerInterval
let indices = insertableIndices(for: scheduleItems, removing: sourceIndexPath.row, with: interval)
let closestDestinationRow = indices.insertableIndex(closestTo: proposedDestinationIndexPath.row, from: sourceIndexPath.row)
return IndexPath(row: closestDestinationRow, section: proposedDestinationIndexPath.section)
}
// MARK: - RepeatingScheduleValueTableViewCellDelegate
override public func datePickerTableViewCellDidUpdateDate(_ cell: DatePickerTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
let currentItem = scheduleItems[indexPath.row]
scheduleItems[indexPath.row] = RepeatingScheduleValue(
startTime: cell.date.timeIntervalSince(midnight),
value: currentItem.value
)
}
super.datePickerTableViewCellDidUpdateDate(cell)
}
func repeatingScheduleValueTableViewCellDidUpdateValue(_ cell: RepeatingScheduleValueTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
let currentItem = scheduleItems[indexPath.row]
scheduleItems[indexPath.row] = RepeatingScheduleValue(startTime: currentItem.startTime, value: cell.value)
}
}
}
| mit | 7cf07b213c4f63073c22fc6072b4178d | 36.953333 | 194 | 0.651765 | 6.157923 | false | false | false | false |
LoopKit/LoopKit | MockKitUI/View Controllers/IssueAlertTableViewController.swift | 1 | 5268 | //
// IssueAlertTableViewController.swift
// MockKitUI
//
// Created by Rick Pasetto on 4/24/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import UIKit
import LoopKit
import LoopKitUI
import MockKit
final class IssueAlertTableViewController: UITableViewController {
let cgmManager: MockCGMManager
static let delay = TimeInterval(60)
private enum AlertRow: Int, CaseIterable, CustomStringConvertible {
case immediate = 0
case delayed
case repeating
case issueLater
case buzz
case critical
case criticalDelayed
case retract // should be kept at the bottom of the list
var description: String {
switch self {
case .immediate: return "Issue an immediate alert"
case .delayed: return "Issue a \"delayed \(delay) seconds\" alert"
case .repeating: return "Issue a \"repeating every \(delay) seconds\" alert"
case .issueLater: return "Issue an immediate alert \(delay) seconds from now"
case .retract: return "Retract any alert above"
case .buzz: return "Issue an immediate vibrate alert"
case .critical: return "Issue a critical immediate alert"
case .criticalDelayed: return "Issue a \"delayed \(delay) seconds\" critical alert"
}
}
var trigger: Alert.Trigger {
switch self {
case .immediate: return .immediate
case .retract: return .immediate
case .critical: return .immediate
case .delayed: return .delayed(interval: delay)
case .criticalDelayed: return .delayed(interval: delay)
case .repeating: return .repeating(repeatInterval: delay)
case .issueLater: return .immediate
case .buzz: return .immediate
}
}
var delayBeforeIssue: TimeInterval? {
switch self {
case .issueLater: return delay
default: return nil
}
}
var identifier: Alert.AlertIdentifier {
switch self {
case .buzz: return MockCGMManager.buzz.identifier
case .critical, .criticalDelayed: return MockCGMManager.critical.identifier
default: return MockCGMManager.submarine.identifier
}
}
var metadata: Alert.Metadata? {
switch self {
case .buzz:
return Alert.Metadata(dict: [
"string": Alert.MetadataValue("Buzz"),
"int": Alert.MetadataValue(1),
"double": Alert.MetadataValue(2.34),
"bool": Alert.MetadataValue(true),
])
default:
return nil
}
}
}
init(cgmManager: MockCGMManager) {
self.cgmManager = cgmManager
super.init(style: .plain)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Issue Alerts"
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
tableView.register(TextButtonTableViewCell.self, forCellReuseIdentifier: TextButtonTableViewCell.className)
let button = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped(_:)))
navigationItem.setRightBarButton(button, animated: false)
}
@objc func doneTapped(_ sender: Any) {
done()
}
private func done() {
if let nav = navigationController as? SettingsNavigationViewController {
nav.notifyComplete()
}
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return AlertRow.allCases.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath) as! TextButtonTableViewCell
cell.textLabel?.text = String(describing: AlertRow(rawValue: indexPath.row)!)
cell.textLabel?.textAlignment = .center
cell.isEnabled = AlertRow(rawValue: indexPath.row)! == .retract && !cgmManager.hasRetractableAlert ? false : true
return cell
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = AlertRow(rawValue: indexPath.row)!
switch row {
case .retract:
cgmManager.retractCurrentAlert()
default:
cgmManager.issueAlert(identifier: row.identifier, trigger: row.trigger, delay: row.delayBeforeIssue, metadata: row.metadata)
}
tableView.deselectRow(at: indexPath, animated: true)
tableView.reloadRows(at: [IndexPath(row: AlertRow.retract.rawValue, section: indexPath.section)], with: .automatic)
}
}
| mit | 2c85fa1383b61f7a2c29d81c08db99cf | 34.113333 | 143 | 0.621416 | 5.15362 | false | false | false | false |
PureSwift/GATT | Sources/DarwinGATT/PeripheralContinuation.swift | 1 | 2565 | //
// PeripheralContinuation.wift
//
//
// Created by Alsey Coleman Miller on 20/12/21.
//
#if canImport(CoreBluetooth)
import Foundation
import Bluetooth
import GATT
#if DEBUG
internal struct PeripheralContinuation<T, E> where E: Error {
private let function: String
private let continuation: CheckedContinuation<T, E>
private let peripheral: DarwinCentral.Peripheral
fileprivate init(
continuation: UnsafeContinuation<T, E>,
function: String,
peripheral: DarwinCentral.Peripheral
) {
self.continuation = CheckedContinuation(continuation: continuation, function: function)
self.function = function
self.peripheral = peripheral
}
func resume(
returning value: T
) {
continuation.resume(returning: value)
}
func resume(
throwing error: E
) {
continuation.resume(throwing: error)
}
func resume(
with result: Result<T, E>
) {
continuation.resume(with: result)
}
}
extension PeripheralContinuation where T == Void {
func resume() {
self.resume(returning: ())
}
}
internal func withContinuation<T>(
for peripheral: DarwinCentral.Peripheral,
function: String = #function,
_ body: (PeripheralContinuation<T, Never>) -> Void
) async -> T {
return await withUnsafeContinuation {
body(PeripheralContinuation(continuation: $0, function: function, peripheral: peripheral))
}
}
internal func withThrowingContinuation<T>(
for peripheral: DarwinCentral.Peripheral,
function: String = #function,
_ body: (PeripheralContinuation<T, Swift.Error>) -> Void
) async throws -> T {
return try await withUnsafeThrowingContinuation {
body(PeripheralContinuation(continuation: $0, function: function, peripheral: peripheral))
}
}
#else
internal typealias PeripheralContinuation<T, E> = CheckedContinuation<T, E> where E: Error
@inline(__always)
internal func withContinuation<T>(
for peripheral: DarwinCentral.Peripheral,
function: String = #function,
_ body: (CheckedContinuation<T, Never>) -> Void
) async -> T {
return await withCheckedContinuation(function: function, body)
}
@inline(__always)
internal func withThrowingContinuation<T>(
for peripheral: DarwinCentral.Peripheral,
function: String = #function,
_ body: (CheckedContinuation<T, Swift.Error>) -> Void
) async throws -> T {
return try await withCheckedThrowingContinuation(function: function, body)
}
#endif
#endif
| mit | 84ccc769049f9631c5c125b2f614846b | 25.173469 | 98 | 0.681481 | 4.596774 | false | false | false | false |
buyiyang/iosstar | iOSStar/AppAPI/DealAPI/DealSocketAPI.swift | 3 | 3902 |
//
// DealSocketAPI.swift
// iOSStar
//
// Created by J-bb on 17/6/8.
// Copyright © 2017年 YunDian. All rights reserved.
//
import Foundation
class DealSocketAPI: BaseSocketAPI, DealAPI{
func allOrder(requestModel:DealRecordRequestModel,OPCode:SocketConst.OPCode,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .allOrder, model: requestModel)
startModelsRequest(packet, listName: "ordersList", modelClass: OrderListModel.self, complete: complete, error: error)
}
//发起委托
func buyOrSell(requestModel:BuyOrSellRequestModel, complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .buyOrSell, model: requestModel)
startModelRequest(packet, modelClass: EntrustSuccessModel.self, complete: complete, error: error)
}
//确认订单
func sureOrderRequest(requestModel:SureOrderRequestModel, complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .sureOrder, model: requestModel)
startModelRequest(packet, modelClass: SureOrderResultModel.self, complete: complete, error: error)
}
//取消订单
func cancelOrderRequest(requestModel:CancelOrderRequestModel, complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .cancelOrder, model: requestModel)
startResultIntRequest(packet, complete: complete, error: error)
}
//收到订单结果
func setReceiveOrderResult(complete:@escaping CompleteBlock) {
SocketRequestManage.shared.receiveOrderResult = { (response) in
let jsonResponse = response as! SocketJsonResponse
let model = jsonResponse.responseModel(OrderResultModel.self) as? OrderResultModel
if model != nil {
complete(model)
}
}
}
//收到匹配成功
func setReceiveMatching(complete:@escaping CompleteBlock) {
SocketRequestManage.shared.receiveMatching = { (response) in
let jsonResponse = response as! SocketJsonResponse
let model = jsonResponse.responseModel(ReceiveMacthingModel.self) as? ReceiveMacthingModel
if model != nil {
complete(model)
}
}
}
//验证交易密码
func checkPayPass( paypwd: String, complete: CompleteBlock?, error: ErrorBlock?){
let param: [String: Any] = [SocketConst.Key.id: StarUserModel.getCurrentUser()?.userinfo?.id ?? 0,
SocketConst.Key.paypwd :paypwd, SocketConst.Key.token :StarUserModel.getCurrentUser()?.token ?? ""]
let packet: SocketDataPacket = SocketDataPacket.init(opcode: .paypwd, dict: param as [String : AnyObject])
startRequest(packet, complete: complete, error: error)
}
//请求委托列表
func requestEntrustList(requestModel:DealRecordRequestModel,OPCode:SocketConst.OPCode,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode:OPCode, model: requestModel)
startModelsRequest(packet, listName: "positionsList", modelClass: EntrustListModel.self, complete: complete, error: error)
}
//订单列表
func requestOrderList(requestModel:OrderRecordRequestModel,OPCode:SocketConst.OPCode,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: OPCode, model: requestModel)
startModelsRequest(packet, listName: "ordersList", modelClass: OrderListModel.self, complete: complete, error: error)
}
func requestMiuCount(requestModel:MiuCountRequestModel, complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .miuCount, model: requestModel)
startModelRequest(packet, modelClass: MiuResponeModel.self, complete: complete, error: error)
}
}
| gpl-3.0 | eec15091cd169aad17574ef7228a5c3c | 45.573171 | 137 | 0.699398 | 4.508855 | false | false | false | false |
cruisediary/Diving | Diving/Scenes/UserList/UserListConfigurator.swift | 1 | 1574 | //
// UserListConfigurator.swift
// Diving
//
// Created by CruzDiary on 5/23/16.
// Copyright (c) 2016 DigitalNomad. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
// MARK: Connect View, Interactor, and Presenter
extension UserListViewController: UserListPresenterOutput {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
router.passDataToNextScene(segue)
}
}
extension UserListInteractor: UserListViewControllerOutput {
}
extension UserListPresenter: UserListInteractorOutput {
}
class UserListConfigurator {
// MARK: Object lifecycle
class var sharedInstance: UserListConfigurator {
struct Static {
static var instance: UserListConfigurator?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = UserListConfigurator()
}
return Static.instance!
}
// MARK: Configuration
func configure(viewController: UserListViewController) {
let router = UserListRouter()
router.viewController = viewController
let presenter = UserListPresenter()
presenter.output = viewController
let interactor = UserListInteractor()
interactor.output = presenter
viewController.output = interactor
viewController.router = router
}
}
| mit | 02a21d5ad6dfdff073a9ffff83ff934a | 25.677966 | 81 | 0.670267 | 5.229236 | false | true | false | false |
opudrovs/SampleTableViewJSON | SampleTableViewJSON/FeedViewController.swift | 1 | 8506 | //
// FeedViewController.swift
// SampleTableViewJSON
//
// Created by Olga Pudrovska on 3/28/15.
// Copyright (c) 2016 Olga Pudrovska. All rights reserved.
//
import UIKit
let ContentItemVCShowSegueIdentifier = "ShowContentItem"
class FeedViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {
static let tableViewRowHeight = CGFloat(120)
// MARK: - Outlets
@IBOutlet var activityIndicator: UIActivityIndicatorView?
@IBOutlet var tableView: UITableView?
// MARK: - Properties
var viewData: FeedViewData?
fileprivate var searchController: UISearchController!
// MARK: - Initializer
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Show that data is loading
self.activityIndicator?.startAnimating()
self.tableView?.isHidden = true
// Create navigation bar buttons
self.createNavBarItems()
// Create search controller
self.definesPresentationContext = true
self.searchController = self.createSearchController()
self.tableView?.tableHeaderView = self.searchController.searchBar
// Load data
self.loadData()
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let viewData = self.viewData else { return 0 }
return viewData.contentCount(for: self.contentMode())
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = self.tableView?.dequeueReusableCell(withIdentifier: FeedTableViewCellIdentifier, for:indexPath) as? FeedTableViewCell else { return UITableViewCell() }
guard let viewData = self.viewData, let contentItem = viewData.contentItem(for: indexPath, mode: self.contentMode()) else { return cell }
let cellViewData = FeedTableViewCellViewData(content: contentItem)
cell.viewData = cellViewData
cell.update(with: cellViewData)
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return FeedViewController.tableViewRowHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: ContentItemVCShowSegueIdentifier as String, sender: tableView)
tableView.deselectRow(at: indexPath, animated: false)
}
// MARK: - Event Handlers
func didPressSortOrder(_ sender: AnyObject) {
guard let viewData = self.viewData else { return }
viewData.updateSortOrder(sortOrder: (sender as? UISegmentedControl)?.selectedSegmentIndex == 0 ? .ascending : .descending)
self.sortTableView(sortType: viewData.sortType, sortOrder: viewData.sortOrder)
}
func didPressSortType(_ sender: AnyObject) {
guard let viewData = self.viewData else { return }
let alertController = UIAlertController(title: FeedLocalizationKey.sortContentBy.localizedString(), message: nil, preferredStyle: .actionSheet)
for action in self.sortActions(currentSortType: viewData.sortType) {
alertController.addAction(action)
}
self.present(alertController, animated: true, completion: nil)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == ContentItemVCShowSegueIdentifier {
guard let viewData = self.viewData, let vc = segue.destination as? ContentItemViewController, let indexPath = self.tableView?.indexPathForSelectedRow else { return }
guard let contentItem = viewData.contentItem(for: indexPath, mode: self.contentMode()) else { return }
let destinationViewData = ContentItemViewData(content: contentItem)
vc.viewData = destinationViewData
}
}
// MARK: - UISearchResultsUpdating
func updateSearchResults(for searchController: UISearchController) {
if let searchText = searchController.searchBar.text {
self.filterContent(for: searchText)
self.tableView?.reloadData()
}
}
// MARK: - Search
fileprivate func filterContent(for searchText: String) {
self.viewData?.filterContent(for: searchText)
}
// MARK: - Private
func update(with viewData: FeedViewData) {
// Set view title
self.title = self.viewData?.title ?? ""
}
fileprivate func loadData() {
self.viewData?.loadData {
DispatchQueue.main.async {
self.activityIndicator?.stopAnimating()
self.tableView?.isHidden = false
if let viewData = self.viewData {
self.sortTableView(sortType: viewData.sortType, sortOrder: viewData.sortOrder)
}
}
}
}
fileprivate func createNavBarItems() {
let items = [FeedLocalizationKey.sortOrderAscending.localizedString(), FeedLocalizationKey.sortOrderDescending.localizedString()]
// create segmented control
let segmentedControl = UISegmentedControl(items: items)
// do not sort initially
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(FeedViewController.didPressSortOrder(_:)), for: UIControlEvents.valueChanged)
// create items
// asc/desc
let directionItem: UIBarButtonItem = UIBarButtonItem(customView: segmentedControl)
// sort
let sortItem: UIBarButtonItem = UIBarButtonItem(title: FeedLocalizationKey.sort.localizedString(), style: UIBarButtonItemStyle.plain, target: self, action: #selector(FeedViewController.didPressSortType(_:)))
// add items to bar
self.navigationItem.setLeftBarButton(directionItem, animated: false)
self.navigationItem.setRightBarButton(sortItem, animated: false)
}
fileprivate func createSearchController() -> UISearchController {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
if #available(iOS 9.1, *) {
searchController.obscuresBackgroundDuringPresentation = false
} else {
searchController.dimsBackgroundDuringPresentation = false
}
searchController.searchBar.placeholder = FeedLocalizationKey.searchPlaceholder.localizedString()
searchController.searchBar.tintColor = UIColor.white
searchController.searchBar.barTintColor = UIColor(red: 127.0/255.0, green: 127.0/255.0, blue: 127.0/255.0, alpha: 1.0)
return searchController
}
fileprivate func sortActions(currentSortType: SortType) -> [UIAlertAction] {
let cancelAction = UIAlertAction(title: FeedLocalizationKey.sortCancelAction.localizedString(), style: .cancel, handler: nil)
let checkmarkString = " ✔︎"
let sortByTitleAction = UIAlertAction(title: "\(FeedLocalizationKey.sortTypeByTitle.localizedString())\(currentSortType == .title ? checkmarkString : "")", style: .default) { action in
if let viewData = self.viewData {
viewData.updateSortType(sortType: .title)
self.sortTableView(sortType: viewData.sortType, sortOrder: viewData.sortOrder)
}
}
let sortByDateAction = UIAlertAction(title: "\(FeedLocalizationKey.sortTypeByDatePublished.localizedString())\(currentSortType == .date ? checkmarkString : "")", style: .default) { action in
if let viewData = self.viewData {
viewData.updateSortType(sortType: .date)
self.sortTableView(sortType: viewData.sortType, sortOrder: viewData.sortOrder)
}
}
return [cancelAction, sortByTitleAction, sortByDateAction]
}
// Sorts content based on sort type and direction and reloads data
fileprivate func sortTableView(sortType: SortType, sortOrder: SortOrder) {
self.viewData?.sortContent(sortType: sortType, sortOrder: sortOrder)
self.tableView?.reloadData()
}
fileprivate func contentMode() -> ContentMode {
return self.searchController.isActive && self.searchController.searchBar.text != "" ? .filtered : .all
}
}
| gpl-3.0 | 99cfab48eab911a909c6d0d0e565cf95 | 37.125561 | 215 | 0.687956 | 5.270924 | false | false | false | false |
ChrisAU/PapyrusCore | PapyrusCore/Array+Solution.swift | 1 | 794 | //
// Array+Solution.swift
// PapyrusCore
//
// Created by Chris Nevin on 13/08/2016.
// Copyright © 2016 CJNevin. All rights reserved.
//
import Foundation
internal extension Array where Element: SolutionType {
func best(forDifficulty difficulty: Difficulty = .hard) -> Element? {
if isEmpty { return nil }
let sorted = self.sorted(by: { $0.score > $1.score })
let highestScore = sorted.first!
if difficulty == .hard || sorted.count == 1 {
return highestScore
}
let scaled = Double(highestScore.score) * difficulty.rawValue
func diff(solution: Element) -> Double {
return abs(scaled - Double(solution.score))
}
return sorted.min(by: { diff(solution: $0) < diff(solution: $1) })
}
}
| bsd-2-clause | 308a8213bc1a1c9f94e9cfd3d6d4587d | 30.72 | 74 | 0.615385 | 3.868293 | false | false | false | false |
johnboyer/Enroller | Enroller/AppDelegate.swift | 1 | 5152 | //
// AppDelegate.swift
// Enroller
//
//
/*
Created by John Boyer on 4/14/16.
Copyright © 2016 Rodax Software, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import CocoaLumberjack
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
/// Main window
var window: UIWindow?
/// School instance
var school: School?
/// Debug a student
private func debug(student: Student) {
print("Custom debugDescription:")
print(student.debugDescription);
print()
print("stdlib dump method:")
/// Dump the entire object to the output stream
dump(student)
print()
print("stdlib debugPrint method:")
debugPrint(student);
}
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
//Configure CocoaLumberjack
let logger = DDTTYLogger.sharedInstance()
logger.logFormatter = CustomDDLogFormatter()
DDLog.addLogger(logger) // TTY = Xcode console
DDLog.addLogger(DDASLLogger.sharedInstance()) // ASL = Apple System Logs
let fileLogger: DDFileLogger = DDFileLogger() // File Logger
fileLogger.rollingFrequency = 60*60*24 // 24 hours
fileLogger.logFileManager.maximumNumberOfLogFiles = 7
DDLog.addLogger(fileLogger)
//Set the default debug to off during profiling
// defaultDebugLevel = .Off
DDLogInfo("Logging framework initialized")
return true
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
DDLogInfo("App launched")
//1) Initialize School object
DDLogInfo("Instantiate the School object")
self.school = School()
//2 Enroll a student
// aStudent.firstName = "Alex"
// aStudent.lastName = "Brown"
// aStudent.email = "alex@example.com"
//
// let components = NSDateComponents()
// components.day = 4
// components.month = 4;
// components.year = 1998
//
// let calendar = NSCalendar.currentCalendar();
// aStudent.birthday = calendar.dateFromComponents(components)
let alex = Student(email: "alex@example.com",
firstName: "Alex",
lastName: "Brown",
birthday: "1998-04-04")
school!.enroll(alex)
//3) Withdraw a student
let email = "jennifer@example.com"
let jennifer = school!.findStudent(email)
if jennifer != nil {
school!.withdraw(jennifer!)
} else {
DDLogWarn("`\(email)` not found")
}
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:.
}
}
| apache-2.0 | 3f5aba283ad21df86939b487bf10499f | 36.59854 | 285 | 0.667637 | 5.130478 | false | false | false | false |
RobinFalko/Ubergang | Examples/TweenApp/TweenApp/TimelinesViewController.swift | 1 | 3589 | //
// ViewController.swift
// TweenApp
//
// Created by RF on 07/01/16.
// Copyright © 2016 Robin Falko. All rights reserved.
//
import UIKit
import Ubergang
class TimelinesViewController: ExampleViewController {
@IBOutlet weak var tweenStatusView0: TweenStatusView!
@IBOutlet weak var tweenStatusView1: TweenStatusView!
@IBOutlet weak var tweenStatusView2: TweenStatusView!
@IBOutlet weak var tweenStatusView3: TweenStatusView!
@IBOutlet var numberLabel: UILabel!
@IBOutlet var progressBar: CircularProgressBar!
override func setupTween() -> UTweenBase {
let timeline = UTimeline(id: "timeline")
.options(.repeat(9))
.repeatCycleChange { [unowned self] repeatCycle in
self.tweenStatusView2.repeatCount = repeatCycle
}
.update { [unowned self] progress in
self.tweenStatusView2.progress = Float(progress)
}
.updateTotal { [unowned self] progressTotal in
self.tweenStatusView2.progressTotal = Float(progressTotal)
self.tweenControls.progress(progressTotal)
}
//closing arc
let tween0 = NumericTween(id: "arcIncreaseTween")
.from(-360.0, to: -0.1)
.duration(5)
.ease(.cubic(.inOut))
.update { [unowned self] (value: CGFloat, progress: Double) in
self.tweenStatusView0.progress = Float(progress)
self.progressBar.endAngle = value
}
.updateTotal { [unowned self] progress in
self.tweenStatusView0.progressTotal = Float(progress)
}
timeline.append(tween0)
let tween1 = NumericTween(id: "arcDecreaseTween")
.from(-360, to: -0.1)
.duration(5)
.ease(.cubic(.inOut))
.update { [unowned self] (value: CGFloat, progress: Double) in
self.tweenStatusView1.progress = Float(progress)
self.progressBar.startAngle = value
}
.updateTotal { [unowned self] progress in
self.tweenStatusView1.progressTotal = Float(progress)
}
//opening arc
timeline.append(tween1)
let timelineContainer = UTimeline(id: "timelineContainer")
.reference(.weak)
.repeatCycleChange { [unowned self] repeatCycle in
self.tweenStatusView3.repeatCount = repeatCycle
}
.update { [unowned self] progress in
self.tweenStatusView3.progress = Float(progress)
}
.updateTotal { [unowned self] progressTotal in
self.tweenStatusView3.progressTotal = Float(progressTotal)
}
.complete { [unowned self] in
self.tweenControls.stop()
}
//timeline arcs
timelineContainer.insert(timeline, at: 0)
//countdown
timelineContainer.insert( 10.tween(to: 0)
.id("countTween")
.duration(10)
.ease(.linear)
.reference(.weak)
.update { [unowned self] (value: Int) in
self.numberLabel.text = String(value)
}, at: 0)
self.tweenStatusView0.title = "\(tween0.id)"
self.tweenStatusView1.title = "\(tween1.id)"
self.tweenStatusView2.title = "\(timeline.id)"
self.tweenStatusView3.title = "\(timelineContainer.id)"
return timelineContainer
}
}
| apache-2.0 | f5d1a1c53cfa5804c8a829760c44f0f2 | 35.242424 | 74 | 0.574972 | 4.6658 | false | false | false | false |
TouchInstinct/LeadKit | TIUIElements/Sources/Helpers/DefaultAnimators/TransitionAnimator.swift | 1 | 466 | import UIKit
final public class TransitionAnimator: CollapsibleViewsAnimator {
public var fractionComplete: CGFloat = 0 {
didSet {
navBar?.topItem?.titleView?.transition(to: fractionComplete)
}
}
public var currentContentOffset = CGPoint.zero
private weak var navBar: UINavigationBar?
public init(navBar: UINavigationBar? = nil) {
navBar?.topItem?.titleView?.alpha = 0
self.navBar = navBar
}
}
| apache-2.0 | d28167563c1042ead7fb9ecb4d350c51 | 24.888889 | 72 | 0.667382 | 4.957447 | false | false | false | false |
gyro-n/PaymentsIos | GyronPayments/Classes/Models/ResponseItems.swift | 1 | 665 | //
// ResponseItems.swift
// GyronPayments
//
// Created by Ye David on 11/2/16.
// Copyright © 2016 gyron. All rights reserved.
//
import Foundation
open class ResponseItems<T: BaseModel>: BaseModel {
public var items: [T]
public var hasMore: Bool
override open func mapFromObject(map: ResponseData) {
let itemList = map["items"] as? [ResponseData] ?? []
items = itemList.map({object in
return T(map: object)
})
// total = map["total"] as? Int ?? 0
hasMore = map["has_more"] as? Bool ?? false
}
override init() {
//
items = []
hasMore = false
}
}
| mit | 2e3bab1f69baaa0708daacb75dffc1a4 | 21.896552 | 60 | 0.563253 | 3.905882 | false | false | false | false |
GloomySunday049/TMCommon | TMCommon/TMCommonTests/FileManagerExtensions.swift | 1 | 1830 | //
// FileManagerExtensions.swift
// TMCommon
//
// Created by 孟钰丰 on 2016/10/19.
// Copyright © 2016年 Petsknow. All rights reserved.
//
import Foundation
extension FileManager {
static var temporaryDirectoryPath: String {
return NSTemporaryDirectory()
}
static var temporaryDirectoryURL: URL {
return URL(fileURLWithPath: temporaryDirectoryPath, isDirectory: true)
}
@discardableResult
static func createDirectory(atPath path: String) -> Bool {
do {
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
return true
} catch {
return false
}
}
@discardableResult
static func createDirectory(at url: URL) -> Bool {
return createDirectory(atPath: url.path)
}
@discardableResult
static func removeItem(atPath path: String) -> Bool {
do {
try FileManager.default.removeItem(atPath: path)
return true
} catch {
return false
}
}
@discardableResult
static func removeItem(at url: URL) -> Bool {
return removeItem(atPath: url.path)
}
@discardableResult
static func removeAllItemInsideDirectory(atPath path: String) -> Bool {
let enumerator = FileManager.default.enumerator(atPath: path)
var result = true
while let fileName = enumerator?.nextObject() as? String {
let success = removeItem(atPath: path + "/\(fileName)")
if !success { result = false }
}
return result
}
@discardableResult
static func removeAllItemInsideDirectory(at url: URL) -> Bool {
return removeAllItemInsideDirectory(atPath: url.path)
}
}
| mit | fae94d5e9ea40ff0fcd3494f405659c4 | 26.179104 | 117 | 0.618891 | 4.97541 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Banking | HatchReadyApp/apps/Hatch/iphone/native/Hatch/Controllers/Watson/WatsonImportanceViewController.swift | 1 | 2796 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
* This view controller is 2/5 of the Watson questionnaire, and asks the user which option is most important in an account.
*/
class WatsonImportanceViewController: UIViewController {
@IBOutlet var check1: UIImageView!
@IBOutlet var check2: UIImageView!
@IBOutlet var check3: UIImageView!
var watsonChoice : [Int] = [-1,-1,-1]
override func viewDidLoad() {
super.viewDidLoad()
Utils.setUpViewKern(self.view)
if (watsonChoice[1] == 0) {
self.check1.hidden = false
}
else if (watsonChoice[1] == 1) {
self.check2.hidden = false
}
else if (watsonChoice[1] == 2) {
self.check3.hidden = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
This method is called when any button/option is tapped on this view controller to push to the next view controller in the UIPageViewController. Buttons' tags have been set to determine which button has been pressed
- parameter sender:
*/
@IBAction func tappedOption(sender: AnyObject) {
var vc : WatsonViewController = self.parentViewController?.parentViewController as! WatsonViewController
vc.touchEnabled = true //tell WatsonViewController that swipe to touch is enabled
//transition to next view
var viewControllers : [UIViewController] = [vc.viewControllerAtIndex(self.view.tag+1)!]
vc.setOutletAttributes(self.view.tag+1)
vc.pageViewController.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
switch sender.tag {
case 0:
MQALogger.log("tapped item 0")
check1.hidden = false
check2.hidden = true
check3.hidden = true
vc.watsonChoice[1] = 0 //tell WatsonViewController which choice was picked
case 1:
MQALogger.log("tapped item 1")
check2.hidden = false
check1.hidden = true
check3.hidden = true
vc.watsonChoice[1] = 1 //tell WatsonViewController which choice was picked
case 2:
MQALogger.log("tapped item 2")
check3.hidden = false
check2.hidden = true
check1.hidden = true
vc.watsonChoice[1] = 2 //tell WatsonViewController which choice was picked
default:
MQALogger.log("tag not set!")
}
}
}
| epl-1.0 | 4fabdc94195ccdaa1c8a600b441cd985 | 31.882353 | 218 | 0.6161 | 4.894921 | false | false | false | false |
MadAppGang/SmartLog | iOS/Pods/CoreStore/Sources/CSObjectMonitor.swift | 2 | 5507 | //
// CSObjectMonitor.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - CSObjectMonitor
/**
The `CSObjectMonitor` serves as the Objective-C bridging type for `ObjectMonitor<T>`.
- SeeAlso: `ObjectMonitor`
*/
@available(OSX 10.12, *)
@objc
public final class CSObjectMonitor: NSObject {
/**
Returns the `NSManagedObject` instance being observed, or `nil` if the object was already deleted.
*/
public var object: Any? {
return self.bridgeToSwift.object
}
/**
Returns `YES` if the `NSManagedObject` instance being observed still exists, or `NO` if the object was already deleted.
*/
public var isObjectDeleted: Bool {
return self.bridgeToSwift.isObjectDeleted
}
/**
Registers a `CSObjectObserver` to be notified when changes to the receiver's `object` are made.
To prevent retain-cycles, `CSObjectMonitor` only keeps `weak` references to its observers.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
Calling `-addObjectObserver:` multiple times on the same observer is safe, as `CSObjectMonitor` unregisters previous notifications to the observer before re-registering them.
- parameter observer: an `CSObjectObserver` to send change notifications to
*/
public func addObjectObserver(_ observer: CSObjectObserver) {
let swift = self.bridgeToSwift
swift.unregisterObserver(observer)
swift.registerObserver(
observer,
willChangeObject: { (observer, monitor, object) in
observer.objectMonitor?(monitor.bridgeToObjectiveC, willUpdateObject: object)
},
didDeleteObject: { (observer, monitor, object) in
observer.objectMonitor?(monitor.bridgeToObjectiveC, didDeleteObject: object)
},
didUpdateObject: { (observer, monitor, object, changedPersistentKeys) in
observer.objectMonitor?(monitor.bridgeToObjectiveC, didUpdateObject: object, changedPersistentKeys: changedPersistentKeys)
}
)
}
/**
Unregisters an `CSObjectObserver` from receiving notifications for changes to the receiver's `object`.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
- parameter observer: an `CSObjectObserver` to unregister notifications to
*/
public func removeObjectObserver(_ observer: CSObjectObserver) {
self.bridgeToSwift.unregisterObserver(observer)
}
// MARK: NSObject
public override var hash: Int {
return self.bridgeToSwift.hashValue
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSObjectMonitor else {
return false
}
return self.bridgeToSwift == object.bridgeToSwift
}
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
}
// MARK: CoreStoreObjectiveCType
@nonobjc
public let bridgeToSwift: ObjectMonitor<NSManagedObject>
@nonobjc
public required init<T: NSManagedObject>(_ swiftValue: ObjectMonitor<T>) {
self.bridgeToSwift = swiftValue.downcast()
super.init()
}
}
// MARK: - ObjectMonitor
@available(OSX 10.12, *)
extension ObjectMonitor where ObjectMonitor.ObjectType: NSManagedObject {
// MARK: CoreStoreSwiftType
public var bridgeToObjectiveC: CSObjectMonitor {
return CSObjectMonitor(self)
}
// MARK: FilePrivate
fileprivate func downcast() -> ObjectMonitor<NSManagedObject> {
@inline(__always)
func noWarnUnsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
return unsafeBitCast(x, to: type)
}
return noWarnUnsafeBitCast(self, to: ObjectMonitor<NSManagedObject>.self)
}
}
| mit | 43118ba8374d1d78e07758b868f584ea | 32.987654 | 185 | 0.664729 | 5.060662 | false | false | false | false |
jacobwhite/firefox-ios | Shared/Extensions/KeychainWrapperExtensions.swift | 22 | 2439 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCGLogger
import SwiftKeychainWrapper
private let log = Logger.keychainLogger
public extension KeychainWrapper {
static var sharedAppContainerKeychain: KeychainWrapper {
let baseBundleIdentifier = AppInfo.baseBundleIdentifier
let accessGroupPrefix = Bundle.main.object(forInfoDictionaryKey: "MozDevelopmentTeam") as! String
let accessGroupIdentifier = AppInfo.keychainAccessGroupWithPrefix(accessGroupPrefix)
return KeychainWrapper(serviceName: baseBundleIdentifier, accessGroup: accessGroupIdentifier)
}
}
public extension KeychainWrapper {
func ensureStringItemAccessibility(_ accessibility: SwiftKeychainWrapper.KeychainItemAccessibility, forKey key: String) {
if self.hasValue(forKey: key) {
if self.accessibilityOfKey(key) != .afterFirstUnlock {
log.debug("updating item \(key) with \(accessibility)")
guard let value = self.string(forKey: key) else {
log.error("failed to get item \(key)")
return
}
if !self.removeObject(forKey: key) {
log.warning("failed to remove item \(key)")
}
if !self.set(value, forKey: key, withAccessibility: accessibility) {
log.warning("failed to update item \(key)")
}
}
}
}
func ensureObjectItemAccessibility(_ accessibility: SwiftKeychainWrapper.KeychainItemAccessibility, forKey key: String) {
if self.hasValue(forKey: key) {
if self.accessibilityOfKey(key) != .afterFirstUnlock {
log.debug("updating item \(key) with \(accessibility)")
guard let value = self.object(forKey: key) else {
log.error("failed to get item \(key)")
return
}
if !self.removeObject(forKey: key) {
log.warning("failed to remove item \(key)")
}
if !self.set(value, forKey: key, withAccessibility: accessibility) {
log.warning("failed to update item \(key)")
}
}
}
}
}
| mpl-2.0 | 2edbf79ac47a7092e670bf7f9c4da16d | 38.33871 | 125 | 0.607626 | 5.167373 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Likes/LikesListController.swift | 2 | 14555 | import Foundation
import UIKit
import WordPressKit
/// Convenience class that manages the data and display logic for likes.
/// This is intended to be used as replacement for table view delegate and data source.
@objc protocol LikesListControllerDelegate: AnyObject {
/// Reports to the delegate that the header cell has been tapped.
@objc optional func didSelectHeader()
/// Reports to the delegate that the user cell has been tapped.
/// - Parameter user: A LikeUser instance representing the user at the selected row.
func didSelectUser(_ user: LikeUser, at indexPath: IndexPath)
/// Ask the delegate to show an error view when fetching fails or there is no connection.
func showErrorView(title: String, subtitle: String?)
/// Send likes count to delegate.
@objc optional func updatedTotalLikes(_ totalLikes: Int)
}
class LikesListController: NSObject {
private let formatter = FormattableContentFormatter()
private let content: ContentIdentifier
private let siteID: NSNumber
private var notification: Notification? = nil
private var readerPost: ReaderPost? = nil
private let tableView: UITableView
private var loadingIndicator = UIActivityIndicatorView()
private weak var delegate: LikesListControllerDelegate?
// Used to control pagination.
private var isFirstLoad = true
private var totalLikes = 0
private var totalLikesFetched = 0
private var lastFetchedDate: String?
private var excludeUserIDs: [NSNumber]?
private let errorTitle = NSLocalizedString("Error loading likes",
comment: "Text displayed when there is a failure loading notification likes.")
private var hasMoreLikes: Bool {
return totalLikesFetched < totalLikes
}
private var isLoadingContent = false {
didSet {
if isLoadingContent != oldValue {
isLoadingContent ? loadingIndicator.startAnimating() : loadingIndicator.stopAnimating()
// Refresh the footer view's frame
tableView.tableFooterView = loadingIndicator
}
}
}
private var likingUsers: [LikeUser] = [] {
didSet {
tableView.reloadData()
}
}
private lazy var postService: PostService = {
PostService(managedObjectContext: ContextManager.shared.mainContext)
}()
private lazy var commentService: CommentService = {
CommentService(managedObjectContext: ContextManager.shared.mainContext)
}()
// Notification Likes has a table header. Post Likes does not.
// Thus this is used to determine table layout depending on which is being shown.
private var showingNotificationLikes: Bool {
return notification != nil
}
private var usersSectionIndex: Int {
return showingNotificationLikes ? 1 : 0
}
private var numberOfSections: Int {
return showingNotificationLikes ? 2 : 1
}
// MARK: Init
/// Init with Notification
///
init?(tableView: UITableView, notification: Notification, delegate: LikesListControllerDelegate? = nil) {
guard let siteID = notification.metaSiteID else {
return nil
}
switch notification.kind {
case .like:
// post likes
guard let postID = notification.metaPostID else {
return nil
}
content = .post(id: postID)
case .commentLike:
// comment likes
guard let commentID = notification.metaCommentID else {
return nil
}
content = .comment(id: commentID)
default:
// other notification kinds are not supported
return nil
}
self.notification = notification
self.siteID = siteID
self.tableView = tableView
self.delegate = delegate
super.init()
configureLoadingIndicator()
}
/// Init with ReaderPost
///
init?(tableView: UITableView, post: ReaderPost, delegate: LikesListControllerDelegate? = nil) {
guard let postID = post.postID else {
return nil
}
content = .post(id: postID)
readerPost = post
siteID = post.siteID
self.tableView = tableView
self.delegate = delegate
super.init()
configureLoadingIndicator()
}
private func configureLoadingIndicator() {
loadingIndicator = UIActivityIndicatorView(style: .medium)
loadingIndicator.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 44)
}
// MARK: Methods
/// Load likes data from remote, and display it in the table view.
func refresh() {
guard !isLoadingContent else {
return
}
isLoadingContent = true
if isFirstLoad {
fetchStoredLikes()
}
guard ReachabilityUtils.isInternetReachable() else {
isLoadingContent = false
if likingUsers.isEmpty {
delegate?.showErrorView(title: errorTitle, subtitle: nil)
}
return
}
fetchLikes(success: { [weak self] users, totalLikes, likesPerPage in
guard let self = self else {
return
}
if self.isFirstLoad {
self.delegate?.updatedTotalLikes?(totalLikes)
}
self.likingUsers = users
self.totalLikes = totalLikes
self.totalLikesFetched = users.count
self.lastFetchedDate = users.last?.dateLikedString
if !self.isFirstLoad && !users.isEmpty {
self.trackFetched(likesPerPage: likesPerPage)
}
self.isFirstLoad = false
self.isLoadingContent = false
self.trackUsersToExclude()
}, failure: { [weak self] error in
guard let self = self else {
return
}
let errorMessage: String? = {
// Get error message from API response if provided.
if let error = error,
let message = (error as NSError).userInfo[WordPressComRestApi.ErrorKeyErrorMessage] as? String,
!message.isEmpty {
return message
}
return nil
}()
self.isLoadingContent = false
self.delegate?.showErrorView(title: self.errorTitle, subtitle: errorMessage)
})
}
private func trackFetched(likesPerPage: Int) {
var properties: [String: Any] = [:]
properties["source"] = showingNotificationLikes ? "notifications" : "reader"
properties["per_page"] = likesPerPage
if likesPerPage > 0 {
properties["page"] = Int(ceil(Double(likingUsers.count) / Double(likesPerPage)))
}
WPAnalytics.track(.likeListFetchedMore, properties: properties)
}
/// Fetch Likes from Core Data depending on the notification's content type.
private func fetchStoredLikes() {
switch content {
case .post(let postID):
likingUsers = postService.likeUsersFor(postID: postID, siteID: siteID)
case .comment(let commentID):
likingUsers = commentService.likeUsersFor(commentID: commentID, siteID: siteID)
}
}
/// Fetch Likes depending on the notification's content type.
/// - Parameters:
/// - success: Closure to be called when the fetch is successful.
/// - failure: Closure to be called when the fetch failed.
private func fetchLikes(success: @escaping ([LikeUser], Int, Int) -> Void, failure: @escaping (Error?) -> Void) {
var beforeStr = lastFetchedDate
if beforeStr != nil,
let modifiedDate = modifiedBeforeDate() {
// The endpoints expect a format like YYYY-MM-DD HH:MM:SS. It isn't expecting the T or Z, hence the replacingMatches calls.
beforeStr = ISO8601DateFormatter().string(from: modifiedDate).replacingMatches(of: "T", with: " ").replacingMatches(of: "Z", with: "")
}
switch content {
case .post(let postID):
postService.getLikesFor(postID: postID,
siteID: siteID,
before: beforeStr,
excludingIDs: excludeUserIDs,
purgeExisting: isFirstLoad,
success: success,
failure: failure)
case .comment(let commentID):
commentService.getLikesFor(commentID: commentID,
siteID: siteID,
before: beforeStr,
excludingIDs: excludeUserIDs,
purgeExisting: isFirstLoad,
success: success,
failure: failure)
}
}
// There is a scenario where multiple users might like a post/comment at the same time,
// and then end up split between pages of results. So we'll track which users we've already
// fetched for the lastFetchedDate, and send those to the endpoints to filter out of the response
// so we don't get duplicates or gaps.
private func trackUsersToExclude() {
guard let modifiedDate = modifiedBeforeDate() else {
return
}
var fetchedUsers = [LikeUser]()
switch content {
case .post(let postID):
fetchedUsers = postService.likeUsersFor(postID: postID, siteID: siteID, after: modifiedDate)
case .comment(let commentID):
fetchedUsers = commentService.likeUsersFor(commentID: commentID, siteID: siteID, after: modifiedDate)
}
excludeUserIDs = fetchedUsers.map { NSNumber(value: $0.userID) }
}
private func modifiedBeforeDate() -> Date? {
guard let lastDate = likingUsers.last?.dateLiked else {
return nil
}
return Calendar.current.date(byAdding: .second, value: 1, to: lastDate)
}
}
// MARK: - Table View Related
extension LikesListController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return numberOfSections
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Header section
if showingNotificationLikes && section == Constants.headerSectionIndex {
return Constants.numberOfHeaderRows
}
// Users section
return likingUsers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if showingNotificationLikes && indexPath.section == Constants.headerSectionIndex {
return headerCell()
}
return userCell(for: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let isUsersSection = indexPath.section == usersSectionIndex
let isLastRow = indexPath.row == totalLikesFetched - 1
guard !isLoadingContent && hasMoreLikes && isUsersSection && isLastRow else {
return
}
refresh()
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return LikeUserTableViewCell.estimatedRowHeight
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if showingNotificationLikes && indexPath.section == Constants.headerSectionIndex {
delegate?.didSelectHeader?()
return
}
guard !isLoadingContent,
let user = likingUsers[safe: indexPath.row] else {
return
}
delegate?.didSelectUser(user, at: indexPath)
}
}
// MARK: - Notification Cell Handling
private extension LikesListController {
func headerCell() -> NoteBlockHeaderTableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: NoteBlockHeaderTableViewCell.reuseIdentifier()) as? NoteBlockHeaderTableViewCell,
let group = notification?.headerAndBodyContentGroups[Constants.headerRowIndex] else {
DDLogError("Error: couldn't get a header cell or FormattableContentGroup.")
return NoteBlockHeaderTableViewCell()
}
setupHeaderCell(cell: cell, group: group)
return cell
}
func setupHeaderCell(cell: NoteBlockHeaderTableViewCell, group: FormattableContentGroup) {
cell.attributedHeaderTitle = nil
cell.attributedHeaderDetails = nil
guard let gravatarBlock: NotificationTextContent = group.blockOfKind(.image),
let snippetBlock: NotificationTextContent = group.blockOfKind(.text) else {
return
}
cell.attributedHeaderTitle = formatter.render(content: gravatarBlock, with: HeaderContentStyles())
cell.attributedHeaderDetails = formatter.render(content: snippetBlock, with: HeaderDetailsContentStyles())
// Download the Gravatar
let mediaURL = gravatarBlock.media.first?.mediaURL
cell.downloadAuthorAvatar(with: mediaURL)
}
func userCell(for indexPath: IndexPath) -> UITableViewCell {
guard let user = likingUsers[safe: indexPath.row],
let cell = tableView.dequeueReusableCell(withIdentifier: LikeUserTableViewCell.defaultReuseID) as? LikeUserTableViewCell else {
DDLogError("Failed dequeueing LikeUserTableViewCell")
return UITableViewCell()
}
cell.configure(withUser: user, isLastRow: (indexPath.row == likingUsers.endIndex - 1))
return cell
}
}
// MARK: - Private Definitions
private extension LikesListController {
/// Convenient type that categorizes notification content and its ID.
enum ContentIdentifier {
case post(id: NSNumber)
case comment(id: NSNumber)
}
struct Constants {
static let headerSectionIndex = 0
static let headerRowIndex = 0
static let numberOfHeaderRows = 1
}
}
| gpl-2.0 | c40e21d956fbee8f2add5661e7a8bfb9 | 33.166667 | 152 | 0.62494 | 5.410781 | false | false | false | false |
pabloroca/PR2StudioSwift | Source/PR2Dates.swift | 1 | 4053 | //
// PR2Dates.swift
// FashionBrowserPablo
//
// Created by Pablo Roca Rozas on 27/1/16.
// Copyright © 2016 PR2Studio. All rights reserved.
//
import Foundation
extension String {
public func PR2DateFormatterFromWeb() -> Date {
return DateFormatter.PR2DateFormatterFromWeb.date(from: self)!
}
public func PR2DateFormatterFromAPI() -> Date {
return DateFormatter.PR2DateFormatterFromAPI.date(from: self)!
}
public func PR2DateFormatterFromAPIT() -> Date {
return DateFormatter.PR2DateFormatterFromAPIT.date(from: self)!
}
public func PR2DateFormatterYYYYMMDD() -> Date {
return DateFormatter.PR2DateFormatterYYYYMMDD.date(from: self)!
}
public func PR2DateFormatterForHeader() -> Date {
return DateFormatter.PR2DateFormatterForHeader.date(from: self)!
}
}
extension Date {
// Date format for API
public func PR2DateFormatterFromAPI() -> String {
return DateFormatter.PR2DateFormatterFromAPI.string(from: self)
}
// Date format for APIT
public func PR2DateFormatterFromAPIT() -> String {
return DateFormatter.PR2DateFormatterFromAPIT.string(from: self)
}
// Date format for Logs
public func PR2DateFormatterForLog() -> String {
return DateFormatter.PR2DateFormatterForLog.string(from: self)
}
// Date in UTC
public func PR2DateFormatterUTC() -> String {
return DateFormatter.PR2DateFormatterUTC.string(from: self)
}
// Date in HHMMh
public func PR2DateFormatterHHMM() -> String {
return DateFormatter.PR2DateFormatterHHMM.string(from: self)
}
// Date in YYYY-MM-DD
public func PR2DateFormatterYYYYMMDD() -> String {
return DateFormatter.PR2DateFormatterYYYYMMDD.string(from: self)
}
// Date in MMM dd., EEE
public func PR2DateFormatterForHeader() -> String {
return DateFormatter.PR2DateFormatterForHeader.string(from: self)
}
// Date in EEEE, d MMM
public func PR2DateFormatterDayWeek() -> String {
return DateFormatter.PR2DateFormatterDayWeek.string(from: self)
}
}
extension DateFormatter {
fileprivate static let PR2DateFormatterFromWeb: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
return formatter
}()
fileprivate static let PR2DateFormatterFromAPI: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
fileprivate static let PR2DateFormatterFromAPIT: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.timeZone = TimeZone(identifier: "UTC")
return formatter
}()
fileprivate static let PR2DateFormatterForLog: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
}()
fileprivate static let PR2DateFormatterUTC: DateFormatter = {
let formatter = DateFormatter()
let timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = timeZone
return formatter
}()
fileprivate static let PR2DateFormatterHHMM: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
return formatter
}()
fileprivate static let PR2DateFormatterYYYYMMDD: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
fileprivate static let PR2DateFormatterForHeader: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd., EEE"
return formatter
}()
fileprivate static let PR2DateFormatterDayWeek: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, d MMM"
return formatter
}()
}
| mit | d74f9035e00eee1a208a06c67f54c658 | 28.576642 | 73 | 0.673495 | 4.467475 | false | false | false | false |
SwiftTools/Switt | Switt/Source/Converting/Swift/Module/File/Support/FunctionSignatureFromContextConverter.swift | 1 | 999 | import SwiftGrammar
protocol FunctionSignatureFromContextConverter {
func convert(context: SwiftParser.Function_signatureContext?) -> FunctionSignature?
}
class FunctionSignatureFromContextConverterImpl: FunctionSignatureFromContextConverter {
private let assembly: ConvertingAssembly
init(assembly: ConvertingAssembly) {
self.assembly = assembly
}
func convert(context: SwiftParser.Function_signatureContext?) -> FunctionSignature? {
guard let context = context else { return nil }
let result = assembly.converter().convert(context.function_result())
let throwing = ThrowingFromTerminalsConverter.convert(context)
let parameters = assembly.converter().convert(context.parameter_clauses()) ?? []
return FunctionSignature(
curry: NonemptyArray(array: parameters) ?? NonemptyArray(first: []),
throwing: throwing,
result: result
)
}
} | mit | e3ffa5327b41733b49ec1f8787fd0e4f | 33.482759 | 89 | 0.678679 | 5.61236 | false | false | false | false |
tullie/CareerCupAPI | CCAnswersSearch.swift | 1 | 2385 | //
// CCAnswersSearch.swift
// AlgorithmMatch
//
// Created by Tullie on 24/03/2015.
// Copyright (c) 2015 Tullie. All rights reserved.
//
import UIKit
class CCAnswersSearch: NSObject {
// Retrive answers from question ID
func loadAnswersWithID(id: String) -> [CCAnswer] {
var answers: [CCAnswer] = []
let answersURLString = "\(CareerCup.DOMAIN)/question?id=\(id)"
let answersURL = NSURL(string: answersURLString)
// Ensure html data was found
if let answersPageHTMLData = NSData(contentsOfURL: answersURL!) {
let answersParser = TFHpple(HTMLData: answersPageHTMLData)
let answersQuery = "//div[@id='commentThread\(id)']//div[@class='comment']" // //div[@class='commentBody']"
let answerNodes = answersParser.searchWithXPathQuery(answersQuery)
for element in answerNodes as [TFHppleElement] {
let answerText = extractAnswerText(element)
let votes = extractUpVotes(element)
if answerText != nil && votes != nil {
var answer = CCAnswer(text: answerText!, upvotes: votes!)
answers += [answer]
}
}
} else {
println("Career Cup page data can not be retrived")
}
return answers;
}
// Extracts answer text from answer element
private func extractAnswerText(element: TFHppleElement) -> String? {
let answerMainElement = element.firstChildWithClassName("commentMain")
let answerBody = answerMainElement.firstChildWithClassName("commentBody")
let answerBodyChildren = answerBody.children as [TFHppleElement]
// Remove author tag element and concatenate text
let answerTextNodeArray = answerBodyChildren.filter({$0.attributes["class"] as String? != "author"})
let answerTextArray = answerTextNodeArray.map({$0.content}) as [String]
return join("", answerTextArray)
}
// Extracts upvotes from answer element
private func extractUpVotes(element: TFHppleElement) -> String? {
let votesWrapperElement = element.firstChildWithClassName("votesWrapper")
let votesNet = votesWrapperElement.firstChildWithClassName("votesNet")
return votesNet.content
}
}
| mit | 76e1b736f9e036667e15acfbb673ee99 | 38.098361 | 119 | 0.626834 | 4.713439 | false | false | false | false |
duycao2506/SASCoffeeIOS | SAS Coffee/View/KasperButton.swift | 1 | 1905 | //
// KasperButton.swift
// SAS Coffee
//
// Created by Duy Cao on 9/3/17.
// Copyright © 2017 Duy Cao. All rights reserved.
//
import UIKit
@IBDesignable
class KasperButton: UIButton {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
@IBInspectable var normalBackground: UIColor = UIColor.white {
didSet {
self.layer.backgroundColor = normalBackground.cgColor
}
}
@IBInspectable var pressedBackground: UIColor = UIColor.white
@IBInspectable var cornerRadiusLevel : CGFloat = 0 {
didSet{
if self.cornerRadiusLevel > 50 {
self.cornerRadiusLevel = 50
}
self.layer.cornerRadius = (self.cornerRadiusLevel * 0.01) * self.layer.frame.width
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
UIView.animate(withDuration: 0.4, animations: {
self.layer.backgroundColor = self.pressedBackground.cgColor
})
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
UIView.animate(withDuration: 0.4, animations: {
self.layer.backgroundColor = self.normalBackground.cgColor
})
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
UIView.animate(withDuration: 0.4, animations: {
self.layer.backgroundColor = self.normalBackground.cgColor
})
}
}
| gpl-3.0 | 99ca0416974f0391650aabbfd8172c7d | 26.594203 | 94 | 0.615021 | 4.736318 | false | false | false | false |
24/ios-o2o-c | gxc/Common/GXMap.swift | 1 | 6364 | //
// GXMap.swift
// gxc
//
// Created by gx on 14/12/3.
// Copyright (c) 2014年 zheng. All rights reserved.
//
import Foundation
import CoreLocation
class GXMap {
//转换过后,算经纬度
func distanceBetweenOrderBy(lat1:Double,lat2:Double,lng1:Double,lng2:Double) ->Double
{
var curLocation: CLLocation = CLLocation(latitude: lat1, longitude: lng1)
var otherLocation: CLLocation = CLLocation(latitude: lat2, longitude: lng2)
let distance = curLocation.distanceFromLocation(otherLocation)
return distance
}
// // 百度坐标转谷歌坐标
let x_pi :Double = (3.14159265358979324 * 3000.0) / 180.0
// + (void)transformatBDLat:(double)fBDLat BDLng:(double)fBDLng toGoogleLat:(double *)pfGoogleLat googleLng:(double *)pfGoogleLng
// {
// Double x = fBDLng - 0.0065f, y = fBDLat - 0.006f;
// Double z = sqrt(x * x + y * y) - 0.00002f * sin(y * x_pi);
// Double theta = atan2(y, x) - 0.000003f * cos(x * x_pi);
// *pfGoogleLng = z * cos(theta);
// *pfGoogleLat = z * sin(theta);
// }
//
// + (CLLocationCoordinate2D)getGoogleLocFromBaiduLocLat:(double)fBaiduLat lng:(double)fBaiduLng
// {
// Double fLat;
// Double fLng;
//
// [[self class] transformatBDLat:fBaiduLat BDLng:fBaiduLng toGoogleLat:&fLat googleLng:&fLng];
//
// CLLocationCoordinate2D objLoc;
// objLoc.latitude = fLat;
// objLoc.longitude = fLng;
// return objLoc;
// }
func transformatBDLat(fBDLat:Double ,fBDLng:Double , pfGoogleLat:Double, pfGoogleLng:Double)
{
var x = fBDLng - 0.0065
var y = fBDLat - 0.006
var z = sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi);
var theta = atan2(y, x) - 0.000003 * cos(x * x_pi);
var pfGoogleLng1 = Double(z * cos(theta))
var pfGoogleLat1 = Double(z * sin(theta))
}
func getGoogleLocFromBaiduLocLat(fBaiduLat:Double ,fBaiduLng:Double) -> CLLocationCoordinate2D
{
var fLat:Double!
var fLng:Double!
self.transformatBDLat(fBaiduLat, fBDLng: fBaiduLng, pfGoogleLat: fLat, pfGoogleLng: fLng)
var objLoc:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude:fLat, longitude: fLng)
return objLoc;
}
// 谷歌坐标转百度坐标
func getBaiduLocFromGoogleLocLat(fGoogleLat:Double , fGoogleLng:Double) -> CLLocationCoordinate2D
{
var x = fGoogleLng
var y = fGoogleLat
var z = sqrt(x * x + y * y) + Double(0.00002 * Double(sin(y * x_pi)))
var theta = atan2(y, x) + Double(0.000003 * cos(x * x_pi))
var objLoc:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude:(z * sin(theta)) + 0.006, longitude: (z * cos(theta)) + 0.0065)
return objLoc;
}
/******************* === GPS-Google END === *******************/
// GPS坐标转谷歌坐标
func GPSLocToGoogleLoc(objGPSLoc :CLLocationCoordinate2D) -> CLLocationCoordinate2D
{
return self.transformFromWGSCoord2MarsCoord(objGPSLoc)
}
/******************* === GPS-Google BEGIN === *******************/
/* 在网上看到的根据这个 c# 代码改的 GPS坐标转火星坐标 */
/* https://on4wp7.codeplex.com/SourceControl/changeset/view/21483#353936 */
/***************************************************************************/
let pi:Double = 3.14159265358979324
//
// Krasovsky 1940
//
// a = 6378245.0, 1/f = 298.3
// b = a * (1 - f)
// ee = (a^2 - b^2) / a^2;
let a:Double = 6378245.0
let ee:Double = 0.00669342162296594323
// World Geodetic System ==> Mars Geodetic System
func transformFromWGSCoord2MarsCoord(wgsCoordinate:CLLocationCoordinate2D) -> CLLocationCoordinate2D
{
var wgLat:Double = wgsCoordinate.latitude
var wgLon:Double = wgsCoordinate.longitude
if (self.outOfChina(wgLat, lon: wgLon))
{
return wgsCoordinate
}
var dLat: Double = self.transformLat(wgLon - 105.0, y: wgLat - 35.0)
var dLon: Double = self.transformLon(wgLon - 105.0, y: wgLat - 35.0)
var radLat :Double = wgLat / 180.0 * pi
var magic :Double = sin(radLat)
magic = 1 - ee * magic * magic
var sqrtMagic:Double = sqrt(magic)
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi)
dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * pi)
var marsCoordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: wgLat + dLat, longitude: wgLon + dLon)
return marsCoordinate
}
func outOfChina(lat :Double,lon:Double) -> Bool
{
if (lon < 72.004 || lon > 137.8347)
{
return true
}
if (lat < 0.8293 || lat > 55.8271)
{
return true
}
return false
}
func transformLat(x:Double,y:Double) ->Double
{
var temp1 :Double = 0.2 * sqrt(abs(x))
var temp2 :Double = 0.1 * x * y
var temp3 :Double = 0.2 * y * y
var temp4 :Double = 3.0 * y
var temp5 :Double = 2.0 * x
var ret :Double = -100.0 + temp1 + temp2 + temp3 + temp4 + temp5
ret += ((20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 ) / 3.0
ret += (20.0 * sin(y * pi) + 40.0 * sin(y / 3.0 * pi)) * 2.0 / 3.0
ret += (160.0 * sin(y / 12.0 * pi) + 320 * sin(y * pi / 30.0)) * 2.0 / 3.0
return ret
}
func transformLon(x:Double,y:Double) ->Double
{
var ret:Double = 300.0 + x + (2.0 * y) + (0.1 * x * x) + ( 0.1 * x * y ) + Double(0.1 * sqrt(abs(x)))
ret += ((20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0) / 3.0
ret += (20.0 * sin(x * pi) + 40.0 * sin(x / 3.0 * pi)) * 2.0 / 3.0
ret += (150.0 * sin(x / 12.0 * pi) + 300.0 * sin(x / 30.0 * pi)) * 2.0 / 3.0
return ret
}
}
| mit | b00dae175decafce14512ae5396faecf | 27.547945 | 139 | 0.519674 | 3.299208 | false | false | false | false |
Charlisim/Palette-iOS | Palette/UIView+ColorAtPoint.swift | 1 | 2003 | //The MIT License (MIT)
//
//Copyright (c) 2015 Carlos Simón
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
import UIKit
public extension UIView{
//returns the color data of the pixel at the currently selected point
func getPixelColorAtPoint(point:CGPoint)->UIColor
{
let pixel = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
var colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
context!.translateBy(x: -point.x, y: -point.y)
layer.render(in: context!)
var color:UIColor = UIColor(red: CGFloat(pixel[0])/255.0, green: CGFloat(pixel[1])/255.0, blue: CGFloat(pixel[2])/255.0, alpha: CGFloat(pixel[3])/255.0)
pixel.deallocate()
return color
}
}
| mit | ccab14614e3f5e5db877baa1519bcdf1 | 46.666667 | 160 | 0.733267 | 4.429204 | false | false | false | false |
xedin/swift | stdlib/public/Darwin/Accelerate/vDSP_Geometry.swift | 2 | 17903 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension vDSP {
// MARK Dot product
/// Returns the dot or scalar product of vectors A and B; single-precision.
///
/// - Parameter vectorA: Single-precision real input vector A.
/// - Parameter vectorB: Single-precision real input vector B.
/// - Returns: The dot product of vectors A and B.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func dot<U>(_ vectorA: U,
_ vectorB: U) -> Float
where
U: AccelerateBuffer,
U.Element == Float {
precondition(vectorA.count == vectorB.count)
let n = vDSP_Length(vectorA.count)
var result = Float.nan
vectorA.withUnsafeBufferPointer { a in
vectorB.withUnsafeBufferPointer { b in
vDSP_dotpr(a.baseAddress!, 1,
b.baseAddress!, 1,
&result, n)
}
}
return result
}
/// Returns the dot or scalar product of vectors A and B; double-precision.
///
/// - Parameter vectorA: Double-precision real input vector A.
/// - Parameter vectorB: Double-precision real input vector B.
/// - Returns: The dot product of vectors A and B.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func dot<U>(_ vectorA: U,
_ vectorB: U) -> Double
where
U: AccelerateBuffer,
U.Element == Double {
precondition(vectorA.count == vectorB.count)
let n = vDSP_Length(vectorA.count)
var result = Double.nan
vectorA.withUnsafeBufferPointer { a in
vectorB.withUnsafeBufferPointer { b in
vDSP_dotprD(a.baseAddress!, 1,
b.baseAddress!, 1,
&result, n)
}
}
return result
}
// MARK: Distance
/// Returns the hypotenuse of right-angled triangles with sides that are the lengths of
/// corresponding elements in vectors `x` and `y`; single-precision.
///
/// - Parameter x: The `x` in `z[i] = sqrt(x[i]² + y[i]²)`.
/// - Parameter y: The `y` in `z[i] = sqrt(x[i]² + y[i]²)`.
/// - Parameter result: The `z` in `z[i] = sqrt(x[i]² + y[i]²)`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func hypot<U, V>(_ x: U,
_ y: V) -> [Float]
where
U: AccelerateBuffer,
V: AccelerateBuffer,
U.Element == Float, V.Element == Float {
precondition(x.count == y.count)
let result = Array<Float>(unsafeUninitializedCapacity: x.count) {
buffer, initializedCount in
hypot(x, y,
result: &buffer)
initializedCount = x.count
}
return result
}
/// Calculates the hypotenuse of right-angled triangles with sides that are the lengths of
/// corresponding elements in vectors `x` and `y`; single-precision.
///
/// - Parameter x: The `x` in `z[i] = sqrt(x[i]² + y[i]²)`.
/// - Parameter y: The `y` in `z[i] = sqrt(x[i]² + y[i]²)`.
/// - Parameter result: The `z` in `z[i] = sqrt(x[i]² + y[i]²)`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func hypot<T, U, V>(_ x: T,
_ y: U,
result: inout V)
where
T: AccelerateBuffer,
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
T.Element == Float, U.Element == Float, V.Element == Float {
precondition(x.count == y.count && y.count == result.count)
let n = vDSP_Length(result.count)
x.withUnsafeBufferPointer { a in
y.withUnsafeBufferPointer { b in
result.withUnsafeMutableBufferPointer { dest in
vDSP_vdist(a.baseAddress!, 1,
b.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
}
/// Returns the hypotenuse of right-angled triangles with sides that are the lengths of
/// corresponding elements in vectors `x` and `y`; double-precision.
///
/// - Parameter x: The `x` in `z[i] = sqrt(x[i]² + y[i]²)`.
/// - Parameter y: The `y` in `z[i] = sqrt(x[i]² + y[i]²)`.
/// - Parameter result: The `z` in `z[i] = sqrt(x[i]² + y[i]²)`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func hypot<U, V>(_ x: U,
_ y: V) -> [Double]
where
U: AccelerateBuffer,
V: AccelerateBuffer,
U.Element == Double, V.Element == Double {
precondition(x.count == y.count)
let result = Array<Double>(unsafeUninitializedCapacity: x.count) {
buffer, initializedCount in
hypot(x, y,
result: &buffer)
initializedCount = x.count
}
return result
}
/// Calculates the hypotenuse of right-angled triangles with sides that are the lengths of
/// corresponding elements in vectors `x` and `y`; double-precision.
///
/// - Parameter x: The `x` in `z[i] = sqrt(x[i]² + y[i]²)`.
/// - Parameter y: The `y` in `z[i] = sqrt(x[i]² + y[i]²)`.
/// - Parameter result: The `z` in `z[i] = sqrt(x[i]² + y[i]²)`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func hypot<T, U, V>(_ x: T,
_ y: U,
result: inout V)
where
T: AccelerateBuffer,
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
T.Element == Double, U.Element == Double, V.Element == Double {
precondition(x.count == y.count && y.count == result.count)
let n = vDSP_Length(result.count)
x.withUnsafeBufferPointer { a in
y.withUnsafeBufferPointer { b in
result.withUnsafeMutableBufferPointer { dest in
vDSP_vdistD(a.baseAddress!, 1,
b.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
}
// MARK: Pythagoras
/// Returns the hypotenuse of right-angled triangles with sides that are the differences of
/// corresponding values in x0 and x1, and y0 and y1. Single-precision.
///
/// - Parameter x0: The `x0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter x1: The `x1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter y0: The `y0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter y1: The `y1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter result: The `z` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func hypot<R, S, T, U>(x0: R, x1: S,
y0: T, y1: U) -> [Float]
where
R: AccelerateBuffer,
S: AccelerateBuffer,
T: AccelerateBuffer,
U: AccelerateBuffer,
R.Element == Float, S.Element == Float,
T.Element == Float, U.Element == Float {
precondition(x0.count == x1.count)
precondition(y0.count == y1.count)
precondition(x0.count == y0.count)
let result = Array<Float>(unsafeUninitializedCapacity: x0.count) {
buffer, initializedCount in
hypot(x0: x0, x1: x1,
y0: y0, y1: y1,
result: &buffer)
initializedCount = x0.count
}
return result
}
/// Calculates the hypotenuse of right-angled triangles with sides that are the differences of
/// corresponding values in x0 and x1, and y0 and y1. Single-precision.
///
/// - Parameter x0: The `x0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter x1: The `x1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter y0: The `y0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter y1: The `y1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter result: The `z` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func hypot<R, S, T, U, V>(x0: R, x1: S,
y0: T, y1: U,
result: inout V)
where
R: AccelerateBuffer,
S: AccelerateBuffer,
T: AccelerateBuffer,
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
R.Element == Float, S.Element == Float,
T.Element == Float, U.Element == Float,
V.Element == Float {
precondition(x0.count == x1.count && x0.count == result.count)
precondition(y0.count == y1.count && y0.count == result.count)
let n = vDSP_Length(result.count)
x0.withUnsafeBufferPointer { a in
x1.withUnsafeBufferPointer { c in
y0.withUnsafeBufferPointer { b in
y1.withUnsafeBufferPointer { d in
result.withUnsafeMutableBufferPointer { dest in
vDSP_vpythg(a.baseAddress!, 1,
b.baseAddress!, 1,
c.baseAddress!, 1,
d.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
}
}
}
/// Returns the hypotenuse of right-angled triangles with sides that are the differences of
/// corresponding values in x0 and x1, and y0 and y1. Double-precision.
///
/// - Parameter x0: The `x0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter x1: The `x1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter y0: The `y0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter y1: The `y1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter result: The `z` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func hypot<R, S, T, U>(x0: R, x1: S,
y0: T, y1: U) -> [Double]
where
R: AccelerateBuffer,
S: AccelerateBuffer,
T: AccelerateBuffer,
U: AccelerateBuffer,
R.Element == Double, S.Element == Double,
T.Element == Double, U.Element == Double {
precondition(x0.count == x1.count)
precondition(y0.count == y1.count)
precondition(x0.count == y0.count)
let result = Array<Double>(unsafeUninitializedCapacity: x0.count) {
buffer, initializedCount in
hypot(x0: x0, x1: x1,
y0: y0, y1: y1,
result: &buffer)
initializedCount = x0.count
}
return result
}
/// Calculates the hypotenuse of right-angled triangles with sides that are the differences of
/// corresponding values in x0 and x1, and y0 and y1. Double-precision.
///
/// - Parameter x0: The `x0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter x1: The `x1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter y0: The `y0` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter y1: The `y1` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
/// - Parameter result: The `z` in `z[i] = sqrt( (x0[i] - x1[i])² + (y0[i] - y1[i])² )`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func hypot<R, S, T, U, V>(x0: R, x1: S,
y0: T, y1: U,
result: inout V)
where
R: AccelerateBuffer,
S: AccelerateBuffer,
T: AccelerateBuffer,
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
R.Element == Double, S.Element == Double,
T.Element == Double, U.Element == Double,
V.Element == Double {
precondition(x0.count == x1.count && x0.count == result.count)
precondition(y0.count == y1.count && y0.count == result.count)
let n = vDSP_Length(result.count)
x0.withUnsafeBufferPointer { a in
x1.withUnsafeBufferPointer { c in
y0.withUnsafeBufferPointer { b in
y1.withUnsafeBufferPointer { d in
result.withUnsafeMutableBufferPointer { dest in
vDSP_vpythgD(a.baseAddress!, 1,
b.baseAddress!, 1,
c.baseAddress!, 1,
d.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
}
}
}
// MARK: Distance Squared
/// Returns the distance squared between two points in `n` dimensional space. Single-precision.
///
/// - Parameter pointA: First point in `n` dimensional space, where `n` is the collection count.
/// - Parameter pointB: Second point in `n` dimensional space, where `n` is the collection count.
/// - Returns: The distance squared between `pointA` and `pointB`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func distanceSquared<U, V>(_ pointA: U,
_ pointB: V) -> Float
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
precondition(pointA.count == pointB.count)
let n = vDSP_Length(pointA.count)
var result = Float.nan
pointA.withUnsafeBufferPointer { a in
pointB.withUnsafeBufferPointer { b in
vDSP_distancesq(a.baseAddress!, 1,
b.baseAddress!, 1,
&result,
n)
}
}
return result
}
/// Returns the distance squared between two points in `n` dimensional space. Double-precision.
///
/// - Parameter pointA: First point in `n` dimensional space, where `n` is the collection count.
/// - Parameter pointB: Second point in `n` dimensional space, where `n` is the collection count.
/// - Returns: The distance squared between `pointA` and `pointB`.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func distanceSquared<U, V>(_ pointA: U,
_ pointB: V) -> Double
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
precondition(pointA.count == pointB.count)
let n = vDSP_Length(pointA.count)
var result = Double.nan
pointA.withUnsafeBufferPointer { a in
pointB.withUnsafeBufferPointer { b in
vDSP_distancesqD(a.baseAddress!, 1,
b.baseAddress!, 1,
&result,
n)
}
}
return result
}
}
| apache-2.0 | bd22934947944b14974c05724afdd054 | 40.009195 | 101 | 0.46701 | 4.197412 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica API Client/Habitica API Client/Decoding-Extensions.swift | 1 | 3792 | //
// Decoding-Extensions.swift
// Habitica API Client
//
// Created by Phillip Thelen on 11.06.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
//https://stackoverflow.com/a/46049763
struct JSONCodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
self.init(stringValue: "\(intValue)")
self.intValue = intValue
}
}
extension KeyedDecodingContainer {
func decode(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any] {
let container = try nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key)
return try container.decode(type)
}
func decodeIfPresent(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any]? {
guard contains(key) else {
return nil
}
guard try decodeNil(forKey: key) == false else {
return nil
}
return try decode(type, forKey: key)
}
func decode(_ type: [Any].Type, forKey key: K) throws -> [Any] {
var container = try nestedUnkeyedContainer(forKey: key)
return try container.decode(type)
}
func decodeIfPresent(_ type: [Any].Type, forKey key: K) throws -> [Any]? {
guard contains(key) else {
return nil
}
guard try decodeNil(forKey: key) == false else {
return nil
}
return try decode(type, forKey: key)
}
func decode(_ type: [String: Any].Type) throws -> [String: Any] {
var dictionary = [String: Any]()
for key in allKeys {
if let boolValue = try? decode(Bool.self, forKey: key) {
dictionary[key.stringValue] = boolValue
} else if let stringValue = try? decode(String.self, forKey: key) {
dictionary[key.stringValue] = stringValue
} else if let intValue = try? decode(Int.self, forKey: key) {
dictionary[key.stringValue] = intValue
} else if let doubleValue = try? decode(Double.self, forKey: key) {
dictionary[key.stringValue] = doubleValue
} else if let nestedDictionary = try? decode(Dictionary<String, Any>.self, forKey: key) {
dictionary[key.stringValue] = nestedDictionary
} else if let nestedArray = try? decode(Array<Any>.self, forKey: key) {
dictionary[key.stringValue] = nestedArray
}
}
return dictionary
}
}
extension UnkeyedDecodingContainer {
mutating func decode(_ type: [Any].Type) throws -> Array<Any> {
var array: [Any] = []
while isAtEnd == false {
// See if the current value in the JSON array is `null` first and prevent infite recursion with nested arrays.
if try decodeNil() {
continue
} else if let value = try? decode(Bool.self) {
array.append(value)
} else if let value = try? decode(Double.self) {
array.append(value)
} else if let value = try? decode(String.self) {
array.append(value)
} else if let nestedDictionary = try? decode(Dictionary<String, Any>.self) {
array.append(nestedDictionary)
} else if let nestedArray = try? decode(Array<Any>.self) {
array.append(nestedArray)
}
}
return array
}
mutating func decode(_ type: [String: Any].Type) throws -> Dictionary<String, Any> {
let nestedContainer = try self.nestedContainer(keyedBy: JSONCodingKeys.self)
return try nestedContainer.decode(type)
}
}
| gpl-3.0 | b33d63b1224564c02ca06fffbaee5346 | 34.101852 | 122 | 0.581113 | 4.43911 | false | false | false | false |
VolodymyrShlikhta/InstaClone | InstaClone/User.swift | 1 | 1405 | //
// User.swift
// InstaClone
//
// Created by Relorie on 6/19/17.
// Copyright © 2017 Relorie. All rights reserved.
//
import Foundation
import UIKit
class User {
var profilePictureURL: URL?
var profileName: String?
var posts = [Post]()
var postCount: Int? {
get {
return self.posts.count
} set { }
}
var followers = [String: Bool]()
var following = [String: Bool]()
var uid: String?
var followedByCurrentUser: Bool?
var followersCount: Int? {
get {
return self.followers.keys.count - 1
}
}
var followingCount: Int? {
get {
return self.following.keys.count - 1
}
}
var profileImage: UIImage?
init(uid: String?, profilePictureURL: URL?, profileName: String?, followers: [String: Bool]?, following: [String: Bool]?, postCount: Int?, isFollowingCurrentUser: Bool?) {
self.uid = uid
self.profilePictureURL = profilePictureURL
self.profileName = profileName
self.followers = followers ?? [:]
self.following = following ?? [:]
self.followedByCurrentUser = isFollowingCurrentUser
self.postCount = postCount
}
convenience init() {
self.init(uid: nil, profilePictureURL: nil, profileName: nil, followers: nil, following: nil, postCount: nil, isFollowingCurrentUser: nil)
}
}
| mit | 430fa08ebba38c30007ac1a6d709c24a | 27.08 | 175 | 0.611111 | 4.254545 | false | false | false | false |
LNTUORG/LntuOnline-iOS-Swift | eduadmin/SelfInfoTableViewController.swift | 1 | 3370 | //
// SelfInfoTableViewController.swift
// eduadmin
//
// Created by Li Jie on 3/7/16.
// Copyright © 2016 PUPBOSS. All rights reserved.
//
import UIKit
class SelfInfoTableViewController: UITableViewController {
let normalIdentifier = "InfoNormalCell"
let eduIdentifier = "InfoEduCell"
let familyIdentifier = "InfoFamilyCell"
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-2.0 | 80a3b2f767cd865d4559d5af810e1047 | 33.030303 | 157 | 0.688335 | 5.486971 | false | false | false | false |
szk-atmosphere/SAParallaxViewControllerSwift | SAParallaxViewControllerSwiftExample/Pods/SABlurImageView/SABlurImageView/SABlurImageView.swift | 1 | 5743 | //
// UIImageView+BlurEffect.swift
// SABlurImageView
//
// Created by 鈴木大貴 on 2015/03/27.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
import Foundation
import QuartzCore
open class SABlurImageView: UIImageView {
//MARK: - Static Properties
fileprivate struct Const {
static let fadeAnimationKey = "FadeAnimationKey"
static let maxImageCount: Int = 10
static let contentsAnimationKey = "contents"
}
//MARK: - Instance Properties
fileprivate var cgImages: [CGImage] = [CGImage]()
fileprivate var nextBlurLayer: CALayer?
fileprivate var previousImageIndex: Int = -1
fileprivate var previousPercentage: CGFloat = 0.0
open fileprivate(set) var isBlurAnimating: Bool = false
deinit {
clearMemory()
}
//MARK: - Life Cycle
open override func layoutSubviews() {
super.layoutSubviews()
nextBlurLayer?.frame = bounds
}
open func configrationForBlurAnimation(_ boxSize: CGFloat = 100) {
guard let image = image else { return }
let baseBoxSize = max(min(boxSize, 200), 0)
let baseNumber = sqrt(CGFloat(baseBoxSize)) / CGFloat(Const.maxImageCount)
let baseCGImages = [image].flatMap { $0.cgImage }
cgImages = bluredCGImages(baseCGImages, sourceImage: image, at: 0, to: Const.maxImageCount, baseNumber: baseNumber)
}
fileprivate func bluredCGImages(_ images: [CGImage], sourceImage: UIImage?, at index: Int, to limit: Int, baseNumber: CGFloat) -> [CGImage] {
guard index < limit else { return images }
let newImage = sourceImage?.blurEffect(pow(CGFloat(index) * baseNumber, 2))
let newImages = images + [newImage].flatMap { $0?.cgImage }
return bluredCGImages(newImages, sourceImage: newImage, at: index + 1, to: limit, baseNumber: baseNumber)
}
open func clearMemory() {
cgImages.removeAll(keepingCapacity: false)
nextBlurLayer?.removeFromSuperlayer()
nextBlurLayer = nil
previousImageIndex = -1
previousPercentage = 0.0
layer.removeAllAnimations()
}
//MARK: - Add single blur
open func addBlurEffect(_ boxSize: CGFloat, times: UInt = 1) {
guard let image = image else { return }
self.image = addBlurEffectTo(image, boxSize: boxSize, remainTimes: times)
}
fileprivate func addBlurEffectTo(_ image: UIImage, boxSize: CGFloat, remainTimes: UInt) -> UIImage {
return remainTimes > 0 ? addBlurEffectTo(image.blurEffect(boxSize), boxSize: boxSize, remainTimes: remainTimes - 1) : image
}
//MARK: - Percentage blur
open func blur(_ percentage: CGFloat) {
let percentage = min(max(percentage, 0.0), 0.99)
if previousPercentage - percentage > 0 {
let index = Int(floor(percentage * 10)) + 1
if index > 0 {
setLayers(index, percentage: percentage, currentIndex: index - 1, nextIndex: index)
}
} else {
let index = Int(floor(percentage * 10))
if index < cgImages.count - 1 {
setLayers(index, percentage: percentage, currentIndex: index, nextIndex: index + 1)
}
}
previousPercentage = percentage
}
fileprivate func setLayers(_ index: Int, percentage: CGFloat, currentIndex: Int, nextIndex: Int) {
if index != previousImageIndex {
CATransaction.animationWithDuration(0) { layer.contents = self.cgImages[currentIndex] }
if nextBlurLayer == nil {
let nextBlurLayer = CALayer()
nextBlurLayer.frame = bounds
layer.addSublayer(nextBlurLayer)
self.nextBlurLayer = nextBlurLayer
}
CATransaction.animationWithDuration(0) {
self.nextBlurLayer?.contents = self.cgImages[nextIndex]
self.nextBlurLayer?.opacity = 1.0
}
}
previousImageIndex = index
let minPercentage = percentage * 100.0
let alpha = min(max((minPercentage - CGFloat(Int(minPercentage / 10.0) * 10)) / 10.0, 0.0), 1.0)
CATransaction.animationWithDuration(0) { self.nextBlurLayer?.opacity = Float(alpha) }
}
//MARK: - Animation blur
open func startBlurAnimation(_ duration: TimeInterval) {
if isBlurAnimating { return }
isBlurAnimating = true
let count = cgImages.count
let group = CAAnimationGroup()
group.animations = cgImages.enumerated().flatMap {
guard $0.offset < count - 1 else { return nil }
let anim = CABasicAnimation(keyPath: Const.contentsAnimationKey)
anim.fromValue = $0.element
anim.toValue = cgImages[$0.offset + 1]
anim.fillMode = kCAFillModeForwards
anim.isRemovedOnCompletion = false
anim.duration = duration / TimeInterval(count)
anim.beginTime = anim.duration * TimeInterval($0.offset)
return anim
}
group.duration = duration
group.delegate = self
group.isRemovedOnCompletion = false
group.fillMode = kCAFillModeForwards
layer.add(group, forKey: Const.fadeAnimationKey)
cgImages = cgImages.reversed()
}
}
extension SABlurImageView: CAAnimationDelegate {
open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
guard let _ = anim as? CAAnimationGroup else { return }
layer.removeAnimation(forKey: Const.fadeAnimationKey)
isBlurAnimating = false
guard let cgImage = cgImages.first else { return }
image = UIImage(cgImage: cgImage)
}
}
| mit | 0bcb6d7e797ab4b58c6e06c208f8d88c | 38.212329 | 145 | 0.630742 | 4.576339 | false | false | false | false |
shopgun/shopgun-ios-sdk | Sources/TjekPublicationViewer/PagedPublication/PagedPublicationView+HotspotOverlayView.swift | 1 | 16047 | ///
/// Copyright (c) 2018 Tjek. All rights reserved.
///
import UIKit
protocol HotspotOverlayViewDelegate: AnyObject {
func didTapHotspot(overlay: PagedPublicationView.HotspotOverlayView, hotspots: [PagedPublicationView.HotspotModel], hotspotRects: [CGRect], locationInOverlay: CGPoint, pageIndex: Int, locationInPage: CGPoint)
func didLongPressHotspot(overlay: PagedPublicationView.HotspotOverlayView, hotspots: [PagedPublicationView.HotspotModel], hotspotRects: [CGRect], locationInOverlay: CGPoint, pageIndex: Int, locationInPage: CGPoint)
func didDoubleTapHotspot(overlay: PagedPublicationView.HotspotOverlayView, hotspots: [PagedPublicationView.HotspotModel], hotspotRects: [CGRect], locationInOverlay: CGPoint, pageIndex: Int, locationInPage: CGPoint)
}
// Make the delegate methods optional
extension HotspotOverlayViewDelegate {
func didTapHotspot(overlay: PagedPublicationView.HotspotOverlayView, hotspots: [PagedPublicationView.HotspotModel], hotspotRects: [CGRect], locationInOverlay: CGPoint, pageIndex: Int, locationInPage: CGPoint) {}
func didLongPressHotspot(overlay: PagedPublicationView.HotspotOverlayView, hotspots: [PagedPublicationView.HotspotModel], hotspotRects: [CGRect], locationInOverlay: CGPoint, pageIndex: Int, locationInPage: CGPoint) {}
func didDoubleTapHotspot(overlay: PagedPublicationView.HotspotOverlayView, hotspots: [PagedPublicationView.HotspotModel], hotspotRects: [CGRect], locationInOverlay: CGPoint, pageIndex: Int, locationInPage: CGPoint) {}
}
extension PagedPublicationView {
fileprivate class CutoutView: UIView {
var foregroundColor: UIColor = UIColor.black { didSet { setNeedsDisplay() } }
var maskLayer: CALayer? { didSet { setNeedsDisplay() } }
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
ctx.addRect(rect)
ctx.setFillColor(foregroundColor.cgColor)
ctx.fillPath()
if let maskLayer = self.maskLayer {
ctx.saveGState()
ctx.setBlendMode(.clear)
maskLayer.render(in: ctx)
ctx.restoreGState()
}
}
}
class HotspotOverlayView: UIView, UIGestureRecognizerDelegate {
fileprivate let dimmedOverlay: CutoutView
fileprivate var hotspotViews: [UIView] = []
public var isZooming: Bool = false {
didSet {
if isZooming {
self.perform(#selector(fadeOutOverlay), with: nil, afterDelay: 0, inModes: [RunLoop.Mode.common])
}
}
}
override init(frame: CGRect) {
dimmedOverlay = CutoutView(frame: frame)
dimmedOverlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
dimmedOverlay.backgroundColor = UIColor.clear
dimmedOverlay.foregroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
dimmedOverlay.alpha = 0.0
dimmedOverlay.isHidden = true
super.init(frame: frame)
_initializeGestureRecognizers()
addSubview(dimmedOverlay)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
weak var delegate: HotspotOverlayViewDelegate?
fileprivate func _getTargetPage(forGesture gesture: UIGestureRecognizer) -> (index: Int, location: CGPoint)? {
// find the page that the gesture occurred in
var possibleTargetPage:(index: Int, location: CGPoint)?
for (pageIndex, pageView) in pageViews {
let pageLocation = gesture.location(in: pageView)
if pageView.bounds.isEmpty == false && pageView.bounds.contains(pageLocation) {
possibleTargetPage = (index:pageIndex, location:CGPoint(x: pageLocation.x/pageView.bounds.size.width, y: pageLocation.y/pageView.bounds.size.height))
break
}
}
return possibleTargetPage
}
fileprivate func _getHotspotsAtPoint(_ location: CGPoint) -> [(model: HotspotModel, rect: CGRect)] {
return hotspotDetails.filter({ $0.rect.contains(location) })
}
// MARK: - Gestures
var touchGesture: UILongPressGestureRecognizer?
var tapGesture: UITapGestureRecognizer?
var longPressGesture: UILongPressGestureRecognizer?
var doubleTapGesture: UITapGestureRecognizer?
fileprivate func _initializeGestureRecognizers() {
touchGesture = UILongPressGestureRecognizer(target: self, action: #selector(didTouch))
touchGesture!.minimumPressDuration = 0.01
touchGesture!.delegate = self
touchGesture!.cancelsTouchesInView = false
tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap))
tapGesture!.delegate = self
tapGesture!.cancelsTouchesInView = false
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(didLongPress))
longPressGesture?.minimumPressDuration = 0.75
longPressGesture!.delegate = self
longPressGesture!.cancelsTouchesInView = false
doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(didDoubleTap))
doubleTapGesture!.numberOfTapsRequired = 2
doubleTapGesture!.delegate = self
addGestureRecognizer(longPressGesture!)
addGestureRecognizer(tapGesture!)
addGestureRecognizer(touchGesture!)
addGestureRecognizer(doubleTapGesture!)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == tapGesture {
return otherGestureRecognizer == touchGesture
} else if gestureRecognizer == touchGesture {
return true
} else if gestureRecognizer == longPressGesture {
return otherGestureRecognizer != tapGesture
} else if gestureRecognizer == doubleTapGesture {
return true
} else {
return false
}
}
func updateDimmedOverlayMask(with rects: [CGRect]) {
hotspotViews.forEach({ $0.removeFromSuperview() })
guard rects.count > 0 else {
dimmedOverlay.isHidden = true
dimmedOverlay.maskLayer = nil
return
}
let rectsMap: (views: [UIView], path: UIBezierPath) = rects.reduce(into: (views: [], path: UIBezierPath())) {
let hotspotView = UIView(frame: $1)
hotspotView.backgroundColor = UIColor(white: 1, alpha: 0)
hotspotView.layer.cornerRadius = 4
hotspotView.layer.borderColor = UIColor.white.cgColor
hotspotView.layer.borderWidth = 2
hotspotView.alpha = 0
$0.views.append(hotspotView)
addSubview(hotspotView)
$0.path.append(UIBezierPath(roundedRect: $1, cornerRadius: 4))
}
self.hotspotViews = rectsMap.views
let maskLayer = CAShapeLayer()
maskLayer.frame = dimmedOverlay.frame
maskLayer.path = rectsMap.path.cgPath
maskLayer.fillColor = UIColor.black.cgColor
self.dimmedOverlay.isHidden = false
self.dimmedOverlay.maskLayer = maskLayer
}
@objc func fadeOutOverlay() {
// fade out all hotspot views when touch finishes
UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: {
self.dimmedOverlay.alpha = 0.0
}, completion: nil)
for hotspotView in hotspotViews {
UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: {
hotspotView.alpha = 0.0
}, completion: nil)
}
}
func updateAndFadeInHotspots(at location: CGPoint) {
let hotspots = _getHotspotsAtPoint(location)
updateDimmedOverlayMask(with: hotspots.map({ $0.rect }))
UIView.animate(withDuration: 0.4, delay: 0.1, options: [.beginFromCurrentState, .allowUserInteraction], animations: {
self.dimmedOverlay.alpha = 0.4
for hotspotView in self.hotspotViews {
hotspotView.alpha = 0.8
}
}, completion: nil)
}
// MARK: Gesture handlers
@objc
func didTouch(_ touch: UILongPressGestureRecognizer) {
guard !isZooming else { return }
guard bounds.size.width > 0 && bounds.size.height > 0 else {
return
}
if touch.state == .began {
let location = touch.location(in: self)
updateAndFadeInHotspots(at: location)
} else if touch.state == .ended || touch.state == .cancelled {
guard tapGesture!.state != .ended else { return }
self.perform(#selector(fadeOutOverlay), with: nil, afterDelay: 0, inModes: [RunLoop.Mode.common])
}
}
@objc
func didTap(_ tap: UITapGestureRecognizer) {
guard bounds.size.width > 0 && bounds.size.height > 0 else {
return
}
guard let targetPage = _getTargetPage(forGesture: tap) else {
return
}
let overlayLocation = tap.location(in: self)
let hotspots = _getHotspotsAtPoint(overlayLocation)
UIView.animate(withDuration: 0.1, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: {
self.dimmedOverlay.alpha = 0.4
for hotspotView in self.hotspotViews {
hotspotView.alpha = 0.8
}
}, completion: { [weak self] finished in
self?.fadeOutOverlay()
})
delegate?.didTapHotspot(overlay: self, hotspots: hotspots.map({ $0.model }), hotspotRects: hotspots.map({ $0.rect }), locationInOverlay: overlayLocation, pageIndex: targetPage.index, locationInPage: targetPage.location)
}
@objc
func didLongPress(_ press: UILongPressGestureRecognizer) {
guard bounds.size.width > 0 && bounds.size.height > 0 else { return }
guard press.state == .began else { return }
guard let targetPage = _getTargetPage(forGesture: press) else { return }
let overlayLocation = press.location(in: self)
let hotspots = _getHotspotsAtPoint(overlayLocation)
UIView.animate(withDuration: 0.1, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: {
self.dimmedOverlay.alpha = 0.4
})
for hotspotView in hotspotViews {
UIView.animate(withDuration: 0.1, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: {
hotspotView.alpha = 0.8
hotspotView.backgroundColor = UIColor(white: 1, alpha: 0.8)
hotspotView.layer.transform = CATransform3DMakeScale(1.1, 1.1, 1.1)
}, completion: { (finished) in
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.7, options: [.beginFromCurrentState, .allowUserInteraction], animations: {
hotspotView.layer.transform = CATransform3DIdentity
})
})
}
delegate?.didLongPressHotspot(overlay: self, hotspots: hotspots.map({ $0.model }), hotspotRects: hotspots.map({ $0.rect }), locationInOverlay: overlayLocation, pageIndex: targetPage.index, locationInPage: targetPage.location)
}
@objc
func didDoubleTap(_ doubleTap: UITapGestureRecognizer) {
guard doubleTap.state == .ended else { return }
guard let targetPage = _getTargetPage(forGesture: doubleTap) else { return }
let overlayLocation = doubleTap.location(in: self)
let hotspots = _getHotspotsAtPoint(overlayLocation)
delegate?.didDoubleTapHotspot(overlay: self, hotspots: hotspots.map({ $0.model }), hotspotRects: hotspots.map({ $0.rect }), locationInOverlay: overlayLocation, pageIndex: targetPage.index, locationInPage: targetPage.location)
}
// MARK: Hotspot views
fileprivate var hotspotDetails: [(model: HotspotModel, rect: CGRect)] = []
fileprivate var pageViews: [Int: UIView] = [:]
func updateWithHotspots(_ hotspots: [HotspotModel], pageFrames: [Int: CGRect]) {
self.pageViews.forEach({ $0.value.removeFromSuperview() })
self.pageViews = pageFrames.mapValues {
let pageView = UIView(frame: $0)
pageView.isHidden = true
pageView.isUserInteractionEnabled = false
pageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(pageView)
return pageView
}
let minSize = CGSize(width: min(bounds.size.width * 0.02, 20), height: min(bounds.size.height * 0.02, 20))
self.hotspotDetails = hotspots.compactMap {
guard let hotspotFrame = _frameForHotspot($0),
hotspotFrame.isEmpty == false,
hotspotFrame.width > minSize.width,
hotspotFrame.height > minSize.height else {
return nil
}
return ($0, hotspotFrame)
}
dimmedOverlay.alpha = 0.0
dimmedOverlay.maskLayer = nil
// hotspot update may come after the touch has started - so show the overlay
if hotspots.count > 0 && (touchGesture!.state == .began || touchGesture!.state == .changed) {
let location = touchGesture!.location(in: self)
updateAndFadeInHotspots(at: location)
}
}
fileprivate func _frameForHotspot(_ hotspot: HotspotModel) -> CGRect? {
return hotspot.pageLocations.reduce(into: nil) {
guard $1.value.isEmpty == false,
let pageFrame = pageViews[$1.key]?.frame else { return }
let hotspotFrame = CGRect(x: pageFrame.origin.x + ($1.value.origin.x * pageFrame.width),
y: pageFrame.origin.y + ($1.value.origin.y * pageFrame.height),
width: $1.value.width * pageFrame.width,
height: $1.value.height * pageFrame.height)
$0 = $0?.union(hotspotFrame) ?? hotspotFrame
}
}
}
}
| mit | 98864200c82edfc6ddf08e339b5c4af0 | 44.717949 | 237 | 0.578114 | 5.504974 | false | false | false | false |
jfosterdavis/Charles | Charles/Clue.swift | 1 | 1168 | //
// Clue.swift
// Charles
//
// Created by Jacob Foster Davis on 6/16/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
/******************************************************/
/*******************///MARK: Data needed to present the user with a clue on how to play this flipping game.
/******************************************************/
class Clue: NSObject {
var clueTitle: String
var part1: String?
var part1Image: UIImage?
var part2: String?
var part2Image: UIImage?
var part3: String?
var part3Image: UIImage?
// MARK: Initializers
init(clueTitle: String,
part1: String? = nil,
part1Image: UIImage? = nil,
part2: String? = nil,
part2Image: UIImage? = nil,
part3: String? = nil,
part3Image: UIImage? = nil ) {
self.clueTitle = clueTitle
self.part1 = part1
self.part1Image = part1Image
self.part2 = part2
self.part2Image = part2Image
self.part3 = part3
self.part3Image = part3Image
super.init()
}
}
| apache-2.0 | 53c9fbfa8a098285a8a54ae7d2806834 | 21.882353 | 107 | 0.513282 | 4.052083 | false | false | false | false |
Glenmax-ltd/GLXSegmentedControl | GLXSegmentedControl/GLXSegmentedControl.swift | 1 | 15633 | //
// GLXSegmentedControl.swift
// GLXSegmentedControlController
//
// Created by Si Ma on 01/10/15.
// Copyright © 2015 Si Ma and Glenmax Ltd. All rights reserved.
//
import UIKit
extension UILabel {
func fontFitsCurrentFrame(_ font:UIFont) -> Bool {
let attributes = [NSFontAttributeName:font]
if let size = self.text?.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil) {
if size.width > frame.size.width {
return false
}
if size.height > frame.size.height {
return false
}
}
return true
}
}
public enum GLXSegmentOrganiseMode: Int {
case horizontal
case vertical
}
open class GLXSegmentedControl: UIControl {
open var segmentAppearance: GLXSegmentAppearance
open var enforceEqualFontForLabels = true
// Divider Color & width
open var dividerColor: UIColor {
get {
return self.segmentAppearance.dividerColor
}
}
open var dividerWidth: CGFloat {
get {
return self.segmentAppearance.dividerWidth
}
}
open var selectedSegmentIndex: Int {
get {
if let segment = self.selectedSegment {
return segment.index
}
else {
return UISegmentedControlNoSegment
}
}
set(newIndex) {
self.deselectSegment()
if newIndex >= 0 && newIndex < self.segments.count {
let currentSelectedSegment = self.segments[newIndex]
self.selectSegment(currentSelectedSegment)
}
}
}
open var organiseMode: GLXSegmentOrganiseMode = .horizontal {
didSet {
if self.organiseMode != oldValue {
self.setNeedsDisplay()
}
}
}
open var numberOfSegments: Int {
get {
return segments.count
}
}
fileprivate var segments: [GLXSegment] = []
fileprivate var selectedSegment: GLXSegment?
// INITIALISER
required public init?(coder aDecoder: NSCoder) {
self.segmentAppearance = GLXSegmentAppearance()
super.init(coder: aDecoder)
self.layer.masksToBounds = true
}
override public init(frame: CGRect) {
self.segmentAppearance = GLXSegmentAppearance()
super.init(frame: frame)
self.backgroundColor = UIColor.clear
self.layer.masksToBounds = true
}
public init(frame: CGRect, segmentAppearance: GLXSegmentAppearance) {
self.segmentAppearance = segmentAppearance
super.init(frame: frame)
self.backgroundColor = UIColor.clear
self.layer.masksToBounds = true
}
// MARK: Actions
// MARK: Select/deselect Segment
fileprivate func selectSegment(_ segment: GLXSegment, fireAction:Bool = false) {
segment.setSelected(true)
self.selectedSegment = segment
if fireAction {
self.sendActions(for: .valueChanged)
}
}
fileprivate func deselectSegment() {
self.selectedSegment?.setSelected(false)
self.selectedSegment = nil
}
// MARK: Add Segment
open func addSegment(withTitle title: String?, onSelectionImage: UIImage?, offSelectionImage: UIImage?, animated:Bool = false) {
self.insertSegment(withTitle:title, onSelectionImage: onSelectionImage, offSelectionImage: offSelectionImage, index: self.segments.count, animated: animated)
}
open func insertSegment(withTitle title: String?, onSelectionImage: UIImage?, offSelectionImage: UIImage?, index: Int, animated:Bool = false) {
let segment = GLXSegment(appearance: self.segmentAppearance)
segment.translatesAutoresizingMaskIntoConstraints = false
segment.title = title
segment.onSelectionImage = onSelectionImage
segment.offSelectionImage = offSelectionImage
segment.index = index
segment.didSelectSegment = { [unowned self] segment in
if self.selectedSegment != segment {
self.deselectSegment()
self.selectSegment(segment, fireAction:true)
}
}
segment.setupUIElements()
self.resetSegmentIndices(withIndex: index, by: 1)
self.segments.insert(segment, at: index)
self.addSubview(segment)
// now we setup constraints for segment
self.updateConstraintsForSegmentInsertion(at: index)
if animated {
UIView.animate(withDuration: 0.5, animations: {
self.layoutSubviews()
})
}
}
// MARK: Remove Segment
open func removeSegment(at index: Int, animated:Bool = false) {
assert(index >= 0 && index < self.segments.count, "Index (\(index)) is out of range")
if index == self.selectedSegmentIndex {
self.selectedSegmentIndex = UISegmentedControlNoSegment
}
self.resetSegmentIndices(withIndex: index, by: -1)
let segment = self.segments.remove(at: index)
segment.removeFromSuperview()
guard segments.count > 0 else {
return
}
// if some segments remain we need to update constraints
self.updateConstraintsForSegmentRemoval(at: index)
if animated {
UIView.animate(withDuration: 0.5, animations: {
self.layoutSubviews()
})
}
}
fileprivate func resetSegmentIndices(withIndex index: Int, by: Int) {
if index < self.segments.count {
for i in index..<self.segments.count {
let segment = self.segments[i]
segment.index += by
}
}
}
// MARK: Access segments
open func segment(at index:Int) -> GLXSegment {
assert(index >= 0 && index < self.segments.count, "Index (\(index)) is out of range")
return segments[index]
}
// MARK: UI
// MARK: Update layout
open override func layoutSubviews() {
super.layoutSubviews()
// FIXME: I do not yet understand why line above is not sufficient
// to put subviews into their frames
for subview in self.subviews {
subview.layoutIfNeeded()
}
labelFontAdj: if enforceEqualFontForLabels {
var labelsToCheck = [UILabel]()
for segment in segments {
guard
let title = segment.title,
title != ""
else {continue}
labelsToCheck.append(segment.label)
}
guard labelsToCheck.count > 0 else {break labelFontAdj}
var minimumScaleFactor:CGFloat = 0.0
var selectedFont = segmentAppearance.titleOnSelectionFont
var nonSelectedFont = segmentAppearance.titleOffSelectionFont
for label in labelsToCheck {
minimumScaleFactor = max(minimumScaleFactor, label.minimumScaleFactor)
}
var selectedFound = false
var nonSelectedFound = false
for currentScaleFactor in stride(from: 1.0, to: minimumScaleFactor, by: -0.05) {
let newSelectedFont = selectedFont.withSize(selectedFont.pointSize * currentScaleFactor)
let newNonSelectedFont = nonSelectedFont.withSize(nonSelectedFont.pointSize * currentScaleFactor)
var trySelected = !selectedFound
var tryNonSelected = !nonSelectedFound
for label in labelsToCheck {
if trySelected {
trySelected = trySelected && label.fontFitsCurrentFrame(newSelectedFont)
}
if tryNonSelected {
tryNonSelected = tryNonSelected && label.fontFitsCurrentFrame(newNonSelectedFont)
}
if !(trySelected || tryNonSelected) {
break
}
}
if trySelected {
selectedFont = newSelectedFont
selectedFound = true
}
if tryNonSelected {
nonSelectedFont = newNonSelectedFont
nonSelectedFound = true
}
if selectedFound && nonSelectedFound {
break
}
}
segmentAppearance.titleOnSelectionFont = selectedFont
segmentAppearance.titleOffSelectionFont = nonSelectedFont
for segment in segments {
if segment.isSelected {
segment.label.font = segmentAppearance.titleOnSelectionFont
}
else {
segment.label.font = segmentAppearance.titleOffSelectionFont
}
}
}
}
func updateConstraintsForSegmentInsertion(at index:Int) {
// first find next/previous items
let itemBefore:UIView
let itemAfter:UIView
let segment = segments[index]
if index == 0 {
itemBefore = self
}
else {
itemBefore = segments[index-1]
}
if index == segments.count - 1 {
itemAfter = self
}
else {
itemAfter = segments[index+1]
}
// now remove old constraints between next/previous
let constraintsToRemove = self.constraints.filter({ (constraint) -> Bool in
return (constraint.firstItem as! NSObject == itemAfter) && (constraint.secondItem as! NSObject == itemBefore)
})
for constraint in constraintsToRemove {
if organiseMode == .horizontal {
// check if we are not trying to remove top or bottom
if (constraint.secondAttribute == .top) || (constraint.secondAttribute == .bottom) {
continue
}
}
else {
// check if we are not trying remove top or bottom
if (constraint.secondAttribute == .left) || (constraint.secondAttribute == .right) {
continue
}
}
constraint.isActive = false
}
// now add constraint between next and segment
// and between segment and previous
self.setConstraintsBetween(nextItem: itemAfter, previousItem: segment)
self.setConstraintsBetween(nextItem: segment, previousItem: itemBefore)
if self.organiseMode == .horizontal {
segment.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
segment.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
else {
segment.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
segment.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
}
}
func updateConstraintsForSegmentRemoval(at index:Int) {
if index == 0 {
// we deleted first segment
segments[0].leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
}
else if index == segments.count {
// we deleted last segment
self.trailingAnchor.constraint(equalTo: segments[index-1].trailingAnchor).isActive = true
}
else {
// there is one segment before and one segment after
let segmentBefore = segments[index-1]
let segmentAfter = segments[index]
self.setConstraintsBetween(nextItem: segmentAfter, previousItem: segmentBefore)
}
}
// MARK: Constraints Setup helper functions
fileprivate func setConstraintsBetween(nextItem:UIView, previousItem:UIView) {
let constant:CGFloat
if (nextItem == self) || (previousItem == self) {
constant = 0
}
else {
constant = dividerWidth
if organiseMode == .horizontal {
nextItem.widthAnchor.constraint(equalTo: previousItem.widthAnchor).isActive = true
}
else {
nextItem.heightAnchor.constraint(equalTo: previousItem.heightAnchor).isActive = true
}
}
if organiseMode == .horizontal {
let nextAnchor:NSLayoutXAxisAnchor
let previousAnchor:NSLayoutXAxisAnchor
if nextItem == self {
nextAnchor = self.trailingAnchor
}
else {
nextAnchor = nextItem.leadingAnchor
}
if previousItem == self {
previousAnchor = self.leadingAnchor
}
else {
previousAnchor = previousItem.trailingAnchor
}
nextAnchor.constraint(equalTo: previousAnchor, constant: constant).isActive = true
}
else {
let nextAnchor:NSLayoutYAxisAnchor
let previousAnchor:NSLayoutYAxisAnchor
if nextItem == self {
nextAnchor = self.bottomAnchor
}
else {
nextAnchor = nextItem.topAnchor
}
if previousItem == self {
previousAnchor = self.topAnchor
}
else {
previousAnchor = previousItem.bottomAnchor
}
nextAnchor.constraint(equalTo: previousAnchor, constant: constant).isActive = true
}
}
// MARK: Drawing Segment Dividers
override open func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()!
self.drawDivider(withContext: context)
}
fileprivate func drawDivider(withContext context: CGContext) {
context.saveGState()
if self.segments.count > 1 {
let path = CGMutablePath()
if self.organiseMode == .horizontal {
var originX: CGFloat = self.segments[0].frame.size.width + self.dividerWidth/2.0
for index in 1..<self.segments.count {
path.move(to: CGPoint(x: originX, y: 0.0))
path.addLine(to: CGPoint(x: originX, y: self.frame.size.height))
originX += self.segments[index].frame.width + self.dividerWidth
}
}
else {
var originY: CGFloat = self.segments[0].frame.size.height + self.dividerWidth/2.0
for index in 1..<self.segments.count {
path.move(to: CGPoint(x: 0.0, y: originY))
path.addLine(to: CGPoint(x: self.frame.size.width, y: originY))
originY += self.segments[index].frame.height + self.dividerWidth
}
}
context.addPath(path)
context.setStrokeColor(self.dividerColor.cgColor)
context.setLineWidth(self.dividerWidth)
context.drawPath(using: CGPathDrawingMode.stroke)
}
context.restoreGState()
}
}
| mit | b28db61f34cbfe1b1fa7441412b84772 | 33.056645 | 214 | 0.565571 | 5.441002 | false | false | false | false |
imclean/JLDishWashers | JLDishwasher/Availability.swift | 1 | 1828 | //
// Availability.swift
// JLDishwasher
//
// Created by Iain McLean on 21/12/2016.
// Copyright © 2016 Iain McLean. All rights reserved.
//
import Foundation
public class Availability {
public var message : String?
public var availabilityStatus : String?
public var stockLevel : Int?
/**
Returns an array of models based on given dictionary.
Sample usage:
let availability_list = Availability.modelsFromDictionaryArray(someDictionaryArrayFromJSON)
- parameter array: NSArray from JSON dictionary.
- returns: Array of Availability Instances.
*/
public class func modelsFromDictionaryArray(array:NSArray) -> [Availability] {
var models:[Availability] = []
for item in array {
models.append(Availability(dictionary: item as! NSDictionary)!)
}
return models
}
/**
Constructs the object based on the given dictionary.
Sample usage:
let availability = Availability(someDictionaryFromJSON)
- parameter dictionary: NSDictionary from JSON.
- returns: Availability Instance.
*/
required public init?(dictionary: NSDictionary) {
message = dictionary["message"] as? String
availabilityStatus = dictionary["availabilityStatus"] as? String
stockLevel = dictionary["stockLevel"] as? Int
}
/**
Returns the dictionary representation for the current instance.
- returns: NSDictionary.
*/
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.message, forKey: "message")
dictionary.setValue(self.availabilityStatus, forKey: "availabilityStatus")
dictionary.setValue(self.stockLevel, forKey: "stockLevel")
return dictionary
}
}
| gpl-3.0 | 39bf9884f525f2a7acd5e9fdaf2070ea | 26.268657 | 99 | 0.679803 | 4.872 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Money/Sources/MoneyKit/CurrencyRepresentation/Crypto/CryptoFormatter.swift | 1 | 6020 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import Foundation
/// A precision level for formatting a `CryptoValue` into a `String`.
public enum CryptoPrecision: String {
/// The currency's display precision.
case short
/// The currency's full precision.
case long
/// Gets the maximum number of digits after the decimal separator, based on the current precision.
///
/// - Parameter currency: A crypto currency.
func maxFractionDigits(for currency: CryptoCurrency) -> Int {
switch self {
case .long:
return currency.precision
case .short:
return currency.displayPrecision
}
}
}
public final class CryptoFormatterProvider {
/// A singleton value.
static let shared = CryptoFormatterProvider()
// MARK: - Private Properties
private var formatters = [String: CryptoFormatter]()
/// Dispatch queue used for thread safe access to `formatters`.
private let queue = DispatchQueue(label: "CryptoFormatterProvider.queue.\(UUID().uuidString)")
// MARK: - Public Methods
/// Returns a `CryptoFormatter`.
///
/// Provides caching for the existing crypto formatters, with thread safe access.
///
/// - Parameters:
/// - locale: A locale.
/// - cryptoCurrency: A crypto currency.
/// - minFractionDigits: The minimum number of digits after the decimal separator.
/// - precision: A precision level.
public func formatter(
locale: Locale,
cryptoCurrency: CryptoCurrency,
minFractionDigits: Int = 1,
withPrecision precision: CryptoPrecision
) -> CryptoFormatter {
queue.sync { [unowned self] in
let key = key(
locale: locale,
cryptoCurrency: cryptoCurrency,
minFractionDigits: minFractionDigits,
precision: precision
)
if let formatter = self.formatters[key] {
return formatter
} else {
let formatter = CryptoFormatter(
locale: locale,
cryptoCurrency: cryptoCurrency,
minFractionDigits: minFractionDigits,
withPrecision: precision
)
self.formatters[key] = formatter
return formatter
}
}
}
// MARK: - Private Methods
/// Creates a caching key.
///
/// - Parameters:
/// - locale: A locale.
/// - cryptoCurrency: A crypto currency.
/// - minFractionDigits: The minimum number of digits after the decimal separator.
/// - precision: A precision level.
private func key(
locale: Locale,
cryptoCurrency: CryptoCurrency,
minFractionDigits: Int,
precision: CryptoPrecision
) -> String {
"\(locale.identifier)_\(cryptoCurrency.code)_\(minFractionDigits)_\(precision)"
}
}
public final class CryptoFormatter {
// MARK: - Private Properties
private let formatter: NumberFormatter
/// The associated crypto currency.
private let cryptoCurrency: CryptoCurrency
// MARK: - Setup
/// Creates a crypto formatter.
///
/// - Parameters:
/// - locale: A locale.
/// - cryptoCurrency: A crypto currency
/// - minFractionDigits: The minimum number of digits after the decimal separator.
/// - precision: A precision level.
public init(
locale: Locale,
cryptoCurrency: CryptoCurrency,
minFractionDigits: Int,
withPrecision precision: CryptoPrecision
) {
formatter = .cryptoFormatter(
locale: locale,
minFractionDigits: minFractionDigits,
maxFractionDigits: precision.maxFractionDigits(for: cryptoCurrency)
)
self.cryptoCurrency = cryptoCurrency
}
// MARK: - Public Methods
/// Returns a string containing the formatted amount, optionally including the symbol.
///
/// - Parameters:
/// - amount: An amount in major units.
/// - includeSymbol: Whether the symbol should be included.
public func format(
major amount: Decimal,
includeSymbol: Bool = false
) -> String {
var formattedString = formatter.string(from: NSDecimalNumber(decimal: amount)) ?? "\(amount)"
if includeSymbol {
formattedString += " " + cryptoCurrency.displayCode
}
return formattedString
}
/// Returns a string containing the formatted amount, optionally including the symbol.
///
/// - Parameters:
/// - amount: An amount in minor units.
/// - includeSymbol: Whether the symbol should be included.
public func format(
minor amount: BigInt,
includeSymbol: Bool = false
) -> String {
let majorAmount = amount.toDecimalMajor(
baseDecimalPlaces: cryptoCurrency.precision,
roundingDecimalPlaces: cryptoCurrency.precision
)
return format(major: majorAmount, includeSymbol: includeSymbol)
}
}
extension NumberFormatter {
/// Creates a crypto number formatter.
///
/// - Parameters:
/// - locale: A locale.
/// - minFractionDigits: The minimum number of digits after the decimal separator.
/// - maxFractionDigits: The maximum number of digits after the decimal separator.
public static func cryptoFormatter(locale: Locale, minFractionDigits: Int, maxFractionDigits: Int) -> NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .decimal
formatter.usesGroupingSeparator = true
formatter.minimumFractionDigits = minFractionDigits
formatter.maximumFractionDigits = maxFractionDigits
formatter.roundingMode = .down
return formatter
}
}
| lgpl-3.0 | 51ca1881b3923ee0e5cef3376830dc23 | 31.535135 | 123 | 0.614886 | 5.345471 | false | false | false | false |
jensmeder/DarkLightning | Sources/Daemon/Sources/Devices/USBDevice.swift | 1 | 6152 | /**
*
* DarkLightning
*
*
*
* The MIT License (MIT)
*
* Copyright (c) 2017 Jens Meder
*
* 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
internal final class USBDevice: DeviceWrap {
private let deviceID: Int
internal convenience init() {
self.init(
devices: DevicesFake(),
deviceID: 0,
dictionary: Memory<[Int : Data]>(initialValue: [:]),
port: 1234,
delegate: DeviceDelegateFake()
)
}
internal convenience init(devices: Devices, deviceID: Int, dictionary: Memory<[Int: Data]>, port: UInt32, delegate: DeviceDelegate) {
let handle = Memory<CFSocketNativeHandle>(initialValue: CFSocketInvalidHandle)
let state = Memory<Int>(initialValue: 0)
let inputStream = Memory<InputStream?>(initialValue: nil)
let outputStream = Memory<OutputStream?>(initialValue: nil)
let tcpMode = Memory<Bool>(initialValue: false)
let queue = DispatchQueue.global(qos: .background)
let root = Memory<Daemon?>(initialValue: nil)
self.init(
deviceID: deviceID,
dictionary: dictionary,
daemon: USBDaemon(
socket: handle,
queue: queue,
stream: SocketStream(
handle: handle,
inputStream: inputStream,
outputStream: outputStream,
readReaction: StreamDelegates(
delegates: [
ReadStreamReaction(
delegate: DataDecodings(
decodings: [
TCPMessage(
tcpMode: tcpMode,
delegate: delegate,
devices: devices,
deviceID: deviceID
),
ReceivingDataReaction(
tcpMode: tcpMode,
mapping: { (plist: [String : Any]) -> (USBMuxMessage) in
return ResultMessage(
plist: plist,
devices: devices,
deviceID: deviceID,
tcpMode: { (device) -> (BoolValue) in
return TCPMode(
tcpMode: tcpMode,
queue: DispatchQueue.main,
delegate: delegate,
device: device
)
}
)
},
dataMapping: { (data: Data) -> (OODataArray) in
return USBMuxMessageDataArray(
data: data
)
}
)
]
)
),
EndOfStreamReaction(
origin: StreamDelegates(
delegates: [
NotifyDisconnectReaction(
delegate: delegate,
deviceID: deviceID,
devices: devices
),
DisconnectReaction(
handle: handle,
state: state,
newState: 0
)
]
)
)
]
),
writeReaction: StreamDelegates(
delegates: [
OpenReaction(
state: state,
outputStream: SocketWriteStream(
outputStream: outputStream
),
message: ConnectMessageData(
deviceID: deviceID,
port: port
),
newState: 1
),
EndOfStreamReaction(
origin: CloseStreamReaction()
),
]
)
),
root: root,
state: state
),
stream: SocketWriteStream(
outputStream: outputStream
),
delegate: delegate
)
}
internal required init(deviceID: Int, dictionary: Memory<[Int: Data]>, daemon: Daemon, stream: WriteStream, delegate: DeviceDelegate) {
self.deviceID = deviceID
super.init(
origin: USBDeviceConnection(
deviceID: deviceID,
dictionary: dictionary,
daemon: daemon,
stream: stream,
delegate: delegate
)
)
}
override func isEqual(obj: Any) -> Bool {
var result = false
if let device = obj as? USBDevice {
result = device.deviceID == deviceID
}
return result
}
}
| mit | 0071368f9d0602c6135c30535f4b708e | 36.060241 | 139 | 0.471554 | 5.771107 | false | false | false | false |
kiwitechnologies/ServiceClientiOS | Example/ServiceSample/ViewController.swift | 1 | 10993 | //
// ViewController.swift
// LoginSample
//
// Created by Yogesh Bhatt on 07/04/16.
// Copyright © 2016 kiwitech. All rights reserved.
//
import UIKit
import TSGServiceClient
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var apiResult: UITextView!
@IBOutlet weak var progressIndicator: UIProgressView!
@IBOutlet weak var plaintText: UITextField!
@IBOutlet weak var cipherText: UILabel!
@IBOutlet weak var decryptedText: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var httpActionBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
activityIndicatorView.hidden = true
httpActionBtn.layer.borderWidth = 1
httpActionBtn.layer.cornerRadius = 5
httpActionBtn.layer.borderColor = UIColor.blueColor().CGColor
}
@IBAction func btnActionClicked(sender: AnyObject)
{
apiResult.text = ""
let optionMenu = UIAlertController(title: nil, message: "ALLECTIVE ACTIONS", preferredStyle: .ActionSheet)
let setProjectId = UIAlertAction(title: "Set ProjectID", style: .Default) { (alert:UIAlertAction) in
self.setProjecRunningID()
}
let hitAnyRequest = UIAlertAction(title: "SESSION Request", style: .Default) { (alert:UIAlertAction) in
self.sessionRequest()
}
let getRequest = UIAlertAction(title: "CATEGORIES Request", style: .Default) { (alert: UIAlertAction) in
self.categoryRequest()
}
let postRequest = UIAlertAction(title: "RESET PASSWORD", style: .Default) { (alert: UIAlertAction) in
self.resetRequest()
}
let downloadRequest = UIAlertAction(title: "Download Request", style: .Default) { (alert:UIAlertAction) in
self.downloadRequest()
}
let pathParamRequest = UIAlertAction(title: "PathParam Request", style: .Default) { (alert: UIAlertAction) in
self.pathParamRequest()
}
let uploadRequest = UIAlertAction(title: "UPLOAD Request", style: .Default) { (alert:UIAlertAction) in
self.uploadRequest()
}
/* let putRequest = UIAlertAction(title: "PUT Request", style: .Default) { (alert:UIAlertAction) in
self.putRequest()
}
let downloadRequest = UIAlertAction(title: "Download Request", style: .Default) { (alert:UIAlertAction) in
self.downloadRequest()
}
let deleteRequest = UIAlertAction(title: "Delete Request", style: .Default) { (alert:UIAlertAction) in
self.deleteRequest()
} */
let cancelRequest = UIAlertAction(title: "Cancel", style: .Default) { (alert:UIAlertAction) in
}
optionMenu.addAction(setProjectId)
optionMenu.addAction(hitAnyRequest)
optionMenu.addAction(getRequest)
optionMenu.addAction(postRequest)
optionMenu.addAction(downloadRequest)
optionMenu.addAction(uploadRequest)
optionMenu.addAction(pathParamRequest)
/*optionMenu.addAction(putRequest)
optionMenu.addAction(downloadRequest)
optionMenu.addAction(deleteRequest)*/
optionMenu.addAction(cancelRequest)
self.presentViewController(optionMenu, animated: true, completion: nil)
}
func pathParamRequest(){
let pathParamDict:[String:AnyObject] = ["id":"11"]
ServiceManager.setBackGroundConfiguration(false, bundleID: "com.tsg.iOS")
TSGServiceManager.enableLog(true)
TSGServiceManager.performAction(RECENTMEDIA, withQueryParam: ["auth_token":"3nzhxHYd9Tpfsjx-WmdL"], withPathParams: pathParamDict, onSuccess: { (object) in
print(object)
}) { (status, error) in
print(error)
}
}
func sessionRequest()
{
TSGServiceManager.enableLog(true)
TSGServiceManager.setEncoding(.URL)
let jsonDict = ["user[email]":"manish.johari@kiwitech.com","user[code]":"9967"]
TSGServiceManager.performAction(SESSION, withBodyParams: jsonDict, onSuccess: { (object) in
print(object)
self.apiResult.text = "\(object)"
}) { (status, error) in
print(error)
self.apiResult.text = "\(error)"
}
}
func downloadRequest()
{
//http://www.charts.noaa.gov/BookletChart/
activityIndicatorView.hidden = false
activityIndicatorView.startAnimating()
ServiceManager.setTimeOutInterval(200)
let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier
print(bundleIdentifier)
ServiceManager.setBackGroundConfiguration(true, bundleID: bundleIdentifier)
progressIndicator.hidden = false
ServiceManager.downloadWith("http://www.jplayer.org/video/m4v/Incredibles_Teaser_640x272_h264aac.m4v", requestType: .GET, downloadType: .SEQUENTIAL, withApiTag: "CCCCC", prority: false, downloadingPath: "DownloadedArticles/Articles",fileName: "image.m4v", progress: { (percentage) in
print("CCCCCC\(percentage)")
dispatch_async(dispatch_get_main_queue()) {
self.progressIndicator.setProgress(percentage, animated: true)
}
}, success: { (response) in
print("CCCCCC\(response)")
}) { (error) in
print(error)
}
ServiceManager.downloadWith("http://www.jplayer.org/video/m4v/Incredibles_Teaser.m4v",requestType: .GET, downloadType: .SEQUENTIAL, withApiTag: "Picture 1", prority: true, progress: { (percentage) in
print("Picture1 progress\(percentage)")
dispatch_async(dispatch_get_main_queue()) {
self.progressIndicator.setProgress(percentage, animated: true)
}
}, success: { (response) in
print("Picture1 response \(response)")
dispatch_async(dispatch_get_main_queue()) {
self.activityIndicatorView.hidden = true
self.progressIndicator.hidden = true
self.apiResult.hidden = false
self.apiResult.text = "SUCCESS: File Downloaded"
}
}) { (error) in
print(error)
}
}
func uploadRequest() {
self.apiResult.hidden = true
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = false
activityIndicatorView.hidden = false
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
picker.sourceType = UIImagePickerControllerSourceType.Camera
} else {
picker.sourceType = .PhotoLibrary
picker.modalPresentationStyle = .FullScreen
}
presentViewController(picker, animated: true, completion: nil)
let paramDict:NSMutableDictionary! = NSMutableDictionary()
paramDict.setObject("json", forKey: "format")
}
func setProjecRunningID()
{
TSGServiceManager.setResponseCode(300)
TSGServiceManager.setProjectRuningMode(.DEVELOPMENT)
let currentTime = NSDate.timeIntervalSinceReferenceDate()
print(currentTime)
}
//MARK : function for Get Request
func categoryRequest() {
ServiceManager.hitRequestForAPI("http://52.24.112.194:8080/AdminAPI/security/REST/getBankSettings?bankId=000010000100001", typeOfRequest: .GET, typeOFResponse: .JSON,cachePolicy:NSURLRequestCachePolicy.ReturnCacheDataElseLoad, success: { (obect) in
print(obect)
}) { (error) in
print(error)
}
}
//MARK : function for Post Request
func resetRequest() {
let bodyDict = ["user[email]":"manish.johari@kiwitech.com"]
TSGServiceManager.performAction(RESETPASSWORD, withBodyParams: bodyDict, onSuccess: { ( dictionary) in
print("\(dictionary)")
self.apiResult.text = "\(dictionary)"
}) { (bool, errors) in
let temp = self.convertDictToJSONString(errors.userInfo)
print(errors)
self.apiResult.text = temp
}
}
//MARK : function for Put Request
func putRequest() {
let bodyDict = ["project_id":"55", "name":"yogesh","user_email":"yogesh@gmail.com","age":"32"]
TSGServiceManager.performAction(UPDATEPROJECT, withBodyParams:bodyDict, onSuccess: { (dictionary) in
// print("\(dictionary)")
self.apiResult.text = "SUCCESS: PUT request executed successfully"
}) { (bool, errors) in
let temp = self.convertDictToJSONString(errors.userInfo)
self.apiResult.text = temp
print("\(bool,errors)")
}
}
//MARK : function for Delete Request
func deleteRequest() {
let keydict = ["project_id":"56"]
TSGServiceManager.performAction(DELETEPROJECT, withBodyParams: keydict, onSuccess: { (dictionary) in
print("\(dictionary)")
}) { (bool, errors) in
print("\(bool,errors)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func convertDictToJSONString(dic:NSDictionary) -> String {
do {
let jsonData:NSData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
return NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
} catch {
}
return "dfd"
}
}
extension ViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
print("Info did not have the required UIImage for the Original Image")
dismissViewControllerAnimated(true, completion: nil)
return
}
imageView.image = UIImage(named: "chand")
let imageData = UIImageJPEGRepresentation(image, 1.0)
activityIndicatorView.startAnimating()
progressIndicator.hidden = false
progressIndicator.setProgress(0, animated: true)
dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 271b4a6fce04de6d57396e34adfdd362 | 34.80456 | 291 | 0.619632 | 4.976007 | false | false | false | false |
sora0077/QiitaKit | QiitaKit/src/Endpoint/Tagging/CreateTagging.swift | 1 | 1413 | //
// CreateTagging.swift
// QiitaKit
//
// Created on 2015/06/08.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import Foundation
import APIKit
import Result
/**
* 投稿にタグを追加します。Qiita:Teamでのみ有効です。
*/
public struct CreateTagging {
public let id: Item.Identifier
/// タグを特定するための一意な名前
/// example: qiita
///
public let name: String
///
/// example: ["0.0.1"]
///
public let versions: Array<String>
public init(id: Item.Identifier, name: String, versions: Array<String>) {
self.id = id
self.name = name
self.versions = versions
}
}
extension CreateTagging: QiitaRequestToken {
public typealias Response = Tagging
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return .POST
}
public var path: String {
return "/api/v2/items/\(id)/taggings"
}
public var parameters: [String: AnyObject]? {
return [
"name": name,
"versions": versions
]
}
public var encoding: RequestEncoding {
return .JSON
}
}
public extension CreateTagging {
func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
return _Tagging(object)
}
}
| mit | 88e28e3bc36f8fba690f5ab50d54cce6 | 18.925373 | 119 | 0.610487 | 4.021084 | false | false | false | false |
sora0077/QiitaKit | QiitaKit/src/Endpoint/Template/UpdateTemplate.swift | 1 | 1913 | //
// UpdateTemplate.swift
// QiitaKit
//
// Created on 2015/06/08.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import Foundation
import APIKit
import Result
/**
* テンプレートを更新します。
*/
public struct UpdateTemplate {
public let id: Template.Identifier
/// テンプレートの本文
/// example: Weekly MTG on %{Year}/%{month}/%{day}
///
public let body: String
/// テンプレートを判別するための名前
/// example: Weekly MTG
///
public let name: String
/// タグ一覧
/// example: [{"name"=>"MTG/%{Year}/%{month}/%{day}", "versions"=>["0.0.1"]}]
///
public let tags: Array<Tagging>
/// 生成される投稿のタイトルの雛形
/// example: Weekly MTG on %{Year}/%{month}/%{day}
///
public let title: String
public init(id: Template.Identifier, body: String, name: String, tags: Array<Tagging>, title: String) {
self.id = id
self.body = body
self.name = name
self.tags = tags
self.title = title
}
}
extension UpdateTemplate: QiitaRequestToken {
public typealias Response = Template
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return .PATCH
}
public var path: String {
return "/api/v2/templates/\(id)"
}
public var parameters: [String: AnyObject]? {
return [
"body": body,
"name": name,
"tags": tags.map({ ["name": $0.name, "versions": $0.versions] }),
"title": title
]
}
public var encoding: RequestEncoding {
return .JSON
}
}
public extension UpdateTemplate {
func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
return _Template(object)
}
}
| mit | ec8dab59996b052615cb5d40f4b750e3 | 21.111111 | 119 | 0.581798 | 3.754717 | false | false | false | false |
joemcsorley/ios-local-storage-client | Pod/LSAPIClient_NOPE.swift | 1 | 4016 | //
// LSAPIClient.swift
// LSAPIClient
//
// Created by Joe McSorley on 12/22/15.
// Copyright © 2015 Lampo Licensing, LLC. All rights reserved.
//
import Foundation
//import PromiseKit
/*
typealias responseTransformerBlockType = ([NSObject : AnyObject]!) -> [NSObject : AnyObject]!
private let userID = "AXIDLOCALUSERIOS"
private let userProfile:[NSObject:AnyObject] = [
"email": "local.user@yoyodyne.com",
"first_name": "Local",
"is_premium": 0,
"is_verified": 1,
"last_name": "User",
"password_reset_initiated": 0,
"user_id": userID,
"zip_code": "38401",
]
private let signInData:[NSObject:AnyObject] = [
"user": [
"is_premium": 0,
"is_verified": 1,
"password_reset_initiated": 0,
"user_id": userID,
],
"oauth": [
"access_token": "e637bc89-1513-4bcf-b87c-05584f7b1621",
"access_token_secret": "MIICSwIBADCB7AYHKoZIzj0CATCB4AIBATAsBgcqhkjOPQEBAiEA/////wAAAAEAAAAAAAAAAAAA" +
"\nAAD///////////////8wRAQg/////wAAAAEAAAAAAAAAAAAAAAD///////////////wEIFrGNdiq" +
"\nOpPns+u9VXaYhrxlHQawzFOw9jvOPD4n0mBLBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5" +
"\nRdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+8" +
"\n5vqtpxeehPO5ysL8YyVRAgEBBIIBVTCCAVECAQEEIO1QQdPSX/OwCs4ms0ZmR/AbK101SANpskXT" +
"\nZbE8ipZZoIHjMIHgAgEBMCwGByqGSM49AQECIQD/////AAAAAQAAAAAAAAAAAAAAAP//////////" +
"\n/////zBEBCD/////AAAAAQAAAAAAAAAAAAAAAP///////////////AQgWsY12Ko6k+ez671VdpiG" +
"\nvGUdBrDMU7D2O848PifSYEsEQQRrF9Hy4SxCR/i85uVjpEDydwN9gS3rM6D0oTlF2JjClk/jQuL+" +
"\nGn+bjufrSnwPnhYrzjNXazFezsu2QGg3v1H1AiEA/////wAAAAD//////////7zm+q2nF56E87nK" +
"\nwvxjJVECAQGhRANCAAQOODNaYaSNTscYvEZ8S2/jID+nTEomPi6I7YpXZznMXpixOSh7p3maoaoT" +
"\n6LR6arEQtNBCoEJKQbJTJmOQyZPX" +
"\n",
"refresh_token": "aaf2a912-bd21-4b8c-95d6-36573d43fdaf",
],
]
class LSAPIClient_NOPE: NSObject {
static func setApiRootURLString(str:String) {}
static func setRequestPathGetURNRules(arr:[NSObject]) {}
static func setRequestPathRefreshToken(arr:[NSObject]) {}
static func setRequestPathUserSignIn(arr:[NSObject]) {}
static func setRequestPathUserSignUp(arr:[NSObject]) {}
static func setRequestPathChangePassword(arr:[NSObject]) {}
static func addGlobalHeaderValue(value:String, forKey:String) {}
static func resumeRequestSequence(requestSequence:LSRequestSequence, responseTransformer:responseTransformerBlockType?) -> Promise<[NSObject:AnyObject]> {
return Promise { fulfill, reject in
let data:[NSObject:AnyObject] = ["data":"its all good"]
var result = data
if let transformer = responseTransformer {
result = transformer(data)
}
fulfill(result)
}
}
static func resumeRequestSequence(requestSequence:LSRequestSequence) -> Promise<[NSObject:AnyObject]> {
return resumeRequestSequence(requestSequence, responseTransformer: nil)
}
static func signUp(data:[NSObject : AnyObject]) -> Promise<[NSObject:AnyObject]> {
return Promise { fulfill, reject in
fulfill(signInData);
}
}
static func signInWithUserName(userName:String, password:String) -> Promise<[NSObject:AnyObject]> {
return Promise { fulfill, reject in
fulfill(signInData);
}
}
static func currentUserName() -> String? {
if let userName = userProfile["email"] as? String {
return userName
}
else {
return nil
}
}
static func lastSignedInUserName() -> String? {
return currentUserName()
}
static func currentUserID() -> String? {
return userID
}
static func signOut() {}
static func isSignedIn() -> Bool {
return true
}
}
class LHAPIClient_NOPE: LSAPIClient {}
*/ | mit | af54da35919382cc654122045bbdc438 | 32.466667 | 158 | 0.639103 | 3.277551 | false | false | false | false |
someoneAnyone/Nightscouter | Common/Protocols/SegueHandlerType.swift | 1 | 3211 | //
// SegueHandler.swift
// Nightscouter
//
// Created by Peter Ina on 9/26/16.
// Copyright © 2016 Peter Ina. All rights reserved.
//
import Foundation
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Contains types / typealiases for cross-platform utility helpers for working with segues / segue identifiers in a controller.
*/
#if os(iOS) || os(tvOS)
import UIKit
public typealias StoryboardSegue = UIStoryboardSegue
public typealias Controller = UIViewController
#elseif os(OSX)
import Cocoa
public typealias StoryboardSegue = NSStoryboardSegue
public typealias Controller = NSWindowController
#endif
/**
A protocol specific to the Lister sample that represents the segue identifier
constraints in the app. Every view controller provides a segue identifier
enum mapping. This protocol defines that structure.
We also want to provide implementation to each view controller that conforms
to this protocol that helps box / unbox the segue identifier strings to
segue identifier enums. This is provided in an extension of `SegueHandlerType`.
*/
public protocol SegueHandlerType {
/**
Gives structure to what we expect the segue identifiers will be. We expect
the `SegueIdentifier` mapping to be an enum case to `String` mapping.
For example:
enum SegueIdentifier: String {
case ShowAccount
case ShowHelp
...
}
*/
associatedtype SegueIdentifier: RawRepresentable
}
/**
Constrain the implementation for `SegueHandlerType` conforming
types to only work with view controller subclasses whose `SegueIdentifier`
raw values are `String` instances. Practically speaking, the enum that provides
the mapping between the view controller's segue identifier strings should
be backed by a `String`. See the description for `SegueHandlerType` for an example.
*/
public extension SegueHandlerType where Self: Controller, SegueIdentifier.RawValue == String {
/**
An overload of `UIViewController`'s `performSegueWithIdentifier(_:sender:)`
method that takes in a `SegueIdentifier` enum parameter rather than a
`String`.
*/
func performSegue(withIdentifier segueIdentifier: SegueIdentifier,
sender: Any?) {
performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender)
}
/**
A convenience method to map a `StoryboardSegue` to the segue identifier
enum that it represents.
*/
func segueIdentifierForSegue(_ segue: StoryboardSegue) -> SegueIdentifier {
/*
Map the segue identifier's string to an enum. It's a programmer error
if a segue identifier string that's provided doesn't map to one of the
raw representable values (most likely enum cases).
*/
guard let identifier = segue.identifier,
let segueIdentifier = SegueIdentifier(rawValue: identifier) else {
fatalError("Couldn't handle segue identifier \(String(describing: segue.identifier)) for view controller of type \(type(of: self)).")
}
return segueIdentifier
}
}
| mit | 1ac04f1f8b0220bfa13a3a0e4a4be9e0 | 35.044944 | 149 | 0.714464 | 5.293729 | false | false | false | false |
eburns1148/CareKit | Sample/OCKSample/InsightsBuilder.swift | 2 | 6504 | /*
Copyright (c) 2016, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CareKit
class InsightsBuilder {
/// An array if `OCKInsightItem` to show on the Insights view.
fileprivate(set) var insights = [OCKInsightItem.emptyInsightsMessage()]
fileprivate let carePlanStore: OCKCarePlanStore
fileprivate let updateOperationQueue = OperationQueue()
required init(carePlanStore: OCKCarePlanStore) {
self.carePlanStore = carePlanStore
}
/**
Enqueues `NSOperation`s to query the `OCKCarePlanStore` and update the
`insights` property.
*/
func updateInsights(_ completion: ((Bool, [OCKInsightItem]?) -> Void)?) {
// Cancel any in-progress operations.
updateOperationQueue.cancelAllOperations()
// Get the dates the current and previous weeks.
let queryDateRange = calculateQueryDateRange()
/*
Create an operation to query for events for the previous week's
`TakeMedication` activity.
*/
let medicationEventsOperation = QueryActivityEventsOperation(store: carePlanStore,
activityIdentifier: ActivityType.takeMedication.rawValue,
startDate: queryDateRange.start,
endDate: queryDateRange.end)
/*
Create an operation to query for events for the previous week and
current weeks' `BackPain` assessment.
*/
let backPainEventsOperation = QueryActivityEventsOperation(store: carePlanStore,
activityIdentifier: ActivityType.backPain.rawValue,
startDate: queryDateRange.start,
endDate: queryDateRange.end)
/*
Create a `BuildInsightsOperation` to create insights from the data
collected by query operations.
*/
let buildInsightsOperation = BuildInsightsOperation()
/*
Create an operation to aggregate the data from query operations into
the `BuildInsightsOperation`.
*/
let aggregateDataOperation = BlockOperation {
// Copy the queried data from the query operations to the `BuildInsightsOperation`.
buildInsightsOperation.medicationEvents = medicationEventsOperation.dailyEvents
buildInsightsOperation.backPainEvents = backPainEventsOperation.dailyEvents
}
/*
Use the completion block of the `BuildInsightsOperation` to store the
new insights and call the completion block passed to this method.
*/
buildInsightsOperation.completionBlock = { [unowned buildInsightsOperation] in
let completed = !buildInsightsOperation.isCancelled
let newInsights = buildInsightsOperation.insights
// Call the completion block on the main queue.
OperationQueue.main.addOperation {
if completed {
completion?(true, newInsights)
}
else {
completion?(false, nil)
}
}
}
// The aggregate operation is dependent on the query operations.
aggregateDataOperation.addDependency(medicationEventsOperation)
aggregateDataOperation.addDependency(backPainEventsOperation)
// The `BuildInsightsOperation` is dependent on the aggregate operation.
buildInsightsOperation.addDependency(aggregateDataOperation)
// Add all the operations to the operation queue.
updateOperationQueue.addOperations([
medicationEventsOperation,
backPainEventsOperation,
aggregateDataOperation,
buildInsightsOperation
], waitUntilFinished: false)
}
fileprivate func calculateQueryDateRange() -> (start: DateComponents, end: DateComponents) {
let calendar = Calendar.current
let now = Date()
let currentWeekRange = calendar.weekDatesForDate(now)
let previousWeekRange = calendar.weekDatesForDate(currentWeekRange.start.addingTimeInterval(-1))
let queryRangeStart = calendar.dateComponents([.year, .month, .day, .era], from: previousWeekRange.start)
let queryRangeEnd = calendar.dateComponents([.year, .month, .day, .era], from: now)
return (start: queryRangeStart, end: queryRangeEnd)
}
}
protocol InsightsBuilderDelegate: class {
func insightsBuilder(_ insightsBuilder: InsightsBuilder, didUpdateInsights insights: [OCKInsightItem])
}
| bsd-3-clause | fcfa8b32fbcb44d2545127727eba3e8b | 43.855172 | 126 | 0.653598 | 5.645833 | false | false | false | false |
silence0201/Swift-Study | Note/Day 01/03-创建对象补充.playground/Contents.swift | 2 | 962 | //: Playground - noun: a place where people can play
import UIKit
// 需求: 创建UIView对象,并且在UIView中添加UIButton
// 1.创建UIView对象
// OC : [[UIView alloc] initWithFrame:CGRect]
let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
let view : UIView = UIView(frame: rect)
// 2.给View设置属性
view.backgroundColor = UIColor.red
// 3.创建UIButton对象
let btn : UIButton = UIButton()
// 4.给btn设置属性
// 4.1.设置btn的frame
btn.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
// 4.2.设置btn的背景颜色
btn.backgroundColor = UIColor.orange
// 4.3.设置btn的文字(了解)
// Swift枚举类型:
// 方式一: 如果可以根据上下文语法推断出该枚举的类型可以直接 .具体类型
// 方式二: 上下文推断不出类型, 枚举类型.具体类型
btn.setTitle("按钮", for: .normal)
// 5.将btn添加到UIView中
// 在swift中调用方法,统一使用 点语法
view.addSubview(btn)
| mit | 90fd32d923fb04bf5791f5475b7e3ef6 | 19.457143 | 54 | 0.701117 | 2.594203 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/Moya/Source/Moya+Internal.swift | 4 | 13361 | import Foundation
import Result
/// Internal extension to keep the inner-workings outside the main Moya.swift file.
internal extension MoyaProvider {
// Yup, we're disabling these. The function is complicated, but breaking it apart requires a large effort.
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
/// Performs normal requests.
func requestNormal(_ target: Target, queue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> Cancellable {
let endpoint = self.endpoint(target)
let stubBehavior = self.stubClosure(target)
let cancellableToken = CancellableWrapper()
if trackInflights {
objc_sync_enter(self)
var inflightCompletionBlocks = self.inflightRequests[endpoint]
inflightCompletionBlocks?.append(completion)
self.inflightRequests[endpoint] = inflightCompletionBlocks
objc_sync_exit(self)
if inflightCompletionBlocks != nil {
return cancellableToken
} else {
objc_sync_enter(self)
self.inflightRequests[endpoint] = [completion]
objc_sync_exit(self)
}
}
let performNetworking = { (requestResult: Result<URLRequest, Moya.Error>) in
if cancellableToken.cancelled {
self.cancelCompletion(completion, target: target)
return
}
var request: URLRequest!
switch requestResult {
case .success(let urlRequest):
request = urlRequest
case .failure(let error):
completion(.failure(error))
return
}
switch stubBehavior {
case .never:
let networkCompletion: Moya.Completion = { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result) })
objc_sync_enter(self)
self.inflightRequests.removeValue(forKey: endpoint)
objc_sync_exit(self)
} else {
completion(result)
}
}
switch target.task {
case .request:
cancellableToken.innerCancellable = self.sendRequest(target, request: request, queue: queue, progress: progress, completion: networkCompletion)
case .upload(.file(let file)):
cancellableToken.innerCancellable = self.sendUploadFile(target, request: request, queue: queue, file: file, progress: progress, completion: networkCompletion)
case .upload(.multipart(let multipartBody)):
guard !multipartBody.isEmpty && target.method.supportsMultipart else {
fatalError("\(target) is not a multipart upload target.")
}
cancellableToken.innerCancellable = self.sendUploadMultipart(target, request: request, queue: queue, multipartBody: multipartBody, progress: progress, completion: networkCompletion)
case .download(.request(let destination)):
cancellableToken.innerCancellable = self.sendDownloadRequest(target, request: request, queue: queue, destination: destination, progress: progress, completion: networkCompletion)
}
default:
cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result) })
objc_sync_enter(self)
self.inflightRequests.removeValue(forKey: endpoint)
objc_sync_exit(self)
} else {
completion(result)
}
}, endpoint: endpoint, stubBehavior: stubBehavior)
}
}
requestClosure(endpoint, performNetworking)
return cancellableToken
}
// swiftlint:enable cyclomatic_complexity
// swiftlint:enable function_body_length
func cancelCompletion(_ completion: Moya.Completion, target: Target) {
let error = Moya.Error.underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
plugins.forEach { $0.didReceiveResponse(.failure(error), target: target) }
completion(.failure(error))
}
/// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters.
final func createStubFunction(_ token: CancellableToken, forTarget target: Target, withCompletion completion: @escaping Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType], request: URLRequest) -> (() -> ()) { // swiftlint:disable:this function_parameter_count
return {
if token.cancelled {
self.cancelCompletion(completion, target: target)
return
}
switch endpoint.sampleResponseClosure() {
case .networkResponse(let statusCode, let data):
let response = Moya.Response(statusCode: statusCode, data: data, request: request, response: nil)
plugins.forEach { $0.didReceiveResponse(.success(response), target: target) }
completion(.success(response))
case .networkError(let error):
let error = Moya.Error.underlying(error)
plugins.forEach { $0.didReceiveResponse(.failure(error), target: target) }
completion(.failure(error))
}
}
}
/// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`.
final func notifyPluginsOfImpendingStub(_ request: URLRequest, target: Target) {
let alamoRequest = manager.request(request as URLRequestConvertible)
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
}
}
private extension MoyaProvider {
func sendUploadMultipart(_ target: Target, request: URLRequest, queue: DispatchQueue?, multipartBody: [MultipartFormData], progress: Moya.ProgressBlock? = nil, completion: @escaping Moya.Completion) -> CancellableWrapper {
let cancellable = CancellableWrapper()
let multipartFormData = { (form: RequestMultipartFormData) -> Void in
for bodyPart in multipartBody {
switch bodyPart.provider {
case .data(let data):
self.append(data: data, bodyPart: bodyPart, to: form)
case .file(let url):
self.append(fileURL: url, bodyPart: bodyPart, to: form)
case .stream(let stream, let length):
self.append(stream: stream, length: length, bodyPart: bodyPart, to: form)
}
}
if let parameters = target.parameters {
parameters
.flatMap { (key, value) in multipartQueryComponents(key, value) }
.forEach { (key, value) in
if let data = value.data(using: .utf8, allowLossyConversion: false) {
form.append(data, withName: key)
}
}
}
}
manager.upload(multipartFormData: multipartFormData, with: request) { (result: MultipartFormDataEncodingResult) in
switch result {
case .success(let alamoRequest, _, _):
if cancellable.cancelled {
self.cancelCompletion(completion, target: target)
return
}
cancellable.innerCancellable = self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
case .failure(let error):
completion(.failure(Moya.Error.underlying(error as NSError)))
}
}
return cancellable
}
func sendUploadFile(_ target: Target, request: URLRequest, queue: DispatchQueue?, file: URL, progress: ProgressBlock? = nil, completion: @escaping Completion) -> CancellableToken {
let alamoRequest = manager.upload(file, with: request)
return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
}
func sendDownloadRequest(_ target: Target, request: URLRequest, queue: DispatchQueue?, destination: @escaping DownloadDestination, progress: ProgressBlock? = nil, completion: @escaping Completion) -> CancellableToken {
let alamoRequest = manager.download(request, to: destination)
return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
}
func sendRequest(_ target: Target, request: URLRequest, queue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> CancellableToken {
let alamoRequest = manager.request(request as URLRequestConvertible)
return sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
}
func sendAlamofireRequest<T: Request>(_ alamoRequest: T, target: Target, queue: DispatchQueue?, progress progressCompletion: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> CancellableToken {
// Give plugins the chance to alter the outgoing request
let plugins = self.plugins
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
var progressAlamoRequest = alamoRequest
let progressClosure: (Progress) -> Void = { (progress) in
let sendProgress: () -> () = {
progressCompletion?(ProgressResponse(progress: progress))
}
if let queue = queue {
queue.async(execute: sendProgress)
} else {
sendProgress()
}
}
// Perform the actual request
if let progress = progressCompletion {
switch progressAlamoRequest {
case let downloadRequest as DownloadRequest:
if let downloadRequest = downloadRequest.downloadProgress(closure: progressClosure) as? T {
progressAlamoRequest = downloadRequest
}
case let uploadRequest as UploadRequest:
if let uploadRequest = uploadRequest.uploadProgress(closure: progressClosure) as? T {
progressAlamoRequest = uploadRequest
}
default: break
}
}
if var dataRequest = progressAlamoRequest as? DataRequest {
dataRequest = dataRequest.response(queue: queue, completionHandler: { handler in
let result = convertResponseToResult(handler.response, request: handler.request, data: handler.data, error: handler.error)
// Inform all plugins about the response
plugins.forEach { $0.didReceiveResponse(result, target: target) }
completion(result)
})
if let dataRequest = dataRequest as? T {
progressAlamoRequest = dataRequest
}
}
progressAlamoRequest.resume()
return CancellableToken(request: progressAlamoRequest)
}
}
// MARK: - RequestMultipartFormData appending
private extension MoyaProvider {
func append(data: Data, bodyPart: MultipartFormData, to form: RequestMultipartFormData) {
if let mimeType = bodyPart.mimeType {
if let fileName = bodyPart.fileName {
form.append(data, withName: bodyPart.name, fileName: fileName, mimeType: mimeType)
} else {
form.append(data, withName: bodyPart.name, mimeType: mimeType)
}
} else {
form.append(data, withName: bodyPart.name)
}
}
func append(fileURL url: URL, bodyPart: MultipartFormData, to form: RequestMultipartFormData) {
if let fileName = bodyPart.fileName, let mimeType = bodyPart.mimeType {
form.append(url, withName: bodyPart.name, fileName: fileName, mimeType: mimeType)
} else {
form.append(url, withName: bodyPart.name)
}
}
func append(stream: InputStream, length: UInt64, bodyPart: MultipartFormData, to form: RequestMultipartFormData) {
form.append(stream, withLength: length, name: bodyPart.name, fileName: bodyPart.fileName ?? "", mimeType: bodyPart.mimeType ?? "")
}
}
/// Encode parameters for multipart/form-data
private func multipartQueryComponents(_ key: String, _ value: Any) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: Any] {
for (nestedKey, value) in dictionary {
components += multipartQueryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [Any] {
for value in array {
components += multipartQueryComponents("\(key)[]", value)
}
} else {
components.append((key, "\(value)"))
}
return components
}
| mit | 4be554131bbc199eda03287395c5cfc3 | 46.379433 | 279 | 0.616571 | 5.5532 | false | false | false | false |
stripe/stripe-ios | StripePayments/StripePayments/API Bindings/Models/Shared/STPIntentAction.swift | 1 | 13400 | //
// STPIntentAction.swift
// StripePayments
//
// Created by Yuki Tokuhiro on 6/27/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
//
// STPIntentNextAction.m
// Stripe
//
// Created by Yuki Tokuhiro on 6/27/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
import Foundation
/// Types of next actions for `STPPaymentIntent` and `STPSetupIntent`.
/// You shouldn't need to inspect this yourself; `STPPaymentHandler` will handle any next actions for you.
@objc public enum STPIntentActionType: Int {
/// This is an unknown action that's been added since the SDK
/// was last updated.
/// Update your SDK, or use the `nextAction.allResponseFields`
/// for custom handling.
case unknown
/// The payment intent needs to be authorized by the user. We provide
/// `STPPaymentHandler` to handle the url redirections necessary.
case redirectToURL
/// The payment intent requires additional action handled by `STPPaymentHandler`.
case useStripeSDK
/// The action type is OXXO payment. We provide `STPPaymentHandler` to display
/// the OXXO voucher.
case OXXODisplayDetails
/// Contains instructions for authenticating a payment by redirecting your customer to Alipay App or website.
case alipayHandleRedirect
/// The action type for BLIK payment methods. The customer must authorize the transaction in their banking app within 1 minute.
case BLIKAuthorize
/// Contains instructions for authenticating a payment by redirecting your customer to the WeChat Pay App.
case weChatPayRedirectToApp
/// The action type is Boleto payment. We provide `STPPaymentHandler` to display the Boleto voucher.
case boletoDisplayDetails
/// Contains details describing the microdeposits verification flow for US Bank Account payments
case verifyWithMicrodeposits
/// The action type for UPI payment methods. The customer must complete the transaction in their banking app within 5 minutes.
case upiAwaitNotification
/// Parse the string and return the correct `STPIntentActionType`,
/// or `STPIntentActionTypeUnknown` if it's unrecognized by this version of the SDK.
/// - Parameter string: the NSString with the `next_action.type`
internal init(
string: String
) {
switch string.lowercased() {
case "redirect_to_url":
self = .redirectToURL
case "use_stripe_sdk":
self = .useStripeSDK
case "oxxo_display_details":
self = .OXXODisplayDetails
case "alipay_handle_redirect":
self = .alipayHandleRedirect
case "wechat_pay_redirect_to_ios_app":
self = .weChatPayRedirectToApp
case "boleto_display_details":
self = .boletoDisplayDetails
case "blik_authorize":
self = .BLIKAuthorize
case "verify_with_microdeposits":
self = .verifyWithMicrodeposits
case "upi_await_notification":
self = .upiAwaitNotification
default:
self = .unknown
}
}
/// Return the string representing the provided `STPIntentActionType`.
/// - Parameter actionType: the enum value to convert to a string
/// - Returns: the string, or @"unknown" if this was an unrecognized type
internal var stringValue: String {
switch self {
case .redirectToURL:
return "redirect_to_url"
case .useStripeSDK:
return "use_stripe_sdk"
case .OXXODisplayDetails:
return "oxxo_display_details"
case .alipayHandleRedirect:
return "alipay_handle_redirect"
case .BLIKAuthorize:
return "blik_authorize"
case .weChatPayRedirectToApp:
return "wechat_pay_redirect_to_ios_app"
case .boletoDisplayDetails:
return "boleto_display_details"
case .verifyWithMicrodeposits:
return "verify_with_microdeposits"
case .upiAwaitNotification:
return "upi_await_notification"
case .unknown:
break
}
// catch any unknown values here
return "unknown"
}
}
/// Next action details for `STPPaymentIntent` and `STPSetupIntent`.
/// This is a container for the various types that are available.
/// Check the `type` to see which one it is, and then use the related
/// property for the details necessary to handle it.
/// You cannot directly instantiate an `STPIntentAction`.
public class STPIntentAction: NSObject {
/// The type of action needed. The value of this field determines which
/// property of this object contains further details about the action.
@objc public let type: STPIntentActionType
/// The details for authorizing via URL, when `type == .redirectToURL`
@objc public let redirectToURL: STPIntentActionRedirectToURL?
/// The details for displaying OXXO voucher via URL, when `type == .OXXODisplayDetails`
@objc public let oxxoDisplayDetails: STPIntentActionOXXODisplayDetails?
/// Contains instructions for authenticating a payment by redirecting your customer to Alipay App or website.
@objc public let alipayHandleRedirect: STPIntentActionAlipayHandleRedirect?
/// Contains instructions for authenticating a payment by redirecting your customer to the WeChat Pay app.
@objc public let weChatPayRedirectToApp: STPIntentActionWechatPayRedirectToApp?
/// The details for displaying Boleto voucher via URL, when `type == .boleto`
@objc public let boletoDisplayDetails: STPIntentActionBoletoDisplayDetails?
/// Contains details describing microdeposits verification flow for US bank accounts
@objc public let verifyWithMicrodeposits: STPIntentActionVerifyWithMicrodeposits?
internal let useStripeSDK: STPIntentActionUseStripeSDK?
/// :nodoc:
@objc public let allResponseFields: [AnyHashable: Any]
/// :nodoc:
@objc public override var description: String {
var props = [
// Object
String(format: "%@: %p", NSStringFromClass(STPIntentAction.self), self),
// Type
"type = \(type.stringValue)",
]
// omit properties that don't apply to this type
switch type {
case .redirectToURL:
if let redirectToURL = redirectToURL {
props.append("redirectToURL = \(redirectToURL)")
}
case .useStripeSDK:
if let useStripeSDK = useStripeSDK {
props.append("useStripeSDK = \(useStripeSDK)")
}
case .OXXODisplayDetails:
if let oxxoDisplayDetails = oxxoDisplayDetails {
props.append("oxxoDisplayDetails = \(oxxoDisplayDetails)")
}
case .alipayHandleRedirect:
if let alipayHandleRedirect = alipayHandleRedirect {
props.append("alipayHandleRedirect = \(alipayHandleRedirect)")
}
case .weChatPayRedirectToApp:
if let weChatPayRedirectToApp = weChatPayRedirectToApp {
props.append("weChatPayRedirectToApp = \(weChatPayRedirectToApp)")
}
case .boletoDisplayDetails:
if let boletoDisplayDetails = boletoDisplayDetails {
props.append("boletoDisplayDetails = \(boletoDisplayDetails)")
}
case .BLIKAuthorize:
break // no additional details
case .verifyWithMicrodeposits:
if let verifyWithMicrodeposits = verifyWithMicrodeposits {
props.append("verifyWithMicrodeposits = \(verifyWithMicrodeposits)")
}
case .upiAwaitNotification:
props.append("upiAwaitNotification != nil")
case .unknown:
// unrecognized type, just show the original dictionary for debugging help
props.append("allResponseFields = \(allResponseFields)")
}
return "<\(props.joined(separator: "; "))>"
}
internal init(
type: STPIntentActionType,
redirectToURL: STPIntentActionRedirectToURL?,
alipayHandleRedirect: STPIntentActionAlipayHandleRedirect?,
useStripeSDK: STPIntentActionUseStripeSDK?,
oxxoDisplayDetails: STPIntentActionOXXODisplayDetails?,
weChatPayRedirectToApp: STPIntentActionWechatPayRedirectToApp?,
boletoDisplayDetails: STPIntentActionBoletoDisplayDetails?,
verifyWithMicrodeposits: STPIntentActionVerifyWithMicrodeposits?,
allResponseFields: [AnyHashable: Any]
) {
self.type = type
self.redirectToURL = redirectToURL
self.alipayHandleRedirect = alipayHandleRedirect
self.useStripeSDK = useStripeSDK
self.oxxoDisplayDetails = oxxoDisplayDetails
self.weChatPayRedirectToApp = weChatPayRedirectToApp
self.boletoDisplayDetails = boletoDisplayDetails
self.verifyWithMicrodeposits = verifyWithMicrodeposits
self.allResponseFields = allResponseFields
super.init()
}
}
// MARK: - STPAPIResponseDecodable
extension STPIntentAction: STPAPIResponseDecodable {
@objc
public class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? {
guard let dict = response,
let rawType = dict["type"] as? String
else {
return nil
}
// Only set the type to a recognized value if we *also* have the expected sub-details.
// ex: If the server said it was `.redirectToURL`, but decoding the
// STPIntentActionRedirectToURL object fails, map type to `.unknown`
var type = STPIntentActionType(string: rawType)
var redirectToURL: STPIntentActionRedirectToURL?
var alipayHandleRedirect: STPIntentActionAlipayHandleRedirect?
var useStripeSDK: STPIntentActionUseStripeSDK?
var oxxoDisplayDetails: STPIntentActionOXXODisplayDetails?
var boletoDisplayDetails: STPIntentActionBoletoDisplayDetails?
var weChatPayRedirectToApp: STPIntentActionWechatPayRedirectToApp?
var verifyWithMicrodeposits: STPIntentActionVerifyWithMicrodeposits?
switch type {
case .unknown:
break
case .redirectToURL:
redirectToURL = STPIntentActionRedirectToURL.decodedObject(
fromAPIResponse: dict["redirect_to_url"] as? [AnyHashable: Any]
)
if redirectToURL == nil {
type = .unknown
}
case .useStripeSDK:
useStripeSDK = STPIntentActionUseStripeSDK.decodedObject(
fromAPIResponse: dict["use_stripe_sdk"] as? [AnyHashable: Any]
)
if useStripeSDK == nil {
type = .unknown
}
case .OXXODisplayDetails:
oxxoDisplayDetails = STPIntentActionOXXODisplayDetails.decodedObject(
fromAPIResponse: dict["oxxo_display_details"] as? [AnyHashable: Any]
)
if oxxoDisplayDetails == nil {
type = .unknown
}
case .alipayHandleRedirect:
alipayHandleRedirect = STPIntentActionAlipayHandleRedirect.decodedObject(
fromAPIResponse: dict["alipay_handle_redirect"] as? [AnyHashable: Any]
)
if alipayHandleRedirect == nil {
type = .unknown
}
case .weChatPayRedirectToApp:
weChatPayRedirectToApp = STPIntentActionWechatPayRedirectToApp.decodedObject(
fromAPIResponse: dict["wechat_pay_redirect_to_ios_app"] as? [AnyHashable: Any]
)
if weChatPayRedirectToApp == nil {
type = .unknown
}
case .boletoDisplayDetails:
boletoDisplayDetails = STPIntentActionBoletoDisplayDetails.decodedObject(
fromAPIResponse: dict["boleto_display_details"] as? [AnyHashable: Any]
)
if boletoDisplayDetails == nil {
type = .unknown
}
case .BLIKAuthorize:
break // no additional details
case .verifyWithMicrodeposits:
verifyWithMicrodeposits = STPIntentActionVerifyWithMicrodeposits.decodedObject(
fromAPIResponse: dict["verify_with_microdeposits"] as? [AnyHashable: Any]
)
if verifyWithMicrodeposits == nil {
type = .unknown
}
case .upiAwaitNotification:
break // no additional details
}
return STPIntentAction(
type: type,
redirectToURL: redirectToURL,
alipayHandleRedirect: alipayHandleRedirect,
useStripeSDK: useStripeSDK,
oxxoDisplayDetails: oxxoDisplayDetails,
weChatPayRedirectToApp: weChatPayRedirectToApp,
boletoDisplayDetails: boletoDisplayDetails,
verifyWithMicrodeposits: verifyWithMicrodeposits,
allResponseFields: dict
) as? Self
}
}
// MARK: - Deprecated
extension STPIntentAction {
/// The details for authorizing via URL, when `type == STPIntentActionTypeRedirectToURL`
/// @deprecated Use `redirectToURL` instead.
@available(*, deprecated, message: "Use `redirectToURL` instead.", renamed: "redirectToURL")
@objc public var authorizeWithURL: STPIntentActionRedirectToURL? {
return redirectToURL
}
}
| mit | 17888d746fd8d61d945d86cbd186caaf | 39.234234 | 131 | 0.659501 | 4.653699 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/Internal/API Bindings/Link/STPAPIClient+Link.swift | 1 | 15773 | //
// STPAPIClient+Link.swift
// StripePaymentSheet
//
// Created by Cameron Sabol on 4/21/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
@_spi(STP) import StripePayments
@_spi(STP) import StripePaymentsUI
extension STPAPIClient {
func lookupConsumerSession(
for email: String?,
cookieStore: LinkCookieStore,
completion: @escaping (Result<ConsumerSession.LookupResponse, Error>) -> Void
) {
let endpoint: String = "consumers/sessions/lookup"
var parameters: [String: Any] = [
"request_surface": "ios_payment_element",
]
if let email = email {
parameters["email_address"] = email.lowercased()
}
let cookies = cookieStore.formattedSessionCookies()
if let cookies = cookies {
parameters["cookies"] = cookies
}
guard parameters.keys.contains("email_address") || parameters.keys.contains("cookies") else {
// no request to make if we don't have an email or cookies
DispatchQueue.main.async {
completion(.success(
ConsumerSession.LookupResponse(.noAvailableLookupParams, allResponseFields: [:])
))
}
return
}
APIRequest<ConsumerSession.LookupResponse>.post(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: publishableKey),
parameters: parameters
) { result in
if case let .success(lookupResponse) = result {
switch lookupResponse.responseType {
case .found(let consumerSession, _):
consumerSession.updateCookie(withStore: cookieStore)
case .notFound(_) where cookies != nil:
// Delete invalid cookie, if any
cookieStore.delete(key: .session)
default:
break
}
}
completion(result)
}
}
func createConsumer(
for email: String,
with phoneNumber: String,
locale: Locale,
legalName: String?,
countryCode: String?,
consentAction: String?,
cookieStore: LinkCookieStore,
completion: @escaping (Result<ConsumerSession.SignupResponse, Error>) -> Void
) {
let endpoint: String = "consumers/accounts/sign_up"
var parameters: [String: Any] = [
"request_surface": "ios_payment_element",
"email_address": email.lowercased(),
"phone_number": phoneNumber,
"locale": locale.toLanguageTag()
]
if let legalName = legalName {
parameters["legal_name"] = legalName
}
if let countryCode = countryCode {
parameters["country"] = countryCode
}
if let cookies = cookieStore.formattedSessionCookies() {
parameters["cookies"] = cookies
}
if let consentAction = consentAction {
parameters["consent_action"] = consentAction
}
APIRequest<ConsumerSession.SignupResponse>.post(
with: self,
endpoint: endpoint,
parameters: parameters
) { result in
if case .success(let signupResponse) = result {
signupResponse.consumerSession.updateCookie(withStore: cookieStore)
}
completion(result)
}
}
func createPaymentDetails(
for consumerSessionClientSecret: String,
cardParams: STPPaymentMethodCardParams,
billingEmailAddress: String,
billingDetails: STPPaymentMethodBillingDetails,
consumerAccountPublishableKey: String?,
completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void
) {
let endpoint: String = "consumers/payment_details"
let billingParams = billingDetails.consumersAPIParams
var card = STPFormEncoder.dictionary(forObject: cardParams)["card"] as? [AnyHashable: Any]
card?["cvc"] = nil // payment_details doesn't store cvc
let parameters: [String: Any] = [
"credentials": ["consumer_session_client_secret": consumerSessionClientSecret],
"request_surface": "ios_payment_element",
"type": "card",
"card": card as Any,
"billing_email_address": billingEmailAddress,
"billing_address": billingParams,
"active": false, // card details are created with active false so we don't save them until the intent confirmation succeeds
]
APIRequest<ConsumerPaymentDetails>.post(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: consumerAccountPublishableKey),
parameters: parameters,
completion: completion
)
}
func createPaymentDetails(
for consumerSessionClientSecret: String,
linkedAccountId: String,
consumerAccountPublishableKey: String?,
completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void
) {
let endpoint: String = "consumers/payment_details"
let parameters: [String: Any] = [
"credentials": ["consumer_session_client_secret": consumerSessionClientSecret],
"request_surface": "ios_payment_element",
"bank_account": [
"account": linkedAccountId,
],
"type": "bank_account",
"is_default": true
]
APIRequest<ConsumerPaymentDetails>.post(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: consumerAccountPublishableKey),
parameters: parameters,
completion: completion
)
}
func startVerification(
for consumerSessionClientSecret: String,
type: ConsumerSession.VerificationSession.SessionType,
locale: Locale,
cookieStore: LinkCookieStore,
consumerAccountPublishableKey: String?,
completion: @escaping (Result<ConsumerSession, Error>) -> Void
) {
let typeString: String = {
switch type {
case .sms:
return "SMS"
case .unknown, .signup, .email:
assertionFailure("We don't support any verification except sms")
return ""
}
}()
let endpoint: String = "consumers/sessions/start_verification"
var parameters: [String: Any] = [
"credentials": ["consumer_session_client_secret": consumerSessionClientSecret],
"type": typeString,
"locale": locale.toLanguageTag()
]
if let cookies = cookieStore.formattedSessionCookies() {
parameters["cookies"] = cookies
}
APIRequest<ConsumerSession>.post(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: consumerAccountPublishableKey),
parameters: parameters
) { result in
if case .success(let consumerSession) = result {
consumerSession.updateCookie(withStore: cookieStore)
}
completion(result)
}
}
func confirmSMSVerification(
for consumerSessionClientSecret: String,
with code: String,
cookieStore: LinkCookieStore,
consumerAccountPublishableKey: String?,
completion: @escaping (Result<ConsumerSession, Error>) -> Void
) {
let endpoint: String = "consumers/sessions/confirm_verification"
var parameters: [String: Any] = [
"credentials": ["consumer_session_client_secret": consumerSessionClientSecret],
"type": "SMS",
"code": code,
"request_surface": "ios_payment_element",
]
if let cookies = cookieStore.formattedSessionCookies() {
parameters["cookies"] = cookies
}
APIRequest<ConsumerSession>.post(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: consumerAccountPublishableKey),
parameters: parameters
) { result in
if case .success(let consumerSession) = result {
consumerSession.updateCookie(withStore: cookieStore)
}
completion(result)
}
}
func createLinkAccountSession(
for consumerSessionClientSecret: String,
consumerAccountPublishableKey: String?,
completion: @escaping (Result<LinkAccountSession, Error>) -> Void
) {
let endpoint: String = "consumers/link_account_sessions"
let parameters: [String: Any] = [
"credentials": [
"consumer_session_client_secret": consumerSessionClientSecret
],
"request_surface": "ios_payment_element",
]
APIRequest<LinkAccountSession>.post(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: consumerAccountPublishableKey),
parameters: parameters,
completion: completion
)
}
func listPaymentDetails(
for consumerSessionClientSecret: String,
consumerAccountPublishableKey: String?,
completion: @escaping (Result<[ConsumerPaymentDetails], Error>) -> Void
) {
let endpoint: String = "consumers/payment_details/list"
let parameters: [String: Any] = [
"credentials": ["consumer_session_client_secret": consumerSessionClientSecret],
"request_surface": "ios_payment_element",
"types": ["card", "bank_account"]
]
APIRequest<ConsumerPaymentDetails.ListDeserializer>.post(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: consumerAccountPublishableKey),
parameters: parameters
) { result in
completion(result.map { $0.paymentDetails })
}
}
func deletePaymentDetails(
for consumerSessionClientSecret: String,
id: String,
consumerAccountPublishableKey: String?,
completion: @escaping (Result<Void, Error>) -> Void
) {
let endpoint: String = "consumers/payment_details/\(id)"
let parameters: [String: Any] = [
"credentials": ["consumer_session_client_secret": consumerSessionClientSecret],
"request_surface": "ios_payment_element",
]
APIRequest<STPEmptyStripeResponse>.delete(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: consumerAccountPublishableKey),
parameters: parameters
) { result in
completion(result.map { _ in () } )
}
}
func updatePaymentDetails(
for consumerSessionClientSecret: String,
id: String,
updateParams: UpdatePaymentDetailsParams,
consumerAccountPublishableKey: String?,
completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void
) {
let endpoint: String = "consumers/payment_details/\(id)"
var parameters: [String: Any] = [
"credentials": ["consumer_session_client_secret": consumerSessionClientSecret],
"request_surface": "ios_payment_element",
]
if let details = updateParams.details, case .card(let expiryDate, let billingDetails) = details {
parameters["exp_month"] = expiryDate.month
parameters["exp_year"] = expiryDate.year
if let billingDetails = billingDetails {
parameters["billing_address"] = billingDetails.consumersAPIParams
}
}
if let isDefault = updateParams.isDefault {
parameters["is_default"] = isDefault
}
APIRequest<ConsumerPaymentDetails>.post(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: consumerAccountPublishableKey),
parameters: parameters,
completion: completion
)
}
func logout(
consumerSessionClientSecret: String,
cookieStore: LinkCookieStore,
consumerAccountPublishableKey: String?,
completion: @escaping (Result<ConsumerSession, Error>) -> Void
) {
let endpoint: String = "consumers/sessions/log_out"
var parameters: [String: Any] = [
"credentials": [
"consumer_session_client_secret": consumerSessionClientSecret
],
"request_surface": "ios_payment_element",
]
if let cookies = cookieStore.formattedSessionCookies() {
parameters["cookies"] = cookies
}
APIRequest<ConsumerSession>.post(
with: self,
endpoint: endpoint,
additionalHeaders: authorizationHeader(using: consumerAccountPublishableKey),
parameters: parameters
) { result in
if case .success(let consumerSession) = result {
consumerSession.updateCookie(withStore: cookieStore)
}
completion(result)
}
}
}
// TODO(ramont): Remove this after switching to modern bindings.
private extension APIRequest {
class func post(
with apiClient: STPAPIClient,
endpoint: String,
additionalHeaders: [String: String] = [:],
parameters: [String: Any],
completion: @escaping (Result<ResponseType, Error>) -> Void
) {
post(
with: apiClient,
endpoint: endpoint,
additionalHeaders: additionalHeaders,
parameters: parameters
) { (responseObject, _, error) in
if let responseObject = responseObject {
completion(.success(responseObject))
} else {
completion(.failure(
error ?? NSError.stp_genericFailedToParseResponseError()
))
}
}
}
class func delete(
with apiClient: STPAPIClient,
endpoint: String,
additionalHeaders: [String: String] = [:],
parameters: [String: Any],
completion: @escaping (Result<ResponseType, Error>) -> Void
) {
delete(
with: apiClient,
endpoint: endpoint,
additionalHeaders: additionalHeaders,
parameters: parameters
) { (responseObject, _, error) in
if let responseObject = responseObject {
completion(.success(responseObject))
} else {
completion(.failure(
error ?? NSError.stp_genericFailedToParseResponseError()
))
}
}
}
}
// MARK: - /v1/consumers Support
extension STPPaymentMethodBillingDetails {
var consumersAPIParams: [String: Any] {
var params = STPFormEncoder.dictionary(forObject: self)
if let addressParams = address?.consumersAPIParams {
params["address"] = nil
params.merge(addressParams) { (_, new) in new }
}
return params
}
}
// MARK: - /v1/consumers Support
extension STPPaymentMethodAddress {
var consumersAPIParams: [String: Any] {
var params = STPFormEncoder.dictionary(forObject: self)
params["country_code"] = params["country"]
params["country"] = nil
return params
}
}
| mit | 0f843c88aec8088ae2d163ef042ca806 | 32.628998 | 135 | 0.588321 | 5.448014 | false | false | false | false |
GeekYong/JYMagicMove | JYMagicMove/JYMagicMove/JYMagicPopTransion.swift | 1 | 2042 | //
// JYMagicPopTransion.swift
// JYMagicMove
//
// Created by 杨勇 on 16/8/16.
// Copyright © 2016年 JackYang. All rights reserved.
//
import UIKit
class JYMagicPopTransion: NSObject ,UIViewControllerAnimatedTransitioning{
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//拿到 fromVC 和 toVC 以及 容器
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! JYDetailController
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ViewController
let container = transitionContext.containerView()
//拿到快照
let snapshotView = fromVC.avaterImageView.snapshotViewAfterScreenUpdates(false)
snapshotView.frame = container!.convertRect(fromVC.avaterImageView.frame, fromView: fromVC.avaterImageView.superview)
fromVC.avaterImageView.hidden = true
toVC.view.frame = transitionContext.finalFrameForViewController(toVC)
toVC.selectCell.imageView.hidden = true
container?.insertSubview(toVC.view, belowSubview: fromVC.view)
container?.addSubview(snapshotView)
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
() -> Void in
snapshotView.frame = container!.convertRect(toVC.selectCell.imageView.frame, fromView: toVC.selectCell.imageView.superview)
fromVC.view.alpha = 0
}) { (finish: Bool) -> Void in
toVC.selectCell.imageView.hidden = false
snapshotView.removeFromSuperview()
fromVC.avaterImageView.hidden = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
}
| mit | c4fb0eed3d65f7c9be530963d414db68 | 40.9375 | 146 | 0.705912 | 5.751429 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/TXTReader/Reader/View/ZSChapterPayView.swift | 1 | 2718 | //
// ZSChapterPayView.swift
// zhuishushenqi
//
// Created by caony on 2019/2/15.
// Copyright © 2019年 QS. All rights reserved.
//
import Foundation
class ZSChapterPayView: UIView {
var titleLabel:UILabel!
var tipLabel:UILabel!
var payButton:UIButton!
var leftLineView:UIView!
var rightLineView:UIView!
override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupSubviews() {
titleLabel = UILabel(frame: CGRect.zero)
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 17)
titleLabel.textColor = UIColor.gray
addSubview(titleLabel)
tipLabel = UILabel(frame: CGRect.zero)
tipLabel.textAlignment = .center
tipLabel.font = UIFont.systemFont(ofSize: 13)
tipLabel.text = "* 本章需购买后阅读 *"
tipLabel.textColor = UIColor.gray
addSubview(tipLabel)
payButton = UIButton(type: .custom)
payButton.setTitle("购买章节", for: .normal)
payButton.setTitleColor(UIColor.gray, for: .normal)
payButton.layer.cornerRadius = 5
payButton.layer.borderWidth = 1
payButton.layer.borderColor = UIColor.gray.cgColor
addSubview(payButton)
leftLineView = UIView(frame: CGRect.zero)
leftLineView.backgroundColor = UIColor.gray
addSubview(leftLineView)
rightLineView = UIView(frame: CGRect.zero)
rightLineView.backgroundColor = UIColor.gray
addSubview(rightLineView)
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = CGRect(x: 20, y: 200, width: bounds.width - 40, height: 60)
tipLabel.frame = CGRect(x: 0, y: 0, width: 130, height: 15)
tipLabel.center = CGPoint(x: bounds.width/2, y: bounds.height/2)
leftLineView.frame = CGRect(x: 0, y: 0, width: bounds.width/2 - tipLabel.bounds.width/2, height: 1)
leftLineView.center = CGPoint(x: bounds.width/4 - tipLabel.bounds.width/4, y: tipLabel.centerY)
rightLineView.frame = CGRect(x: bounds.width/2 + tipLabel.bounds.width/2, y: tipLabel.centerY, width: bounds.width/2 - tipLabel.bounds.width/2, height: 1)
// rightLineView.center = CGPoint(x:bounds.width + tipLabel.bounds.width + bounds.width/4 - tipLabel.bounds.width/4, y: tipLabel.centerY)
payButton.frame = CGRect(x: 0, y: 0, width: 200, height: 40)
payButton.center = CGPoint(x: bounds.width/2, y: tipLabel.frame.maxY + 60)
}
}
| mit | e6ee950260c80d8bedd5af27556ceb33 | 36.375 | 162 | 0.648086 | 4.028443 | false | false | false | false |
mono0926/firebase-verifier | Sources/Verifier.swift | 1 | 2074 | import Foundation
import JWT
public protocol Verifier {
func verify(token: String, allowExpired: Bool) throws -> User
}
extension Verifier {
public func verify(token: String) throws -> User {
return try verify(token: token, allowExpired: false)
}
}
public struct JWTVerifier: Verifier {
public let projectId: String
public let publicCertificateFetcher: PublicCertificateFetcher
public init(projectId: String, publicCertificateFetcher: PublicCertificateFetcher = GooglePublicCertificateFetcher()) throws {
if projectId.isEmpty {
throw VerificationError(type: .emptyProjectId, message: nil)
}
self.projectId = projectId
self.publicCertificateFetcher = publicCertificateFetcher
}
public func verify(token: String, allowExpired: Bool = false) throws -> User {
let jwt = try JWT(token: token)
assert(jwt.subject == jwt.userId)
if !allowExpired {
try jwt.verifyExpirationTime()
}
try jwt.verifyAlgorithm()
try jwt.verifyAudience(with: projectId)
try jwt.verifyIssuer(with: projectId)
guard let keyIdentifier = jwt.keyIdentifier else {
throw VerificationError(type: .notFound(key: "kid"), message: "Firebase ID token has no 'kid' claim.")
}
guard let subject = jwt.subject else {
let message = "Firebase ID token has no 'sub' (subject) claim. \(verifyIdTokenDocsMessage)"
throw VerificationError(type: .notFound(key: "sub"), message: message)
}
guard subject.characters.count <= 128 else {
let message = "Firebase ID token has 'sub' (subject) claim longer than 128 characters. \(verifyIdTokenDocsMessage)"
throw VerificationError(type: .incorrect(key: "sub"), message: message)
}
let cert = try publicCertificateFetcher.fetch(with: keyIdentifier).makeBytes().base64Decoded
let signer = try RS256(x509Cert: cert)
try jwt.verifySignature(using: signer)
return User(jwt: jwt)
}
}
| mit | 95edeca30e8481283672fc9ebb1246de | 37.407407 | 130 | 0.667792 | 4.528384 | false | false | false | false |
manavgabhawala/swift | test/Serialization/noinline.swift | 1 | 1430 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-module -sil-serialize-all -o %t %S/Inputs/def_noinline.swift
// RUN: llvm-bcanalyzer %t/def_noinline.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -sil-link-all -I %t %s | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: UnknownCode
import def_noinline
// SIL-LABEL: sil @main
// SIL: [[RAW:%.+]] = global_addr @_T08noinline3rawSbv : $*Bool
// SIL: [[FUNC:%.+]] = function_ref @_T012def_noinline12testNoinlineS2b1x_tF : $@convention(thin) (Bool) -> Bool
// SIL: [[RESULT:%.+]] = apply [[FUNC]]({{%.+}}) : $@convention(thin) (Bool) -> Bool
// SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Bool
var raw = testNoinline(x: false)
// SIL: [[FUNC2:%.+]] = function_ref @_T012def_noinline18NoInlineInitStructVACSb1x_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct
// SIL: apply [[FUNC2]]({{%.+}}, {{%.+}}) : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct
var a = NoInlineInitStruct(x: false)
// SIL-LABEL: [fragile] [noinline] @_T012def_noinline12testNoinlineS2b1x_tF : $@convention(thin) (Bool) -> Bool
// SIL-LABEL: sil public_external [fragile] [noinline] @_T012def_noinline18NoInlineInitStructVACSb1x_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct {
| apache-2.0 | 02d84928f6ba16dc3579f2b629aacd2b | 56.2 | 190 | 0.686014 | 3.25 | false | true | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Scenes/Animate 3D graphic/PlaneStatsViewController.swift | 1 | 2537 | //
// Copyright 2017 Esri.
//
// 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 UIKit
class PlaneStatsViewController: UITableViewController {
var frame: Frame? {
didSet {
updateUI()
}
}
let measurementFormatter: MeasurementFormatter = {
let formatter = MeasurementFormatter()
formatter.numberFormatter.maximumFractionDigits = 0
formatter.unitOptions = .providedUnit
return formatter
}()
@IBOutlet private var altitudeLabel: UILabel!
@IBOutlet private var headingLabel: UILabel!
@IBOutlet private var pitchLabel: UILabel!
@IBOutlet private var rollLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
private var tableViewContentSizeObservation: NSKeyValueObservation?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableViewContentSizeObservation = tableView.observe(\.contentSize) { [unowned self] (tableView, _) in
self.preferredContentSize = CGSize(width: self.preferredContentSize.width, height: tableView.contentSize.height)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
tableViewContentSizeObservation = nil
}
func updateUI() {
guard isViewLoaded else { return }
if let frame = frame {
measurementFormatter.unitStyle = .medium
altitudeLabel.text = measurementFormatter.string(from: frame.altitude)
measurementFormatter.unitStyle = .short
headingLabel.text = measurementFormatter.string(from: frame.heading)
pitchLabel.text = measurementFormatter.string(from: frame.pitch)
rollLabel.text = measurementFormatter.string(from: frame.roll)
} else {
altitudeLabel.text = ""
headingLabel.text = ""
pitchLabel.text = ""
rollLabel.text = ""
}
}
}
| apache-2.0 | a0a6055745907f405d63a3af1aea5753 | 34.732394 | 124 | 0.669689 | 5.104628 | false | false | false | false |
tardieu/swift | test/expr/unary/selector/property.swift | 6 | 10418 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -disable-objc-attr-requires-foundation-module -typecheck -primary-file %s %S/Inputs/property_helper.swift -verify -swift-version 4
import ObjectiveC
// REQUIRES: objc_interop
@objc class HelperClass: NSObject {}
struct Wrapper {
var objcInstance = ObjCClass()
}
class ObjCClass {
@objc var myProperty = HelperClass()
@objc let myConstant = HelperClass() // expected-note 4{{'myConstant' declared here}}
@objc var myComputedReadOnlyProperty: HelperClass { // expected-note 2{{'myComputedReadOnlyProperty' declared here}}
get {
return HelperClass()
}
}
@objc var myComputedReadWriteProperty: HelperClass {
get {
return HelperClass()
}
set {
}
}
@objc func myFunc() {}
@objc class func myClassFunc() {}
func instanceMethod() {
let _ = #selector(myFunc)
let _ = #selector(getter: myProperty)
let _ = #selector(setter: myProperty)
let _ = #selector(setter: myComputedReadWriteProperty)
let _ = #selector(setter: myConstant) // expected-error {{argument of '#selector(setter:)' refers to non-settable let 'myConstant'}}
let _ = #selector(setter: myComputedReadOnlyProperty) // expected-error {{argument of '#selector(setter:)' refers to non-settable var 'myComputedReadOnlyProperty'}}
let _ = #selector(myClassFunc) // expected-error{{static member 'myClassFunc' cannot be used on instance of type 'ObjCClass'}}
}
class func classMethod() {
let _ = #selector(myFunc)
let _ = #selector(getter: myProperty)
let _ = #selector(setter: myProperty)
let _ = #selector(setter: myComputedReadWriteProperty)
let _ = #selector(setter: myConstant) // expected-error {{argument of '#selector(setter:)' refers to non-settable let 'myConstant'}}
let _ = #selector(setter: myComputedReadOnlyProperty) // expected-error {{argument of '#selector(setter:)' refers to non-settable var 'myComputedReadOnlyProperty'}}
let _ = #selector(myClassFunc)
}
}
let myObjcInstance = ObjCClass()
let myWrapperInstance = Wrapper()
func testSimple(myObjcInstance: ObjCClass, myWrapperInstance: Wrapper) {
// Check cases that should work
let _ = #selector(ObjCClass.myFunc)
let _ = #selector(getter: ObjCClass.myProperty)
let _ = #selector(setter: ObjCClass.myProperty)
let _ = #selector(myObjcInstance.myFunc)
let _ = #selector(getter: myObjcInstance.myProperty)
let _ = #selector(setter: myObjcInstance.myProperty)
let _ = #selector(myWrapperInstance.objcInstance.myFunc)
let _ = #selector(getter: myWrapperInstance.objcInstance.myProperty)
let _ = #selector(setter: myWrapperInstance.objcInstance.myProperty)
}
func testWrongKind(myObjcInstance: ObjCClass, myWrapperInstance: Wrapper) {
// Referring to a property with a method selector or a method with a
// property selector
let _ = #selector(myObjcInstance.myProperty) // expected-error{{use 'getter:' or 'setter:' to refer to the Objective-C getter or setter of property 'myProperty', respectively}}
// expected-note@-1{{add 'getter:' to reference the Objective-C getter for 'myProperty'}}{{21-21=getter: }}
// expected-note@-2{{add 'setter:' to reference the Objective-C setter for 'myProperty'}}{{21-21=setter: }}
let _ = #selector(myObjcInstance.myComputedReadOnlyProperty) // expected-error{{use 'getter:' to refer to the Objective-C getter of property 'myComputedReadOnlyProperty'}}{{21-21=getter: }}
let _ = #selector(ObjCClass.myProperty) // expected-error{{use 'getter:' or 'setter:' to refer to the Objective-C getter or setter of property 'myProperty', respectively}}
// expected-note@-1{{add 'setter:' to reference the Objective-C setter for 'myProperty'}}{{21-21=setter: }}
// expected-note@-2{{add 'getter:' to reference the Objective-C getter for 'myProperty'}}{{21-21=getter: }}
// Referring to a method with a property selector
let _ = #selector(getter: myObjcInstance.myFunc) // expected-error{{cannot reference instance method 'myFunc()' as a property; remove 'getter:'}} {{21-29=}}
let _ = #selector(setter: myObjcInstance.myFunc) // expected-error{{cannot reference instance method 'myFunc()' as a property; remove 'setter:'}} {{21-29=}}
let _ = #selector(getter: ObjCClass.myFunc) // expected-error{{cannot reference instance method 'myFunc()' as a property; remove 'getter:'}} {{21-29=}}
let _ = #selector(setter: ObjCClass.myFunc) // expected-error{{cannot reference instance method 'myFunc()' as a property; remove 'setter:'}} {{21-29=}}
// Referring to a let property with a setter
let _ = #selector(setter: myObjcInstance.myConstant) // expected-error {{argument of '#selector(setter:)' refers to non-settable let 'myConstant'}}
let _ = #selector(setter: ObjCClass.myConstant) // expected-error {{argument of '#selector(setter:)' refers to non-settable let 'myConstant'}}
}
// Referring to non ObjC members
class NonObjCClass {
var nonObjCPropertyForGetter = HelperClass() // expected-note{{add '@objc' to expose this var to Objective-C}} {{3-3=@objc }}
var nonObjCPropertyForSetter = HelperClass() // expected-note{{add '@objc' to expose this var to Objective-C}} {{3-3=@objc }}
}
func testNonObjCMembers(nonObjCInstance: NonObjCClass) {
let _ = #selector(getter: nonObjCInstance.nonObjCPropertyForGetter) // expected-error{{argument of '#selector' refers to var 'nonObjCPropertyForGetter' that is not exposed to Objective-C}}
let _ = #selector(setter: nonObjCInstance.nonObjCPropertyForSetter) // expected-error{{argument of '#selector' refers to var 'nonObjCPropertyForSetter' that is not exposed to Objective-C}}
// Referencing undefined symbols
let _ = #selector(getter: UndefinedClass.myVariable) // expected-error{{use of unresolved identifier 'UndefinedClass'}}
let _ = #selector(getter: ObjCClass.undefinedProperty) // expected-error{{type 'ObjCClass' has no member 'undefinedProperty'}}
let _ = #selector(getter: myObjcInstance.undefinedProperty) // expected-error{{value of type 'ObjCClass' has no member 'undefinedProperty'}}
}
// Ambiguous expressions
func testAmbiguous(myObjcInstance: ObjCClass) { // expected-note{{'myObjcInstance' declared here}}
// Referring to a properties not within a type.
let myOtherObjcInstance = ObjCClass(); // expected-note{{'myOtherObjcInstance' declared here}}
let _ = #selector(getter: myObjcInstance) // expected-error{{argument of '#selector' cannot refer to parameter 'myObjcInstance'}}
let _ = #selector(getter: myOtherObjcInstance) // expected-error{{argument of '#selector' cannot refer to variable 'myOtherObjcInstance'}}
}
// Getter/setter is no keyword
let getter = HelperClass()
let setter = HelperClass()
// Referencing methods named getter and setter
class ObjCClassWithGetterSetter: NSObject {
@objc func getter() {
}
@objc func setter() {
}
func referenceGetterSetter() {
let _ = #selector(getter)
let _ = #selector(setter)
}
}
// Looking up inherited members
class BaseClass: NSObject {
var myVar = 1
func myFunc() {
}
}
class SubClass: BaseClass {
}
func testInherited() {
let _ = #selector(getter: SubClass.myVar)
let _ = #selector(SubClass.myFunc)
let subInstance = SubClass()
let _ = #selector(getter: subInstance.myVar)
let _ = #selector(subInstance.myFunc)
}
// Looking up instance/static methods on instance/static contexts
class InstanceStaticTestClass {
@objc static let staticProperty = HelperClass()
@objc let instanceProperty = HelperClass()
@objc class func classMethod() {}
@objc static func staticMethod() {}
@objc func instanceMethod() {}
@objc func instanceAndStaticMethod() {}
@objc class func instanceAndStaticMethod() {}
class func testClass() {
let _ = #selector(getter: instanceProperty)
let _ = #selector(instanceMethod)
let _ = #selector(classMethod)
let _ = #selector(staticMethod)
let _ = #selector(getter: staticProperty)
let _ = #selector(instanceAndStaticMethod)
}
static func testStatic() {
let _ = #selector(getter: instanceProperty)
let _ = #selector(getter: staticProperty)
let _ = #selector(instanceMethod)
let _ = #selector(classMethod)
let _ = #selector(staticMethod)
let _ = #selector(instanceAndStaticMethod)
}
func testInstance() {
let _ = #selector(getter: instanceProperty)
let _ = #selector(instanceMethod)
let _ = #selector(getter: staticProperty) // expected-error{{static member 'staticProperty' cannot be used on instance of type 'InstanceStaticTestClass'}}
let _ = #selector(classMethod) // expected-error{{static member 'classMethod' cannot be used on instance of type 'InstanceStaticTestClass'}}
let _ = #selector(staticMethod) // expected-error{{static member 'staticMethod' cannot be used on instance of type 'InstanceStaticTestClass'}}
let _ = #selector(instanceAndStaticMethod)
}
}
// Accessibility
let otherObjCInstance = OtherObjCClass()
let v11 = #selector(getter: OtherObjCClass.privateVar) // expected-error{{'privateVar' is inaccessible due to 'private' protection level}}
let v12 = #selector(setter: OtherObjCClass.privateVar) // expected-error{{'privateVar' is inaccessible due to 'private' protection level}}
let v13 = #selector(getter: otherObjCInstance.privateVar) // expected-error{{}}
let v14 = #selector(setter: otherObjCInstance.privateVar) // expected-error{{privateVar' is inaccessible due to 'private' protection level}}
let v21 = #selector(getter: OtherObjCClass.privateSetVar)
let v22 = #selector(setter: OtherObjCClass.privateSetVar) // expected-error{{setter of var 'privateSetVar' is inaccessible}}
let v23 = #selector(getter: otherObjCInstance.privateSetVar)
let v24 = #selector(setter: otherObjCInstance.privateSetVar) // expected-error{{setter of var 'privateSetVar' is inaccessible}}
let v31 = #selector(getter: OtherObjCClass.internalVar)
let v32 = #selector(setter: OtherObjCClass.internalVar)
let v33 = #selector(getter: otherObjCInstance.internalVar)
let v34 = #selector(setter: otherObjCInstance.internalVar)
let v41 = #selector(OtherObjCClass.internalFunc)
let v42 = #selector(otherObjCInstance.internalFunc)
let v51 = #selector(OtherObjCClass.privateFunc) // expected-error{{'privateFunc' is inaccessible due to 'private' protection level}}
let v52 = #selector(otherObjCInstance.privateFunc) // expected-error{{'privateFunc' is inaccessible due to 'private' protection level}}
| apache-2.0 | ab38c02c56cbde47d26017cc3e563845 | 42.957806 | 192 | 0.728355 | 4.008465 | false | true | false | false |
Solar1011/- | 我的微博/我的微博/Classes/Module/NewFeature/NewFeatureViewController.swift | 1 | 5753 | //
// NewFeatureViewController.swift
// 我的微博
//
// Created by teacher on 15/7/30.
// Copyright © 2015年 itheima. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class NewFeatureViewController: UICollectionViewController {
/// 图像总数
private let imageCount = 4
/// 布局属性
private let layout = HMFlowLayout()
// 没有 override,因为 collectionView 的指定的构造函数是带 layout 的
init() {
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
// 本类禁止用 sb 开发 - 纯代码开发,考虑因素少,风险小
// fatalError("init(coder:) has not been implemented")
// 本类允许用 sb 开发,有些公司是混合开发!需要考虑的因素多,都需要测试才行!
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
// MARK: UICollectionViewDataSource
// 1. 获取数据源,确认有 cell
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageCount
}
// 3. 获取每个索引对应的cell
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
// Configure the cell
cell.imageIndex = indexPath.item
return cell
}
/// 完成显示 cell - indexPath 是之前消失 cell 的 indexPath
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
// 获取当前显示的 indexPath
let path = collectionView.indexPathsForVisibleItems().last!
// 判断是否是末尾的 indexPath
if path.item == imageCount - 1 {
// 播放动画
let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
cell.startButtonAnim()
}
}
}
/// 新特性的 cell
class NewFeatureCell: UICollectionViewCell {
/// 图像索引 - 私有属性,在同一个文件中,是允许访问的!
private var imageIndex: Int = 0 {
didSet {
iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
startButton.hidden = true
}
}
/// 开始体验
func clickStartButton() {
NSNotificationCenter.defaultCenter().postNotificationName(HMRootViewControllerSwitchNotification, object: true)
}
/// 开始按钮动画
private func startButtonAnim() {
startButton.hidden = false
startButton.transform = CGAffineTransformMakeScale(0, 0)
// 禁用按钮操作
startButton.userInteractionEnabled = false
UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
// 恢复默认形变
self.startButton.transform = CGAffineTransformIdentity
}) { (_) -> Void in
// 启用按钮点击
self.startButton.userInteractionEnabled = true
}
}
// MARK: - 设置 UI
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareUI()
}
private func prepareUI() {
// 添加控件 - 建议都加载 contentView 上
contentView.addSubview(iconView)
contentView.addSubview(startButton)
// 自动布局
iconView.ff_Fill(contentView)
startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
}
// MARK: - 懒加载控件
private lazy var iconView = UIImageView()
private lazy var startButton: UIButton = {
let button = UIButton()
button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
button.setTitle("开始体验", forState: UIControlState.Normal)
// 根据背景图片自动调整大小
button.sizeToFit()
// 提示: 按钮的隐藏属性会因为复用工作不正常
button.hidden = true
button.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
}
/// 自定义流水布局
private class HMFlowLayout: UICollectionViewFlowLayout {
// 2. 如果还没有设置 layout,获取数量之后,准备cell之前,会被调用一次
// 准备布局属性
private override func prepareLayout() {
itemSize = collectionView!.bounds.size
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView?.pagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.bounces = false
}
}
| mit | e71f746ac76ed947d11d776174a0f6b5 | 30.803681 | 179 | 0.639082 | 5.003861 | false | false | false | false |
RaviiOS/Swift_ReusableCode | RKSwift3Plus/RKSwift3Plus/Utitlities/KeyChainWrapper.swift | 1 | 16918 | //
// KeyChainWrapper.swift
// RKSwift3Plus
//
// Created by Ravi on 04/08/17.
// Copyright © 2017 RKSolutions. All rights reserved.
//
import Foundation
//
// Keychain helper for iOS/Swift.
//
// https://github.com/marketplacer/keychain-swift
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// KeychainSwift.swift
//
// ----------------------------
import Security
import Foundation
/**
A collection of helper functions for saving text and data in the keychain.
*/
open class KeychainSwift {
var lastQueryParameters: [String: Any]? // Used by the unit tests
/// Contains result code from the last operation. Value is noErr (0) for a successful result.
open var lastResultCode: OSStatus = noErr
var keyPrefix = "" // Can be useful in test.
/**
Specify an access group that will be used to access keychain items. Access groups can be used to share keychain items between applications. When access group value is nil all application access groups are being accessed. Access group name is used by all functions: set, get, delete and clear.
*/
open var accessGroup: String?
/**
Specifies whether the items can be synchronized with other devices through iCloud. Setting this property to true will
add the item to other devices with the `set` method and obtain synchronizable items with the `get` command. Deleting synchronizable items will remove them from all devices. In order for keychain synchronization to work the user must enable "Keychain" in iCloud settings.
Does not work on macOS.
*/
open var synchronizable: Bool = false
/// Instantiate a KeychainSwift object
public init() { }
/**
- parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain.
*/
public init(keyPrefix: String) {
self.keyPrefix = keyPrefix
}
/**
Stores the text value in the keychain item under the given key.
- parameter key: Key under which the text value is stored in the keychain.
- parameter value: Text string to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the text was successfully written to the keychain.
*/
@discardableResult
open func set(_ value: String, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
if let value = value.data(using: String.Encoding.utf8) {
return set(value, forKey: key, withAccess: access)
}
return false
}
/**
Stores the data in the keychain item under the given key.
- parameter key: Key under which the data is stored in the keychain.
- parameter value: Data to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the text was successfully written to the keychain.
*/
@discardableResult
open func set(_ value: Data, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
delete(key) // Delete any existing key before saving it
let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
let prefixedKey = keyWithPrefix(key)
var query: [String : Any] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey,
KeychainSwiftConstants.valueData : value,
KeychainSwiftConstants.accessible : accessible
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: true)
lastQueryParameters = query
lastResultCode = SecItemAdd(query as CFDictionary, nil)
return lastResultCode == noErr
}
/**
Stores the boolean value in the keychain item under the given key.
- parameter key: Key under which the value is stored in the keychain.
- parameter value: Boolean to be written to the keychain.
- parameter withAccess: Value that indicates when your app needs access to the value in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user.
- returns: True if the value was successfully written to the keychain.
*/
@discardableResult
open func set(_ value: Bool, forKey key: String,
withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
let bytes: [UInt8] = value ? [1] : [0]
let data = Data(bytes: bytes)
return set(data, forKey: key, withAccess: access)
}
/**
Retrieves the text value from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The text value from the keychain. Returns nil if unable to read the item.
*/
open func get(_ key: String) -> String? {
if let data = getData(key) {
if let currentString = String(data: data, encoding: .utf8) {
return currentString
}
lastResultCode = -67853 // errSecInvalidEncoding
}
return nil
}
/**
Retrieves the data from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The text value from the keychain. Returns nil if unable to read the item.
*/
open func getData(_ key: String) -> Data? {
let prefixedKey = keyWithPrefix(key)
var query: [String: Any] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey,
KeychainSwiftConstants.returnData : kCFBooleanTrue,
KeychainSwiftConstants.matchLimit : kSecMatchLimitOne
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
var result: AnyObject?
lastResultCode = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
if lastResultCode == noErr { return result as? Data }
return nil
}
/**
Retrieves the boolean value from the keychain that corresponds to the given key.
- parameter key: The key that is used to read the keychain item.
- returns: The boolean value from the keychain. Returns nil if unable to read the item.
*/
open func getBool(_ key: String) -> Bool? {
guard let data = getData(key) else { return nil }
guard let firstBit = data.first else { return nil }
return firstBit == 1
}
/**
Deletes the single keychain item specified by the key.
- parameter key: The key that is used to delete the keychain item.
- returns: True if the item was successfully deleted.
*/
@discardableResult
open func delete(_ key: String) -> Bool {
let prefixedKey = keyWithPrefix(key)
var query: [String: Any] = [
KeychainSwiftConstants.klass : kSecClassGenericPassword,
KeychainSwiftConstants.attrAccount : prefixedKey
]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
lastResultCode = SecItemDelete(query as CFDictionary)
return lastResultCode == noErr
}
/**
Deletes all Keychain items used by the app. Note that this method deletes all items regardless of the prefix settings used for initializing the class.
- returns: True if the keychain items were successfully deleted.
*/
@discardableResult
open func clear() -> Bool {
var query: [String: Any] = [ kSecClass as String : kSecClassGenericPassword ]
query = addAccessGroupWhenPresent(query)
query = addSynchronizableIfRequired(query, addingItems: false)
lastQueryParameters = query
lastResultCode = SecItemDelete(query as CFDictionary)
return lastResultCode == noErr
}
/// Returns the key with currently set prefix.
func keyWithPrefix(_ key: String) -> String {
return "\(keyPrefix)\(key)"
}
func addAccessGroupWhenPresent(_ items: [String: Any]) -> [String: Any] {
guard let accessGroup = accessGroup else { return items }
var result: [String: Any] = items
result[KeychainSwiftConstants.accessGroup] = accessGroup
return result
}
/**
Adds kSecAttrSynchronizable: kSecAttrSynchronizableAny` item to the dictionary when the `synchronizable` property is true.
- parameter items: The dictionary where the kSecAttrSynchronizable items will be added when requested.
- parameter addingItems: Use `true` when the dictionary will be used with `SecItemAdd` method (adding a keychain item). For getting and deleting items, use `false`.
- returns: the dictionary with kSecAttrSynchronizable item added if it was requested. Otherwise, it returns the original dictionary.
*/
func addSynchronizableIfRequired(_ items: [String: Any], addingItems: Bool) -> [String: Any] {
if !synchronizable { return items }
var result: [String: Any] = items
result[KeychainSwiftConstants.attrSynchronizable] = addingItems == true ? true : kSecAttrSynchronizableAny
return result
}
}
// ----------------------------
//
// KeychainSwiftAccessOptions.swift
//
// ----------------------------
import Security
/**
These options are used to determine when a keychain item should be readable. The default value is AccessibleWhenUnlocked.
*/
public enum KeychainSwiftAccessOptions {
/**
The data in the keychain item can be accessed only while the device is unlocked by the user.
This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups.
This is the default value for keychain items added without explicitly setting an accessibility constant.
*/
case accessibleWhenUnlocked
/**
The data in the keychain item can be accessed only while the device is unlocked by the user.
This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case accessibleWhenUnlockedThisDeviceOnly
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.
*/
case accessibleAfterFirstUnlock
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case accessibleAfterFirstUnlockThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
*/
case accessibleAlways
/**
The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device.
This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted.
*/
case accessibleWhenPasscodeSetThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case accessibleAlwaysThisDeviceOnly
static var defaultOption: KeychainSwiftAccessOptions {
return .accessibleWhenUnlocked
}
var value: String {
switch self {
case .accessibleWhenUnlocked:
return toString(kSecAttrAccessibleWhenUnlocked)
case .accessibleWhenUnlockedThisDeviceOnly:
return toString(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
case .accessibleAfterFirstUnlock:
return toString(kSecAttrAccessibleAfterFirstUnlock)
case .accessibleAfterFirstUnlockThisDeviceOnly:
return toString(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
case .accessibleAlways:
return toString(kSecAttrAccessibleAlways)
case .accessibleWhenPasscodeSetThisDeviceOnly:
return toString(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
case .accessibleAlwaysThisDeviceOnly:
return toString(kSecAttrAccessibleAlwaysThisDeviceOnly)
}
}
func toString(_ value: CFString) -> String {
return KeychainSwiftConstants.toString(value)
}
}
// ----------------------------
//
// TegKeychainConstants.swift
//
// ----------------------------
import Foundation
import Security
/// Constants used by the library
public struct KeychainSwiftConstants {
/// Specifies a Keychain access group. Used for sharing Keychain items between apps.
public static var accessGroup: String { return toString(kSecAttrAccessGroup) }
/**
A value that indicates when your app needs access to the data in a keychain item. The default value is AccessibleWhenUnlocked. For a list of possible values, see KeychainSwiftAccessOptions.
*/
public static var accessible: String { return toString(kSecAttrAccessible) }
/// Used for specifying a String key when setting/getting a Keychain value.
public static var attrAccount: String { return toString(kSecAttrAccount) }
/// Used for specifying synchronization of keychain items between devices.
public static var attrSynchronizable: String { return toString(kSecAttrSynchronizable) }
/// An item class key used to construct a Keychain search dictionary.
public static var klass: String { return toString(kSecClass) }
/// Specifies the number of values returned from the keychain. The library only supports single values.
public static var matchLimit: String { return toString(kSecMatchLimit) }
/// A return data type used to get the data from the Keychain.
public static var returnData: String { return toString(kSecReturnData) }
/// Used for specifying a value when setting a Keychain value.
public static var valueData: String { return toString(kSecValueData) }
static func toString(_ value: CFString) -> String {
return value as String
}
}
| mit | b3b9445069c91fe5ccb471c653d6f266 | 38.069284 | 380 | 0.667908 | 5.642762 | false | false | false | false |
53ningen/todo | TODO/Domain/Entity/Milestone.swift | 1 | 2572 | /// マイルストンを表すエンティティ
public final class MilestoneInfo: EntityInfo {
public let state: MilestoneState
public let description: String
public let createdAt: Date
public let updatedAt: Date
public let dueOn: Date?
public let openIssuesCount: Int?
public let closedIssuesCount: Int?
public init(state: MilestoneState, description: String, createdAt: Date, updatedAt: Date, dueOn: Date?, openIssuesCount: Int? = nil, closedIssuesCount: Int? = nil) {
self.state = state
self.description = description
self.createdAt = createdAt
self.updatedAt = updatedAt
self.dueOn = dueOn
self.openIssuesCount = openIssuesCount
self.closedIssuesCount = closedIssuesCount
}
}
extension MilestoneInfo: Equatable {}
public func ==(lhs: MilestoneInfo, rhs: MilestoneInfo) -> Bool {
return lhs.state == rhs.state
&& lhs.description == rhs.description
&& lhs.createdAt == rhs.createdAt
&& lhs.updatedAt == rhs.updatedAt
&& lhs.dueOn == rhs.dueOn
&& lhs.openIssuesCount == rhs.openIssuesCount
&& lhs.closedIssuesCount == rhs.closedIssuesCount
}
public final class Milestone: Entity, Equatable {
public typealias INFO = MilestoneInfo
public let id: Id<Milestone>
public let info: MilestoneInfo
public init(id: Id<Milestone>, info: MilestoneInfo) {
self.id = id
self.info = info
}
public var closed: Bool {
return info.state != .Open
}
public func isPastDue(_ now: Date) -> Bool {
return now > info.dueOn!
}
public var progress: Float {
guard let openIssuesCount = info.openIssuesCount, let closedIssuesCount = info.closedIssuesCount else { return 1 }
let total = Float(openIssuesCount) + Float(closedIssuesCount)
return openIssuesCount == 0 ? 1 : Float(closedIssuesCount) / total
}
}
public enum MilestoneState: String {
case Open = "open"
case Closed = "closed"
public static func of(_ rawValue: String) -> MilestoneState? {
switch rawValue {
case MilestoneState.Open.rawValue: return .Open
case MilestoneState.Closed.rawValue: return .Closed
default: return nil
}
}
}
extension MilestoneState: Equatable {}
public func ==(lhs: MilestoneState, rhs: MilestoneState) -> Bool {
switch (lhs, rhs) {
case (.Open, .Open): return true
case (.Closed, .Closed): return true
default: return false
}
}
| mit | 45333b2eabad964724ebcf5ad186518b | 28.905882 | 169 | 0.647522 | 4.250836 | false | false | false | false |
sergdort/CleanArchitectureRxSwift | CleanArchitectureRxSwift/Scenes/CreatePost/CreatePostViewModel.swift | 1 | 1747 | //
// Created by sergdort on 19/02/2017.
// Copyright (c) 2017 sergdort. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Domain
final class CreatePostViewModel: ViewModelType {
private let createPostUseCase: PostsUseCase
private let navigator: CreatePostNavigator
init(createPostUseCase: PostsUseCase, navigator: CreatePostNavigator) {
self.createPostUseCase = createPostUseCase
self.navigator = navigator
}
func transform(input: Input) -> Output {
let titleAndDetails = Driver.combineLatest(input.title, input.details)
let activityIndicator = ActivityIndicator()
let canSave = Driver.combineLatest(titleAndDetails, activityIndicator.asDriver()) {
return !$0.0.isEmpty && !$0.1.isEmpty && !$1
}
let save = input.saveTrigger.withLatestFrom(titleAndDetails)
.map { (title, content) in
return Post(body: content, title: title)
}
.flatMapLatest { [unowned self] in
return self.createPostUseCase.save(post: $0)
.trackActivity(activityIndicator)
.asDriverOnErrorJustComplete()
}
let dismiss = Driver.merge(save, input.cancelTrigger)
.do(onNext: navigator.toPosts)
return Output(dismiss: dismiss, saveEnabled: canSave)
}
}
extension CreatePostViewModel {
struct Input {
let cancelTrigger: Driver<Void>
let saveTrigger: Driver<Void>
let title: Driver<String>
let details: Driver<String>
}
struct Output {
let dismiss: Driver<Void>
let saveEnabled: Driver<Bool>
}
}
| mit | 53dea936b5a36f8d58eb11af36a2d78e | 29.12069 | 91 | 0.627361 | 4.734417 | false | true | false | false |
zhouxinv/SwiftThirdTest | SwiftTest/AlamofireController.swift | 1 | 6217 | //
// AlamofireController.swift
// SwiftTest
//
// Created by GeWei on 2017/1/10.
// Copyright © 2017年 GeWei. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class AlamofireController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "我的";
self.getListValue()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//nib 已经存在cell的时候调用
// let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
var cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier:"reuseIdentifier")
}
cell?.textLabel?.text = "celllllll";
return cell!
}
func toSortedWithAppKey(newParams: NSMutableDictionary) -> (String) {
let APPKEY = "CHE168CRMMRC"
let str = NSMutableString(string: "CHE168CRMMRC")
let keys = newParams.allKeys as Array
let sortedArray = keys.sorted(by: { (obj1, obj2) -> Bool in
return true
})
for key in sortedArray {
let value = newParams.object(forKey: key)
str.appendFormat(key as! NSString,value as! CVarArg)
}
str.append(APPKEY as String)
let strs = str as String
return strs.md5();
}
// MARK: - NetWork
func getListValue() -> Void {
let params = self.getParams()
let urlStr = "https://apicrm.che168.com/api/DealerNew/GetDealerListByCondition"
let headers: HTTPHeaders = [
"set-Cookie": "aaUSpwbiqekJh0YhhFuAEo4B6NYT5q81d0SAeixF/vp2Bb1Dfr48ovMPFHVGO2/IKF13YZ7Tcma06piBIZo47YlPetJ8S2c9Vfu0/1pe3siUk9bvQbTuNxjwMSs5K3iGw9FTMpH3NiYKbQUXoQ1r1pSGbgNqXRoVWFCL1fxehsO8="
]
Alamofire.request(urlStr, method: .get, parameters: params as? Parameters, headers: headers)
.responseJSON { (response) in
/*这里使用了闭包*/
//当请求后response是我们自定义的,这个变量用于接受服务器响应的信息
//使用switch判断请求是否成功,也就是response的result
switch response.result {
//swift 值绑定的写法
case .success(_):
//当响应成功是,使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success
if let value = response.result.value as? [String : AnyObject] {
// success(value)
let json = JSON(value)
print("JSON: \(json)")
}
case .failure(_):
// failture(error)
print("error")
}
}
}
func getParams() -> NSDictionary {
// _device iOS 10.2(iPhone Simulator)
// _latitude 0
// _longitude 0
// _net Wifi
// _sign b628ec882900e4beac7552ff86b2f01d
// _timestamp 1484014953583
// _token aUSpwbiqekJh0YhhFuAEo4B6NYT5q81d0SAeixF/vp2Bb1Dfr48ovMPFHVGO2/IKF13YZ7Tcma06piBIZo47YlPetJ8S2c9Vfu0/1pe3siVqMN64MarARLg7PmLL/Y1J9FTMpH3NiYKbQUXoQ1r1pSGbgNqXRoVWFCL1fxehsO8=
// _udid bf83c555dd8544e0aec2e877bb200fcae9fa1c80
// _ver 3.3.0
// adviserid 0
// areaid 0
// carstatus -1
// cityid 0
// collarstate -1
// dealerkeyword
// dealerstatus 1
// dealertype 0
// focusstatus -1
// marketingstate -1
// pageindex 1
// pagesize 20
// paystatus -1
// sorttype 40
// tasktype -1
let _token = "aUSpwbiqekJh0YhhFuAEo4B6NYT5q81d0SAeixF/vp2Bb1Dfr48ovMPFHVGO2/IKF13YZ7Tcma06piBIZo47YlPetJ8S2c9Vfu0/1pe3siUk9bvQbTuNxjwMSs5K3iGw9FTMpH3NiYKbQUXoQ1r1pSGbgNqXRoVWFCL1fxehsO8="
let _udid = "bf83c555dd8544e0aec2e877bb200fcae9fa1c80 "
let _device = "iOS 10.2(iPhone Simulator)"
let _version = "3.3.0";
let _netwoktype = "Wifi";
let _longitude = "0";
let _latitude = "0"
let _timestamp = Date().timeIntervalSince1970 * 1000
// [[NSDate date] timeIntervalSince1970] * 1000;
let dict = NSMutableDictionary()
dict .setValue ("20 ", forKey: "pagesize")
dict .setValue ("1 ", forKey: "pageindex")
let newParams = NSMutableDictionary(dictionary: dict)
newParams.setValue(_udid, forKey: "_udid")
newParams.setValue(_device, forKey: "_device")
newParams.setValue(_version, forKey: "_ver")
newParams.setValue(_netwoktype, forKey: "_net")
newParams.setValue(_longitude, forKey: "_longitude")
newParams.setValue(_latitude, forKey: "_latitude")
newParams.setValue(_timestamp, forKey: "_timestamp")
newParams.setValue(_token, forKey: "c")
// 获取sign加密
// _sign = [newParams cmToSorted];
let _sign = self.toSortedWithAppKey(newParams: newParams)
newParams.setValue(_sign, forKey: "_sign")
newParams.setValue(_token, forKey: "_token")
newParams.removeObject(forKey: "c")
// [newParams setValue:_sign forKey:@"_sign"];
// [newParams setValue:_token forKey: @"_token" ];//_token不参与加密
// [newParams removeObjectForKey:@"c"]; //加密后剔除
return newParams ;
}
}
| mit | 4ac60b1e6d648e91f4353d70fac55c58 | 34.464286 | 201 | 0.574354 | 3.71215 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/Authentication/AuthenticationInterfaceBuilderTests.swift | 1 | 6725 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import Wire
final class AuthenticationInterfaceBuilderTests: ZMSnapshotTestCase, CoreDataFixtureTestHelper {
var coreDataFixture: CoreDataFixture!
var featureProvider: MockAuthenticationFeatureProvider!
var builder: AuthenticationInterfaceBuilder!
override func setUp() {
super.setUp()
coreDataFixture = CoreDataFixture()
featureProvider = MockAuthenticationFeatureProvider()
builder = AuthenticationInterfaceBuilder(featureProvider: featureProvider)
}
override func tearDown() {
builder = nil
featureProvider = nil
coreDataFixture = nil
super.tearDown()
}
// MARK: - General
func testLandingScreen() {
runSnapshotTest(for: .landingScreen)
}
func testThatItDoesNotGenerateInterfaceForCompanyLoginFlow() {
runSnapshotTest(for: .companyLogin)
}
// MARK: - User Registration
func testRegistrationScreen() {
runSnapshotTest(for: .createCredentials(UnregisteredUser()))
}
func testActivationScreen_Phone() {
let phoneNumber = UnverifiedCredentials.phone("+0123456789")
runSnapshotTest(for: .enterActivationCode(phoneNumber, user: UnregisteredUser()))
}
func testActivationScreen_Email() {
let email = UnverifiedCredentials.email("test@example.com")
runSnapshotTest(for: .enterActivationCode(email, user: UnregisteredUser()))
}
func testSetNameScreen() {
runSnapshotTest(for: .incrementalUserCreation(UnregisteredUser(), .setName))
}
func testSetPasswordScreen() {
runSnapshotTest(for: .incrementalUserCreation(UnregisteredUser(), .setPassword))
}
func testThatItDoesNotGenerateInterfaceForMarketingConsentStep() {
runSnapshotTest(for: .incrementalUserCreation(UnregisteredUser(), .provideMarketingConsent))
}
// MARK: - Login
func testLoginScreen_Phone() {
runSnapshotTest(for: .provideCredentials(.phone, nil))
}
func testLoginScreen_Email() {
runSnapshotTest(for: .provideCredentials(.email, nil))
}
func testLoginScreen_Email_PhoneDisabled() {
featureProvider.allowOnlyEmailLogin = true
runSnapshotTest(for: .provideCredentials(.email, nil))
}
func testLoginScreen_PhoneNumberVerification() {
runSnapshotTest(for: .enterPhoneVerificationCode(phoneNumber: "+0123456789"))
}
func testBackupScreen_NewDevice() {
runSnapshotTest(for: .noHistory(credentials: nil, context: .newDevice))
}
func testBackupScreen_LoggedOut() {
runSnapshotTest(for: .noHistory(credentials: nil, context: .loggedOut))
}
func testTooManyDevicesScreen() {
runSnapshotTest(for: .clientManagement(clients: [], credentials: nil))
}
func testClientRemovalScreen() {
runSnapshotTest(for: .deleteClient(clients: [mockUserClient()], credentials: nil))
}
func testAddEmailPasswordScreen() {
runSnapshotTest(for: .addEmailAndPassword)
}
func testVerifyEmailLinkTests() {
let credentials = ZMEmailCredentials(email: "test@example.com", password: "12345678")
runSnapshotTest(for: .pendingEmailLinkVerification(credentials))
}
func testReauthenticate_Email_TokenExpired() {
let credentials = LoginCredentials(emailAddress: "test@example.com", phoneNumber: nil, hasPassword: true, usesCompanyLogin: false)
runSnapshotTest(for: .reauthenticate(credentials: credentials, numberOfAccounts: 1, isSignedOut: true))
}
func testReauthenticate_Email_DuringLogin() {
let credentials = LoginCredentials(emailAddress: "test@example.com", phoneNumber: nil, hasPassword: true, usesCompanyLogin: false)
runSnapshotTest(for: .reauthenticate(credentials: credentials, numberOfAccounts: 1, isSignedOut: false))
}
func testReauthenticate_EmailAndPhone_TokenExpired() {
let credentials = LoginCredentials(emailAddress: "test@example.com", phoneNumber: "+33123456789", hasPassword: true, usesCompanyLogin: false)
// Email should have priority
runSnapshotTest(for: .reauthenticate(credentials: credentials, numberOfAccounts: 1, isSignedOut: true))
}
func testReauthenticate_Phone_DuringLogin() {
let credentials = LoginCredentials(emailAddress: nil, phoneNumber: "+33123456789", hasPassword: true, usesCompanyLogin: false)
// Email should have priority
runSnapshotTest(for: .reauthenticate(credentials: credentials, numberOfAccounts: 1, isSignedOut: false))
}
func testReauthenticate_CompanyLogin() {
let credentials = LoginCredentials(emailAddress: nil, phoneNumber: nil, hasPassword: false, usesCompanyLogin: true)
runSnapshotTest(for: .reauthenticate(credentials: credentials, numberOfAccounts: 1, isSignedOut: true))
}
func testReauthenticate_NoCredentials() {
runSnapshotTest(for: .reauthenticate(credentials: nil, numberOfAccounts: 1, isSignedOut: true))
}
// MARK: - Helpers
private func runSnapshotTest(for step: AuthenticationFlowStep,
file: StaticString = #file,
testName: String = #function,
line: UInt = #line) {
if let viewController = builder.makeViewController(for: step) {
if !step.needsInterface {
return XCTFail("An interface was generated but we didn't expect one.", file: file, line: line)
}
let navigationController = UINavigationController(navigationBarClass: AuthenticationNavigationBar.self, toolbarClass: nil)
navigationController.viewControllers = [viewController]
verify(matching: navigationController,
file: file,
testName: testName,
line: line)
} else {
XCTAssertFalse(step.needsInterface, "Missing interface.", file: file, line: line)
}
}
}
| gpl-3.0 | 2e86dde245f13048c5ea386c3921813e | 35.748634 | 149 | 0.693532 | 4.912345 | false | true | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Home/Wallpapers/v1/UI/WallpaperCollectionViewCell.swift | 2 | 5309 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import UIKit
class WallpaperCollectionViewCell: UICollectionViewCell, ReusableCell {
private struct UX {
static let cornerRadius: CGFloat = 10
static let borderWidth: CGFloat = 1
static let selectedBorderWidth: CGFloat = 3
static let shadowOffset: CGSize = CGSize(width: 0, height: 5.0)
static let shadowOpacity: Float = 0.2
static let shadowRadius: CGFloat = 4.0
}
// MARK: - UI Element
private lazy var imageView: UIImageView = .build { imageView in
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
private lazy var borderView: UIView = .build { borderView in
borderView.layer.cornerRadius = WallpaperCollectionViewCell.UX.cornerRadius
borderView.layer.borderWidth = WallpaperCollectionViewCell.UX.borderWidth
borderView.backgroundColor = .clear
}
private lazy var selectedView: UIView = .build { selectedView in
selectedView.layer.cornerRadius = WallpaperCollectionViewCell.UX.cornerRadius
selectedView.layer.borderWidth = WallpaperCollectionViewCell.UX.selectedBorderWidth
selectedView.backgroundColor = .clear
selectedView.alpha = 0.0
}
private lazy var activityIndicatorView: UIActivityIndicatorView = .build { view in
view.style = .large
view.isHidden = true
}
// MARK: - Variables
var viewModel: WallpaperCellViewModel? {
didSet {
updateContent()
}
}
override var isSelected: Bool {
didSet {
selectedView.alpha = isSelected ? 1.0 : 0.0
}
}
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
func showDownloading(_ isDownloading: Bool) {
if isDownloading {
activityIndicatorView.startAnimating()
} else {
activityIndicatorView.stopAnimating()
}
}
func setupShadow(theme: Theme) {
layer.backgroundColor = UIColor.clear.cgColor
layer.shadowColor = theme.colors.shadowDefault.cgColor
layer.shadowOffset = WallpaperCollectionViewCell.UX.shadowOffset
layer.shadowOpacity = WallpaperCollectionViewCell.UX.shadowOpacity
layer.shadowRadius = WallpaperCollectionViewCell.UX.shadowRadius
layer.shadowPath = UIBezierPath(
roundedRect: self.bounds,
cornerRadius: WallpaperCollectionViewCell.UX.cornerRadius).cgPath
}
}
// MARK: - Private
private extension WallpaperCollectionViewCell {
func updateContent() {
guard let viewModel = viewModel else { return }
imageView.image = viewModel.image
accessibilityIdentifier = viewModel.a11yId
accessibilityLabel = viewModel.a11yLabel
isAccessibilityElement = true
}
func setupView() {
contentView.addSubview(borderView)
contentView.addSubview(imageView)
contentView.addSubview(selectedView)
contentView.addSubview(activityIndicatorView)
contentView.layer.cornerRadius = WallpaperCollectionViewCell.UX.cornerRadius
contentView.clipsToBounds = true
NSLayoutConstraint.activate([
borderView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
borderView.topAnchor.constraint(equalTo: contentView.topAnchor),
borderView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
borderView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
selectedView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
selectedView.topAnchor.constraint(equalTo: contentView.topAnchor),
selectedView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
selectedView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
activityIndicatorView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
activityIndicatorView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
])
}
}
// MARK: - ThemeApplicable
extension WallpaperCollectionViewCell: ThemeApplicable {
func applyTheme(theme: Theme) {
contentView.backgroundColor = theme.colors.layer2
borderView.layer.borderColor = theme.colors.borderPrimary.cgColor
selectedView.layer.borderColor = theme.colors.actionPrimary.cgColor
activityIndicatorView.color = theme.colors.iconSpinner
setupShadow(theme: theme)
}
}
| mpl-2.0 | d504a8eef48c87b60195b89ea5b14009 | 35.613793 | 95 | 0.695611 | 5.524454 | false | false | false | false |
benlangmuir/swift | test/Generics/unify_concrete_types_1.swift | 9 | 861 | // RUN: %target-typecheck-verify-swift -dump-requirement-machine 2>&1 | %FileCheck %s
struct Foo<A, B> {}
protocol P1 {
associatedtype X where X == Foo<Y1, Z1>
associatedtype Y1
associatedtype Z1
}
protocol P2 {
associatedtype X where X == Foo<Y2, Z2>
associatedtype Y2
associatedtype Z2
}
struct MergeTest<G : P1 & P2> {
func foo1(x: G.Y1) -> G.Y2 { return x }
func foo2(x: G.Z1) -> G.Z2 { return x }
}
// CHECK-LABEL: Requirement machine for fresh signature < G >
// CHECK-LABEL: Rewrite system: {
// CHECK: - τ_0_0.[P2:Y2] => τ_0_0.[P1:Y1]
// CHECK: - τ_0_0.[P2:Z2] => τ_0_0.[P1:Z1]
// CHECK: }
// CHECK-LABEL: Property map: {
// CHECK: [P1:X] => { concrete_type: [concrete: Foo<[P1:Y1], [P1:Z1]>] }
// CHECK: [P2:X] => { concrete_type: [concrete: Foo<[P2:Y2], [P2:Z2]>] }
// CHECK: τ_0_0 => { conforms_to: [P1 P2] }
// CHECK: }
| apache-2.0 | 9ec2f4d68a62ae22bff7b5e3dd4b0884 | 26.612903 | 85 | 0.602804 | 2.418079 | false | false | false | false |
jejefcgb/ProjetS9-iOS | Projet S9/Topology.swift | 1 | 1061 | //
// Topology.swift
// Projet S9
//
// Created by Guillaume SCHAHL on 04/01/2015.
// Copyright (c) 2015 Jérémie Foucault. All rights reserved.
//
import Foundation
private let _TopologySharedInstance = Topology()
/**
Data entity that represents a topologys.
Subclasses NSObject to enable Obj-C instantiation.
*/
class Topology : NSObject, Equatable
{
var
major: Int?,
name: String?,
link: String?,
floors: [Floor]?
class var sharedInstance: Topology {
return _TopologySharedInstance
}
// Used by Foundation collections, such as NSSet.
override func isEqual(object: AnyObject!) -> Bool {
return self == object as Topology
}
func setData(major:Int, name:String, link:String, floors:[Floor]) {
self.major = major
self.name = name
self.link = link
self.floors = floors
}
}
// Required for Equatable protocol conformance
func == (lhs: Topology, rhs: Topology) -> Bool {
return lhs.major == rhs.major
} | apache-2.0 | 2123ca479825bbbb58bcd804c0535425 | 20.2 | 71 | 0.624174 | 3.996226 | false | false | false | false |
zweigraf/march-thirteen | MarchThirteen/MarchThirteen/WalkieTalkie/CommunicatorMessage.swift | 1 | 1786 | //
// CommunicatorMessage.swift
// MarchThirteen
//
// Created by Luis Reisewitz on 18.03.17.
// Copyright © 2017 ZweiGraf. All rights reserved.
//
import Foundation
fileprivate enum DictionaryKeys: String {
case meta
case payload
}
/// Represents a message.
public struct CommunicatorMessage<PayloadType: CommunicatorPayload> {
/// The payload of the message as sent by the other party.
public let payload: PayloadType
/// The peer that sent this message.
public let peer: Peer
// TODO: add timestamps & figure out way to synchronise devices times
}
// MARK: - ↔️ Data In/Out ↔️
internal extension CommunicatorMessage {
private init?(from dictionary: [String : Any], peer: Peer) {
guard let payloadDict = dictionary[DictionaryKeys.payload.rawValue] as? [String: Any],
let payload = PayloadType(from: payloadDict) else {
return nil
}
self.init(payload: payload, peer: peer)
}
private var dictionaryRepresentation: [String : Any] {
// Wrap payload in dictionary to later attach metadata for ourselves
// Do not serialise the peer, that will not be transferred.
let dictionary: [String: Any] = [
DictionaryKeys.payload.rawValue: payload.dictionaryRepresentation
]
return dictionary
}
init?(from data: Data, peer: Peer) {
guard let dictionary = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: Any] else {
return nil
}
self.init(from: dictionary, peer: peer)
}
var dataRepresentation: Data {
let dictionary = dictionaryRepresentation
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)
return data
}
}
| mit | 6e0dcfd6e97ebe07e077f50f699a74fa | 30.175439 | 101 | 0.657288 | 4.603627 | false | false | false | false |
caicai0/ios_demo | load/thirdpart/SwiftSoup/OrderedSet.swift | 3 | 12621 | //
// OrderedSet.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 12/11/16.
// Copyright © 2016 Nabil Chatbi. All rights reserved.
//
import Foundation
/// An ordered, unique collection of objects.
public class OrderedSet<T: Hashable> {
public typealias Index = Int
fileprivate var contents = [T: Index]() // Needs to have a value of Index instead of Void for fast removals
fileprivate var sequencedContents = Array<UnsafeMutablePointer<T>>()
/**
Inititalizes an empty ordered set.
- returns: An empty ordered set.
*/
public init() { }
deinit {
removeAllObjects()
}
/**
Initializes a new ordered set with the order and contents
of sequence.
If an object appears more than once in the sequence it will only appear
once in the ordered set, at the position of its first occurance.
- parameter sequence: The sequence to initialize the ordered set with.
- returns: An initialized ordered set with the contents of sequence.
*/
public init<S: Sequence>(sequence: S) where S.Iterator.Element == T {
for object in sequence {
if contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
}
public required init(arrayLiteral elements: T...) {
for object in elements {
if contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
}
/**
Locate the index of an object in the ordered set.
It is preferable to use this method over the global find() for performance reasons.
- parameter object: The object to find the index for.
- returns: The index of the object, or nil if the object is not in the ordered set.
*/
public func index(of object: T) -> Index? {
if let index = contents[object] {
return index
}
return nil
}
/**
Appends an object to the end of the ordered set.
- parameter object: The object to be appended.
*/
public func append(_ object: T) {
if let lastIndex = index(of: object) {
remove(object)
insert(object, at: lastIndex)
} else {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
/**
Appends a sequence of objects to the end of the ordered set.
- parameter sequence: The sequence of objects to be appended.
*/
public func append<S: Sequence>(contentsOf sequence: S) where S.Iterator.Element == T {
var gen = sequence.makeIterator()
while let object: T = gen.next() {
append(object)
}
}
/**
Removes an object from the ordered set.
If the object exists in the ordered set, it will be removed.
If it is not the last object in the ordered set, subsequent
objects will be shifted down one position.
- parameter object: The object to be removed.
*/
public func remove(_ object: T) {
if let index = contents[object] {
contents[object] = nil
sequencedContents[index].deallocate(capacity: 1)
sequencedContents.remove(at: index)
for (object, i) in contents {
if i < index {
continue
}
contents[object] = i - 1
}
}
}
/**
Removes the given objects from the ordered set.
- parameter objects: The objects to be removed.
*/
public func remove<S: Sequence>(_ objects: S) where S.Iterator.Element == T {
var gen = objects.makeIterator()
while let object: T = gen.next() {
remove(object)
}
}
/**
Removes an object at a given index.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter index: The index of the object to be removed.
*/
public func removeObject(at index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to remove an object at an index that does not exist")
}
remove(sequencedContents[index].pointee)
}
/**
Removes all objects in the ordered set.
*/
public func removeAllObjects() {
contents.removeAll()
for sequencedContent in sequencedContents {
sequencedContent.deallocate(capacity: 1)
}
sequencedContents.removeAll()
}
/**
Swaps two objects contained within the ordered set.
Both objects must exist within the set, or the swap will not occur.
- parameter first: The first object to be swapped.
- parameter second: The second object to be swapped.
*/
public func swapObject(_ first: T, with second: T) {
if let firstPosition = contents[first] {
if let secondPosition = contents[second] {
contents[first] = secondPosition
contents[second] = firstPosition
sequencedContents[firstPosition].pointee = second
sequencedContents[secondPosition].pointee = first
}
}
}
/**
Tests if the ordered set contains any objects within a sequence.
- parameter other: The sequence to look for the intersection in.
- returns: Returns true if the sequence and set contain any equal objects, otherwise false.
*/
public func intersects<S: Sequence>(_ other: S) -> Bool where S.Iterator.Element == T {
var gen = other.makeIterator()
while let object: T = gen.next() {
if contains(object) {
return true
}
}
return false
}
/**
Tests if a the ordered set is a subset of another sequence.
- parameter sequence: The sequence to check.
- returns: true if the sequence contains all objects contained in the receiver, otherwise false.
*/
public func isSubset<S: Sequence>(of sequence: S) -> Bool where S.Iterator.Element == T {
for (object, _) in contents {
if !sequence.contains(object) {
return false
}
}
return true
}
/**
Moves an object to a different index, shifting all objects in between the movement.
This method is a no-op if the object doesn't exist in the set or the index is the
same that the object is currently at.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter object: The object to be moved
- parameter index: The index that the object should be moved to.
*/
public func moveObject(_ object: T, toIndex index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to move an object at an index that does not exist")
}
if let position = contents[object] {
// Return if the client attempted to move to the current index
if position == index {
return
}
let adjustment = position > index ? -1 : 1
var currentIndex = position
while currentIndex != index {
let nextIndex = currentIndex + adjustment
let firstObject = sequencedContents[currentIndex].pointee
let secondObject = sequencedContents[nextIndex].pointee
sequencedContents[currentIndex].pointee = secondObject
sequencedContents[nextIndex].pointee = firstObject
contents[firstObject] = nextIndex
contents[secondObject] = currentIndex
currentIndex += adjustment
}
}
}
/**
Moves an object from one index to a different index, shifting all objects in between the movement.
This method is a no-op if the index is the same that the object is currently at.
This method will cause a fatal error if you attempt to move an object fro man index that is out of bounds
or to an index that is out of bounds.
- parameter index: The index of the object to be moved.
- parameter toIndex: The index that the object should be moved to.
*/
public func moveObject(at index: Index, to toIndex: Index) {
if ((index < 0 || index >= count) || (toIndex < 0 || toIndex >= count)) {
fatalError("Attempting to move an object at or to an index that does not exist")
}
moveObject(self[index], toIndex: toIndex)
}
/**
Inserts an object at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the object out of bounds.
If the object already exists in the OrderedSet, this operation is a no-op.
- parameter object: The object to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert(_ object: T, at index: Index) {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
if contents[object] != nil {
return
}
// Append our object, then swap them until its at the end.
append(object)
for i in (index..<count-1).reversed() {
swapObject(self[i], with: self[i+1])
}
}
/**
Inserts objects at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the objects out of bounds.
If an object in objects already exists in the OrderedSet it will not be added. Objects that occur twice
in the sequence will only be added once.
- parameter objects: The objects to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert<S: Sequence>(_ objects: S, at index: Index) where S.Iterator.Element == T {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
var addedObjectCount = 0
for object in objects {
if contents[object] == nil {
let seqIdx = index + addedObjectCount
let element = UnsafeMutablePointer<T>.allocate(capacity: 1)
element.initialize(to: object)
sequencedContents.insert(element, at: seqIdx)
contents[object] = seqIdx
addedObjectCount += 1
}
}
// Now we'll remove duplicates and update the shifted objects position in the contents
// dictionary.
for i in index + addedObjectCount..<count {
contents[sequencedContents[i].pointee] = i
}
}
/// Returns the last object in the set, or `nil` if the set is empty.
public var last: T? {
return sequencedContents.last?.pointee
}
}
extension OrderedSet: ExpressibleByArrayLiteral { }
extension OrderedSet where T: Comparable {}
extension OrderedSet {
public var count: Int {
return contents.count
}
public var isEmpty: Bool {
return count == 0
}
public var first: T? {
guard count > 0 else { return nil }
return sequencedContents[0].pointee
}
public func index(after i: Int) -> Int {
return sequencedContents.index(after: i)
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return contents.count
}
public subscript(index: Index) -> T {
get {
return sequencedContents[index].pointee
}
set {
let previousCount = contents.count
contents[sequencedContents[index].pointee] = nil
contents[newValue] = index
// If the count is reduced we used an existing value, and need to sync up sequencedContents
if contents.count == previousCount {
sequencedContents[index].pointee = newValue
} else {
sequencedContents.remove(at: index)
}
}
}
}
extension OrderedSet: Sequence {
public typealias Iterator = OrderedSetGenerator<T>
public func makeIterator() -> Iterator {
return OrderedSetGenerator(set: self)
}
}
public struct OrderedSetGenerator<T: Hashable>: IteratorProtocol {
public typealias Element = T
private var generator: IndexingIterator<Array<UnsafeMutablePointer<T>>>
public init(set: OrderedSet<T>) {
generator = set.sequencedContents.makeIterator()
}
public mutating func next() -> Element? {
return generator.next()?.pointee
}
}
extension OrderedSetGenerator where T: Comparable {}
public func +<T: Hashable, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T {
let joinedSet = lhs
joinedSet.append(contentsOf: rhs)
return joinedSet
}
public func +=<T: Hashable, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T {
lhs.append(contentsOf: rhs)
}
public func -<T: Hashable, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T {
let purgedSet = lhs
purgedSet.remove(rhs)
return purgedSet
}
public func -=<T: Hashable, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T {
lhs.remove(rhs)
}
extension OrderedSet: Equatable { }
public func ==<T: Hashable> (lhs: OrderedSet<T>, rhs: OrderedSet<T>) -> Bool {
if lhs.count != rhs.count {
return false
}
for object in lhs {
if lhs.contents[object] != rhs.contents[object] {
return false
}
}
return true
}
extension OrderedSet: CustomStringConvertible {
public var description: String {
let children = map({ "\($0)" }).joined(separator: ", ")
return "OrderedSet (\(count) object(s)): [\(children)]"
}
}
| mit | 68222e8ec350f3cb50ebf1bff1739880 | 27.359551 | 117 | 0.695246 | 3.631655 | false | false | false | false |
sr-tune/RBGenericFilterController | C4GenericFilter/Classes/Filter/cell/FilterValidationCell.swift | 1 | 2788 | //
// FilterValidationCell.swift
// Carrefour_FR_V2
//
// Created by rboyer on 10/08/2016.
//
import UIKit
protocol FilterValidatorDelegate {
func validateSelections()
func cancelFilterSelection()
func reinitFilter()
}
class FilterValidationCell: FilterGenericCell {
var btnValidator = UIButton()
var btnCancel = UIButton()
var btnReInit = UIButton()
var delegate : FilterValidatorDelegate?
override func configureWithType(_ type: FilterSpecializedCellType, theme: FilterTheme) {
self.type = type
self.selectionStyle = UITableViewCellSelectionStyle.none
updateOutlets()
}
func updateOutlets() {
func addValidorsButton() {
btnValidator.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(btnValidator)
btnValidator.centerHorizontalyInSuperview()
btnValidator.C4_ButtonBackgroundRounded("filtrer", color: UIColor.red)
btnValidator.addTarget(self, action: #selector(self.pushOnValidateButton), for: .touchUpInside)
}
func addReinitButton() {
btnReInit.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(btnReInit)
let attrsDictionary = [NSUnderlineStyleAttributeName: 1, NSFontAttributeName: UIFont.systemFont(ofSize: 17), NSForegroundColorAttributeName: UIColor.carrefourBlueCarrefourColor()] as [String : Any]
let attrString = NSAttributedString(string: "Reinitialiser", attributes: attrsDictionary)
btnReInit.setAttributedTitle(attrString, for: UIControlState())
btnReInit.setTitleColor(UIColor.carrefourBlueColor(), for: UIControlState())
btnReInit.addTarget(self, action: #selector(self.pushOnReinitButton), for: .touchUpInside)
btnReInit.centerHorizontalyInSuperview()
}
func removeAllOutlets() {
for view in contentView.subviews {
view.removeFromSuperview()
}
}
removeAllOutlets()
addValidorsButton()
addReinitButton()
manageConstraintBetweenButtons()
}
func manageConstraintBetweenButtons() {
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-15-[filterBtn]-10-[reinitBtn]-1-|",
options: NSLayoutFormatOptions.init(rawValue: 0),
metrics: nil,
views: ["filterBtn" : btnValidator,"reinitBtn" : btnReInit]))
}
func pushOnReinitButton() {
delegate?.reinitFilter()
delegate?.validateSelections()
}
func pushOnValidateButton() {
delegate?.validateSelections()
}
func pushOnCancelButton() {
delegate?.cancelFilterSelection()
}
}
| mit | f706b3c15cc29fe0feea27f2997c8df4 | 30.681818 | 203 | 0.67396 | 4.969697 | false | false | false | false |
IamAlchemist/DemoDynamicCollectionView | DemoDynamicCollectionView/SampleCalendarEvent.swift | 1 | 1003 | //
// SampleCalendarEvent.swift
// DemoDynamicCollectionView
//
// Created by Wizard Li on 1/11/16.
// Copyright © 2016 morgenworks. All rights reserved.
//
import UIKit
class SampleCalendarEvent : CalendarEvent {
static func randomEvent() -> CalendarEvent {
let randomID = Int(arc4random_uniform(10000))
let title = "\(randomID)"
let randomDay = Int(arc4random_uniform(7));
let randomStartHour = Int(arc4random_uniform(20))
let randomDuration = Int(arc4random_uniform(5)) + 1
return SampleCalendarEvent(title: title, day: randomDay, startHour: randomStartHour, durationInHours: randomDuration)
}
var title : String
var day : Int
var startHour : Int
var durationInHours : Int
init(title: String, day : Int, startHour : Int, durationInHours : Int){
self.title = title
self.day = day
self.startHour = startHour
self.durationInHours = durationInHours
}
} | mit | 93f79e918b908cc5c5779f7cdfdb4ec6 | 27.657143 | 125 | 0.648703 | 4.106557 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/Model/ReqModel/Valet.swift | 1 | 1049 | //
// Valet.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 18..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
import ObjectMapper
class Valet: Mappable {
var category1: CategoryP?
var category2: CategoryP?
var category3: CategoryP?
var category4: CategoryP?
var brand: BrandP?
var sellPrice: Float?
var signature: String?
var seller: Seller?
init?() {
category1 = CategoryP()
category2 = CategoryP()
category3 = CategoryP()
category4 = CategoryP()
brand = BrandP()
seller = Seller()
}
required init?(map: Map) {
}
func mapping(map: Map) {
category1 <- map["category1"]
category2 <- map["category2"]
category3 <- map["category3"]
category4 <- map["category4"]
brand <- map["brand"]
sellPrice <- map["sellPrice"]
signature <- map["signature"]
seller <- map["seller"]
}
}
| mit | 417013fa40cf5e1a16343d0be2500ad6 | 22.111111 | 55 | 0.547115 | 3.895131 | false | false | false | false |
rhwood/Doing-Time | Event/Event.swift | 1 | 7399 | //
// Event.swift
// Doing Time
//
// Created by Randall Wood on 2020-11-21.
//
// Copyright 2020 Randall Wood DBA Alexandria Software
//
// 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 SwiftUI
class Event: ObservableObject, Identifiable, Codable {
enum TodayIs: Int32 {
case complete = 0
case remaining = 1
case uncounted = 2
}
@Published var title: String
@Published var start: Date
@Published var end: Date
@Published var todayIs: TodayIs
@Published var includeEnd: Bool
@Published var showDates: Bool
@Published var showPercentages: Bool
@Published var showTotals: Bool
@Published var showRemainingDaysOnly: Bool
@Published var completedColor: Color
@Published var remainingColor: Color
@Published var backgroundColor: Color
let id: UUID
enum CodingKeys: String, CodingKey {
case title
case start
case end
case todayIs
case includeEnd
case showDates
case showPercentages
case showTotals
case showRemainingDaysOnly
case completedColor
case remainingColor
case backgroundColor
case id
}
init(title: String = "",
start: Date = Date(),
end: Date = Date(),
todayIs: TodayIs = .complete,
includeEnd: Bool = true,
showDates: Bool = true,
showPercentages: Bool = true,
showTotals: Bool = true,
showRemainingDaysOnly: Bool = true,
completedColor: Color = .green,
remainingColor: Color = .red,
backgroundColor: Color = .white,
id: UUID = UUID()) {
self.title = title
self.start = start
self.end = end
self.todayIs = todayIs
self.includeEnd = includeEnd
self.showDates = showDates
self.showPercentages = showPercentages
self.showTotals = showTotals
self.showRemainingDaysOnly = showRemainingDaysOnly
self.completedColor = completedColor
self.remainingColor = remainingColor
self.backgroundColor = backgroundColor
self.id = id
}
required init(from: Decoder) throws {
let values = try from.container(keyedBy: CodingKeys.self)
title = try values.decode(String.self, forKey: .title)
start = try values.decode(Date.self, forKey: .start)
end = try values.decode(Date.self, forKey: .end)
todayIs = Event.TodayIs(rawValue: try values.decode(Int32.self, forKey: .todayIs)) ?? .complete
includeEnd = try values.decode(Bool.self, forKey: .includeEnd)
showDates = try values.decode(Bool.self, forKey: .showDates)
showPercentages = try values.decode(Bool.self, forKey: .showPercentages)
showTotals = try values.decode(Bool.self, forKey: .showTotals)
showRemainingDaysOnly = try values.decode(Bool.self, forKey: .showRemainingDaysOnly)
completedColor = EventsModel.colorFromData(try values.decode(Data.self, forKey: .completedColor))
remainingColor = EventsModel.colorFromData(try values.decode(Data.self, forKey: .remainingColor))
backgroundColor = EventsModel.colorFromData(try values.decode(Data.self, forKey: .backgroundColor))
id = try values.decode(UUID.self, forKey: .id)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(title, forKey: .title)
try container.encode(start, forKey: .start)
try container.encode(end, forKey: .end)
try container.encode(todayIs.rawValue, forKey: .todayIs)
try container.encode(includeEnd, forKey: .includeEnd)
try container.encode(showDates, forKey: .showDates)
try container.encode(showPercentages, forKey: .showPercentages)
try container.encode(showTotals, forKey: .showTotals)
try container.encode(showRemainingDaysOnly, forKey: .showRemainingDaysOnly)
try container.encode(EventsModel.dataFromColor(completedColor), forKey: .completedColor)
try container.encode(EventsModel.dataFromColor(remainingColor), forKey: .remainingColor)
try container.encode(EventsModel.dataFromColor(backgroundColor), forKey: .backgroundColor)
try container.encode(id, forKey: .id)
}
var firstDay: Date {
Calendar.current.startOfDay(for: start)
}
var lastDay: Date {
let date = includeEnd ? Calendar.current.date(byAdding: .day, value: 1, to: end)! : end
// return 1 second before end of day
return Calendar.current.date(byAdding: .second, value: -1, to: Calendar.current.startOfDay(for: date))!
}
var totalDuration: Int {
get {
Calendar.current.dateComponents([.day], from: firstDay, to: lastDay).day! + 1
}
set {
end = Calendar.current.date(byAdding: .day, value: includeEnd ? newValue - 1 : newValue, to: firstDay)!
}
}
var totalDurationAsString: String {
get {
String(totalDuration)
}
set {
totalDuration = NumberFormatter().number(from: newValue)?.intValue ?? totalDuration
}
}
var completedDuration: Int {
let today = Calendar.current.startOfDay(for: Date())
if lastDay >= today && firstDay <= today {
let duration = Calendar.current.dateComponents([.day], from: firstDay, to: today).day!
if todayIs == .complete {
return duration + 1
} else {
return duration
}
} else if firstDay > today {
return 0
} else {
return totalDuration
}
}
var completedPercentage: Float {
Float(completedDuration) / Float(totalDuration)
}
var remainingDuration: Int {
let today = Calendar.current.startOfDay(for: Date())
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)!
if firstDay <= tomorrow && lastDay >= today {
let duration = Calendar.current.dateComponents([.day], from: lastDay, to: tomorrow).day! + 1
switch todayIs {
case .remaining:
return duration < totalDuration ? duration + 1 : totalDuration
case .complete:
return duration + completedDuration <= totalDuration ? duration : 0
default:
return duration
}
} else if lastDay < today {
return 0
} else {
return totalDuration
}
}
var remainingPercentage: Float {
Float(remainingDuration) / Float(totalDuration)
}
var todayPercentage: Float {
if todayIs == .uncounted {
return Float(1) / Float(totalDuration)
} else {
return 0
}
}
}
| mit | 7a6d5b0fd670d48d1e7df2cca94c795e | 36.75 | 115 | 0.634951 | 4.459916 | false | false | false | false |
jiecao-fm/SwiftTheme | Source/ThemeManager+Plist.swift | 3 | 2279 | //
// ThemeManager+Plist.swift
// SwiftTheme
//
// Created by Gesen on 16/9/18.
// Copyright © 2016年 Gesen. All rights reserved.
//
import UIKit
@objc extension ThemeManager {
public class func value(for keyPath: String) -> Any? {
return currentTheme?.value(forKeyPath: keyPath)
}
public class func string(for keyPath: String) -> String? {
guard let string = currentTheme?.value(forKeyPath: keyPath) as? String else {
print("SwiftTheme WARNING: Not found string key path: \(keyPath)")
return nil
}
return string
}
public class func number(for keyPath: String) -> NSNumber? {
guard let number = currentTheme?.value(forKeyPath: keyPath) as? NSNumber else {
print("SwiftTheme WARNING: Not found number key path: \(keyPath)")
return nil
}
return number
}
public class func dictionary(for keyPath: String) -> NSDictionary? {
guard let dict = currentTheme?.value(forKeyPath: keyPath) as? NSDictionary else {
print("SwiftTheme WARNING: Not found dictionary key path: \(keyPath)")
return nil
}
return dict
}
public class func color(for keyPath: String) -> UIColor? {
guard let rgba = string(for: keyPath) else { return nil }
guard let color = try? UIColor(rgba_throws: rgba) else {
print("SwiftTheme WARNING: Not convert rgba \(rgba) at key path: \(keyPath)")
return nil
}
return color
}
public class func image(for keyPath: String) -> UIImage? {
guard let imageName = string(for: keyPath) else { return nil }
if let filePath = currentThemePath?.URL?.appendingPathComponent(imageName).path {
guard let image = UIImage(contentsOfFile: filePath) else {
print("SwiftTheme WARNING: Not found image at file path: \(filePath)")
return nil
}
return image
} else {
guard let image = UIImage(named: imageName) else {
print("SwiftTheme WARNING: Not found image name at main bundle: \(imageName)")
return nil
}
return image
}
}
}
| mit | 54a1d1d71b9d624355030a9260344b78 | 32.970149 | 94 | 0.59051 | 4.811839 | false | false | false | false |
dedykuncoro/BlinkingLabel | Example/BlinkingLabel/ViewController.swift | 1 | 1278 | //
// ViewController.swift
// BlinkingLabel
//
// Created by Ujuizi Lab's on 08/27/2016.
// Copyright (c) 2016 Ujuizi Lab's. All rights reserved.
//
import UIKit
import BlinkingLabel
class ViewController: UIViewController {
var isBlinking = false
let blinkingLabel = BlinkingLabel(frame: CGRectMake(10, 20, 200, 30))
override func viewDidLoad() {
super.viewDidLoad()
// Setup the BlinkingLabel
blinkingLabel.text = "I blink!"
blinkingLabel.font = UIFont.systemFontOfSize(20)
view.addSubview(blinkingLabel)
blinkingLabel.startBlinking()
isBlinking = true
// Create a UIButton to toggle the blinking
let toggleButton = UIButton(frame: CGRectMake(10, 60, 125, 30))
toggleButton.setTitle("Toggle Blinking", forState: .Normal)
toggleButton.setTitleColor(UIColor.redColor(), forState: .Normal)
toggleButton.addTarget(self, action: "toggleBlinking", forControlEvents: .TouchUpInside)
view.addSubview(toggleButton)
}
func toggleBlinking() {
if (isBlinking) {
blinkingLabel.stopBlinking()
} else {
blinkingLabel.startBlinking()
}
isBlinking = !isBlinking
}
}
| mit | f1703d85bebec8e248a157520a6e240c | 28.045455 | 96 | 0.63928 | 4.768657 | false | false | false | false |
longjianjiang/BlogDemo | VCInteractiveNavigationAnimation/VCInteractiveNavigationAnimation/InteractiveTransition.swift | 1 | 1525 | //
// InteractiveTransition.swift
// VCInteractiveNavigationAnimation
//
// Created by longjianjiang on 2017/10/13.
// Copyright © 2017年 Jiang. All rights reserved.
//
import UIKit
class InteractiveTransition: UIPercentDrivenInteractiveTransition {
var navigationController: UINavigationController!
var transitionInProgress = false
func attachToViewController(viewController: UIViewController) {
navigationController = viewController.navigationController
setupGestureRecognizer(view: viewController.view)
}
private func setupGestureRecognizer(view: UIView) {
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(recognizer:)))
view.addGestureRecognizer(pan)
}
@objc func handlePanGesture(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: recognizer.view?.superview) // nivigation's view
var progress: CGFloat = abs(translation.x / 200.0)
progress = min(max(progress, 0.01), 0.99)
switch recognizer.state {
case .began:
transitionInProgress = true
navigationController.popViewController(animated: true)
case .changed:
update(progress)
case .cancelled, .ended:
if progress < 0.5 {
cancel()
} else {
finish()
}
transitionInProgress = false
default:
break
}
}
}
| apache-2.0 | d12e39cc8f87e66a01695947223dd994 | 30.061224 | 104 | 0.644547 | 5.340351 | false | false | false | false |