repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dvl/imagefy-ios
|
imagefy/Modules/Login/LoginInteractor.swift
|
1
|
1589
|
//
// LoginInteractor.swift
// imagefy
//
// Created by Guilherme Augusto on 21/05/16.
// Copyright © 2016 Alan M. Lira. All rights reserved.
//
import UIKit
import FBSDKLoginKit
class LoginInteractor: LoginInteractorInputProtocol, LoginServiceOutputProtocol {
var presenter: LoginInteractorOutputProtocol?
var service: LoginServiceProtocol?
func login(viewController: UIViewController) {
let login = FBSDKLoginManager()
login.logInWithReadPermissions(["public_profile", "email", "user_birthday", "user_hometown", "user_about_me", "user_photos"], fromViewController: viewController) { (result, error) in
guard error == nil else {
self.presenter?.didFail(.UnknowError)
return
}
if result.isCancelled {
self.presenter?.didFail(.Cancelled)
}
if((FBSDKAccessToken.currentAccessToken()) != nil){
let userId = FBSDKAccessToken.currentAccessToken().userID
let token = FBSDKAccessToken.currentAccessToken().tokenString
self.service?.login(userId, accessToken: token)
}
}
}
func getUserByKey(key: String) {
service?.user(key)
}
func didFail(error: LoginError) {
}
func didLogin(user: User) {
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
delegate.loggedUser = user
self.presenter?.didLogin(user)
}
}
|
mit
|
113b592d9c65d09a7b131e084ba597ca
| 28.981132 | 190 | 0.598237 | 5.206557 | false | false | false | false |
FlexMonkey/Filterpedia
|
Filterpedia/customFilters/CIKL_Sky.swift
|
1
|
4639
|
//
// CIKL_Sky.swift
// Filterpedia
//
// Created by Simon Gladman on 28/04/2016.
// Copyright © 2016 Simon Gladman. All rights reserved.
//
import CoreImage
class SimpleSky: CIFilter
{
var inputSunDiameter: CGFloat = 0.01
var inputAlbedo: CGFloat = 0.2
var inputSunAzimuth: CGFloat = 0.0
var inputSunAlitude: CGFloat = 1.0
var inputSkyDarkness: CGFloat = 1.25
var inputScattering: CGFloat = 10.0
var inputWidth: CGFloat = 640
var inputHeight: CGFloat = 640
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "Simple Sky",
"inputSunDiameter": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.01,
kCIAttributeDisplayName: "Sun Diameter",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputAlbedo": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.2,
kCIAttributeDisplayName: "Albedo",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputSunAzimuth": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Sun Azimuth",
kCIAttributeMin: -1,
kCIAttributeSliderMin: -1,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputSunAlitude": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Sun Alitude",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 10,
kCIAttributeType: kCIAttributeTypeScalar],
"inputSkyDarkness": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1.25,
kCIAttributeDisplayName: "Sky Darkness",
kCIAttributeMin: 0.1,
kCIAttributeSliderMin: 0.1,
kCIAttributeSliderMax: 2,
kCIAttributeType: kCIAttributeTypeScalar],
"inputScattering": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 10,
kCIAttributeDisplayName: "Scattering",
kCIAttributeMin: 1,
kCIAttributeSliderMin: 1,
kCIAttributeSliderMax: 20,
kCIAttributeType: kCIAttributeTypeScalar],
"inputWidth": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 640,
kCIAttributeDisplayName: "Width",
kCIAttributeMin: 1,
kCIAttributeSliderMin: 1,
kCIAttributeSliderMax: 1280,
kCIAttributeType: kCIAttributeTypeScalar],
"inputHeight": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 640,
kCIAttributeDisplayName: "Height",
kCIAttributeMin: 1,
kCIAttributeSliderMin: 1,
kCIAttributeSliderMax: 1280,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
let skyKernel: CIColorKernel =
{
let shaderPath = NSBundle.mainBundle().pathForResource("cikl_sky", ofType: "cikernel")
guard let path = shaderPath,
code = try? String(contentsOfFile: path),
kernel = CIColorKernel(string: code) else
{
fatalError("Unable to build Sky shader")
}
return kernel
}()
override var outputImage: CIImage?
{
let extent = CGRect(x: 0, y: 0, width: inputWidth, height: inputHeight)
let arguments = [inputWidth, inputHeight, inputSunDiameter, inputAlbedo, inputSunAzimuth, inputSunAlitude, inputSkyDarkness, inputScattering]
let final = skyKernel.applyWithExtent(extent, arguments: arguments)?.imageByCroppingToRect(extent)
return final
}
}
|
gpl-3.0
|
327a128f81faad67dd8c45c572d555dd
| 35.809524 | 149 | 0.567917 | 6.102632 | false | false | false | false |
abertelrud/swift-package-manager
|
Sources/PackageModel/IdentityResolver.swift
|
2
|
2787
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 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 the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import TSCBasic
// TODO: refactor this when adding registry support
public protocol IdentityResolver {
func resolveIdentity(for packageKind: PackageReference.Kind) throws -> PackageIdentity
func resolveIdentity(for url: URL) throws -> PackageIdentity
func resolveIdentity(for path: AbsolutePath) throws -> PackageIdentity
func mappedLocation(for location: String) -> String
}
public struct DefaultIdentityResolver: IdentityResolver {
let locationMapper: (String) -> String
public init(locationMapper: @escaping (String) -> String = { $0 }) {
self.locationMapper = locationMapper
}
public func resolveIdentity(for packageKind: PackageReference.Kind) throws -> PackageIdentity {
switch packageKind {
case .root(let path):
return try self.resolveIdentity(for: path)
case .fileSystem(let path):
return try self.resolveIdentity(for: path)
case .localSourceControl(let path):
return try self.resolveIdentity(for: path)
case .remoteSourceControl(let url):
return try self.resolveIdentity(for: url)
case .registry(let identity):
return identity
}
}
public func resolveIdentity(for url: URL) throws -> PackageIdentity {
let location = self.mappedLocation(for: url.absoluteString)
if let path = try? AbsolutePath(validating: location) {
return PackageIdentity(path: path)
} else if let url = URL(string: location) {
return PackageIdentity(url: url)
} else {
throw StringError("invalid mapped location: \(location) for \(url)")
}
}
public func resolveIdentity(for path: AbsolutePath) throws -> PackageIdentity {
let location = self.mappedLocation(for: path.pathString)
if let path = try? AbsolutePath(validating: location) {
return PackageIdentity(path: path)
} else if let url = URL(string: location) {
return PackageIdentity(url: url)
} else {
throw StringError("invalid mapped location: \(location) for \(path)")
}
}
public func mappedLocation(for location: String) -> String {
return self.locationMapper(location)
}
}
|
apache-2.0
|
6987d76f84ed364927afebb8458f8eb2
| 38.253521 | 99 | 0.632939 | 4.950266 | false | false | false | false |
beeth0ven/TFBubbleItUp
|
Pod/Classes/TFBubbleItUpViewFlowLayout.swift
|
2
|
2208
|
//
// TFContactViewFlowLayout.swift
// TFContactCollection
//
// Created by Aleš Kocur on 12/09/15.
// Copyright © 2015 The Funtasty. All rights reserved.
//
import UIKit
class TFBubbleItUpViewFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
// Let FlowLayout give us atributes
guard let array = super.layoutAttributesForElementsInRect(rect) else {
return nil
}
let newArray = array.map { (element) -> UICollectionViewLayoutAttributes in
let attributes = element.copy() as! UICollectionViewLayoutAttributes
if (attributes.representedElementKind == nil) {
let indexPath = attributes.indexPath
// Give them the right frame
attributes.frame = (self.layoutAttributesForItemAtIndexPath(indexPath)?.frame)!
}
return attributes
}
return newArray
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)!.copy() as! UICollectionViewLayoutAttributes
var frame = attributes.frame
if (attributes.frame.origin.x <= self.sectionInset.left) {
return attributes
}
if indexPath.item == 0 {
frame.origin.x = self.sectionInset.left
} else {
let previousIndexPath = NSIndexPath(forItem: indexPath.item - 1, inSection: indexPath.section)
let previousAttributes = self.layoutAttributesForItemAtIndexPath(previousIndexPath)!
if (attributes.frame.origin.y > previousAttributes.frame.origin.y) {
frame.origin.x = self.sectionInset.left
} else {
frame.origin.x = CGRectGetMaxX(previousAttributes.frame) + self.minimumInteritemSpacing
}
}
attributes.frame = frame;
return attributes;
}
}
|
mit
|
ed2db0e0c5826ce2cffb3d9f94351e38
| 32.938462 | 121 | 0.614234 | 5.914209 | false | false | false | false |
jeffreybergier/WaterMe2
|
WaterMe/Frameworks/Datum/Datum/Wrapper/ReminderVessel/RLM_ReminderVesselWrapper.swift
|
1
|
3353
|
//
// RLM_ReminderVesselWrapper.swift
// Datum
//
// Created by Jeffrey Bergier on 2020/05/20.
// Copyright © 2020 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe 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.
//
// WaterMe 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 WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import RealmSwift
internal struct RLM_ReminderVesselWrapper: ReminderVessel {
internal let wrappedObject: RLM_ReminderVessel
internal init(_ wrappedObject: RLM_ReminderVessel) {
self.wrappedObject = wrappedObject
}
public var uuid: String { self.wrappedObject.uuid }
public var displayName: String? { self.wrappedObject.displayName }
public var icon: ReminderVesselIcon? { self.wrappedObject.icon }
public var kind: ReminderVesselKind { self.wrappedObject.kind }
public var isModelComplete: ModelCompleteError? { self.wrappedObject.isModelComplete }
public var shortLabelSafeDisplayName: String? { self.wrappedObject.shortLabelSafeDisplayName }
}
extension RLM_ReminderVesselWrapper {
func observe(_ block: @escaping (ReminderVesselChange) -> Void) -> ObservationToken {
return self.wrappedObject.observe { realmChange in
switch realmChange {
case .error:
block(.error(.readError))
case .change(let properties):
let changedDisplayName = RLM_ReminderVessel.propertyChangesContainDisplayName(properties)
let changedIconEmoji = RLM_ReminderVessel.propertyChangesContainIconEmoji(properties)
let changedReminders = RLM_ReminderVessel.propertyChangesContainReminders(properties)
let changedPointlessBloop = RLM_ReminderVessel.propertyChangesContainPointlessBloop(properties)
block(.change(.init(changedDisplayName: changedDisplayName,
changedIconEmoji: changedIconEmoji,
changedReminders: changedReminders,
changedPointlessBloop: changedPointlessBloop)))
case .deleted:
block(.deleted)
}
}
}
func observeReminders(_ block: @escaping (ReminderCollectionChange) -> Void) -> ObservationToken {
return self.wrappedObject.reminders.observe { realmChange in
switch realmChange {
case .initial(let data):
block(.initial(data: AnyCollection(RLM_ReminderCollection(AnyRealmCollection(data)))))
case .update(_, let deletions, let insertions, let modifications):
block(.update(.init(insertions: insertions, deletions: deletions, modifications: modifications)))
case .error:
block(.error(error: .readError))
}
}
}
}
|
gpl-3.0
|
dff949eb9979a6f3216f9778ea7d62ab
| 44.917808 | 113 | 0.676313 | 4.980684 | false | false | false | false |
powerytg/Accented
|
Accented/UI/Common/Components/Drawer/DrawerPresentationController.swift
|
1
|
6585
|
//
// DrawerPresentationController.swift
// Accented
//
// Created by You, Tiangong on 6/17/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
class DrawerPresentationController: UIPresentationController, UIViewControllerTransitioningDelegate {
// Animation context
private var animationContext : DrawerAnimationContext
// Curtain view
private var curtainView : UIView!
// Open animator
var openAnimator : DrawerOpenAnimator?
// Close animator
var dismissAnimator : DrawerDismissAnimator?
// Interactive open animator
var interactiveOpenAnimator : DrawerOpenAnimator?
// Interactive close animator
var interactiveDismissAnimator : DrawerDismissAnimator?
// Dismissal gesture controller
private var dismissGestureController : DrawerDismissGestureController?
required init(animationContext : DrawerAnimationContext) {
self.animationContext = animationContext
super.init(presentedViewController: animationContext.content, presenting: animationContext.container!)
// Create curtain view
if ThemeManager.sharedInstance.currentTheme.drawerUseBlurBackground {
let blurView = BlurView(frame: CGRect.zero)
curtainView = blurView
} else {
curtainView = UIView()
}
animationContext.presentationController = self
animationContext.backgroundView = curtainView
// Animators
self.openAnimator = DrawerOpenAnimator(animationContext : animationContext)
self.dismissAnimator = DrawerDismissAnimator(animationContext : animationContext)
self.interactiveOpenAnimator = DrawerOpenAnimator(animationContext : animationContext)
self.interactiveDismissAnimator = DrawerDismissAnimator(animationContext : animationContext)
// Initialization
animationContext.content.modalPresentationStyle = .custom
animationContext.content.transitioningDelegate = self
}
//MARK: UIPresentationController
override func presentationTransitionWillBegin() {
// Setup curtain view
containerView!.addSubview(curtainView)
curtainView.isUserInteractionEnabled = true
curtainView.alpha = 0
curtainView.backgroundColor = UIColor.black
curtainView.translatesAutoresizingMaskIntoConstraints = false
curtainView.widthAnchor.constraint(equalTo: self.containerView!.widthAnchor).isActive = true
curtainView.heightAnchor.constraint(equalTo: self.containerView!.heightAnchor).isActive = true
// Setup drawer
let contentView = presentedViewController.view
containerView!.addSubview(contentView!)
contentView?.translatesAutoresizingMaskIntoConstraints = false
contentView?.widthAnchor.constraint(equalToConstant: animationContext.drawerSize.width).isActive = true
contentView?.heightAnchor.constraint(equalToConstant: animationContext.drawerSize.height).isActive = true
switch animationContext.anchor {
case .left:
contentView?.leadingAnchor.constraint(equalTo: containerView!.leadingAnchor).isActive = true
case .right:
contentView?.trailingAnchor.constraint(equalTo: containerView!.trailingAnchor).isActive = true
case .bottom:
contentView?.bottomAnchor.constraint(equalTo: containerView!.bottomAnchor).isActive = true
}
switch animationContext.anchor {
case .left:
contentView?.transform = CGAffineTransform(translationX: -(contentView?.bounds.width)!, y: 0)
case .right:
contentView?.transform = CGAffineTransform(translationX: (contentView?.bounds.width)!, y: 0)
case .bottom:
contentView?.transform = CGAffineTransform(translationX: 0, y: (contentView?.bounds.height)!)
}
// Perform the curtain view animation along with the transition
let curtainAlpha = animationContext.configurations.curtainAlpha
presentedViewController.transitionCoordinator?.animate(alongsideTransition: { [weak self] (context) in
self?.curtainView.alpha = curtainAlpha
}, completion: nil)
}
override func presentationTransitionDidEnd(_ completed: Bool) {
if completed {
// Reset the animation context to non-interactive
// This is important as the interactive should only be set after a gesture detection
animationContext.interactive = false
// Install dismissal gestures
dismissGestureController = DrawerDismissGestureController(animationContext: animationContext)
dismissGestureController!.installDismissalGestures()
} else {
curtainView.removeFromSuperview()
}
}
override func dismissalTransitionWillBegin() {
// Perform the curtain view animation along with the transition
presentedViewController.transitionCoordinator?.animate(alongsideTransition: { [weak self] (context) in
self?.curtainView.alpha = 0
}, completion: nil)
}
override func dismissalTransitionDidEnd(_ completed: Bool) {
if completed {
curtainView.removeFromSuperview()
} else {
curtainView.alpha = animationContext.configurations.curtainAlpha
}
}
//MARK: UIViewControllerTransitioningDelegate
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self.openAnimator
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self.dismissAnimator
}
func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return animationContext.interactive ? self.interactiveOpenAnimator : nil
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return animationContext.interactive ? self.interactiveDismissAnimator : nil
}
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return self
}
}
|
mit
|
d09174a6b118eb242bc1b12799ff9200
| 41.753247 | 170 | 0.708536 | 6.223062 | false | false | false | false |
krizhanovskii/KKCircularProgressView
|
Example/Tests/Tests.swift
|
1
|
1189
|
// https://github.com/Quick/Quick
import Quick
import Nimble
import KKCircularProgressView
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
|
mit
|
99bdc3f44559322a138e40d4b6c723a7
| 22.66 | 63 | 0.370245 | 5.528037 | false | false | false | false |
a1exb1/ABToolKit-pod
|
Pod/Classes/CompresJSON/Encryption/Encryptor.swift
|
1
|
1300
|
//
// Encryptor.swift
// EncryptionTests3
//
// Created by Alex Bechmann on 08/05/2015.
// Copyright (c) 2015 Alex Bechmann. All rights reserved.
//
import UIKit
private let kAnalyzer = JavaScriptAnalyzer.sharedInstance()
private let kScriptPath = "encryptor_compressor"
public class Encryptor: NSObject {
public class func encrypt(str: String, key: String) -> String {
Encryptor.printErrorIfEncryptionKeyIsNotSet()
kAnalyzer.loadScript(kScriptPath)
let encrypted = kAnalyzer.executeJavaScriptFunction("Encrypt", args: [str, key]).toString()
return encrypted.base64Encode()
}
public class func decrypt(str: String, key: String) -> String {
Encryptor.printErrorIfEncryptionKeyIsNotSet()
kAnalyzer.loadScript(kScriptPath)
let decoded = str.base64Decode()
return kAnalyzer.executeJavaScriptFunction("Decrypt", args: [decoded, key]).toString()
}
public class func printErrorIfEncryptionKeyIsNotSet() {
if CompresJSON.sharedInstance().settings.encryptionKey == "" {
println("Encryption key not set: add to appdelegate: CompresJSON.sharedInstance().settings.encryptionKey = xxxx")
}
}
}
|
mit
|
10b09a92fadd990fb2ad3e3a05e705f7
| 27.888889 | 125 | 0.653846 | 4.659498 | false | false | false | false |
yidahis/ShopingCart
|
ShopingCart/ShopingCartViewCell.swift
|
1
|
3921
|
//
// asd.swift
// ShopingCart
//
// Created by zhouyi on 2017/9/18.
// Copyright © 2017年 NewBornTown, Inc. All rights reserved.
//
import UIKit
typealias clickAction = (String,String) -> Void
class ShopingCartViewCell: UITableViewCell {
var tipLabel: UILabel = UILabel()
var lineView: UIView = UIView()
var buttonTapAction: clickAction?
var model: SpecKeyVaules!{
didSet{
tipLabel.text = model.key
var index = 10000
//如果没有button子视图就创建,否则直接操作
if (contentView.viewWithTag(10000) != nil) {
contentView.subviews.forEach({ (view) in
if let button = view as? UIButton{
var selectedItem = SpecItem()
model.vaules.forEach({ (item) in//取出选中的item
if item.isSelected == true {
selectedItem = item
}
})
//如果选择的item.content 等于 当前button的title 时,设置这个button为选中
if let buttonTitle = button.titleLabel?.text, buttonTitle == selectedItem.content {
button.isSelected = true
}else{
button.isSelected = false
}
}
})
return
}
Array(model.vaules).forEach { (item) in
let button = UIButton()
button.setTitle(item.content, for: UIControlState.normal)
button.isSelected = item.isSelected
button.setTitleColor(UIColor.red, for: UIControlState.selected)
button.setTitleColor(UIColor.white, for: UIControlState.normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button.backgroundColor = UIColor.gray
button.titleLabel?.textAlignment = .center
button.addTarget(self, action: #selector(click), for: UIControlEvents.touchUpInside)
contentView.addSubview(button)
button.tag = index
index += 1
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
tipLabel.frame = CGRect(x: XSpace, y: XSpace, width: 100, height: 16)
lineView.frame = CGRect(x: 0, y: contentView.height - 1, width: contentView.width, height: 1)
let maxX = self.width - XSpace
var minY = tipLabel.bottom + XSpace
var minX = XSpace
contentView.subviews.forEach { (view) in
if let button = view as? UIButton, let width = button.titleLabel?.text?.stringWidthWithSpace(fontSize: 14){
if minX + width + XSpace > maxX {
minX = XSpace
minY = minY + 28 + XSpace
}
button.frame = CGRect(x: minX, y: minY, width: width, height: 28)
minX = button.right + XSpace
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
contentView.addSubview(tipLabel)
contentView.addSubview(lineView)
tipLabel.font = UIFont.systemFont(ofSize: 14)
tipLabel.tag = 1000
lineView.backgroundColor = UIColor.groupTableViewBackground
}
@objc func click(sender: UIButton) {
print(sender.tag)
if let text = sender.titleLabel?.text {
buttonTapAction?(tipLabel.text! ,text)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
159cbb9955337853c284c040ba895a38
| 35.533333 | 119 | 0.535193 | 5.007833 | false | false | false | false |
colemancda/SwiftObserverSet
|
ObserverSet/ObserverSet.swift
|
1
|
2395
|
//
// ObserverSet.swift
// ObserverSet
//
// Created by Mike Ash on 1/22/15.
// Copyright (c) 2015 Mike Ash. All rights reserved.
//
import Dispatch
public class ObserverSetEntry<Parameters> {
private weak var object: AnyObject?
private let f: AnyObject -> Parameters -> Void
private init(object: AnyObject, f: AnyObject -> Parameters -> Void) {
self.object = object
self.f = f
}
}
public class ObserverSet<Parameters>: CustomStringConvertible {
// Locking support
private var queue = dispatch_queue_create("com.mikeash.ObserverSet", nil)
private func synchronized(f: Void -> Void) {
dispatch_sync(queue, f)
}
// Main implementation
private var entries: [ObserverSetEntry<Parameters>] = []
public init() {}
public func add<T: AnyObject>(object: T, _ f: T -> Parameters -> Void) -> ObserverSetEntry<Parameters> {
let entry = ObserverSetEntry<Parameters>(object: object, f: { f($0 as! T) })
synchronized {
self.entries.append(entry)
}
return entry
}
public func add(f: Parameters -> Void) -> ObserverSetEntry<Parameters> {
return self.add(self, { ignored in f })
}
public func remove(entry: ObserverSetEntry<Parameters>) {
synchronized {
self.entries = self.entries.filter{ $0 !== entry }
}
}
public func notify(parameters: Parameters) {
var toCall: [Parameters -> Void] = []
synchronized {
for entry in self.entries {
if let object: AnyObject = entry.object {
toCall.append(entry.f(object))
}
}
self.entries = self.entries.filter{ $0.object != nil }
}
for f in toCall {
f(parameters)
}
}
// Printable
public var description: String {
var entries: [ObserverSetEntry<Parameters>] = []
synchronized {
entries = self.entries
}
let strings = entries.map{
entry in
(entry.object === self
? "\(entry.f)"
: "\(entry.object) \(entry.f)")
}
let joined = strings.joinWithSeparator(", ")
return "\(Mirror(reflecting: self)): (\(joined))"
}
}
|
bsd-3-clause
|
216d16e695e6120795a41e98b5109c31
| 25.032609 | 108 | 0.544468 | 4.544592 | false | false | false | false |
Donkey-Tao/SinaWeibo
|
SinaWeibo/SinaWeibo/Classes/Message/TFMessageViewController.swift
|
1
|
2981
|
//
// TFMessageViewController.swift
// SinaWeibo
//
// Created by Donkey-Tao on 2016/10/20.
// Copyright © 2016年 http://taofei.me All rights reserved.
//
import UIKit
class TFMessageViewController: TFBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
visitorView.setupVisitorViewInfo(iconName: "visitordiscover_image_message", tip: "登录后,别人评论你的微薄,给你发信息,都会在这里收到")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
8d6439b9e32962367e2be9719cf2ab31
| 31.153846 | 136 | 0.667122 | 5.097561 | false | false | false | false |
gurenupet/hah-auth-ios-swift
|
hah-auth-ios-swift/hah-auth-ios-swift/UIViewController+Base.swift
|
1
|
2926
|
//
// UIViewController+Base.swift
// hah-auth-ios-swift
//
// Created by Anton Antonov on 06.07.17.
// Copyright © 2017 KRIT. All rights reserved.
//
import UIKit
import RNNotificationView
extension UIViewController {
func showErrorWith(title: String, message: String) {
let alertController = JHTAlertController(title: title, message: message, preferredStyle: .alert, iconImage: UIImage(named: "Alert Sad"))
alertController.hasRoundedCorners = true
alertController.dividerColor = UIColor.white
//Заголовок
let titleFont = UIFont(name: Fonts.Medium.rawValue, size: 17.0)
let titleColor = UIColor.colorFrom(hex: "333333")
alertController.titleFont = titleFont
alertController.titleTextColor = titleColor
alertController.titleViewBackgroundColor = UIColor.white
//Текст
let messageFont = UIFont(name: Fonts.Regular.rawValue, size: 15.0)
let messageColor = UIColor.colorFrom(hex: "333333")
alertController.messageFont = messageFont
alertController.messageTextColor = messageColor
alertController.alertBackgroundColor = UIColor.white
//Кнопка
let cancelText = NSLocalizedString("Alert.Button.Cancel", comment: "")
let cancelAction = JHTAlertAction(title: cancelText, style: .cancel, bgColor: UIColor.colorFrom(hex: "ff9b00"), handler: nil)
let buttonFont = UIFont(name: Fonts.Medium.rawValue, size: 17.0)!
alertController.setButtonFontFor(.cancel, to: buttonFont)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
func showAlertWith(title: String, message: String, complition: @escaping () -> ()) {
let aa = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelActionButton = NSLocalizedString("Auth.Success.Close", comment: "")
let cancelAction = UIAlertAction(title: cancelActionButton, style: .default, handler: {(alert: UIAlertAction) in
complition()
})
aa.addAction(cancelAction)
self.present(aa, animated: true, completion: nil)
}
func showNotificationErrorWith(title: String, message: String, duration: TimeInterval) {
RNNotificationView.show(withImage: UIImage(named: "Notification Warning"), title: title, message: message, duration: duration, iconSize: CGSize(width: 22, height: 22), onTap: nil)
}
///Проверка наличия соединения с интернетом
func hasConnectivity() -> Bool {
let reachability: Reachability = Reachability.forInternetConnection()
let networkStatus: Int = reachability.currentReachabilityStatus().rawValue
return networkStatus != 0
}
}
|
mit
|
d8cede2f2d26509caa3795d05a56530c
| 39.985714 | 187 | 0.671663 | 4.821849 | false | false | false | false |
brightdigit/tubeswift
|
TubeSwift/PlaylistClient.swift
|
1
|
2802
|
//
// PlaylistClient.swift
// TubeSwift
//
// Created by Leo G Dion on 4/29/15.
// Copyright (c) 2015 Leo G Dion. All rights reserved.
//
let _dateFormatter = { ()->NSDateFormatter in
let __ = NSDateFormatter()
__.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return __
}()
public struct PlaylistSnippet {
public let publishedAt:NSDate
public let channelId: String?
public let title: String
public let description: String
public let thumbnails:[String:Thumbnail]
public let channelTitle:String?
public let tags:[String]
public init?(result: [String:AnyObject]?) {
if let publishAtStr = result?["publishedAt"] as? String,
let publishedAt = _dateFormatter.dateFromString(publishAtStr),
let title = result?["title"] as? String,
let description = result?["description"] as? String,
let thumbnails = Thumbnail.Set((result?["thumbnails"] as? [String:[String:AnyObject]])) {
self.publishedAt = publishedAt
self.channelId = result?["channelId"] as? String
self.title = title
self.description = description
self.thumbnails = thumbnails
self.channelTitle = result?["channelTitle"] as? String
self.tags = result?["tags"] as? [String] ?? [String]()
} else {
return nil
}
}
// "publishedAt": datetime,
// "channelId": string,
// "title": string,
// "description": string,
// "thumbnails": {
// (key): {
// "url": string,
// "width": unsigned integer,
// "height": unsigned integer
// }
// },
// "channelTitle": string,
// "tags": [
// string
// ]
}
public struct Playlist {
public let etag:String
public let id:String
//public let contentDetails:ContentDetails
public let kind:YouTubeKind = YouTubeKind.Playlist
public let snippet:PlaylistSnippet
public init?(result: [String:AnyObject]) {
if let etag = result["etag"] as? String,
let id = result["id"] as? String,
let snippet = PlaylistSnippet(result: result["snippet"] as? [String:AnyObject]) {
self.etag = etag
self.id = id
self.snippet = snippet
} else {
return nil
}
}
}
public class PlaylistClient: NSObject {
public let client: TubeSwiftClient
public init (client: TubeSwiftClient) {
self.client = client
}
public func list (query: ResourceQuery, completion: (NSURLRequest, NSURLResponse?, Response<Playlist>?, NSError?) -> Void) {
request(.GET, "https://www.googleapis.com/youtube/v3/playlists", parameters: query.parameters).responseJSON(options: .allZeros) { (request, response, result, error) -> Void in
if let aError = error {
completion(request, response, nil, aError)
} else if let clRes = Response<Playlist>(kind: YouTubeKind.PlaylistListResponse,result: result, itemFactory: {Playlist(result: $0)}) {
completion(request, response, clRes, nil)
} else {
completion(request, response, nil, NSError())
}
}
}
}
|
mit
|
1d340af10a0f3df915cd3cf0451a7442
| 28.494737 | 177 | 0.685939 | 3.454994 | false | false | false | false |
chordsNcode/jsonperf
|
Pods/JSONCodable/JSONCodable/JSONEncodable.swift
|
2
|
11775
|
//
// JSONEncodable.swift
// JSONCodable
//
// Created by Matthew Cheok on 17/7/15.
// Copyright © 2015 matthewcheok. All rights reserved.
//
// Encoding Errors
public enum JSONEncodableError: Error, CustomStringConvertible {
case incompatibleTypeError(
elementType: Any.Type
)
case arrayIncompatibleTypeError(
elementType: Any.Type
)
case dictionaryIncompatibleTypeError(
elementType: Any.Type
)
case childIncompatibleTypeError(
key: String,
elementType: Any.Type
)
case transformerFailedError(
key: String
)
public var description: String {
switch self {
case let .incompatibleTypeError(elementType: elementType):
return "JSONEncodableError: Incompatible type \(elementType)"
case let .arrayIncompatibleTypeError(elementType: elementType):
return "JSONEncodableError: Got an array of incompatible type \(elementType)"
case let .dictionaryIncompatibleTypeError(elementType: elementType):
return "JSONEncodableError: Got an dictionary of incompatible type \(elementType)"
case let .childIncompatibleTypeError(key: key, elementType: elementType):
return "JSONEncodableError: Got incompatible type \(elementType) for key \(key)"
case let .transformerFailedError(key: key):
return "JSONEncodableError: Transformer failed for key \(key)"
}
}
}
// Struct -> Dictionary
public protocol JSONEncodable {
func toJSON() throws -> Any
}
public extension JSONEncodable {
func toJSON() throws -> Any {
let mirror = Mirror(reflecting: self)
#if !swift(>=3.0)
guard let style = mirror.displayStyle where style == .Struct || style == .Class else {
throw JSONEncodableError.IncompatibleTypeError(elementType: self.dynamicType)
}
#else
guard let style = mirror.displayStyle , style == .`struct` || style == .`class` else {
throw JSONEncodableError.incompatibleTypeError(elementType: type(of: self))
}
#endif
return try JSONEncoder.create { encoder in
// loop through all properties (instance variables)
for (labelMaybe, valueMaybe) in mirror.children {
guard let label = labelMaybe else {
continue
}
let value: Any
// unwrap optionals
if let v = valueMaybe as? JSONOptional {
guard let unwrapped = v.wrapped else {
continue
}
value = unwrapped
}
else {
value = valueMaybe
}
switch (value) {
case let value as JSONEncodable:
try encoder.encode(value, key: label)
case let value as JSONArray:
try encoder.encode(value, key: label)
case let value as JSONDictionary:
try encoder.encode(value, key: label)
default:
throw JSONEncodableError.childIncompatibleTypeError(key: label, elementType: type(of: value))
}
}
}
}
}
public extension Array { //where Element: JSONEncodable {
private var wrapped: [Any] { return self.map{$0} }
public func toJSON() throws -> Any {
var results: [Any] = []
for item in self.wrapped {
if let item = item as? JSONEncodable {
results.append(try item.toJSON())
}
else {
throw JSONEncodableError.arrayIncompatibleTypeError(elementType: type(of: item))
}
}
return results
}
}
// Dictionary convenience methods
public extension Dictionary {//where Key: String, Value: JSONEncodable {
public func toJSON() throws -> Any {
var result: [String: Any] = [:]
for (k, item) in self {
if let item = item as? JSONEncodable {
result[String(describing:k)] = try item.toJSON()
}
else {
throw JSONEncodableError.dictionaryIncompatibleTypeError(elementType: type(of: item))
}
}
return result
}
}
// JSONEncoder - provides utility methods for encoding
public class JSONEncoder {
var object = JSONObject()
public static func create(_ setup: (_ encoder: JSONEncoder) throws -> Void) rethrows -> JSONObject {
let encoder = JSONEncoder()
try setup(encoder)
return encoder.object
}
private func update(object: JSONObject, keys: [String], value: Any) -> JSONObject {
if keys.isEmpty {
return object
}
var newObject = object
var newKeys = keys
let firstKey = newKeys.removeFirst()
if newKeys.count > 0 {
let innerObject = object[firstKey] as? JSONObject ?? JSONObject()
newObject[firstKey] = update(object: innerObject, keys: newKeys, value: value)
} else {
newObject[firstKey] = value
}
return newObject
}
/*
Note:
There is some duplication because methods with generic constraints need to
take a concrete type conforming to the constraint are unable to take a parameter
typed to the protocol. Hence we need non-generic versions so we can cast from
Any to JSONEncodable in the default implementation for toJSON().
*/
// JSONEncodable
public func encode<Encodable: JSONEncodable>(_ value: Encodable, key: String) throws {
let result = try value.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
fileprivate func encode(_ value: JSONEncodable, key: String) throws {
let result = try value.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// JSONEncodable?
public func encode(_ value: JSONEncodable?, key: String) throws {
guard let actual = value else {
return
}
let result = try actual.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// Enum
public func encode<Enum: RawRepresentable>(_ value: Enum, key: String) throws {
guard let compatible = value.rawValue as? JSONCompatible else {
return
}
let result = try compatible.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// Enum?
public func encode<Enum: RawRepresentable>(_ value: Enum?, key: String) throws {
guard let actual = value else {
return
}
guard let compatible = actual.rawValue as? JSONCompatible else {
return
}
let result = try compatible.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [JSONEncodable]
public func encode<Encodable: JSONEncodable>(_ array: [Encodable], key: String) throws {
guard array.count > 0 else {
return
}
let result = try array.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
public func encode(_ array: [JSONEncodable], key: String) throws {
guard array.count > 0 else {
return
}
let result = try array.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
fileprivate func encode(_ array: JSONArray, key: String) throws {
guard array.count > 0 && array.elementsAreJSONEncodable() else {
return
}
let encodable = array.elementsMadeJSONEncodable()
let result = try encodable.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [JSONEncodable]?
public func encode<Encodable: JSONEncodable>(_ value: [Encodable]?, key: String) throws {
guard let actual = value else {
return
}
guard actual.count > 0 else {
return
}
let result = try actual.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [Enum]
public func encode<Enum: RawRepresentable>(_ value: [Enum], key: String) throws {
guard value.count > 0 else {
return
}
let result = try value.flatMap {
try ($0.rawValue as? JSONCompatible)?.toJSON()
}
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [Enum]?
public func encode<Enum: RawRepresentable>(_ value: [Enum]?, key: String) throws {
guard let actual = value else {
return
}
guard actual.count > 0 else {
return
}
let result = try actual.flatMap {
try ($0.rawValue as? JSONCompatible)?.toJSON()
}
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [String:JSONEncodable]
public func encode<Encodable: JSONEncodable>(_ dictionary: [String:Encodable], key: String) throws {
guard dictionary.count > 0 else {
return
}
let result = try dictionary.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
public func encode(_ dictionary: [String:JSONEncodable], key: String) throws {
guard dictionary.count > 0 else {
return
}
let result = try dictionary.toJSON()
object[key] = result
}
fileprivate func encode(_ dictionary: JSONDictionary, key: String) throws {
guard dictionary.count > 0 && dictionary.valuesAreJSONEncodable() else {
return
}
let encodable = dictionary.valuesMadeJSONEncodable()
let result = try encodable.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// [String:JSONEncodable]?
public func encode<Encodable: JSONEncodable>(_ value: [String:Encodable]?, key: String) throws {
guard let actual = value else {
return
}
guard actual.count > 0 else {
return
}
let result = try actual.toJSON()
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// JSONTransformable
public func encode<EncodedType, DecodedType>(_ value: DecodedType, key: String, transformer: JSONTransformer<EncodedType, DecodedType>) throws {
guard let result = transformer.encoding(value) else {
throw JSONEncodableError.transformerFailedError(key: key)
}
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
// JSONTransformable?
public func encode<EncodedType, DecodedType>(_ value: DecodedType?, key: String, transformer: JSONTransformer<EncodedType, DecodedType>) throws {
guard let actual = value else {
return
}
guard let result = transformer.encoding(actual) else {
return
}
object = update(object: object, keys: key.components(separatedBy: "."), value: result)
}
}
|
mit
|
c527c1fb94848075eb5e0c006d3c413b
| 34.357357 | 149 | 0.586886 | 5.003825 | false | false | false | false |
CoderZhuXH/XHTabBarSwift
|
XHTabBarExampleSwift/AppDelegate.swift
|
1
|
3923
|
//
// AppDelegate.swift
// XHTabBarExampleSwift
//
// Created by xiaohui on 16/8/8.
// Copyright © 2016年 CoderZhuXH. All rights reserved.
// 代码地址:https://github.com/CoderZhuXH/XHTabBarSwift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame:UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
/*
控制器name数组
*/
let controllerArray = ["MainVC","MsgVC","FriendVC","MeVC"]
/*
title数组
*/
let titleArray = ["首页","消息","朋友","我的"]
/*
默认图片数组
*/
let imageArray = ["home_tabbar","msg_tabbar","friend_tabbar","me_tabbar"]
/*
选中图片数组
*/
let selImageArray = ["home_tabbar_sel","msg_tabbar_sel","friend_tabbar_sel","me_tabbar_sel"]
/*
tabbar高度最小值49.0, 传nil或<49.0均按49.0处理
*/
let height = CGFloat(49)
/*
创建tabBarController
*/
let tabBarController = XHTabBar(controllerArray:controllerArray,titleArray: titleArray,imageArray: imageArray,selImageArray: selImageArray,height:height)
/**
* 设为根控制器
*/
window?.rootViewController = tabBarController
/*
设置数字角标(可选)
*/
tabBarController.showBadgeMark(100, index: 1)
/*
设置小红点(可选)
*/
tabBarController.showPointMarkIndex(2)
/*
不显示小红点/数字角标(可选)
*/
//tabBarController.hideMarkIndex(3)
/*
手动切换tabBarController 显示到指定控制器(可选)
*/
//tabBarController.showControllerIndex(3)
window?.makeKeyAndVisible()
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
2fd0d41ef9a91e163457ff3e417965e1
| 34.6 | 285 | 0.648208 | 5.071913 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet
|
GLFramework/SoundGenerator.swift
|
1
|
1229
|
//
// SoundGenerator.swift
// SwiftGL
//
// Created by jerry on 2017/1/8.
// Copyright © 2017年 Jerry Chan. All rights reserved.
//
import Foundation
import AudioKit
public class SoundGenerator{
public init()
{
oscillator = AKOscillator()
AudioKit.output = oscillator
AudioKit.start()
/*
do{
let pencil = try AKAudioFile(readFileName: "pencil.aiff")
try audioPlayer = AKAudioPlayer(file: pencil, looping: true, completionHandler: nil)
}
catch
{
}*/
//audioPlayer.play()
}
var oscillator:AKOscillator
public func start()
{
oscillator.start()
}
public func play(point:PaintPoint)
{
oscillator.amplitude = Double(point.force)// random(0.5, 1)
let v = Int(point.velocity.length*20)/20
oscillator.frequency = Double(v)*20 + 360.0// random(220, 880)
//oscillator.start()
}
public func stop()
{
oscillator.stop()
}
deinit {
AudioKit.stop()
}
var audioPlayer:AKAudioPlayer!
public func playSOund(){
}
func playBlaster() {
}
}
|
mit
|
9cacf03a69b1e8069faaf8ae60dc9416
| 19.433333 | 96 | 0.547308 | 4.410072 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet
|
SwiftGL-Demo/Source/iOS/Dot.swift
|
1
|
2358
|
//
// Dot.swift
// SwiftGL
//
// Created by jerry on 2015/7/14.
// Copyright (c) 2015年 Jerry Chan. All rights reserved.
//
import SpriteKit
import SwiftGL
import CGUtility
class Dot: SKNode {
override init()
{
super.init()
//self.name = "dot"
let touchArea = SKShapeNode(circleOfRadius: 30) // Size of Circle
touchArea.fillColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
touchArea.strokeColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.addChild(touchArea)
//let image = SKSpriteNode(imageNamed: "spongebob")
//self.addChild(image)
let Circle = SKShapeNode(circleOfRadius: 20) // Size of Circle
Circle.position = CGPoint(x: 0,y: 0) //Middle of Screen
//Circle.strokeColor = uIntColor(0, 0, 0, 0)//SKColor(red: 0.2, green: 0.5, blue: 0.6, alpha: 1)
//Circle.strokeColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.2)
//Circle.fillColor = uIntColor(80, 151, 255, 255)
Circle.fillColor = uIntColor(80, green: 151, blue: 255, alpha: 255)
self.addChild(Circle)
isUserInteractionEnabled = true
shape = Circle
}
convenience init(name:String)
{
self.init()
}
var shape:SKShapeNode!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func changeColor(_ color:UIColor)
{
shape.fillColor = color
}
func setAsFixedPoint()
{
changeColor(uIntColor(255, green: 70, blue: 142, alpha: 255))
}
func getPos()->Vec2
{
return Vec2(Float(self.position.x),Float(self.position.y))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
//let touch = touches.first as UITouch?
//let loc = touch!.locationInNode(self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
{
let touch = touches.first as UITouch?
let loc = touch!.location(in: self)
let prev_loc = touch!.previousLocation(in: self)
//let node = selectNodeForTouch(prev_loc)
let p = position
position = CGPoint(x: p.x+loc.x-prev_loc.x, y: p.y+loc.y-prev_loc.y)
}
}
|
mit
|
b219b711e73f69909954ecbd3d2c8e4d
| 26.717647 | 104 | 0.574278 | 3.849673 | false | false | false | false |
DataBreweryIncubator/StructuredQuery
|
Sources/Compiler/TypeInspector.swift
|
1
|
3373
|
import Basic
import Types
import Schema
import Relation
/// Expression compiler that returns expression's data type.
public class TypeInspector: ExpressionVisitor {
public typealias VisitorResult = DataType
let dialect: Dialect
/// Creates a type compiler for `dialect`. If dialect is not specified then
/// `DefaultDialect` is used.
init(dialect: Dialect?=nil) {
self.dialect = dialect ?? DefaultDialect()
}
public func visitNull() -> VisitorResult {
return DataType.NULL
}
public func visit(integer value: Int) -> VisitorResult {
return INTEGER
}
public func visit(string value: String) -> VisitorResult {
return TEXT
}
public func visit(bool value: Bool) -> VisitorResult {
return BOOLEAN
}
public func visit(binary op: String, _ left: Expression,_ right: Expression) -> VisitorResult {
guard let opinfo = self.dialect.binaryOperator(op) else {
return ErrorDataType(message: "Unknown binary operator '\(op)'")
}
let leftType = self.visit(expression: left)
let rightType = self.visit(expression: right)
let match = opinfo.signatures.first {
signature in signature.matches(arguments: [leftType, rightType])
}
return match.map { $0.returnType }
?? ErrorDataType(message: "Unable to match binary operator '\(op)'")
}
public func visit(unary op: String, _ arg: Expression) -> VisitorResult {
guard let opinfo = self.dialect.unaryOperator(op) else {
return ErrorDataType(message: "Unknown unary operator '\(op)'")
}
let argType = self.visit(expression: arg)
let match = opinfo.signatures.first {
signature in signature.matches(arguments: [argType])
}
return match.map { $0.returnType }
?? ErrorDataType(message: "Unable to match unary operator '\(op)'")
}
public func visit(function: String, _ args: [Expression]) -> VisitorResult {
return ErrorDataType(message: "Visit function type not implemented")
}
public func visit(column name: String, inTable table: Table) -> VisitorResult {
let columns = table.columnDefinitions
if columns.ambiguous.contains(name) {
// TODO: Add table name to the error
return ErrorDataType(message: "Duplicate column '\(name)'")
}
else if let column = columns[name] {
return column.type
}
else {
// TODO: Add table name to the error
return ErrorDataType(message: "Unknown column \(name)")
}
}
public func visit(attribute reference: AttributeReference) -> VisitorResult {
if let error = reference.error {
return ErrorDataType(message: error.description)
}
// Value is guaranteed to exist if there is no error
let expr = reference.relation.projectedExpressions[reference.index.value!]
return visit(expression: expr)
}
public func visit(parameter: String) -> VisitorResult {
return ErrorDataType(message: "Type compilation of parameters is not implemented")
}
public func visit(error: ExpressionError) -> VisitorResult {
return ErrorDataType(message: "Expression error: \(error.description)")
}
}
|
mit
|
ce9e4266cd8cb7344beca889ecfdee1f
| 32.068627 | 99 | 0.636229 | 4.646006 | false | false | false | false |
kstaring/swift
|
test/SILGen/property_behavior_init.swift
|
4
|
2094
|
// RUN: %target-swift-frontend -enable-experimental-property-behaviors -emit-silgen %s | %FileCheck %s
protocol diBehavior {
associatedtype Value
var storage: Value { get set }
}
extension diBehavior {
var value: Value {
get { }
set { }
}
static func initStorage(_ initial: Value) -> Value { }
}
func whack<T>(_ x: inout T) {}
struct Foo {
var x: Int __behavior diBehavior
// FIXME: Hack because we can't find the synthesized associated type witness
// during witness matching.
typealias Value = Int
// TODO
// var xx: (Int, Int) __behavior diBehavior
// CHECK-LABEL: sil hidden @_TFV22property_behavior_init3FooC
// CHECK: bb0([[X:%.*]] : $Int,
init(x: Int) {
// CHECK: [[UNINIT_SELF:%.*]] = mark_uninitialized [rootself]
// CHECK: [[UNINIT_STORAGE:%.*]] = struct_element_addr [[UNINIT_SELF]]
// CHECK: [[UNINIT_BEHAVIOR:%.*]] = mark_uninitialized_behavior {{.*}}<Foo>([[UNINIT_STORAGE]]) : {{.*}}, {{%.*}}([[UNINIT_SELF]])
// Pure assignments undergo DI analysis so assign to the marking proxy.
// CHECK: assign [[X]] to [[UNINIT_BEHAVIOR]]
self.x = x
// CHECK: assign [[X]] to [[UNINIT_BEHAVIOR]]
self.x = x
// Reads or inouts use the accessors normally.
// CHECK: [[SELF:%.*]] = load [trivial] [[UNINIT_SELF]]
// CHECK: [[GETTER:%.*]] = function_ref @_TFV22property_behavior_init3Foog1xSi
// CHECK: apply [[GETTER]]([[SELF]])
_ = self.x
// CHECK: [[WHACK:%.*]] = function_ref @_TF22property_behavior_init5whackurFRxT_
// CHECK: [[INOUT:%.*]] = alloc_stack
// CHECK: [[SELF:%.*]] = load [trivial] [[UNINIT_SELF]]
// CHECK: [[GETTER:%.*]] = function_ref @_TFV22property_behavior_init3Foog1xSi
// CHECK: [[VALUE:%.*]] = apply [[GETTER]]([[SELF]])
// CHECK: store [[VALUE]] to [trivial] [[INOUT]]
// CHECK: apply [[WHACK]]<Int>([[INOUT]])
// CHECK: [[VALUE:%.*]] = load [trivial] [[INOUT]]
// CHECK: [[SETTER:%.*]] = function_ref @_TFV22property_behavior_init3Foos1xSi
// CHECK: apply [[SETTER]]([[VALUE]], [[UNINIT_SELF]])
whack(&self.x)
}
}
|
apache-2.0
|
fc6d583d333f2f33b982342b6184ca76
| 33.9 | 134 | 0.598854 | 3.629116 | false | false | false | false |
ReactiveKit/Bond
|
Sources/Bond/Observable Collections/OrderedCollectionDiff+IndexPath+Patch.swift
|
2
|
7805
|
//
// The MIT License (MIT)
//
// Copyright (c) 2018 DeclarativeHub/Bond
//
// 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
extension OrderedCollectionDiff where Index == IndexPath {
private struct Edit<Element> {
var deletionIndex: IndexPath?
var insertionIndex: IndexPath?
var element: Element?
var asOperation: OrderedCollectionOperation<Element, Index> {
if let from = deletionIndex, let to = insertionIndex {
return .move(from: from, to: to)
} else if let deletionIndex = deletionIndex {
return .delete(at: deletionIndex)
} else if let insertionIndex = insertionIndex, let element = element {
return .insert(element, at: insertionIndex)
} else {
fatalError()
}
}
}
public func generatePatch<C: TreeProtocol>(to collection: C) -> [OrderedCollectionOperation<C.Children.Element, IndexPath>] {
let inserts = self.inserts.map { Edit<C.Children.Element>(deletionIndex: nil, insertionIndex: $0, element: collection[childAt: $0]) }
let deletes = self.deletes.map { Edit<C.Children.Element>(deletionIndex: $0, insertionIndex: nil, element: nil) }
let moves = self.moves.map { Edit<C.Children.Element>(deletionIndex: $0.from, insertionIndex: $0.to, element: nil) }
func makeInsertionTree(_ script: [Edit<C.Children.Element>]) -> TreeNode<Int> {
func insert(_ edit: Edit<C.Children.Element>, value: Int, into tree: TreeNode<Int>) -> TreeNode<Int> {
var tree = tree
if let insertionIndex = edit.insertionIndex, let index = tree.children.firstIndex(where: { script[$0.value].insertionIndex?.isAncestor(of: insertionIndex) ?? false }) {
tree.children[index] = insert(edit, value: value, into: tree.children[index])
} else {
var newNode = TreeNode(value)
for (index, node) in tree.children.enumerated().reversed() {
if let insertionIndex = script[node.value].insertionIndex, edit.insertionIndex?.isAncestor(of: insertionIndex) ?? false {
tree.children.remove(at: index)
newNode.children.append(node)
}
}
newNode.children = newNode.children.reversed()
tree.children.insert(newNode, isOrderedBefore: { script[$0.value].insertionIndex ?? [] < script[$1.value].insertionIndex ?? [] })
}
return tree
}
var tree = TreeNode(-1)
for (index, edit) in script.enumerated() {
tree = insert(edit, value: index, into: tree)
}
return tree
}
func makeDeletionTree(_ script: [Edit<C.Children.Element>]) -> TreeNode<Int> {
func insert(_ edit: Edit<C.Children.Element>, value: Int, into tree: TreeNode<Int>) -> TreeNode<Int> {
var tree = tree
if let deletionIndex = edit.deletionIndex, let index = tree.children.firstIndex(where: { script[$0.value].deletionIndex?.isAncestor(of: deletionIndex) ?? false }) {
tree.children[index] = insert(edit, value: value, into: tree.children[index])
} else {
var newNode = TreeNode(value)
for (index, node) in tree.children.enumerated().reversed() {
if let deletionIndex = script[node.value].deletionIndex, edit.deletionIndex?.isAncestor(of: deletionIndex) ?? false {
tree.children.remove(at: index)
newNode.children.append(node)
}
}
newNode.children = newNode.children.reversed()
tree.children.insert(newNode, isOrderedBefore: { script[$0.value].deletionIndex ?? [Int.max] < script[$1.value].deletionIndex ?? [Int.max] })
}
return tree
}
var tree = TreeNode(-1)
for (index, edit) in script.enumerated() {
tree = insert(edit, value: index, into: tree)
}
return tree
}
let deletesAndMoves = deletes + moves
let deletionTree = makeDeletionTree(deletesAndMoves)
var deletionScript = Array(deletionTree.depthFirst.indices.dropFirst().map { deletesAndMoves[deletionTree[$0].value] }.reversed())
var insertionSeedScript = deletionScript
var moveCounter = 0
for index in 0..<deletionScript.count {
if deletionScript[index].deletionIndex != nil {
deletionScript[index].deletionIndex![0] += moveCounter
insertionSeedScript[index].deletionIndex = [moveCounter]
}
if deletionScript[index].insertionIndex != nil {
deletionScript[index].insertionIndex = [moveCounter]
moveCounter += 1
}
}
let movesAndInserts = insertionSeedScript.filter { $0.insertionIndex != nil } + inserts
let insertionTree = makeInsertionTree(movesAndInserts)
var insertionScript = insertionTree.depthFirst.indices.dropFirst().map { movesAndInserts[insertionTree[$0].value] }
for index in 0..<insertionScript.count {
for j in index+1..<insertionScript.count {
if let deletionIndex = insertionScript[j].deletionIndex, let priorDeletionIndex = insertionScript[index].deletionIndex {
if deletionIndex.isAffectedByDeletionOrInsertion(at: priorDeletionIndex) {
insertionScript[j].deletionIndex = deletionIndex.shifted(by: -1, atLevelOf: priorDeletionIndex)
}
}
}
if insertionScript[index].insertionIndex != nil {
if insertionScript[index].deletionIndex != nil {
moveCounter -= 1
}
insertionScript[index].insertionIndex![0] += moveCounter
}
}
let patch = (deletionScript + insertionScript).map { $0.asOperation }
let updatesInFinalCollection: [Index] = self.updates.compactMap {
return AnyOrderedCollectionOperation.simulate(patch: patch.map { $0.asAnyOrderedCollectionOperation }, on: $0)
}
let zipped = zip(self.updates, updatesInFinalCollection)
let updates = zipped.map { (pair) -> OrderedCollectionOperation<C.Children.Element, IndexPath> in
return .update(at: pair.0, newElement: collection[childAt: pair.1])
}
return updates + patch
}
}
|
mit
|
c6ac050465f19991d499f1af42e40db7
| 49.354839 | 184 | 0.609353 | 4.612884 | false | false | false | false |
chenzhe555/core-ios-swift
|
core-ios-swift/Framework_swift/CustomView/custom/NaviView/BaseNaviView_s.swift
|
1
|
6921
|
//
// BaseNaviView_s.swift
// core-ios-swift
//
// Created by mc962 on 16/3/1.
// Copyright © 2016年 陈哲是个好孩子. All rights reserved.
//
import UIKit
//文字基本信息
let kBaseNaviViewTitleNormalColor = UIColor.lightGrayColor();
let kBaseNaviViewTitleSelectedColor = UIColor.redColor();
let kBaseNaviViewTitleFont:CGFloat = 14.0
//左右间隙
let kBaseNaviViewHaveImageSpace:CGFloat = 10.0 //有图片时候的间隙
let kBaseNaviViewOnlyTitleOrImageSpace:CGFloat = 3.0 //只有图片或者文字时候的间隙
let kBaseNaviViewTitleAndImageSpace:CGFloat = 5.0 //图片和文字的间隙
enum BaseNaviImageViewShowType_s: Int {
case Left = 111, //文字左(如果没有图片、居中)
Right, //文字右(如果没有图片、居中)
Bottom, //文字底部(如果没有图片、居中)
Top //文字顶部(如果没有图片、居中)
}
class BaseNaviView_s: UIView {
let titleLabel = MCLabel_s();
let contentImageView = BaseNaviImageView_s();
//MARK: *************** .h(Protocal Enum ...)
//MARK: *************** .h(Property Method ...)
/**
创建Navi视图(必须先设置BaseNaviView的frame)
- parameter title: 文字
- parameter normalImage: 正常情况下图片
- parameter selectedImage: 选中下图片
- parameter showType: 显示类型
*/
func createNaviView(title: String?, normalImage: UIImage?, selectedImage: UIImage?,showType:BaseNaviImageViewShowType_s) -> Void {
self.contentImageView.normalImage = normalImage;
self.contentImageView.selectedImage = selectedImage;
self.showType = showType;
if(title == nil)
{
self.contentImageView.frame = CGRectMake(kBaseNaviViewOnlyTitleOrImageSpace, (self.height - normalImage!.size.height)/2, normalImage!.size.width, normalImage!.size.height);
self.frame = CGRectMake(self.x, self.y, self.contentImageView.width + kBaseNaviViewOnlyTitleOrImageSpace*2.0, self.height);
self.contentImageView.isSelect = false;
return;
}
self.titleLabel.text = title;
if(normalImage != nil)
{
self.contentImageView.isSelect = false;
switch(self.showType) {
case .Left:
self.titleLabel.frame = CGRectMake(kBaseNaviViewHaveImageSpace, (self.height - self.titleLabel.height)/2, self.titleLabel.width, self.titleLabel.height);
self.contentImageView.frame = CGRectMake(self.titleLabel.x + self.titleLabel.width + kBaseNaviViewTitleAndImageSpace, (self.height - normalImage!.size.height)/2, normalImage!.size.width, normalImage!.size.height);
self.frame = CGRectMake(self.x, self.y, self.contentImageView.x + self.contentImageView.width + kBaseNaviViewHaveImageSpace, self.height);
break;
case .Right:
self.contentImageView.frame = CGRectMake(kBaseNaviViewHaveImageSpace, (self.height - normalImage!.size.height)/2, normalImage!.size.width, normalImage!.size.height);
self.titleLabel.frame = CGRectMake(self.contentImageView.x + self.contentImageView.width + kBaseNaviViewTitleAndImageSpace, (self.height - self.titleLabel.height)/2, self.titleLabel.width, self.titleLabel.height);
self.frame = CGRectMake(self.x, self.y, self.titleLabel.x + self.titleLabel.width + kBaseNaviViewHaveImageSpace, self.height);
break;
case .Bottom:
let superViewWidth = max(self.titleLabel.width, self.contentImageView.width) + kBaseNaviViewHaveImageSpace*2.0 + kBaseNaviViewTitleAndImageSpace;
self.contentImageView.frame = CGRectMake((superViewWidth - normalImage!.size.width)/2, (self.height - normalImage!.size.height - kBaseNaviViewTitleAndImageSpace - self.titleLabel.height)/2, normalImage!.size.width, normalImage!.size.height);
self.titleLabel.frame = CGRectMake((superViewWidth - self.titleLabel.width)/2, self.contentImageView.y + self.contentImageView.height + kBaseNaviViewTitleAndImageSpace, self.titleLabel.width, self.titleLabel.height);
self.frame = CGRectMake(self.x, self.y,superViewWidth , self.height);
break;
case .Top:
let superViewWidth = max(self.titleLabel.width, self.contentImageView.width) + kBaseNaviViewHaveImageSpace*2.0 + kBaseNaviViewTitleAndImageSpace;
self.titleLabel.frame = CGRectMake((superViewWidth - self.titleLabel.width)/2, (self.height - normalImage!.size.height - kBaseNaviViewTitleAndImageSpace - self.titleLabel.height)/2, self.titleLabel.width, self.titleLabel.height);
self.contentImageView.frame = CGRectMake((superViewWidth - normalImage!.size.width)/2, self.titleLabel.y + self.titleLabel.height + kBaseNaviViewTitleAndImageSpace, normalImage!.size.width, normalImage!.size.height);
self.frame = CGRectMake(self.x, self.y, superViewWidth, self.height);
break;
}
}
else
{
self.titleLabel.frame = CGRectMake(kBaseNaviViewOnlyTitleOrImageSpace, (self.height - self.titleLabel.height)/2, self.titleLabel.width, self.titleLabel.height);
self.frame = CGRectMake(self.x, self.y, self.titleLabel.width + kBaseNaviViewOnlyTitleOrImageSpace*2.0, self.height);
}
}
//MARK: *************** .m(Category ...)
//显示的类型
var showType: BaseNaviImageViewShowType_s = .Left;
//MARK: *************** .m(Method ...)
override init(frame: CGRect) {
super.init(frame: frame);
self.titleLabel.textColor = kBaseNaviViewTitleNormalColor;
self.titleLabel.font = UIFont.systemFontOfSize(kBaseNaviViewTitleFont);
self.addSubview(self.titleLabel);
self.addSubview(self.contentImageView);
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event);
self.titleLabel.textColor = kBaseNaviViewTitleSelectedColor;
self.contentImageView.isSelect = true;
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event);
self.titleLabel.textColor = kBaseNaviViewTitleNormalColor;
self.contentImageView.isSelect = false;
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event);
self.titleLabel.textColor = kBaseNaviViewTitleNormalColor;
self.contentImageView.isSelect = false;
}
}
|
mit
|
d6e39997ab332b3623208ed4e31d2d96
| 51.03125 | 257 | 0.667417 | 4.196597 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
Steps4Impact/App/Cache.swift
|
1
|
3698
|
/**
* Copyright © 2019 Aga Khan Foundation
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import Foundation
import RxSwift
import RxCocoa
class Cache {
static let shared = Cache()
typealias FirebaseID = String
typealias SocialDisplayName = String
typealias SocialProfileImageURL = URL
typealias PersonalProgress = Int
typealias PersonalCommitment = Int
func fetchSocialInfo(fbid: FirebaseID) {
AKFCausesService.getParticipantSocial(fbid: fbid) { [weak self] (result) in
guard
let `self` = self,
let response = result.response?.dictionaryValue,
let displayName = response["displayName"]?.stringValue,
let photoURLRaw = response["photoURL"]?.stringValue,
let photoURL = URL(string: photoURLRaw)
else { return }
self.update(fbid: fbid, name: displayName)
self.update(fbid: fbid, url: photoURL)
}
}
let socialDisplayNamesRelay = BehaviorRelay<[FirebaseID: SocialDisplayName]>(value: [:])
private var socialDisplayNames = [FirebaseID: SocialDisplayName]()
func update(fbid: FirebaseID, name: SocialDisplayName) {
socialDisplayNames[fbid] = name
socialDisplayNamesRelay.accept(socialDisplayNames)
}
let socialProfileImageURLsRelay = BehaviorRelay<[FirebaseID: SocialProfileImageURL]>(value: [:])
private var socialProfileImageURLs = [FirebaseID: SocialProfileImageURL]()
func update(fbid: FirebaseID, url: SocialProfileImageURL) {
socialProfileImageURLs[fbid] = url
socialProfileImageURLsRelay.accept(socialProfileImageURLs)
}
let personalProgressRelay = BehaviorRelay<[FirebaseID: PersonalProgress]>(value: [:])
private var personalProgresses = [FirebaseID: PersonalProgress]()
func update(fbid: FirebaseID, progress: PersonalProgress) {
personalProgresses[fbid] = progress
personalProgressRelay.accept(personalProgresses)
}
let personalCommitmentRelay = BehaviorRelay<[FirebaseID: PersonalCommitment]>(value: [:])
private var personalCommitments = [FirebaseID: PersonalCommitment]()
func update(fbid: FirebaseID, commitment: PersonalCommitment) {
personalCommitments[fbid] = commitment
personalCommitmentRelay.accept(personalCommitments)
}
let participantRelay = BehaviorRelay<Participant?>(value: nil)
let currentEventRelay = BehaviorRelay<Event?>(value: nil)
}
|
bsd-3-clause
|
a3d974e5ba67127d85ee57725375e16a
| 41.011364 | 98 | 0.759264 | 4.581165 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
Steps4Impact/Settings/Cells/SettingsDisclosureCell.swift
|
1
|
4318
|
/**
* Copyright © 2019 Aga Khan Foundation
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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 UIKit
struct SettingsDisclosureCellContext: CellContext {
let identifier: String = SettingsDisclosureCell.identifier
let title: String
let body: String?
let value: String?
let isDisclosureHidden: Bool
let isLastItem: Bool
let context: Context?
init(title: String,
body: String? = nil,
value: String? = nil,
isDisclosureHidden: Bool = false,
isLastItem: Bool = false,
context: Context? = nil) {
self.title = title
self.body = body
self.value = value
self.isDisclosureHidden = isDisclosureHidden
self.isLastItem = isLastItem
self.context = context
}
}
class SettingsDisclosureCell: ConfigurableTableViewCell, Contextable {
static let identifier = "SettingsDisclosureCell"
private let titleLabel = UILabel(typography: .bodyRegular)
private let bodyLabel = UILabel(typography: .smallRegular)
private let valueLabel = UILabel(typography: .subtitleRegular)
private let disclosureImageView = UIImageView(image: Assets.disclosure.image)
private let seperatorView = UIView()
var context: Context?
override func commonInit() {
super.commonInit()
backgroundColor = Style.Colors.white
valueLabel.textAlignment = .right
seperatorView.backgroundColor = Style.Colors.Seperator
let layoutGuide = UILayoutGuide()
contentView.addLayoutGuide(layoutGuide) {
$0.top.bottom.equalToSuperview().inset(Style.Padding.p16)
$0.leading.equalToSuperview().inset(Style.Padding.p32)
$0.width.equalToSuperview().multipliedBy(0.6)
}
contentView.addSubview(titleLabel) {
$0.leading.trailing.top.equalTo(layoutGuide)
}
contentView.addSubview(bodyLabel) {
$0.leading.trailing.bottom.equalTo(layoutGuide)
$0.top.equalTo(titleLabel.snp.bottom)
}
contentView.addSubview(disclosureImageView) {
$0.top.equalToSuperview().inset(Style.Padding.p16)
$0.trailing.equalToSuperview().inset(Style.Padding.p32)
$0.height.equalTo(16)
$0.width.equalTo(10)
}
contentView.addSubview(valueLabel) {
$0.leading.equalTo(layoutGuide.snp.trailing)
$0.trailing.equalTo(disclosureImageView.snp.leading).offset(-Style.Padding.p8)
$0.top.equalToSuperview().inset(Style.Padding.p16)
}
contentView.addSubview(seperatorView) {
$0.height.equalTo(1)
$0.bottom.equalToSuperview()
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p32)
}
}
func configure(context: CellContext) {
guard let context = context as? SettingsDisclosureCellContext else { return }
titleLabel.text = context.title
bodyLabel.text = context.body
valueLabel.text = context.value
disclosureImageView.isHidden = context.isDisclosureHidden
seperatorView.isHidden = context.isLastItem
self.context = context.context
}
}
|
bsd-3-clause
|
8733d787d2e8e3e191a106f779e8da45
| 35.277311 | 84 | 0.73338 | 4.400612 | false | false | false | false |
Mossuru777/DrawUIBezierPathFitToUIView
|
Classes/DrawUIBezierPathFitToUIView.swift
|
1
|
5640
|
//
// DrawUIBezierPathFitToUIView.swift
//
// Created by Mossuru777 on 2018/01/23.
// Copyright (c) 2018 Mossan. All rights reserved.
//
import UIKit
import CoreGraphics
public class DrawUIBezierPathFitToUIView {
/// UIBezierPaths scale when fit to UIView.
/// The value must be between 0.0 and 1.0.
public var scale: CGFloat
private typealias PathInfo = (path: UIBezierPath, fillColor: UIColor?, strokeColor: UIColor?)
private let viewSize: CGSize
private var paths: [PathInfo]
/// Initialize with UIView to fit UIBezierPaths.
///
/// - Parameters:
/// - view: UIView to fit UIBezierPaths.
public init(_ view: UIView) {
self.scale = 1.0
self.viewSize = view.frame.size
self.paths = []
}
/// Adding fit target UIBezierPath.
/// It is necessary to set a value for fillColor or strokeColor.
///
/// - Parameters:
/// - path: Fit target UIBezierPath object.
/// - fillColor: Path fill color
/// - strokeColor: Path stroke color
public func addPath(_ path: UIBezierPath, fillColor: UIColor?, strokeColor: UIColor?) {
if fillColor == nil && strokeColor == nil {
fatalError("NoDrawPathError: arguments indicate no draw path.")
}
// check exist path in array
for path_info: PathInfo in self.paths {
if path_info.path == path {
return
}
}
// add path to array
paths.append((path, fillColor, strokeColor))
}
/// Draw scaled UIBezierPaths for fit UIView.
/// Scaled UIBezierPath keeps original aspect ratio.
public func drawScaledPathFitToView() {
if self.scale < 0 || self.scale > 1.0 {
fatalError("ValueError: scale must be between 0.0 and 1.0.")
}
var totalRect = CGRect(x: .greatestFiniteMagnitude, y: .greatestFiniteMagnitude, width: 0.0, height: 0.0)
var fit_scale: CGFloat
var centering_margin_x: CGFloat = 0.0
var centering_margin_y: CGFloat = 0
var move_x: CGFloat
var move_y: CGFloat
// calculate total bounds / origin
for path_info: PathInfo in self.paths {
let path = path_info.path
// reset path scaling
path.apply(.identity)
// extends bounds / origin
if path_info.strokeColor != nil {
// width
if path.bounds.origin.x + path.bounds.size.width + (path.lineWidth / 2) > totalRect.size.width {
totalRect.size.width = path.bounds.origin.x + path.bounds.size.width + (path.lineWidth / 2)
}
// x origin
if path.bounds.origin.x - (path.lineWidth / 2) < totalRect.origin.x {
totalRect.origin.x = path.bounds.origin.x - (path.lineWidth / 2)
}
// height
if path.bounds.origin.y + path.bounds.size.height + (path.lineWidth / 2) > totalRect.size.height {
totalRect.size.height = path.bounds.origin.y + path.bounds.size.height + (path.lineWidth / 2)
}
// y origin
if path.bounds.origin.y - (path.lineWidth / 2) < totalRect.origin.y {
totalRect.origin.y = path.bounds.origin.y - (path.lineWidth / 2)
}
} else if path_info.fillColor != nil {
// width
if path.bounds.origin.x + path.bounds.size.width > totalRect.size.width {
totalRect.size.width = path.bounds.origin.x + path.bounds.size.width
}
// x origin
if path.bounds.origin.x < totalRect.origin.x {
totalRect.origin.x = path.bounds.origin.x
}
// height
if path.bounds.origin.y + path.bounds.size.height > totalRect.size.height {
totalRect.size.height = path.bounds.origin.y + path.bounds.size.height
}
// y origin
if path.bounds.origin.y < totalRect.origin.y {
totalRect.origin.y = path.bounds.origin.y
}
}
}
// calculate scale / centering margin / move
if self.viewSize.width / totalRect.size.width < self.viewSize.height / totalRect.size.height {
fit_scale = self.viewSize.width / totalRect.size.width * self.scale
} else {
fit_scale = self.viewSize.height / totalRect.size.height * self.scale
}
centering_margin_x = (self.viewSize.width / 2) - (totalRect.size.width * fit_scale / 2)
centering_margin_y = (self.viewSize.height / 2) - (totalRect.size.height * fit_scale / 2)
move_x = totalRect.origin.x * fit_scale
move_y = totalRect.origin.y * fit_scale
// draw scaled path
for path_info: PathInfo in self.paths {
let path = path_info.path
// scaling path
path.lineWidth = path.lineWidth * fit_scale
path.apply(CGAffineTransform(scaleX: fit_scale, y: fit_scale))
// move path
path.apply(CGAffineTransform(translationX: centering_margin_x - move_x, y: centering_margin_y - move_y))
// fill path
if let fillColor = path_info.fillColor {
fillColor.setFill()
path.fill()
}
// stroke path
if let strokeColor = path_info.strokeColor {
strokeColor.setStroke()
path.stroke()
}
}
}
}
|
mit
|
a514582a75d0c1bf725e0a48cfe6e3d2
| 35.387097 | 116 | 0.558333 | 4.240602 | false | false | false | false |
mozilla-mobile/firefox-ios
|
Storage/Visit.swift
|
2
|
3686
|
// 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
// These are taken from the Places docs
// http://mxr.mozilla.org/mozilla-central/source/toolkit/components/places/nsINavHistoryService.idl#1187
@objc public enum VisitType: Int, CaseIterable {
case unknown
/**
* This transition type means the user followed a link and got a new toplevel
* window.
*/
case link
/**
* This transition type means that the user typed the page's URL in the
* URL bar or selected it from URL bar autocomplete results, clicked on
* it from a history query (from the History sidebar, History menu,
* or history query in the personal toolbar or Places organizer).
*/
case typed
case bookmark
case embed
case permanentRedirect
case temporaryRedirect
case download
case framedLink
case recentlyClosed
}
// WKWebView has these:
/*
WKNavigationTypeLinkActivated,
WKNavigationTypeFormSubmitted,
WKNavigationTypeBackForward,
WKNavigationTypeReload,
WKNavigationTypeFormResubmitted,
WKNavigationTypeOther = -1,
*/
/**
* SiteVisit is a sop to the existing API, which expects to be able to go
* backwards from a visit to a site, and preserve the ID of the database row.
* Visit is the model of what lives on the wire: just a date and a type.
* Ultimately we'll end up with something similar to ClientAndTabs: the tabs
* don't need to know about the client, and visits don't need to know about
* the site, because they're bound together.
*
* (Furthermore, we probably shouldn't ever need something like SiteVisit
* to reach the UI: we care about "last visited", "visit count", or just
* "places ordered by frecency" — we don't care about lists of visits.)
*/
open class Visit: Hashable {
public let date: MicrosecondTimestamp
public let type: VisitType
public func hash(into hasher: inout Hasher) {
hasher.combine(date)
hasher.combine(type)
}
public init(date: MicrosecondTimestamp, type: VisitType = .unknown) {
self.date = date
self.type = type
}
open class func fromJSON(_ json: [String: Any]) -> Visit? {
if let type = json["type"] as? Int,
let typeEnum = VisitType(rawValue: type),
let date = json["date"] as? Int64, date >= 0 {
return Visit(date: MicrosecondTimestamp(date), type: typeEnum)
}
return nil
}
open func toJSON() -> [String: Any] {
let d = NSNumber(value: self.date)
let o: [String: Any] = ["type": self.type.rawValue, "date": d]
return o
}
}
public func == (lhs: Visit, rhs: Visit) -> Bool {
return lhs.date == rhs.date &&
lhs.type == rhs.type
}
open class SiteVisit: Visit {
var id: Int?
public let site: Site
public override func hash(into hasher: inout Hasher) {
hasher.combine(date)
hasher.combine(type)
hasher.combine(id)
hasher.combine(site.id)
}
public init(site: Site, date: MicrosecondTimestamp, type: VisitType = .unknown) {
self.site = site
super.init(date: date, type: type)
}
}
public func == (lhs: SiteVisit, rhs: SiteVisit) -> Bool {
if let lhsID = lhs.id, let rhsID = rhs.id {
if lhsID != rhsID {
return false
}
} else {
if lhs.id != nil || rhs.id != nil {
return false
}
}
// TODO: compare Site.
return lhs.date == rhs.date &&
lhs.type == rhs.type
}
|
mpl-2.0
|
c596d31cd37a3fb05c11d395177e30ae
| 28.472 | 104 | 0.647394 | 4.039474 | false | false | false | false |
garthmac/ChemicalVisualizer
|
BrowserViewController.swift
|
1
|
2940
|
//
// BrowserViewController.swift
// ChemicalVisualizer
//
// Created by iMac 27 on 2015-12-14.
// Copyright © 2015 Garth MacKenzie. All rights reserved.
//
import UIKit
import WebKit
class BrowserViewController: UIViewController, UIWebViewDelegate {
var url = ""
var nsurl: NSURL? {
didSet {
if view.window != nil {
loadURL()
}
}
}
private func loadURL() {
if url == ViewController.Constants.DemoURL {
allowHTTP = true
}
if nsurl != nil {
if allowHTTP {
UIApplication.sharedApplication().openURL(nsurl!)
}
else { //cache it
let request = NSURLRequest(URL: nsurl!)
webView.loadRequest(request)
}
}
}
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var webView: UIWebView! //WKWebView
//MARK: IBAction
@IBAction func unwind(sender: UIButton) {
if let vc = presentingViewController as? ViewController {
vc.unwindFromModalViewController(nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// let button = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 28), size: CGSize(width: 160, height: 30))) //WKWebView
// button.setTitle("◁Back to Chem 3D", forState: .Normal)
// button.setTitleColor(UIColor.redColor(), forState: .Normal)
// button.addTarget(self, action: "unwind:", forControlEvents: .TouchUpInside)
// webView.addSubview(button)
webView.delegate = self
//webView.scalesPageToFit = true
loadURL()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if allowHTTP {
dismissViewControllerAnimated(true, completion: nil)
}
let swipeLeft = UISwipeGestureRecognizer(target: self, action: "swipeLeft:")
swipeLeft.direction = .Left
webView.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: "swipeRight:")
swipeRight.direction = .Right
webView.addGestureRecognizer(swipeRight)
}
func swipeLeft(gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .Ended:
webView.goBack()
default: break
}
}
func swipeRight(gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .Ended:
webView.goForward()
default: break
}
}
var allowHTTP = false
// MARK: - UIWebView delegate
var activeDownloads = 0
func webViewDidStartLoad(webView: UIWebView) {
activeDownloads++
spinner.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView) {
activeDownloads--
if activeDownloads < 1 {
spinner.stopAnimating()
}
}
}
|
mit
|
9c3446f554887bcc3e99be2b3ef21b0d
| 30.580645 | 128 | 0.602656 | 4.903172 | false | false | false | false |
einsteinx2/iSub
|
Frameworks/CocoaLumberjack/CocoaLumberjack.swift
|
2
|
5847
|
// Software License Agreement (BSD License)
//
// Copyright (c) 2014-2016, Deusty, LLC
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms,
// with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Neither the name of Deusty nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission of Deusty, LLC.
import Foundation
extension DDLogFlag {
public static func fromLogLevel(_ logLevel: DDLogLevel) -> DDLogFlag {
return DDLogFlag(rawValue: logLevel.rawValue)
}
public init(_ logLevel: DDLogLevel) {
self = DDLogFlag(rawValue: logLevel.rawValue)
}
///returns the log level, or the lowest equivalant.
public func toLogLevel() -> DDLogLevel {
if let ourValid = DDLogLevel(rawValue: self.rawValue) {
return ourValid
} else {
let logFlag:DDLogFlag = self
if logFlag.contains(.verbose) {
return .verbose
} else if logFlag.contains(.debug) {
return .debug
} else if logFlag.contains(.info) {
return .info
} else if logFlag.contains(.warning) {
return .warning
} else if logFlag.contains(.error) {
return .error
} else {
return .off
}
}
}
}
public var defaultDebugLevel = DDLogLevel.verbose
public func resetDefaultDebugLevel() {
defaultDebugLevel = DDLogLevel.verbose
}
@available(*, deprecated, message: "Use one of the DDLog*() functions if appropriate or call _DDLogMessage()")
public func SwiftLogMacro(_ isAsynchronous: Bool, level: DDLogLevel, flag flg: DDLogFlag, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, string: @autoclosure () -> String, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(string, level: level, flag: flg, context: context, file: file, function: function, line: line, tag: tag, asynchronous: isAsynchronous, ddlog: ddlog)
}
public func _DDLogMessage(_ message: @autoclosure () -> String, level: DDLogLevel, flag: DDLogFlag, context: Int, file: StaticString, function: StaticString, line: UInt, tag: AnyObject?, asynchronous: Bool, ddlog: DDLog) {
if level.rawValue & flag.rawValue != 0 {
// Tell the DDLogMessage constructor to copy the C strings that get passed to it.
let logMessage = DDLogMessage(message: message(), level: level, flag: flag, context: context, file: String(describing: file), function: String(describing: function), line: line, tag: tag, options: [.copyFile, .copyFunction], timestamp: nil)
ddlog.log(asynchronous, message: logMessage)
}
}
public func DDLogDebug(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .debug, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
public func DDLogInfo(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .info, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
public func DDLogWarn(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .warning, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
public func DDLogVerbose(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .verbose, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
public func DDLogError(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = false, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .error, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
/// Returns a String of the current filename, without full path or extension.
///
/// Analogous to the C preprocessor macro `THIS_FILE`.
public func CurrentFileName(_ fileName: StaticString = #file) -> String {
var str = String(describing: fileName)
if let idx = str.range(of: "/", options: .backwards)?.upperBound {
str = str.substring(from: idx)
}
if let idx = str.range(of: ".", options: .backwards)?.lowerBound {
str = str.substring(to: idx)
}
return str
}
|
gpl-3.0
|
b6b8748bb77a02e55aee9e00422ff7bb
| 56.323529 | 300 | 0.685822 | 4.258558 | false | false | false | false |
macfeteria/swift-line-echobot-demo
|
Sources/Line.swift
|
1
|
1533
|
//
// Line.swift
// demo
//
// Created by Ter on 3/14/17.
//
//
import Foundation
import Cryptor
import SwiftyJSON
public func validateSignature( message: String, signature: String , secretKey: String) -> Bool {
let key = CryptoUtils.byteArray(from: secretKey)
let data : [UInt8] = CryptoUtils.byteArray(from: message)
if let hmac = HMAC(using: HMAC.Algorithm.sha256, key: key).update(byteArray: data)?.final() {
let hmacData = Data(hmac)
let hmacHex = hmacData.base64EncodedString(options: .endLineWithLineFeed)
if signature == hmacHex {
return true
} else {
return false
}
}
return false
}
public func textFromLineWebhook(json: JSON) -> (text:String,replyToken:String) {
let emptyResult = ("","")
guard let eventsJSON = json["events"].arrayValue.first else {
return emptyResult
}
if eventsJSON["type"].stringValue == "message" {
let token = eventsJSON["replyToken"].stringValue
let messageJson = eventsJSON["message"]
if messageJson["type"].stringValue == "text" {
let textMessage = messageJson["text"].stringValue
return (text:textMessage , replyToken: token)
}
return emptyResult
}
return emptyResult
}
public func reply(text:String,token:String) -> [String:Any] {
let message = ["type":"text", "text":text]
let json:[String:Any] = ["replyToken":token , "messages": [message] ]
return json
}
|
mit
|
bbba5f090b35610977036f2cfb4fa820
| 26.872727 | 97 | 0.6197 | 4.09893 | false | false | false | false |
OscarSwanros/swift
|
test/SILGen/objc_thunks.swift
|
2
|
29140
|
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
import ansible
class Hoozit : Gizmo {
@objc func typical(_ x: Int, y: Gizmo) -> Gizmo { return y }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo : $@convention(objc_method) (Int, Gizmo, Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[X:%.*]] : @trivial $Int, [[Y:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[Y_COPY:%.*]] = copy_value [[Y]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.typical
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytF : $@convention(method) (Int, @owned Gizmo, @guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[X]], [[Y_COPY]], [[BORROWED_THIS_COPY]]) {{.*}} line:[[@LINE-8]]:14:auto_gen
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit
// CHECK-NEXT: return [[RES]] : $Gizmo{{.*}} line:[[@LINE-11]]:14:auto_gen
// CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo'
// NS_CONSUMES_SELF by inheritance
override func fork() { }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4forkyyFTo : $@convention(objc_method) (@owned Hoozit) -> () {
// CHECK: bb0([[THIS:%.*]] : @owned $Hoozit):
// CHECK-NEXT: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC4forkyyF : $@convention(method) (@guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[BORROWED_THIS]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS]] from [[THIS]]
// CHECK-NEXT: destroy_value [[THIS]]
// CHECK-NEXT: return
// CHECK-NEXT: }
// NS_CONSUMED 'gizmo' argument by inheritance
override class func consume(_ gizmo: Gizmo?) { }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZTo : $@convention(objc_method) (@owned Optional<Gizmo>, @objc_metatype Hoozit.Type) -> () {
// CHECK: bb0([[GIZMO:%.*]] : @owned $Optional<Gizmo>, [[THIS:%.*]] : @trivial $@objc_metatype Hoozit.Type):
// CHECK-NEXT: [[THICK_THIS:%[0-9]+]] = objc_to_thick_metatype [[THIS]] : $@objc_metatype Hoozit.Type to $@thick Hoozit.Type
// CHECK: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZ : $@convention(method) (@owned Optional<Gizmo>, @thick Hoozit.Type) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[GIZMO]], [[THICK_THIS]])
// CHECK-NEXT: return
// CHECK-NEXT: }
// NS_RETURNS_RETAINED by family (-copy)
@objc func copyFoo() -> Gizmo { return self }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7copyFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// Override the normal family conventions to make this non-consuming and
// returning at +0.
@objc func initFoo() -> Gizmo { return self }
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7initFooSo5GizmoCyFTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7initFooSo5GizmoCyF : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
@objc var typicalProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[SELF:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.typicalProperty.getter
// CHECK-NEXT: [[GETIMPL:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvg
// CHECK-NEXT: [[RES:%.*]] = apply [[GETIMPL]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RES]] : $Gizmo
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK: bb0(%0 : @guaranteed $Hoozit):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.typicalProperty
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Gizmo
// CHECK-NEXT: [[RES:%.*]] = load [copy] [[READ]] {{.*}}
// CHECK-NEXT: end_access [[READ]] : $*Gizmo
// CHECK-NEXT: return [[RES]]
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Gizmo
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Hoozit
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: // function_ref objc_thunks.Hoozit.typicalProperty.setter
// CHECK: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs
// CHECK: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: return [[RES]] : $(), scope {{.*}} // id: {{.*}} line:[[@LINE-34]]:13:auto_gen
// CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvsTo'
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs
// CHECK: bb0([[ARG0:%.*]] : @owned $Gizmo, [[ARG1:%.*]] : @guaranteed $Hoozit):
// CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[ARG0_COPY:%.*]] = copy_value [[BORROWED_ARG0]]
// CHECK: [[ADDR:%.*]] = ref_element_addr [[ARG1]] : {{.*}}, #Hoozit.typicalProperty
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Gizmo
// CHECK: assign [[ARG0_COPY]] to [[WRITE]] : $*Gizmo
// CHECK: end_access [[WRITE]] : $*Gizmo
// CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]]
// CHECK: destroy_value [[ARG0]]
// CHECK: } // end sil function '_T011objc_thunks6HoozitC15typicalPropertySo5GizmoCvs'
// NS_RETURNS_RETAINED getter by family (-copy)
@objc var copyProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo {
// CHECK: bb0([[SELF:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.getter
// CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvg
// CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[BORROWED_SELF_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvg
// CHECK: bb0(%0 : @guaranteed $Hoozit):
// CHECK: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.copyProperty
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Gizmo
// CHECK-NEXT: [[RES:%.*]] = load [copy] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Gizmo
// CHECK-NEXT: return [[RES]]
// -- setter is normal
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.setter
// CHECK-NEXT: [[FR:%.*]] = function_ref @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs
// CHECK-NEXT: [[RES:%.*]] = apply [[FR]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs
// CHECK: bb0([[ARG1:%.*]] : @owned $Gizmo, [[SELF:%.*]] : @guaranteed $Hoozit):
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK: [[ADDR:%.*]] = ref_element_addr [[SELF]] : {{.*}}, #Hoozit.copyProperty
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Gizmo
// CHECK: assign [[ARG1_COPY]] to [[WRITE]]
// CHECK: end_access [[WRITE]] : $*Gizmo
// CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: } // end sil function '_T011objc_thunks6HoozitC12copyPropertySo5GizmoCvs'
@objc var roProperty: Gizmo { return self }
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]] : $Hoozit
// CHECK-NEXT: return [[RES]] : $Gizmo
// CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC10roPropertySo5GizmoCvgTo'
// -- no setter
// CHECK-NOT: sil hidden [thunk] @_T011objc_thunks6HoozitC10roPropertySo5GizmoCvsTo
@objc var rwProperty: Gizmo {
get {
return self
}
set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC10rwPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
@objc var copyRWProperty: Gizmo {
get {
return self
}
set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @owned Gizmo {
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NOT: return
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter is normal
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC14copyRWPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
@objc var initProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12initPropertySo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
@objc var propComputed: Gizmo {
@objc(initPropComputedGetter) get { return self }
@objc(initPropComputedSetter:) set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvgTo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvg : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvsTo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
// CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK-NEXT: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC12propComputedSo5GizmoCvs : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE_COPY]], [[BORROWED_THIS_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
// CHECK-NEXT: destroy_value [[THIS_COPY]]
// CHECK-NEXT: return
// CHECK-NEXT: }
// Don't export generics to ObjC yet
func generic<T>(_ x: T) {}
// CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7generic{{.*}}
// Constructor.
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSi7bellsOn_tcfc : $@convention(method) (Int, @owned Hoozit) -> @owned Hoozit {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[GIZMO:%[0-9]+]] = upcast [[SELF:%[0-9]+]] : $Hoozit to $Gizmo
// CHECK: [[BORROWED_GIZMO:%.*]] = begin_borrow [[GIZMO]]
// CHECK: [[CAST_BORROWED_GIZMO:%.*]] = unchecked_ref_cast [[BORROWED_GIZMO]] : $Gizmo to $Hoozit
// CHECK: [[SUPERMETHOD:%[0-9]+]] = objc_super_method [[CAST_BORROWED_GIZMO]] : $Hoozit, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK-NEXT: end_borrow [[BORROWED_GIZMO]] from [[GIZMO]]
// CHECK-NEXT: [[SELF_REPLACED:%[0-9]+]] = apply [[SUPERMETHOD]](%0, [[X:%[0-9]+]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK-NOT: unconditional_checked_cast downcast [[SELF_REPLACED]] : $Gizmo to $Hoozit
// CHECK: unchecked_ref_cast
// CHECK: return
override init(bellsOn x : Int) {
super.init(bellsOn: x)
other()
}
// Subscript
@objc subscript (i: Int) -> Hoozit {
// Getter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicigTo : $@convention(objc_method) (Int, Hoozit) -> @autoreleased Hoozit
// CHECK: bb0([[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicig : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]]
// CHECK-NEXT: return [[RESULT]] : $Hoozit
get {
return self
}
// Setter
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicisTo : $@convention(objc_method) (Hoozit, Int, Hoozit) -> ()
// CHECK: bb0([[VALUE:%[0-9]+]] : @unowned $Hoozit, [[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Hoozit
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicis : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[VALUE_COPY]], [[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
// CHECK: } // end sil function '_T011objc_thunks6HoozitCACSicisTo'
set {}
}
}
class Wotsit<T> : Gizmo {
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC5plainyyFTo : $@convention(objc_method) <T> (Wotsit<T>) -> () {
// CHECK: bb0([[SELF:%.*]] : @unowned $Wotsit<T>):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T>
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC5plainyyF : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> ()
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T>
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
@objc func plain() { }
func generic<U>(_ x: U) {}
var property : T
init(t: T) {
self.property = t
super.init()
}
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC11descriptionSSvgTo : $@convention(objc_method) <T> (Wotsit<T>) -> @autoreleased NSString {
// CHECK: bb0([[SELF:%.*]] : @unowned $Wotsit<T>):
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Wotsit<T>
// CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_T011objc_thunks6WotsitC11descriptionSSvg : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String
// CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE:%.*]]<T>([[BORROWED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String
// CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK-NEXT: destroy_value [[SELF_COPY]] : $Wotsit<T>
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK-NEXT: [[BORROWED_RESULT:%.*]] = begin_borrow [[RESULT]]
// CHECK-NEXT: [[NSRESULT:%.*]] = apply [[BRIDGE]]([[BORROWED_RESULT]]) : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK-NEXT: end_borrow [[BORROWED_RESULT]] from [[RESULT]]
// CHECK-NEXT: destroy_value [[RESULT]]
// CHECK-NEXT: return [[NSRESULT]] : $NSString
// CHECK-NEXT: }
override var description : String {
return "Hello, world."
}
// Ivar destroyer
// CHECK: sil hidden @_T011objc_thunks6WotsitCfETo
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGycfcTo : $@convention(objc_method) <T> (@owned Wotsit<T>) -> @owned Optional<Wotsit<T>>
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGSi7bellsOn_tcfcTo : $@convention(objc_method) <T> (Int, @owned Wotsit<T>) -> @owned Optional<Wotsit<T>>
}
// CHECK-NOT: sil hidden [thunk] @_TToF{{.*}}Wotsit{{.*}}
// Extension initializers, properties and methods need thunks too.
extension Hoozit {
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSi3int_tcfcTo : $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
@objc dynamic convenience init(int i: Int) { self.init(bellsOn: i) }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSd6double_tcfc : $@convention(method) (Double, @owned Hoozit) -> @owned Hoozit
convenience init(double d: Double) {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[X_BOX:%[0-9]+]] = alloc_box ${ var X }
var x = X()
// CHECK: [[CTOR:%[0-9]+]] = objc_method [[SELF:%[0-9]+]] : $Hoozit, #Hoozit.init!initializer.1.foreign : (Hoozit.Type) -> (Int) -> Hoozit, $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
// CHECK: [[NEW_SELF:%[0-9]+]] = apply [[CTOR]]
// CHECK: store [[NEW_SELF]] to [init] [[PB_BOX]] : $*Hoozit
// CHECK: return
self.init(int:Int(d))
other()
}
func foof() {}
// CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC4foofyyFTo : $@convention(objc_method) (Hoozit) -> () {
var extensionProperty: Int { return 0 }
// CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC17extensionPropertySivg : $@convention(method) (@guaranteed Hoozit) -> Int
}
// Calling objc methods of subclass should go through native entry points
func useHoozit(_ h: Hoozit) {
// sil @_T011objc_thunks9useHoozityAA0D0C1h_tF
// In the class decl, overrides importd method, 'dynamic' was inferred
h.fork()
// CHECK: objc_method {{%.*}} : {{.*}}, #Hoozit.fork!1.foreign
// In an extension, 'dynamic' was inferred.
h.foof()
// CHECK: objc_method {{%.*}} : {{.*}}, #Hoozit.foof!1.foreign
}
func useWotsit(_ w: Wotsit<String>) {
// sil @_T011objc_thunks9useWotsitySo0D0CySSG1w_tF
w.plain()
// CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.plain!1 :
w.generic(2)
// CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.generic!1 :
// Inherited methods only have objc entry points
w.clone()
// CHECK: objc_method {{%.*}} : {{.*}}, #Gizmo.clone!1.foreign
}
func other() { }
class X { }
// CHECK-LABEL: sil hidden @_T011objc_thunks8propertySiSo5GizmoCF
func property(_ g: Gizmo) -> Int {
// CHECK: bb0([[ARG:%.*]] : @owned $Gizmo):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.count!getter.1.foreign
return g.count
}
// CHECK-LABEL: sil hidden @_T011objc_thunks13blockPropertyySo5GizmoCF
func blockProperty(_ g: Gizmo) {
// CHECK: bb0([[ARG:%.*]] : @owned $Gizmo):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!setter.1.foreign
g.block = { }
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.block!getter.1.foreign
g.block()
}
class DesignatedStubs : Gizmo {
var i: Int
override init() { i = 5 }
// CHECK-LABEL: sil hidden @_T011objc_thunks15DesignatedStubsCSQyACGSi7bellsOn_tcfc
// CHECK: function_ref @_T0s25_unimplementedInitializers5NeverOs12StaticStringV9className_AE04initG0AE4fileSu4lineSu6columntF
// CHECK: string_literal utf8 "objc_thunks.DesignatedStubs"
// CHECK: string_literal utf8 "init(bellsOn:)"
// CHECK: string_literal utf8 "{{.*}}objc_thunks.swift"
// CHECK: return
// CHECK-NOT: sil hidden @_TFCSo15DesignatedStubsc{{.*}}
}
class DesignatedOverrides : Gizmo {
var i: Int = 5
// CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGycfc
// CHECK-NOT: return
// CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivpfi : $@convention(thin) () -> Int
// CHECK: objc_super_method [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> () -> Gizmo!, $@convention(objc_method) (@owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: return
// CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGSi7bellsOn_tcfc
// CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivpfi : $@convention(thin) () -> Int
// CHECK: objc_super_method [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
// CHECK: return
}
// Make sure we copy blocks passed in as IUOs - <rdar://problem/22471309>
func registerAnsible() {
// CHECK: function_ref @_T011objc_thunks15registerAnsibleyyFyyycSgcfU_
Ansible.anseAsync({ completion in completion!() })
}
|
apache-2.0
|
8bb8046b07eb4f5157ce1f188f44f870
| 54.59542 | 231 | 0.628072 | 3.351202 | false | false | false | false |
devxoul/allkdic
|
Allkdic/Controllers/ContentViewController.swift
|
1
|
10002
|
// The MIT License (MIT)
//
// Copyright (c) 2013 Suyeol Jeon (http://xoul.kr)
//
// 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 Cocoa
import WebKit
import SimpleCocoaAnalytics
open class ContentViewController: NSViewController {
let titleLabel = LabelButton()
let hotKeyLabel = Label()
let separatorView = NSImageView()
let webView = WebView()
let indicator = NSProgressIndicator(frame: NSZeroRect)
let menuButton = NSButton()
let mainMenu = NSMenu()
let dictionaryMenu = NSMenu()
override open func loadView() {
self.view = NSView(frame: CGRect(x: 0, y: 0, width: 405, height: 566))
self.view.autoresizingMask = NSAutoresizingMaskOptions()
self.view.appearance = NSAppearance(named: NSAppearanceNameAqua)
self.view.addSubview(self.titleLabel)
self.titleLabel.textColor = NSColor.controlTextColor
self.titleLabel.font = NSFont.systemFont(ofSize: 16)
self.titleLabel.stringValue = BundleInfo.bundleName
self.titleLabel.sizeToFit()
self.titleLabel.target = self
self.titleLabel.action = #selector(ContentViewController.navigateToMain)
self.titleLabel.snp.makeConstraints { make in
make.top.equalTo(10)
make.centerX.equalTo(0)
}
self.view.addSubview(self.hotKeyLabel)
self.hotKeyLabel.textColor = NSColor.headerColor
self.hotKeyLabel.font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize())
self.hotKeyLabel.snp.makeConstraints { make in
make.top.equalTo(self.titleLabel.snp.bottom).offset(2)
make.centerX.equalTo(0)
}
self.view.addSubview(self.separatorView)
self.separatorView.image = NSImage(named: "line")
self.separatorView.snp.makeConstraints { make in
make.top.equalTo(self.hotKeyLabel.snp.bottom).offset(8)
make.left.right.equalTo(0)
make.height.equalTo(2)
}
self.view.addSubview(self.webView)
self.webView.frameLoadDelegate = self
self.webView.shouldUpdateWhileOffscreen = true
self.webView.snp.makeConstraints { make in
make.top.equalTo(self.separatorView.snp.bottom)
make.left.right.bottom.equalTo(0)
}
self.view.addSubview(self.indicator)
self.indicator.style = .spinningStyle
self.indicator.controlSize = .small
self.indicator.isDisplayedWhenStopped = false
self.indicator.sizeToFit()
self.indicator.snp.makeConstraints { make in
make.center.equalTo(self.webView)
return
}
self.view.addSubview(self.menuButton)
self.menuButton.title = ""
self.menuButton.bezelStyle = .roundedDisclosure
self.menuButton.setButtonType(.momentaryPushIn)
self.menuButton.target = self
self.menuButton.action = #selector(ContentViewController.showMenu)
self.menuButton.snp.makeConstraints { make in
make.right.equalTo(-10)
make.centerY.equalTo(self.separatorView.snp.top).dividedBy(2)
}
let mainMenuItems = [
NSMenuItem(title: gettext("change_dictionary"), action: nil, keyEquivalent: ""),
NSMenuItem.separator(),
NSMenuItem(title: gettext("about"), action: #selector(ContentViewController.showAboutWindow), keyEquivalent: ""),
NSMenuItem(title: gettext("preferences") + "...", action: #selector(ContentViewController.showPreferenceWindow), keyEquivalent: ","),
NSMenuItem.separator(),
NSMenuItem(title: gettext("quit"), action: #selector(ContentViewController.quit), keyEquivalent: ""),
]
for mainMenuItem in mainMenuItems {
self.mainMenu.addItem(mainMenuItem)
}
//
// Dictionary Sub Menu
//
mainMenuItems[0].submenu = self.dictionaryMenu
let selectedDictionary = DictionaryType.selectedDictionary
// dictionary submenu
for (i, dictionary) in DictionaryType.allTypes.enumerated() {
let dictionaryMenuItem = NSMenuItem()
dictionaryMenuItem.title = dictionary.title
dictionaryMenuItem.tag = i
dictionaryMenuItem.action = #selector(ContentViewController.swapDictionary(_:))
dictionaryMenuItem.keyEquivalent = "\(i + 1)"
dictionaryMenuItem.keyEquivalentModifierMask = .command
if dictionary == selectedDictionary {
dictionaryMenuItem.state = NSOnState
}
self.dictionaryMenu.addItem(dictionaryMenuItem)
}
self.navigateToMain()
}
open func updateHotKeyLabel() {
let keyBindingData = UserDefaults.standard.dictionary(forKey: UserDefaultsKey.hotKey)
let keyBinding = KeyBinding(dictionary: keyBindingData)
self.hotKeyLabel.stringValue = keyBinding.description
self.hotKeyLabel.sizeToFit()
}
open func focusOnTextArea() {
self.javascript(DictionaryType.selectedDictionary.inputFocusingScript)
}
// MARK: - WebView
func navigateToMain() {
self.webView.mainFrameURL = DictionaryType.selectedDictionary.URLString
self.indicator.startAnimation(self)
self.indicator.isHidden = false
}
@discardableResult
func javascript(_ script: String) -> AnyObject? {
return self.webView.mainFrameDocument?.evaluateWebScript(script) as AnyObject?
}
open func handleKeyBinding(_ keyBinding: KeyBinding) {
let key = (keyBinding.shift, keyBinding.control, keyBinding.option, keyBinding.command, keyBinding.keyCode)
switch key {
case (false, false, false, false, 53):
// ESC
PopoverController.sharedInstance().close()
break
case (_, false, false, true, let index) where 18...(18 + DictionaryType.allTypes.count) ~= index:
// Command + [Shift] + 1, 2, 3, ...
self.swapDictionary(index - 18)
break
case (false, false, false, true, KeyBinding.keyCodeFormKeyString(",")):
// Command + ,
self.showPreferenceWindow()
break
default:
break
}
}
// MARK: - Menu
func showMenu() {
self.mainMenu.popUp(
positioning: self.mainMenu.item(at: 0),
at:self.menuButton.frame.origin,
in:self.view
)
}
/// Swap dictionary to given index.
///
/// - parameter sender: `Int` or `NSMenuItem`. If `NSMenuItem` is given, guess dictionary's index with `tag`
/// property.
func swapDictionary(_ sender: Any?) {
if sender == nil {
return
}
guard let index = (sender as? Int) ?? (sender as? NSMenuItem)?.tag,
index < DictionaryType.allTypes.count
else { return }
let selectedDictionary = DictionaryType.allTypes[index]
DictionaryType.selectedDictionary = selectedDictionary
NSLog("Swap dictionary: \(selectedDictionary.name)")
for menuItem in self.dictionaryMenu.items {
menuItem.state = NSOffState
}
self.dictionaryMenu.item(withTag: index)?.state = NSOnState
AnalyticsHelper.sharedInstance().recordCachedEvent(
withCategory: AnalyticsCategory.allkdic,
action: AnalyticsAction.dictionary,
label: selectedDictionary.name,
value: nil
)
self.navigateToMain()
}
func showPreferenceWindow() {
PopoverController.sharedInstance().preferenceWindowController.showWindow(self)
}
func showAboutWindow() {
PopoverController.sharedInstance().aboutWindowController.showWindow(self)
}
func quit() {
exit(0)
}
}
// MARK: - WebFrameLoadDelegate
extension ContentViewController: WebFrameLoadDelegate {
public func webView(_ sender: WebView!,
willPerformClientRedirectTo URL: URL!,
delay seconds: TimeInterval,
fire date: Date!,
for frame: WebFrame!) {
let URLString = URL.absoluteString
if URLString.range(of: "query=") == nil && URLString.range(of: "q=") == nil {
return
}
let URLPatternsForDictionaryType = [
AnalyticsLabel.english: ["endic", "eng", "ee"],
AnalyticsLabel.korean: ["krdic", "kor"],
AnalyticsLabel.hanja: ["hanja"],
AnalyticsLabel.japanese: ["jpdic", "jp"],
AnalyticsLabel.chinese: ["cndic", "ch"],
AnalyticsLabel.french: ["frdic", "fr"],
AnalyticsLabel.russian: ["ru"],
AnalyticsLabel.spanish: ["spdic"],
]
let URLPattern = DictionaryType.selectedDictionary.URLPattern
let regex = try! NSRegularExpression(pattern: URLPattern, options: .caseInsensitive)
let regexRange = NSMakeRange(0, URLString.characters.count)
guard let result = regex.firstMatch(in: URLString, options: [], range: regexRange) else {
return
}
let range = result.rangeAt(0)
let pattern = (URLString as NSString).substring(with: range)
for (type, patterns) in URLPatternsForDictionaryType {
if patterns.contains(pattern) {
AnalyticsHelper.sharedInstance().recordCachedEvent(
withCategory: AnalyticsCategory.allkdic,
action: AnalyticsAction.search,
label: type,
value: nil
)
break
}
}
}
public func webView(_ sender: WebView!, didFinishLoadFor frame: WebFrame!) {
self.indicator.stopAnimation(self)
self.indicator.isHidden = true
self.focusOnTextArea()
}
}
|
mit
|
d96b3888fbfa8ce971fc48769c8759af
| 32.676768 | 139 | 0.697361 | 4.417845 | false | false | false | false |
TheTrueTom/TransferCalculator
|
Transfer calculator/BatchViewController.swift
|
1
|
11206
|
//
// BatchViewController.swift
// Transfer calculator
//
// Created by Thomas Brichart on 16/02/2016.
// Copyright © 2016 Thomas Brichart. All rights reserved.
//
import Foundation
import Cocoa
class BatchViewController: NSViewController {
@IBOutlet weak var stopButton: NSButton!
@IBAction func stopJobList(_ sender: AnyObject) {
queue.cancelAllOperations()
currentJob?.status = .cancelled
jobListTable.reloadData()
}
@IBOutlet weak var playButton: NSButton!
@IBAction func startJobList(_ sender: AnyObject) {
processJobList() {
if let url = self.pathControl.url {
SummaryBuilder.createReport(self.jobList, url: url)
}
}
}
@IBOutlet weak var pathControl: NSPathControl!
@IBOutlet weak var jobListTable: NSTableView!
@IBOutlet weak var addButton: NSButton!
@IBAction func addJob(_ sender: AnyObject) {
let job = Job()
job.description = "Experiment #\(jobListTable.numberOfRows + 1)"
jobList.append(job)
jobListTable.reloadData()
playButton.isEnabled = true
}
@IBOutlet weak var removeButton: NSButton!
@IBAction func removeJob(_ sender: AnyObject) {
jobList = jobList.filter { !jobListTable.selectedRowIndexes.contains(jobList.index(of: $0)!) }
jobListTable.reloadData()
if jobList.isEmpty {
playButton.isEnabled = false
}
}
@IBAction func openJobList(_ sender: AnyObject) {
jobList = CSVEngine.getJobListFromCSV()
jobListTable.reloadData()
}
@IBAction func saveJobList(_ sender: AnyObject) {
CSVEngine.saveAsCSV(jobList)
}
@IBOutlet weak var progressIndicator: NSProgressIndicator!
var jobList: [Job] = [Job()]
var queue: OperationQueue = OperationQueue()
var currentJob: Job?
var distancesResultsList = [DistancesResult]()
var kTResultsList = [[(distance: Double, kT: Double)]]()
override func viewDidLoad() {
jobListTable.delegate = self
jobListTable.dataSource = self
playButton.isEnabled = true
pathControl.url = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first
}
func processJobList(_ completionHandler: (() -> Void)? = nil) {
stopButton.isEnabled = true
playButton.isEnabled = false
queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
for job in jobList {
let operation = BlockOperation(block: {
self.currentJob = job
OperationQueue.main.addOperation {
job.status = .inProgress
self.jobListTable.reloadData()
self.progressIndicator.doubleValue = 0
self.progressIndicator.maxValue = Double(job.repeats)
}
// Calcul des distances
let distancesResult = job.getAverageDistances(job.repeats, repeatCompletionHandler: {
OperationQueue.main.addOperation {
self.progressIndicator.increment(by: (job.kTCalculations == .none) ? 1 : 0.5)
}
})
OperationQueue.main.addOperation {
self.distancesResultsList.append(distancesResult)
if job.kTCalculations == .none {
job.status = .finished
self.jobListTable.reloadData()
completionHandler?()
}
}
// Calcul des kT
if job.kTCalculations != .none {
let relation: RelationType = (job.kTCalculations == .donorDonor) ? .donorDonor : ((job.kTCalculations == .donorAcceptor) ? .donorAcceptor : .acceptorAcceptor)
let kTResults = job.maxKTAsCSV(relation, repeats: job.repeats, repeatCompletionHandler: {
OperationQueue.main.addOperation {
self.progressIndicator.increment(by: 0.5)
}
})
OperationQueue.main.addOperation {
self.kTResultsList.append(kTResults)
job.status = .finished
self.jobListTable.reloadData()
completionHandler?()
}
}
})
queue.addOperation(operation)
}
DispatchQueue.global(qos: .default).async {
self.queue.waitUntilAllOperationsAreFinished()
DispatchQueue.main.async {
self.stopButton.isEnabled = false
self.playButton.isEnabled = true
}
}
}
}
extension BatchViewController: NSTableViewDelegate, NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return jobList.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let job = jobList[row]
if let identifier = tableColumn?.identifier {
switch identifier {
case "numberCol":
return configureLabel("\(row + 1)")
case "descriptionCol":
return configureLabel(job.description, row: row, tableColumnIdentifier: identifier)
case "radiusCol":
return configureLabel("\(job.particleRadius)", row: row, tableColumnIdentifier: identifier)
case "donorsCol":
return configureLabel("\(job.donors)", row: row, tableColumnIdentifier: identifier)
case "acceptorsCol":
return configureLabel("\(job.acceptors)", row: row, tableColumnIdentifier: identifier)
case "exclusionCol":
return configureLabel("\(job.exclusionRadius)", row: row, tableColumnIdentifier: identifier)
case "dimerCol":
return configureLabel("\(job.dimerProbability)", row: row, tableColumnIdentifier: identifier)
case "repeatsCol":
return configureLabel("\(job.repeats)", row: row, tableColumnIdentifier: identifier)
case "kTCol":
return configurePopUpButton(job, row: row, tableColumnIdentifier: identifier)
case "statusCol":
return configureStatusImage(job)
default:
return nil
}
}
return nil
}
func configureLabel(_ text: String, row: Int = 0, tableColumnIdentifier: String = "") -> NSTextField {
let label = CellTextField()
label.delegate = self
label.row = row
label.columnIdentifier = tableColumnIdentifier
label.stringValue = text
label.isBordered = false
label.backgroundColor = NSColor.clear
return label
}
func configureStatusImage(_ job: Job) -> NSImageView {
var imageView = NSImageView()
switch job.status {
case .cancelled:
imageView.image = NSImage(named: "cancelled")
case .finished:
imageView.image = NSImage(named: "complete")
case .inProgress:
imageView = NSAnimatedImageView(imageList: ["working0", "working1", "working2", "working3", "working4", "working5"])
case .queued:
imageView.image = NSImage()
}
return imageView
}
func configurePopUpButton(_ job: Job, row: Int = 0, tableColumnIdentifier: String = "") -> NSPopUpButton {
let popup = CellPopUpButton()
popup.action = #selector(BatchViewController.popUpButtonDidChange(_:))
popup.row = row
popup.columnIdentifier = tableColumnIdentifier
popup.addItems(withTitles: ["None","Donor-Donor","Donor-Acceptor","Acceptor-Acceptor"])
let title: String!
if job.kTCalculations == .none {
title = "None"
} else if job.kTCalculations == .donorDonor {
title = "Donor-Donor"
} else if job.kTCalculations == .donorAcceptor {
title = "Donor-Acceptor"
} else {
title = "Acceptor-Acceptor"
}
popup.selectItem(withTitle: title)
return popup
}
func tableViewSelectionDidChange(_ notification: Notification) {
if jobListTable.selectedRowIndexes.count != 0 {
removeButton.isEnabled = true
} else {
removeButton.isEnabled = false
}
}
}
extension BatchViewController: NSTextFieldDelegate {
override func controlTextDidEndEditing(_ obj: Notification) {
if let cellTextField = obj.object as? CellTextField {
let job = jobList[cellTextField.row]
switch cellTextField.columnIdentifier {
case "descriptionCol":
job.description = cellTextField.stringValue
case "radiusCol":
if let particleRadius = Double(cellTextField.stringValue) {
job.particleRadius = particleRadius
}
case "donorsCol":
if let donors = Int(cellTextField.stringValue) {
job.donors = donors
}
case "acceptorsCol":
if let acceptors = Int(cellTextField.stringValue) {
job.acceptors = acceptors
}
case "exclusionCol":
if let exclusionRadius = Double(cellTextField.stringValue) {
job.exclusionRadius = exclusionRadius
}
case "dimerCol":
if let dimerProbability = Double(cellTextField.stringValue) {
job.dimerProbability = dimerProbability
}
case "repeatsCol":
if let repeats = Int(cellTextField.stringValue) {
job.repeats = repeats
}
default:
return
}
}
}
func popUpButtonDidChange(_ obj: AnyObject) {
if let popUpButton = obj as? CellPopUpButton {
let job = jobList[popUpButton.row]
switch popUpButton.title {
case "None":
job.kTCalculations = .none
case "Donor-Donor":
job.kTCalculations = .donorDonor
case "Donor-Acceptor":
job.kTCalculations = .donorAcceptor
case "Acceptor-Acceptor":
job.kTCalculations = .acceptorAcceptor
default:
return
}
}
}
}
|
mit
|
cedd0ed1ecfe84ee25343bdc1e923e58
| 34.684713 | 178 | 0.543507 | 5.3948 | false | false | false | false |
TotemTraining/PracticaliOSAppSecurity
|
V6/Keymaster/Keymaster/CategoriesCollectionViewController.swift
|
5
|
3379
|
//
// CategoriesCollectionViewController.swift
// Keymaster
//
// Created by Chris Forant on 4/22/15.
// Copyright (c) 2015 Totem. All rights reserved.
//
import UIKit
let reuseIdentifier = "Cell"
let highlightColor = UIColor(red:0.99, green:0.67, blue:0.16, alpha:1)
class CategoriesCollectionViewController: UICollectionViewController {
let categories = ["Household" , "Finance", "Computer", "Mobile", "Email", "Shopping", "User Accounts", "Secrets", "Music", "ID", "Biometrics", "Media"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "SEGUE_ENTRIES":
let vc = segue.destinationViewController as! EntriesViewController
if let selectedIndex = (collectionView?.indexPathsForSelectedItems().last as? NSIndexPath)?.row {
vc.category = categories[selectedIndex]
}
default: return
}
}
}
}
// MARK: - Collection View Datasource
extension CategoriesCollectionViewController {
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return count(categories)
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CategoryCell
// Configure the cell
cell.categoryImageView.image = UIImage(named: categories[indexPath.row])
cell.categoryImageView.highlightedImage = UIImage(named: categories[indexPath.row])?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
return cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader: return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SectionHeader", forIndexPath: indexPath) as! SectionHeaderView
case UICollectionElementKindSectionFooter: return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SectionFooter", forIndexPath: indexPath) as! SectionFooterView
default: return UICollectionReusableView()
}
}
override func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
cell?.contentView.backgroundColor = highlightColor
}
override func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
cell?.contentView.backgroundColor = UIColor.clearColor()
}
}
|
mit
|
b2c617891089f07772c2f81557255308
| 42.320513 | 202 | 0.717964 | 6.110307 | false | false | false | false |
Palleas/Rewatch
|
Rewatch/Model/StoredShow.swift
|
1
|
923
|
//
// StoredShow.swift
// Rewatch
//
// Created by Romain Pouclet on 2015-11-03.
// Copyright © 2015 Perfectly-Cooked. All rights reserved.
//
import Foundation
import CoreData
class StoredShow: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
extension StoredShow {
static func showInContext(context: NSManagedObjectContext, mappedOnShow show: Show) -> StoredShow {
// TODO use throws + attemptMap ?
let stored: StoredShow
if let localStored = showWithId(show.id, inContext: context) {
stored = context.objectWithID(localStored.objectID) as! StoredShow
} else {
stored = NSEntityDescription.insertNewObjectForEntityForName("Show", inManagedObjectContext: context) as! StoredShow
}
stored.id = Int64(show.id)
stored.title = show.title
return stored
}
}
|
mit
|
5ef7ab0a008b6c85b924db9ed66a233f
| 24.638889 | 128 | 0.673536 | 4.519608 | false | false | false | false |
doo/das-quadrat
|
Source/Shared/Endpoints/Multi.swift
|
1
|
1852
|
//
// Multi.swift
// Quadrat
//
// Created by Constantine Fry on 17/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
public class Multi: Endpoint {
override var endpoint : String {
return "multi"
}
/**
Returns task to make request to `multi` endpoint.
Use `subresponses` property of response object.
*/
public func get(tasks:[Task], completionHandler: ResponseClosure) -> Task {
let firstTask = tasks.first as Task!
var queries = [String]()
for task in tasks {
let request = task.request
let path = "/" + request.path.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())!
if request.parameters != nil {
let query = path + makeQuery(request.parameters!)
queries.append(query)
} else {
queries.append(path)
}
}
let queryString = ",".join(queries)
let request =
Request(baseURL: firstTask.request.baseURL,
path: self.endpoint,
parameters: [Parameter.requests:queryString],
sessionParameters: firstTask.request.sessionParameters,
HTTPMethod: "POST")
let multiTask = DataTask(session: self.session!, request: request, completionHandler: completionHandler)
return multiTask
}
func makeQuery(parameters: Parameters) -> String {
var query = String()
for (key,value) in parameters {
let encodedValue = value.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
query += key + "=" + encodedValue! + "&"
}
query.removeAtIndex(query.endIndex.predecessor())
return query
}
}
|
bsd-2-clause
|
dd27c1ca844826d0d89a741fb8e07f41
| 31.491228 | 125 | 0.602052 | 5.144444 | false | false | false | false |
codepgq/WeiBoDemo
|
PQWeiboDemo/PQWeiboDemo/classes/NewFeature 新特性/PQNewFeatureCollectionViewController.swift
|
1
|
5217
|
//
// PQNewFeatureCollectionViewController.swift
// PQWeiboDemo
//
// Created by ios on 16/9/29.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class PQNewFeatureCollectionViewController: UICollectionViewController {
/// 一共有几页
private let itemCount = 4;
private var layout : UICollectionViewFlowLayout = NewFeatureLayout()
//设置布局,这里需要注意的是collectionView默认的初始化函数是带参数的这个,而不是不带参数的
init(){
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.register(CollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemCount
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CollectionCell
cell.imageIndex = indexPath.item
return cell
}
//完全显示一个Cell是调用
override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//这里需要注意的是,indexPath拿到的是上一个cell的索引
// print(indexPath)
//在一般情况下,我们可能会看到很多个CollectionViewCell,但是这里我们把Cell大小设置成为了全屏大小,所以这里我们可以使用这个方法去获取已经在屏幕上显示的Cell的indexPath
let index = collectionView.indexPathsForVisibleItems.last
if index?.item == itemCount - 1 {
let cel = collectionView.cellForItem(at: index!) as! CollectionCell
cel.startButtonAnimation()
}
}
}
/// Cell
private class CollectionCell: UICollectionViewCell {
var imageIndex : Int?{
didSet{
imageView.image = UIImage(named: "new_feature_\(imageIndex! + 1)")
joinIndexBtn.isHidden = true
}
}
func startButtonAnimation() {
joinIndexBtn.isHidden = true
joinIndexBtn.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
joinIndexBtn.isUserInteractionEnabled = false
UIView.animate(withDuration: 0.75, delay: 0.15, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: UIViewAnimationOptions.init(rawValue: 0), animations: {
self.joinIndexBtn.transform = CGAffineTransform.identity
self.joinIndexBtn.isHidden = false
}) { (_) in
self.joinIndexBtn.isUserInteractionEnabled = true
}
}
override init(frame: CGRect) {
super.init(frame: frame)
///初始化UI
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setUpUI(){
contentView.addSubview(imageView)
contentView.addSubview(joinIndexBtn)
imageView.pq_fill(referView: contentView)
joinIndexBtn.pq_AlignInner(type: pq_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
}
private lazy var imageView : UIImageView = UIImageView()
private lazy var joinIndexBtn :UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "new_feature_button"), for: .normal)
button.setImage(UIImage(named: "new_feature_button_highlighted"), for: .highlighted)
button.addTarget(self, action: #selector(CollectionCell.joinIndexPage), for: .touchUpInside)
button.sizeToFit()
button.isHidden = true
return button
}()
@objc private func joinIndexPage() -> Void {
// 去主页
NotificationCenter.default.post(name: NSNotification.Name(rawValue: PQChangeRootViewControllerKey), object: true)
}
}
private class NewFeatureLayout : UICollectionViewFlowLayout{
fileprivate override func prepare() {
//设置layout 大小、Item之间的间距、排列方向
itemSize = UIScreen.main.bounds.size
minimumLineSpacing = 0
minimumInteritemSpacing = 0
scrollDirection = .horizontal
//设置collectionView的属性
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.bounces = false
collectionView?.isPagingEnabled = true
}
}
|
mit
|
6091125eabe2c296824e3d949bd32acf
| 31.197368 | 175 | 0.661422 | 5.071503 | false | false | false | false |
plantain-00/demo-set
|
swift-demo/NewsCatcher/Ridge/Ridge/CommentParser.swift
|
1
|
1131
|
//
// CommentParser.swift
// Ridge
//
// Created by 姚耀 on 15/1/30.
// Copyright (c) 2015年 姚耀. All rights reserved.
//
import Foundation
class CommentParser: ParserBase {
init(strings: [String], index: Int, endIndex: Int, depth: Int) {
self.depth = depth
super.init(strings: strings, index: index, endIndex: endIndex)
}
private let depth: Int
var comment: Comment?
override func parse() {
if strings[index] != StringStatic.lessThan
|| !strings[index + 1].hasPrefix(StringStatic.commentStart) {
fatalError("This situation is surprising.")
}
comment = Comment(text: StringStatic.empty, depth: depth)
index++
findEndOfCommentThenGetComment()
}
private func findEndOfCommentThenGetComment() {
while index < endIndex
&& (!strings[index].hasSuffix(StringStatic.commentEnd)
|| strings[index + 1] != StringStatic.largeThan) {
comment!.text += strings[index]
index++
}
comment!.text += strings[index]
index += 2
}
}
|
mit
|
d8c622d3547ecaca3dbff7f451dc37ac
| 25.093023 | 77 | 0.594112 | 4.167286 | false | false | false | false |
yashvyas29/YVSwiftTableForms
|
YVSwiftTableFormsExample/Resources/YVSwiftTableForms/YVSubClasses/YVTextFieldValidator.swift
|
1
|
13221
|
//
// YVTextFieldValidator.swift
// YVSwiftTableForms
//
// Created by Yash on 10/05/16.
// Copyright © 2016 Yash. All rights reserved.
//
import UIKit
let numberCharacterSet = NSCharacterSet.decimalDigitCharacterSet()
let alphabetCharacterSet : NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
let specialSymbolsCharacterSet : NSCharacterSet = NSCharacterSet(charactersInString: "!~`@#$%^&*-+();:=_{}[],.<>?\\/|\"\'")
class YVTextFieldValidator: UITextField, UITextFieldDelegate {
//** properties which will decide which kind of validation user wants
var ParentDelegate : AnyObject?
var checkForEmptyTextField : Bool = false
var allowOnlyNumbers : Bool = false
var allowOnlyAlphabets : Bool = false
var restrictSpecialSymbolsOnly : Bool = false
var checkForValidEmailAddress : Bool = false
var restrictTextFieldToLimitedCharecters : Bool = false
var setNumberOfCharectersToBeRestricted : Int = 0
var allowToShowAlertView : Bool = false
var alertControllerForNumberOnly = UIAlertController()
var alertControllerForAlphabetsOnly = UIAlertController()
var alertControllerForSpecialSymbols = UIAlertController()
var alertControllerForInvalidEmailAddress = UIAlertController()
//MARK: awakeFromNib
// Setting the delegate to Class's instance
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
}
//MARK: validation methods
// 01. This method will check if there are any blank textFields in class
class func checkIfAllFieldsAreFilled(view:UIView) -> Bool{
let subviews : NSArray = view.subviews
if(subviews.count == 0){
return false
}
for currentObject in subviews{
if let currentObject = currentObject as? UITextField {
if((currentObject.text?.isEmpty) != nil){
YVTextFieldValidator.shaketextField(currentObject)
}
}
self.checkIfAllFieldsAreFilled(currentObject as! UIView)
}
return true
}
// 02. This method will check if there are any white space in the textField.
class func checkForWhiteSpaceInTextField(inputString : String) -> String{
let trimmedString = inputString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return trimmedString
}
// 03. This method will allow only numbers in the textField.
func allowOnlyNumbersInTextField(string : String)->Bool{
let numberCharacterSet = NSCharacterSet.decimalDigitCharacterSet()
let inputString = string
let range = inputString.rangeOfCharacterFromSet(numberCharacterSet)
print(inputString)
// range will be nil if no numbers are found
if range != nil {
return true
}
else {
return false
// do your stuff
}
}
// 04. This method will allow only alphabets in the textField.
func allowOnlyAlphabetsInTextField(string : String)->Bool{
let inputString = string
let range = inputString.rangeOfCharacterFromSet(alphabetCharacterSet)
print(inputString)
// range will be nil if no alphabet are found
if range != nil {
return true
}
else {
return false
// do your stuff
}
}
// 05. This method will restrict only special symbols in the textField.
func restrictSpecialSymbols(string : String) -> Bool
{
let range = string.rangeOfCharacterFromSet(specialSymbolsCharacterSet.invertedSet)
print(string)
// range will be nil if no specialSymbol are found
if range != nil {
return true
}
else {
return false
// do your stuff
}
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
if(checkForValidEmailAddress){
let emailReg = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let range = textField.text!.rangeOfString(emailReg, options:.RegularExpressionSearch)
let result = range != nil ? true : false
print(result)
if(result){
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForInvalidEmailAddress, animated: true, completion: nil)
return false
}
}
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if(allowOnlyNumbers){
if(string == ""){
return true
}
let flag : Bool = self.allowOnlyNumbersInTextField(string)
if(flag){
return true
}
else{
if(allowToShowAlertView){
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForNumberOnly, animated: true, completion: nil)
return false
}
}
}
else if(allowOnlyAlphabets){
if(string == "") {
return true
}
let flag : Bool = self.allowOnlyAlphabetsInTextField(string)
if(flag) {
return true
}
else {
if(allowToShowAlertView) {
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForAlphabetsOnly, animated: true, completion: nil)
return false
}
}
}
else if(restrictSpecialSymbolsOnly){
if(string == ""){
return true
}
let flag : Bool = self.restrictSpecialSymbols(string)
if(flag){
return true
}
else{
if(allowToShowAlertView){
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForSpecialSymbols, animated: true, completion: nil)
return false
}
}
}
else if(restrictTextFieldToLimitedCharecters){
let newLength = textField.text!.characters.count + string.characters.count - range.length
return newLength <= setNumberOfCharectersToBeRestricted
}
else{
return true
}
return false
}
//MARK: Setter methods
func setFlagForAllowNumbersOnly(flagForNumbersOnly : Bool){
allowOnlyNumbers = flagForNumbersOnly
}
func setFlagForAllowAlphabetsOnly(flagForAlphabetsOnly : Bool){
allowOnlyAlphabets = flagForAlphabetsOnly
}
func setFlagForRestrictSpecialSymbolsOnly(RestrictSpecialSymbols : Bool){
restrictSpecialSymbolsOnly = RestrictSpecialSymbols
}
func setFlagForcheckForValidEmailAddressOnly(flagForValidEmailAddress : Bool){
checkForValidEmailAddress = flagForValidEmailAddress
}
func setFlagForLimitedNumbersOFCharecters(numberOfCharacters : Int,flagForLimitedNumbersOfCharacters : Bool){
restrictTextFieldToLimitedCharecters = flagForLimitedNumbersOfCharacters
setNumberOfCharectersToBeRestricted = numberOfCharacters
}
//MARK: show alert methods
func showAlertForNumberOnly(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForNumberOnly = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForNumberOnly.addAction(buttonAction)
}
}
func showAlertForAlphabetsOnly(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForAlphabetsOnly = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForAlphabetsOnly.addAction(buttonAction)
}
}
func showAlertForSpecialSymbolsOnly(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForSpecialSymbols = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForSpecialSymbols.addAction(buttonAction)
}
}
func showAlertForinvalidEmailAddrress(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForInvalidEmailAddress = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForInvalidEmailAddress.addAction(buttonAction)
}
}
//MARK: Shake TextField
class func shaketextField(textfield : UITextField) {
let shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
let from_point:CGPoint = CGPointMake(textfield.center.x - 5, textfield.center.y)
let from_value:NSValue = NSValue(CGPoint: from_point)
let to_point:CGPoint = CGPointMake(textfield.center.x + 5, textfield.center.y)
let to_value:NSValue = NSValue(CGPoint: to_point)
shake.fromValue = from_value
shake.toValue = to_value
textfield.layer.addAnimation(shake, forKey: "position")
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
|
gpl-3.0
|
0722126da92eb8679acb3b7308b1fd56
| 33.516971 | 174 | 0.593116 | 5.750326 | false | false | false | false |
sigito/material-components-ios
|
components/TextFields/tests/unit/TextInputProtocolTests.swift
|
4
|
5771
|
/*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
import MaterialComponents.MaterialTextFields
class TextInputTests: XCTestCase {
func testMDCTextInputProtocolConformanceSingleline() {
let textField = MDCTextField()
XCTAssertNotNil(textField.cursorColor)
XCTAssertNotNil(textField.leadingUnderlineLabel)
XCTAssertNotNil(textField.trailingUnderlineLabel)
XCTAssertNotNil(textField.placeholderLabel)
textField.borderView?.borderFillColor = .purple
XCTAssertEqual(textField.borderView?.borderFillColor, .purple)
let borderPath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
textField.borderView?.borderPath = borderPath
XCTAssertEqual(textField.borderView?.borderPath, borderPath)
textField.borderView?.borderStrokeColor = .orange
XCTAssertEqual(textField.borderView?.borderStrokeColor, .orange)
textField.clearButton.tintColor = .red
XCTAssertEqual(textField.clearButton.tintColor, .red)
textField.cursorColor = .yellow
XCTAssertEqual(textField.cursorColor, .yellow)
textField.borderView?.borderFillColor = nil
XCTAssertNotEqual(textField.borderView?.borderFillColor, .purple)
textField.borderView?.borderPath = nil
XCTAssertNotEqual(textField.borderView?.borderPath, borderPath)
textField.borderView?.borderStrokeColor = nil
XCTAssertNotEqual(textField.borderView?.borderStrokeColor, .orange)
let font = UIFont.boldSystemFont(ofSize: 6)
textField.font = font
XCTAssertEqual(font, textField.font)
let testLeading = "Helper Test"
textField.leadingUnderlineLabel.text = testLeading
XCTAssertEqual(testLeading, textField.leadingUnderlineLabel.text)
let testPlaceholder = "Test placeholder"
textField.placeholder = testPlaceholder
XCTAssertEqual(testPlaceholder, textField.placeholder)
let testText = "Test text"
textField.text = testText
XCTAssertEqual(testText, textField.text)
textField.textColor = .red
XCTAssertEqual(.red, textField.textColor)
let trailingView = UIView()
textField.trailingView = trailingView
XCTAssertEqual(textField.trailingView, trailingView)
let testTrailing = "NN / NN"
textField.trailingUnderlineLabel.text = testTrailing
XCTAssertEqual(testTrailing, textField.trailingUnderlineLabel.text)
textField.underline?.color = .red
XCTAssertEqual(.red, textField.underline?.color)
let width: CGFloat = 5.0
textField.underline?.lineHeight = width
XCTAssertEqual(width, textField.underline?.lineHeight)
}
func testMDCTextInputProtocolConformanceMultiline() {
let textField = MDCMultilineTextField()
XCTAssertNotNil(textField.leadingUnderlineLabel)
XCTAssertNotNil(textField.trailingUnderlineLabel)
XCTAssertNotNil(textField.placeholderLabel)
textField.borderView?.borderFillColor = .purple
XCTAssertEqual(textField.borderView?.borderFillColor, .purple)
let borderPath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
textField.borderView?.borderPath = borderPath
XCTAssertEqual(textField.borderView?.borderPath, borderPath)
textField.borderView?.borderStrokeColor = .orange
XCTAssertEqual(textField.borderView?.borderStrokeColor, .orange)
textField.borderView?.borderFillColor = nil
XCTAssertNotEqual(textField.borderView?.borderFillColor, .purple)
textField.borderView?.borderPath = nil
XCTAssertNotEqual(textField.borderView?.borderPath, borderPath)
textField.borderView?.borderStrokeColor = nil
XCTAssertNotEqual(textField.borderView?.borderStrokeColor, .orange)
textField.clearButton.tintColor = .red
XCTAssertEqual(textField.clearButton.tintColor, .red)
textField.cursorColor = .yellow
XCTAssertEqual(textField.cursorColor, .yellow)
let gray = UIColor.gray
textField.textColor = gray.copy() as? UIColor
XCTAssertEqual(textField.textColor, gray)
let testText = "Test text"
textField.text = testText
XCTAssertEqual(textField.text, testText)
let testPlaceholder = "Test placeholder"
textField.placeholder = testPlaceholder
XCTAssertEqual(textField.placeholder, testPlaceholder)
textField.underline?.color = gray.copy() as? UIColor
XCTAssertEqual(textField.underline?.color, gray)
let width: CGFloat = 5.0
textField.underline?.lineHeight = width
XCTAssertEqual(textField.underline?.lineHeight, width)
let testLeading = "Helper Test"
textField.leadingUnderlineLabel.text = testLeading
XCTAssertEqual(textField.leadingUnderlineLabel.text, testLeading)
let testTrailing = "NN / NN"
textField.trailingUnderlineLabel.text = testTrailing
XCTAssertEqual(textField.trailingUnderlineLabel.text, testTrailing)
let controller = MDCTextInputControllerLegacyDefault(textInput: textField)
XCTAssertNotNil(controller.textInput)
}
func testMDCMultilineTextInputProtocolConformance() {
let textField = MDCMultilineTextField()
XCTAssertEqual(textField.minimumLines, 1)
textField.minimumLines = 3
XCTAssertEqual(textField.minimumLines, 3)
textField.minimumLines = 0
XCTAssertEqual(textField.minimumLines, 1)
}
}
|
apache-2.0
|
e9c93c088680d98e6f04d19917452b50
| 34.404908 | 86 | 0.770924 | 5.175785 | false | true | false | false |
wyzzarz/SwiftCollection
|
SwiftCollection/SwiftCollection/SCExtensions.swift
|
1
|
2616
|
//
// SCExtensions.swift
//
// Copyright 2017 Warner Zee
//
// 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
extension UInt64 {
/// Generates a random integer within the upper and lower bounds.
///
/// - Parameters:
/// - upper: Upper bounds for the randomizer. Defaults to max.
/// - lower: Lower bounds for the randomizer. Defaults to min.
/// - Returns: A random integer.
public static func random(upper: UInt64 = max, lower: UInt64 = min) -> UInt64 {
// calculate total random length
let length: UInt64 = upper - lower
// if the length is less than what the randomizer returns, then just make one call
if length < UInt64(UInt32.max) { return UInt64(arc4random_uniform(UInt32(length))) + lower }
// otherwise get a random number as the sum of two randomizer calls
let remainder = UInt64(length - UInt64(UInt32.max)) >> 32
let random1 = UInt64(arc4random_uniform(UInt32.max))
let random2 = UInt64(arc4random_uniform(UInt32(remainder)))
return random1 + random2 + lower
}
}
extension UInt32 {
/// Generates a random integer within the upper and lower bounds.
///
/// - Parameters:
/// - upper: Upper bounds for the randomizer. Defaults to max.
/// - lower: Lower bounds for the randomizer. Defaults to min.
/// - Returns: A random integer.
public static func random(upper: UInt32 = max, lower: UInt32 = min) -> UInt32 {
return arc4random_uniform(upper - lower) + lower
}
}
extension String {
/// Enlarges a string by padding it with a character. If the string is equal to or greater than
/// the specified length, then the string is unchanged.
///
/// - Parameters:
/// - length: Length to pad the string to.
/// - c: Character to be inserted on the left.
/// - Returns: A left padded string. Or the original string if padding is unecessary.
public func padding(toLength length: Int, withLeftPad c: Character) -> String {
let diff = length - count
if diff <= 0 { return self }
return String(repeating: String(c), count: diff) + self
}
}
|
apache-2.0
|
11d8cf3894e6d45e063b6f10d3ce1a52
| 35.333333 | 98 | 0.683486 | 3.858407 | false | false | false | false |
webim/webim-client-sdk-ios
|
WebimClientLibrary/Backend/SurveyController.swift
|
1
|
3636
|
//
// SurveyController.swift
// WebimClientLibrary
//
// Created by Nikita Kaberov on 01.08.20.
// Copyright © 2020 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/**
- author:
Nikita Kaberov
- copyright:
2020 Webim
*/
final class SurveyController {
// MARK: - Properties
private weak var surveyListener: SurveyListener?
private var survey: Survey?
private var currentFormPointer = 0
private var currentQuestionPointer = 0
// MARK: - Initialization
init(surveyListener: SurveyListener) {
self.surveyListener = surveyListener
}
// MARK: - Methods
func set(survey: Survey) {
self.survey = survey
setCurrentQuestionPointer()
surveyListener?.on(survey: survey)
}
func getSurvey() -> Survey? {
return survey
}
func getCurrentFormID() -> Int {
let forms = survey?.getConfig().getDescriptor().getForms()
return forms?[currentFormPointer].getID() ?? 0
}
func getCurrentQuestionPointer() -> Int {
return currentQuestionPointer
}
func nextQuestion() {
if let question = getCurrentQuestion() {
surveyListener?.on(nextQuestion: question)
}
}
func cancelSurvey() {
surveyListener?.onSurveyCancelled()
survey = nil
currentFormPointer = 0
currentQuestionPointer = 0
}
private func getCurrentQuestion() -> SurveyQuestion? {
guard let survey = survey else {
return nil
}
let forms = survey.getConfig().getDescriptor().getForms()
guard forms.count > currentFormPointer else {
return nil
}
let form = forms[currentFormPointer]
let questions = form.getQuestions()
currentQuestionPointer += 1
if questions.count <= currentQuestionPointer {
currentQuestionPointer = -1
currentFormPointer += 1
return getCurrentQuestion()
}
return questions[currentQuestionPointer]
}
private func setCurrentQuestionPointer() {
guard let survey = survey else {
return
}
let forms = survey.getConfig().getDescriptor().getForms()
let questionInfo = survey.getCurrentQuestionInfo()
currentQuestionPointer = questionInfo.getQuestionID() - 1
for (i, form) in forms.enumerated() {
if form.getID() == questionInfo.getFormID() {
currentFormPointer = i
break
}
}
}
}
|
mit
|
89705d58b2fc32ac690f0b2fe7b811fb
| 30.068376 | 82 | 0.653095 | 4.67825 | false | false | false | false |
TrondKjeldas/KnxBasics2
|
Source/KnxOnOffControl.swift
|
1
|
4734
|
//
// KnxOnOffControl.swift
// KnxBasics2
//
// The KnxBasics2 framework provides basic interworking with a KNX installation.
// Copyright © 2016 Trond Kjeldås ([email protected]).
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License Version 2.1
// as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
import Foundation
import SwiftyBeaver
/// Class representing a light switch.
open class KnxOnOffControl: KnxTelegramResponseHandlerDelegate {
// MARK: Public API:
/**
Initializes a new object.
- parameter setOnOffAddress: The group address to use for turning light on and off.
*/
public init(setOnOffAddress: KnxGroupAddress,
responseHandler: KnxOnOffResponseHandlerDelegate) {
onOffAddress = setOnOffAddress
self._lightOn = false
self.responseHandler = responseHandler
onOffInterface = KnxRouterInterface.getKnxRouterInstance()
if let onOffInterface = onOffInterface {
// TODO: Better error handling!
try! onOffInterface.connect()
onOffInterface.subscribeFor(address: setOnOffAddress,
responseHandler: self)
readState()
}
}
/**
Trigger reading of switch state.
*/
open func readState() {
onOffInterface?.sendReadRequest(to: onOffAddress)
}
/// Read/write property holding the on/off state.
open var lightOn: Bool {
get {
return _lightOn
}
set {
if newValue != _lightOn {
_lightOn = newValue
log.verbose("lightOn soon: \(_lightOn)")
onOffInterface?.sendWriteRequest(to: onOffAddress, type: .dpt10_001, value: _lightOn ? 1 : 0)
}
}
}
/**
Handler for telegram responses.
- parameter sender: The interface the telegran were received on.
- parameter telegram: The received telegram.
*/
open func subscriptionResponse(sender: AnyObject?, telegram: KnxTelegram) {
let type: KnxTelegramType
switch KnxRouterInterface.connectionType {
case .tcpDirect:
let interface = sender as! KnxRouterInterface
if interface == onOffInterface {
type = KnxGroupAddressRegistry.getTypeForGroupAddress(address: onOffAddress)
do {
let val: Int = try telegram.getValueAsType(type: type)
_lightOn = Bool(truncating: NSNumber(value:val))
responseHandler?.onOffResponse(sender: onOffAddress,
state: _lightOn)
} catch KnxException.illformedTelegramForType {
log.error("Illegal telegram type...")
} catch let error as NSError {
log.error("Error: \(error)")
}
}
case .udpMulticast:
let srcAddress = telegram.getGroupAddress()
if srcAddress == onOffAddress {
type = KnxGroupAddressRegistry.getTypeForGroupAddress(address: onOffAddress)
do {
let val: Int = try telegram.getValueAsType(type: type)
_lightOn = Bool(truncating: NSNumber(value:val))
responseHandler?.onOffResponse(sender: onOffAddress,
state: _lightOn)
} catch KnxException.illformedTelegramForType {
log.error("Illegal telegram type...")
} catch let error as NSError {
log.error("Error: \(error)")
}
}
default:
log.error("Connection type not set")
}
log.debug("HANDLING: \(telegram.payload)")
}
// MARK: Internal and private declarations
fileprivate var onOffAddress: KnxGroupAddress
fileprivate var onOffInterface: KnxRouterInterface?
fileprivate var responseHandler: KnxOnOffResponseHandlerDelegate?
fileprivate var _lightOn: Bool
fileprivate let log = SwiftyBeaver.self
}
|
lgpl-2.1
|
caae8252333c70799104ffc37f7f9911
| 29.928105 | 109 | 0.604184 | 4.883385 | false | false | false | false |
xmkevinchen/CKMessagesKit
|
Sample/RootViewController.swift
|
1
|
4965
|
//
// RootViewController.swift
// CKMessagesKit
//
// Created by Chen Kevin on 9/13/16.
// Copyright © 2016 Kevin Chen. All rights reserved.
//
import UIKit
import Reusable
protocol SegueHandler {
associatedtype SegueIdentifier: RawRepresentable
}
extension SegueHandler where Self: UIViewController, SegueIdentifier.RawValue == String {
func performSegue(withIdentifier identifier: SegueIdentifier, sender: AnyObject?) {
performSegue(withIdentifier: identifier.rawValue, sender: sender)
}
func segueIdentifier(for segue: UIStoryboardSegue) -> SegueIdentifier {
guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else {
fatalError("Invalid segue identifier \(segue.identifier)")
}
return segueIdentifier
}
}
class RootViewController: UIViewController, SegueHandler {
enum SegueIdentifier: String {
case PushSegue
case PresentModalSegua
}
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "CKMessagesKit"
tableView.delegate = self
tableView.dataSource = self
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
switch segueIdentifier(for: segue) {
case .PushSegue:
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
case .PresentModalSegua:
if let navController = segue.destination as? UINavigationController,
let viewController = navController.viewControllers.first as? ViewController {
viewController.isModel = true
}
}
}
func dismiss(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
}
extension RootViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "PRESENTATION"
}
return nil
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfRows = 0
switch section {
case 0:
numberOfRows = 2
case 1:
numberOfRows = 2
default:
break
}
return numberOfRows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CKMessagesKitCell", for: indexPath)
var title: String?
switch (indexPath.section, indexPath.row) {
case (0, 0):
title = "Push via Storyboard"
case (0, 1):
title = "Push programmatically"
case (1, 0):
title = "Present via Storyboard"
case (1, 1):
title = "Present programmatically"
default: break
}
cell.textLabel?.text = title
cell.accessoryType = .disclosureIndicator
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch (indexPath.section, indexPath.row) {
case (0, 0):
performSegue(withIdentifier: .PushSegue, sender: nil)
case (0, 1):
let viewController = ViewController()
show(viewController, sender: nil)
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
case (1, 0):
performSegue(withIdentifier: .PresentModalSegua, sender: nil)
case (1, 1):
let viewController = ViewController()
viewController.isModel = true
let navController = UINavigationController(rootViewController: viewController)
present(navController, animated: true, completion: nil)
default:
break
}
}
}
|
mit
|
9a9aae35d867e41db68a30713489cbf9
| 27.365714 | 115 | 0.59025 | 5.732102 | false | false | false | false |
radazzouz/firefox-ios
|
Client/Frontend/Settings/Clearables.swift
|
1
|
5163
|
/* 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
import Deferred
import WebImage
private let log = Logger.browserLogger
// Removed Clearables as part of Bug 1226654, but keeping the string around.
private let removedSavedLoginsLabel = NSLocalizedString("Saved Logins", tableName: "ClearPrivateData", comment: "Settings item for clearing passwords and login data")
// A base protocol for something that can be cleared.
protocol Clearable {
func clear() -> Success
var label: String { get }
}
class ClearableError: MaybeErrorType {
fileprivate let msg: String
init(msg: String) {
self.msg = msg
}
var description: String { return msg }
}
// Clears our browsing history, including favicons and thumbnails.
class HistoryClearable: Clearable {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
var label: String {
return NSLocalizedString("Browsing History", tableName: "ClearPrivateData", comment: "Settings item for clearing browsing history")
}
func clear() -> Success {
return profile.history.clearHistory().bind { success in
SDImageCache.shared().clearDisk()
SDImageCache.shared().clearMemory()
self.profile.recentlyClosedTabs.clearTabs()
NotificationCenter.default.post(name: NotificationPrivateDataClearedHistory, object: nil)
log.debug("HistoryClearable succeeded: \(success).")
return Deferred(value: success)
}
}
}
struct ClearableErrorType: MaybeErrorType {
let err: Error
init(err: Error) {
self.err = err
}
var description: String {
return "Couldn't clear: \(err)."
}
}
// Clear the web cache. Note, this has to close all open tabs in order to ensure the data
// cached in them isn't flushed to disk.
class CacheClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cache", tableName: "ClearPrivateData", comment: "Settings item for clearing the cache")
}
func clear() -> Success {
let dataTypes = Set([WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
WKWebsiteDataStore.default().removeData(ofTypes: dataTypes, modifiedSince: Date.distantPast, completionHandler: {})
log.debug("CacheClearable succeeded.")
return succeed()
}
}
private func deleteLibraryFolderContents(_ folder: String) throws {
let manager = FileManager.default
let library = manager.urls(for: FileManager.SearchPathDirectory.libraryDirectory, in: .userDomainMask)[0]
let dir = library.appendingPathComponent(folder)
let contents = try manager.contentsOfDirectory(atPath: dir.path)
for content in contents {
do {
try manager.removeItem(at: dir.appendingPathComponent(content))
} catch where ((error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError)?.code == Int(EPERM) {
// "Not permitted". We ignore this.
log.debug("Couldn't delete some library contents.")
}
}
}
private func deleteLibraryFolder(_ folder: String) throws {
let manager = FileManager.default
let library = manager.urls(for: FileManager.SearchPathDirectory.libraryDirectory, in: .userDomainMask)[0]
let dir = library.appendingPathComponent(folder)
try manager.removeItem(at: dir)
}
// Removes all app cache storage.
class SiteDataClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Offline Website Data", tableName: "ClearPrivateData", comment: "Settings item for clearing website data")
}
func clear() -> Success {
let dataTypes = Set([WKWebsiteDataTypeOfflineWebApplicationCache])
WKWebsiteDataStore.default().removeData(ofTypes: dataTypes, modifiedSince: Date.distantPast, completionHandler: {})
log.debug("SiteDataClearable succeeded.")
return succeed()
}
}
// Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
class CookiesClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cookies", tableName: "ClearPrivateData", comment: "Settings item for clearing cookies")
}
func clear() -> Success {
let dataTypes = Set([WKWebsiteDataTypeCookies, WKWebsiteDataTypeLocalStorage, WKWebsiteDataTypeSessionStorage, WKWebsiteDataTypeWebSQLDatabases, WKWebsiteDataTypeIndexedDBDatabases])
WKWebsiteDataStore.default().removeData(ofTypes: dataTypes, modifiedSince: Date.distantPast, completionHandler: {})
log.debug("CookiesClearable succeeded.")
return succeed()
}
}
|
mpl-2.0
|
6831ce5c5d6219cc79927042153a8891
| 34.122449 | 190 | 0.702499 | 4.978785 | false | false | false | false |
pmtao/SwiftUtilityFramework
|
SwiftUtilityFramework/Foundation/Basic/String+Subscript.swift
|
1
|
1871
|
//
// String+Subscript.swift
// SwiftUtilityFramework
//
// Created by 阿涛 on 17-12-25.
// Copyright © 2017年 SinkingSoul. All rights reserved.
//
extension String {
/// 通过范围表达式形式读取字符串
/// 例如,可以使用 String[3...] 读取字符串从第 4 位到末尾的 Substring。
/// - Parameter digitIndex: 范围表达式 n...
public subscript(digitIndex: PartialRangeFrom<Int>) -> Substring? {
let lowerBound = digitIndex.lowerBound
let size = self.count
if lowerBound < 0 || lowerBound > size - 1 {
return nil
}
let lowerBoundIndex = index(startIndex, offsetBy: lowerBound)
return self[lowerBoundIndex...]
}
/// 通过范围表达式形式读取字符串
/// 例如,可以使用 String[...3] 读取字符串从第 1 位到第 4 位的 Substring。
/// - Parameter digitIndex: 范围表达式 ...n
public subscript(digitIndex: PartialRangeThrough<Int>) -> Substring? {
let upperBound = digitIndex.upperBound
let size = self.count
if upperBound < 0 || upperBound > size - 1 {
return nil
}
let upperBoundIndex = index(startIndex, offsetBy: upperBound)
return self[...upperBoundIndex]
}
/// 通过范围表达式形式读取字符串
/// 例如,可以使用 String[..<3] 读取字符串从第 1 位到第 3 位的 Substring。
/// - Parameter digitIndex: 范围表达式 ..<n
public subscript(digitIndex: PartialRangeUpTo<Int>) -> Substring? {
let upperBound = digitIndex.upperBound
let size = self.count
if upperBound < 1 || upperBound > size {
return nil
}
let upperBoundIndex = index(startIndex, offsetBy: upperBound)
return self[..<upperBoundIndex]
}
}
|
mit
|
70ddbf1339a7eae65fc00a1f78b0366d
| 29.754717 | 74 | 0.606135 | 4.168798 | false | false | false | false |
linhaosunny/smallGifts
|
小礼品/小礼品/Classes/Categories/UIImage+Extension.swift
|
1
|
1404
|
//
// UIImage+Extension.swift
// PresentGift
//
// Created by 李莎鑫 on 17/3/18.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
extension UIImage {
class func image(withColor color: UIColor,withSize size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width == 0 ? 1.0 : size.width, height: size.height == 0 ? 1.0 : size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
class func resize(withImage image:UIImage) -> UIImage {
return image.resizableImage(withCapInsets: UIEdgeInsets(top: image.size.height*0.5, left: image.size.width*0.5, bottom: image.size.height*0.5, right: image.size.width*0.5))
}
func resetImageSize(newWidth: CGFloat) -> UIImage {
let scale = newWidth / self.size.width
let newHeight = self.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
|
mit
|
eae411cde45d2834f903cb580bf0d294
| 31.302326 | 180 | 0.641469 | 4.367925 | false | false | false | false |
iOSDevLog/InkChat
|
InkChat/Pods/IBAnimatable/IBAnimatable/AnimatedTransitioning.swift
|
1
|
2167
|
//
// Created by Jake Lin on 2/24/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
/**
AnimatedTransitioning is the protocol of all Animator subclasses
*/
public protocol AnimatedTransitioning: ViewControllerAnimatedTransitioning {
/**
Transition animation type: used to specify the transition animation.
*/
var transitionAnimationType: TransitionAnimationType { get set }
/**
Reverse animation type: used to specify the revers animation for pop or dismiss.
*/
var reverseAnimationType: TransitionAnimationType? { get set }
/**
Interactive gesture type: used to specify the gesture type to pop or dismiss.
*/
var interactiveGestureType: InteractiveGestureType? { get set }
}
public extension AnimatedTransitioning {
public func animateWithCATransition(transitionContext: UIViewControllerContextTransitioning,
type: TransitionAnimationType.SystemTransitionType,
subtype: String?) {
let (_, tempToView, tempContainerView) = retrieveViews(transitionContext: transitionContext)
guard let toView = tempToView, let containerView = tempContainerView else {
transitionContext.completeTransition(true)
return
}
let (_, tempToViewController, _) = retrieveViewControllers(transitionContext: transitionContext)
if let toViewController = tempToViewController {
toView.frame = transitionContext.finalFrame(for: toViewController)
}
containerView.addSubview(toView)
CALayer.animate({
let transition = CATransition()
transition.type = type.rawValue
if let subtype = subtype {
transition.subtype = subtype
}
transition.duration = self.transitionDuration(using: transitionContext)
// Use `EaseOutQubic` for system built-in transition animations. Thanks to @lexrus
transition.timingFunction = CAMediaTimingFunction(controlPoints: 0.215, 0.61, 0.355, 1)
containerView.layer.add(transition, forKey: kCATransition)
},
completion: {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
|
apache-2.0
|
466b07dba93cc9c4323d192a02abc3fb
| 36.344828 | 100 | 0.720683 | 5.469697 | false | false | false | false |
inkyfox/KRWordWrapLabel
|
KRWordWrapLabelDemo/ViewController.swift
|
1
|
2167
|
//
// ViewController.swift
// KRWordWrapLabelApp
//
// Created by Yoo YongHa on 2016. 3. 5..
// Copyright © 2016년 Gen X Hippies Company. All rights reserved.
//
import UIKit
import KRWordWrapLabel
class ViewController: UIViewController {
@IBOutlet weak var container: UIView!
@IBOutlet weak var label: KRWordWrapLabel!
@IBOutlet weak var alignmentSegment: UISegmentedControl!
@IBOutlet weak var maxLinesStepper: UIStepper!
@IBOutlet weak var fontSizeStepper: UIStepper!
@IBOutlet weak var minFontScaleStepper: UIStepper!
@IBOutlet weak var widthStepper: UIStepper!
@IBOutlet weak var maxLinesLabel: UILabel!
@IBOutlet weak var fontSizeLabel: UILabel!
@IBOutlet weak var minFontScaleLabel: UILabel!
@IBOutlet weak var widthLabel: UILabel!
@IBOutlet weak var labelWidthConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
updateLabel()
}
override func viewDidAppear(_ animated: Bool) {
labelWidthConstraint.constant = min(CGFloat(widthStepper.maximumValue), (self.view.window?.frame.width ?? 320) - 48)
widthStepper.value = Double(labelWidthConstraint.constant)
widthLabel.text = "\(widthStepper.value)"
}
fileprivate func updateLabel() {
let index = alignmentSegment.selectedSegmentIndex
label.textAlignment = index == 1 ? .center : index == 2 ? .right: .left
label.numberOfLines = Int(maxLinesStepper.value)
label.font = label.font.withSize(CGFloat(fontSizeStepper.value))
label.minimumScaleFactor = CGFloat(minFontScaleStepper.value)
maxLinesLabel.text = "\(label.numberOfLines)"
fontSizeLabel.text = "\(label.font.pointSize)"
minFontScaleLabel.text = NSString(format: "%.01f", label.minimumScaleFactor) as String
}
@IBAction func updateLabel(_ sender: AnyObject) {
updateLabel()
}
@IBAction func updateWidth(_ sender: AnyObject) {
labelWidthConstraint.constant = CGFloat(widthStepper.value)
widthLabel.text = "\(widthStepper.value)"
}
}
|
mit
|
56cb2d57f328c59d6dc58ce5a80ed844
| 32.292308 | 124 | 0.68207 | 4.714597 | false | false | false | false |
eugeneego/utilities-ios
|
Sources/Network/Http/UrlSessionHttp.swift
|
1
|
16497
|
//
// UrlSessionHttp
// Legacy
//
// Copyright (c) 2015 Eugene Egorov.
// License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE
//
import Foundation
open class UrlSessionHttp: Http {
public let session: URLSession
open var trustPolicies: [String: ServerTrustPolicy] {
get { delegateObject.trustPolicies }
set { delegateObject.trustPolicies = newValue }
}
private let delegateObject: Delegate
private let logger: UrlSessionHttpLogger?
public init(
configuration: URLSessionConfiguration,
trustPolicies: [String: ServerTrustPolicy] = [:],
logger: UrlSessionHttpLogger? = nil
) {
self.logger = logger
delegateObject = Delegate(trustPolicies: trustPolicies)
session = URLSession(configuration: configuration, delegate: delegateObject, delegateQueue: delegateObject.queue)
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Request
open func data(request: URLRequest) -> HttpDataTask {
let dataTask = session.dataTask(with: request)
let task = DataTask(task: dataTask, request: request, logger: logger)
delegateObject.add(task: task)
return task
}
open func download(request: URLRequest, destination: URL) -> HttpDownloadTask {
let downloadTask = session.downloadTask(with: request)
let task = DownloadTask(task: downloadTask, destination: destination, request: request, logger: logger)
delegateObject.add(task: task)
return task
}
open func data(request: URLRequest) async -> HttpResult<Data> {
let startDate = Date()
logger?.log(request, date: startDate)
if #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) {
do {
let data = try await session.data(for: request)
logger?.log(data.1, request, logger?.log(data.0, data.1) ?? "", nil, startDate: startDate, date: Date())
return Routines.process(response: data.1, data: data.0, error: nil)
} catch {
logger?.log(nil, request, "", error as NSError?, startDate: startDate, date: Date())
return Routines.process(response: nil, data: nil, error: error)
}
} else {
let task = TaskActor()
return await withTaskCancellationHandler(
operation: {
await withCheckedContinuation { continuation in
Task {
await task.resume(task: session.dataTask(with: request) { [logger] data, response, error in
let content = logger?.log(data, response) ?? ""
logger?.log(response, request, content, error as NSError?, startDate: startDate, date: Date())
let result = Routines.process(response: response, data: data, error: error)
continuation.resume(returning: result)
})
}
}
},
onCancel: {
Task {
await task.cancel()
}
}
)
}
}
open func download(request: URLRequest, destination: URL) async -> HttpResult<URL> {
let startDate = Date()
logger?.log(request, date: startDate)
if #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) {
do {
let data = try await session.download(for: request)
logger?.log(data.1, request, logger?.log(data.0) ?? "", nil, startDate: startDate, date: Date())
var result = Routines.process(response: data.1, data: data.0, error: nil)
result = Routines.moveFile(result: result, destination: destination)
return Routines.process(response: data.1, data: data.0, error: nil)
} catch {
logger?.log(nil, request, "", error as NSError?, startDate: startDate, date: Date())
return Routines.process(response: nil, data: nil, error: error)
}
} else {
let task = TaskActor()
return await withTaskCancellationHandler(
operation: {
await withCheckedContinuation { continuation in
Task {
await task.resume(task: session.downloadTask(with: request) { [logger] url, response, error in
let content = logger?.log(url) ?? ""
logger?.log(response, request, content, error as NSError?, startDate: startDate, date: Date())
var result = Routines.process(response: response, data: url, error: error)
result = Routines.moveFile(result: result, destination: destination)
continuation.resume(returning: result)
})
}
}
},
onCancel: {
Task {
await task.cancel()
}
}
)
}
}
private actor TaskActor {
weak var task: URLSessionTask?
func resume(task: URLSessionTask) {
self.task = task
task.resume()
}
func cancel() {
task?.cancel()
}
}
// MARK: - Task
private class TaskProgress: HttpProgress {
private(set) var data: HttpProgressData = .init(bytes: nil, totalBytes: nil)
var callback: ((HttpProgressData) -> Void)?
init() {
}
func set(bytes: Int64?, totalBytes: Int64?) {
data.bytes = bytes
data.totalBytes = totalBytes
DispatchQueue.main.async {
self.callback?(self.data)
}
}
func set(bytes: Int64?) {
set(bytes: bytes, totalBytes: data.totalBytes)
}
func set(totalBytes: Int64?) {
set(bytes: data.bytes, totalBytes: totalBytes)
}
}
private class InternalTask {
var uploadProgress: HttpProgress { upload }
var downloadProgress: HttpProgress { download }
let task: URLSessionTask
let upload: TaskProgress = TaskProgress()
let download: TaskProgress = TaskProgress()
var progress: Progress { task.progress }
var startDate: Date = Date()
let request: URLRequest
let logger: UrlSessionHttpLogger?
init(task: URLSessionTask, request: URLRequest, logger: UrlSessionHttpLogger?) {
self.task = task
self.request = request
self.logger = logger
}
func process(response: URLResponse?, error: Error?) {
}
}
private class ResultTask<T>: InternalTask {
var result: T? { nil }
var error: Error?
var continuation: CheckedContinuation<HttpResult<T>, Never>?
func run() async -> HttpResult<T> {
await withTaskCancellationHandler(
operation: {
await withCheckedContinuation { continuation in
resume(continuation: continuation)
}
},
onCancel: {
cancel()
}
)
}
override func process(response: URLResponse?, error: Error?) {
let error = error ?? self.error
let resultString = log(result: result, response: response)
logger?.log(response, request, resultString, error as NSError?, startDate: startDate, date: Date())
guard let continuation = continuation else { return }
let result = Routines.process(response: response, data: result, error: error)
continuation.resume(returning: result)
self.continuation = nil
}
func log(result: T?, response: URLResponse?) -> String {
""
}
private func resume(continuation: CheckedContinuation<HttpResult<T>, Never>) {
guard task.state == .suspended else {
return continuation.resume(returning: HttpResult<T>(response: nil, data: nil, error: .invalidState))
}
self.continuation = continuation
startDate = Date()
logger?.log(request, date: startDate)
task.resume()
}
private func cancel() {
task.cancel()
}
}
private class DataTask: ResultTask<Data>, HttpDataTask {
var data: Data = Data()
override var result: Data? { data }
override func log(result: Data?, response: URLResponse?) -> String {
logger?.log(result, response) ?? ""
}
}
private class DownloadTask: ResultTask<URL>, HttpDownloadTask {
var url: URL?
let destination: URL
override var result: URL? { url }
override func log(result: URL?, response: URLResponse?) -> String {
logger?.log(result) ?? ""
}
init(task: URLSessionTask, destination: URL, request: URLRequest, logger: UrlSessionHttpLogger?) {
self.destination = destination
super.init(task: task, request: request, logger: logger)
}
}
// MARK: - Delegate
private class Delegate: NSObject, URLSessionDataDelegate, URLSessionDownloadDelegate {
var trustPolicies: [String: ServerTrustPolicy]
let queue: OperationQueue = OperationQueue()
private var tasks: [InternalTask] = []
init(trustPolicies: [String: ServerTrustPolicy]) {
self.trustPolicies = trustPolicies
queue.qualityOfService = .userInitiated
queue.maxConcurrentOperationCount = 1
}
func add(task: InternalTask) {
queue.addOperation {
self.tasks.append(task)
}
}
// MARK: - Authentication
func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
let space = challenge.protectionSpace
let host = space.host
let isServerTrust = space.authenticationMethod == NSURLAuthenticationMethodServerTrust
if isServerTrust, let serverTrust = space.serverTrust, let policy = trustPolicy(host: host) {
if policy.evaluate(serverTrust: serverTrust, host: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
completionHandler(disposition, credential)
}
private func trustPolicy(host: String) -> ServerTrustPolicy? {
var components = host.components(separatedBy: ".")
repeat {
let host = components.isEmpty ? "*" : components.joined(separator: ".")
if let policy = trustPolicies[host] {
return policy
}
if components.isEmpty {
return nil
}
components.remove(at: 0)
} while true
}
// MARK: - Task
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64
) {
guard let httpTask = tasks.first(where: { $0.task === task }) else { return }
let total = totalBytesExpectedToSend != NSURLSessionTransferSizeUnknown ? totalBytesExpectedToSend : nil
httpTask.upload.set(bytes: totalBytesSent, totalBytes: total)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let index = tasks.firstIndex(where: { $0.task === task }) else { return }
let httpTask = tasks.remove(at: index)
httpTask.process(response: httpTask.task.response, error: httpTask.task.error ?? error)
}
// MARK: - Data
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
) {
guard let httpTask = tasks.first(where: { $0.task === dataTask }) as? DataTask else { return completionHandler(.allow) }
let total = response.expectedContentLength != NSURLSessionTransferSizeUnknown ? response.expectedContentLength : nil
httpTask.download.set(totalBytes: total)
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let httpTask = tasks.first(where: { $0.task === dataTask }) as? DataTask else { return }
httpTask.data.append(data)
httpTask.download.set(bytes: Int64(httpTask.data.count))
}
// MARK: - Download
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let httpTask = tasks.first(where: { $0.task === downloadTask }) as? DownloadTask else { return }
do {
try? FileManager.default.removeItem(at: httpTask.destination)
try FileManager.default.moveItem(at: location, to: httpTask.destination)
httpTask.url = httpTask.destination
} catch {
httpTask.error = error
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64
) {
guard let httpTask = tasks.first(where: { $0.task === downloadTask }) as? DownloadTask else { return }
let total = totalBytesExpectedToWrite != NSURLSessionTransferSizeUnknown ? totalBytesExpectedToWrite : nil
httpTask.download.set(bytes: totalBytesWritten, totalBytes: total)
}
}
// MARK: - Routines
private enum Routines {
static func process<DataType>(response: URLResponse?, data: DataType?, error: Error?) -> HttpResult<DataType> {
var result = HttpResult<DataType>(response: response as? HTTPURLResponse, data: data, error: error.map(Routines.process))
if let httpResponse = result.response, httpResponse.statusCode >= 400 {
result.error = .status(code: httpResponse.statusCode, error: error)
} else if let response = response, result.response == nil {
result.error = .nonHttpResponse(response: response)
}
return result
}
static func process(error: Error) -> HttpError {
let nsError = error as NSError
guard nsError.domain == NSURLErrorDomain else { return .error(error) }
switch nsError.code {
case NSURLErrorTimedOut, NSURLErrorNetworkConnectionLost, NSURLErrorNotConnectedToInternet:
return .unreachable(error)
case NSURLErrorCannotFindHost, NSURLErrorCannotConnectToHost, NSURLErrorDNSLookupFailed:
return .unreachable(error)
default:
return .error(error)
}
}
static func moveFile(result: HttpResult<URL>, destination: URL) -> HttpResult<URL> {
var result = result
if let url = result.data {
do {
try? FileManager.default.removeItem(at: destination)
try FileManager.default.moveItem(at: url, to: destination)
} catch {
result.error = .error(error)
}
}
return result
}
}
}
|
mit
|
97d8740f791318eb2d76cddc14aaef9c
| 36.924138 | 133 | 0.564891 | 5.2875 | false | false | false | false |
invalidstream/audio-reverser
|
AudioReverser/AudioReverser/ReversePlaybackModel.swift
|
1
|
2441
|
//
// ReversePlaybackModel.swift
// AudioReverser
//
// Created by Chris Adamson on 2/15/17.
// Copyright © 2017 Subsequently & Furthermore, Inc. All rights reserved.
//
import Foundation
import AVFoundation
private enum CONVERTER_OPTION {
case useToolboxSwift
case useToolboxC
case useAVAudioFile
}
private let converterOption: CONVERTER_OPTION = .useToolboxC
class ReversePlaybackModel {
enum State {
case loading
case error
case ready
}
var forwardURL: URL?
var backwardURL: URL?
var onStateChange : ((State) -> Void)?
var state : State = .loading {
didSet {
onStateChange?(state)
}
}
init (source: URL) {
let tempDirURL: URL = URL(fileURLWithPath: NSTemporaryDirectory())
let stripExtension = source.deletingPathExtension()
let filenameStub = stripExtension.pathComponents.last!
forwardURL = tempDirURL.appendingPathComponent(filenameStub + "-forward.caf")
backwardURL = tempDirURL.appendingPathComponent(filenameStub + "-backward.caf")
DispatchQueue.global(qos: .default).async {
guard let forwardURL = self.forwardURL, let backwardURL = self.backwardURL
else { return }
var err: OSStatus = noErr
switch converterOption {
case .useToolboxSwift:
err = convertAndReverseSwift(sourceURL: source as CFURL,
forwardURL: forwardURL as CFURL,
backwardURL: backwardURL as CFURL)
case .useToolboxC:
err = convertAndReverse(source as CFURL,
forwardURL as CFURL,
backwardURL as CFURL)
case .useAVAudioFile:
do {
try convertAndReverseAVAudioFile(sourceURL: source as CFURL,
forwardURL: forwardURL as CFURL,
backwardURL: backwardURL as CFURL)
} catch {
print ("convertAndReverseAVAudioFile failed: \(error)")
err = -99999
}
}
print ("converter done, err is \(err)")
self.state = (err == noErr) ? .ready : .error
}
}
}
|
unlicense
|
2374330f27f79fa3aba93dca3ab550c8
| 31.972973 | 87 | 0.543852 | 5.224839 | false | false | false | false |
iRoMeL/Calculator
|
Model/Protocols.swift
|
1
|
2803
|
// =======
// Requirements: (* - is required, o - optional)
// (*) 1. Implement given interfaces
// (*) 2. Implement CalculatorInterface using:
// - Reverse Polish notation algorithm
// - NSExpression
// - other ways are also possible
// (*) 3. Use child view controllers (input and output contollers)
// (o) 4. Cover BL with Unit tests
// (o) 5. Use UIStackView for buttons layout
// (o) 6. Additional panel with functions in landscape. Implement using Size Classes
// (*) 7. Add animation on button press (using CoreAnimation)
// (o) 8. Graphics of Function.sin, Function.cos, Function.tan (using CoreGraphics)
import Foundation
let numbers : Set<String> = ["0","1","2","3","4","5","6","7","8","9"]
let operations: Set<String> = ["+","-","*","/"]
let functions: Set<String> = ["√","sin","cos","tan","sinh","cosh","tanh","ln","log","log₂","x!","%","+/-","1/x","x²","x³","xʸ","eˣ","2ˣ","10ˣ","ʸ√x","³√x","Deg"]
// MARK: Enums
enum Operation: String {
case plus = "+"
case minus = "-"
case mult = "*"
case div = "/"
case exp = "^"
case equal = "="
}
enum Function: String {
case sqrt = "√"
case sin = "sin"
case cos = "cos"
case tan = "tan"
case sinh = "sinh"
case cosh = "cosh"
case tanh = "tanh"
case ln = "ln"
case log = "log"
case log2 = "log₂"
case fact = "x!"
case percent = "%"
case sign = "+/-"
case x_1 = "1/x"
case x2 = "x²"
case x3 = "x³"
case xy = "xʸ"
case ex = "eˣ"
case x2x = "2ˣ"
case x10 = "10ˣ"
case y_root_x = "ʸ√x"
case root3_x = "³√x"
case Deg = "Deg"
}
enum Memory: String {
case memoryClean = "mc"
case memoryAdd = "m+"
case memoryRemove = "m-"
case clean = "C"
case allClean = "AC"
}
enum Utility: String {
//case dot = "."
case leftBracket = "("
case rightBracket = ")"
}
enum Constants: String {
case pi = "π"
case e = "e"
}
// MARK: Protocols
protocol InputInterface {
func symbolPressed(_ symbol: String)
}
protocol OutputInterface {
var displayValue:String{get set}
func display(_ result: String)
}
protocol CalculatorDelegate {
func input(_ symbol:String)
}
protocol CalculatorInterface {
func digit(_ value: Double)
func operation(_ operation: Operation)
func function(_ function: Function)
func memory(_ memory: Memory, _ number: Double?)
func utility(_ utility: Utility)
var resultClosure: ((Double?, Error?) -> Void) { get set }
}
// MARK: Extensions
extension Double {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ?
String(format: "%.0f", self) : String(self)
}
private static let arc4randomMax = Double(UInt32.max)
static func random0to1() -> Double {
return Double(arc4random()) / arc4randomMax
}
}
|
apache-2.0
|
4c5442da42baceb2365bbfe4da9ee9d9
| 23.086957 | 161 | 0.602166 | 2.912723 | false | false | false | false |
machelix/Lightbox
|
Demos/LightboxDemo/LightboxDemo/MainViewController.swift
|
1
|
1260
|
import UIKit
import Lightbox
class MainViewController: UIViewController {
lazy var galleryButton: UIButton = { [unowned self] in
let button = UIButton()
button.setTitle("Show the gallery", forState: .Normal)
button.setTitleColor(UIColor(red:0.98, green:0.18, blue:0.36, alpha:1), forState: .Normal)
button.titleLabel!.font = UIFont(name: "AvenirNextCondensed-DemiBold", size: 24)
button.addTarget(self, action: "galleryButtonDidPress:", forControlEvents: .TouchUpInside)
button.frame = CGRectMake(0, 0,
UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(galleryButton)
}
// MARK: Action handlers
func galleryButtonDidPress(button: UIButton) {
let controller = LightboxController(images: ["photo1", "photo2", "photo3"])
controller.dismissalDelegate = self
presentViewController(controller, animated: true, completion: nil)
}
}
// MARK: Lightbox delegate methods
extension MainViewController : LightboxControllerDismissalDelegate {
func lightboxControllerDidDismiss(controller: LightboxController) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
091fdb66c60c51e61597823d22b9493d
| 30.5 | 94 | 0.740476 | 4.390244 | false | false | false | false |
mleiv/SerializableData
|
SerializableDataDemo/SerializableDataDemo/Core Data/SimpleCoreDataManageable.swift
|
1
|
18651
|
//
// SimpleCoreDataManageable.swift
//
// Copyright 2017 Emily Ivie
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import CoreData
/// Manages the storage and retrieval of CoreDataStorable/SerializableData objects.
public protocol SimpleCoreDataManageable {
//MARK: Required:
/// Prevents any automatic migrations - useful for heavy migrations.
static var isManageMigrations: Bool { get }
/// A flag for the type of store.
var isConfinedToMemoryStore: Bool { get }
/// The store name of the current persistent store container.
var storeName: String { get }
/// This is managed for you - just declare it.
var persistentContainer: NSPersistentContainer { get }
/// Override the default context - useful when doing save/fetch in background.
var specificContext: NSManagedObjectContext? { get }
/// Implement this using the sample below, because protocols can't do this.
init(storeName: String?, context: NSManagedObjectContext?, isConfineToMemoryStore: Bool)
//MARK: Already implemented:
func runMigrations(storeUrl: URL)
/// Save the primary context to file. Call this before exiting App.current.
func save()
/// Retrieve single row with criteria closure.
func getOne<T: NSManagedObject>(
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> T?
/// Retrieve multiple rows with criteria closure.
func getAll<T: NSManagedObject>(
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> [T]
/// Retrieve a count of matching entities
func getCount<T: NSManagedObject>(
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> Int
/// Retrieve faulted data for optimization.
func getAllFetchedResults<T: NSManagedObject>(
alterFetchRequest: AlterFetchRequest<T>,
sectionKey: String?,
cacheName: String?
) -> NSFetchedResultsController<T>?
/// Creates a new row of CoreData and returns a SimpleCoreDataStorable object.
func createOne<T: NSManagedObject>(
setInitialValues: @escaping SetAdditionalColumns<T>
) -> T?
/// Save a single row of an entity.
func saveChanges<T: NSManagedObject>(
item: T,
setChangedValues: @escaping SetAdditionalColumns<T>
) -> Bool
/// Delete single row of a entity.
func deleteOne<T: NSManagedObject>(
item: T
) -> Bool
/// Remove all rows of an entity matching restrictions.
func deleteAll<T: NSManagedObject>(
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> Bool
}
// MARK: Core data initialization functions
extension SimpleCoreDataManageable {
static var isCoreDataInaccessible: Bool {
#if TARGET_INTERFACE_BUILDER
return true
#else
return false
#endif
}
public var context: NSManagedObjectContext { return specificContext ?? persistentContainer.viewContext }
public init(storeName: String, isConfineToMemoryStore: Bool = false) {
self.init(storeName: storeName, context: nil, isConfineToMemoryStore: isConfineToMemoryStore)
}
public init(context: NSManagedObjectContext?) {
self.init(storeName: nil, context: context, isConfineToMemoryStore: false)
}
// // implement the following:
// public init(storeName: String?, context: NSManagedObjectContext?, isConfineToMemoryStore: Bool) {
// self.isConfinedToMemoryStore = isConfineToMemoryStore
// self.storeName = storeName ?? CoreDataManager.defaultStoreName
// self.specificContext = context
// if let storeName = storeName {
// self.persistentContainer = NSPersistentContainer(name: storeName)
// initContainer(isConfineToMemoryStore: isConfineToMemoryStore)
// } else {
// persistentContainer = CoreDataManager.current.persistentContainer
// }
// }
/// Configure the persistent container.
/// Also runs any manual migrations.
public func initContainer(isConfineToMemoryStore: Bool = false) {
guard !Self.isCoreDataInaccessible else { return }
let isManageMigrations = Self.isManageMigrations
// find our persistent store file
guard let storeUrl = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("\(storeName).sqlite") else {
fatalError("Could not create path to \(storeName) sqlite")
}
// make any pending changes
if !isConfineToMemoryStore {
runMigrations(storeUrl: storeUrl)
}
// Set some rules for this container
let description = NSPersistentStoreDescription(url: storeUrl)
if isManageMigrations {
description.shouldMigrateStoreAutomatically = false
description.shouldInferMappingModelAutomatically = false
}
if isConfineToMemoryStore {
description.type = NSInMemoryStoreType
}
persistentContainer.persistentStoreDescriptions = [description]
// load any existing stores
persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
self.initContext()
})
}
/// Configure the primary context.
public func initContext() {
print("Using persistent store: \(persistentContainer.persistentStoreCoordinator.persistentStores.first?.url)")
let context = self.persistentContainer.viewContext
context.automaticallyMergesChangesFromParent = true // not triggered w/o autoreleasepool
context.mergePolicy = NSMergePolicy.mergeByPropertyStoreTrump
// try? context.setQueryGenerationFrom(.current)
}
/// Runs any manual migrations before initializing the persistent container.
/// If you are still using light migrations, leave this empty.
public func runMigrations(storeUrl: URL) {}
}
// MARK: Core data content functions
extension SimpleCoreDataManageable {
/// The closure type for editing fetch requests.
public typealias AlterFetchRequest<T: NSManagedObject> = ((NSFetchRequest<T>)->Void)
/// The closure type for editing fetched entity objects.
public typealias SetAdditionalColumns<T: NSManagedObject> = ((T)->Void)
public typealias TransformEntity<T: NSManagedObject, U> = ((T)->U?)
/// Save the primary context to file. Call this before exiting App.current.
public func save() {
guard !Self.isCoreDataInaccessible else { return }
let moc = persistentContainer.viewContext
moc.performAndWait {
do {
// save if changes found
if moc.hasChanges {
try moc.save()
}
} catch {
// this sucks, but not fatal IMO
print("Failed to save context: \(error)")
}
}
}
/// Retrieve single row with criteria closure.
public func getOne<T: NSManagedObject>(
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> T? {
guard !Self.isCoreDataInaccessible else { return nil }
let moc = context
var result: T?
moc.performAndWait {
guard let fetchRequest = T.fetchRequest() as? NSFetchRequest<T> else { return }
alterFetchRequest(fetchRequest)
fetchRequest.fetchLimit = 1
autoreleasepool {
do {
if let item = try fetchRequest.execute().first {
result = item
}
} catch let fetchError as NSError {
print("Error: get failed for \(T.self): \(fetchError)")
}
}
}
return result
}
/// Retrieve multiple rows with criteria closure, and transform them to another data type.
public func getOneTransformed<T: NSManagedObject, U>(
transformEntity: @escaping TransformEntity<T,U>,
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> U? {
guard !Self.isCoreDataInaccessible else { return nil }
let moc = context
var result: U?
moc.performAndWait {
guard let fetchRequest = T.fetchRequest() as? NSFetchRequest<T> else { return }
alterFetchRequest(fetchRequest)
fetchRequest.fetchLimit = 1
autoreleasepool {
do {
if let item = try fetchRequest.execute().first {
result = transformEntity(item)
}
} catch let fetchError as NSError {
print("Error: get failed for \(T.self): \(fetchError)")
}
}
}
return result
}
/// Retrieve multiple rows with criteria closure.
public func getAll<T: NSManagedObject>(
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> [T] {
guard !Self.isCoreDataInaccessible else { return [] }
let moc = context
var result: [T] = []
moc.performAndWait { // performAndWait does not require autoreleasepool
guard let fetchRequest = T.fetchRequest() as? NSFetchRequest<T> else { return }
alterFetchRequest(fetchRequest)
do {
result = try fetchRequest.execute()
} catch let fetchError as NSError {
print("Error: getAll failed: \(fetchError)")
}
}
return result
}
/// Retrieve multiple rows with criteria closure, and transform them to another data type.
///
/// WARNING: Do not perform any core data action in transformEntity.
/// Just retrieve your values and do stuff with them later, or it will deadlock!
public func getAllTransformed<T: NSManagedObject, U>(
transformEntity: @escaping TransformEntity<T,U>,
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> [U] {
guard !Self.isCoreDataInaccessible else { return [] }
let moc = context
var result: [U] = []
moc.performAndWait { // performAndWait does not require autoreleasepool
guard let fetchRequest = T.fetchRequest() as? NSFetchRequest<T> else { return }
alterFetchRequest(fetchRequest)
do {
let items: [T] = try fetchRequest.execute()
result = items.flatMap { transformEntity($0) }
} catch let fetchError as NSError {
print("Error: getAllTransformed failed: \(fetchError)")
}
}
return result
}
/// Retrieve a count of matching entities
public func getCount<T: NSManagedObject>(
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> Int {
guard !Self.isCoreDataInaccessible else { return 0 }
let moc = context
var result = 0
moc.performAndWait { // performAndWait does not require autoreleasepool
guard let fetchRequest = T.fetchRequest() as? NSFetchRequest<T> else { return }
alterFetchRequest(fetchRequest)
do {
result = try moc.count(for: fetchRequest)
} catch let countError as NSError {
print("Error: getCount failed for \(T.self): \(countError)")
}
}
return result
}
/// Retrieve faulted data for optimization.
public func getAllFetchedResults<T: NSManagedObject>(
alterFetchRequest: AlterFetchRequest<T>,
sectionKey: String?,
cacheName: String?
) -> NSFetchedResultsController<T>? {
guard !Self.isCoreDataInaccessible else { return nil }
let moc = context
guard let fetchRequest = T.fetchRequest() as? NSFetchRequest<T> else { return nil }
alterFetchRequest(fetchRequest)
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: sectionKey, cacheName: cacheName)
do {
try controller.performFetch()
return controller
} catch let fetchError as NSError {
print("Error: getAllFetchedResults failed for \(T.self): \(fetchError)")
}
return nil
}
/// Creates a new row of CoreData and returns a SimpleCoreDataStorable object.
public func createOne<T: NSManagedObject>(
setInitialValues: @escaping SetAdditionalColumns<T>
) -> T? {
guard !Self.isCoreDataInaccessible else { return nil }
let moc = context
var result: T?
let waitForEndTask = DispatchWorkItem() {} // semaphore flag
persistentContainer.performBackgroundTask { moc in
defer { waitForEndTask.perform() }
moc.automaticallyMergesChangesFromParent = true
moc.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
autoreleasepool {
let coreItem = T(context: moc)
setInitialValues(coreItem)
result = coreItem
}
do {
try moc.save()
} catch let createError as NSError {
print("Error: create failed for \(T.self): \(createError)")
result = nil
}
}
waitForEndTask.wait()
if let result = result {
return moc.object(with: result.objectID) as? T
}
return nil
}
/// Save a single row of an entity.
public func saveChanges<T: NSManagedObject>(
item: T,
setChangedValues: @escaping SetAdditionalColumns<T>
) -> Bool {
guard !Self.isCoreDataInaccessible else { return false }
var result: Bool = false
let waitForEndTask = DispatchWorkItem() {} // semaphore flag
persistentContainer.performBackgroundTask { moc in
defer { waitForEndTask.perform() }
moc.automaticallyMergesChangesFromParent = true
moc.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
autoreleasepool {
if let coreItem = moc.object(with: item.objectID) as? T {
// CAUTION: anything you do here *must* use the same context,
// so if you are setting up relationships, create a new SimpleCoreDataManager
// and use that to do any fetching/saving:
//
// let localManager = SimpleCoreDataManager(context: coreItem.managedObjectContext)
// coreItem.otherEntity = OtherEntity.get(with: localManager) {
// fetchRequest.predicate = NSPredicate(format: "(%K == %@)", #keyPath(OtherEntity.id), lookupId)
// }
setChangedValues(coreItem)
}
}
do {
try moc.save()
result = true
} catch let saveError as NSError {
print("Error: save failed for \(T.self): \(saveError)")
}
}
waitForEndTask.wait()
return result
}
/// Delete single row of a entity.
public func deleteOne<T: NSManagedObject>(
item: T
) -> Bool {
return deleteAll() { (fetchRequest: NSFetchRequest<T>) in
fetchRequest.predicate = NSPredicate(format: "(%K == %@)", #keyPath(NSManagedObject.objectID), item.objectID)
}
}
/// Remove all rows of an entity matching restrictions.
public func deleteAll<T: NSManagedObject>(
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> Bool {
guard !Self.isCoreDataInaccessible else { return false }
guard persistentContainer.persistentStoreDescriptions.first?.type != NSInMemoryStoreType else {
return tediousManualDelete(alterFetchRequest: alterFetchRequest)
}
var result: Bool = false
let waitForEndTask = DispatchWorkItem() {} // semaphore flag
persistentContainer.performBackgroundTask { moc in
defer { waitForEndTask.perform() }
moc.automaticallyMergesChangesFromParent = true
moc.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
guard let fetchRequest = T.fetchRequest() as? NSFetchRequest<T> else { return }
alterFetchRequest(fetchRequest)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest as! NSFetchRequest<NSFetchRequestResult>)
do {
try _ = moc.execute(deleteRequest) as? NSBatchDeleteResult
try moc.save()
result = true
} catch let deleteError as NSError {
print("Error: deleteAll failed for \(T.self): \(deleteError)")
}
}
waitForEndTask.wait()
return result
}
private func tediousManualDelete<T: NSManagedObject>(
alterFetchRequest: @escaping AlterFetchRequest<T>
) -> Bool {
var result: Bool = false
let waitForEndTask = DispatchWorkItem() {} // semaphore flag
persistentContainer.performBackgroundTask { moc in
defer { waitForEndTask.perform() }
moc.automaticallyMergesChangesFromParent = true
moc.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
guard let fetchRequest = T.fetchRequest() as? NSFetchRequest<T> else { return }
fetchRequest.includesPropertyValues = false
alterFetchRequest(fetchRequest)
autoreleasepool {
do {
for item in try fetchRequest.execute() {
moc.delete(item)
}
} catch let deleteError as NSError {
print("Error: delete row failed for \(T.self): \(deleteError)")
}
}
do {
try moc.save()
result = true
} catch let deleteError as NSError {
print("Error: deleteAll failed for \(T.self): \(deleteError)")
}
}
waitForEndTask.wait()
return result
}
}
|
mit
|
301b06eb722649fd22cc32e512089e39
| 38.265263 | 169 | 0.609833 | 5.429694 | false | false | false | false |
rivetlogic/liferay-mobile-directory-ios
|
Liferay-Screens/Source/DDL/Model/DDLFieldDocument.swift
|
1
|
4176
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
import Foundation
public class DDLFieldDocument : DDLField {
public enum UploadStatus: Hashable, Equatable {
case Uploaded([String:AnyObject])
case Failed(NSError?)
case Uploading(UInt,UInt)
case Pending
public var hashValue: Int {
return toInt()
}
private func toInt() -> Int {
switch self {
case .Uploaded(_):
return Int.max
case .Failed(_):
return Int.min
case .Uploading(_,_):
return 1
default:
return 0
}
}
}
public var uploadStatus = UploadStatus.Pending
public var mimeType: String? {
switch currentValue {
case is UIImage:
return "image/png"
case is NSURL:
return "video/mpeg"
case is [String:AnyObject]:
return nil
default:
return nil
}
}
//MARK: DDLField
override internal func convert(fromString value:String?) -> AnyObject? {
var result:AnyObject?
if let valueString = value {
let data = valueString.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)
if let jsonObject:AnyObject = NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions(0), error: nil) {
if let jsonDict = jsonObject as? NSDictionary {
let dict = ["groupId" : jsonDict["groupId"]!,
"uuid" : jsonDict["uuid"]!,
"version" : jsonDict["version"]!]
uploadStatus = UploadStatus.Uploaded(dict)
result = dict
}
}
else if valueString != "" {
result = valueString
}
}
return result
}
override func convert(fromLabel label: String?) -> AnyObject? {
return nil
}
override internal func convert(fromCurrentValue value: AnyObject?) -> String? {
var result: String?
switch uploadStatus {
case .Uploaded(let json):
let groupId = (json["groupId"] ?? nil) as? Int
let uuid = (json["uuid"] ?? nil) as? String
let version = (json["version"] ?? nil) as? String
if groupId != nil && uuid != nil && version != nil {
result = "{\"groupId\":\(groupId!)," +
"\"uuid\":\"\(uuid!)\"," +
"\"version\":\"\(version!)\"}"
}
default: ()
}
return result
}
override func convertToLabel(fromCurrentValue value: AnyObject?) -> String? {
switch currentValue {
case is UIImage:
return LocalizedString("base", "an-image-has-been-selected", self)
case is NSURL:
return LocalizedString("base", "a-video-has-been-selected", self)
case is [String:AnyObject]:
return LocalizedString("base", "a-file-is-already-uploaded", self)
default: ()
}
return nil
}
override internal func doValidate() -> Bool {
var result = super.doValidate()
if result {
switch uploadStatus {
case .Failed(_): result = false
default: result = true
}
}
return result
}
//MARK: Public methods
public func getStream(inout size:Int64) -> NSInputStream? {
var result: NSInputStream?
switch currentValue {
case let image as UIImage:
let imageData = UIImagePNGRepresentation(image)
size = Int64(imageData.length)
result = NSInputStream(data: imageData)
case let videoURL as NSURL:
var outError:NSError?
if let attributes = NSFileManager.defaultManager().attributesOfItemAtPath(
videoURL.path!, error: &outError) {
if let sizeValue = attributes[NSFileSize] as? NSNumber {
size = sizeValue.longLongValue
}
}
result = NSInputStream(URL: videoURL)
default: ()
}
return result
}
}
//MARK: Equatable
public func ==(left: DDLFieldDocument.UploadStatus, right: DDLFieldDocument.UploadStatus) ->
Bool {
return left.hashValue == right.hashValue
}
|
gpl-3.0
|
32ca3f53dc01e09b37c7e08efcb812a4
| 22.59322 | 92 | 0.667146 | 3.786038 | false | false | false | false |
renxlWin/gege
|
swiftChuge/Pods/RealmSwift/RealmSwift/Util.swift
|
1
|
4413
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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 Foundation
import Realm
// MARK: Internal Helpers
internal func notFoundToNil(index: UInt) -> Int? {
if index == UInt(NSNotFound) {
return nil
}
return Int(index)
}
internal func throwRealmException(_ message: String, userInfo: [AnyHashable: Any]? = nil) {
NSException(name: NSExceptionName(rawValue: RLMExceptionName), reason: message, userInfo: userInfo).raise()
}
internal func throwForNegativeIndex(_ int: Int, parameterName: String = "index") {
if int < 0 {
throwRealmException("Cannot pass a negative value for '\(parameterName)'.")
}
}
internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? {
let regex = try? NSRegularExpression(pattern: pattern, options: [])
return regex?.stringByReplacingMatches(in: string, options: [],
range: NSRange(location: 0, length: string.utf16.count),
withTemplate: template)
}
extension Object {
// Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject`
// but actually operate on `RLMObjectBase`. Do not expose cast value to user.
internal func unsafeCastToRLMObject() -> RLMObject {
return unsafeBitCast(self, to: RLMObject.self)
}
}
// MARK: CustomObjectiveCBridgeable
internal func dynamicBridgeCast<T>(fromObjectiveC x: Any) -> T {
if let BridgeableType = T.self as? CustomObjectiveCBridgeable.Type {
return BridgeableType.bridging(objCValue: x) as! T
} else {
return x as! T
}
}
internal func dynamicBridgeCast<T>(fromSwift x: T) -> Any {
if let x = x as? CustomObjectiveCBridgeable {
return x.objCValue
} else {
return x
}
}
// Used for conversion from Objective-C types to Swift types
internal protocol CustomObjectiveCBridgeable {
/* FIXME: Remove protocol once SR-2393 bridges all integer types to `NSNumber`
* At this point, use `as! [SwiftType]` to cast between. */
static func bridging(objCValue: Any) -> Self
var objCValue: Any { get }
}
extension Int8: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int8 {
return (objCValue as! NSNumber).int8Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int16: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int16 {
return (objCValue as! NSNumber).int16Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int32: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int32 {
return (objCValue as! NSNumber).int32Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int64: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int64 {
return (objCValue as! NSNumber).int64Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Optional: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Optional {
if objCValue is NSNull {
return nil
} else {
return .some(dynamicBridgeCast(fromObjectiveC: objCValue))
}
}
var objCValue: Any {
if let value = self {
return value
} else {
return NSNull()
}
}
}
// MARK: AssistedObjectiveCBridgeable
internal protocol AssistedObjectiveCBridgeable {
static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self
var bridged: (objectiveCValue: Any, metadata: Any?) { get }
}
|
mit
|
fc04929da86092b8f018bec41865178c
| 31.448529 | 111 | 0.642647 | 4.51227 | false | false | false | false |
blg-andreasbraun/ProcedureKit
|
Sources/Mac/Process.swift
|
2
|
2702
|
//
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import Foundation
import ProcedureKit
open class ProcessProcedure: Procedure {
/// Error type for ProcessProcedure
public enum Error: Swift.Error, Equatable {
case launchPathNotSet
case terminationReason(Process.TerminationReason)
public static func == (lhs: ProcessProcedure.Error, rhs: ProcessProcedure.Error) -> Bool {
switch (lhs, rhs) {
case (.launchPathNotSet, .launchPathNotSet):
return true
case let (.terminationReason(lhsReason), .terminationReason(rhsReason)):
return lhsReason == rhsReason
default:
return false
}
}
}
/// Closure type for testing if the task did exit cleanly
public typealias ProcessDidExitCleanly = (Int) -> Bool
/// The default closure for checking the exit status
public static let defaultProcessDidExitCleanly: ProcessDidExitCleanly = { status in
switch status {
case 0: return true
default: return false
}
}
// - returns process: the Process
public let process: Process
/// - returns processDidExitCleanly: the closure for exiting cleanly.
public let processDidExitCleanly: ProcessDidExitCleanly
/**
Initializes ProcessProcedure with a Process.
- parameter task: the Process
- parameter processDidExitCleanly: a ProcessDidExitCleanly closure with a default.
*/
public init(process: Process, processDidExitCleanly: @escaping ProcessDidExitCleanly = ProcessProcedure.defaultProcessDidExitCleanly) {
self.process = process
self.processDidExitCleanly = processDidExitCleanly
super.init()
addWillCancelBlockObserver { procedure, errors in
guard procedure.process.isRunning else { return }
procedure.process.terminate()
}
}
open override func execute() {
guard let _ = process.launchPath else {
finish(withError: Error.launchPathNotSet)
return
}
let previousTerminationHandler = process.terminationHandler
process.terminationHandler = { [weak self] task in
guard let strongSelf = self else { return }
previousTerminationHandler?(strongSelf.process)
if strongSelf.processDidExitCleanly(Int(strongSelf.process.terminationStatus)) {
strongSelf.finish()
}
else {
strongSelf.finish(withError: Error.terminationReason(strongSelf.process.terminationReason))
}
}
process.launch()
}
}
|
mit
|
bdb897733c9672ab619a05d139d96e0d
| 31.154762 | 139 | 0.648649 | 5.275391 | false | false | false | false |
coderMONSTER/ioscelebrity
|
YStar/YStar/Scenes/view/BenifityCell.swift
|
1
|
1532
|
//
// BenifityCell.swift
// YStar
//
// Created by MONSTER on 2017/7/13.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
class BenifityCell: UITableViewCell {
// 容器View
@IBOutlet weak var containerView: UIView!
// 成交日期Label
@IBOutlet weak var dateLabel: UILabel!
// 成交总数Label
@IBOutlet weak var totalLabel: UILabel!
// 时间总数Label
@IBOutlet weak var timeLabel: UILabel!
// 订单总金额Label
@IBOutlet weak var orderPriceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
// 设置BenifityCell数据
func setBenifity(model : EarningInfoModel) {
let stringDate = String.init(format: "%d", model.orderdate)
let yearStr = (stringDate as NSString).substring(to: 4)
let monthStr = (stringDate as NSString).substring(with: NSMakeRange(4, 2))
let dayStr = (stringDate as NSString).substring(from: 6)
// print("日期=\(stringDate),年份==\(yearStr),月份==\(monthStr),天==\(dayStr)")
self.dateLabel.text = String.init(format: "%@-%@-%@", yearStr,monthStr,dayStr)
self.totalLabel.text = String.init(format: "%d", model.order_count)
self.timeLabel.text = String.init(format: "%d", model.order_num)
self.orderPriceLabel.text = String.init(format: "%.2f", model.price)
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
|
mit
|
952567760644781785bbf0485d0e1728
| 26.203704 | 86 | 0.618108 | 3.835509 | false | false | false | false |
distivi/MySpends
|
MySpends/MySpends/CoreDataManager.swift
|
1
|
2569
|
//
// CoreDataManager.swift
// MySpends
//
// Created by Dymedyuk Stanislav on 8/12/17.
// Copyright © 2017 Dymedyuk Stanislav. All rights reserved.
//
import UIKit
import CoreData
class CoreDataManager: NSObject {
// MARK: - Core Data stack
static var sharedInstance = CoreDataManager()
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded 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.
*/
let container = NSPersistentContainer(name: "MySpends")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
mit
|
459b275fce8304caf49b1b85f4481e7a
| 41.098361 | 199 | 0.625 | 5.668874 | false | false | false | false |
erikmartens/NearbyWeather
|
NearbyWeather/Commons/Factory/Factory+UIImageView.swift
|
1
|
1975
|
//
// Factory+UIImageView.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 13.04.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import UIKit.UIImageView
extension Factory {
struct ImageView: FactoryFunction {
enum ImageViewType {
case weatherConditionSymbol
case symbol(systemImageName: String? = nil, tintColor: UIColor? = nil)
case appIcon
case cellPrefix
}
typealias InputType = ImageViewType
typealias ResultType = UIImageView
static func make(fromType type: InputType) -> ResultType {
let imageView = UIImageView()
switch type {
case .weatherConditionSymbol:
imageView.tintAdjustmentMode = .automatic
imageView.contentMode = .scaleAspectFit
imageView.layer.masksToBounds = true
case let .symbol(systemImageName, tintColor):
imageView.contentMode = .scaleAspectFit
imageView.layer.masksToBounds = true
if let systemImageName = systemImageName {
imageView.image = UIImage(
systemName: systemImageName,
withConfiguration: UIImage.SymbolConfiguration(weight: .semibold)
)?
.trimmingTransparentPixels()?
.withRenderingMode(.alwaysTemplate) ?? UIImage()
} else {
imageView.image = UIImage()
}
imageView.tintColor = tintColor ?? Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundPrimaryTitle
case .appIcon:
imageView.contentMode = .scaleAspectFit
imageView.layer.cornerRadius = Constants.Dimensions.AppIconImage.cornerRadius
imageView.layer.masksToBounds = true
case .cellPrefix:
imageView.tintColor = Constants.Theme.Color.ViewElement.cellPrefixSymbolImage
imageView.contentMode = .scaleAspectFit
imageView.layer.masksToBounds = true
}
return imageView
}
}
}
|
mit
|
196c6780e1e32913414014948e3c9983
| 30.83871 | 123 | 0.66768 | 5.529412 | false | false | false | false |
xedin/swift
|
test/Profiler/coverage_ternary.swift
|
7
|
1237
|
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_ternary %s | %FileCheck %s
// coverage_ternary.bar.init() -> coverage_ternary.bar
// CHECK-LABEL: sil hidden @$s16coverage_ternary3barCACycfc
// CHECK-NOT: return
// CHECK: builtin "int_instrprof_increment"
// rdar://problem/23256795 - Avoid crash if an if_expr has no parent
// CHECK: sil_coverage_map {{.*}}// variable initialization expression of coverage_ternary.bar.m1 : Swift.String
class bar {
var m1 = flag == 0 // CHECK: [[@LINE]]:12 -> [[@LINE+2]]:22 : 0
? "false" // CHECK: [[@LINE]]:16 -> [[@LINE]]:23 : 1
: "true"; // CHECK: [[@LINE]]:16 -> [[@LINE]]:22 : (0 - 1)
}
// Note: We didn't instantiate bar, but we still expect to see instrumentation
// for its *structors, and coverage mapping information for it.
var flag: Int = 0
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_ternary.foo
func foo(_ x : Int32) -> Int32 { // CHECK: [[@LINE]]:32 -> [[@LINE+4]]:2 : 0
return x == 3
? 9000 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : 1
: 1234 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : (0 - 1)
}
foo(1)
foo(2)
foo(3)
|
apache-2.0
|
e0cf1bc9894cc8c5e8e179939d81a9d6
| 40.233333 | 176 | 0.607114 | 3.298667 | false | false | false | false |
dllewellyn/iOS-Networking-Scheduler
|
NetworkingScheduler/Schedule.swift
|
1
|
1765
|
//
// Schedule.swift
// NetworkingScheduler
//
// Created by Daniel Llewellyn on 14/04/16.
// Copyright © 2016 Daniel Llewellyn. All rights reserved.
//
import Foundation
public class Schedule
{
// Singleton class
private static var instance : Schedule? = nil
// Schedule list
var scheduleList : Array<NetworkCallback> = Array<NetworkCallback>()
/**
Schedule instance
*/
public class func sharedManager() -> Schedule {
if instance == nil
{
instance = Schedule.init()
}
return instance!
}
/**
Add a callback to the queue
@param callback an instance of NetworkCallback that you want to be called (when the network is next available)
*/
public func addCallbackToQueue(callback : NetworkCallback) {
self.scheduleList.append(callback)
}
/**
Execute all the callbacks
*/
public func executeAllCallbacks() {
for callback in scheduleList
{
// Only trigger if we're connected to the network
if Reachability.isConnectedToNetwork()
{
let session = NSURLSession.init(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
session.dataTaskWithURL(callback.urlToCall, completionHandler: { (data : NSData?, response : NSURLResponse?, error : NSError?) in
// Call the callback :)
callback.callbackTrigger(data, error: error)
}).resume()
self.scheduleList.removeFirst()
}
else
{
break
}
}
}
}
|
apache-2.0
|
20de9007be368eb60fca52dbf7cf67f1
| 24.955882 | 145 | 0.558957 | 5.478261 | false | false | false | false |
practicalswift/swift
|
test/SourceKit/CodeComplete/complete_moduleimportdepth.swift
|
13
|
4485
|
import ImportsImportsFoo
import FooHelper.FooHelperExplicit
func test() {
let x = 1
#^A^#
}
// XFAIL: broken_std_regex
// REQUIRES: objc_interop
// RUN: %complete-test -hide-none -group=none -tok=A %s -raw -- -I %S/Inputs -F %S/../Inputs/libIDE-mock-sdk > %t
// RUN: %FileCheck %s < %t
// Swift == 1
// CHECK-LABEL: key.name: "abs(:)",
// CHECK-NEXT: key.sourcetext: "abs(<#T##x: Comparable & SignedNumeric##Comparable & SignedNumeric#>)",
// CHECK-NEXT: key.description: "abs(x: Comparable & SignedNumeric)",
// CHECK-NEXT: key.typename: "Comparable & SignedNumeric",
// CHECK-NEXT: key.doc.brief: "Returns the absolute value of the given number.",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 1,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK-NOT: key.modulename
// CHECK: key.modulename: "Swift"
// CHECK-NEXT: },
// FooHelper.FooHelperExplicit == 1
// CHECK-LABEL: key.name: "fooHelperExplicitFrameworkFunc1(:)",
// CHECK-NEXT: key.sourcetext: "fooHelperExplicitFrameworkFunc1(<#T##a: Int32##Int32#>)",
// CHECK-NEXT: key.description: "fooHelperExplicitFrameworkFunc1(a: Int32)",
// CHECK-NEXT: key.typename: "Int32",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 1,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK-NOT: key.modulename
// CHECK: key.modulename: "FooHelper.FooHelperExplicit"
// CHECK-NEXT: },
// ImportsImportsFoo == 1
// CHECK-LABEL: key.name: "importsImportsFoo()",
// CHECK-NEXT: key.sourcetext: "importsImportsFoo()",
// CHECK-NEXT: key.description: "importsImportsFoo()",
// CHECK-NEXT: key.typename: "Void",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 1,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK-NOT: key.modulename
// CHECK: key.modulename: "ImportsImportsFoo"
// CHECK-NEXT: },
// Bar == 2
// CHECK-LABEL: key.name: "BarForwardDeclaredClass",
// CHECK-NEXT: key.sourcetext: "BarForwardDeclaredClass",
// CHECK-NEXT: key.description: "BarForwardDeclaredClass",
// CHECK-NEXT: key.typename: "BarForwardDeclaredClass",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 2,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK-NOT: key.modulename
// CHECK: key.modulename: "Bar"
// CHECK-NEXT: },
// ImportsFoo == 2
// CHECK-LABEL: key.name: "importsFoo()",
// CHECK-NEXT: key.sourcetext: "importsFoo()",
// CHECK-NEXT: key.description: "importsFoo()",
// CHECK-NEXT: key.typename: "Void",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 2,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK-NOT: key.modulename
// CHECK: key.modulename: "ImportsFoo"
// CHECK-NEXT: },
// Foo == FooSub == 3
// CHECK-LABEL: key.name: "FooClassBase",
// CHECK-NEXT: key.sourcetext: "FooClassBase",
// CHECK-NEXT: key.description: "FooClassBase",
// CHECK-NEXT: key.typename: "FooClassBase",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 3,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK-NOT: key.modulename
// CHECK: key.modulename: "Foo"
// CHECK-NEXT: },
// CHECK-LABEL: key.name: "FooSubEnum1",
// CHECK-NEXT: key.sourcetext: "FooSubEnum1",
// CHECK-NEXT: key.description: "FooSubEnum1",
// CHECK-NEXT: key.typename: "FooSubEnum1",
// CHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// CHECK-NEXT: key.moduleimportdepth: 3,
// CHECK-NEXT: key.num_bytes_to_erase: 0,
// CHECK-NOT: key.modulename
// CHECK: key.modulename: "Foo.FooSub"
// CHECK-NEXT: },
// FooHelper == 4
// FIXME: rdar://problem/20230030
// We're picking up the implicit import of FooHelper used to attach FooHelperExplicit to.
// xCHECK-LABEL: key.name: "FooHelperUnnamedEnumeratorA2",
// xCHECK-NEXT: key.sourcetext: "FooHelperUnnamedEnumeratorA2",
// xCHECK-NEXT: key.description: "FooHelperUnnamedEnumeratorA2",
// xCHECK-NEXT: key.typename: "Int",
// xCHECK-NEXT: key.context: source.codecompletion.context.othermodule,
// xCHECK-NEXT: key.moduleimportdepth: 4,
// xCHECK-NEXT: key.num_bytes_to_erase: 0,
// xCHECK-NOT: key.modulename
// xCHECK: key.modulename: "FooHelper"
// xCHECK-NEXT: },
|
apache-2.0
|
e90af48cdbd24f89e50df2ab8644e048
| 40.146789 | 113 | 0.683166 | 3.151792 | false | false | false | false |
robocopklaus/sportskanone
|
Sportskanone/AppDelegate.swift
|
1
|
2918
|
//
// AppDelegate.swift
// Sportskanone
//
// Created by Fabian Pahl on 22/02/2017.
// Copyright © 2017 21st digital GmbH. All rights reserved.
//
import UIKit
import HealthKit
import ReactiveSwift
import ReactiveCocoa
import Result
import Parse
import TestFairySDK
@UIApplicationMain
final class AppDelegate: UIResponder {
var window: UIWindow?
fileprivate let healthStore = HKHealthStore()
fileprivate lazy var store: SportskanoneStore = { [unowned self] in
return SportskanoneStore(healthStore: self.healthStore)
}()
}
// MARK: - UIApplicationDelegate
extension AppDelegate: UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Parse
Parse.initialize(with: ParseClientConfiguration {
$0.applicationId = Secrets.Parse.applicationID
$0.clientKey = Secrets.Parse.clientKey
$0.server = Secrets.Parse.serverURL
})
PFActivitySummary.registerSubclass()
// Testfairy
TestFairy.begin(Secrets.TestFairy.appToken)
// Model
let coordinatorViewModel = CoordinatorViewModel(store: store)
// View
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = CoordinatorViewController(viewModel: coordinatorViewModel)
window.makeKeyAndVisible()
self.window = window
// Styling
applyTheme(window: window)
// Notifications
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
store.registerForRemoteNotifications(withDeviceToken: deviceToken).start()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
PFPush.handle(userInfo)
}
}
private extension AppDelegate {
func applyTheme(window: UIWindow) {
let tintColor: UIColor = .skGreen
window.tintColor = tintColor
BorderButton.appearance().titleFont = .skTextButton
BorderButton.appearance().shadowColor = .skGray
BorderButton.appearance().shadowOffset = CGSize(width: 0, height: 0)
BorderButton.appearance().shadowRadius = 6
BorderButton.appearance().shadowOpacity = 0.8
TextLabel.appearance().fontColor = .skGray
TextLabel.appearance().textFont = .skText
HeadlineLabel.appearance().textAlignment = .center
HeadlineLabel.appearance().fontColor = .skBlack
HeadlineLabel.appearance().textFont = .skHeadline
BorderButton.appearance().backgroundColor = tintColor
BorderButton.appearance().tintColor = .white
BorderButton.appearance().contentEdgeInsets = UIEdgeInsets(top: 6, left: 20, bottom: 6, right: 20)
}
}
|
mit
|
3055f6690d88197cb8581c5babf1655d
| 27.881188 | 197 | 0.734659 | 5.073043 | false | false | false | false |
PJayRushton/stats
|
Stats/GameStats.swift
|
1
|
2562
|
//
// GameStats.swift
// Stats
//
// Created by Parker Rushton on 8/24/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import Foundation
import Firebase
import Marshal
struct GameStats {
var id: String
var creationDate: Date?
var gameId: String
var isSeason = false
var teamId: String
var stats = [String: [Stat]]()
var allStats: [Stat] {
return stats.values.joined().compactMap { $0 }
}
init(_ game: Game) {
self.id = UUID().uuidString
self.creationDate = Date()
self.gameId = game.id
self.teamId = game.teamId
}
init(_ season: Season) {
self.id = UUID().uuidString
self.creationDate = Date()
self.gameId = season.id
self.isSeason = true
self.teamId = season.teamId
}
}
// MARK: - Unmarshaling
extension GameStats: Unmarshaling {
init(object: MarshaledObject) throws {
id = try object.value(for: idKey)
creationDate = try object.value(for: creationDateKey)
gameId = try object.value(for: gameIdKey)
isSeason = try object.value(for: isSeasonKey) ?? false
teamId = try object.value(for: teamIdKey)
let statsJSON: JSONObject = try object.value(for: statsKey)
statsJSON.keys.forEach { playerId in
guard let statsDict: [String: Double] = try? statsJSON.value(for: playerId) else { return }
let stats = statsDict.compactMap { Stat(playerId: playerId, type: StatType(rawValue: $0.key)!, value: $0.value) }
self.stats[playerId] = stats
}
}
}
// MARK: - JSONMarshaling
extension GameStats: JSONMarshaling {
func jsonObject() -> JSONObject {
var object = JSONObject()
object[idKey] = id
object[creationDateKey] = creationDate?.iso8601String
object[gameIdKey] = gameId
object[isSeasonKey] = isSeason
object[teamIdKey] = teamId
var statsObject = JSONObject()
stats.forEach { playerId, playerStats in
var object = JSONObject()
playerStats.forEach { object[$0.type.rawValue] = $0.value }
statsObject[playerId] = object
}
object[statsKey] = statsObject
return object
}
}
extension GameStats: Identifiable {
var ref: DatabaseReference {
return StatsRefs.gameStatsRef(teamId: teamId).child(id)
}
}
extension GameStats: Hashable {
var hashValue: Int {
return id.hashValue
}
}
|
mit
|
99e7b6080aa04b527e15cf22f3748e58
| 23.864078 | 125 | 0.602109 | 4.123994 | false | false | false | false |
EZ-NET/ESSwim
|
Sources/State/Cache.swift
|
1
|
1282
|
//
// Cache.swift
// ESOcean
//
// Created by Tomohiro Kumagai on H27/06/15.
//
//
public protocol CacheType : CacheDataType {
mutating func release()
}
public protocol CacheDataType {
associatedtype Value
var value:Value? { get }
var cached:Bool { get }
func cache(value:Value)
}
extension CacheDataType {
func value(@autoclosure predicate:()->Value) -> Value {
return value(predicate: predicate)
}
public func value(@noescape predicate predicate:()->Value) -> Value {
if !self.cached {
self.cache(predicate())
}
return self.value!
}
}
public struct Cache<T> {
var _data:_CacheData<T>
public init() {
self._data = _CacheData()
}
}
extension Cache : CacheType {
public var cached:Bool {
return self._data.cached
}
public var value:T? {
return self._data.value
}
public mutating func release() {
self._data = _CacheData()
}
public func cache(value: T) {
guard !self.cached else {
fatalError("Aready cached.")
}
self._data.cache(value)
}
}
final class _CacheData<T> : CacheDataType {
private(set) var _value:T? = nil
var cached:Bool {
return self._value != nil
}
var value:T? {
return self._value
}
func cache(value:T) {
self._value = value
}
}
|
mit
|
c1dc3877c6ece0a010c983dacf9c7107
| 12.081633 | 70 | 0.629485 | 3.173267 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Blockchain/Announcements/Kinds/Periodic/TransferInCryptoAnnouncement.swift
|
1
|
4062
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import PlatformKit
import PlatformUIKit
import RxCocoa
import RxSwift
import SwiftUI
import ToolKit
/// Transfer in crypto announcement
final class TransferInCryptoAnnouncement: PeriodicAnnouncement, ActionableAnnouncement {
// MARK: - Properties
var viewModel: AnnouncementCardViewModel {
let button = ButtonViewModel.primary(
with: LocalizationConstants.AnnouncementCards.TransferInCrypto.ctaButton
)
button.tapRelay
.bind { [weak self] in
guard let self = self else { return }
self.analyticsRecorder.record(event: self.actionAnalyticsEvent)
self.markDismissed()
self.action()
self.dismiss()
}
.disposed(by: disposeBag)
return AnnouncementCardViewModel(
type: type,
badgeImage: .init(
image: .local(name: "card-icon-transfer", bundle: .main),
contentColor: nil,
backgroundColor: .clear,
cornerRadius: .none,
size: .edge(40)
),
title: LocalizationConstants.AnnouncementCards.TransferInCrypto.title,
description: LocalizationConstants.AnnouncementCards.TransferInCrypto.description,
buttons: [button],
dismissState: .dismissible { [weak self] in
guard let self = self else { return }
self.analyticsRecorder.record(event: self.dismissAnalyticsEvent)
self.markDismissed()
self.dismiss()
},
didAppear: { [weak self] in
guard let self = self else { return }
self.analyticsRecorder.record(event: self.didAppearAnalyticsEvent)
}
)
}
var associatedAppModes: [AppMode] {
[AppMode.trading, AppMode.legacy]
}
var shouldShow: Bool {
guard !isKycSupported else {
return false
}
return !isDismissed
}
let type = AnnouncementType.transferBitcoin
let analyticsRecorder: AnalyticsEventRecorderAPI
let dismiss: CardAnnouncementAction
let recorder: AnnouncementRecorder
let action: CardAnnouncementAction
let appearanceRules: PeriodicAnnouncementAppearanceRules
private let disposeBag = DisposeBag()
private let isKycSupported: Bool
// MARK: - Setup
init(
isKycSupported: Bool,
cacheSuite: CacheSuite = resolve(),
reappearanceTimeInterval: TimeInterval,
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
errorRecorder: ErrorRecording = CrashlyticsRecorder(),
dismiss: @escaping CardAnnouncementAction,
action: @escaping CardAnnouncementAction
) {
self.isKycSupported = isKycSupported
recorder = AnnouncementRecorder(cache: cacheSuite, errorRecorder: errorRecorder)
appearanceRules = PeriodicAnnouncementAppearanceRules(recessDurationBetweenDismissals: reappearanceTimeInterval)
self.analyticsRecorder = analyticsRecorder
self.dismiss = dismiss
self.action = action
}
}
// MARK: SwiftUI Preview
#if DEBUG
struct TransferInCryptoAnnouncementContainer: UIViewRepresentable {
typealias UIViewType = AnnouncementCardView
func makeUIView(context: Context) -> UIViewType {
let presenter = TransferInCryptoAnnouncement(
isKycSupported: true,
reappearanceTimeInterval: 0,
dismiss: {},
action: {}
)
return AnnouncementCardView(using: presenter.viewModel)
}
func updateUIView(_ uiView: UIViewType, context: Context) {}
}
struct TransferInCryptoAnnouncementContainer_Previews: PreviewProvider {
static var previews: some View {
Group {
TransferInCryptoAnnouncementContainer().colorScheme(.light)
}.previewLayout(.fixed(width: 375, height: 250))
}
}
#endif
|
lgpl-3.0
|
45fa9a3c51c9bbaf0c9cf60a87ac752c
| 31.230159 | 120 | 0.650086 | 5.473046 | false | false | false | false |
CoderFeiSu/FFCategoryHUD
|
FFCategoryHUDExample/FFCategoryHUDExample/ContainerViewController.swift
|
1
|
3236
|
//
// ViewController.swift
// FFCategoryHUDExample
//
// Created by Freedom on 2017/4/20.
// Copyright © 2017年 Freedom. All rights reserved.
//
import UIKit
class ContainerViewController: UIViewController,FFSegmentContainerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// 不要增加内边距
automaticallyAdjustsScrollViewInsets = false
// 分类视图
let frame = CGRect(x: 0, y: kNavigationBarH, width: 375, height: view.bounds.height - kNavigationBarH)
let barStyle = FFSegmentBarStyle()
barStyle.bottomLine.isShow = true
barStyle.bottomLine.isFitTitle = true
// barStyle.isNeedScale = true
barStyle.bottomLine.color = UIColor.red
barStyle.contentColor = UIColor.red
let item1: FFSegmentItem = FFSegmentItem(title: "第一个控制器", vc: FirstViewController())
let item2: FFSegmentItem = FFSegmentItem(title: "第二个控制器", vc: SecondViewController(), isPushVC: true)
let item3: FFSegmentItem = FFSegmentItem(title: "第三个控制器", vc: ThirdViewController())
let segmentContainer = FFSegmentContainer(frame: frame, barStyle: barStyle, items: [item1, item2, item3], parentVC: self)
segmentContainer.delegate = self
view.addSubview(segmentContainer)
// 后面都属于图片键盘
// let frame = CGRect(x: 0, y: view.bounds.height - 216, width: view.bounds.width, height: 216)
// let titles = ["低级", "初级", "中级", "高级"]
// let barStyle = FFKeyboardBarStyle()
// barStyle.isShowBottomLine = true
// barStyle.bottomLineColor = UIColor.red
// let layout = FFCategoryKeyboardLayout()
// let keyboardContainer = FFKeyboardContainer.init(frame: frame, barTitles: titles, barStyle: barStyle, layout: layout)
// keyboardContainer.delegate = self
// keyboardContainer.dataSource = self
// keyboardContainer.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "abc")
// view.addSubview(keyboardContainer)
}
func segmentContainer(_ segmentContainer: FFSegmentContainer, didClickedlAt index: Int) {
print(self,#function,index)
}
deinit {
print("我欧洲了")
}
}
//extension ViewController: FFKeyboardContainerDataSource, FFKeyboardContainerDelegate {
//
// func numberOfSections(in keyboardContainer: FFKeyboardContainer) -> Int {
// return 4
// }
//
// func keyboardContainer(_ keyboardContainer: FFKeyboardContainer, numberOfItemsInSection section: Int) -> Int {
// if (section == 0) {
// return 1
// } else if (section == 1) {
// return 50
// } else if (section == 2) {
// return 22
// } else {
// return 10
// }
// }
//
// func keyboardContainer(_ keyboardContainer: FFKeyboardContainer, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// let cell = keyboardContainer.dequeueReusableCell(withReuseIdentifier: "abc", for: indexPath)
// cell.backgroundColor = UIColor.random
// return cell
// }
//
//}
|
mit
|
a2ac137774068a3a5ea582bb5d838d47
| 34.202247 | 132 | 0.64443 | 4.28591 | false | false | false | false |
huonw/swift
|
benchmark/utils/ArgParse.swift
|
4
|
2657
|
//===--- ArgParse.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
public struct Arguments {
public var progName: String
public var positionalArgs: [String]
public var optionalArgsMap: [String : String]
init(_ pName: String, _ posArgs: [String], _ optArgsMap: [String : String]) {
progName = pName
positionalArgs = posArgs
optionalArgsMap = optArgsMap
}
}
/// Using CommandLine.arguments, returns an Arguments struct describing
/// the arguments to this program. If we fail to parse arguments, we
/// return nil.
///
/// We assume that optional switch args are of the form:
///
/// --opt-name[=opt-value]
/// -opt-name[=opt-value]
///
/// with opt-name and opt-value not containing any '=' signs. Any
/// other option passed in is assumed to be a positional argument.
public func parseArgs(_ validOptions: [String]? = nil)
-> Arguments? {
let progName = CommandLine.arguments[0]
var positionalArgs = [String]()
var optionalArgsMap = [String : String]()
// For each argument we are passed...
var passThroughArgs = false
for arg in CommandLine.arguments[1..<CommandLine.arguments.count] {
// If the argument doesn't match the optional argument pattern. Add
// it to the positional argument list and continue...
if passThroughArgs || !arg.starts(with: "-") {
positionalArgs.append(arg)
continue
}
if arg == "--" {
passThroughArgs = true
continue
}
// Attempt to split it into two components separated by an equals sign.
let components = arg.split(separator: "=")
let optionName = String(components[0])
if validOptions != nil && !validOptions!.contains(optionName) {
print("Invalid option: \(arg)")
return nil
}
var optionVal : String
switch components.count {
case 1: optionVal = ""
case 2: optionVal = String(components[1])
default:
// If we do not have two components at this point, we can not have
// an option switch. This is an invalid argument. Bail!
print("Invalid option: \(arg)")
return nil
}
optionalArgsMap[optionName] = optionVal
}
return Arguments(progName, positionalArgs, optionalArgsMap)
}
|
apache-2.0
|
e6dc200291f081949fe73a75f2e05643
| 33.064103 | 80 | 0.645088 | 4.565292 | false | false | false | false |
zmian/xcore.swift
|
Sources/Xcore/SwiftUI/Extensions/Font+Extensions.swift
|
1
|
6534
|
//
// Xcore
// Copyright © 2020 Xcore
// MIT license, see LICENSE file for details
//
import SwiftUI
extension Font {
/// Creates a font from a UIKit font.
///
/// - Parameter font: A UIFont instance from which to create a font.
public init(uiFont font: UIFont) {
self.init(font as CTFont)
}
/// Returns default app font that scales relative to the given `style`.
///
/// - Parameters:
/// - style: The text style for which to return a font descriptor. See Text
/// Styles for valid values.
/// - weight: The weight of the font. If set to `nil`, the value is derived
/// from the given text style.
/// - trait: The trait of the font. The default value is `.normal`.
/// - Returns: The new scaled font object.
public static func app(
_ style: TextStyle,
weight: Weight? = nil,
trait: UIFont.Trait = .normal
) -> Font {
let weight = weight.normalize(style: style)
let typeface = UIFont.defaultAppTypeface.name(weight: weight, trait: trait)
if typeface == UIFont.Typeface.systemFontId {
var font = system(
style,
design: trait == .monospaced ? .monospaced : .default
).weight(weight)
if trait == .italic {
font = font.italic()
}
return font
}
let pointSize = UIFontDescriptor.preferredFontDescriptor(
withTextStyle: .init(style)
).pointSize
return .custom(typeface, size: pointSize, relativeTo: style)
}
/// Returns default app font with given `size`.
///
/// - Parameters:
/// - size: The point size of the font.
/// - textStyle: Scales the size relative to the text style. The default value
/// is `.body`.
/// - weight: The weight of the font. If set to `nil`, the value is derived
/// from the given text style.
/// - trait: The trait of the font. The default value is `.normal`.
/// - Returns: The new font object.
public static func app(
size: CGFloat,
relativeTo textStyle: TextStyle? = nil,
weight: Weight? = nil,
trait: UIFont.Trait = .normal
) -> Font {
let weight = weight.normalize(style: textStyle)
let typeface = UIFont.defaultAppTypeface.name(weight: weight, trait: trait)
if typeface == UIFont.Typeface.systemFontId {
var font = system(
size: size,
weight: weight,
design: trait == .monospaced ? .monospaced : .default
)
if trait == .italic {
font = font.italic()
}
return font
}
if let textStyle = textStyle {
return custom(typeface, size: size, relativeTo: textStyle)
} else {
return custom(typeface, size: size)
}
}
}
// MARK: - CustomTextStyle
extension Font {
public struct CustomTextStyle {
public let size: CGFloat
public let textStyle: TextStyle
public init(size: CGFloat, relativeTo textStyle: TextStyle) {
self.size = size
self.textStyle = textStyle
}
}
/// Returns default app font that scales relative to the given `style`.
///
/// - Parameters:
/// - style: The text style for which to return a font descriptor. See Custom
/// Text Styles for valid values.
/// - weight: The weight of the font. If set to `nil`, the value is derived
/// from the given text style.
/// - trait: The trait of the font. The default value is `.normal`.
/// - Returns: The new scaled font object.
public static func app(
_ style: CustomTextStyle,
weight: Weight? = nil,
trait: UIFont.Trait = .normal
) -> Font {
.app(
size: style.size,
relativeTo: style.textStyle,
weight: weight,
trait: trait
)
}
}
// MARK: - Helpers
extension UIFont.Weight {
init(_ weight: Font.Weight) {
switch weight {
case .ultraLight:
self = .ultraLight
case .thin:
self = .thin
case .light:
self = .light
case .regular:
self = .regular
case .medium:
self = .medium
case .semibold:
self = .semibold
case .bold:
self = .bold
case .heavy:
self = .heavy
case .black:
self = .black
default:
self = .regular
}
}
}
extension UIFont.TextStyle {
fileprivate init(_ textStyle: Font.TextStyle) {
switch textStyle {
case .largeTitle:
self = .largeTitle
case .title:
self = .title1
case .title2:
self = .title2
case .title3:
self = .title3
case .headline:
self = .headline
case .subheadline:
self = .subheadline
case .body:
self = .body
case .callout:
self = .callout
case .footnote:
self = .footnote
case .caption:
self = .caption1
case .caption2:
self = .caption2
default:
self = .body
}
}
}
extension Optional where Wrapped == Font.Weight {
/// Returns non-optional font weight.
///
/// - If `self` is non-nil then it returns `self`
/// - Otherwise, if style is non-nil then it returns default preferred weight
/// based on Apple's Typography [Guidelines].
/// - Else, it returns `.regular` weight.
///
/// [Guidelines]: https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/typography/#dynamic-type-sizes
fileprivate func normalize(style: Font.TextStyle?) -> Wrapped {
self ?? style?.defaultPreferredWeight() ?? .regular
}
}
extension Font.TextStyle {
/// Returns default preferred weight based on Apple's Typography [Guidelines].
///
/// [Guidelines]: https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/typography/#dynamic-type-sizes
fileprivate func defaultPreferredWeight() -> Font.Weight {
self == .headline ? .semibold : .regular
}
}
|
mit
|
e21eb75d6ede9131c43216dc25a6f278
| 29.816038 | 132 | 0.542324 | 4.584561 | false | false | false | false |
jholsapple/TIY-Assignments
|
31 -- TheHitList -- John Holsapple/31 -- TheHitList -- John Holsapple/ViewController.swift
|
2
|
3444
|
//
// ViewController.swift
// 31 -- TheHitList -- John Holsapple
//
// Created by John Holsapple on 7/27/15.
// Copyright (c) 2015 John Holsapple -- The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource
{
var people = [NSManagedObject]()
@IBOutlet weak var tableView: UITableView!
@IBAction func addName(sender: AnyObject)
{
let alert = UIAlertController(title: "New name", message: "Add a new name", preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save", style: .Default) { (action: UIAlertAction) -> Void in
let textField = alert.textFields![0]
self.saveName(textField.text)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction) -> Void in
}
alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion: nil)
}
func saveName(name: String)
{
// 1
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
// 2
let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)
let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
// 3
person.setValue(name, forKey: "name")
// 4
var error: NSError?
do {
try managedContext.save()
} catch let error1 as NSError {
error = error1
print("Could not save \(error), \(error?.userInfo)")
}
//5
people.append(person)
}
override func viewDidLoad()
{
super.viewDidLoad()
title = "\"The List\""
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
// 1
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
// 2
let fetchRequest = NSFetchRequest(entityName:"Person")
// 3
let error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]
if let results = fetchedResults
{
people = results
}
else
{
print("Could not fetch \(error), \(error!.userInfo)")
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return people.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
let person = people[indexPath.row]
cell.textLabel!.text = person.valueForKey("name") as? String
return cell
}
}
|
cc0-1.0
|
ad2af1def0d2b6319992d00997ae7fd0
| 28.947826 | 111 | 0.618467 | 5.323029 | false | false | false | false |
jad6/CV
|
Swift/Jad's CV/Sections/ExperienceDetail/ExperienceDetailView.swift
|
1
|
3668
|
//
// ExperienceDetailView.swift
// Jad's CV
//
// Created by Jad Osseiran on 24/07/2014.
// Copyright (c) 2014 Jad. All rights reserved.
//
import UIKit
class ExperienceDetailView: DynamicTypeView {
//MARK:- Constants
private struct LayoutConstants {
struct Padding {
static let top: CGFloat = 20.0
static let betweenVerticalLarge: CGFloat = 15.0
static let betweenVerticalSmall: CGFloat = 3.0
}
static let imagveViewSize = CGSize(width: 70.0, height: 70.0)
static let imageViewMaskingRadius: CGFloat = 18.0
}
//MARK:- Properties
let organisationImageView = UIImageView()
let positionLabel = UILabel()
let organisationLabel = UILabel()
let dateLabel = UILabel()
let textView = FormattedTextView()
//MARK:- Init
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.organisationImageView.frame.size = LayoutConstants.imagveViewSize
self.organisationImageView.maskToRadius(LayoutConstants.imageViewMaskingRadius)
self.addSubview(self.organisationImageView)
self.addSubview(self.positionLabel)
self.addSubview(self.organisationLabel)
self.addSubview(self.dateLabel)
if UIDevice.isPad() {
self.textView.textContainerInset = UIEdgeInsets(top: 0.0, left: 44.0, bottom: 0.0, right: 44.0)
} else {
self.textView.textContainerInset = UIEdgeInsets(top: 0.0, left: 20.0, bottom: 0.0, right: 20.0)
}
self.addSubview(self.textView)
self.backgroundColor = UIColor.backgroundGrayColor()
}
convenience init() {
self.init(frame: CGRectZero)
}
//MARK:- Layout
override func layoutSubviews() {
super.layoutSubviews()
organisationImageView.frame.origin.y = LayoutConstants.Padding.top
organisationImageView.centerHorizontallyWithReferenceRect(self.bounds)
positionLabel.frame.size = positionLabel.sizeThatFits(bounds.size).ceilSize
positionLabel.frame.origin.y = organisationImageView.frame.maxY + LayoutConstants.Padding.betweenVerticalLarge
positionLabel.centerHorizontallyWithReferenceRect(self.bounds)
organisationLabel.frame.size = organisationLabel.sizeThatFits(bounds.size).ceilSize
organisationLabel.frame.origin.y = positionLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalSmall
organisationLabel.centerHorizontallyWithReferenceRect(self.bounds)
dateLabel.frame.size = dateLabel.sizeThatFits(bounds.size).ceilSize
dateLabel.frame.origin.y = organisationLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalSmall
dateLabel.centerHorizontallyWithReferenceRect(self.bounds)
textView.frame.origin.y = dateLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalLarge
textView.frame.size.width = bounds.size.width
textView.frame.size.height = bounds.size.height - textView.frame.origin.y
}
//MARK:- Dynamic type
override func reloadDynamicTypeContent() {
positionLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
organisationLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
dateLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
textView.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleBody)
}
}
|
bsd-3-clause
|
8b5de3c21cdaf228186f1b277cdeabbc
| 36.428571 | 118 | 0.693566 | 4.858278 | false | false | false | false |
Digipolitan/side-navigation-swift
|
Sources/SideNavigationController.swift
|
1
|
19661
|
//
// SideNavigationController.swift
// SideNavigationController
//
// Created by Benoit BRIATTE on 24/02/2017.
// Copyright © 2019 Digipolitan. All rights reserved.
//
import UIKit
open class SideNavigationController: UIViewController {
private lazy var gestures: Gestures = {
return Gestures(sideNavigationController: self)
}()
fileprivate lazy var overlay: UIView = {
let overlay = UIView()
overlay.isUserInteractionEnabled = false
overlay.autoresizingMask = UIView.AutoresizingMask(rawValue: 0b111111)
overlay.alpha = 0
return overlay
}()
fileprivate lazy var mainContainer: UIView = {
let mainContainer = UIView()
mainContainer.autoresizingMask = UIView.AutoresizingMask(rawValue: 0b111111)
return mainContainer
}()
fileprivate var sideProgress: CGFloat = 0
fileprivate var revertSideDirection: Bool = false
public private(set) var left: Side?
public private(set) var right: Side?
public var mainViewController: UIViewController! {
willSet(newValue) {
self.unlink(viewController: self.mainViewController)
}
didSet {
if let mainViewController = self.mainViewController {
self.link(viewController: mainViewController, in: self.mainContainer, at: 0)
if self.isViewLoaded {
mainViewController.view.frame = self.mainContainer.bounds
}
}
}
}
public var visibleViewController: UIViewController {
if self.visibleSideViewController != nil {
return self.visibleSideViewController!
}
return self.mainViewController
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public convenience init(mainViewController: UIViewController) {
self.init()
// swiftlint:disable inert_defer
defer {
self.mainViewController = mainViewController
}
// swiftlint:enable inert_defer
}
fileprivate var visibleSideViewController: UIViewController? {
willSet(newValue) {
if self.visibleSideViewController != newValue {
self.visibleSideViewController?.view.isHidden = true
}
}
didSet {
if self.visibleSideViewController != oldValue {
self.visibleSideViewController?.view.isHidden = false
#if os(iOS)
self.setNeedsStatusBarAppearanceUpdate()
if #available(iOS 11.0, *) {
self.setNeedsUpdateOfHomeIndicatorAutoHidden()
self.setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
}
#elseif os(tvOS)
self.setNeedsFocusUpdate()
if #available(tvOS 11.0, *) {
self.setNeedsUserInterfaceAppearanceUpdate()
}
#endif
}
}
}
fileprivate func side(direction: Direction) -> Side? {
return direction == .left ? self.left : self.right
}
fileprivate func setSide(_ side: Side, direction: Direction) {
if let old = self.side(direction: direction) {
if old.viewController == self.visibleSideViewController {
self.close(direction: direction, animated: false)
}
self.unlink(viewController: old.viewController)
}
side.viewController.view.isHidden = true
self.link(viewController: side.viewController, at: side.options.position == .back ? 0 : -1)
if direction == .left {
self.left = side
} else {
self.right = side
}
self.updateSide(with: direction, progress: 0)
#if os(iOS)
self.sideGestures(enabled: true)
#endif
}
open override func viewDidLoad() {
super.viewDidLoad()
self.mainContainer.frame = self.view.bounds
let mainBounds = self.mainContainer.bounds
self.overlay.frame = mainBounds
self.mainContainer.addSubview(self.overlay)
if let mainViewController = self.mainViewController {
mainViewController.view.frame = mainBounds
}
self.view.addSubview(self.mainContainer)
#if os(iOS)
self.mainContainer.addGestureRecognizer(self.gestures.mainPan)
self.mainContainer.addGestureRecognizer(self.gestures.mainTap)
self.view.addGestureRecognizer(self.gestures.leftScreenEdgePan)
self.view.addGestureRecognizer(self.gestures.rightScreenEdgePan)
self.sideGestures(enabled: true)
#elseif os(tvOS)
self.view.addGestureRecognizer(self.gestures.mainPan)
self.view.addGestureRecognizer(self.gestures.mainTap)
#endif
self.mainGestures(enabled: false)
}
private func link(viewController: UIViewController, in view: UIView? = nil, at position: Int = -1) {
viewController.view.autoresizingMask = UIView.AutoresizingMask(rawValue: 0b111111)
let container: UIView = view != nil ? view! : self.view
self.addChild(viewController)
if position < 0 {
container.addSubview(viewController.view)
} else {
container.insertSubview(viewController.view, at: position)
}
}
private func unlink(viewController: UIViewController?) {
if let viewController = viewController {
viewController.view.removeFromSuperview()
viewController.removeFromParent()
}
}
#if os(iOS)
open override var childForStatusBarStyle: UIViewController? {
return self.visibleViewController
}
open override var childForStatusBarHidden: UIViewController? {
return self.visibleViewController
}
@available(iOS 11.0, *)
open override var childForHomeIndicatorAutoHidden: UIViewController? {
return self.visibleViewController
}
@available(iOS 11.0, *)
open override var childForScreenEdgesDeferringSystemGestures: UIViewController? {
return self.visibleViewController
}
#elseif os(tvOS)
@available(tvOS 11.0, *)
open override var childViewControllerForUserInterfaceStyle: UIViewController? {
return self.visibleViewController
}
open override var preferredFocusEnvironments: [UIFocusEnvironment] {
return self.visibleViewController.preferredFocusEnvironments
}
#endif
public func leftSide(viewController: UIViewController, options: Options = Options()) {
self.setSide(Side(viewController: viewController, options: options), direction: .left)
}
public func rightSide(viewController: UIViewController, options: Options = Options()) {
self.setSide(Side(viewController: viewController, options: options), direction: .right)
}
public func closeSide(animated: Bool = true) {
guard let visibleSideViewController = self.visibleSideViewController else {
return
}
if self.left?.viewController == visibleSideViewController {
self.close(direction: .left, animated: animated)
} else if self.right?.viewController == visibleSideViewController {
self.close(direction: .right, animated: animated)
}
}
private func close(direction: Direction, animated: Bool) {
guard self.visibleSideViewController != nil else {
return; // NO SIDE VISIBLE TO CLOSE
}
guard let side = self.side(direction: direction) else {
// EXCEPTION
return
}
side.viewController.view.endEditing(animated)
UIView.animate(withDuration: animated ? side.options.animationDuration : 0, animations: {
self.visibleSideViewController = nil
side.viewController.view.isHidden = false
self.updateSide(with: direction, progress: 0)
}, completion: { _ in
side.viewController.view.isHidden = true
self.revertSideDirection = false
self.mainGestures(enabled: false, direction: direction)
#if os(iOS)
self.sideGestures(enabled: true)
#endif
})
}
public func showLeftSide(animated: Bool = true) {
self.show(direction: .left, animated: animated)
}
public func showRightSide(animated: Bool = true) {
self.show(direction: .right, animated: animated)
}
fileprivate func show(direction: Direction, animated: Bool) {
guard let side = self.side(direction: direction) else {
// EXCEPTION
return
}
guard side.viewController == self.visibleSideViewController || self.visibleSideViewController == nil else {
return
}
self.mainViewController.view.endEditing(animated)
UIView.animate(withDuration: animated ? side.options.animationDuration : 0, animations: {
self.visibleSideViewController = side.viewController
self.updateSide(with: direction, progress: 1)
}, completion: { _ in
self.revertSideDirection = true
self.mainGestures(enabled: true, direction: direction)
#if os(iOS)
self.sideGestures(enabled: false)
#endif
})
}
fileprivate func updateSide(with direction: Direction, progress: CGFloat) {
guard let side = self.side(direction: direction) else {
// EXCEPTION
return
}
self.sideProgress = progress
if side.options.position == .back {
self.updateBack(side: side, direction: direction, progress: progress)
} else {
self.updateFront(side: side, direction: direction, progress: progress)
}
}
fileprivate func mainGestures(enabled: Bool, direction: Direction? = nil) {
var overlayInteractionEnabled = enabled
var panningEnabled = enabled
if enabled && direction != nil {
if let side = self.side(direction: direction!) {
overlayInteractionEnabled = !side.options.alwaysInteractionEnabled
panningEnabled = side.options.panningEnabled
}
}
self.overlay.isUserInteractionEnabled = overlayInteractionEnabled
self.gestures.mainPan.isEnabled = panningEnabled
self.gestures.mainTap.isEnabled = enabled
}
#if os(iOS)
fileprivate func sideGestures(enabled: Bool) {
self.gestures.leftScreenEdgePan.isEnabled = enabled ? self.left?.options.panningEnabled ?? false : enabled
self.gestures.rightScreenEdgePan.isEnabled = enabled ? self.right?.options.panningEnabled ?? false : enabled
}
#endif
}
// NESTED TYPES
public extension SideNavigationController {
fileprivate enum Direction {
case left
case right
}
fileprivate class Gestures {
public static let velocityTolerance: CGFloat = 600
private weak var sideNavigationController: SideNavigationController?
#if os(iOS)
public var leftScreenEdgePan: UIScreenEdgePanGestureRecognizer!
public var rightScreenEdgePan: UIScreenEdgePanGestureRecognizer!
#endif
public var mainPan: UIPanGestureRecognizer!
public var mainTap: UITapGestureRecognizer!
init(sideNavigationController: SideNavigationController) {
self.sideNavigationController = sideNavigationController
#if os(iOS)
let leftScreenEdgePan = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handle(panGesture:)))
leftScreenEdgePan.edges = .left
leftScreenEdgePan.maximumNumberOfTouches = 1
self.leftScreenEdgePan = leftScreenEdgePan
let rightScreenEdgePan = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handle(panGesture:)))
rightScreenEdgePan.edges = .right
rightScreenEdgePan.maximumNumberOfTouches = 1
self.rightScreenEdgePan = rightScreenEdgePan
self.leftScreenEdgePan.require(toFail: self.rightScreenEdgePan)
self.rightScreenEdgePan.require(toFail: self.leftScreenEdgePan)
#endif
self.mainPan = UIPanGestureRecognizer(target: self, action: #selector(handle(panGesture:)))
self.mainTap = UITapGestureRecognizer(target: self, action: #selector(handle(tapGesture:)))
#if os(tvOS)
self.mainTap.allowedPressTypes = [NSNumber(value: UIPress.PressType.menu.rawValue)]
#endif
self.mainTap.require(toFail: self.mainPan)
}
@objc
private func handle(panGesture: UIPanGestureRecognizer) {
guard let sideNavigationController = self.sideNavigationController else {
return
}
if panGesture.state == .changed {
let offset = panGesture.translation(in: sideNavigationController.view).x
sideNavigationController.update(offset: offset)
} else if panGesture.state != .began {
let velocity = panGesture.velocity(in: sideNavigationController.view)
let info = self.info(velocity: velocity.x)
sideNavigationController.finish(direction: info.direction, swipe: info.swipe)
}
}
@objc
private func handle(tapGesture: UITapGestureRecognizer) {
guard let sideNavigationController = self.sideNavigationController else {
return
}
if sideNavigationController.visibleSideViewController == sideNavigationController.left?.viewController {
sideNavigationController.finish(direction: .left, swipe: true)
} else {
sideNavigationController.finish(direction: .right, swipe: true)
}
}
private func info(velocity: CGFloat) -> (direction: Direction, swipe: Bool) {
if velocity >= 0 {
if velocity > Gestures.velocityTolerance {
return (direction: .right, swipe: true)
}
return (direction: .right, swipe: false)
}
if -velocity > Gestures.velocityTolerance {
return (direction: .left, swipe: true)
}
return (direction: .left, swipe: false)
}
}
}
// DRAWING
fileprivate extension SideNavigationController {
func apply(options: Options, front: UIView!, back: UIView!, progress: CGFloat) {
self.overlay.alpha = options.overlayOpacity * progress
self.overlay.backgroundColor = options.overlayColor
front.layer.shadowColor = options.shadowCGColor
front.layer.shadowOpacity = Float(options.shadowOpacity)
front.layer.shadowRadius = 10
back.layer.shadowColor = nil
back.layer.shadowOpacity = 0
back.layer.shadowRadius = 3
if options.scale != 1 {
let scale = 1 - (1 - options.scale) * progress
self.mainContainer.transform = CGAffineTransform.identity.scaledBy(x: scale, y: scale)
}
}
func updateBack(side: Side, direction: Direction, progress: CGFloat) {
let sideView: UIView! = side.viewController.view
self.apply(options: side.options, front: self.mainContainer, back: sideView, progress: progress)
var mainFrame = self.mainContainer.frame
let viewBounds = self.view.bounds
var sideFrame = sideView.frame
sideFrame.size.width = viewBounds.width * side.options.widthPercent
sideFrame.size.height = viewBounds.height
let parallaxWidth = sideFrame.width / 3
switch direction {
case .left :
mainFrame.origin.x = sideFrame.width * progress
sideFrame.origin.x = parallaxWidth * progress - parallaxWidth
case .right :
mainFrame.origin.x = -sideFrame.width * progress
sideFrame.origin.x = (viewBounds.width - sideFrame.width) + parallaxWidth * (1.0 - progress)
}
self.mainContainer.frame = mainFrame
sideView.frame = sideFrame
}
func updateFront(side: Side, direction: Direction, progress: CGFloat) {
let sideView: UIView! = side.viewController.view
self.apply(options: side.options, front: sideView, back: self.mainContainer, progress: progress)
let viewBounds = self.view.bounds
var sideFrame = sideView.frame
sideFrame.size.width = viewBounds.width * side.options.widthPercent
sideFrame.size.height = viewBounds.height
switch direction {
case .left :
sideFrame.origin.x = -sideFrame.width + sideFrame.width * progress
case .right :
sideFrame.origin.x = (viewBounds.width - sideFrame.width) + sideFrame.width * (1.0 - progress)
}
sideView.frame = sideFrame
}
}
// GESTURES
fileprivate extension SideNavigationController {
func update(offset: CGFloat) {
if let left = self.left {
if self.visibleSideViewController == left.viewController || (offset > 0 && self.visibleSideViewController == nil) {
UIView.animate(withDuration: left.options.animationDuration, animations: {
self.visibleSideViewController = left.viewController
})
let leftWidth = left.viewController.view.frame.width
var progress = min(abs(offset), leftWidth) / leftWidth
if self.revertSideDirection {
progress = 1 - (offset <= 0 ? progress : 0)
} else if offset <= 0 {
progress = 0
}
self.updateSide(with: .left, progress: progress)
return
}
}
if let right = self.right {
if self.visibleSideViewController == right.viewController || (offset < 0 && self.visibleSideViewController == nil) {
UIView.animate(withDuration: right.options.animationDuration, animations: {
self.visibleSideViewController = right.viewController
})
let rightWidth = right.viewController.view.frame.width
var progress = min(abs(offset), rightWidth) / rightWidth
if self.revertSideDirection {
progress = 1 - (offset >= 0 ? progress : 0)
} else if offset >= 0 {
progress = 0
}
self.updateSide(with: .right, progress: progress)
return
}
}
var mainFrame = self.mainContainer.frame
mainFrame.origin.x = 0
self.mainContainer.frame = mainFrame
}
func finish(direction: Direction, swipe: Bool) {
if self.visibleSideViewController != nil {
if self.visibleSideViewController == self.left?.viewController {
if !(swipe && direction == .left) {
if self.sideProgress > 0.5 || swipe {
self.show(direction: .left, animated: true)
return
}
}
} else if !(swipe && direction == .right) {
if self.sideProgress > 0.5 || swipe {
self.show(direction: .right, animated: true)
return
}
}
}
self.closeSide()
}
}
|
bsd-3-clause
|
fa3e4eb702830a818003d846855d9700
| 37.77712 | 128 | 0.624161 | 5.056584 | false | false | false | false |
OSzhou/MyTestDemo
|
PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-Mustache.git-4271886153857801499/Package.swift
|
1
|
766
|
//
// Package.swift
// PerfectMustache
//
// Created by Kyle Jessup on 2016-05-02.
// Copyright (C) 2016 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PackageDescription
let package = Package(
name: "PerfectMustache",
targets: [],
dependencies: [.Package(url: "https://github.com/PerfectlySoft/Perfect-HTTP.git", majorVersion: 2)],
exclude: []
)
|
apache-2.0
|
803f2728f45075dc3fb155ccd26755f0
| 27.37037 | 101 | 0.560052 | 4.377143 | false | false | false | false |
kesun421/firefox-ios
|
Client/Frontend/Browser/BackForwardListViewController.swift
|
3
|
9357
|
/* 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
import Shared
import WebKit
import Storage
import SnapKit
struct BackForwardViewUX {
static let RowHeight: CGFloat = 50
static let BackgroundColor = UIColor(rgb: 0xf9f9fa).withAlphaComponent(0.4)
}
class BackForwardListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate {
fileprivate let BackForwardListCellIdentifier = "BackForwardListViewController"
fileprivate var profile: Profile
fileprivate lazy var sites = [String: Site]()
fileprivate var dismissing = false
fileprivate var currentRow = 0
fileprivate var verticalConstraints: [Constraint] = []
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.separatorStyle = .none
tableView.dataSource = self
tableView.delegate = self
tableView.alwaysBounceVertical = false
tableView.register(BackForwardTableViewCell.self, forCellReuseIdentifier: self.BackForwardListCellIdentifier)
tableView.backgroundColor = BackForwardViewUX.BackgroundColor
let blurEffect = UIBlurEffect(style: .extraLight)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
tableView.backgroundView = blurEffectView
return tableView
}()
lazy var shadow: UIView = {
let shadow = UIView()
shadow.backgroundColor = UIColor(white: 0, alpha: 0.2)
return shadow
}()
var tabManager: TabManager!
weak var bvc: BrowserViewController?
var currentItem: WKBackForwardListItem?
var listData = [WKBackForwardListItem]()
var tableHeight: CGFloat {
get {
assert(Thread.isMainThread, "tableHeight interacts with UIKit components - cannot call from background thread.")
return min(BackForwardViewUX.RowHeight * CGFloat(listData.count), self.view.frame.height/2)
}
}
var backForwardTransitionDelegate: UIViewControllerTransitioningDelegate? {
didSet {
self.transitioningDelegate = backForwardTransitionDelegate
}
}
var snappedToBottom: Bool = true
init(profile: Profile, backForwardList: WKBackForwardList) {
self.profile = profile
super.init(nibName: nil, bundle: nil)
loadSites(backForwardList)
loadSitesFromProfile()
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(shadow)
view.addSubview(tableView)
snappedToBottom = bvc?.toolbar != nil
tableView.snp.makeConstraints { make in
make.height.equalTo(0)
make.left.right.equalTo(self.view)
}
shadow.snp.makeConstraints { make in
make.left.right.equalTo(self.view)
}
remakeVerticalConstraints()
view.layoutIfNeeded()
scrollTableViewToIndex(currentRow)
setupDismissTap()
}
func loadSitesFromProfile() {
let sql = profile.favicons as! SQLiteHistory
let urls = listData.flatMap {$0.url.isLocal ? $0.url.getQuery()["url"]?.unescape() : $0.url.absoluteString}
sql.getSitesForURLs(urls).uponQueue(.main) { result in
guard let results = result.successValue else {
return
}
// Add all results into the sites dictionary
results.flatMap({$0}).forEach({site in
if let url = site?.url {
self.sites[url] = site
}
})
self.tableView.reloadData()
}
}
func homeAndNormalPagesOnly(_ bfList: WKBackForwardList) {
let items = bfList.forwardList.reversed() + [bfList.currentItem].flatMap({$0}) + bfList.backList.reversed()
//error url's are OK as they are used to populate history on session restore.
listData = items.filter({return !($0.url.isLocal && ($0.url.originalURLFromErrorURL?.isLocal ?? true)) || $0.url.isAboutHomeURL})
}
func loadSites(_ bfList: WKBackForwardList) {
currentItem = bfList.currentItem
homeAndNormalPagesOnly(bfList)
}
func scrollTableViewToIndex(_ index: Int) {
guard index > 1 else {
return
}
let moveToIndexPath = IndexPath(row: index-2, section: 0)
tableView.reloadRows(at: [moveToIndexPath], with: .none)
tableView.scrollToRow(at: moveToIndexPath, at: UITableViewScrollPosition.middle, animated: false)
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
guard let bvc = self.bvc else {
return
}
if bvc.shouldShowFooterForTraitCollection(newCollection) != snappedToBottom {
tableView.snp.updateConstraints { make in
if snappedToBottom {
make.bottom.equalTo(self.view).offset(0)
} else {
make.top.equalTo(self.view).offset(0)
}
make.height.equalTo(0)
}
snappedToBottom = !snappedToBottom
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let correctHeight = {
self.tableView.snp.updateConstraints { make in
make.height.equalTo(min(BackForwardViewUX.RowHeight * CGFloat(self.listData.count), size.height / 2))
}
}
coordinator.animate(alongsideTransition: nil) { _ in
self.remakeVerticalConstraints()
correctHeight()
}
}
func remakeVerticalConstraints() {
guard let bvc = self.bvc else {
return
}
for constraint in self.verticalConstraints {
constraint.deactivate()
}
self.verticalConstraints = []
tableView.snp.makeConstraints { make in
if snappedToBottom {
verticalConstraints += [make.bottom.equalTo(self.view).offset(-bvc.footer.frame.height).constraint]
} else {
verticalConstraints += [make.top.equalTo(self.view).offset(bvc.header.frame.height + UIApplication.shared.statusBarFrame.size.height).constraint]
}
}
shadow.snp.makeConstraints() { make in
if snappedToBottom {
verticalConstraints += [
make.bottom.equalTo(tableView.snp.top).constraint,
make.top.equalTo(self.view).constraint
]
} else {
verticalConstraints += [
make.top.equalTo(tableView.snp.bottom).constraint,
make.bottom.equalTo(self.view).constraint
]
}
}
}
func setupDismissTap() {
let tap = UITapGestureRecognizer(target: self, action: #selector(BackForwardListViewController.handleTap))
tap.cancelsTouchesInView = false
tap.delegate = self
view.addGestureRecognizer(tap)
}
func handleTap() {
dismiss(animated: true, completion: nil)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view?.isDescendant(of: tableView) ?? true {
return false
}
return true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: BackForwardListCellIdentifier, for: indexPath) as! BackForwardTableViewCell
let item = listData[indexPath.item]
let urlString = item.url.isLocal ? item.url.getQuery()["url"]?.unescape() : item.url.absoluteString
cell.isCurrentTab = listData[indexPath.item] == self.currentItem
cell.connectingBackwards = indexPath.item != listData.count-1
cell.connectingForwards = indexPath.item != 0
guard let url = urlString, !item.url.isAboutHomeURL else {
cell.site = Site(url: item.url.absoluteString, title: Strings.FirefoxHomePage)
return cell
}
cell.site = sites[url] ?? Site(url: url, title: item.title ?? "")
cell.setNeedsDisplay()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tabManager.selectedTab?.goToBackForwardListItem(listData[indexPath.item])
dismiss(animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return BackForwardViewUX.RowHeight
}
}
|
mpl-2.0
|
f6ed36ad7e23133bc0f7d3528aaa9003
| 36.578313 | 161 | 0.633323 | 5.152533 | false | false | false | false |
alloyapple/Goose
|
Sources/Goose/Socket.swift
|
1
|
21917
|
//
// Created by color on 17-9-23.
//
import Foundation
import Glibc
public typealias Byte = UInt8
public typealias Bytes = [Byte]
public typealias ByteBuffer = UnsafeBufferPointer<Byte>
public typealias MutableByteBuffer = UnsafeMutableBufferPointer<Byte>
public typealias BytesPointer = UnsafePointer<Byte>
public typealias MutableBytesPointer = UnsafeMutablePointer<Byte>
public enum SockFamily: Int32 {
case inet = 2
case inet6 = 10
case unix = 1
}
public enum SocketType: Int32 {
case tcp = 1
case udp = 2
}
public enum SocketProtocol: Int32 {
case tcp = 6
case udp = 17
case unix = 0
}
public class Socket: FileDescriptor {
public let family: SockFamily
public let proto: SocketProtocol
public let type: SocketType
var blocking: Bool {
set {
var delay_flag = self.fcntl(cmd: F_GETFL, arg: 0) ?? 0
if newValue {
delay_flag &= (~O_NONBLOCK)
} else {
delay_flag |= (O_NONBLOCK)
}
_ = self.fcntl(cmd: F_SETFL, arg: delay_flag)
}
get {
let delay_flag = self.fcntl(cmd: F_GETFL, arg: 0) ?? 0
if delay_flag & O_NONBLOCK == 0 {
return true
} else {
return false
}
}
}
public init(family: SockFamily = .inet, type: SocketType = .tcp, proto: SocketProtocol = .tcp) {
let fd = Glibc.socket(family.rawValue, type.rawValue, proto.rawValue)
self.family = family
self.proto = proto
self.type = type
super.init(fd: fd)
}
public init(fd: Int32, family: SockFamily = .inet, type: SocketType = .tcp, proto: SocketProtocol = .tcp) {
self.family = family
self.proto = proto
self.type = type
super.init(fd: fd)
}
public func accept() -> Socket? {
let clientFd = Glibc.accept(fd, nil, nil)
guard clientFd > 0 else {
return nil
}
return Socket(fd: clientFd, family: self.family, type: self.type, proto: self.proto)
}
public func bind(hostname: String = "localhost", port: UInt16 = 80) -> Bool {
var hints = addrinfo()
// Support both IPv4 and IPv6
hints.ai_family = self.family.rawValue
// Specify that this is a TCP Stream
hints.ai_socktype = self.type.rawValue
hints.ai_protocol = self.proto.rawValue
// If the AI_PASSIVE flag is specified in hints.ai_flags, and node is
// NULL, then the returned socket addresses will be suitable for
// bind(2)ing a socket that will accept(2) connections.
hints.ai_flags = AI_PASSIVE
// Look ip the sockeaddr for the hostname
var result: UnsafeMutablePointer<addrinfo>?
var res = Glibc.getaddrinfo(hostname, "\(port)", &hints, &result)
guard res == 0 else {
return false
}
defer {
freeaddrinfo(result)
}
guard let info = result else {
return false
}
res = Glibc.bind(fd, info.pointee.ai_addr, info.pointee.ai_addrlen)
guard res == 0 else {
return false
}
return true
}
public func bind(path: String) -> Bool {
_ = Glibc.unlink(path)
let addrlen = MemoryLayout<sockaddr_un>.size
var acceptAddr = sockaddr_un()
acceptAddr.sun_family = UInt16(Glibc.AF_UNIX)
let bytes = path.utf8CString
let buffer = UnsafeMutableBufferPointer<CChar>(start: &acceptAddr.sun_path.0,
count: MemoryLayout.size(ofValue: acceptAddr.sun_path))
for (i, byte) in bytes.enumerated() {
buffer[i] = CChar(byte)
if i >= len(path) - 1 {
break
}
}
let ret = Glibc.bind(self.fd, toAddr(&acceptAddr), UInt32(addrlen))
guard ret > 0 else {
return false
}
return true
}
public func connect(hostname: String = "localhost", port: UInt16 = 80) -> Bool {
var hints = addrinfo()
// Support both IPv4 and IPv6
hints.ai_family = self.family.rawValue
// Specify that this is a TCP Stream
hints.ai_socktype = self.type.rawValue
// Look ip the sockeaddr for the hostname
var result: UnsafeMutablePointer<addrinfo>?
var res = getaddrinfo(hostname, "\(port)", &hints, &result)
guard res == 0 else {
return false
}
defer {
freeaddrinfo(result)
}
guard let info = result else {
return false
}
res = Glibc.connect(self.fd, info.pointee.ai_addr, info.pointee.ai_addrlen)
guard res == 0 else {
return false
}
return true
}
public func connect(path: String) -> Bool {
_ = Glibc.unlink(path)
let addrlen = MemoryLayout<sockaddr_un>.size
var acceptAddr = sockaddr_un()
acceptAddr.sun_family = UInt16(Glibc.AF_UNIX)
let bytes = path.utf8CString
let buffer = UnsafeMutableBufferPointer<CChar>(start: &acceptAddr.sun_path.0,
count: MemoryLayout.size(ofValue: acceptAddr.sun_path))
for (i, byte) in bytes.enumerated() {
buffer[i] = CChar(byte)
if i >= len(path) - 1 {
break
}
}
let ret = withUnsafeMutablePointer(to: &acceptAddr) {
Glibc.connect(fd, UnsafeMutableRawPointer($0).assumingMemoryBound(to: sockaddr.self), UInt32(addrlen))
}
guard ret > 0 else {
return false
}
return true
}
public func getsockname(host: inout String, port: inout UInt16) -> Bool {
var sin = sockaddr_in()
var len = UInt32(MemoryLayout.size(ofValue: sin))
guard Glibc.getsockname(self.fd, toAddr(&sin), &len) != -1 else {
return false
}
port = Glibc.ntohs(sin.sin_port)
var ip = [Int8](repeating: 0, count: 17)
Glibc.inet_ntop(AF_INET, &sin.sin_addr, &ip, 16)
host = String(data: ip)
return true
}
public func getsocknamev6(host: inout String, port: inout UInt16) -> Bool {
var sin = sockaddr_in6()
var len = UInt32(MemoryLayout.size(ofValue: sin))
guard Glibc.getsockname(self.fd, toAddr(&sin), &len) != -1 else {
return false
}
port = Glibc.ntohs(sin.sin6_port)
var ip = [Int8](repeating: 0, count: 17)
Glibc.inet_ntop(AF_INET, &sin.sin6_addr, &ip, 16)
host = String(data: ip)
return true
}
public func getpeername(host: inout String, port: inout UInt16) -> Bool {
var sin = sockaddr_in()
var len = UInt32(MemoryLayout.size(ofValue: sin))
guard Glibc.getpeername(self.fd, toAddr(&sin), &len) != -1 else {
return false
}
port = Glibc.ntohs(sin.sin_port)
var ip = [Int8](repeating: 0, count: 17)
Glibc.inet_ntop(AF_INET, &sin.sin_addr, &ip, 16)
host = String(data: ip)
return true
}
public func getpeernamev6(host: inout String, port: inout UInt16) -> Bool {
var sin = sockaddr_in6()
var len = UInt32(MemoryLayout.size(ofValue: sin))
guard Glibc.getpeername(self.fd, toAddr(&sin), &len) != -1 else {
return false
}
port = Glibc.ntohs(sin.sin6_port)
var ip = [Int8](repeating: 0, count: 17)
Glibc.inet_ntop(AF_INET, &sin.sin6_addr, &ip, 16)
host = String(data: ip)
return true
}
public func close() {
Glibc.close(self.fd)
}
public func listen(backlog: Int32 = 4096) -> Bool {
let res = Glibc.listen(self.fd, backlog)
guard res == 0 else {
return false
}
return true
}
public func dup() -> Socket {
let newfd = Glibc.dup(self.fd)
return Socket(fd: newfd, family: family, type: type, proto: proto)
}
override public func write(_ data: [Int8]) -> Int {
return Glibc.write(self.fd, data, data.count)
}
override public func read(_ data: inout [Int8]) -> Int {
return Glibc.read(self.fd, &data, data.count)
}
public func read(max: Int, into buffer: MutableByteBuffer) -> Int? {
let receivedBytes = Glibc.read(self.fd, buffer.baseAddress.unsafelyUnwrapped, max)
guard receivedBytes != -1 else {
switch errno {
case EINTR:
// try again
return read(max: max, into: buffer)
case ECONNRESET:
// closed by peer, need to close this side.
// Since this is not an error, no need to throw unless the close
// itself throws an error.
_ = close()
return 0
case EAGAIN:
// timeout reached (linux)
return 0
default:
return nil
}
}
guard receivedBytes > 0 else {
// receiving 0 indicates a proper close .. no error.
// attempt a close, no failure possible because throw indicates already closed
// if already closed, no issue.
// do NOT propogate as error
_ = close()
return 0
}
return receivedBytes
}
public func read(_ max: Int) -> Data? {
var pointer = MutableBytesPointer.allocate(capacity: max)
defer {
pointer.deallocate()
pointer.deinitialize(count: max)
}
let buffer = MutableByteBuffer(start: pointer, count: max)
guard let read = self.read(max: max, into: buffer) else {
return nil
}
let frame = ByteBuffer(start: pointer, count: read)
return Data(buffer: frame)
}
public func write(max: Int, from buffer: ByteBuffer) -> Int? {
guard let pointer = buffer.baseAddress else {
return nil
}
let sent = send(self.fd, pointer, max, 0)
guard sent != -1 else {
switch errno {
case EINTR:
// try again
return write(max: max, from: buffer)
case ECONNRESET, EBADF:
self.close()
return 0
default:
return nil
}
}
return sent
}
public func write(_ data: Data) -> Int? {
let buffer = ByteBuffer(start: data.withUnsafeBytes {
$0
}, count: data.count)
guard let ret = write(max: data.count, from: buffer) else {
return nil
}
return ret
}
public func sendall(_ data: Data) {
let bytes = Array(data)
self.sendall(bytes)
}
public func sendall(_ data: [UInt8]) -> Int {
var data = data
let dataLen = data.count
var len = data.count
while len > 0 {
let leftLen = Glibc.send(self.fd, &data, len, 0)
guard leftLen >= 0 else {
return dataLen - len
}
len = len - leftLen
if len > 0 {
data.removeFirst(leftLen)
}
if leftLen < 0 {
break
}
}
return dataLen - len
}
public func getsockopt<T>(level: Int, name: Int32) -> T? {
guard sockoptsize(Int32(level), name) == MemoryLayout<T>.size else {
return nil
}
let ptr = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer {
ptr.deallocate()
}
var length = socklen_t(MemoryLayout<T>.size)
let result = Glibc.getsockopt(self.fd, Int32(level), name, ptr, &length)
if result != 0 {
return nil
}
let value = ptr.pointee
return value
}
@discardableResult
public func setsockopt<T>(level: Int, name: Int32, value: T) -> Bool {
guard sockoptsize(Int32(level), name) == MemoryLayout<T>.size else {
return false
}
var value = value
let result = Glibc.setsockopt(self.fd, Int32(level), name, &value, socklen_t(MemoryLayout<T>.size))
if result != 0 {
return false
}
return true
}
public func getsockopt(level: Int, name: Int32) -> Bool {
let value: Int32 = getsockopt(level: level, name: name) ?? 0
return value != 0
}
public func setsockopt(level: Int, name: Int32, value: Bool) {
let value: Int32 = value ? -1 : 0
setsockopt(level: level, name: name, value: value)
}
// Just for bools
public func getsockopt(level: Int, name: Int32) -> TimeInterval {
let value: TimeInterval = getsockopt(level: level, name: name) ?? 0
return value
}
public func setsockopt(level: Int, name: Int32, value: TimeInterval) {
setsockopt(level: level, name: name, value: value)
}
fileprivate func sockoptsize(_ level: Int32, _ name: Int32) -> Int {
var length = socklen_t(256)
var buffer = [UInt8](repeating: 0, count: Int(length))
return buffer.withUnsafeMutableBufferPointer() {
(buffer: inout UnsafeMutableBufferPointer<UInt8>) -> Int in
let result = Glibc.getsockopt(self.fd, level, name, buffer.baseAddress, &length)
if result != 0 {
return 0
}
return Int(length)
}
}
deinit {
}
}
public extension Socket {
var socketOptions: SocketOptions {
return SocketOptions(socket: self)
}
}
public class SocketOptions {
public fileprivate(set) weak var socket: Socket!
public init(socket: Socket) {
self.socket = socket
}
}
public extension SocketOptions {
/// turn on debugging info recording
var debug: Bool {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_DEBUG) ?? false
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_DEBUG, value: newValue)
}
}
/// socket has had listen()
var acceptConnection: Bool {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_ACCEPTCONN) ?? false
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_ACCEPTCONN, value: newValue)
}
}
/// allow local address reuse
var reuseAddress: Bool {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_REUSEADDR) ?? false
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_REUSEADDR, value: newValue)
}
}
/// keep connections alive
var keepAlive: Bool {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_KEEPALIVE) ?? false
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_KEEPALIVE, value: newValue)
}
}
/// just use interface addresses
var dontRoute: Bool {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_DONTROUTE) ?? false
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_DONTROUTE, value: newValue)
}
}
/// permit sending of broadcast msgs
var broadcast: Bool {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_BROADCAST) ?? false
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_BROADCAST, value: newValue)
}
}
/// linger on close if data present (in ticks)
var linger: Int64 {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_LINGER) ?? 0
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_LINGER, value: newValue)
}
}
/// leave received OOB data in line
var outOfBandInline: Bool {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_OOBINLINE)
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_OOBINLINE, value: newValue)
}
}
/// allow local address & port reuse
var reusePort: Bool {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_REUSEPORT) ?? false
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_REUSEPORT, value: newValue)
}
}
// SO_TIMESTAMP
// SO_TIMESTAMP_MONOTONIC
// SO_DONTTRUNC: APPLE: Retain unread data *
// SO_WANTMORE: APPLE: Give hint when more data ready *
// SO_WANTOOBFLAG: APPLE: Want OOB in MSG_FLAG on receive *
/// send buffer size *
var sendBufferSize: Int32 {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_SNDBUF) ?? 0
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_SNDBUF, value: newValue)
}
}
/// receive buffer size *
var receiveBufferSize: Int32 {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_RCVBUF) ?? 0
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_RCVBUF, value: newValue)
}
}
/// send low-water mark *
var sendLowWaterMark: Int32 {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_SNDLOWAT) ?? 0
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_SNDLOWAT, value: newValue)
}
}
/// receive low-water mark
var receiveLowWaterMark: Int32 {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_RCVLOWAT) ?? 0
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_RCVLOWAT, value: newValue)
}
}
/// send timeout
var sendTimeout: TimeInterval {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_SNDTIMEO) ?? 0
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_SNDTIMEO, value: newValue)
}
}
/// receive timeout
var receiveTimeout: TimeInterval {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_RCVTIMEO) ?? 0
}
set {
socket.setsockopt(level: Int(SOL_SOCKET), name: SO_RCVTIMEO, value: newValue)
}
}
/// get error status and clear *
var error: Int32 {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_ERROR) ?? 0
}
}
/// get socket type *
var type: Int32 {
get {
return socket.getsockopt(level: Int(SOL_SOCKET), name: SO_TYPE) ?? 0
}
}
}
public extension SocketOptions {
var all: [String: Any] {
var all: [String: Any] = [:]
all["debug"] = debug
all["reuseAddress"] = reuseAddress
all["keepAlive"] = keepAlive
all["dontRoute"] = dontRoute
all["broadcast"] = broadcast
all["linger"] = linger
all["outOfBandInline"] = outOfBandInline
all["reusePort"] = reusePort
all["sendBufferSize"] = sendBufferSize
all["receiveBufferSize"] = receiveBufferSize
all["sendLowWaterMark"] = sendLowWaterMark
all["receiveLowWaterMark"] = receiveLowWaterMark
all["sendTimeout"] = sendTimeout
all["receiveTimeout"] = receiveTimeout
all["error"] = error
all["type"] = type
return all
}
}
public extension SocketOptions {
/// don't delay send to coalesce packets
var noDelay: Bool {
get {
return socket.getsockopt(level: IPPROTO_TCP, name: TCP_NODELAY) ?? false
}
set {
socket.setsockopt(level: IPPROTO_TCP, name: TCP_NODELAY, value: newValue)
}
}
/// set maximum segment size
var maxSegmentSize: Int32 {
get {
return socket.getsockopt(level: IPPROTO_TCP, name: TCP_MAXSEG) ?? 0
}
set {
socket.setsockopt(level: IPPROTO_TCP, name: TCP_MAXSEG, value: newValue)
}
}
/// interval between keepalives
var keepAliveInterval: Int32 {
get {
return socket.getsockopt(level: IPPROTO_TCP, name: TCP_KEEPINTVL) ?? 0
}
set {
socket.setsockopt(level: IPPROTO_TCP, name: TCP_KEEPINTVL, value: newValue)
}
}
/// number of keepalives before close
var keepAliveCount: Int32 {
get {
return socket.getsockopt(level: IPPROTO_TCP, name: TCP_KEEPCNT) ?? 0
}
set {
socket.setsockopt(level: IPPROTO_TCP, name: TCP_KEEPCNT, value: newValue)
}
}
/// Enable/Disable TCP Fastopen on this socket
var fastOpen: Bool {
get {
return socket.getsockopt(level: IPPROTO_TCP, name: TCP_FASTOPEN) ?? false
}
set {
socket.setsockopt(level: IPPROTO_TCP, name: TCP_FASTOPEN, value: newValue)
}
}
/// Low water mark for TCP unsent data
var notSentLowWaterMark: Int32 {
get {
return socket.getsockopt(level: IPPROTO_TCP, name: TCP_NOTSENT_LOWAT) ?? 0
}
set {
socket.setsockopt(level: IPPROTO_TCP, name: TCP_NOTSENT_LOWAT, value: newValue)
}
}
}
public extension SocketOptions {
var tcpAll: [String: Any] {
var all: [String: Any] = [:]
all["noDelay"] = noDelay
all["maxSegmentSize"] = maxSegmentSize
all["keepAliveInterval"] = keepAliveInterval
all["keepAliveCount"] = keepAliveCount
all["notSentLowWaterMark"] = notSentLowWaterMark
return all
}
}
|
bsd-3-clause
|
a94802a4b513e7b799a41badd6e0621e
| 26.921019 | 114 | 0.555687 | 4.02812 | false | false | false | false |
arnoappenzeller/PiPifier
|
PiPifier iOS/PiPifier iOS/SwiftUI Representables/MailView.swift
|
1
|
2005
|
//
// MailView.swift
// PiPifier iOS
//
// Created by Arno on 27.06.20.
// Copyright © 2020 APPenzeller. All rights reserved.
//
import SwiftUI
import MessageUI
struct MailView: UIViewControllerRepresentable {
@Binding var isShowing: Bool
@Binding var result: Result<MFMailComposeResult, Error>?
class Coordinator: NSObject, MFMailComposeViewControllerDelegate {
@Binding var isShowing: Bool
@Binding var result: Result<MFMailComposeResult, Error>?
init(isShowing: Binding<Bool>,
result: Binding<Result<MFMailComposeResult, Error>?>) {
_isShowing = isShowing
_result = result
}
func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult,
error: Error?) {
defer {
isShowing = false
}
guard error == nil else {
self.result = .failure(error!)
return
}
self.result = .success(result)
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(isShowing: $isShowing,
result: $result)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<MailView>) -> MFMailComposeViewController {
let vc = MFMailComposeViewController()
vc.setToRecipients(["[email protected]"])
vc.setSubject(NSLocalizedString("PiPifier iOS Feedback",comment: "pipifierFeedBackMailHeader"))
vc.setMessageBody(NSLocalizedString("Hi, \n I have some feedback for PiPifier.",comment: "pipifierFeedBackMailContetn"), isHTML: false)
vc.mailComposeDelegate = context.coordinator
return vc
}
func updateUIViewController(_ uiViewController: MFMailComposeViewController,
context: UIViewControllerRepresentableContext<MailView>) {
}
}
|
mit
|
7280d428cc0a1ceed8e4fa6141bfab53
| 32.4 | 143 | 0.625749 | 5.551247 | false | false | false | false |
CatchChat/Yep
|
Yep/ViewControllers/Conversation/ConversationViewController+PhotosViewControllerDelegate.swift
|
1
|
1510
|
//
// ConversationViewController+PhotosViewControllerDelegate.swift
// Yep
//
// Created by NIX on 16/6/28.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepPreview
extension ConversationViewController: PhotosViewControllerDelegate {
func photosViewController(vc: PhotosViewController, referenceViewForPhoto photo: Photo) -> UIView? {
println("photosViewController:referenceViewForPhoto:\(photo)")
if let previewAttachmentPhoto = photo as? PreviewAttachmentPhoto {
if let index = previewAttachmentPhotos.indexOf(previewAttachmentPhoto) {
return previewTransitionViews?[index]
}
} else if let previewMessagePhoto = photo as? PreviewMessagePhoto {
if let index = previewMessagePhotos.indexOf(previewMessagePhoto) {
return previewTransitionViews?[index]
}
}
return nil
}
func photosViewController(vc: PhotosViewController, didNavigateToPhoto photo: Photo, atIndex index: Int) {
println("photosViewController:didNavigateToPhoto:\(photo):atIndex:\(index)")
}
func photosViewControllerWillDismiss(vc: PhotosViewController) {
println("photosViewControllerWillDismiss")
}
func photosViewControllerDidDismiss(vc: PhotosViewController) {
println("photosViewControllerDidDismiss")
previewTransitionViews = nil
previewAttachmentPhotos = []
previewMessagePhotos = []
}
}
|
mit
|
d24fd2134e04e36fa4ea9c840016deeb
| 28.54902 | 110 | 0.70073 | 5.440433 | false | false | false | false |
hollance/swift-algorithm-club
|
Select Minimum Maximum/SelectMinimumMaximum.playground/Contents.swift
|
3
|
1686
|
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
// Compare each item to find minimum
func minimum<T: Comparable>(_ array: [T]) -> T? {
guard var minimum = array.first else {
return nil
}
for element in array.dropFirst() {
minimum = element < minimum ? element : minimum
}
return minimum
}
// Compare each item to find maximum
func maximum<T: Comparable>(_ array: [T]) -> T? {
guard var maximum = array.first else {
return nil
}
for element in array.dropFirst() {
maximum = element > maximum ? element : maximum
}
return maximum
}
// Compare in pairs to find minimum and maximum
func minimumMaximum<T: Comparable>(_ array: [T]) -> (minimum: T, maximum: T)? {
guard !array.isEmpty else {
return nil
}
var minimum = array.first!
var maximum = array.first!
// if 'array' has an odd number of items, let 'minimum' or 'maximum' deal with the leftover
let start = array.count % 2 // 1 if odd, skipping the first element
for i in stride(from: start, to: array.count, by: 2) {
let pair = (array[i], array[i+1])
if pair.0 > pair.1 {
if pair.0 > maximum {
maximum = pair.0
}
if pair.1 < minimum {
minimum = pair.1
}
} else {
if pair.1 > maximum {
maximum = pair.1
}
if pair.0 < minimum {
minimum = pair.0
}
}
}
return (minimum, maximum)
}
// Test of minimum and maximum functions
let array = [ 8, 3, 9, 4, 6 ]
minimum(array)
maximum(array)
// Test of minimumMaximum function
let result = minimumMaximum(array)!
result.minimum
result.maximum
// Built-in Swift functions
array.min()
array.max()
|
mit
|
94cc9c08be85c2897eb9d7f0543824b5
| 21.184211 | 93 | 0.62159 | 3.534591 | false | false | false | false |
material-components/material-components-ios
|
components/PageControl/examples/PageControlTypicalUseExample.swift
|
2
|
4714
|
// Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import MaterialComponents.MaterialPageControl
class PageControlSwiftExampleViewController: UIViewController, UIScrollViewDelegate {
static let pageColors = [
UIColor(white: 0.3, alpha: 1),
UIColor(white: 0.2, alpha: 1),
UIColor(white: 0.3, alpha: 1),
UIColor(white: 0.2, alpha: 1),
UIColor(white: 0.3, alpha: 1),
UIColor(white: 0.2, alpha: 1),
]
let pageControl: MDCPageControl = {
let pageControl = MDCPageControl()
pageControl.currentPageIndicatorTintColor = .white
pageControl.pageIndicatorTintColor = .lightGray
return pageControl
}()
let scrollView = UIScrollView()
let pageLabels: [UILabel] = PageControlSwiftExampleViewController.pageColors.enumerated().map {
enumeration in
let (i, pageColor) = enumeration
let pageLabel = UILabel()
pageLabel.text = "Page \(i + 1)"
pageLabel.font = pageLabel.font.withSize(50)
pageLabel.textColor = UIColor(white: 1, alpha: 0.8)
pageLabel.backgroundColor = pageColor
pageLabel.textAlignment = NSTextAlignment.center
pageLabel.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
return pageLabel
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
scrollView.frame = self.view.bounds
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
scrollView.delegate = self
scrollView.isPagingEnabled = true
scrollView.contentSize = CGSize(
width: view.bounds.width * CGFloat(pageLabels.count),
height: view.bounds.height)
scrollView.showsHorizontalScrollIndicator = false
view.addSubview(scrollView)
// Add pages to scrollView.
for (i, pageLabel) in pageLabels.enumerated() {
let pageFrame = view.bounds.offsetBy(dx: CGFloat(i) * view.bounds.width, dy: 0)
pageLabel.frame = pageFrame
scrollView.addSubview(pageLabel)
}
pageControl.numberOfPages = pageLabels.count
pageControl.addTarget(self, action: #selector(didChangePage), for: .valueChanged)
pageControl.autoresizingMask = [.flexibleTopMargin, .flexibleWidth]
view.addSubview(pageControl)
}
// MARK: - Frame changes
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let pageBeforeFrameChange = pageControl.currentPage
for (i, pageLabel) in pageLabels.enumerated() {
pageLabel.frame = view.bounds.offsetBy(dx: CGFloat(i) * view.bounds.width, dy: 0)
}
scrollView.contentSize = CGSize(
width: view.bounds.width * CGFloat(pageLabels.count),
height: view.bounds.height)
var offset = scrollView.contentOffset
offset.x = CGFloat(pageBeforeFrameChange) * view.bounds.width
// This non-anmiated change of offset ensures we keep the same page
scrollView.contentOffset = offset
var edgeInsets = UIEdgeInsets.zero
edgeInsets = self.view.safeAreaInsets
let pageControlSize = pageControl.sizeThatFits(view.bounds.size)
let yOffset = self.view.bounds.height - pageControlSize.height - 8 - edgeInsets.bottom
pageControl.frame =
CGRect(x: 0, y: yOffset, width: view.bounds.width, height: pageControlSize.height)
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.scrollViewDidScroll(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
pageControl.scrollViewDidEndDecelerating(scrollView)
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
pageControl.scrollViewDidEndScrollingAnimation(scrollView)
}
// MARK: - User events
@objc func didChangePage(_ sender: MDCPageControl) {
var offset = scrollView.contentOffset
offset.x = CGFloat(sender.currentPage) * scrollView.bounds.size.width
scrollView.setContentOffset(offset, animated: true)
}
// MARK: - CatalogByConvention
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["Page Control", "Swift example"],
"primaryDemo": false,
"presentable": false,
]
}
}
|
apache-2.0
|
448795b8c1bf36c5d32da002b2d52915
| 34.443609 | 97 | 0.726983 | 4.590068 | false | false | false | false |
material-components/material-components-ios
|
components/AppBar/examples/AppBarModalPresentationExample.swift
|
2
|
5694
|
// Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import MaterialComponents.MaterialAppBar
import MaterialComponents.MaterialAppBar_Theming
import MaterialComponents.MaterialContainerScheme
class AppBarModalPresentationSwiftExamplePresented: UITableViewController {
let appBarViewController = MDCAppBarViewController()
@objc var containerScheme: MDCContainerScheming = MDCContainerScheme()
deinit {
// Required for pre-iOS 11 devices because we've enabled observesTrackingScrollViewScrollEvents.
appBarViewController.headerView.trackingScrollView = nil
}
init() {
super.init(nibName: nil, bundle: nil)
self.title = "Modal Presentation (Swift)"
// Behavioral flags.
appBarViewController.inferTopSafeAreaInsetFromViewController = true
appBarViewController.headerView.minMaxHeightIncludesSafeArea = false
self.addChild(appBarViewController)
self.modalPresentationStyle = .formSheet
self.modalTransitionStyle = .coverVertical
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
appBarViewController.applyPrimaryTheme(withScheme: containerScheme)
// Allows us to avoid forwarding events, but means we can't enable shift behaviors.
appBarViewController.headerView.observesTrackingScrollViewScrollEvents = true
appBarViewController.headerView.trackingScrollView = self.tableView
view.addSubview(appBarViewController.view)
appBarViewController.didMove(toParent: self)
self.navigationItem.rightBarButtonItem =
UIBarButtonItem(title: "Touch", style: .done, target: nil, action: nil)
self.navigationItem.leftBarButtonItem =
UIBarButtonItem(title: "Dismiss", style: .done, target: self, action: #selector(dismissSelf))
}
override var childForStatusBarHidden: UIViewController? {
return appBarViewController
}
override var childForStatusBarStyle: UIViewController? {
return appBarViewController
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell =
self.tableView.dequeueReusableCell(withIdentifier: "cell")
?? UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.layoutMargins = .zero
return cell
}
@objc func dismissSelf() {
self.dismiss(animated: true, completion: nil)
}
}
class AppBarModalPresentationSwiftExample: UITableViewController {
let appBarViewController = MDCAppBarViewController()
@objc var containerScheme: MDCContainerScheming = MDCContainerScheme()
init() {
super.init(nibName: nil, bundle: nil)
self.title = "Modal Presentation (Swift)"
self.addChild(appBarViewController)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
appBarViewController.applyPrimaryTheme(withScheme: containerScheme)
appBarViewController.headerView.trackingScrollView = self.tableView
self.tableView.delegate = appBarViewController
view.addSubview(appBarViewController.view)
appBarViewController.didMove(toParent: self)
self.navigationItem.rightBarButtonItem =
UIBarButtonItem(title: "Detail", style: .done, target: self, action: #selector(presentModal))
}
override var childForStatusBarHidden: UIViewController? {
return appBarViewController
}
override var childForStatusBarStyle: UIViewController? {
return appBarViewController
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
@objc func presentModal() {
let modalVC = AppBarModalPresentationSwiftExamplePresented()
self.present(modalVC, animated: true, completion: nil)
}
}
// MARK: Catalog by convention
extension AppBarModalPresentationSwiftExample {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["App Bar", "Modal Presentation (Swift)"],
"primaryDemo": false,
"presentable": false,
]
}
@objc func catalogShouldHideNavigation() -> Bool {
return true
}
}
// MARK: - Typical application code (not Material-specific)
// MARK: UITableViewDataSource
extension AppBarModalPresentationSwiftExample {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell =
self.tableView.dequeueReusableCell(withIdentifier: "cell")
?? UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.layoutMargins = .zero
return cell
}
}
|
apache-2.0
|
d35ff17c0c9727ad0f4d6895c0f99fd7
| 28.65625 | 100 | 0.749737 | 5.134355 | false | false | false | false |
debugsquad/nubecero
|
nubecero/View/AdminUsersPhotos/VAdminUsersPhotos.swift
|
1
|
6062
|
import UIKit
class VAdminUsersPhotos:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private weak var controller:CAdminUsersPhotos!
private weak var collectionView:UICollectionView!
private weak var spinner:VSpinner!
private var imageSize:CGSize!
private let kCollectionBottom:CGFloat = 20
private let kInterLine:CGFloat = 1
private let kImageMaxSize:CGFloat = 150
private let kHeaderHeight:CGFloat = 60
convenience init(controller:CAdminUsersPhotos)
{
self.init()
clipsToBounds = true
backgroundColor = UIColor.background
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let barHeight:CGFloat = controller.parentController.viewParent.kBarHeight
let spinner:VSpinner = VSpinner()
self.spinner = spinner
let flow:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
flow.headerReferenceSize = CGSize(width:0, height:kHeaderHeight)
flow.footerReferenceSize = CGSize.zero
flow.minimumLineSpacing = kInterLine
flow.minimumInteritemSpacing = 0
flow.scrollDirection = UICollectionViewScrollDirection.vertical
flow.sectionInset = UIEdgeInsets(top:kInterLine, left:0, bottom:kCollectionBottom, right:0)
let collectionView:UICollectionView = UICollectionView(frame:CGRect.zero, collectionViewLayout:flow)
collectionView.clipsToBounds = true
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = UIColor.clear
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.alwaysBounceVertical = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(
VAdminUsersPhotosHeader.self,
forSupplementaryViewOfKind:
UICollectionElementKindSectionHeader,
withReuseIdentifier:
VAdminUsersPhotosHeader.reusableIdentifier)
collectionView.register(
VAdminUsersPhotosCell.self,
forCellWithReuseIdentifier:
VAdminUsersPhotosCell.reusableIdentifier)
self.collectionView = collectionView
addSubview(spinner)
addSubview(collectionView)
let views:[String:UIView] = [
"spinner":spinner,
"collectionView":collectionView]
let metrics:[String:CGFloat] = [
"barHeight":barHeight]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[spinner]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-(barHeight)-[spinner]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[collectionView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-(barHeight)-[collectionView]-0-|",
options:[],
metrics:metrics,
views:views))
}
override func layoutSubviews()
{
computeImageSize()
collectionView.collectionViewLayout.invalidateLayout()
super.layoutSubviews()
}
//MARK: private
private func computeImageSize()
{
let width:CGFloat = bounds.maxX - kInterLine
let proximate:CGFloat = floor(width / kImageMaxSize)
let size:CGFloat = (width / proximate) - kInterLine
imageSize = CGSize(width:size, height:size)
}
private func modelAtIndex(index:IndexPath) -> MAdminUsersPhotosItem
{
let item:MAdminUsersPhotosItem = controller.photos!.items[index.item]
return item
}
//MARK: public
func loadingError()
{
spinner.removeFromSuperview()
}
func loadingFinished()
{
spinner.removeFromSuperview()
collectionView.reloadData()
}
//MARK: collectionView delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
return imageSize
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
guard
let _:MAdminUsersPhotos = controller.photos
else
{
return 0
}
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let count:Int = controller.photos!.items.count
return count
}
func collectionView(_ collectionView:UICollectionView, viewForSupplementaryElementOfKind kind:String, at indexPath:IndexPath) -> UICollectionReusableView
{
let reusable:VAdminUsersPhotosHeader = collectionView.dequeueReusableSupplementaryView(
ofKind:kind,
withReuseIdentifier:
VAdminUsersPhotosHeader.reusableIdentifier,
for:indexPath) as! VAdminUsersPhotosHeader
reusable.config(controller:controller)
return reusable
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MAdminUsersPhotosItem = modelAtIndex(index:indexPath)
let cell:VAdminUsersPhotosCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
VAdminUsersPhotosCell.reusableIdentifier,
for:indexPath) as! VAdminUsersPhotosCell
cell.config(model:item)
return cell
}
}
|
mit
|
47da701de7edc6bf88a149b4513e92b2
| 33.248588 | 157 | 0.655724 | 6.185714 | false | false | false | false |
Pencroff/ai-hackathon-2017
|
IOS APP/Pods/Cloudinary/Cloudinary/Features/ManagementApi/Results/CLDSpriteResult.swift
|
1
|
3436
|
//
// CLDSpriteResult.swift
//
// Copyright (c) 2016 Cloudinary (http://cloudinary.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
@objc open class CLDSpriteResult: CLDBaseResult {
// MARK: - Getters
open var cssUrl: String? {
return getParam(.cssUrl) as? String
}
open var secureCssUrl: String? {
return getParam(.secureCssUrl) as? String
}
open var imageUrl: String? {
return getParam(.imageUrl) as? String
}
open var jsonUrl: String? {
return getParam(.jsonUrl) as? String
}
open var publicId: String? {
return getParam(.publicId) as? String
}
open var version: String? {
guard let version = getParam(.version) else {
return nil
}
return String(describing: version)
}
open var imageInfos: [String : CLDImageInfo]? {
guard let imageInfosDic = getParam(.imageInfos) as? [String : AnyObject] else {
return nil
}
var imageInfos: [String : CLDImageInfo] = [:]
for key in imageInfosDic.keys {
if let imgInfo = imageInfosDic[key] as? [String : AnyObject] {
imageInfos[key] = CLDImageInfo(json: imgInfo)
}
}
return imageInfos
}
// MARK: - Private Helpers
fileprivate func getParam(_ param: SpriteResultKey) -> AnyObject? {
return resultJson[String(describing: param)]
}
fileprivate enum SpriteResultKey: CustomStringConvertible {
case cssUrl, secureCssUrl, imageUrl, jsonUrl, imageInfos
var description: String {
switch self {
case .cssUrl: return "css_url"
case .secureCssUrl: return "secure_css_url"
case .imageUrl: return "image_url"
case .jsonUrl: return "json_url"
case .imageInfos: return "image_infos"
}
}
}
}
@objc open class CLDImageInfo: CLDBaseResult {
open var x: Int? {
return getParam(.x) as? Int
}
open var y: Int? {
return getParam(.y) as? Int
}
open var width: Int? {
return getParam(.width) as? Int
}
open var height: Int? {
return getParam(.height) as? Int
}
}
|
mit
|
001bff97c630a8cedf9658ca22378ab2
| 29.678571 | 87 | 0.61525 | 4.427835 | false | false | false | false |
banxi1988/BXAppKit
|
BXForm/Cells/VerticalLabelTextCell.swift
|
1
|
2734
|
//
// VerticalLabelTextCell.swift
// BXForm
//
// Created by Haizhen Lee on 09/10/2017.
// Copyright © 2017 banxi1988. All rights reserved.
//
import Foundation
import UIKit
import BXModel
import SwiftyJSON
import BXiOSUtils
//LabelTextCell:stc
public final class VerticalLabelTextCell : StaticTableViewCell, LeadingLabelRow, TextFieldCellAware{
public let labelLabel = UILabel(frame:.zero)
public let inputTextField = UITextField(frame:.zero)
public var textField:UITextField{
return inputTextField
}
public convenience init() {
self.init(style: .default, reuseIdentifier: "VerticalLabelTextCell")
}
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
public func bind(label:String,text:String){
labelLabel.text = label
inputTextField.text = text
}
public func bind(label:String,placeholder:String){
labelLabel.text = label
inputTextField.placeholder = placeholder
}
public override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var allOutlets :[UIView]{
return [labelLabel,inputTextField]
}
var allUILabelOutlets :[UILabel]{
return [labelLabel]
}
var allUITextFieldOutlets :[UITextField]{
return [inputTextField]
}
func commonInit(){
for childView in allOutlets{
contentView.addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
public var labelWidth: CGFloat = -1
public var paddingLeft:CGFloat = FormMetrics.cellPaddingLeft{
didSet{
paddingLeftConstraint?.constant = paddingLeft
}
}
public var paddingRight:CGFloat = FormMetrics.cellPaddingRight{
didSet{
paddingRightConstraint?.constant = paddingRight
}
}
public var paddingLeftConstraint:NSLayoutConstraint?
public var labelWidthConstraint:NSLayoutConstraint? = nil
fileprivate var paddingRightConstraint:NSLayoutConstraint?
func installConstaints(){
labelLabel.pa_top.eq(8).install()
paddingLeftConstraint = labelLabel.pa_leadingMargin.eq(paddingLeft).install()
inputTextField.pa_leading.eqTo(labelLabel).install()
inputTextField.pa_below(labelLabel, offset: 4).install()
inputTextField.pa_height.gte(32).install()
paddingRightConstraint = inputTextField.pa_trailingMargin.eq(paddingRight).install()
inputTextField.pa_bottom.eq(8).install()
}
func setupAttrs(){
setupLeadingLabel()
labelLabel.textAlignment = .left
inputTextField.textAlignment = .left
}
}
|
mit
|
d70f8d3dd2adaba13a1d06d287c97ba1
| 22.560345 | 100 | 0.732162 | 4.616554 | false | false | false | false |
thomas-mcdonald/SoundTop
|
SoundTop/STInfoTextField.swift
|
1
|
2135
|
// STInfoTextField.swift
//
// Copyright (c) 2015 Thomas McDonald
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. 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. Neither the name of the nor the names of
// its contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import Cocoa
class STInfoTextField: NSTextField {
override init(frame: NSRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
// init() {
// super.init(coder: NSCoder.init())
// setup()
// }
func setup() {
self.alignment = NSTextAlignment.Center
self.backgroundColor = NSColor(red: 0, green: 0, blue: 0, alpha: 0)
self.bordered = false
self.selectable = false
self.translatesAutoresizingMaskIntoConstraints = false
}
}
|
bsd-3-clause
|
2f634718637a405d14c568252df1dfb7
| 39.283019 | 78 | 0.72459 | 4.671772 | false | false | false | false |
Mazy-ma/DemoBySwift
|
Solive/Solive/Tools/Protocol/Emitterable.swift
|
1
|
1892
|
//
// Emitterable.swift
// Solive
//
// Created by Mazy on 2017/9/5.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
protocol Emitterable {
}
extension Emitterable where Self : UIViewController {
func startEmittering(_ point: CGPoint) {
// 1 创建发射器
let emitter = CAEmitterLayer()
// 2 设置发射器的位置
emitter.emitterPosition = point
// 3 开启三维效果
emitter.preservesDepth = true
// 4 创建粒子,并设置其属性
var cells = [CAEmitterCell]()
for i in 0..<10 {
// 4.1 创建 cell
let cell = CAEmitterCell()
// 4.2 设置粒子速度
cell.velocity = 150
cell.velocityRange = 100
// 4.3 设置 粒子的比例大小
cell.scale = 0.7
cell.scaleRange = 0.3
// 4.4 设置粒子的方向
cell.emissionLongitude = CGFloat(-(Double.pi/2))
cell.emissionRange = CGFloat(Double.pi/6)
// 4.5 设置粒子的存活时间
cell.lifetime = 3
cell.lifetimeRange = 1.5
// 4.6 设置粒子旋转
cell.spin = CGFloat(Double.pi/2)
cell.scaleRange = CGFloat(Double.pi/4)
// 4.7 设置粒子每秒弹出的个数
cell.birthRate = 2
// 4.8 设置离子的图片
cell.contents = UIImage(named: "good\(i)_30x30")?.cgImage
// 4.9 添加到数组中
cells.append(cell)
}
// 5 讲粒子添加到发射器
emitter.emitterCells = cells
// 6 讲发射器的 layer 添加到父 layer
view.layer.addSublayer(emitter)
}
func stopEmittering() {
view.layer.sublayers?.filter({ $0.isKind(of: CAEmitterLayer.self) }).first?.removeFromSuperlayer()
}
}
|
apache-2.0
|
53149d221722e0a2f666831dc0c32217
| 26.783333 | 106 | 0.534493 | 3.841014 | false | false | false | false |
XavierDK/Coordinator
|
Pods/Action/Sources/Action/Action.swift
|
1
|
4841
|
import Foundation
import RxSwift
import RxCocoa
/// Typealias for compatibility with UIButton's rx.action property.
public typealias CocoaAction = Action<Void, Void>
/// Typealias for actions with work factory returns `Completable`.
public typealias CompletableAction<Input> = Action<Input, Never>
/// Possible errors from invoking execute()
public enum ActionError: Error {
case notEnabled
case underlyingError(Error)
}
/**
Represents a value that accepts a workFactory which takes some Observable<Input> as its input
and produces an Observable<Element> as its output.
When this excuted via execute() or inputs subject, it passes its parameter to this closure and subscribes to the work.
*/
public final class Action<Input, Element> {
public typealias WorkFactory = (Input) -> Observable<Element>
public let _enabledIf: Observable<Bool>
public let workFactory: WorkFactory
/// Inputs that triggers execution of action.
/// This subject also includes inputs as aguments of execute().
/// All inputs are always appear in this subject even if the action is not enabled.
/// Thus, inputs count equals elements count + errors count.
public let inputs = InputSubject<Input>()
/// Errors aggrevated from invocations of execute().
/// Delivered on whatever scheduler they were sent from.
public let errors: Observable<ActionError>
/// Whether or not we're currently executing.
/// Delivered on whatever scheduler they were sent from.
public let elements: Observable<Element>
/// Whether or not we're currently executing.
public let executing: Observable<Bool>
/// Observables returned by the workFactory.
/// Useful for sending results back from work being completed
/// e.g. response from a network call.
public let executionObservables: Observable<Observable<Element>>
/// Whether or not we're enabled. Note that this is a *computed* sequence
/// property based on enabledIf initializer and if we're currently executing.
/// Always observed on MainScheduler.
public let enabled: Observable<Bool>
private let disposeBag = DisposeBag()
public convenience init<O: ObservableConvertibleType>(
enabledIf: Observable<Bool> = Observable.just(true),
workFactory: @escaping (Input) -> O
) where O.E == Element {
self.init(enabledIf: enabledIf) {
workFactory($0).asObservable()
}
}
public init(
enabledIf: Observable<Bool> = Observable.just(true),
workFactory: @escaping WorkFactory) {
self._enabledIf = enabledIf
self.workFactory = workFactory
let enabledSubject = BehaviorSubject<Bool>(value: false)
enabled = enabledSubject.asObservable()
let errorsSubject = PublishSubject<ActionError>()
errors = errorsSubject.asObservable()
executionObservables = inputs
.withLatestFrom(enabled) { input, enabled in (input, enabled) }
.flatMap { input, enabled -> Observable<Observable<Element>> in
if enabled {
return Observable.of(workFactory(input)
.do(onError: { errorsSubject.onNext(.underlyingError($0)) })
.share(replay: 1, scope: .forever))
} else {
errorsSubject.onNext(.notEnabled)
return Observable.empty()
}
}
.share()
elements = executionObservables
.flatMap { $0.catchError { _ in Observable.empty() } }
executing = executionObservables.flatMap {
execution -> Observable<Bool> in
let execution = execution
.flatMap { _ in Observable<Bool>.empty() }
.catchError { _ in Observable.empty()}
return Observable.concat([Observable.just(true),
execution,
Observable.just(false)])
}
.startWith(false)
.share(replay: 1, scope: .forever)
Observable
.combineLatest(executing, enabledIf) { !$0 && $1 }
.bind(to: enabledSubject)
.disposed(by: disposeBag)
}
@discardableResult
public func execute(_ value: Input) -> Observable<Element> {
defer {
inputs.onNext(value)
}
let subject = ReplaySubject<Element>.createUnbounded()
let work = executionObservables
.map { $0.catchError { throw ActionError.underlyingError($0) } }
let error = errors
.map { Observable<Element>.error($0) }
work.amb(error)
.take(1)
.flatMap { $0 }
.subscribe(subject)
.disposed(by: disposeBag)
return subject.asObservable()
}
}
|
mit
|
4de487c200afb48ccd25389d1a669413
| 34.335766 | 118 | 0.630861 | 4.960041 | false | false | false | false |
kaideyi/KDYSample
|
KYPlayer/KYPlayer/KYPlayer/KYPlayerSpeedView.swift
|
1
|
3268
|
//
// KYPlayerSpeedView.swift
// KYPlayer
//
// Created by mac on 2017/5/8.
// Copyright © 2017年 mac. All rights reserved.
//
import UIKit
/// 快进视图
class KYPlayerSpeedView: UIView {
// MARK: - Properties
lazy var timeLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .right
label.textColor = .white
label.text = "00:00"
return label
}()
lazy var totalTimeLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .left
label.textColor = .white
label.text = "00:00"
return label
}()
lazy var label: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .center
label.textColor = .white
label.text = "/"
label.sizeToFit()
return label
}()
lazy var speedImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "fast_forward")
return imageView
}()
lazy var snapshotImage: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.isHidden = true
return imageView
}()
lazy var progressView: UIProgressView = {
let progress = UIProgressView()
progress.progressTintColor = .red
return progress
}()
var isFullScreen: Bool = false
// MARK: - Life Cycle
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews() {
self.addSubview(speedImageView)
self.addSubview(label)
self.addSubview(timeLabel)
self.addSubview(totalTimeLabel)
self.addSubview(progressView)
self.addSubview(snapshotImage)
speedImageView.snp.makeConstraints { (make) in
make.top.equalTo(self).offset(5)
make.centerX.equalTo(self)
make.size.equalTo(CGSize(width: 30, height: 30))
}
label.snp.makeConstraints { (make) in
make.top.equalTo(speedImageView.snp.bottom)
make.centerX.equalTo(self)
}
timeLabel.snp.makeConstraints { (make) in
make.right.equalTo(label.snp.left).offset(-2)
make.centerY.equalTo(label)
}
totalTimeLabel.snp.makeConstraints { (make) in
make.left.equalTo(label.snp.right).offset(2)
make.centerY.equalTo(label)
}
progressView.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.left.right.bottom.equalTo(self).inset(UIEdgeInsetsMake(0, 10, 10, 10))
}
snapshotImage.snp.makeConstraints { (make) in
make.top.equalTo(label.snp.bottom).offset(5)
make.left.right.bottom.equalTo(self).inset(UIEdgeInsets.zero)
}
}
}
|
mit
|
deb776d17abf5d851d7bd19b89d3eb99
| 25.696721 | 87 | 0.56985 | 4.574438 | false | false | false | false |
box/box-ios-sdk
|
Sources/Modules/FilesModule+RetentionPolicy.swift
|
1
|
3662
|
//
// RetentionPolicy+File.swift
// BoxSDK-iOS
//
// Created by Martina Stremenova on 01/09/2019.
// Copyright © 2019 box. All rights reserved.
//
import Foundation
/// Handles retention policy management for file versions. A retention policy blocks permanent deletion of content for a specified amount of time.
/// Admins can apply policies to specified folders, or an entire enterprise. A file version retention is a record for a retained file version.
/// To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console.
/// For more information about retention policies, please visit our [help documentation.] (https://community.box.com/t5/For-Admins/Retention-Policies-In-Box/ta-p/1095)
public extension FilesModule {
/// Retrieves information about a file version retention policy.
///
/// - Parameters:
/// - id: Identifier of retention policy of a file version.
/// - completion: Either specified file version retention will be returned upon success or an error.
func getVersionRetention(
retentionId id: String,
completion: @escaping Callback<FileVersionRetention>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/file_version_retentions/\(id)", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Retrieves all file version retentions for the given enterprise.
///
/// - Parameters:
/// - fileId: A file id to filter the file version retentions by.
/// - fileVersionId: A file version id to filter the file version retentions by.
/// - policyId: A policy id to filter the file version retentions by.
/// - dispositionAction: The disposition action of the retention policy.
/// - dispositionBefore: Filter retentions with disposition date before provided date.
/// - dispositionAfter: Filter retentions with disposition date after provided date.
/// - limit: The maximum number of items to return in a page.
/// - marker: The position marker at which to begin the response. See [marker-based paging]
/// (https://developer.box.com/reference#section-marker-based-paging) for details.
/// - Returns: Returns either the list of all file version retentions for the enterprise or an error.
/// If optional parameters are given, only the file version retentions that match the query parameters are returned.
@available(*, deprecated, message: "Please use RetentionPoliciesModule#listFilesUnderRetentionForAssignment(retentionPolicyAssignmentId:limit:marker) instead.")
func listVersionRetentions(
fileId: String? = nil,
fileVersionId: String? = nil,
policyId: String? = nil,
dispositionAction: DispositionAction? = nil,
dispositionBefore: Date? = nil,
dispositionAfter: Date? = nil,
limit: Int? = nil,
marker: String? = nil
) -> PagingIterator<FileVersionRetention> {
.init(
client: boxClient,
url: URL.boxAPIEndpoint("/2.0/file_version_retentions", configuration: boxClient.configuration),
queryParameters: [
"file_id": fileId,
"file_version_id": fileVersionId,
"policy_id": policyId,
"disposition_action": dispositionAction?.description,
"disposition_before": dispositionBefore?.iso8601,
"disposition_after": dispositionAfter?.iso8601,
"marker": marker,
"limit": limit
]
)
}
}
|
apache-2.0
|
fad7297737f815efe069b13bf6f5c0aa
| 49.847222 | 167 | 0.675772 | 4.628319 | false | true | false | false |
lieonCX/Live
|
Live/View/User/Setting/VerifyPhoneViewController.swift
|
1
|
8432
|
//
// VerifyPhoneViewController.swift
// Live
//
// Created by fanfans on 2017/7/13.
// Copyright © 2017年 ChengDuHuanLeHui. All rights reserved.
//
import UIKit
import RxSwift
class VerifyPhoneViewController: BaseViewController {
var phoneNum: String?
fileprivate lazy var tipsLable: UILabel = {
let tipsLable = UILabel()
tipsLable.text = "已绑定的手机号18380225528"
tipsLable.font = UIFont.systemFont(ofSize: 13)
tipsLable.textAlignment = .left
tipsLable.textColor = UIColor(hex: 0x999999)
return tipsLable
}()
fileprivate lazy var pwdTF: UITextField = {
let pwdTF = UITextField()
pwdTF.placeholder = "请输入短信验证码"
pwdTF.textColor = UIColor(hex:0x333333)
pwdTF.font = UIFont.sizeToFit(with: 13)
pwdTF.tintColor = UIColor(hex: CustomKey.Color.mainColor)
pwdTF.returnKeyType = .done
return pwdTF
}()
fileprivate lazy var pwdLog: UIImageView = {
let pwdLog = UIImageView(image: UIImage(named: "user_center_captch"))
pwdLog.contentMode = .center
return pwdLog
}()
fileprivate lazy var line0: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hex: 0xe6e6e6)
return view
}()
fileprivate lazy var line1: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hex: 0xe6e6e6)
return view
}()
fileprivate lazy var getVerifiedCodeBtn: UIButton = {
let getVerifiedCodeBtn = UIButton()
getVerifiedCodeBtn.sizeToFit()
getVerifiedCodeBtn.titleLabel?.font = UIFont.sizeToFit(with: 12)
getVerifiedCodeBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
getVerifiedCodeBtn.setTitleColor(UIColor.gray, for: .disabled)
getVerifiedCodeBtn.setTitleColor(UIColor.gray, for: .normal)
return getVerifiedCodeBtn
}()
fileprivate lazy var nextBtn: UIButton = {
let nextBtn = UIButton()
nextBtn.setBackgroundImage(UIImage(named: "loginBtn_normal"), for: .normal)
nextBtn.setBackgroundImage(UIImage(named: "loginBtn_highlighted"), for: .highlighted)
nextBtn.setBackgroundImage(UIImage(named: "loginBtn_highlighted"), for: .disabled)
nextBtn.titleLabel?.font = UIFont.sizeToFit(with: 16)
nextBtn.layer.cornerRadius = 22.5
nextBtn.layer.masksToBounds = true
nextBtn.setTitle("下 一 步", for: .normal)
nextBtn.setTitleColor(UIColor.white, for: .normal)
nextBtn.isEnabled = false
return nextBtn
}()
fileprivate lazy var cannotGetVerifiedCodeLable: UILabel = {
let cannotGetVerifiedCodeLable = UILabel()
cannotGetVerifiedCodeLable.text = "原手机无法获取验证码"
cannotGetVerifiedCodeLable.font = UIFont.systemFont(ofSize: 13)
cannotGetVerifiedCodeLable.textAlignment = .left
cannotGetVerifiedCodeLable.textColor = UIColor(hex: 0x999999)
return cannotGetVerifiedCodeLable
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "已绑定手机号"
self.view.backgroundColor = UIColor.white
tipsLable.text = "已绑定的手机号" + (phoneNum ?? "")
// MARK: congfigUI
self.view.addSubview(tipsLable)
self.view.addSubview(pwdTF)
self.view.addSubview(pwdLog)
self.view.addSubview(line0)
self.view.addSubview(line1)
self.view.addSubview(getVerifiedCodeBtn)
self.view.addSubview(nextBtn)
self.view.addSubview(cannotGetVerifiedCodeLable)
// MARK: layout
tipsLable.snp.makeConstraints { (maker) in
maker.left.equalTo(28)
maker.top.equalTo(40)
}
pwdLog.snp.makeConstraints { (maker) in
maker.left.equalTo(tipsLable.snp.left)
maker.top.equalTo(tipsLable.snp.bottom).offset(25)
maker.width.equalTo(20)
}
getVerifiedCodeBtn.snp.makeConstraints { (maker) in
maker.right.equalTo(-15)
maker.top.equalTo(pwdLog.snp.top).offset(0)
maker.width.equalTo(80)
}
line0.snp.makeConstraints { (maker) in
maker.right.equalTo(getVerifiedCodeBtn.snp.left)
maker.centerY.equalTo(pwdLog.snp.centerY).offset(5)
maker.width.equalTo(1)
maker.height.equalTo(20)
}
pwdTF.snp.makeConstraints { (maker) in
maker.left.equalTo(pwdLog.snp.right).offset(20)
maker.right.equalTo(line0.snp.left).offset(0)
maker.centerY.equalTo(pwdLog.snp.centerY)
maker.height.equalTo(35)
}
line1.snp.makeConstraints { (maker) in
maker.left.equalTo(15)
maker.right.equalTo(-15)
maker.height.equalTo(1)
maker.top.equalTo(pwdLog.snp.bottom).offset(12)
}
nextBtn.snp.makeConstraints { (maker) in
maker.left.equalTo(10)
maker.right.equalTo(-10)
maker.height.equalTo(45)
maker.top.equalTo(line1.snp.bottom).offset(35)
}
cannotGetVerifiedCodeLable.snp.makeConstraints { (maker) in
maker.top.equalTo(nextBtn.snp.bottom) .offset(15)
maker.centerX.equalTo(self.view.snp.centerX)
}
self.getVerifiedCodeBtn.start(withTime: 120, title: "获取验证码", countDownTitle: "S后重发", mainColor: self.view.backgroundColor ?? .red, count: self.view.backgroundColor ?? .red)
// MARK: nextBtnAction
let usernameValid = pwdTF.rx.text.orEmpty
.map { $0.characters.count >= 4 }
.shareReplay(1)
usernameValid
.bind(to: nextBtn.rx.isEnabled)
.disposed(by: disposeBag)
pwdTF.rx.text.orEmpty
.map { (text) -> String in
return text.characters.count <= 4 ? text: text.substring(to: "1560".endIndex)
}
.shareReplay(1)
.bind(to: pwdTF.rx.text)
.disposed(by: disposeBag)
nextBtn.rx.tap
.subscribe(onNext: { [weak self] in
guard let phoneNum = self?.phoneNum, let code = self?.pwdTF.text else { return }
let verfiedVM = UserSessionViewModel()
let param = SmsCaptchaParam()
param.phone = phoneNum
param.type = .changePhoneNum
param.code = code
HUD.show(true, show: "", enableUserActions: false, with: self)
verfiedVM.checkCaptcha(param: param)
.then(execute: { (_) -> Void in
let vcc = ModifyPhoneViewController()
self?.navigationController?.pushViewController(vcc, animated: true)
})
.always {
HUD.show(false, show: "", enableUserActions: false, with: self)
}
.catch(execute: { error in
if let error = error as? AppError {
self?.view.makeToast(error.message)
}
})
})
.disposed(by: disposeBag)
getVerifiedCodeBtn.rx.tap
.subscribe(onNext: { [weak self] in
guard let phoneNum = self?.phoneNum else { return }
let verfiedVM = UserSessionViewModel()
HUD.show(true, show: "", enableUserActions: false, with: self)
verfiedVM.sendCaptcha(phoneNum: phoneNum, type: .changePhoneNum)
.then(execute: { (_) -> Void in
self?.getVerifiedCodeBtn.start(withTime: 120, title: "获取验证码", countDownTitle: "S后重发", mainColor: self?.view.backgroundColor ?? .red, count: self?.view.backgroundColor ?? .red)
})
.always {
HUD.show(false, show: "", enableUserActions: false, with: self)
}
.catch(execute: { error in
if let error = error as? AppError {
self?.view.makeToast(error.message)
}
})
})
.disposed(by: disposeBag)
}
}
|
mit
|
2f9ff178f0f96143edb1558d5a9f2d9c
| 40.163366 | 199 | 0.580878 | 4.33977 | false | false | false | false |
stephentyrone/swift
|
stdlib/public/core/Availability.swift
|
5
|
2033
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Returns 1 if the running OS version is greater than or equal to
/// major.minor.patchVersion and 0 otherwise.
///
/// This is a magic entry point known to the compiler. It is called in
/// generated code for API availability checking.
@_semantics("availability.osversion")
@_effects(readnone)
public func _stdlib_isOSVersionAtLeast(
_ major: Builtin.Word,
_ minor: Builtin.Word,
_ patch: Builtin.Word
) -> Builtin.Int1 {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
if Int(major) == 9999 {
return true._value
}
let runningVersion = _swift_stdlib_operatingSystemVersion()
let result =
(runningVersion.majorVersion,runningVersion.minorVersion,runningVersion.patchVersion)
>= (Int(major),Int(minor),Int(patch))
return result._value
#else
// FIXME: As yet, there is no obvious versioning standard for platforms other
// than Darwin-based OSes, so we just assume false for now.
// rdar://problem/18881232
return false._value
#endif
}
#if os(macOS)
// This is a magic entry point known to the compiler. It is called in
// generated code for API availability checking.
@_semantics("availability.osversion")
@_effects(readnone)
public func _stdlib_isOSVersionAtLeastOrVariantVersionAtLeast(
_ major: Builtin.Word,
_ minor: Builtin.Word,
_ patch: Builtin.Word,
_ variantMajor: Builtin.Word,
_ variantMinor: Builtin.Word,
_ variantPatch: Builtin.Word
) -> Builtin.Int1 {
return _stdlib_isOSVersionAtLeast(major, minor, patch)
}
#endif
|
apache-2.0
|
10b4735bf3994fe47452e5cad087f758
| 32.327869 | 89 | 0.669946 | 4.165984 | false | false | false | false |
harshalrj25/GlowingEffectView
|
Example/GlowingEffectView/ViewController.swift
|
1
|
1968
|
//
// ViewController.swift
// GlowingEffectView
//
// Created by harshalrj25 on 07/11/2017.
// Copyright (c) 2017 harshalrj25. All rights reserved.
//
import UIKit
import GlowingEffectView
class ViewController: UIViewController {
func generateView() {
let viewWidth: Float = Float(view.frame.size.width)
let viewHeight: Float = Float(view.frame.size.height)
var numViews: Int = 0
// change the below number for more than 1 view at a time
while numViews < 1 {
var goodView: Bool = true
let candidateView:GlowingEffectView = GlowingEffectView()
candidateView.frame = CGRect(x: CGFloat(arc4random() % UInt32(viewWidth)), y: CGFloat(arc4random() % UInt32(viewHeight)), width: CGFloat(arc4random_uniform(UInt32(50.0))), height: CGFloat(arc4random_uniform(UInt32(50.0))))
candidateView.radius = CGFloat(arc4random_uniform(UInt32(50.0)))
candidateView.baseColor = UIColor.randomColor()
for placedView: UIView in view.subviews {
if candidateView.frame.insetBy(dx: CGFloat(-10), dy: CGFloat(-10)).intersects(placedView.frame) {
goodView = false
break
}
}
if goodView {
view.addSubview(candidateView)
numViews += 1
}
}
}
@IBAction func addButtonClicked(_ sender: Any) {
self.generateView()
}
}
extension UIColor {
class func randomColor(randomAlpha randomApha:Bool = false)->UIColor{
let redValue = CGFloat(arc4random_uniform(255)) / 255.0;
let greenValue = CGFloat(arc4random_uniform(255)) / 255.0;
let blueValue = CGFloat(arc4random_uniform(255)) / 255.0;
let alphaValue = randomApha ? CGFloat(arc4random_uniform(255)) / 255.0 : 1;
return UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: alphaValue)
}
}
|
mit
|
6452d3d7f0729494ab96db0edbdd5fd0
| 36.132075 | 234 | 0.621951 | 4.032787 | false | false | false | false |
swipe-org/swipe
|
browser/SwipeExporter.swift
|
2
|
9148
|
//
// SwipeExporter.swift
// sample
//
// Created by satoshi on 8/19/16.
// Copyright © 2016 Satoshi Nakajima. All rights reserved.
//
import UIKit
import ImageIO
import MobileCoreServices
import AVFoundation
class SwipeExporter: NSObject {
enum Error: Swift.Error {
case FailedToCreate
case FailedToFinalize
}
let swipeViewController:SwipeViewController
let fps:Int
let resolution:CGFloat
var progress = 0.0 as CGFloat // Output: Proress from 0.0 to 1.0
var outputSize = CGSize.zero // Output: Size of generated GIF/video
var pauseDuration = 0.0 as CGFloat
var transitionDuration = 1.0 as CGFloat
private var iFrame = 0
init(swipeViewController:SwipeViewController, fps:Int, resolution:CGFloat = 720.0) {
self.swipeViewController = swipeViewController
self.fps = fps
self.resolution = resolution
}
func exportAsGifAnimation(_ fileURL:URL, startPage:Int, pageCount:Int, progress:@escaping (_ complete:Bool, _ error:Swift.Error?)->Void) {
guard let idst = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeGIF, pageCount * fps + 1, nil) else {
return progress(false, Error.FailedToCreate)
}
CGImageDestinationSetProperties(idst, [String(kCGImagePropertyGIFDictionary):
[String(kCGImagePropertyGIFLoopCount):0]] as CFDictionary)
iFrame = 0
outputSize = swipeViewController.view.frame.size
self.processFrame(idst, startPage:startPage, pageCount: pageCount, progress:progress)
}
func processFrame(_ idst:CGImageDestination, startPage:Int, pageCount:Int, progress:@escaping (_ complete:Bool, _ error:Swift.Error?)->Void) {
self.progress = CGFloat(iFrame) / CGFloat(fps) / CGFloat(pageCount)
swipeViewController.scrollTo(CGFloat(startPage) + CGFloat(iFrame) / CGFloat(fps))
// HACK: This delay is not 100% reliable, but is sufficient practically.
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
progress(false, nil)
let presentationLayer = self.swipeViewController.view.layer.presentation()!
UIGraphicsBeginImageContext(self.swipeViewController.view.frame.size); defer {
UIGraphicsEndImageContext()
}
presentationLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()!
CGImageDestinationAddImage(idst, image.cgImage!, [String(kCGImagePropertyGIFDictionary):
[String(kCGImagePropertyGIFDelayTime):0.2]] as CFDictionary)
self.iFrame += 1
if self.iFrame < pageCount * self.fps + 1 {
self.processFrame(idst, startPage:startPage, pageCount: pageCount, progress:progress)
} else {
if CGImageDestinationFinalize(idst) {
progress(true, nil)
} else {
progress(false, Error.FailedToFinalize)
}
}
}
}
func exportAsMovie(_ fileURL:URL, startPage:Int, pageCount:Int?, progress:@escaping (_ complete:Bool, _ error:Swift.Error?)->Void) {
// AVAssetWrite will fail if the file already exists
let manager = FileManager.default
if manager.fileExists(atPath: fileURL.path) {
try! manager.removeItem(at: fileURL)
}
let efps = Int(round(CGFloat(fps) * transitionDuration)) // Effective FPS
let extra = Int(round(CGFloat(fps) * pauseDuration))
let limit:Int
if let pageCount = pageCount, startPage + pageCount < swipeViewController.book.pages.count {
limit = pageCount * (efps + extra) + extra + 1
} else {
limit = (swipeViewController.book.pages.count - startPage - 1) * (efps + extra) + extra + 1
}
print("SwipeExporter:exportAsMovie", self.fps, efps, extra, limit)
let viewSize = swipeViewController.view.frame.size
let scale = min(resolution / min(viewSize.width, viewSize.height), swipeViewController.view.contentScaleFactor)
outputSize = CGSize(width: viewSize.width * scale, height: viewSize.height * scale)
self.swipeViewController.scrollTo(CGFloat(startPage))
DispatchQueue.main.async { // HACK: work-around of empty first page bug
do {
let writer = try AVAssetWriter(url: fileURL, fileType: AVFileType.mov)
let input = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: [
AVVideoCodecKey : AVVideoCodecType.h264,
AVVideoWidthKey : self.outputSize.width,
AVVideoHeightKey : self.outputSize.height
])
let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: [
kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32ARGB),
kCVPixelBufferWidthKey as String: self.outputSize.width,
kCVPixelBufferHeightKey as String: self.outputSize.height,
])
writer.add(input)
self.iFrame = 0
guard writer.startWriting() else {
return progress(false, Error.FailedToFinalize)
}
writer.startSession(atSourceTime: CMTimeMake(value:0, timescale:Int32(self.fps)))
//self.swipeViewController.scrollTo(CGFloat(startPage))
input.requestMediaDataWhenReady(on: DispatchQueue.main) {
guard input.isReadyForMoreMediaData else {
print("SwipeExporter:not ready", self.iFrame)
return // Not ready. Just wait.
}
self.progress = 0.5 * CGFloat(self.iFrame) / CGFloat(limit)
progress(false, nil)
var pixelBufferX: CVPixelBuffer? = nil
let status: CVReturn = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, adaptor.pixelBufferPool!, &pixelBufferX)
guard let managedPixelBuffer = pixelBufferX, status == 0 else {
print("failed to allocate pixel buffer")
writer.cancelWriting()
return progress(false, Error.FailedToCreate)
}
CVPixelBufferLockBaseAddress(managedPixelBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
let data = CVPixelBufferGetBaseAddress(managedPixelBuffer)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
if let context = CGContext(data: data, width: Int(self.outputSize.width), height: Int(self.outputSize.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(managedPixelBuffer), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) {
let xf = CGAffineTransform(scaleX: scale, y: -scale)
context.concatenate(xf.translatedBy(x: 0, y: -viewSize.height))
let presentationLayer = self.swipeViewController.view.layer.presentation()!
presentationLayer.render(in: context)
//print("SwipeExporter:render", self.iFrame)
} else {
print("SwipeExporter:failed to get context", self.iFrame, self.fps)
}
CVPixelBufferUnlockBaseAddress(managedPixelBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
let presentationTime = CMTimeMake(value:Int64(self.iFrame), timescale: Int32(self.fps))
if !adaptor.append(managedPixelBuffer, withPresentationTime: presentationTime) {
print("SwipeExporter:failed to append", self.iFrame)
writer.cancelWriting()
return progress(false, Error.FailedToCreate)
}
self.iFrame += 1
if self.iFrame < limit {
let curPage = self.iFrame / (extra + efps)
let offset = self.iFrame % (extra + efps)
if offset == 0 {
self.swipeViewController.scrollTo(CGFloat(startPage + curPage))
} else if offset > extra {
self.swipeViewController.scrollTo(CGFloat(startPage + curPage) + CGFloat(offset - extra) / CGFloat(efps))
}
} else {
input.markAsFinished()
print("SwipeExporter: finishWritingWithCompletionHandler")
writer.finishWriting(completionHandler: {
DispatchQueue.main.async {
progress(true, nil)
}
})
}
}
} catch let error {
progress(false, error)
}
}
}
}
|
mit
|
46fa1c15af2f46f2492c1575be93a14e
| 48.443243 | 293 | 0.603695 | 5.235833 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/Authentication/Interface/Descriptions/ViewDescriptions/EmailPasswordFieldDescription.swift
|
1
|
2407
|
//
// 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 UIKit
final class EmailPasswordFieldDescription: ValueSubmission {
let textField = EmailPasswordTextField()
var forRegistration: Bool
var prefilledEmail: String?
var usePasswordDeferredValidation: Bool
var acceptsInput: Bool = true
var valueSubmitted: ValueSubmitted?
var valueValidated: ValueValidated?
init(forRegistration: Bool, prefilledEmail: String? = nil, usePasswordDeferredValidation: Bool = false) {
self.forRegistration = forRegistration
self.usePasswordDeferredValidation = usePasswordDeferredValidation
}
}
extension EmailPasswordFieldDescription: ViewDescriptor, EmailPasswordTextFieldDelegate {
func create() -> UIView {
textField.passwordField.kind = .password(isNew: forRegistration)
textField.delegate = self
textField.prefill(email: prefilledEmail)
textField.emailField.validateInput()
return textField
}
func textFieldDidUpdateText(_ textField: EmailPasswordTextField) {
// Reset the error message when the user changes the text and we use deferred validation
guard usePasswordDeferredValidation else { return }
valueValidated?(nil)
textField.passwordField.hideGuidanceDot()
}
func textField(_ textField: EmailPasswordTextField, didConfirmCredentials credentials: (String, String)) {
valueSubmitted?(credentials)
}
func textFieldDidSubmitWithValidationError(_ textField: EmailPasswordTextField) {
if let passwordError = textField.passwordValidationError {
textField.passwordField.showGuidanceDot()
valueValidated?(.error(passwordError, showVisualFeedback: true))
}
}
}
|
gpl-3.0
|
e3f16985a4640b5d38ea7e6a524e3c6b
| 36.030769 | 110 | 0.73494 | 4.942505 | false | false | false | false |
honishi/Hakumai
|
Hakumai/Managers/HandleNameManager/HandleNameManager.swift
|
1
|
10682
|
//
// HandleNameManager.swift
// Hakumai
//
// Created by Hiroyuki Onishi on 1/4/15.
// Copyright (c) 2015 Hiroyuki Onishi. All rights reserved.
//
import Foundation
import FMDB
private let handleNamesDatabase = "HandleNames"
private let handleNamesTable = "handle_names"
private let handleNameObsoleteThreshold = TimeInterval(60 * 60 * 24 * 7) // = 1 week
// comment like "@5" (="あと5分")
private let regexpRemainingTime = "[@@][0-90-9]{1,2}$"
private let regexpHandleName = ".*[@@]\\s*(\\S{2,})\\s*"
// handle name manager
final class HandleNameManager {
// MARK: - Properties
static let shared = HandleNameManager()
private var database: FMDatabase!
private var databaseQueue: FMDatabaseQueue!
private let handleNameCacher = DatabaseValueCacher<String>()
private let colorCacher = DatabaseValueCacher<NSColor>()
// MARK: - Object Lifecycle
init() {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
LoggerHelper.createApplicationDirectoryIfNotExists()
database = HandleNameManager.databaseForHandleNames()
databaseQueue = HandleNameManager.databaseQueueForHandleNames()
createHandleNamesTableIfNotExists()
deleteObsoleteRows()
}
}
// MARK: - Public Functions
extension HandleNameManager {
func extractAndUpdateHandleName(from comment: String, for userId: String, in communityId: String) {
guard let handleName = extractHandleName(from: comment) else { return }
setHandleName(name: handleName, for: userId, in: communityId)
}
func setHandleName(name: String, for userId: String, in communityId: String) {
upsert(handleName: name, for: userId, in: communityId)
handleNameCacher.update(value: name, for: userId, in: communityId)
}
func removeHandleName(for userId: String, in communityId: String) {
updateHandleNameToNull(for: userId, in: communityId)
deleteRowIfHasNoData(for: userId, in: communityId)
handleNameCacher.updateValueAsNil(for: userId, in: communityId)
}
func handleName(for userId: String, in communityId: String) -> String? {
let cached = handleNameCacher.cachedValue(for: userId, in: communityId)
switch cached {
case .cached(let handleName):
// log.debug("handleName: cached: \(handleName ?? "nil")")
return handleName
case .notCached:
// log.debug("handleName: not cached")
break
}
let queried = selectHandleName(for: userId, in: communityId)
handleNameCacher.update(value: queried, for: userId, in: communityId)
// log.debug("handleName: update cache: \(queried ?? "nil")")
return queried
}
func setColor(_ color: NSColor, for userId: String, in communityId: String) {
upsert(color: color, for: userId, in: communityId)
colorCacher.update(value: color, for: userId, in: communityId)
}
func removeColor(for userId: String, in communityId: String) {
updateColorToNull(for: userId, in: communityId)
deleteRowIfHasNoData(for: userId, in: communityId)
colorCacher.updateValueAsNil(for: userId, in: communityId)
}
func color(for userId: String, in communityId: String) -> NSColor? {
let cached = colorCacher.cachedValue(for: userId, in: communityId)
switch cached {
case .cached(let color):
// log.debug("color: cached: \(color?.description ?? "nil")")
return color
case .notCached:
// log.debug("color: not cached")
break
}
let queried = selectColor(for: userId, in: communityId)
colorCacher.update(value: queried, for: userId, in: communityId)
// log.debug("color: update cache: \(queried?.description ?? "nil")")
return queried
}
}
// MARK: - Internal Functions
// Making methods internal for tests.
extension HandleNameManager {
func extractHandleName(from comment: String) -> String? {
if comment.hasRegexp(pattern: regexpRemainingTime) {
return nil
}
if comment.hasRegexp(pattern: kRegexpMailAddress) {
return nil
}
return comment.extractRegexp(pattern: regexpHandleName)
}
func upsert(handleName: String, for userId: String, in communityId: String) {
if isRowExisted(for: userId, in: communityId) {
update(column: "handle_name", value: handleName, for: userId, in: communityId)
} else {
insert(handleName: handleName, for: userId, in: communityId)
}
}
func selectHandleName(for userId: String, in communityId: String) -> String? {
return select(column: "handle_name", for: userId, in: communityId)
}
func upsert(color: NSColor, for userId: String, in communityId: String) {
let colorHex = color.hex
guard colorHex.isValidHexString else { return }
if isRowExisted(for: userId, in: communityId) {
update(column: "color", value: colorHex, for: userId, in: communityId)
} else {
insert(colorHex: colorHex, for: userId, in: communityId)
}
}
func selectColor(for userId: String, in communityId: String) -> NSColor? {
let string = select(column: "color", for: userId, in: communityId)
guard let _string = string, _string.isValidHexString else { return nil }
return NSColor(hex: _string)
}
}
// MARK: DDL Functions
private extension HandleNameManager {
func dropHandleNamesTableIfExists() {
let sql = """
drop table if exists \(handleNamesTable)
"""
executeUpdate(sql, args: [])
}
func createHandleNamesTableIfNotExists() {
let sql = """
create table if not exists \(handleNamesTable)
(community_id text, user_id text, handle_name text, anonymous integer,
color text, updated integer,
reserved1 text, reserved2 text, reserved3 text,
primary key (community_id, user_id))
"""
executeUpdate(sql, args: [])
}
}
// MARK: Select + DML Functions
private extension HandleNameManager {
func isRowExisted(for userId: String, in communityId: String) -> Bool {
return select(column: "user_id", for: userId, in: communityId) != nil
}
func select(column: String, for userId: String, in communityId: String) -> String? {
let sql = """
select \(column) from \(handleNamesTable)
where community_id = ? and user_id = ?
"""
return executeQuery(sql, args: [communityId, userId], column: column)
}
func insert(handleName: String, for userId: String, in communityId: String) {
let sql = """
insert into \(handleNamesTable)
values (?, ?, ?, ?, null, strftime('%s', 'now'), null, null, null)
"""
executeUpdate(sql, args: [communityId, userId, handleName, userId.isAnonymous])
}
func insert(colorHex: String, for userId: String, in communityId: String) {
let sql = """
insert into \(handleNamesTable)
values (?, ?, null, ?, ?, strftime('%s', 'now'), null, null, null)
"""
executeUpdate(sql, args: [communityId, userId, userId.isAnonymous, colorHex])
}
func update(column: String, value: Any, for userId: String, in communityId: String) {
let sql = """
update \(handleNamesTable) set \(column) = ?
where community_id = ? and user_id = ?
"""
executeUpdate(sql, args: [value, communityId, userId])
}
func updateHandleNameToNull(for userId: String, in communityId: String) {
_updateColumnToNull(column: "handle_name", for: userId, in: communityId)
}
func updateColorToNull(for userId: String, in communityId: String) {
_updateColumnToNull(column: "color", for: userId, in: communityId)
}
func _updateColumnToNull(column: String, for userId: String, in communityId: String) {
let sql = """
update \(handleNamesTable)
set \(column) = null
where community_id = ? and user_id = ?
"""
executeUpdate(sql, args: [communityId, userId])
}
func deleteRowIfHasNoData(for userId: String, in communityId: String) {
let sql = """
delete from \(handleNamesTable)
where community_id = ? and user_id = ? and
handle_name is null and color is null
"""
executeUpdate(sql, args: [communityId, userId])
}
func deleteObsoleteRows() {
let sql = """
delete from \(handleNamesTable)
where updated < ? and anonymous = 1
"""
let threshold = Date().timeIntervalSince1970 - handleNameObsoleteThreshold
executeUpdate(sql, args: [threshold])
}
}
// MARK: SQL Execution Utility
private extension HandleNameManager {
func executeQuery(_ sql: String, args: [Any], column: String) -> String? {
guard let databaseQueue = databaseQueue else { return nil }
var selected: String?
databaseQueue.inDatabase { database in
// log.debug(sql)
guard let resultSet = database.executeQuery(sql, withArgumentsIn: args) else { return }
while resultSet.next() {
selected = resultSet.string(forColumn: column)
break
}
resultSet.close()
}
return selected
}
func executeUpdate(_ sql: String, args: [Any]) {
guard let databaseQueue = databaseQueue else { return }
databaseQueue.inDatabase { database in
// log.debug(sql)
let success = database.executeUpdate(sql, withArgumentsIn: args)
if !success {
let message = String(describing: database.lastErrorMessage())
log.error("failed to execute update: \(message)")
}
}
}
}
// MARK: Database Instance Utility
private extension HandleNameManager {
static func fullPathForHandleNamesDatabase() -> String {
return LoggerHelper.applicationDirectoryPath() + "/" + handleNamesDatabase
}
static func databaseForHandleNames() -> FMDatabase? {
let database = FMDatabase(path: HandleNameManager.fullPathForHandleNamesDatabase())
guard database.open() else {
log.error("unable to open database")
return nil
}
return database
}
static func databaseQueueForHandleNames() -> FMDatabaseQueue? {
return FMDatabaseQueue(path: HandleNameManager.fullPathForHandleNamesDatabase())
}
}
|
mit
|
93532bd2859848214bb23415230911ab
| 35.786207 | 103 | 0.628328 | 4.263789 | false | false | false | false |
liuxianghong/GreenBaby
|
工程/greenbaby/greenbaby/ViewController/Login/CompleteMaterialTableViewController.swift
|
1
|
9307
|
//
// CompleteMaterialTableViewController.swift
// greenbaby
//
// Created by 刘向宏 on 15/12/3.
// Copyright © 2015年 刘向宏. All rights reserved.
//
import UIKit
class CompleteMaterialModel{
var id : String!
var value : String!
init(){
id = ""
value = ""
}
}
class CompleteMaterialTableViewController: UITableViewController ,CompleteValueTableViewDelegate {
var wxLoginModel = WXLoginModel()
var tableViewArray : NSArray = [["视力信息",CompleteMaterialModel()],["平均每天读写时间(小时)",CompleteMaterialModel()],["年龄(岁)",CompleteMaterialModel()],["省份",CompleteMaterialModel()],["城市",CompleteMaterialModel()]]
var sex = "0"
var currentCompleteMaterialModel : CompleteMaterialModel!
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()
var frame = self.tableView.tableFooterView?.frame
frame?.size.height = 90.0
self.tableView.tableFooterView?.frame = frame!
self.navigationItem.backBarButtonItem = UIBarButtonItem();
self.navigationItem.backBarButtonItem?.title = "返回"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
func didChoice(model: CompleteMaterialModel, index: Int) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func manClicked(sender: UIButton) {
sex = "0"
}
@IBAction func womanClicked(sender: UIButton) {
sex = "1"
}
@IBAction func nextClicked(sender: UIButton) {
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
let eyesight = ((tableViewArray[0] as! NSArray)[1] as! CompleteMaterialModel).id
let averageTime = ((tableViewArray[1] as! NSArray)[1] as! CompleteMaterialModel).id
let age = ((tableViewArray[2] as! NSArray)[1] as! CompleteMaterialModel).id
let provinceId = ((tableViewArray[3] as! NSArray)[1] as! CompleteMaterialModel).id
let cityId = ((tableViewArray[4] as! NSArray)[1] as! CompleteMaterialModel).id
if eyesight.isEmpty{
hud.mode = .Text
hud.detailsLabelText = "请选择视力范围"
hud.hide(true, afterDelay: 1.5)
return;
}
if averageTime.isEmpty{
hud.mode = .Text
hud.detailsLabelText = "请选择用眼时间范围"
hud.hide(true, afterDelay: 1.5)
return;
}
if age.isEmpty{
hud.mode = .Text
hud.detailsLabelText = "请选择年龄范围"
hud.hide(true, afterDelay: 1.5)
return;
}
if provinceId.isEmpty{
hud.mode = .Text
hud.detailsLabelText = "请选择省份"
hud.hide(true, afterDelay: 1.5)
return;
}
if cityId.isEmpty{
hud.mode = .Text
hud.detailsLabelText = "请选择城市"
hud.hide(true, afterDelay: 1.5)
return;
}
let userId = NSUserDefaults.standardUserDefaults().objectForKey("userId")!
let dic :NSDictionary = ["userId": userId,"nickName": wxLoginModel.userName,"headImage": wxLoginModel.iconURL, "eyesight":eyesight,"averageTime": averageTime,"age": age,"sex": sex,"provinceId":provinceId,"cityId": cityId]
LoginRequest.UpdateEndUserWithParameters(dic, success: { (object) -> Void in
let dic:NSDictionary = object as! NSDictionary
let state:Int = dic["state"] as! Int
if state == 0{
hud.hide(true)
self.dismissViewControllerAnimated(true) { () -> Void in
}
}else{
hud.mode = .Text
hud.detailsLabelText = dic["description"] as! String
hud.hide(true, afterDelay: 1.5)
}
}) { (error:NSError!) -> Void in
hud.mode = .Text
hud.detailsLabelText = error.domain
hud.hide(true, afterDelay: 1.5)
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return tableViewArray.count+1
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 85
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == tableViewArray.count{
let cell:CompleteMaterialSexTableViewCell = tableView.dequeueReusableCellWithIdentifier("sexIdentifier", forIndexPath: indexPath) as! CompleteMaterialSexTableViewCell
return cell
}
else
{
let cell:CompleteTableViewCell = tableView.dequeueReusableCellWithIdentifier("customIdentifier", forIndexPath: indexPath) as! CompleteTableViewCell
// Configure the cell...
let array : NSArray = tableViewArray[indexPath.row] as! NSArray
cell.nameLabel.text = array[0] as? String
let completeMaterialModel = (array[1] as! CompleteMaterialModel)
cell.valueLabel.text = completeMaterialModel.value
return cell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row != tableViewArray.count{
if indexPath.row == 4{
let array : NSArray = tableViewArray[3] as! NSArray
let model = array[1] as! CompleteMaterialModel
if model.id.isEmpty{
let hud = MBProgressHUD.showHUDAddedTo(self.view.window, animated: true)
hud.mode = .Text
hud.detailsLabelText = "请先选择省份"
hud.hide(true, afterDelay: 1.5)
return
}
}
self.performSegueWithIdentifier("CompleteValueIdentifier", sender: indexPath.row)
}
}
/*
// 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.
if segue.identifier == "CompleteValueIdentifier"{
let vc : CompleteValueTableViewController = segue.destinationViewController as! CompleteValueTableViewController
vc.type = sender as! Int
let array : NSArray = tableViewArray[vc.type] as! NSArray
vc.completeMaterialModel = (array[1] as! CompleteMaterialModel)
vc.completeValueDelegate = self
if vc.type == 4{
let array : NSArray = tableViewArray[3] as! NSArray
let model = array[1] as! CompleteMaterialModel
vc.pid = model.id
}
}
}
}
|
lgpl-3.0
|
775885de72cbbf5a6a6ad0b35f48664f
| 36.85124 | 229 | 0.620742 | 5.016429 | false | false | false | false |
MilanNosal/InteractiveTransitioningContainer
|
InteractiveTransitioningContainer/InteractiveTransitionContainerPercentDrivenInteractiveTransition.swift
|
1
|
2767
|
//
// InteractiveTransitionContainerPercentDrivenInteractiveTransition.swift
// InteractiveTransitioningContainer
//
// Created by Milan Nosáľ on 23/02/2017.
// Copyright © 2017 Svagant. All rights reserved.
//
import UIKit
public class InteractiveTransitionContainerPercentDrivenInteractiveTransition: NSObject, UIViewControllerInteractiveTransitioning {
// MARK: UIPercentDrivenInteractiveTransition fields
open var completionCurve: UIViewAnimationCurve = .linear
// Duration is delegated to the animator
open var duration: CGFloat {
return CGFloat(animator!.transitionDuration(using: transitionContext!))
}
open var percentComplete: CGFloat {
didSet {
transitionContext!.updateInteractiveTransition(percentComplete)
}
}
open var completionSpeed: CGFloat = 1
// MARK: Context fields
open weak var animator: UIViewControllerAnimatedTransitioning?
open weak var transitionContext: UIViewControllerContextTransitioning?
// MARK: Flag reporting the state
fileprivate(set) var state: InteractiveTransitionControllerState = .isInactive
// MARK: Initializers
public convenience init(with animator: UIViewControllerAnimatedTransitioning) {
self.init()
self.animator = animator
}
public override init() {
percentComplete = 0
super.init()
}
// MARK: Transition lifecycle
open func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) {
assert(self.animator != nil, "Animator object must be set on interactive transitioning context.")
guard state == .isInactive else {
return
}
self.state = .isInteracting
self.transitionContext = transitionContext
}
open func updateInteractiveTransition(percentComplete: CGFloat) {
guard state == .isInteracting else {
return
}
let percent = fmin(percentComplete, 1)
let normalizedPercent = fmax(percent, 0)
self.percentComplete = normalizedPercent
}
open func cancelInteractiveTransition() {
guard state == .isInteracting else {
return
}
self.state = .isInTearDown
transitionContext!.cancelInteractiveTransition()
}
open func finishInteractiveTransition() {
guard state == .isInteracting else {
return
}
self.state = .isInTearDown
self.transitionContext!.finishInteractiveTransition()
}
// MARK: Internal methods
open func interactiveTransitionCompleted() {
self.state = .isInactive
}
}
|
mit
|
5c67bc6e1c320bcb0b7b9bee0dfda0d2
| 27.791667 | 131 | 0.663169 | 6.142222 | false | false | false | false |
carping/Postal
|
Postal/ReactiveSwift/Postal+RAC.swift
|
1
|
7828
|
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Snips
//
// 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 ReactiveSwift
public extension Postal {
func rac_connect() -> SignalProducer<Void, PostalError> {
return SignalProducer { observer, disposable in
self.connect(timeout: Postal.defaultTimeout) { result in
result.analysis(
ifSuccess: {
observer.send(value: ())
observer.sendCompleted()
},
ifFailure: observer.send)
}
}
}
func rac_listFolders() -> SignalProducer<[Folder], PostalError> {
return SignalProducer { observer, disposable in
self.listFolders { result in
result.analysis(
ifSuccess: { folders in
observer.send(value: folders)
observer.sendCompleted()
},
ifFailure: observer.send)
}
}
}
func rac_findAllMailFolder() -> SignalProducer<String, PostalError> {
return rac_listFolders()
.map { (folders: [Folder]) -> String in
// We want to search in the "All Mail" folder but if for any reason we can't find it,
// we fallback in the "INBOX" folder which should always exist.
if let allMailFolder = folders.filter({ $0.flags.contains(.AllMail) }).first {
return allMailFolder.name
} else if let inboxFolder = folders.filter({ $0.flags.contains(.Inbox) }).first {
return inboxFolder.name
}
return "INBOX"
}
}
func rac_search(folder: String, filter: SearchKind) -> SignalProducer<IndexSet, PostalError> {
return rac_search(folder: folder, filter: .base(filter))
}
func rac_search(folder: String, filter: SearchFilter) -> SignalProducer<IndexSet, PostalError> {
return SignalProducer { observer, disposable in
self.search(folder, filter: filter) { result in
result.analysis(
ifSuccess: { uids in
observer.send(value: uids)
observer.sendCompleted()
},
ifFailure: observer.send)
}
}
}
func rac_fetch(folder: String, uids: IndexSet, flags: FetchFlag, extraHeaders: Set<String> = []) -> SignalProducer<FetchResult, PostalError> {
return SignalProducer<FetchResult, PostalError> { observer, disposable in
self.fetchMessages(folder, uids: uids, flags: flags, extraHeaders: extraHeaders,
onMessage: { message in
observer.send(value: message)
}, onComplete: { error in
if let error = error {
observer.send(error: error)
} else {
observer.sendCompleted()
}
})
}
}
func rac_fetchAttachment(folder: String, uid: UInt, partId: String) -> SignalProducer<MailData, PostalError> {
return SignalProducer<MailData, PostalError> { observer, disposable in
self.fetchAttachments(folder, uid: uid, partId: partId,
onAttachment: { data in
observer.send(value: data)
},
onComplete: { error in
if let error = error {
observer.send(error: error)
} else {
observer.sendCompleted()
}
})
}
}
func rac_fetchTextualMail(folder: String, uids: IndexSet) -> SignalProducer<FetchResult, PostalError> {
return rac_fetch(folder: folder, uids: uids, flags: [ .structure, .fullHeaders ])
.flatMap(.concat) { (fetchResult: FetchResult) -> SignalProducer<FetchResult, PostalError> in
let inlineElements = fetchResult.body?.allParts.filter { singlePart in
if case .some(.attachment) = singlePart.mimeFields.contentDisposition { return false }
return [ "text/html", "text/plain" ].contains("\(singlePart.mimeType)")
} ?? []
return SignalProducer<SinglePart, PostalError>(inlineElements)
.flatMap(.merge) { (singlePart: SinglePart) -> SignalProducer<(String, MailData), PostalError> in
return self.rac_fetchAttachment(folder: folder, uid: fetchResult.uid, partId: singlePart.id).map { (singlePart.id, $0) }
}
.collect()
.map { fetchResult.mergeAttachments(attachments: Dictionary<String, MailData>($0)) }
}
}
}
private extension Dictionary {
init<S: Sequence>(_ seq: S) where S.Iterator.Element == (Key, Value) {
self.init()
for (k, v) in seq {
self[k] = v
}
}
init<S: Sequence>(elements: S) where S.Iterator.Element == Element {
self.init()
for (k, v) in elements {
self[k] = v
}
}
}
private extension FetchResult {
func mergeAttachments(attachments: [String: MailData]) -> FetchResult {
return FetchResult(uid: uid,
header: header,
flags: flags,
body: body?.mergeAttachments(attachments: attachments),
rfc822Size: rfc822Size,
internalDate: internalDate,
gmailThreadId: gmailThreadId,
gmailMessageId: gmailMessageId,
gmailLabels: gmailLabels)
}
}
private extension MailPart {
func mergeAttachments(attachments: [String: MailData]) -> MailPart {
switch self {
case .single(let id, let mimeType, let mimeFields, let data):
if let replacedData = attachments[id] {
return .single(id: id, mimeType: mimeType, mimeFields: mimeFields, data: MailData(rawData: replacedData.rawData, encoding: mimeFields.contentEncoding ?? data?.encoding ?? replacedData.encoding))
}
return self
case .multipart(let id, let mimeType, let parts):
return .multipart(id: id, mimeType: mimeType, parts: parts.map { $0.mergeAttachments(attachments: attachments) })
case .message(let id, let header, let message):
return .message(id: id, header: header, message: message.mergeAttachments(attachments: attachments))
}
}
}
|
mit
|
9a7eaaa9a564c5dec984a78145e7a523
| 42.977528 | 210 | 0.56745 | 4.844059 | false | false | false | false |
jlecomte/iOSYelpApp
|
Yelp/MainViewController.swift
|
1
|
6308
|
//
// MainViewController.swift
// Yelp
//
// Created by Julien Lecomte on 9/18/14.
// Copyright (c) 2014 Julien Lecomte. All rights reserved.
//
import UIKit
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchDisplayDelegate, UISearchBarDelegate, YelpSearchSettingsDelegate {
@IBOutlet var searchBar: UISearchBar!
@IBOutlet weak var filterBtn: UIBarButtonItem!
@IBOutlet var tableView: UITableView!
var client = YelpOAuthClient.sharedInstance
var businesses: [NSDictionary] = []
var query = "Restaurants"
var offset = 0
let n = 20
var settings = YelpSearchSettings(radius: 10, sortBy: 0, deals: false)
var searching = false
override func viewDidLoad() {
super.viewDidLoad()
MMProgressHUD.setPresentationStyle(MMProgressHUDPresentationStyle.None)
tableView.delegate = self
tableView.dataSource = self
navigationItem.titleView = searchBar
// Trigger initial search...
searchBar.text = query
fetchBusinessListing()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 90
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return businesses.count + 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.row == businesses.count) {
var cell = UITableViewCell()
if businesses.count == 0 {
if query != "" && !searching {
cell.textLabel?.text = "No results..."
}
} else {
cell.textLabel?.text = "Loading..."
}
return cell
} else {
var cell = tableView.dequeueReusableCellWithIdentifier("BusinessListingCell") as BusinessListingTableViewCell
var business = businesses[indexPath.row]
var thumbnailImageUrl = business["image_url"] as String
cell.thumbnailImageView.setImageWithURL(NSURL(string: thumbnailImageUrl))
var ratingImageUrl = business["rating_img_url_large"] as String
cell.starRatingImageView.setImageWithURL(NSURL(string: ratingImageUrl))
cell.businessNameLabel.text = business["name"] as? String
var reviewCount = business["review_count"] as Int
cell.reviewCountLabel.text = "\(reviewCount) reviews"
var location = business["location"] as NSDictionary
var addressParts = location["address"] as [String]
var address = " ".join(addressParts)
var city = location["city"] as String
cell.addressLabel.text = "\(address), \(city)"
var categories = business["categories"] as [NSArray]
var categoriesLabels: [String] = categories.reduce([]) {
var currentValue = $0 as [String]
var category = $1 as [String]
var label = category[0]
currentValue.append(label)
return currentValue
}
cell.categoryLabel.text = ", ".join(categoriesLabels)
// Additional data used for segue...
cell.businessId = business["id"] as String
// Infinite scrolling...
if indexPath.row >= businesses.count - 1 && offset < businesses.count {
offset += n
fetchBusinessListing()
}
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.text = query
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
if searchBar.text != query {
query = searchBar.text
offset = 0
businesses = []
tableView.reloadData()
fetchBusinessListing()
}
}
func fetchBusinessListing() {
if offset == 0 {
MMProgressHUD.showWithStatus("Loading...")
}
searching = true
client.search(query, limit: n, offset: offset, settings: settings) {
(response: AnyObject!, error: NSError!) -> Void in
self.searching = false
MMProgressHUD.dismiss()
if error == nil {
var object = response as NSDictionary
var business = object["businesses"] as [NSDictionary]
if self.offset > 0 {
self.businesses += business
} else {
self.businesses = business
}
self.tableView.reloadData()
} else {
var alert = UIAlertController(title: "Error", message: "API error", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: false, completion: nil)
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Detail" {
var cell = sender as BusinessListingTableViewCell
var detailViewController = segue.destinationViewController as DetailViewController
detailViewController.businessId = cell.businessId
} else if segue.identifier == "Settings" {
var settingsViewController = segue.destinationViewController as SettingsViewController
settingsViewController.delegate = self
}
}
func getCurrentSearchSettings() -> YelpSearchSettings {
return settings
}
func applyYelpSearchSettings(settings: YelpSearchSettings) {
self.settings = settings
// Repeat the current search with the new settings...
if query != "" {
offset = 0
businesses = []
tableView.reloadData()
fetchBusinessListing()
}
}
}
|
mit
|
c9c2c02c1b1557f89f902b19d7f6043e
| 31.020305 | 162 | 0.607483 | 5.602131 | false | false | false | false |
yyny1789/KrMediumKit
|
Source/Utils/Extensions/UIColor+BFKit.swift
|
1
|
13945
|
//
// UIColorExtension.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2017 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
// MARK: - Global functions
/// Create an UIColor in format RGBA.
///
/// - Parameters:
/// - red: Red value.
/// - green: Green value.
/// - blue: Blue value.
/// - alpha: Alpha value.
/// - Returns: Returns the created UIColor.
public func RGBA(_ red: Int, _ green: Int, _ blue: Int, _ alpha: Float) -> UIColor {
return UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha))
}
/// Create an UIColor in format ARGB.
///
/// - Parameters:
/// - alpha: Alpha value.
/// - red: Red value.
/// - green: Green value.
/// - blue: Blue value.
/// - Returns: Returns the created UIColor.
public func ARGB( _ alpha: Float, _ red: Int, _ green: Int, _ blue: Int) -> UIColor {
return RGBA(red, green, blue, alpha)
}
/// Create an UIColor in format RGB.
///
/// - Parameters:
/// - red: Red value.
/// - green: Green value.
/// - blue: Blue value.
/// - Returns: Returns the created UIColor.
public func RGB(_ red: Int, _ green: Int, _ blue: Int) -> UIColor {
return UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
// MARK: - UIColor extension
/// This extesion adds some useful functions to UIColor.
public extension UIColor {
// MARK: - Variables
/// RGB properties: red.
public var redComponent: CGFloat {
if self.canProvideRGBComponents() {
let component = self.cgColor.__unsafeComponents
return component![0]
}
return 0.0
}
/// RGB properties: green.
public var greenComponent: CGFloat {
if self.canProvideRGBComponents() {
let component = self.cgColor.__unsafeComponents
if self.cgColor.colorSpace?.model == CGColorSpaceModel.monochrome {
return component![0]
}
return component![1]
}
return 0.0
}
/// RGB properties: blue.
public var blueComponent: CGFloat {
if self.canProvideRGBComponents() {
let component = self.cgColor.__unsafeComponents
if self.cgColor.colorSpace?.model == CGColorSpaceModel.monochrome {
return component![0]
}
return component![2]
}
return 0.0
}
/// RGB properties: white.
public var whiteComponent: CGFloat {
if self.cgColor.colorSpace?.model == CGColorSpaceModel.monochrome {
let component = self.cgColor.__unsafeComponents
return component![0]
}
return 0.0
}
/// RGB properties: luminance.
public var luminance: CGFloat {
if self.canProvideRGBComponents() {
var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
if !self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
return 0.0
}
return red * 0.2126 + green * 0.7152 + blue * 0.0722
}
return 0.0
}
/// RGBA properties: alpha.
public var alpha: CGFloat {
return self.cgColor.alpha
}
/// HSB properties: hue.
public var hue: CGFloat {
if self.canProvideRGBComponents() {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
if self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return hue
}
}
return 0.0
}
/// HSB properties: saturation.
public var saturation: CGFloat {
if self.canProvideRGBComponents() {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
if self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return saturation
}
}
return 0.0
}
/// HSB properties: brightness.
public var brightness: CGFloat {
if self.canProvideRGBComponents() {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
if self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return brightness
}
}
return 0.0
}
/// Returns the HEX string from UIColor.
public var hex: String {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
let rgb: Int = (Int)(red * 255) << 16 | (Int)(green * 255) << 8 | (Int)(blue * 255) << 0
return String(format:"#%06x", rgb)
}
// MARK: - Functions
/// Create a color from HEX with alpha.
///
/// - Parameters:
/// - hex: HEX value.
/// - alpha: Alpha value.
public convenience init(hex: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat(((hex & 0xFF0000) >> 16)) / 255.0, green: CGFloat(((hex & 0xFF00) >> 8)) / 255.0, blue: CGFloat((hex & 0xFF)) / 255.0, alpha: alpha)
}
/// Create a color from a HEX string.
/// It supports the following type:
/// - #ARGB, ARGB if irstIsAlpha is true. #RGBA, RGBA if firstIsAlpha is false.
/// - #ARGB.
/// - #RRGGBB.
/// - #AARRGGBB, AARRGGBB if irstIsAlpha is true. #RRGGBBAA, RRGGBBAA if firstIsAlpha is false.
///
/// - Parameters:
/// - hexString: HEX string.
/// - alphaFirst: Set it to true if alpha value is the first in the HEX string. If alpha value is the last one, set it to false. Default is false.
public convenience init(hex: String, alphaFirst: Bool = false) {
let colorString: String = hex.replacingOccurrences(of: "#", with: "").uppercased()
var alpha: CGFloat = 0.0, red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0
switch colorString.length {
case 3: // #RGB
alpha = 1.0
red = UIColor.colorComponentFrom(colorString, start: 0, lenght: 1)
green = UIColor.colorComponentFrom(colorString, start: 1, lenght: 1)
blue = UIColor.colorComponentFrom(colorString, start: 2, lenght: 1)
case 4: // #ARGB
alpha = UIColor.colorComponentFrom(colorString, start: 0, lenght: 1)
red = UIColor.colorComponentFrom(colorString, start: 1, lenght: 1)
green = UIColor.colorComponentFrom(colorString, start: 2, lenght: 1)
blue = UIColor.colorComponentFrom(colorString, start: 3, lenght: 1)
case 6: // #RRGGBB
alpha = 1.0
red = UIColor.colorComponentFrom(colorString, start: 0, lenght: 2)
green = UIColor.colorComponentFrom(colorString, start: 2, lenght: 2)
blue = UIColor.colorComponentFrom(colorString, start: 4, lenght: 2)
case 8: // #AARRGGBB
alpha = UIColor.colorComponentFrom(colorString, start: 0, lenght: 2)
red = UIColor.colorComponentFrom(colorString, start: 2, lenght: 2)
green = UIColor.colorComponentFrom(colorString, start: 4, lenght: 2)
blue = UIColor.colorComponentFrom(colorString, start: 6, lenght: 2)
default:
break
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
/// A good contrasting color, it will be either black or white.
///
/// - Returns: Returns the color.
public func contrasting() -> UIColor {
return self.luminance > 0.5 ? UIColor.black : UIColor.white
}
/// A complementary color that should look good.
///
/// - Returns: Returns the color.
public func complementary() -> UIColor? {
var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0
if !self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
return nil
}
hue += 180
if hue > 360 {
hue -= 360
}
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
/// Check if the color is in RGB format.
///
/// - Returns: Returns if the color is in RGB format.
public func canProvideRGBComponents() -> Bool {
guard let colorSpace = self.cgColor.colorSpace else {
return false
}
switch colorSpace.model {
case CGColorSpaceModel.rgb, CGColorSpaceModel.monochrome:
return true
default:
return false
}
}
/// Returns the color component from the string.
///
/// - Parameters:
/// - fromString: String to convert.
/// - start: Component start index.
/// - lenght: Component lenght.
/// - Returns: Returns the color component from the string.
fileprivate static func colorComponentFrom(_ string: String, start: Int, lenght: Int) -> CGFloat {
var substring: NSString = string as NSString
substring = substring.substring(with: NSMakeRange(start, lenght)) as NSString
let fullHex = lenght == 2 ? substring as String : "\(substring)\(substring)"
var hexComponent: CUnsignedInt = 0
Scanner(string: fullHex).scanHexInt32(&hexComponent)
return CGFloat(hexComponent) / 255.0
}
/// Create a random color.
///
/// - Parameter alpha: Alpha value.
/// - Returns: Returns the UIColor instance.
public static func random(alpha: CGFloat = 1.0) -> UIColor {
let red: UInt32 = arc4random_uniform(255)
let green: UInt32 = arc4random_uniform(255)
let blue: UInt32 = arc4random_uniform(255)
return UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
}
/// Create an UIColor from a given string. Example: "blue" or hex string.
///
/// - Parameter color: String with color.
/// - Returns: Returns the created UIColor.
public static func color(string color: String) -> UIColor {
if color.length >= 3 {
if UIColor.responds(to: Selector(color.lowercased() + "Color")) {
return self.convertColor(string: color)
} else {
return UIColor(hex: color)
}
} else {
return UIColor.black
}
}
/// Create an UIColor from a given string like "blue" or an hex string.
///
/// - Parameter color: String with color.
public convenience init(string color: String) {
if UIColor.responds(to: Selector(color.lowercased() + "Color")) {
self.init(cgColor: UIColor.convertColor(string: color).cgColor)
} else {
self.init(hex: color)
}
}
/// Used the retrive the color from the string color ("blue" or "red").
///
/// - Parameter color: String with the color.
/// - Returns: Returns the created UIColor.
private static func convertColor(string color: String) -> UIColor {
let color = color.lowercased()
switch color {
case "black":
return UIColor.black
case "darkgray":
return UIColor.darkGray
case "lightgray":
return UIColor.lightGray
case "white":
return UIColor.white
case "gray":
return UIColor.gray
case "red":
return UIColor.red
case "green":
return UIColor.green
case "blue":
return UIColor.blue
case "cyan":
return UIColor.cyan
case "yellow":
return UIColor.yellow
case "magenta":
return UIColor.magenta
case "orange":
return UIColor.orange
case "purple":
return UIColor.purple
case "brown":
return UIColor.brown
case "clear":
return UIColor.clear
default:
return UIColor.clear
}
}
/// Creates and returns a color object that has the same color space and component values as the given color, but has the specified alpha component.
///
/// - Parameters:
/// - color: UIColor value.
/// - alpha: Alpha value.
/// - Returns: Returns an UIColor instance.
public static func color(color: UIColor, alpha: CGFloat) -> UIColor {
return color.withAlphaComponent(alpha)
}
}
|
mit
|
fa25f882e812445875a375f2940bcaff
| 35.033592 | 163 | 0.58702 | 4.272365 | false | false | false | false |
RikkiGibson/Corvallis-Bus-iOS
|
TodayExtension/TodayViewController.swift
|
1
|
6802
|
//
// TodayViewController.swift
// CorvallisBusTodayExtension
//
// Created by Rikki Gibson on 10/15/14.
// Copyright (c) 2014 Rikki Gibson. All rights reserved.
//
import UIKit
import NotificationCenter
final class TodayViewController: UITableViewController, NCWidgetProviding {
let errorPlaceholder = FavoriteStopViewModel(stopName: "An error occurred",
stopId: 0, distanceFromUser: "", isNearestStop: false,
firstRouteColor: UIColor.clear, firstRouteName: "", firstRouteArrivals: "Tap to open the app.",
secondRouteColor: UIColor.clear, secondRouteName: "", secondRouteArrivals: "")
let emptyPlaceholder = FavoriteStopViewModel(stopName: "No favorites to display",
stopId: 0, distanceFromUser: "", isNearestStop: false,
firstRouteColor: UIColor.clear, firstRouteName: "", firstRouteArrivals: "Tap to open the app.",
secondRouteColor: UIColor.clear, secondRouteName: "", secondRouteArrivals: "")
let loadingPlaceholder = FavoriteStopViewModel(stopName: "Loading...",
stopId: 0, distanceFromUser: "", isNearestStop: false,
firstRouteColor: UIColor.clear, firstRouteName: "", firstRouteArrivals: "",
secondRouteColor: UIColor.clear, secondRouteName: "", secondRouteArrivals: "")
var favoriteStops: Resource<[FavoriteStopViewModel], BusError> = .loading
var didCompleteUpdate = false
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UINib(nibName: "FavoritesTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "FavoritesTableViewCell")
self.tableView.backgroundColor = .clear
self.tableView.separatorInset = UIEdgeInsets(top: 0, left: 66, bottom: 0, right: 8)
}
@available(iOSApplicationExtension 10.0, *)
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
reloadCachedFavorites()
if activeDisplayMode == .compact {
self.preferredContentSize = CGSize(width: maxSize.width, height: min(maxSize.height, self.tableView.contentSize.height))
} else {
self.preferredContentSize = CGSize(width: maxSize.width, height: self.tableView.contentSize.height)
}
}
// MARK: Table view
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Use a placeholder row when favorites is empty (either no displayable favorites or failed to load)
let itemCount = (favoriteStops ?? []).count
return isWidgetCollapsed() ? 1 : max(1, itemCount)
}
func viewModel(for row: Int) -> FavoriteStopViewModel {
if case .error = favoriteStops {
return errorPlaceholder
}
guard case .success(let viewModels) = favoriteStops else {
return loadingPlaceholder
}
if viewModels.isEmpty {
return emptyPlaceholder
}
if isWidgetCollapsed() {
return viewModels.first({ !$0.isNearestStop }) ?? viewModels[row]
}
return viewModels[row]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FavoritesTableViewCell") as! FavoriteStopTableViewCell
cell.update(viewModel(for: indexPath.row))
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let urlString: String
if case .success(let viewModels) = favoriteStops, !viewModels.isEmpty {
let selectedStop = viewModel(for: indexPath.row)
urlString = "CorvallisBus://?\(selectedStop.stopId)"
} else {
urlString = "CorvallisBus://"
}
if let url = URL(string: urlString) {
self.extensionContext?.open(url) { success in }
}
}
func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsets(top: defaultMarginInsets.top,
left: defaultMarginInsets.left - 50,
bottom: defaultMarginInsets.bottom,
right: defaultMarginInsets.right)
}
func isWidgetCollapsed() -> Bool {
if #available(iOSApplicationExtension 10.0, *) {
return extensionContext?.widgetActiveDisplayMode == NCWidgetDisplayMode.compact
} else {
return false
}
}
func reloadCachedFavorites() {
let viewModels = CorvallisBusFavoritesManager.cachedFavoriteStopsForWidget()
favoriteStops = .success(viewModels)
if #available(iOSApplicationExtension 10.0, *) {
extensionContext?.widgetLargestAvailableDisplayMode = viewModels.count > 1 ? .expanded : .compact
}
tableView.reloadData()
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
reloadCachedFavorites()
didCompleteUpdate = false
CorvallisBusFavoritesManager.favoriteStopsForWidget()
.startOnMainThread({ self.onUpdate($0, completionHandler: completionHandler) })
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(TodayViewController.clearTableIfUpdatePending), userInfo: nil, repeats: false)
}
@objc func clearTableIfUpdatePending() {
if !didCompleteUpdate {
favoriteStops = .loading
UserDefaults.groupUserDefaults().cachedFavoriteStops = []
tableView.reloadData()
}
}
func onUpdate(_ result: Failable<[FavoriteStopViewModel], BusError>, completionHandler: (NCUpdateResult) -> Void) {
didCompleteUpdate = true
let updateResult: NCUpdateResult
switch(result) {
case .success(let data):
favoriteStops = .success(data)
updateResult = .newData
if #available(iOSApplicationExtension 10.0, *) {
extensionContext?.widgetLargestAvailableDisplayMode = data.count > 1 ? .expanded : .compact
}
case .error(let err):
favoriteStops = .error(err)
updateResult = .failed
if #available(iOSApplicationExtension 10.0, *) {
extensionContext?.widgetLargestAvailableDisplayMode = .compact
}
}
tableView.reloadData()
if (preferredContentSize != tableView.contentSize) {
preferredContentSize = tableView.contentSize
}
completionHandler(updateResult)
}
}
|
mit
|
b401e4136dc69d57f95417ac3dc40820
| 39.975904 | 160 | 0.654072 | 5.16085 | false | true | false | false |
coniferprod/ContactCard
|
Example/ContactCard/ViewController.swift
|
1
|
2111
|
import UIKit
import ContactsUI
import ContactCard
class ViewController: UIViewController, CNContactPickerDelegate {
let controller = CNContactPickerViewController()
@IBOutlet weak var pickContactButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
controller.delegate = self
ContactAuthorizer.authorizeContacts { succeeded in
DispatchQueue.main.async { [weak self] in
self?.pickContactButton.isEnabled = succeeded
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pickContact(_ sender: Any) {
print("Button clicked")
present(controller, animated: true, completion: nil)
}
func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
print("Contact picking cancelled by user")
}
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
print("User did select contact")
let card = cardFrom(contact: contact)
let cardAsJSON = card.asJSON()
print("Contact card as JSON (\(cardAsJSON.count) characters):")
print(cardAsJSON)
print("\n")
let cardAsvCard = card.asvCard()
print("Contact card as vCard 3.0 (\(cardAsvCard.count) characters):")
print(cardAsvCard)
}
}
public final class ContactAuthorizer {
public class func authorizeContacts(completionHandler : @escaping (_ succeeded: Bool) -> Void) {
switch CNContactStore.authorizationStatus(for: .contacts) {
case .authorized:
completionHandler(true)
case .notDetermined:
CNContactStore().requestAccess(for: .contacts) { succeeded, err in completionHandler(err == nil && succeeded)
}
default:
completionHandler(false)
}
}
}
|
mit
|
4bff99933d22d606406c4d34863270a4
| 30.044118 | 121 | 0.635718 | 5.357868 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.