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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
flipacholas/RCActionView
|
RCActionView/Classes/RCGridMenu.swift
|
1
|
7591
|
//
// RCGridMenu.swift
// Pods
//
// Created by Rodrigo on 10/06/2016.
//
//
import Foundation
class RCGridItem: UIButton {
init() {
super.init(frame: CGRect.zero)
}
convenience init(title: String, image: UIImage, style: RCActionViewStyle?) {
self.init()
self.clipsToBounds = false
self.titleLabel!.font = UIFont.systemFont(ofSize: 13)
self.titleLabel!.backgroundColor = UIColor.clear
self.titleLabel!.textAlignment = .center
self.setTitle(title, for: UIControlState())
self.setTitleColor(RCBaseMenu.BaseMenuTextColor(style), for: UIControlState())
self.setImage(image, for: UIControlState())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let width = self.bounds.size.width
let height = self.bounds.size.height
let imageRect = CGRect(x: width * 0.2, y: width * 0.2, width: width * 0.6, height: width * 0.6)
self.imageView!.frame = imageRect
let labelHeight = height - (imageRect.origin.y + imageRect.size.height)
let labelRect = CGRect(x: width * 0.05, y: imageRect.origin.y + imageRect.size.height, width: width * 0.9, height: labelHeight)
self.titleLabel!.frame = labelRect
}
}
class RCGridMenu: RCBaseMenu{
let kMAX_CONTENT_SCROLLVIEW_HEIGHT:CGFloat = 400
var titleLabel: UILabel
var contentScrollView: UIScrollView
var cancelButton: RCButton
var itemTitles: [String]
var itemImages: [UIImage]
var items: [RCGridItem]
var actionHandle: ((NSInteger) -> Void)?
override init(frame: CGRect) {
self.itemTitles = []
self.itemImages = []
self.items = []
self.titleLabel = UILabel(frame: CGRect.zero)
self.contentScrollView = UIScrollView(frame: CGRect.zero)
self.cancelButton = RCButton(type: .custom)
super.init(frame: frame)
}
convenience init(title: String, itemTitles: [String], images: [UIImage], style: RCActionViewStyle) {
self.init(frame: UIScreen.main.bounds)
var count: Int = min(itemTitles.count, images.count)
self.titleLabel.text = title
self.itemTitles = itemTitles
self.itemImages = images
self.style = style
if (style == .light){
self.cancelButton.setTitleColor(RCBaseMenu.BaseMenuActionTextColor(), for: UIControlState())
} else {
self.cancelButton.setTitleColor(RCBaseMenu.BaseMenuTextColor(self.style), for: UIControlState())
}
self.backgroundColor = RCBaseMenu.BaseMenuBackgroundColor(self.style)
self.titleLabel.backgroundColor = UIColor.clear
self.titleLabel.font = UIFont.boldSystemFont(ofSize: 17)
self.titleLabel.textAlignment = .center
self.titleLabel.textColor = RCBaseMenu.BaseMenuTextColor(self.style)
self.addSubview(titleLabel)
self.contentScrollView.contentSize = contentScrollView.bounds.size
self.contentScrollView.showsHorizontalScrollIndicator = false
self.contentScrollView.showsVerticalScrollIndicator = true
self.contentScrollView.backgroundColor = UIColor.clear
self.addSubview(contentScrollView)
self.cancelButton.clipsToBounds = true
self.cancelButton.titleLabel!.font = UIFont.systemFont(ofSize: 17)
cancelButton.addTarget(self, action: #selector(RCGridMenu.tapAction(_:)), for: .touchUpInside)
cancelButton.setTitle("Cancel", for: UIControlState())
self.addSubview(cancelButton)
self.setupWithItemTitles(itemTitles, images: itemImages)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupWithItemTitles(_ titles: [String], images: [UIImage]) {
var items:[RCGridItem] = []
for i in 0 ..< titles.count {
let item: RCGridItem = RCGridItem(title: titles[i], image: images[i], style: style)
item.tag = i
item.addTarget(self, action: #selector(RCGridMenu.tapAction(_:)), for: .touchUpInside)
items.append(item)
contentScrollView.addSubview(item)
}
self.items = items
}
override func layoutSubviews() {
super.layoutSubviews()
self.titleLabel.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.size.width, height: 40))
self.layoutContentScrollView()
self.contentScrollView.frame = CGRect(origin: CGPoint(x: 0, y: self.titleLabel.frame.size.height), size: self.contentScrollView.bounds.size)
self.cancelButton.frame = CGRect(x: self.bounds.size.width * 0.05, y: self.titleLabel.bounds.size.height + self.contentScrollView.bounds.size.height, width: self.bounds.size.width * 0.9, height: 44)
self.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.size.width, height: self.titleLabel.bounds.size.height + self.contentScrollView.bounds.size.height + self.cancelButton.bounds.size.height))
}
func layoutContentScrollView() {
let margin: UIEdgeInsets = UIEdgeInsetsMake(0, 10, 15, 10)
let itemSize: CGSize = CGSize(width: (self.bounds.size.width - margin.left - margin.right) / 4, height: 85)
let itemCount: Int = self.items.count
let rowCount: Int = ((itemCount - 1) / 4) + 1
self.contentScrollView.contentSize = CGSize(width: self.bounds.size.width, height: CGFloat(rowCount) * itemSize.height + margin.top + margin.bottom)
for i in 0 ..< itemCount {
let item: RCGridItem = self.items[i]
let row: Int = i / 4
let column: Int = i % 4
let p: CGPoint = CGPoint(x: margin.left + CGFloat(column) * itemSize.width, y: margin.top + CGFloat(row) * itemSize.height)
item.frame = CGRect(origin: p, size: itemSize)
item.layoutIfNeeded()
}
if self.contentScrollView.contentSize.height > kMAX_CONTENT_SCROLLVIEW_HEIGHT {
self.contentScrollView.bounds = CGRect(origin: CGPoint.zero,size: CGSize(width: self.bounds.size.width, height: kMAX_CONTENT_SCROLLVIEW_HEIGHT))
}
else {
self.contentScrollView.bounds = CGRect(origin: CGPoint.zero, size: self.contentScrollView.contentSize)
}
}
func triggerSelectedAction(_ actionHandle: @escaping (NSInteger) -> Void) {
self.actionHandle = actionHandle
}
func tapAction(_ sender: AnyObject) {
if let handle = actionHandle {
if sender.isEqual(self.cancelButton) {
let delayInSeconds: Double = 0.15
let popTime: DispatchTime = DispatchTime.now() + Double(Int64(delayInSeconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: popTime, execute: {() -> Void in
self.actionHandle!(0)
})
}
else {
let delayInSeconds: Double = 0.15
let popTime: DispatchTime = DispatchTime.now() + Double(Int64(delayInSeconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: popTime, execute: {() -> Void in
self.actionHandle!(sender.tag + 1)
})
}
}
}
}
|
mit
|
fedca026a9ddb113800281f4c121ce3c
| 40.708791 | 222 | 0.634436 | 4.345163 | false | false | false | false |
tehprofessor/SwiftyFORM
|
Example/TextField/TextFieldKeyboardTypesViewController.swift
|
1
|
1608
|
// MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved.
import UIKit
import SwiftyFORM
class TextFieldKeyboardTypesViewController: FormViewController {
override func populate(builder: FormBuilder) {
builder.navigationTitle = "Keyboard Types"
builder.toolbarMode = .None
builder.demo_showInfo("Shows all the UIKeyboardType variants")
builder += TextFieldFormItem().styleClass("align").title("ASCIICapable").placeholder("Lorem Ipsum").keyboardType(.ASCIICapable)
builder += TextFieldFormItem().title("NumbersAndPunctuation").placeholder("123.45").keyboardType(.NumbersAndPunctuation)
builder += TextFieldFormItem().styleClass("align").title("URL").placeholder("example.com/blog").keyboardType(.URL)
builder += TextFieldFormItem().styleClass("align").title("NumberPad").placeholder("0123456789").keyboardType(.NumberPad)
builder += TextFieldFormItem().styleClass("align").title("PhonePad").placeholder("+999#22;123456,27").keyboardType(.PhonePad)
builder += TextFieldFormItem().styleClass("align").title("EmailAddress").placeholder("[email protected]").keyboardType(.EmailAddress)
builder += TextFieldFormItem().styleClass("align").title("DecimalPad").placeholder("1234.5678").keyboardType(.DecimalPad)
builder += TextFieldFormItem().styleClass("align").title("Twitter").placeholder("@user or #hashtag").keyboardType(.Twitter)
builder += TextFieldFormItem().styleClass("align").title("WebSearch").placeholder("how to do this.").keyboardType(.WebSearch)
builder.alignLeftElementsWithClass("align")
builder += SectionFooterTitleFormItem().title("Footer text")
}
}
|
mit
|
abd7d7476c09971d74e7cdb284a00e6f
| 72.090909 | 141 | 0.774254 | 4.872727 | false | false | false | false |
VirrageS/TDL
|
TDL/FilterCell.swift
|
1
|
2501
|
import UIKit
let filterCellHeight: CGFloat = 50
let filterCellTextFontSize: CGFloat = 15
class FilterCell: UITableViewCell {
let nameTextLabel: UILabel
let separatorLineLabel: UILabel
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
nameTextLabel = UILabel(frame: CGRectZero)
nameTextLabel.backgroundColor = UIColor.whiteColor()
nameTextLabel.font = UIFont.systemFontOfSize(filterCellTextFontSize)
nameTextLabel.numberOfLines = 1
nameTextLabel.textAlignment = NSTextAlignment.Left
nameTextLabel.textColor = UIColor(red: 142/255, green: 142/255, blue: 147/255, alpha: 1)
separatorLineLabel = UILabel(frame: CGRectZero)
separatorLineLabel.backgroundColor = UIColor(red: 178/255, green: 178/255, blue: 178/255, alpha: 1.0)
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(nameTextLabel)
contentView.addSubview(separatorLineLabel)
nameTextLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addConstraint(NSLayoutConstraint(item: nameTextLabel, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 20))
contentView.addConstraint(NSLayoutConstraint(item: nameTextLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 17))
separatorLineLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.addConstraint(NSLayoutConstraint(item: separatorLineLabel, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: separatorLineLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: -0.5))
contentView.addConstraint(NSLayoutConstraint(item: separatorLineLabel, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: separatorLineLabel, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0))
}
func configure(row: Int) {
nameTextLabel.text = allFilters[row]
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
045087f254c5b31100a22fae8b765431
| 55.863636 | 187 | 0.728908 | 4.932939 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK
|
BridgeAppSDK/SBAAppDelegate.swift
|
1
|
29140
|
//
// SBAAppDelegate.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
import BridgeSDK
import ResearchKit
/**
The BridgeAppSDK delegate is used to define additional functionality on the app delegate.
It is used throughout this SDK with the assumption that the UIAppDelegate will conform to
the methods defined by this protocol.
*/
@objc
public protocol SBABridgeAppSDKDelegate : UIApplicationDelegate, SBAAppInfoDelegate, SBBBridgeErrorUIDelegate, SBAAlertPresenter, SBAOnboardingAppDelegate {
}
/**
Default name for a embedded json file that can be used to create a `SBAOnboardingManager`.
(See Onboarding.json in the sample app for an example.)
*/
public let SBAOnboardingJSONFilename = "Onboarding"
/**
Default name for the storyboard that defines the view controllers to display to a new user
who has started the onboarding sign up process.
*/
public let SBASignUpStoryboardName = "SignUp"
/**
Default name for the storyboard that defines the view controllers to display to a new user
who has not registered or logged in. If this is not applicable to your application, you should
override `showOnboardingViewController` to set a different view controller as the "root" using
the method `transition(toRootViewController:state:animated:)`.
*/
public let SBAStudyOverviewStoryboardName = "StudyOverview"
/**
Default name for the storyboard that defines the view controllers to display to a user who
has completed registration. If this is not applicable to your application, you should
override `showMainViewController` to set a different view controller as the "root" using
the method `transition(toRootViewController:state:animated:)`.
*/
public let SBAMainStoryboardName = "Main"
@UIApplicationMain
@objc open class SBAAppDelegate: UIResponder, SBABridgeAppSDKDelegate, ORKPasscodeDelegate, ORKTaskViewControllerDelegate {
open var window: UIWindow?
@objc
public final class var shared: SBAAppDelegate? {
return UIApplication.shared.delegate as? SBAAppDelegate
}
// MARK: UIApplicationDelegate
open func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization before application launch.
// emm 2017-09-28 Hack to make sure SBAUser has the app delegate available for later use off the main queue,
// no matter where in the app that happens. See related hack comments in SBAUser.swift and SBAUserWrapper.swift.
let _ = SBAUser.mainQueueAppDelegate
self.resetUserDataIfLoggedOut()
self.initializeBridgeServerConnection()
BridgeSDK.setErrorUIDelegate(self)
// Save any outstanding clientData profile item updates to Bridge, and ensure the class has
// access to all the SBBScheduledActivity objects in BridgeSDK's cache.
SBAClientDataProfileItem.updateChangesToBridge()
// Set the tint colors if applicable
if let tintColor = UIColor.primaryTintColor {
self.window?.tintColor = tintColor
}
if let tintColor = UIColor.taskNavigationBarTintColor {
UINavigationBar.appearance(whenContainedInInstancesOf: [ORKTaskViewController.self]).barTintColor = tintColor
}
if let tintColor = UIColor.taskNavigationButtonTintColor {
UINavigationBar.appearance(whenContainedInInstancesOf: [ORKTaskViewController.self]).tintColor = tintColor
}
// Replace the launch root view controller with an SBARootViewController
// This allows transitioning between root view controllers while a lock screen
// or onboarding view controller is being presented modally.
self.window?.rootViewController = SBARootViewController(rootViewController: self.window?.rootViewController)
return true
}
open func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if shouldShowPasscode() {
lockScreen()
}
else {
showAppropriateViewController(animated: true)
}
return true
}
open func applicationDidEnterBackground(_ application: UIApplication) {
if shouldShowPasscode() {
// Hide content so it doesn't appear in the app switcher.
rootViewController?.contentHidden = true
self.backgroundTimestamp = Date()
}
}
open func applicationWillResignActive(_ application: UIApplication) {
// Save any outstanding clientData profile item updates to Bridge.
SBAClientDataProfileItem.updateChangesToBridge()
}
open func applicationDidBecomeActive(_ application: UIApplication) {
// Make sure that the content view controller is not hiding content
rootViewController?.contentHidden = false
self.currentUser.ensureSignedInWithCompletion() { (error) in
// Check if there are any errors during sign in that we need to address
if let error = error, let errorCode = SBBErrorCode(rawValue: (error as NSError).code) {
switch errorCode {
case SBBErrorCode.serverPreconditionNotMet:
DispatchQueue.main.async {
self.continueOnboardingFlowIfNeeded()
}
case SBBErrorCode.unsupportedAppVersion:
if !self.handleUnsupportedAppVersionError(error, networkManager: nil) {
self.registerCatastrophicStartupError(error)
}
default:
break
}
}
}
// Hacky work-around for no longer being able to determine if permission has been granted
// without attempting to collect data. syoung 07/14/2017
let sensorPermission = SBAPermissionObjectType(permissionType: .coremotion)
if SBAPermissionsManager.shared.isPermissionGranted(for: sensorPermission) {
SBAPermissionsManager.shared.requestPermission(for: sensorPermission, completion: nil)
}
}
open func applicationWillEnterForeground(_ application: UIApplication) {
if shouldShowPasscode(),
let backgroundDuration = self.backgroundTimestamp?.timeIntervalSinceNow,
abs(backgroundDuration) > backgroundTimeout {
lockScreen()
}
}
open func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
SBAPermissionsManager.shared.appDidRegister(forNotifications: notificationSettings)
}
open func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
if identifier == kBackgroundSessionIdentifier {
SBABridgeManager.restoreBackgroundSession(identifier, completionHandler: completionHandler)
}
}
// MARK: Lock orientation to portrait by default
open var defaultOrientationLock: UIInterfaceOrientationMask {
return .portrait
}
open func resetOrientation() {
orientationLock = nil
}
var orientationLock: UIInterfaceOrientationMask?
open func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return orientationLock ?? defaultOrientationLock
}
// MARK: Flag for running active taskViewController
open var disablePasscodeLock: Bool = false
// ------------------------------------------------
// MARK: Default setup
// ------------------------------------------------
/**
Bridge info used for setting up this study. By default, this is defined in a BridgeInfo.plist
but the inheriting AppDelegate subclass can override this to set a different source.
*/
open var bridgeInfo: SBABridgeInfo {
return _bridgeInfo
}
private let _bridgeInfo: SBABridgeInfo = SBAInfoManager.shared
/**
A wrapper object for the current user. By default, this class will instantiate a singleton for
the current user that implements SBAUser.
*/
open var currentUser: SBAUserWrapper {
return _currentUser
}
private let _currentUser = SBAUser.shared
/**
Called on launch. This will reset the keychain if the user's stored information
indicates that they are logged out. This is necessary b/c deleting the app and reinstalling
does not remove values stored in the keychain.
*/
open func resetUserDataIfLoggedOut() {
// If the user defaults keys all indicate logged out state
// and *not* in the middle of onboarding, then reset the user.
if !currentUser.isLoginVerified &&
(currentUser.onboardingStepIdentifier == nil) &&
!currentUser.isConsentVerified &&
!currentUser.isRegistered {
currentUser.resetStoredUserData()
}
}
// ------------------------------------------------
// MARK: RootViewController management
// ------------------------------------------------
/**
The root view controller for this app. By default, this is setup in `willFinishLaunchingWithOptions`
as the key window root view controller. This container view controller allows presenting
onboarding flow and/or a passcode modally while transitioning the underlying view controller
for the appropriate app state.
*/
open var rootViewController: SBARootViewController? {
return window?.rootViewController as? SBARootViewController
}
/**
Convenience method for setting up and displaying the appropriate view controller
for the current user state.
@param animated Should the transition be animated
*/
open func showAppropriateViewController(animated: Bool) {
let newState: SBARootViewControllerState = {
if (self.catastrophicStartupError != nil) {
return .catastrophicError
}
else if (self.currentUser.onboardingStepIdentifier != nil) {
return .signup
}
else if (self.currentUser.isLoginVerified) {
return .main
}
else {
return .studyOverview
}
}()
if (newState != self.rootViewController?.state) {
switch(newState) {
case .catastrophicError:
showCatastrophicStartupErrorViewController(animated: animated)
case .main:
showMainViewController(animated: animated)
case .signup:
showSignUpViewController(animated: animated)
case .studyOverview:
showStudyOverviewViewController(animated: animated)
default: break
}
}
continueOnboardingFlowIfNeeded()
}
/**
Convenience method for continuing an onboarding flow for reconsent or email verification.
*/
open func continueOnboardingFlowIfNeeded() {
if (self.currentUser.isLoginVerified && !self.currentUser.isConsentVerified) {
presentOnboarding(for: .reconsent)
}
else if (!self.currentUser.isLoginVerified &&
self.currentUser.isRegistered) &&
(self.rootViewController?.state == .studyOverview) {
// If this app uses the signup view, then let that view control the flow
presentOnboarding(for: .signup)
}
}
@available(*, unavailable, message:"Use `showStudyOverviewViewController(animated:)` instead.")
public final func showOnboardingViewController(animated: Bool) {
showStudyOverviewViewController(animated: animated)
}
/**
Method for showing the study overview (onboarding) for a user who is not signed in.
By default, this method looks for a storyboard named "StudyOverview" that is included
in the main bundle.
@param animated Should the transition be animated
*/
open func showStudyOverviewViewController(animated: Bool) {
// Check that not already showing onboarding
guard self.rootViewController?.state != .studyOverview else { return }
// Get the default storyboard
guard let storyboard = openStoryboard(SBAStudyOverviewStoryboardName),
let vc = storyboard.instantiateInitialViewController()
else {
assertionFailure("Failed to load onboarding storyboard. If default onboarding is used, the storyboard should be implemented at the app level.")
return
}
transition(toRootViewController: vc, state: .studyOverview, animated: animated)
}
open func showSignUpViewController(animated: Bool) {
// Check that not already showing sign up
guard self.rootViewController?.state != .signup else { return }
// Get the default storyboard
guard let storyboard = openStoryboard(SBASignUpStoryboardName),
let vc = storyboard.instantiateInitialViewController()
else {
showStudyOverviewViewController(animated: animated)
return
}
transition(toRootViewController: vc, state: .signup, animated: animated)
}
/**
Method for showing the main view controller for a user who signed in.
By default, this method looks for a storyboard named "Main" that is included
in the main bundle.
@param animated Should the transition be animated
*/
open func showMainViewController(animated: Bool) {
// Check that not already showing main
guard self.rootViewController?.state != .main else { return }
// Get the default storyboard
guard let storyboard = openStoryboard(SBAMainStoryboardName),
let vc = storyboard.instantiateInitialViewController()
else {
assertionFailure("Failed to load main storyboard. If default onboarding is used, the storyboard should be implemented at the app level.")
return
}
transition(toRootViewController: vc, state: .main, animated: animated)
}
/**
Convenience method for opening a storyboard
@param name Name of the storyboard to open (assumes main bundle)
@return Storyboard if found
*/
open func openStoryboard(_ name: String) -> UIStoryboard? {
return UIStoryboard(name: name, bundle: nil)
}
/**
Convenience method for transitioning to the given view controller as the main window
rootViewController.
@param viewController View controller to transition to
@param state State of the app
@param animated Should the transition be animated
*/
open func transition(toRootViewController viewController: UIViewController, state: SBARootViewControllerState, animated: Bool) {
guard let window = self.window, rootViewController?.state != state else { return }
if let root = self.rootViewController {
root.set(viewController: viewController, state: state, animated: animated)
}
else {
if (animated) {
UIView.transition(with: window,
duration: 0.6,
options: UIView.AnimationOptions.transitionCrossDissolve,
animations: {
window.rootViewController = viewController
},
completion: nil)
}
else {
window.rootViewController = viewController
}
}
}
/**
Convenience method for presenting a modal view controller.
*/
open func presentModalViewController(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?) {
guard let rootVC = self.window?.rootViewController else { return }
var topViewController: UIViewController = rootVC
while let presentedVC = topViewController.presentedViewController {
if presentedVC.modalPresentationStyle != .fullScreen {
presentedVC.dismiss(animated: false, completion: nil)
break
}
else {
topViewController = presentedVC
}
}
topViewController.present(viewController, animated: animated, completion: completion)
}
// ------------------------------------------------
// MARK: Onboarding
// ------------------------------------------------
private weak var onboardingViewController: UIViewController?
/**
Should the onboarding be displayed (or ignored)? By default, if there isn't a catasrophic error,
there isn't a lockscreen, and there isn't already an onboarding view controller then show it.
*/
open func shouldShowOnboarding() -> Bool {
return !self.hasCatastrophicError &&
(self.passcodeViewController == nil) &&
(self.onboardingViewController == nil)
}
/**
Get an instance of an onboarding manager for the given `SBAOnboardingTaskType`
By default, this assumes a json file named "Onboarding" (included in the main bundle) is used
to describe the onboarding for this application.
@param onboardingTaskType `SBAOnboardingTaskType` for which to get the manager. (Ingored by default)
*/
open func onboardingManager(for onboardingTaskType: SBAOnboardingTaskType) -> SBAOnboardingManager {
// By default, the onboarding manager returns an onboarding manager for
return SBAOnboardingManager(jsonNamed: SBAOnboardingJSONFilename)!
}
/**
Present onboarding flow for the given type. By default, this will present an SBATaskViewController
modally with the app delegate as the delegate for the view controller.
@param onboardingTaskType `SBAOnboardingTaskType` to present
*/
open func presentOnboarding(for onboardingTaskType: SBAOnboardingTaskType) {
guard shouldShowOnboarding() else { return }
let onboardingManager = self.onboardingManager(for: onboardingTaskType)
guard let taskViewController = onboardingManager.initializeTaskViewController(for: onboardingTaskType)
else {
assertionFailure("Failed to create an onboarding manager.")
return
}
// present the onboarding
taskViewController.delegate = self
self.onboardingViewController = taskViewController
self.presentModalViewController(taskViewController, animated: true, completion: nil)
}
// MARK: ORKTaskViewControllerDelegate
open func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
// Discard the registration information that has been gathered so far if not completed
if (reason != .completed) {
self.currentUser.resetStoredUserData()
}
// Show the appropriate view controller
showAppropriateViewController(animated: false)
// Hide the taskViewController
taskViewController.dismiss(animated: true, completion: nil)
self.onboardingViewController = nil
}
// ------------------------------------------------
// MARK: Catastrophic startup errors
// ------------------------------------------------
private var catastrophicStartupError: Error?
/**
Catastrophic Errors are errors from which the system cannot recover. By default,
this will display a screen that blocks all activity. The user is then asked to
update their app.
@param animated Should the transition be animated
*/
open func showCatastrophicStartupErrorViewController(animated: Bool) {
guard self.rootViewController?.state != .catastrophicError else { return }
// If we cannot open the catastrophic error view controller (for some reason)
// then this is a fatal error
guard let vc = SBACatastrophicErrorViewController.instantiateWithMessage(catastrophicErrorMessage) else {
fatalError(catastrophicErrorMessage)
}
// Present the view controller
transition(toRootViewController: vc, state: .catastrophicError, animated: animated)
}
/**
Is there a catastrophic error.
*/
public final var hasCatastrophicError: Bool {
return catastrophicStartupError != nil
}
/**
Register a catastrophic error. Once launch is complete, this will trigger showing
the error.
*/
public final func registerCatastrophicStartupError(_ error: Error) {
self.catastrophicStartupError = error
}
/**
The error message to display for a catastrophic error.
*/
open var catastrophicErrorMessage: String {
return catastrophicStartupError?.localizedDescription ??
Localization.localizedString("SBA_CATASTROPHIC_FAILURE_MESSAGE")
}
// ------------------------------------------------
// MARK: SBBBridgeErrorUIDelegate
// ------------------------------------------------
/**
Default implementation for handling a user who is not consented (because consent has been
revoked by the server).
*/
open func handleUserNotConsentedError(_ error: Error, sessionInfo: Any, networkManager: SBBNetworkManagerProtocol?) -> Bool {
currentUser.isConsentVerified = false
DispatchQueue.main.async {
if self.rootViewController?.state == .main {
self.continueOnboardingFlowIfNeeded()
}
}
return true
}
/**
Default implementation for handling an unsupported app version is to display a
catastrophic error.
*/
open func handleUnsupportedAppVersionError(_ error: Error, networkManager: SBBNetworkManagerProtocol?) -> Bool {
registerCatastrophicStartupError(error)
DispatchQueue.main.async {
if let _ = self.window?.rootViewController {
self.showCatastrophicStartupErrorViewController(animated: true)
}
}
return true
}
// ------------------------------------------------
// MARK: SBABridgeAppSDKDelegate
// ------------------------------------------------
/**
Default "main" resource bundle. This allows the application to specific a different bundle
for a given resource by overriding this method in the app delegate.
*/
@available(*, deprecated, message:"Use `resourceBundles` on `SBABridgeManager` instead.")
public final func resourceBundle() -> Bundle {
return Bundle.main
}
/**
Default path to a resource. This allows the application to specific fine-grain control over
where to search for a given resource. By default, this will look in the main bundle.
*/
@available(*, deprecated, message:"Use `resourceBundles` on `SBABridgeManager` instead.")
public final func path(forResource resourceName: String, ofType resourceType: String) -> String? {
return self.resourceBundle().path(forResource: resourceName, ofType: resourceType)
}
// ------------------------------------------------
// MARK: Passcode Display Handling
// ------------------------------------------------
private weak var passcodeViewController: UIViewController?
private var backgroundTimestamp: Date?
public var backgroundTimeout: TimeInterval = 5 * 60
/**
Is the passcode blocking?
*/
open func isShowingPasscode() -> Bool {
return (self.passcodeViewController != nil)
}
/**
Should the passcode be displayed. By default, if there isn't a catasrophic error,
the user is registered and there is a passcode in the keychain, then show it.
*/
open func shouldShowPasscode() -> Bool {
return !self.hasCatastrophicError &&
self.currentUser.isRegistered &&
(self.passcodeViewController == nil) &&
!self.disablePasscodeLock &&
!UIApplication.shared.isIdleTimerDisabled &&
ORKPasscodeViewController.isPasscodeStoredInKeychain()
}
private func instantiateViewControllerForPasscode() -> UIViewController? {
return ORKPasscodeViewController.passcodeAuthenticationViewController(withText: nil, delegate: self)
}
private func lockScreen() {
guard self.shouldShowPasscode(), let vc = instantiateViewControllerForPasscode() else {
return
}
window?.makeKeyAndVisible()
vc.modalPresentationStyle = .fullScreen
vc.modalTransitionStyle = .coverVertical
passcodeViewController = vc
presentModalViewController(vc, animated: false, completion: nil)
}
private func dismissPasscodeViewController() {
// Onboarding flow is shown modally (so that the participant can cancel it
// and return to the study overview). Because of this, the lock screen must be dismissed
// BEFORE the onboarding is presented.
self.showAppropriateViewController(animated: false)
self.passcodeViewController?.presentingViewController?.dismiss(animated: true) {
self.continueOnboardingFlowIfNeeded()
}
self.passcodeViewController = nil
}
private func resetPasscode() {
// reset the user and sign them out of bridge
SBABridgeManager.signOut(completion: nil)
self.currentUser.resetStoredUserData()
// then dismiss the passcode view controller
dismissPasscodeViewController()
}
// MARK: ORKPasscodeDelegate
open func passcodeViewControllerDidFinish(withSuccess viewController: UIViewController) {
dismissPasscodeViewController()
}
open func passcodeViewControllerDidFailAuthentication(_ viewController: UIViewController) {
// Do nothing in default implementation
}
open func passcodeViewControllerForgotPasscodeTapped(_ viewController: UIViewController) {
let title = Localization.localizedString("SBA_RESET_PASSCODE_TITLE")
let message = Localization.localizedString("SBA_RESET_PASSCODE_MESSAGE")
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: Localization.buttonCancel(), style: .cancel, handler: nil)
alert.addAction(cancelAction)
let logoutAction = UIAlertAction(title: Localization.localizedString("SBA_LOGOUT"), style: .destructive, handler: { _ in
self.resetPasscode()
})
alert.addAction(logoutAction)
viewController.present(alert, animated: true, completion: nil)
}
}
|
bsd-3-clause
|
ccb4e5e15e75af7da74dfb36f9709af0
| 39.810924 | 159 | 0.655685 | 5.629637 | false | false | false | false |
away4m/Vendors
|
Vendors/Extensions/String.swift
|
1
|
82533
|
//
// String.swift
// Pods
//
// Created by Admin on 11/24/16.
//
//
#if canImport(Foundation)
import Foundation
#endif
#if canImport(UIKit)
import UIKit
#endif
#if canImport(Cocoa)
import Cocoa
#endif
#if canImport(CoreGraphics)
import CoreGraphics
#endif
public extension StringProtocol where Index == String.Index {
/// SwifterSwift: The longest common suffix.
///
/// "Hello world!".commonSuffix(with: "It's cold!") = "ld!"
///
/// - Parameters:
/// - Parameter aString: The string with which to compare the receiver.
/// - Parameter options: Options for the comparison.
/// - Returns: The longest common suffix of the receiver and the given String
public func commonSuffix<T: StringProtocol>(with aString: T, options: String.CompareOptions = []) -> String {
let reversedSuffix = String(reversed()).commonPrefix(with: String(aString.reversed()), options: options)
return String(reversedSuffix.reversed())
}
}
public extension String {
#if canImport(Foundation)
/// SwifterSwift: String decoded from base64 (if applicable).
///
/// "SGVsbG8gV29ybGQh".base64Decoded = Optional("Hello World!")
///
public var base64Decoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
guard let decodedData = Data(base64Encoded: self) else { return nil }
return String(data: decodedData, encoding: .utf8)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: String encoded in base64 (if applicable).
///
/// "Hello World!".base64Encoded -> Optional("SGVsbG8gV29ybGQh")
///
public var base64Encoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
let plainData = data(using: .utf8)
return plainData?.base64EncodedString()
}
#endif
/// SwifterSwift: Array of characters of a string.
///
public var charactersArray: [Character] {
return Array(self)
}
#if canImport(Foundation)
/// SwifterSwift: CamelCase of string.
///
/// "sOme vAriable naMe".camelCased -> "someVariableName"
///
public var camelCased: String {
let source = lowercased()
let first = source[..<source.index(after: source.startIndex)]
if source.contains(" ") {
let connected = source.capitalized.replacingOccurrences(of: " ", with: "")
let camel = connected.replacingOccurrences(of: "\n", with: "")
let rest = String(camel.dropFirst())
return first + rest
}
let rest = String(source.dropFirst())
return first + rest
}
#endif
/// SwifterSwift: Check if string contains one or more emojis.
///
/// "Hello 😀".containEmoji -> true
///
public var containEmoji: Bool {
// http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
for scalar in unicodeScalars {
switch scalar.value {
case 0x3030, 0x00AE, 0x00A9, // Special Characters
0x1D000 ... 0x1F77F, // Emoticons
0x2100 ... 0x27BF, // Misc symbols and Dingbats
0xFE00 ... 0xFE0F, // Variation Selectors
0x1F900 ... 0x1F9FF: // Supplemental Symbols and Pictographs
return true
default:
continue
}
}
return false
}
/// SwifterSwift: First character of string (if applicable).
///
/// "Hello".firstCharacterAsString -> Optional("H")
/// "".firstCharacterAsString -> nil
///
public var firstCharacterAsString: String? {
guard let first = self.first else { return nil }
return String(first)
}
#if canImport(Foundation)
/// SwifterSwift: Check if string contains one or more letters.
///
/// "123abc".hasLetters -> true
/// "123".hasLetters -> false
///
public var hasLetters: Bool {
return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string contains one or more numbers.
///
/// "abcd".hasNumbers -> false
/// "123abc".hasNumbers -> true
///
public var hasNumbers: Bool {
return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string contains only letters.
///
/// "abc".isAlphabetic -> true
/// "123abc".isAlphabetic -> false
///
public var isAlphabetic: Bool {
let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
return hasLetters && !hasNumbers
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string contains at least one letter and one number.
///
/// // useful for passwords
/// "123abc".isAlphaNumeric -> true
/// "abc".isAlphaNumeric -> false
///
public var isAlphaNumeric: Bool {
let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
let comps = components(separatedBy: .alphanumerics)
return comps.joined(separator: "").isEmpty && hasLetters && hasNumbers
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is valid email format.
///
/// - Note: Note that this property does not validate the email address against an email server. It merely attempts to determine whether its format is suitable for an email address.
///
/// "[email protected]".isValidEmail -> true
///
public var isValidEmail: Bool {
// http://emailregex.com/
let regex = "^(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$"
return range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid URL.
///
/// "https://google.com".isValidUrl -> true
///
public var isValidUrl: Bool {
return URL(string: self) != nil
}
#endif
/// SwifterSwift: Check if string is a valid schemed URL.
///
/// "https://google.com".
public var escapedForXML: String {
// & needs to go first, otherwise other replacements will be replaced again
let htmlEscapes = [
("&", "&"),
("\"", """),
("'", "'"),
(">", ">"),
("<", "<"),
]
var newString = self
for (key, value) in htmlEscapes {
newString = newString.replacingOccurrences(of: key, with: value)
}
return newString
}
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid schemed URL.
///
/// "https://google.com".isValidSchemedUrl -> true
/// "google.com".isValidSchemedUrl -> false
///
public var isValidSchemedUrl: Bool {
guard let url = URL(string: self) else { return false }
return url.scheme != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid https URL.
///
/// "https://google.com".isValidHttpsUrl -> true
///
public var isValidHttpsUrl: Bool {
guard let url = URL(string: self) else { return false }
return url.scheme == "https"
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid http URL.
///
/// "http://google.com".isValidHttpUrl -> true
///
public var isValidHttpUrl: Bool {
guard let url = URL(string: self) else { return false }
return url.scheme == "http"
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid file URL.
///
/// "file://Documents/file.txt".isValidFileUrl -> true
///
public var isValidFileUrl: Bool {
return URL(string: self)?.isFileURL ?? false
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid Swift number.
///
/// Note:
/// In North America, "." is the decimal separator,
/// while in many parts of Europe "," is used,
///
/// "123".isNumeric -> true
/// "1.3".isNumeric -> true (en_US)
/// "1,3".isNumeric -> true (fr_FR)
/// "abc".isNumeric -> false
///
public var isNumeric: Bool {
let scanner = Scanner(string: self)
scanner.locale = NSLocale.current
return scanner.scanDecimal(nil) && scanner.isAtEnd
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string only contains digits.
///
/// "123".isDigits -> true
/// "1.3".isDigits -> false
/// "abc".isDigits -> false
///
public var isDigits: Bool {
return CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: self))
}
#endif
/// SwifterSwift: Last character of string (if applicable).
///
/// "Hello".lastCharacterAsString -> Optional("o")
/// "".lastCharacterAsString -> nil
///
public var lastCharacterAsString: String? {
guard let last = self.last else { return nil }
return String(last)
}
#if canImport(Foundation)
/// SwifterSwift: Latinized string.
///
/// "Hèllö Wórld!".latinized -> "Hello World!"
///
public var latinized: String {
return folding(options: .diacriticInsensitive, locale: Locale.current)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Bool value from string (if applicable).
///
/// "1".bool -> true
/// "False".bool -> false
/// "Hello".bool = nil
///
public var bool: Bool? {
let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
if selfLowercased == "true" || selfLowercased == "1" {
return true
} else if selfLowercased == "false" || selfLowercased == "0" {
return false
}
return nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Date object from "yyyy-MM-dd" formatted string.
///
/// "2007-06-29".date -> Optional(Date)
///
public var date: Date? {
let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd"
return formatter.date(from: selfLowercased)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Date object from "yyyy-MM-dd HH:mm:ss" formatted string.
///
/// "2007-06-29 14:23:09".dateTime -> Optional(Date)
///
public var dateTime: Date? {
let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.date(from: selfLowercased)
}
#endif
/// SwifterSwift: Integer value from string (if applicable).
///
/// "101".int -> 101
///
public var int: Int? {
return Int(self)
}
/// SwifterSwift: Lorem ipsum string of given length.
///
/// - Parameter length: number of characters to limit lorem ipsum to (default is 445 - full lorem ipsum).
/// - Returns: Lorem ipsum dolor sit amet... string.
public static func loremIpsum(ofLength length: Int = 445) -> String {
guard length > 0 else { return "" }
// https://www.lipsum.com/
let loremIpsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
if loremIpsum.count > length {
return String(loremIpsum[loremIpsum.startIndex ..< loremIpsum.index(loremIpsum.startIndex, offsetBy: length)])
}
return loremIpsum
}
#if canImport(Foundation)
/// SwifterSwift: URL from string (if applicable).
///
/// "https://google.com".url -> URL(string: "https://google.com")
/// "not url".url -> nil
///
public var url: URL? {
return URL(string: self)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: String with no spaces or new lines in beginning and end.
///
/// " hello \n".trimmed -> "hello"
///
public var trimmed: String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Readable string from a URL string.
///
/// "it's%20easy%20to%20decode%20strings".urlDecoded -> "it's easy to decode strings"
///
public var urlDecoded: String {
return removingPercentEncoding ?? self
}
#endif
#if canImport(Foundation)
/// SwifterSwift: URL escaped string.
///
/// "it's easy to encode strings".urlEncoded -> "it's%20easy%20to%20encode%20strings"
///
public var urlEncoded: String {
return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
#endif
#if canImport(Foundation)
/// SwifterSwift: String without spaces and new lines.
///
/// " \n Swifter \n Swift ".withoutSpacesAndNewLines -> "SwifterSwift"
///
public var withoutSpacesAndNewLines: String {
return replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "")
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if the given string contains only white spaces
public var isWhitespace: Bool {
return trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
#endif
#if os(iOS) || os(tvOS)
/// SwifterSwift: Check if the given string spelled correctly
public var isSpelledCorrectly: Bool {
let checker = UITextChecker()
let range = NSRange(location: 0, length: utf16.count)
let misspelledRange = checker.rangeOfMisspelledWord(in: self, range: range, startingAt: 0, wrap: false, language: Locale.preferredLanguages.first ?? "en")
return misspelledRange.location == NSNotFound
}
#endif
public func stripHTML() -> String? {
return data?.attributedString?.string
}
/// The collection of Latin letters and Arabic digits or a text constructed from this collection.
public enum RandomStringType {
/// The character set with 36 (`A-Z+0-9`, case insensitive) or 62 (`A-Z+a-z+0-9`, case-sensitive) alphanumeric characters.
case alphanumeric(caseSensitive: Bool)
/// The character set with 26 (`A-Z`, case insensitive) or 52 (`A-Z+a-z`, case-sensitive) Latin letters.
case alphabetic(caseSensitive: Bool)
/// The character set with 10 (`0-9`) Arabic digits.
case numeric
fileprivate var characterSet: String {
switch self {
case .alphanumeric(true): return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
case .alphanumeric(false): return "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
case .alphabetic(true): return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
case .alphabetic(false): return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
case .numeric: return "0123456789"
}
}
}
/**
Creates a new string with randomized characters.
- parameter random: The desired randomized character set.
- parameter length: The desired length of a string.
- parameter nonRepeating: The boolean value that determines whether characters in the initialized can or cannot be repeated. The default value is `false`. If `true` and length is greater than number of characters in selected character set, then string with maximum allowed length will be produced.
- returns: The new string with randomized characters.
*/
public init(random: RandomStringType, length: Int, nonRepeating: Bool = false) {
var letters = random.characterSet
var length = length
if length > random.characterSet.count, nonRepeating {
length = random.characterSet.count
}
var string = ""
while string.count < length {
let index = letters.characters.index(letters.startIndex, offsetBy: Int(arc4random_uniform(UInt32(letters.count))))
let letter = letters[index]
string.append(letter)
if nonRepeating {
letters.remove(at: index)
}
}
self = string
}
/**
Creates a new string with a path for the specified directories in the user's home directory.
- parameter directory: The location of a variety of directories
- note: The directory returned by this method may not exist. This method simply gives you the appropriate location for the requested directory. Depending on the application’s needs, it may be up to the developer to create the appropriate directory and any in between.
- returns: The string with a path for the specified directories in the user's home directory or `nil` if a path cannot be found.
*/
public init?(path directory: FileManager.SearchPathDirectory) {
guard let path = NSSearchPathForDirectoriesInDomains(directory, .userDomainMask, true).first else { return nil }
self = path
}
/// Returns a new string made by first letter of the each String word.
public var initials: String? {
return components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
.map { $0.substring(to: index(after: startIndex)) }
.joined()
}
/// Returns an array of strings where elements are the String non-empty lines.
public var nonEmptyLines: [String] {
return lines().filter { !$0.trimmed.isEmpty }
}
/// Returns a data created from the value treated as a hexadecimal string.
public var dataFromHexadecimalString: Data? {
guard let regex = try? NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive) else { return nil }
var data = Data(capacity: count / 2)
regex.enumerateMatches(in: self, options: [], range: NSRange(location: 0, length: count)) { match, _, _ in
guard let match = match else { return }
let byteString = (self as NSString).substring(with: match.range)
guard var num = UInt8(byteString, radix: 16) else { return }
data.append(&num, count: 1)
}
return data
}
/// Returns the number of occurrences of a String into self.
///
/// - Parameter string: String of occurrences.
/// - Returns: Returns the number of occurrences of a String into self.
public func occurrences(of string: String, caseSensitive: Bool = true) -> Int {
var string = string
if !caseSensitive {
string = string.lowercased()
}
return lowercased().components(separatedBy: string).count - 1
}
/// Returns true if the String has at least one uppercase chatacter, otherwise false.
///
/// - returns: Returns true if the String has at least one uppercase chatacter, otherwise false.
public func hasUppercasedCharacters() -> Bool {
var found = false
for character in unicodeScalars {
if CharacterSet.uppercaseLetters.contains(character) {
found = true
break
}
}
return found
}
/// Returns true if the String has at least one lowercase chatacter, otherwise false.
///
/// - returns: Returns true if the String has at least one lowercase chatacter, otherwise false.
public func hasLowercasedCharacters() -> Bool {
var found = false
for character in unicodeScalars {
if CharacterSet.lowercaseLetters.contains(character) {
found = true
break
}
}
return found
}
// Check if string starts with substring.
///
/// - Parameters:
/// - suffix: substring to search if string starts with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string starts with substring.
public func start(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
// Check if string is https URL.
public var isHttpsUrl: Bool {
guard start(with: "https://".lowercased()) else {
return false
}
return URL(string: self) != nil
}
// Check if string is http URL.
public var isHttpUrl: Bool {
guard start(with: "http://".lowercased()) else {
return false
}
return URL(string: self) != nil
}
/**
Returns an upper camel case version of the string.
Here’s an example of transforming a string to all upper camel case letters.
let variable = "find way home"
print(variable.camelCased)
// Prints "FindWayHome"
*/
public var upperCamelCased: String {
return capitalized.components(separatedBy: .whitespacesAndNewlines).joined()
}
// initialize string with an array of UInt8 integer values
public init?(utf8chars: [UInt8]) {
var str = ""
var generator = utf8chars.makeIterator()
var utf8 = UTF8()
var done = false
while !done {
let r = utf8.decode(&generator)
switch r {
case .emptyInput:
done = true
case let .scalarValue(val):
str.append(Character(val))
case .error:
return nil
}
}
self = str
}
/// Converts self to an unsigned byte array.
public var bytes: [UInt8] {
return utf8.map { $0 }
}
// composed count takes into account emojis that are represented by character sequences
public var composedCount: Int {
var count = 0
enumerateSubstrings(in: startIndex ..< endIndex, options: .byComposedCharacterSequences) { _, _, _, _ in
count += 1
}
return count
}
// encode string for a url query parameter value
public func encodingForURLQueryValue() -> String? {
let characterSet = NSMutableCharacterSet.alphanumeric()
characterSet.addCharacters(in: "-._~")
return addingPercentEncoding(withAllowedCharacters: characterSet as CharacterSet)
}
public func getPathNameExtension() -> String {
return (self as NSString).pathExtension
}
public func maxFontSize(_ font: UIFont, boundingWidth: CGFloat, maxHeight: CGFloat) -> CGFloat {
let textHeight = labelHeightWithConstrainedWidth(boundingWidth, font: font) // self.height(font: font, boundingWidth: boundingWidth)
if textHeight < maxHeight {
return floor(textHeight)
} else {
let newFont = font.withSize(font.pointSize - 1)
return maxFontSize(newFont, boundingWidth: boundingWidth, maxHeight: maxHeight)
}
}
public func labelHeightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat {
if isEmpty {
return 0
}
let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: 0))
label.font = font
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.text = self
label.sizeToFit()
label.layoutIfNeeded()
return ceil(label.frame.height)
}
// get index of substring in string, or -1 if not contained in other string
public func indexOf(_ target: String) -> Int {
let range = self.range(of: target)
if let range = range {
return characters.distance(from: startIndex, to: range.lowerBound)
} else {
return -1
}
}
// check if digits only (if empty string returns true)
public func isDigitsOnly() -> Bool {
let digits = CharacterSet.decimalDigits
var isDigitsOnly = true
for char in unicodeScalars {
if !digits.contains(UnicodeScalar(char.value)!) {
// character not alpha
isDigitsOnly = false
break
}
}
return isDigitsOnly
}
// check if letters only (if empty string returns true)
public func isValidName() -> Bool {
let letters = CharacterSet.letters
let punctuation = CharacterSet.punctuationCharacters
var isValidName = true
for char in unicodeScalars {
if !letters.contains(UnicodeScalar(char.value)!), !punctuation.contains(UnicodeScalar(char.value)!) {
// character not alpha
isValidName = false
break
}
}
return isValidName
}
public func isAlphaPunctuationWhiteSpace() -> Bool {
let letters = CharacterSet.letters
let punctuation = CharacterSet.punctuationCharacters
let whitespace = CharacterSet.whitespaces
var isAlphaPunctuationWhiteSpace = true
for char in unicodeScalars {
if !letters.contains(UnicodeScalar(char.value)!), !punctuation.contains(UnicodeScalar(char.value)!), !whitespace.contains(UnicodeScalar(char.value)!) {
// character not letter or whitespace
isAlphaPunctuationWhiteSpace = false
break
}
}
return isAlphaPunctuationWhiteSpace
}
/// Remove double or more duplicated spaces.
///
/// - returns: Remove double or more duplicated spaces.
public func removeExtraSpaces() -> String {
let squashed = replacingOccurrences(of: "[ ]+", with: " ", options: .regularExpression, range: nil)
#if os(Linux) // Caused by a Linux bug with emoji.
return squashed
#else
return squashed.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
#endif
}
public func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return boundingBox.height
}
public func widthWithConstrainedHeight(_ height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.width)
}
public func replace(_ target: String, withString: String) -> String {
return replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
/**
Replaces all occurences of the pattern on self in-place.
Examples:
```
"hello".regexInPlace("[aeiou]", "*") // "h*ll*"
"hello".regexInPlace("([aeiou])", "<$1>") // "h<e>ll<o>"
```
*/
public mutating func formRegex(_ pattern: String, _ replacement: String) {
do {
let expression = try NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: characters.count)
self = expression.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replacement)
} catch { return }
}
/**
Returns a string containing replacements for all pattern matches.
Examples:
```
"hello".regex("[aeiou]", "*") // "h*ll*"
"hello".regex("([aeiou])", "<$1>") // "h<e>ll<o>"
```
*/
public func regex(_ pattern: String, _ replacement: String) -> String {
var replacementString = self
replacementString.formRegex(pattern, replacement)
return replacementString
}
/**
Replaces pattern-matched strings, operated upon by a closure, on self in-place.
- parameter pattern: The pattern to match against.
- parameter matches: The closure in which to handle matched strings.
Example:
```
"hello".regexInPlace(".") {
let s = $0.unicodeScalars
let v = s[s.startIndex].value
return "\(v) "
} // "104 101 108 108 111 "
*/
public mutating func formRegex(_ pattern: String, _ matches: (String) -> String) {
let expression: NSRegularExpression
do {
expression = try NSRegularExpression(pattern: "(\(pattern))", options: [])
} catch {
print("regex error: \(error)")
return
}
let range = NSMakeRange(0, characters.count)
var startOffset = 0
let results = expression.matches(in: self, options: [], range: range)
for result in results {
var endOffset = startOffset
for i in 1 ..< result.numberOfRanges {
var resultRange = result.range
resultRange.location += startOffset
let startIndex = index(self.startIndex, offsetBy: resultRange.location)
let endIndex = index(self.startIndex, offsetBy: resultRange.location + resultRange.length)
let replacementRange = startIndex ..< endIndex
let match = expression.replacementString(for: result, in: self, offset: startOffset, template: "$\(i)")
let replacement = matches(match)
replaceSubrange(replacementRange, with: replacement)
endOffset += replacement.characters.count - resultRange.length
}
startOffset = endOffset
}
}
/**
Returns a string with pattern-matched strings, operated upon by a closure.
- parameter pattern: The pattern to match against.
- parameter matches: The closure in which to handle matched strings.
- returns: String containing replacements for the matched pattern.
Example:
```
"hello".regex(".") {
let s = $0.unicodeScalars
let v = s[s.startIndex].value
return "\(v) "
} // "104 101 108 108 111 "
*/
public func regex(_ pattern: String, _ matches: (String) -> String) -> String {
var replacementString = self
replacementString.formRegex(pattern, matches)
return replacementString
}
/// Returns if self is a valid UUID for APNS (Apple Push Notification System) or not.
///
/// - Returns: Returns if self is a valid UUID for APNS (Apple Push Notification System) or not.
public func isUUIDForAPNS() -> Bool {
do {
let regex: NSRegularExpression = try NSRegularExpression(pattern: "^[0-9a-f]{32}$", options: .caseInsensitive)
let matches: Int = regex.numberOfMatches(in: self, options: .reportCompletion, range: NSRange(location: 0, length: count))
return matches == 1
} catch {
return false
}
}
/// Returns if self is a valid UUID or not.
///
/// - Returns: Returns if self is a valid UUID or not.
public func isUUID() -> Bool {
do {
let regex: NSRegularExpression = try NSRegularExpression(pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", options: .caseInsensitive)
let matches: Int = regex.numberOfMatches(in: self, options: .reportCompletion, range: NSRange(location: 0, length: count))
return matches == 1
} catch {
return false
}
}
/// Returns the reversed String.
///
/// - parameter preserveFormat: If set to true preserve the String format.
/// The default value is false.
/// **Example:**
/// "Let's try this function?" ->
/// "?noitcnuf siht yrt S'tel"
///
/// - returns: Returns the reversed String.
public func reversed(preserveFormat: Bool = false) -> String {
guard !characters.isEmpty else {
return ""
}
var reversed = String(removeExtraSpaces().characters.reversed())
if !preserveFormat {
return reversed
}
let words = reversed.components(separatedBy: " ").filter { $0 != "" }
reversed.removeAll()
for word in words {
if let char = word.unicodeScalars.first {
if CharacterSet.uppercaseLetters.contains(char) {
reversed += word.lowercased().uppercasedFirst() + " "
} else {
reversed += word.lowercased() + " "
}
} else {
reversed += word.lowercased() + " "
}
}
return reversed
}
/// Returns string with the first character uppercased.
///
/// - returns: Returns string with the first character uppercased.
public func uppercasedFirst() -> String {
return String(characters.prefix(1)).uppercased() + String(characters.dropFirst())
}
/// Returns string with the first character lowercased.
///
/// - returns: Returns string with the first character lowercased.
public func lowercasedFirst() -> String {
return String(characters.prefix(1)).lowercased() + String(characters.dropFirst())
}
// Array of strings separated by given string.
///
/// - Parameter separator: separator to split string by.
/// - Returns: array of strings separated by given string.
public func splited(by separator: Character) -> [String] {
return characters.split { $0 == separator }.map(String.init)
}
/**
Truncates the string to length characters, optionally appending a trailing string. If the string is shorter
than the required length, then this function is a non-op.
- parameter length: The length of string required.
- parameter trailing: An optional addition to the end of the string (increasing "length"), such as ellipsis.
- returns: The truncated string.
Examples:
```
"hello there".truncated(to: 5) // "hello"
"hello there".truncated(to: 5, trailing: "...") // "hello..."
```
*/
public func truncated(to length: Int, trailing: String = "") -> String {
guard !characters.isEmpty, characters.count > length else { return self }
return substring(to: index(startIndex, offsetBy: length)) + trailing
}
public mutating func truncate(to length: Int, trailing: String = "") {
self = truncated(to: length, trailing: trailing)
}
/// Get the character at a given index.
///
/// - Parameter index: The index.
/// - Returns: Returns the character at a given index, starts from 0.
public func character(at index: Int) -> Character {
return self[self.characters.index(self.startIndex, offsetBy: index)]
}
/// Creates a substring with a given range.
///
/// - Parameter range: The range.
/// - Returns: Returns the string between the range.
public func substring(with range: Range<Int>) -> String {
let start = characters.index(startIndex, offsetBy: range.lowerBound)
let end = characters.index(startIndex, offsetBy: Swift.min(characters.count - 1, range.upperBound))
return substring(with: start ..< end)
}
/**
Convert an NSRange to a Range. There is still a mismatch between the regular expression libraries
and NSString/String. This makes it easier to convert between the two. Using this allows complex
strings (including emoji, regonial indicattors, etc.) to be manipulated without having to resort
to NSString instances.
Note that it may not always be possible to convert from an NSRange as they are not exactly the same.
Taken from:
http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index
- parameter nsRange: The NSRange instance to covert to a Range.
- returns: The Range, if it was possible to convert. Otherwise nil.
*/
public func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from ..< to
}
/// Returns the index of the given character.
///
/// - Parameter character: The character to search.
/// - Returns: Returns the index of the given character, -1 if not found.
public func index(of character: Character) -> Int {
if let index = self.characters.index(of: character) {
return characters.distance(from: startIndex, to: index)
}
return -1
}
fileprivate var vowels: [String] {
return ["a", "e", "i", "o", "u"]
}
fileprivate var consonants: [String] {
return ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"]
}
/**
Convenience property for a `String`'s length
*/
// public var length: Int {
// return characters.count
// }
/**
An Array of the individual substrings composing `self`. Read-only.
*/
public var chars: [String] {
return Array(characters).map({ String($0) })
}
/**
A Set<String> of the unique characters in `self`.
*/
public var charSet: Set<String> {
return Set(characters.map { String($0) })
}
public var firstCharacter: String? {
return chars.first
}
/// SwifterSwift: Last character of string (if applicable).
public var lastCharacter: String? {
guard let last = characters.last else {
return nil
}
return String(last)
}
public func random() -> Character {
let randomIndex = Int(arc4random_uniform(UInt32(count)))
return characters[self.characters.index(self.startIndex, offsetBy: randomIndex)]
}
/// Percent escapes values to be added to a URL query as specified in RFC 3986
///
/// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Returns percent-escaped string.
public func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
return addingPercentEncoding(withAllowedCharacters: allowedCharacters)
}
/// Gets the individual characters and puts them in an array as Strings.
var array: [String] {
return description.characters.map { String($0) }
}
// Double value from string (if applicable).
public var double: Double? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Double
}
// Double value from string (if applicable).
public var doubleValue: Double {
return NSString(string: self).doubleValue
}
// Float value from string (if applicable).
public var float: Float? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float
}
/// Returns the Float value
public var floatValue: Float {
return NSString(string: self).floatValue
}
// Float32 value from string (if applicable).
public var float32: Float32? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float32
}
// Float64 value from string (if applicable).
public var float64: Float64? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float64
}
/// Returns the Int value
public var intValue: Int {
return Int(NSString(string: self).intValue)
}
// Int16 value from string (if applicable).
public var int16: Int16? {
return Int16(self)
}
// Int32 value from string (if applicable).
public var int32: Int32? {
return Int32(self)
}
// Int64 value from string (if applicable).
public var int64: Int64? {
return Int64(self)
}
// Int8 value from string (if applicable).
public var int8: Int8? {
return Int8(self)
}
/// Convert self to a Data.
public var data: Data? {
return data(using: .utf8)
}
/// Returns a new string containing the characters of the String from the one at a given index to the end.
///
/// - Parameter index: The index.
/// - Returns: Returns the substring from index.
public func substring(from index: Int) -> String {
return substring(from: characters.index(startIndex, offsetBy: index))
}
/// Creates a substring from the given character.
///
/// - Parameter character: The character.
/// - Returns: Returns the substring from character.
public func substring(from character: Character) -> String {
let index: Int = self.index(of: character) + 1
guard index > -1 else {
return ""
}
return substring(from: index)
}
/// Returns a new string containing the characters of the String up to, but not including, the one at a given index.
///
/// - Parameter index: The index.
/// - Returns: Returns the substring to index.
public func substring(to index: Int) -> String {
var _index = max(0, min(index, count - 1))
return substring(to: characters.index(startIndex, offsetBy: _index))
}
/// Creates a substring to the given character.
///
/// - Parameter character: The character.
/// - Returns: Returns the substring to character.
public func substring(to character: Character) -> String {
let index: Int = self.index(of: character)
guard index > -1 else {
return ""
}
return substring(to: index)
}
// // Subscript string with index.
// ///
// /// - Parameter i: index.
// public subscript(i: Int) -> String? {
// guard i >= 0 && i < length else {
// return nil
// }
// return String(self[index(startIndex, offsetBy: i)])
// }
/// Creates a substring with a given range.
///
/// - Parameter range: The range.
/// - Returns: Returns the string between the range.
public func substring(with range: CountableClosedRange<Int>) -> String {
return substring(with: Range(uncheckedBounds: (lower: range.lowerBound, upper: range.upperBound + 1)))
}
// Subscript string within a half-open range.
///
/// - Parameter range: Half-open range.
public subscript(range: CountableRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else {
return nil
}
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else {
return nil
}
return String(self[lowerIndex ..< upperIndex])
}
// Subscript string within a closed range.
///
/// - Parameter range: Closed range.
public subscript(range: ClosedRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else {
return nil
}
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else {
return nil
}
return String(self[lowerIndex ..< upperIndex])
}
public subscript(r: Range<Int>) -> String {
let startIndex = characters.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = characters.index(self.startIndex, offsetBy: r.upperBound - 1)
return String(self[startIndex ..< endIndex])
}
// Check if string contains one or more instance of substring.
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string contains one or more instance of substring.
public func contain(_ string: String, caseSensitive: Bool = true) -> Bool {
// if !caseSensitive {
// return range(of: string, options: .caseInsensitive) != nil
// }
// return range(of: string) != nil
if #available(iOS 9.0, *) {
return caseSensitive ? localizedStandardContains(string) : localizedCaseInsensitiveContains(string)
}
return range(of: string, options: [.caseInsensitive, .diacriticInsensitive], locale: .current) != nil
}
// Check if string ends with substring.
///
/// - Parameters:
/// - suffix: substring to search if string ends with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string ends with substring.
public func end(with suffix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasSuffix(suffix.lowercased())
}
return hasSuffix(suffix)
}
/**
Convert argb string to rgba string.
*/
public func argb2rgba() -> String? {
guard hasPrefix("#") else {
return nil
}
let hexString: String = substring(from: characters.index(startIndex, offsetBy: 1))
switch hexString.count {
case 4:
return "#"
+ hexString.substring(from: characters.index(startIndex, offsetBy: 1))
+ hexString.substring(to: characters.index(startIndex, offsetBy: 1))
case 8:
return "#"
+ hexString.substring(from: characters.index(startIndex, offsetBy: 2))
+ hexString.substring(to: characters.index(startIndex, offsetBy: 2))
default:
return nil
}
}
/// Converts self to an UUID APNS valid (No "<>" or "-" or spaces).
///
/// - Returns: Converts self to an UUID APNS valid (No "<>" or "-" or spaces).
public func readableUUID() -> String {
return trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "-", with: "")
}
/// Returns an array of String with all the hashtags in self.
///
/// - Returns: Returns an array of String with all the hashtags in self.
/// - Throws: Throws NSRegularExpression errors.
public func hashtags() -> [String] {
guard let detector = try? NSRegularExpression(pattern: "#(\\w+)", options: NSRegularExpression.Options.caseInsensitive) else {
return []
}
let hashtags = detector.matches(in: self, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSRange(location: 0, length: count)).map { $0 }
return hashtags.map(
{
(self as NSString).substring(with: $0.range(at: 1))
}
)
}
/// Returns an array of String with all the mentions in self.
///
/// - Returns: Returns an array of String with all the mentions in self.
/// - Throws: Throws NSRegularExpression errors.
public func mentions() -> [String] {
guard let detector = try? NSRegularExpression(pattern: "@(\\w+)", options: NSRegularExpression.Options.caseInsensitive) else {
return []
}
let mentions = detector.matches(in: self, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSRange(location: 0, length: count)).map { $0 }
return mentions.map(
{
(self as NSString).substring(with: $0.range(at: 1))
}
)
}
/// Returns an array of String with all the links in self.
///
/// - Returns: Returns an array of String with all the links in self.
/// - Throws: Throws NSDataDetector errors.
public func links() -> [String] {
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
return []
}
let links = detector.matches(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: count)).map { $0 }
return links.filter { link in
link.url != nil
}.map { link -> String in
link.url!.absoluteString
}
}
/// Returns an array of Date with all the dates in self.
///
/// - Returns: Returns an array of Date with all the date in self.
/// - Throws: Throws NSDataDetector errors.
public func dates() -> [Date] {
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue) else {
return []
}
let dates = detector.matches(in: self, options: NSRegularExpression.MatchingOptions.withTransparentBounds, range: NSRange(location: 0, length: count)).map { $0 }
return dates.filter { date in
date.date != nil
}.map { date -> Date in
date.date!
}
}
/// SwifterSwift: String by replacing part of string with another string.
///
/// - Parameters:
/// - substring: old substring to find and replace.
/// - newString: new string to insert in old string place.
/// - Returns: string after replacing substring with newString.
public func replacing(_ substring: String, with newString: String) -> String {
return replacingOccurrences(of: substring, with: newString)
}
}
// MARK: - Methods
public extension String {
#if canImport(Foundation)
/// Float value from string (if applicable).
///
/// - Parameter locale: Locale (default is Locale.current)
/// - Returns: Optional Float value from given string.
public func float(locale: Locale = .current) -> Float? {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.allowsFloats = true
return formatter.number(from: self)?.floatValue
}
#endif
#if canImport(Foundation)
/// Double value from string (if applicable).
///
/// - Parameter locale: Locale (default is Locale.current)
/// - Returns: Optional Double value from given string.
public func double(locale: Locale = .current) -> Double? {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.allowsFloats = true
return formatter.number(from: self)?.doubleValue
}
#endif
#if canImport(CoreGraphics) && canImport(Foundation)
/// CGFloat value from string (if applicable).
///
/// - Parameter locale: Locale (default is Locale.current)
/// - Returns: Optional CGFloat value from given string.
public func cgFloat(locale: Locale = .current) -> CGFloat? {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.allowsFloats = true
return formatter.number(from: self) as? CGFloat
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Array of strings separated by new lines.
///
/// "Hello\ntest".lines() -> ["Hello", "test"]
///
/// - Returns: Strings separated by new lines.
public func lines() -> [String] {
var result = [String]()
enumerateLines { line, _ in
result.append(line)
}
return result
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Returns a localized string, with an optional comment for translators.
///
/// "Hello world".localized -> Hallo Welt
///
public func localized(comment: String = "") -> String {
return NSLocalizedString(self, comment: comment)
}
#endif
/// SwifterSwift: The most common character in string.
///
/// "This is a test, since e is appearing everywhere e should be the common character".mostCommonCharacter() -> "e"
///
/// - Returns: The most common character.
public func mostCommonCharacter() -> Character? {
let mostCommon = withoutSpacesAndNewLines.reduce(into: [Character: Int]()) {
let count = $0[$1] ?? 0
$0[$1] = count + 1
}.max { $0.1 < $1.1 }?.0
return mostCommon
}
/// SwifterSwift: Array with unicodes for all characters in a string.
///
/// "SwifterSwift".unicodeArray -> [83, 119, 105, 102, 116, 101, 114, 83, 119, 105, 102, 116]
///
/// - Returns: The unicodes for all characters in a string.
public func unicodeArray() -> [Int] {
return unicodeScalars.map { $0.hashValue }
}
#if canImport(Foundation)
/// SwifterSwift: an array of all words in a string
///
/// "Swift is amazing".words() -> ["Swift", "is", "amazing"]
///
/// - Returns: The words contained in a string.
public func words() -> [String] {
// https://stackoverflow.com/questions/42822838
let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
let comps = components(separatedBy: chararacterSet)
return comps.filter { !$0.isEmpty }
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Count of words in a string.
///
/// "Swift is amazing".wordsCount() -> 3
///
/// - Returns: The count of words contained in a string.
public func wordCount() -> Int {
// https://stackoverflow.com/questions/42822838
let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
let comps = components(separatedBy: chararacterSet)
let words = comps.filter { !$0.isEmpty }
return words.count
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Transforms the string into a slug string.
///
/// "Swift is amazing".toSlug() -> "swift-is-amazing"
///
/// - Returns: The string in slug format.
public func toSlug() -> String {
let lowercased = self.lowercased()
let latinized = lowercased.latinized
let withDashes = latinized.replacingOccurrences(of: " ", with: "-")
let alphanumerics = NSCharacterSet.alphanumerics
var filtered = withDashes.filter {
guard String($0) != "-" else { return true }
guard String($0) != "&" else { return true }
return String($0).rangeOfCharacter(from: alphanumerics) != nil
}
while filtered.lastCharacterAsString == "-" {
filtered = String(filtered.dropLast())
}
while filtered.firstCharacterAsString == "-" {
filtered = String(filtered.dropFirst())
}
return filtered.replacingOccurrences(of: "--", with: "-")
}
#endif
// swiftlint:disable next identifier_name
/// SwifterSwift: Safely subscript string with index.
///
/// "Hello World!"[safe: 3] -> "l"
/// "Hello World!"[safe: 20] -> nil
///
/// - Parameter i: index.
public subscript(safe i: Int) -> Character? {
guard i >= 0, i < count else { return nil }
return self[index(startIndex, offsetBy: i)]
}
/// SwifterSwift: Safely subscript string within a half-open range.
///
/// "Hello World!"[safe: 6..<11] -> "World"
/// "Hello World!"[safe: 21..<110] -> nil
///
/// - Parameter range: Half-open range.
public subscript(safe range: CountableRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil }
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else { return nil }
return String(self[lowerIndex ..< upperIndex])
}
/// SwifterSwift: Safely subscript string within a closed range.
///
/// "Hello World!"[safe: 6...11] -> "World!"
/// "Hello World!"[safe: 21...110] -> nil
///
/// - Parameter range: Closed range.
public subscript(safe range: ClosedRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil }
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else { return nil }
return String(self[lowerIndex ..< upperIndex])
}
#if os(iOS) || os(macOS)
/// SwifterSwift: Copy string to global pasteboard.
///
/// "SomeText".copyToPasteboard() // copies "SomeText" to pasteboard
///
public func copyToPasteboard() {
#if os(iOS)
UIPasteboard.general.string = self
#elseif os(macOS)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(self, forType: .string)
#endif
}
#endif
/// SwifterSwift: Converts string format to CamelCase.
///
/// var str = "sOme vaRiabLe Name"
/// str.camelize()
/// print(str) // prints "someVariableName"
///
public mutating func camelize() {
let source = lowercased()
let first = source[..<source.index(after: source.startIndex)]
if source.contains(" ") {
let connected = source.capitalized.replacingOccurrences(of: " ", with: "")
let camel = connected.replacingOccurrences(of: "\n", with: "")
let rest = String(camel.dropFirst())
self = first + rest
return
}
let rest = String(source.dropFirst())
self = first + rest
}
/// SwifterSwift: Check if string contains only unique characters.
///
public func hasUniqueCharacters() -> Bool {
guard count > 0 else { return false }
var uniqueChars = Set<String>()
for char in self {
if uniqueChars.contains(String(char)) { return false }
uniqueChars.insert(String(char))
}
return true
}
#if canImport(Foundation)
/// SwifterSwift: Check if string contains one or more instance of substring.
///
/// "Hello World!".contain("O") -> false
/// "Hello World!".contain("o", caseSensitive: false) -> true
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string contains one or more instance of substring.
public func contains(_ string: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return range(of: string, options: .caseInsensitive) != nil
}
return range(of: string) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Count of substring in string.
///
/// "Hello World!".count(of: "o") -> 2
/// "Hello World!".count(of: "L", caseSensitive: false) -> 3
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: count of appearance of substring in string.
public func count(of string: String, caseSensitive: Bool = true) -> Int {
if !caseSensitive {
return lowercased().components(separatedBy: string.lowercased()).count - 1
}
return components(separatedBy: string).count - 1
}
#endif
/// SwifterSwift: Check if string ends with substring.
///
/// "Hello World!".ends(with: "!") -> true
/// "Hello World!".ends(with: "WoRld!", caseSensitive: false) -> true
///
/// - Parameters:
/// - suffix: substring to search if string ends with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string ends with substring.
public func ends(with suffix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasSuffix(suffix.lowercased())
}
return hasSuffix(suffix)
}
#if canImport(Foundation)
/// SwifterSwift: Latinize string.
///
/// var str = "Hèllö Wórld!"
/// str.latinize()
/// print(str) // prints "Hello World!"
///
public mutating func latinize() {
self = folding(options: .diacriticInsensitive, locale: Locale.current)
}
#endif
/// SwifterSwift: Random string of given length.
///
/// String.random(ofLength: 18) -> "u7MMZYvGo9obcOcPj8"
///
/// - Parameter length: number of characters in string.
/// - Returns: random string of given length.
public static func random(ofLength length: Int) -> String {
guard length > 0 else { return "" }
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString = ""
for _ in 1 ... length {
let randomIndex = arc4random_uniform(UInt32(base.count))
let randomCharacter = base.charactersArray[Int(randomIndex)]
randomString.append(randomCharacter)
}
return randomString
}
/// SwifterSwift: Reverse string.
public mutating func reverse() {
let chars: [Character] = reversed()
self = String(chars)
}
// swiftlint:disable next identifier_name
/// SwifterSwift: Sliced string from a start index with length.
///
/// "Hello World".slicing(from: 6, length: 5) -> "World"
///
/// - Parameters:
/// - i: string index the slicing should start from.
/// - length: amount of characters to be sliced after given index.
/// - Returns: sliced substring of length number of characters (if applicable) (example: "Hello World".slicing(from: 6, length: 5) -> "World")
public func slicing(from i: Int, length: Int) -> String? {
guard length >= 0, i >= 0, i < count else { return nil }
guard i.advanced(by: length) <= count else {
return self[safe: i ..< count]
}
guard length > 0 else { return "" }
return self[safe: i ..< i.advanced(by: length)]
}
// swiftlint:disable next identifier_name
/// SwifterSwift: Slice given string from a start index with length (if applicable).
///
/// var str = "Hello World"
/// str.slice(from: 6, length: 5)
/// print(str) // prints "World"
///
/// - Parameters:
/// - i: string index the slicing should start from.
/// - length: amount of characters to be sliced after given index.
public mutating func slice(from i: Int, length: Int) {
if let str = self.slicing(from: i, length: length) {
self = String(str)
}
}
/// SwifterSwift: Slice given string from a start index to an end index (if applicable).
///
/// var str = "Hello World"
/// str.slice(from: 6, to: 11)
/// print(str) // prints "World"
///
/// - Parameters:
/// - start: string index the slicing should start from.
/// - end: string index the slicing should end at.
public mutating func slice(from start: Int, to end: Int) {
guard end >= start else { return }
if let str = self[safe: start ..< end] {
self = str
}
}
// swiftlint:disable next identifier_name
/// SwifterSwift: Slice given string from a start index (if applicable).
///
/// var str = "Hello World"
/// str.slice(at: 6)
/// print(str) // prints "World"
///
/// - Parameter i: string index the slicing should start from.
public mutating func slice(at i: Int) {
guard i < count else { return }
if let str = self[safe: i ..< count] {
self = str
}
}
/// SwifterSwift: Check if string starts with substring.
///
/// "hello World".starts(with: "h") -> true
/// "hello World".starts(with: "H", caseSensitive: false) -> true
///
/// - Parameters:
/// - suffix: substring to search if string starts with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string starts with substring.
public func starts(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
#if canImport(Foundation)
/// SwifterSwift: Date object from string of date format.
///
/// "2017-01-15".date(withFormat: "yyyy-MM-dd") -> Date set to Jan 15, 2017
/// "not date string".date(withFormat: "yyyy-MM-dd") -> nil
///
/// - Parameter format: date format.
/// - Returns: Date object from string (if applicable).
public func date(withFormat format: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Removes spaces and new lines in beginning and end of string.
///
/// var str = " \n Hello World \n\n\n"
/// str.trim()
/// print(str) // prints "Hello World"
///
public mutating func trim() {
self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
#endif
/// SwifterSwift: Truncate string (cut it to a given number of characters).
///
/// var str = "This is a very long sentence"
/// str.truncate(toLength: 14)
/// print(str) // prints "This is a very..."
///
/// - Parameters:
/// - toLength: maximum number of characters before cutting.
/// - trailing: string to add at the end of truncated string (default is "...").
public mutating func truncate(toLength length: Int, trailing: String? = "...") {
guard length > 0 else { return }
if count > length {
self = self[startIndex ..< index(startIndex, offsetBy: length)] + (trailing ?? "")
}
}
/// SwifterSwift: Truncated string (limited to a given number of characters).
///
/// "This is a very long sentence".truncated(toLength: 14) -> "This is a very..."
/// "Short sentence".truncated(toLength: 14) -> "Short sentence"
///
/// - Parameters:
/// - toLength: maximum number of characters before cutting.
/// - trailing: string to add at the end of truncated string.
/// - Returns: truncated string (this is an extr...).
public func truncated(toLength length: Int, trailing: String? = "...") -> String {
guard 1 ..< count ~= length else { return self }
return self[startIndex ..< index(startIndex, offsetBy: length)] + (trailing ?? "")
}
#if canImport(Foundation)
/// SwifterSwift: Convert URL string to readable string.
///
/// var str = "it's%20easy%20to%20decode%20strings"
/// str.urlDecode()
/// print(str) // prints "it's easy to decode strings"
///
public mutating func urlDecode() {
if let decoded = removingPercentEncoding {
self = decoded
}
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Escape string.
///
/// var str = "it's easy to encode strings"
/// str.urlEncode()
/// print(str) // prints "it's%20easy%20to%20encode%20strings"
///
public mutating func urlEncode() {
if let encoded = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
self = encoded
}
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Verify if string matches the regex pattern.
///
/// - Parameter pattern: Pattern to verify.
/// - Returns: true if string matches the pattern.
public func matches(pattern: String) -> Bool {
return range(of: pattern, options: .regularExpression, range: nil, locale: nil) != nil
}
#endif
/// SwifterSwift: Pad string to fit the length parameter size with another string in the start.
///
/// "hue".padStart(10) -> " hue"
/// "hue".padStart(10, with: "br") -> "brbrbrbhue"
///
/// - Parameter length: The target length to pad.
/// - Parameter string: Pad string. Default is " ".
public mutating func padStart(_ length: Int, with string: String = " ") {
self = paddingStart(length, with: string)
}
/// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the start.
///
/// "hue".paddingStart(10) -> " hue"
/// "hue".paddingStart(10, with: "br") -> "brbrbrbhue"
///
/// - Parameter length: The target length to pad.
/// - Parameter string: Pad string. Default is " ".
/// - Returns: The string with the padding on the start.
public func paddingStart(_ length: Int, with string: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
if padLength < string.count {
return string[string.startIndex ..< string.index(string.startIndex, offsetBy: padLength)] + self
} else {
var padding = string
while padding.count < padLength {
padding.append(string)
}
return padding[padding.startIndex ..< padding.index(padding.startIndex, offsetBy: padLength)] + self
}
}
/// SwifterSwift: Pad string to fit the length parameter size with another string in the start.
///
/// "hue".padEnd(10) -> "hue "
/// "hue".padEnd(10, with: "br") -> "huebrbrbrb"
///
/// - Parameter length: The target length to pad.
/// - Parameter string: Pad string. Default is " ".
public mutating func padEnd(_ length: Int, with string: String = " ") {
self = paddingEnd(length, with: string)
}
/// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the end.
///
/// "hue".paddingEnd(10) -> "hue "
/// "hue".paddingEnd(10, with: "br") -> "huebrbrbrb"
///
/// - Parameter length: The target length to pad.
/// - Parameter string: Pad string. Default is " ".
/// - Returns: The string with the padding on the end.
public func paddingEnd(_ length: Int, with string: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
if padLength < string.count {
return self + string[string.startIndex ..< string.index(string.startIndex, offsetBy: padLength)]
} else {
var padding = string
while padding.count < padLength {
padding.append(string)
}
return self + padding[padding.startIndex ..< padding.index(padding.startIndex, offsetBy: padLength)]
}
}
/// SwifterSwift: Removes given prefix from the string.
///
/// "Hello, World!".removingPrefix("Hello, ") -> "World!"
///
/// - Parameter prefix: Prefix to remove from the string.
/// - Returns: The string after prefix removing.
public func removingPrefix(_ prefix: String) -> String {
guard hasPrefix(prefix) else { return self }
return String(dropFirst(prefix.count))
}
/// SwifterSwift: Removes given suffix from the string.
///
/// "Hello, World!".removingSuffix(", World!") -> "Hello"
///
/// - Parameter suffix: Suffix to remove from the string.
/// - Returns: The string after suffix removing.
public func removingSuffix(_ suffix: String) -> String {
guard hasSuffix(suffix) else { return self }
return String(dropLast(suffix.count))
}
}
// MARK: - Initializers
public extension String {
#if canImport(Foundation)
/// SwifterSwift: Create a new string from a base64 string (if applicable).
///
/// String(base64: "SGVsbG8gV29ybGQh") = "Hello World!"
/// String(base64: "hello") = nil
///
/// - Parameter base64: base64 string.
public init?(base64: String) {
guard let decodedData = Data(base64Encoded: base64) else { return nil }
guard let str = String(data: decodedData, encoding: .utf8) else { return nil }
self.init(str)
}
#endif
/// SwifterSwift: Create a new random string of given length.
///
/// String(randomOfLength: 10) -> "gY8r3MHvlQ"
///
/// - Parameter length: number of characters in string.
public init(randomOfLength length: Int) {
guard length > 0 else {
self.init()
return
}
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString = ""
for _ in 1 ... length {
let randomIndex = arc4random_uniform(UInt32(base.count))
let randomCharacter = Array(base)[Int(randomIndex)]
randomString.append(randomCharacter)
}
self = randomString
}
}
// MARK: - NSAttributedString extensions
public extension String {
#if canImport(UIKit)
private typealias Font = UIFont
#endif
#if canImport(Cocoa)
private typealias Font = NSFont
#endif
#if os(iOS) || os(macOS)
/// SwifterSwift: Bold string.
public var bold: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [.font: Font.boldSystemFont(ofSize: Font.systemFontSize)])
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Underlined string
public var underline: NSAttributedString {
return NSAttributedString(string: self, attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Strikethrough string.
public var strikethrough: NSAttributedString {
return NSAttributedString(string: self, attributes: [.strikethroughStyle: NSNumber(value: NSUnderlineStyle.single.rawValue as Int)])
}
#endif
#if os(iOS)
/// SwifterSwift: Italic string.
public var italic: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
}
#endif
#if canImport(UIKit)
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
public func colored(with color: UIColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [.foregroundColor: color])
}
#endif
#if canImport(Cocoa)
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
public func colored(with color: NSColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [.foregroundColor: color])
}
#endif
}
// MARK: - NSString extensions
#if canImport(Foundation)
// MARK: - NSString extensions
public extension String {
/// SwifterSwift: NSString from a string.
public var nsString: NSString {
return NSString(string: self)
}
/// SwifterSwift: NSString lastPathComponent.
public var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
/// SwifterSwift: NSString pathExtension.
public var pathExtension: String {
return (self as NSString).pathExtension
}
/// SwifterSwift: NSString deletingLastPathComponent.
public var deletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
/// SwifterSwift: NSString deletingPathExtension.
public var deletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
/// SwifterSwift: NSString pathComponents.
public var pathComponents: [String] {
return (self as NSString).pathComponents
}
/// SwifterSwift: NSString appendingPathComponent(str: String)
///
/// - Parameter str: the path component to append to the receiver.
/// - Returns: a new string made by appending aString to the receiver, preceded if necessary by a path separator.
public func appendingPathComponent(_ str: String) -> String {
return (self as NSString).appendingPathComponent(str)
}
/// SwifterSwift: NSString appendingPathExtension(str: String)
///
/// - Parameter str: The extension to append to the receiver.
/// - Returns: a new string made by appending to the receiver an extension separator followed by ext (if applicable).
public func appendingPathExtension(_ str: String) -> String? {
return (self as NSString).appendingPathExtension(str)
}
}
#endif
infix operator ???: NilCoalescingPrecedence
/// Returns defaultValue if optional is nil, otherwise returns optional.
///
/// - Parameters:
/// - optional: The optional variable.
/// - defaultValue: The default value.
/// - Returns: Returns defaultValue if optional is nil, otherwise returns optional.
public func ??? <T>(optional: T?, defaultValue: @autoclosure () -> String) -> String {
return optional.map { String(describing: $0) } ?? defaultValue()
}
// MARK: - Operators
public extension String {
/// SwifterSwift: Repeat string multiple times.
///
/// 'bar' * 3 -> "barbarbar"
///
/// - Parameters:
/// - lhs: string to repeat.
/// - rhs: number of times to repeat character.
/// - Returns: new string with given string repeated n times.
public static func * (lhs: String, rhs: Int) -> String {
guard rhs > 0 else { return "" }
return String(repeating: lhs, count: rhs)
}
/// SwifterSwift: Repeat string multiple times.
///
/// 3 * 'bar' -> "barbarbar"
///
/// - Parameters:
/// - lhs: number of times to repeat character.
/// - rhs: string to repeat.
/// - Returns: new string with given string repeated n times.
public static func * (lhs: Int, rhs: String) -> String {
guard lhs > 0 else { return "" }
return String(repeating: rhs, count: lhs)
}
}
|
mit
|
d38d1a842b331b008c84d0718de6ce15
| 36.004484 | 533 | 0.591772 | 4.678005 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
TranslationEditor/USXChapterProcessor.swift
|
1
|
2519
|
//
// USXChapterProcessor.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 17.10.2016.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
class USXChapterProcessor: USXContentProcessor
{
typealias Generated = Chapter
typealias Processed = Section
// ATTRIBUTES ---------
private let userId: String
private let bookId: String
private let chapterIndex: Int
private var sectionIndex = 0
// INIT -----------------
init(userId: String, bookId: String, index: Int)
{
self.userId = userId
self.bookId = bookId
self.chapterIndex = index
}
// Creates a new USX parser for chapter contents
// The parser should start after a chapter element
// the parser will stop at the next chapter element (or at next book / end of usx)
static func createChapterParser(caller: XMLParserDelegate, userId: String, bookId: String, index: Int, targetPointer: UnsafeMutablePointer<[Chapter]>, using errorHandler: @escaping ErrorHandler) -> USXContentParser<Chapter, Section>
{
let parser = USXContentParser<Chapter, Section>(caller: caller, containingElement: .usx, lowestBreakMarker: .chapter, targetPointer: targetPointer, using: errorHandler)
parser.processor = AnyUSXContentProcessor(USXChapterProcessor(userId: userId, bookId: bookId, index: index))
return parser
}
// USX PARSING ---------
func getParser(_ caller: USXContentParser<Chapter, Section>, forElement elementName: String, attributes: [String : String], into targetPointer: UnsafeMutablePointer<[Section]>, using errorHandler: @escaping ErrorHandler) -> (XMLParserDelegate, Bool)?
{
// Delegates all para element parsing to section parsers
if elementName == USXContainerElement.para.rawValue
{
sectionIndex += 1
// Creates the new processor and parser
return (USXSectionProcessor.createSectionParser(caller: caller, userId: userId, bookId: bookId, chapterIndex: chapterIndex, sectionIndex: sectionIndex, targetPointer: targetPointer, using: errorHandler), true)
}
else
{
return nil
}
}
func getCharacterParser(_ caller: USXContentParser<Chapter, Section>, forCharacters string: String, into targetPointer: UnsafeMutablePointer<[Section]>, using errorHandler: @escaping ErrorHandler) -> XMLParserDelegate?
{
// Character parsing is only handled below para level
return nil
}
func generate(from content: [Section], using errorHandler: @escaping ErrorHandler) -> Chapter?
{
// Resets status for reuse
sectionIndex = 0
return content
}
}
|
mit
|
b6f204d33024efe29d06b23e5fb9ed32
| 31.282051 | 251 | 0.74027 | 4.087662 | false | false | false | false |
AliceAponasko/LJReader
|
LJReader/Cells/FeedCell.swift
|
1
|
1486
|
//
// FeedCell.swift
// LJReader
//
// Created by Alice Aponasko on 2/14/16.
// Copyright © 2016 aliceaponasko. All rights reserved.
//
import UIKit
class FeedCell: UITableViewCell {
static let cellID = "FeedCell"
static let cellHeight: CGFloat = 75.0
static let minTextHeight: CGFloat = 20.0
static let padding: CGFloat = 120.0
@IBOutlet weak var nameTitleLabel: UILabel!
@IBOutlet weak var articleTitleLabel: UILabel!
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var pubDateLabel: UILabel!
private var dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .ShortStyle
formatter.doesRelativeDateFormatting = true
return formatter
}()
// MARK: Helpers
func setFromArticle(
article: FeedEntry,
pubDate: NSDate,
width: CGFloat) {
pubDateLabel.text = dateFormatter.stringFromDate(pubDate)
nameTitleLabel.text = article.author
nameTitleLabel.preferredMaxLayoutWidth = width - 30
nameTitleLabel.sizeToFit()
articleTitleLabel.text = article.title
articleTitleLabel.preferredMaxLayoutWidth = width - 30
articleTitleLabel.sizeToFit()
avatarImageView.layer.cornerRadius = 3.0
avatarImageView.layer.masksToBounds = true
avatarImageView.af_setImageWithURL(NSURL(string: article.imageURL)!)
}
}
|
mit
|
54e1523a2ae12fa1351b34c037e31cd2
| 27.018868 | 76 | 0.687542 | 4.966555 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
Swift/happy-number.swift
|
2
|
460
|
/**
* https://leetcode.com/problems/happy-number/
*
*
*/
class Solution {
func isHappy(_ n: Int) -> Bool {
var n = n
var list: Set<Int> = [n]
while n > 1 {
var sum = 0
while n > 0 {
sum += (n % 10) * (n % 10)
n /= 10
}
if list.contains(sum) { return false }
list.insert(sum)
n = sum
}
return true
}
}
|
mit
|
fb9b278df63e4172bc5729615ed06a28
| 19.909091 | 50 | 0.378261 | 3.68 | false | false | false | false |
felixjendrusch/Pistachiargo
|
PistachiargoTests/Fixtures/Node.swift
|
2
|
700
|
// Copyright (c) 2015 Felix Jendrusch. All rights reserved.
import Monocle
import Pistachio
import Pistachiargo
struct Node: Equatable {
var children: [Node]
init(children: [Node]) {
self.children = children
}
}
func == (lhs: Node, rhs: Node) -> Bool {
return lhs.children == rhs.children
}
struct NodeLenses {
static let children = Lens(get: { $0.children }, set: { (inout node: Node, children) in
node.children = children
})
}
struct NodeAdapters {
static let json = fix { adapter in
return JSONAdapter(specification: [
"children": JSONArray(NodeLenses.children)(adapter: adapter)
], value: Node(children: []))
}
}
|
mit
|
2b9465b5cb1153af91ba6ff4365704f7
| 21.580645 | 91 | 0.635714 | 3.684211 | false | false | false | false |
bengottlieb/ios
|
FiveCalls/FiveCalls/WelcomeViewController.swift
|
3
|
3077
|
//
// ViewController.swift
// FiveCalls
//
// Created by Ben Scheirman on 1/30/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
import Crashlytics
class WelcomeViewController: UIViewController {
@IBOutlet weak var pageContainer: UIView!
var completionBlock = {}
lazy var pageController: UIPageViewController = {
let pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
pageController.view.translatesAutoresizingMaskIntoConstraints = false
return pageController
}()
let numberOfPages = 2
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
Answers.logCustomEvent(withName:"Screen: Welcome")
loadPages()
}
private func loadPages() {
pageContainer.backgroundColor = .white
addChildViewController(pageController)
pageContainer.addSubview(pageController.view)
NSLayoutConstraint.activate([
pageController.view.topAnchor.constraint(equalTo: pageContainer.topAnchor),
pageController.view.leftAnchor.constraint(equalTo: pageContainer.leftAnchor),
pageController.view.rightAnchor.constraint(equalTo: pageContainer.rightAnchor),
pageController.view.bottomAnchor.constraint(equalTo: pageContainer.bottomAnchor),
])
pageController.didMove(toParentViewController: self)
pageController.dataSource = self
pageController.setViewControllers([viewController(atIndex: 0)], direction: .forward, animated: false, completion: nil)
}
}
extension WelcomeViewController : UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let index = viewController.view.tag + 1
guard index < numberOfPages else { return nil }
return self.viewController(atIndex: index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let index = viewController.view.tag - 1
guard index >= 0 else { return nil }
return self.viewController(atIndex: index)
}
func viewController(atIndex index: Int) -> UIViewController {
guard let storyboard = self.storyboard else { fatalError() }
let page = storyboard.instantiateViewController(withIdentifier: "Page\(index + 1)")
page.view.tag = index
if var finalPage = page as? FinalPage {
finalPage.didFinishBlock = completionBlock
}
return page
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return numberOfPages
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
}
|
mit
|
03f34119716f8a936ee26e59dd192f22
| 34.356322 | 149 | 0.692133 | 5.96124 | false | false | false | false |
0xcodezero/Vatrena
|
Vatrena/Vatrena/controller/CartViewController.swift
|
1
|
3716
|
//
// CartsViewController.swift
// Vatrena
//
// Created by Ahmed Ghalab on 7/29/17.
// Copyright © 2017 Softcare, LLC. All rights reserved.
//
import UIKit
import Firebase
protocol CartActionsDelegate {
func confirmRequestedCartItems()
func cartItemsUpdated()
func continueClosingCartViewWithDecision(confirmed: Bool)
}
class CartViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var cartDelegate : CartActionsDelegate?
@IBOutlet weak var cartItemsTableView: UITableView!
@IBOutlet weak var blurViewContainer: UIView!
@IBOutlet weak var storeLabel: UILabel!
@IBOutlet weak var totalOrderValueLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.blurViewContainer.addSubview(blurEffectView)
cartItemsTableView.contentInset = UIEdgeInsetsMake(0, 0, 20, 0);
adjustViewsValues()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Views Customization
func adjustViewsValues(){
storeLabel.text = VTCartManager.sharedInstance.selectedStore?.name
totalOrderValueLabel.text = "\(VTCartManager.sharedInstance.calclateTotalOrderCost()) ريال"
}
//MARK: - TableView DataSource & Delegate
final let REUSE_IDENTIFIER = "product-cell"
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return VTCartManager.sharedInstance.cartItems?.count ?? 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = cartItemsTableView.dequeueReusableCell(withIdentifier:REUSE_IDENTIFIER ) as! ProductTableViewCell
let productItem = VTCartManager.sharedInstance.cartItems?[indexPath.row]
// set the text from the data model
cell.selectionStyle = .none
cell.setProductItem(productItem!)
cell.addItemButton.tag = indexPath.row
cell.removeItemButton.tag = indexPath.row
cell.showDetailsButton.tag = indexPath.row
return cell
}
//MARK: - IBAction Handlers
@IBAction func closeCartAction(_ sender: UIButton) {
Analytics.logEvent("Close_Cart_Without_Action", parameters: nil)
cartDelegate?.continueClosingCartViewWithDecision(confirmed: false)
}
@IBAction func confirmStartingOrderAction(_ sender: UIButton) {
Analytics.logEvent("Delivery_Within_Cart", parameters: nil)
cartDelegate?.confirmRequestedCartItems()
}
@IBAction func updateCartItemsAction(_ sender: UIButton) {
let row = sender.tag
let item = VTCartManager.sharedInstance.cartItems?[row]
VTCartManager.sharedInstance.updateItemInsideCart(store: VTCartManager.sharedInstance.selectedStore, item: item!)
cartItemsTableView.reloadData()
adjustViewsValues()
if (VTCartManager.sharedInstance.cartItems?.count ?? 0) == 0 {
cartDelegate?.continueClosingCartViewWithDecision(confirmed: false)
}
}
}
|
mit
|
976e9368c45977914db099664ba270cf
| 33.682243 | 121 | 0.682296 | 5.118621 | false | false | false | false |
NinjaIshere/GKGraphKit
|
Example Projects/GraphKitListManager/GraphKitListManager/ListViewController.swift
|
1
|
6446
|
//
// FocusGroupsViewController.swift
// Focus
//
// Created by Daniel Dahan on 2015-02-15.
// Copyright (c) 2015 GraphKit, Inc. All rights reserved.
//
import UIKit
import GKGraphKit
class ListViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, GKGraphDelegate {
private let statusBarHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height
private var collectionView: UICollectionView!
private lazy var toolbar: ListToolbar = ListToolbar()
private lazy var layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
private let list: GKEntity!
// ViewController property value.
// May also be setup as a local variable in any function
// and maintain synchronization.
private lazy var graph: GKGraph = GKGraph()
private var items: Array<GKEntity>?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(list: GKEntity!) {
super.init(nibName: nil, bundle: nil)
self.list = list
}
// #pragma mark View Handling
override func viewDidLoad() {
super.viewDidLoad()
// set the graph as a delegate
graph.delegate = self
// watch the Clicked Action
graph.watch(Action: "Clicked")
// watch for changes in Items
graph.watch(Entity: "Item")
// flow layout for collection view
layout.headerReferenceSize = CGSizeMake(0, 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 10
layout.scrollDirection = .Vertical
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
// collection view
collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.setTranslatesAutoresizingMaskIntoConstraints(false)
collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .clearColor()
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell")
view.addSubview(collectionView)
// toolbar
toolbar.setTranslatesAutoresizingMaskIntoConstraints(false)
toolbar.hideBottomHairline()
toolbar.barTintColor = .whiteColor()
toolbar.clipsToBounds = true
toolbar.sizeToFit()
toolbar.displayAddView()
view.addSubview(toolbar)
// tool bar constraints
view.addConstraint(NSLayoutConstraint(
item: toolbar,
attribute: .Bottom,
relatedBy: .Equal,
toItem: view,
attribute: .Bottom,
multiplier: 1,
constant: 0
))
// autolayout commands
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[toolbar]|", options: nil, metrics: nil, views: ["toolbar": toolbar]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[collectionView]|", options: nil, metrics: nil, views: ["collectionView": collectionView]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[collectionView][toolbar]|", options: nil, metrics: nil, views: ["collectionView": collectionView, "toolbar": toolbar]))
// orientation change
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationDidChange:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
// fetch all the items in the list
items = graph.search(Entity: "Item")
collectionView?.reloadData()
}
override func viewWillDisappear(animated: Bool) {
}
func graph(graph: GKGraph!, didInsertEntity entity: GKEntity!) {
let bond: GKBond = GKBond(type: "ItemOf")
bond.subject = list
bond.object = entity
println("\(bond)")
println("\(entity.bonds.count)")
}
func graph(graph: GKGraph!, didDeleteEntity entity: GKEntity!) {
println("\(entity.bonds.count)")
}
// Add the watch item delegate callback when this event
// is saved to the Graph instance.
func graph(graph: GKGraph!, didInsertAction action: GKAction!) {
// prepare the Item that will be used to launch the new
// ViewController
var item: GKEntity?
if "AddItemButton" == action.objects.last?.type {
// passing a newly created Item
item = GKEntity(type: "Item")
} else if "Item" == action.objects.last?.type {
// clicking a collection cell and passing the Item
item = action.objects.last!
}
var itemViewController: ItemViewController = ItemViewController(item: item)
navigationController!.pushViewController(itemViewController, animated: true)
}
// orientation changes
func orientationDidChange(sender: UIRotationGestureRecognizer) {
// calling reload on orientation change
// updates the cell sizes
collectionView.reloadData()
}
// #pragma mark CollectionViewDelegate
func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
let action: GKAction = GKAction(type: "Clicked")
let user: GKEntity = graph.search(Entity: "User").last!
action.addSubject(user)
action.addObject(items![indexPath.row])
graph.save() { (success: Bool, error: NSError?) in }
return true
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("UICollectionViewCell", forIndexPath: indexPath) as UICollectionViewCell;
// clear before reuse
for subView: AnyObject in cell.subviews {
subView.removeFromSuperview()
}
cell.backgroundColor = .whiteColor()
// var label: UILabel = UILabel(frame: cell.bounds)
// label.font = UIFont(name: "Roboto", size: 20.0)
// label.text = items![indexPath.row]["note"] as? String
// label.textColor = UIColor(red: 0/255.0, green: 145/255.0, blue: 254/255.0, alpha: 1.0)
// cell.addSubview(label)
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(collectionView.bounds.width - 20, 0 == indexPath.row % 2 ? 100 : 150)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items!.count
}
}
|
agpl-3.0
|
c093e2ecac043091bfaddf8e53f3ed3b
| 33.475936 | 193 | 0.751008 | 4.331989 | false | false | false | false |
iandundas/ReactiveKitSwappableDatasource
|
ReactiveKitSwappableDatasource/Classes/Base/DataSource.swift
|
1
|
2113
|
//
// DataSource.swift
// ReactiveKitSwappableDatasource
//
// Created by Ian Dundas on 04/05/2016.
// Copyright © 2016 IanDundas. All rights reserved.
//
import Foundation
import ReactiveKit
public protocol DataSourceType {
associatedtype ItemType : Equatable
// Access a (currently unsorted) array of items:
func items() -> [ItemType]
// Access a feed of mutation events:
func mutations() -> Stream<CollectionChangeset<[ItemType]>>
func encloseInContainer() -> DatasourceContainer<ItemType>
func eraseType() -> AnyDataSource<ItemType>
}
public extension DataSourceType{
public func encloseInContainer() -> DatasourceContainer<ItemType>{
let wrapper = AnyDataSource(self)
let datasourceContainer = DatasourceContainer(datasource: wrapper)
return datasourceContainer
}
public func eraseType() -> AnyDataSource<ItemType>{
return AnyDataSource(self)
}
public func postSort(isOrderedBefore: (ItemType, ItemType) -> Bool) -> AnyDataSource<ItemType>{
let wrapper = AnyDataSource(self)
let postsort = PostSortDataSource(datasource: wrapper, isOrderedBefore: isOrderedBefore)
return AnyDataSource(postsort)
}
}
public class ManualDataSource<Item: Equatable>: DataSourceType {
public func items() -> [Item] {
return collection.filter{_ in true}
}
// only available publicly on ManualDataSource (because it's.. manual)
public func replaceItems(items: [Item]) {
collection.replace(items, performDiff: true)
}
public func mutations() -> Stream<CollectionChangeset<[Item]>>{
return collection.filter {_ in true}
}
private let collection: CollectionProperty<Array<Item>>
/* TODO: currently only takes Array CollectionType
init<C: CollectionType where C.Generator.Element == Element>(collection: C){
self.collection = CollectionProperty<C>(collection)
}
*/
public init(items: [Item]){
self.collection = CollectionProperty(items)
}
}
// TODO: FetchedResultsControllerDataSource
|
mit
|
20bc0b19c8e7b63f9f32355a998d33b1
| 28.746479 | 99 | 0.690341 | 4.735426 | false | false | false | false |
hooman/swift
|
test/IRGen/actor_class.swift
|
12
|
2963
|
// RUN: %target-swift-frontend -emit-ir %s -swift-version 5 -disable-availability-checking | %IRGenFileCheck %s
// REQUIRES: concurrency
// CHECK: %T11actor_class7MyClassC = type <{ %swift.refcounted, %swift.defaultactor, %TSi }>
// CHECK: %swift.defaultactor = type { [12 x i8*] }
// CHECK-objc-LABEL: @"$s11actor_class7MyClassCMm" = global
// CHECK-objc-SAME: @"OBJC_METACLASS_$__TtCs12_SwiftObject{{(.ptrauth)?}}"
// CHECK: @"$s11actor_class7MyClassCMf" = internal global
// CHECK-SAME: @"$s11actor_class7MyClassCfD{{(.ptrauth)?}}"
// CHECK-objc-SAME: @"OBJC_CLASS_$__TtCs12_SwiftObject{{(.ptrauth)?}}"
// CHECK-nonobjc-SAME: %swift.type* null,
// Flags: uses Swift refcounting
// CHECK-SAME: i32 2,
// Instance size
// CHECK-64-SAME: i32 120,
// CHECK-32-SAME: i32 60,
// Alignment mask
// CHECK-64-SAME: i16 15,
// CHECK-32-SAME: i16 7,
// Field offset for 'x'
// CHECK-objc-SAME: [[INT]] {{56|112}},
// Type descriptor.
// CHECK-LABEL: @"$s11actor_class9ExchangerCMn" = {{.*}}constant
// superclass ref, negative bounds, positive bounds, num immediate members, num fields, field offset vector offset
// CHECK-SAME: i32 0, i32 2, i32 [[#CLASS_METADATA_HEADER+8]], i32 8, i32 2, i32 [[#CLASS_METADATA_HEADER+1]],
// Reflection field records.
// CHECK-LABEL: @"$s11actor_class9ExchangerCMF" = internal constant
// Field descriptor kind, field size, num fields,
// (artificial var, "BD", ...)
// CHECK-SAME: i16 1, i16 12, i32 2, i32 6,
// CHECK-SAME: @"symbolic BD"
public actor MyClass {
public var x: Int
public init() { self.x = 0 }
}
// CHECK-LABEL: define {{.*}}@"$s11actor_class7MyClassC1xSivg"
// CHECK: [[T0:%.*]] = getelementptr inbounds %T11actor_class7MyClassC, %T11actor_class7MyClassC* %0, i32 0, i32 2
// CHECK: [[T1:%.*]] = getelementptr inbounds %TSi, %TSi* [[T0]], i32 0, i32 0
// CHECK: load [[INT]], [[INT]]* [[T1]], align
// CHECK-LABEL: define {{.*}}swiftcc %T11actor_class7MyClassC* @"$s11actor_class7MyClassCACycfc"
// CHECK: swift_defaultActor_initialize
// CHECK-LABEL: ret %T11actor_class7MyClassC*
// CHECK-LABEL: define {{.*}}swiftcc %swift.refcounted* @"$s11actor_class7MyClassCfd"
// CHECK: swift_defaultActor_destroy
// CHECK-LABEL: ret
public actor Exchanger<T> {
public var value: T
public init(value: T) { self.value = value }
public func exchange(newValue: T) -> T {
let oldValue = value
value = newValue
return oldValue
}
}
// CHECK-LABEL: define{{.*}} void @"$s11actor_class9ExchangerC5valuexvg"(
// Note that this is one more than the field offset vector offset from
// the class descriptor, since this is the second field.
// CHECK: [[T0:%.*]] = getelementptr inbounds [[INT]], [[INT]]* {{.*}}, [[INT]] [[#CLASS_METADATA_HEADER+2]]
// CHECK-NEXT: [[OFFSET:%.*]] = load [[INT]], [[INT]]* [[T0]], align
// CHECK-NEXT: [[T0:%.*]] = bitcast %T11actor_class9ExchangerC* %1 to i8*
// CHECK-NEXT: getelementptr inbounds i8, i8* [[T0]], [[INT]] [[OFFSET]]
|
apache-2.0
|
b16263f62976672202ff7eb875ab59ea
| 40.152778 | 116 | 0.660817 | 3.145435 | false | false | false | false |
lorentey/swift
|
test/stdlib/Dispatch.swift
|
7
|
7310
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: libdispatch
// UNSUPPORTED: OS=linux-gnu
import Dispatch
import StdlibUnittest
defer { runAllTests() }
var DispatchAPI = TestSuite("DispatchAPI")
DispatchAPI.test("constants") {
expectEqual(2147483648, DispatchSource.ProcessEvent.exit.rawValue)
expectEqual(0, DispatchData.empty.endIndex)
// This is a lousy test, but really we just care that
// DISPATCH_QUEUE_CONCURRENT comes through at all.
_ = DispatchQueue.Attributes.concurrent
}
DispatchAPI.test("OS_OBJECT support") {
let mainQueue = DispatchQueue.main as AnyObject
expectTrue(mainQueue is DispatchQueue)
// This should not be optimized out, and should succeed.
expectNotNil(mainQueue as? DispatchQueue)
}
DispatchAPI.test("DispatchGroup creation") {
let group = DispatchGroup()
expectNotNil(group)
}
DispatchAPI.test("Dispatch sync return value") {
let value = 24
let q = DispatchQueue(label: "Test")
let result = q.sync() { return 24 }
expectEqual(value, result)
}
DispatchAPI.test("dispatch_block_t conversions") {
var counter = 0
let closure = { () -> Void in
counter += 1
}
typealias Block = @convention(block) () -> ()
let block = closure as Block
block()
expectEqual(1, counter)
let closureAgain = block as () -> Void
closureAgain()
expectEqual(2, counter)
}
if #available(OSX 10.10, iOS 8.0, *) {
DispatchAPI.test("dispatch_block_t identity") {
let block = DispatchWorkItem(flags: .inheritQoS) {
_ = 1
}
DispatchQueue.main.async(execute: block)
// This will trap if the block's pointer identity is not preserved.
block.cancel()
}
}
DispatchAPI.test("DispatchTime comparisons") {
do {
let now = DispatchTime.now()
checkComparable([now, now + .milliseconds(1), .distantFuture], oracle: {
return $0 < $1 ? .lt : $0 == $1 ? .eq : .gt
})
}
do {
let now = DispatchWallTime.now()
checkComparable([now, now + .milliseconds(1), .distantFuture], oracle: {
return $0 < $1 ? .lt : $0 == $1 ? .eq : .gt
})
}
}
DispatchAPI.test("DispatchTime.create") {
var info = mach_timebase_info_data_t(numer: 1, denom: 1)
mach_timebase_info(&info)
let scales = info.numer != info.denom
// Simple tests for non-overflow behavior
var time = DispatchTime(uptimeNanoseconds: 0)
expectEqual(time.uptimeNanoseconds, 0)
time = DispatchTime(uptimeNanoseconds: 15 * NSEC_PER_SEC)
expectEqual(time.uptimeNanoseconds, 15 * NSEC_PER_SEC)
// On platforms where the timebase scale is not 1, the next two cases
// overflow and become DISPATCH_TIME_FOREVER (UInt64.max) instead of trapping.
time = DispatchTime(uptimeNanoseconds: UInt64.max - 1)
expectEqual(time.uptimeNanoseconds, scales ? UInt64.max : UInt64.max - UInt64(1))
time = DispatchTime(uptimeNanoseconds: UInt64.max / 2)
expectEqual(time.uptimeNanoseconds, scales ? UInt64.max : UInt64.max / 2)
// UInt64.max must always be returned as UInt64.max.
time = DispatchTime(uptimeNanoseconds: UInt64.max)
expectEqual(time.uptimeNanoseconds, UInt64.max)
}
DispatchAPI.test("DispatchTime.addSubtract") {
var then = DispatchTime.now() + Double.infinity
expectEqual(DispatchTime.distantFuture, then)
then = DispatchTime.now() + Double.nan
expectEqual(DispatchTime.distantFuture, then)
then = DispatchTime.now() - Double.infinity
expectEqual(DispatchTime(uptimeNanoseconds: 1), then)
then = DispatchTime.now() - Double.nan
expectEqual(DispatchTime.distantFuture, then)
}
DispatchAPI.test("DispatchWallTime.addSubtract") {
let distantPastRawValue = DispatchWallTime.distantFuture.rawValue - UInt64(1)
var then = DispatchWallTime.now() + Double.infinity
expectEqual(DispatchWallTime.distantFuture, then)
then = DispatchWallTime.now() + Double.nan
expectEqual(DispatchWallTime.distantFuture, then)
then = DispatchWallTime.now() - Double.infinity
expectEqual(distantPastRawValue, then.rawValue)
then = DispatchWallTime.now() - Double.nan
expectEqual(DispatchWallTime.distantFuture, then)
}
DispatchAPI.test("DispatchTime.uptimeNanos") {
let seconds = 1
let nowMach = DispatchTime.now()
let oneSecondFromNowMach = nowMach + .seconds(seconds)
let nowNanos = nowMach.uptimeNanoseconds
let oneSecondFromNowNanos = oneSecondFromNowMach.uptimeNanoseconds
let diffNanos = oneSecondFromNowNanos - nowNanos
expectEqual(NSEC_PER_SEC, diffNanos)
}
DispatchAPI.test("DispatchIO.initRelativePath") {
let q = DispatchQueue(label: "initRelativePath queue")
let chan = DispatchIO(type: .random, path: "_REL_PATH_", oflag: O_RDONLY, mode: 0, queue: q, cleanupHandler: { (error) in })
expectEqual(chan, nil)
}
if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
var block = DispatchWorkItem(qos: .unspecified, flags: .assignCurrentContext) {}
DispatchAPI.test("DispatchSource.replace") {
let g = DispatchGroup()
let q = DispatchQueue(label: "q")
let ds = DispatchSource.makeUserDataReplaceSource(queue: q)
var lastValue = UInt(0)
var nextValue = UInt(1)
let maxValue = UInt(1 << 24)
ds.setEventHandler() {
let value = ds.data;
expectTrue(value > lastValue) // Values must increase
expectTrue((value & (value - 1)) == 0) // Must be power of two
lastValue = value
if value == maxValue {
g.leave()
}
}
ds.activate()
g.enter()
block = DispatchWorkItem(qos: .unspecified, flags: .assignCurrentContext) {
ds.replace(data: nextValue)
nextValue <<= 1
if nextValue <= maxValue {
q.asyncAfter(
deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1),
execute: block)
}
}
q.asyncAfter(
deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1),
execute: block)
let result = g.wait(timeout: DispatchTime.now() + .seconds(30))
expectTrue(result == .success)
}
}
DispatchAPI.test("DispatchTimeInterval") {
// Basic tests that the correct value is stored and the == method works
for i in stride(from:1, through: 100, by: 5) {
expectEqual(DispatchTimeInterval.seconds(i), DispatchTimeInterval.milliseconds(i * 1000))
expectEqual(DispatchTimeInterval.milliseconds(i), DispatchTimeInterval.microseconds(i * 1000))
expectEqual(DispatchTimeInterval.microseconds(i), DispatchTimeInterval.nanoseconds(i * 1000))
}
// Check some cases that used to cause arithmetic overflow when evaluating the rawValue for ==
var t = DispatchTimeInterval.seconds(Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.seconds(-Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.milliseconds(Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.milliseconds(-Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.microseconds(Int.max)
expectTrue(t == t) // This would crash.
t = DispatchTimeInterval.microseconds(-Int.max)
expectTrue(t == t) // This would crash.
}
DispatchAPI.test("DispatchTimeInterval.never.equals") {
expectTrue(DispatchTimeInterval.never == DispatchTimeInterval.never)
expectTrue(DispatchTimeInterval.seconds(10) != DispatchTimeInterval.never);
expectTrue(DispatchTimeInterval.never != DispatchTimeInterval.seconds(10));
expectTrue(DispatchTimeInterval.seconds(10) == DispatchTimeInterval.seconds(10));
}
|
apache-2.0
|
f65d93c28ba3dc7f0adf1ab1b8fc5649
| 30.508621 | 125 | 0.722025 | 3.841303 | false | true | false | false |
okla/QuickRearrangeTableView
|
QuickRearrangeTableView.swift
|
1
|
6138
|
import UIKit
protocol RearrangeDataSource: class {
var currentIndexPath: NSIndexPath? { get set }
func moveObjectAtCurrentIndexPath(to indexPath: NSIndexPath)
}
struct RearrangeOptions: OptionSetType {
let rawValue: Int
init(rawValue: Int) { self.rawValue = rawValue }
static let hover = RearrangeOptions(rawValue: 1)
static let translucency = RearrangeOptions(rawValue: 2)
}
struct RearrangeProperties {
let options: RearrangeOptions
let displayLink: CADisplayLink
let recognizer: UILongPressGestureRecognizer
var catchedView: UIImageView?
var scrollSpeed: CGFloat = 0.0
weak var dataSource: RearrangeDataSource?
init(options: RearrangeOptions, dataSource: RearrangeDataSource,
recognizer: UILongPressGestureRecognizer, displayLink: CADisplayLink) {
self.options = options
self.dataSource = dataSource
self.recognizer = recognizer
self.displayLink = displayLink
}
}
protocol Rearrangable {
var rearrange: RearrangeProperties! { get set }
}
extension TableView: Rearrangable {
func setRearrangeOptions(options: RearrangeOptions, dataSource: RearrangeDataSource) {
rearrange = RearrangeProperties(options: options, dataSource: dataSource,
recognizer: UILongPressGestureRecognizer(target: self, action: #selector(longPress)),
displayLink: CADisplayLink(target: self, selector: #selector(scrollEvent)))
rearrange.displayLink.addToRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
rearrange.displayLink.paused = true
addGestureRecognizer(rearrange.recognizer)
}
func scrollEvent() {
contentOffset.y = min(max(0.0, contentOffset.y + rearrange.scrollSpeed), contentSize.height - frame.height)
moveCatchedViewCenterToY(rearrange.recognizer.locationInView(self).y)
}
private func moveCatchedViewCenterToY(y: CGFloat) {
guard let catchedView = rearrange.catchedView else { return }
catchedView.center.y = min(max(y, bounds.origin.y), bounds.origin.y + bounds.height)
moveDummyRowIfNeeded()
}
private func moveDummyRowIfNeeded() {
guard let source = rearrange.dataSource, currentIndexPath = source.currentIndexPath,
catchedViewCenter = rearrange.catchedView?.center, newIndexPath = indexPathForRowAtPoint(catchedViewCenter)
where newIndexPath != currentIndexPath else { return }
source.moveObjectAtCurrentIndexPath(to: newIndexPath)
source.currentIndexPath = newIndexPath
beginUpdates()
deleteRowsAtIndexPaths([currentIndexPath], withRowAnimation: .Top)
insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Top)
endUpdates()
}
func longPress() {
guard let source = rearrange.dataSource where !editing else { return }
let location = rearrange.recognizer.locationInView(self)
switch rearrange.recognizer.state {
case .Began:
source.currentIndexPath = indexPathForRowAtPoint(location)
guard let currentIndexPath = source.currentIndexPath,
catchedCell = cellForRowAtIndexPath(currentIndexPath) else { return }
allowsSelection = false
catchedCell.highlighted = false
let sizeWithoutSeparator = CGSizeMake(catchedCell.bounds.size.width, catchedCell.bounds.size.height - 1.0)
UIGraphicsBeginImageContextWithOptions(sizeWithoutSeparator, true, 0.0)
guard let context = UIGraphicsGetCurrentContext() else { return }
catchedCell.layer.renderInContext(context)
rearrange.catchedView = UIImageView(image: UIGraphicsGetImageFromCurrentImageContext())
UIGraphicsEndImageContext()
rearrange.catchedView!.center = catchedCell.center
addSubview(rearrange.catchedView!)
rearrange.catchedView!.layer.shadowRadius = 4.0
rearrange.catchedView!.layer.shadowOpacity = 0.25
rearrange.catchedView!.layer.shadowOffset = CGSizeZero
rearrange.catchedView!.layer.shadowPath = UIBezierPath(rect: rearrange.catchedView!.bounds).CGPath
UIView.animateWithDuration(0.2) { [unowned self] in
if self.rearrange.options.contains(.translucency) { self.rearrange.catchedView!.alpha = 0.5 }
if self.rearrange.options.contains(.hover) {
self.rearrange.catchedView!.transform = CGAffineTransformMakeScale(1.05, 1.05)
}
self.moveCatchedViewCenterToY(location.y)
}
reloadRowsAtIndexPaths([currentIndexPath], withRowAnimation: .None)
case .Changed:
guard let catchedView = rearrange.catchedView else { return }
moveCatchedViewCenterToY(location.y)
rearrange.scrollSpeed = 0.0
if contentSize.height > frame.height {
let halfCellHeight = 0.5*catchedView.frame.height
let cellCenterY = catchedView.center.y - bounds.origin.y
if cellCenterY < halfCellHeight {
rearrange.scrollSpeed = 5.0*(cellCenterY/halfCellHeight - 1.1)
}
else if cellCenterY > frame.height - halfCellHeight {
rearrange.scrollSpeed = 5.0*((cellCenterY - frame.height)/halfCellHeight + 1.1)
}
rearrange.displayLink.paused = rearrange.scrollSpeed == 0.0
}
default:
allowsSelection = true
rearrange.displayLink.paused = true
guard let currentIndexPath = source.currentIndexPath, catchedView = rearrange.catchedView else { return }
source.currentIndexPath = nil
UIView.animateWithDuration(0.2, animations: { [unowned self] in
if self.rearrange.options.contains(.translucency) { catchedView.alpha = 1.0 }
if self.rearrange.options.contains(.hover) { catchedView.transform = CGAffineTransformIdentity }
catchedView.frame = self.rectForRowAtIndexPath(currentIndexPath)
}) { [unowned self] _ in
catchedView.layer.shadowOpacity = 0.0
UIView.animateWithDuration(0.1, animations: {
self.reloadData()
self.layer.addAnimation(CATransition(), forKey: "reload")
}) { _ in
catchedView.removeFromSuperview()
self.rearrange.catchedView = nil
}
}
}
}
}
|
mit
|
2003fa27ccebc135d9d6451888ead617
| 28.941463 | 121 | 0.710818 | 4.886943 | false | false | false | false |
ontouchstart/swift3-playground
|
Learn to Code 2.playgroundbook/Contents/Sources/ActorType.swift
|
2
|
1482
|
//
// ActorType.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import SceneKit
/// An enum used to group all the characters.
enum ActorType: String {
case byte
case blu
case hopper
case expert
var resourceFilePath: String {
let pathPrefix = WorldConfiguration.charactersDir
switch self {
case .byte: return pathPrefix + "Byte/"
case .hopper: return pathPrefix + "Hopper/"
case .blu: return pathPrefix + "Blu/"
case .expert: return pathPrefix + "Expert/"
}
}
func createNode() -> SCNNode {
let sceneName = self.resourceFilePath + "NeutralPose"
let bundle = Bundle.main
let actorSceneURL: URL
if let daeURL = bundle.url(forResource: sceneName, withExtension: "dae") {
actorSceneURL = daeURL
}
else {
actorSceneURL = bundle.url(forResource: sceneName, withExtension: "scn")!
}
let actorScene: SCNScene
do {
actorScene = try SCNScene(url: actorSceneURL)
}
catch {
fatalError("Could not load: \(sceneName). \(error)")
}
let node = actorScene.rootNode.childNodes[0]
// Configure the node.
node.enumerateChildNodes { child, _ in
child.castsShadow = true
child.categoryBitMask = WorldConfiguration.shadowBitMask
}
return node
}
}
|
mit
|
51c23aa4439f1eb550da125b22e00eed
| 25.945455 | 85 | 0.576248 | 4.53211 | false | true | false | false |
snazzware/HexMatch
|
HexMatch/Helpers/GameKitHelper.swift
|
2
|
3243
|
/*
* Copyright (c) 2015-2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import Foundation
import GameKit
let PresentAuthenticationViewController = "PresentAuthenticationViewController"
let ShowGKGameCenterViewController = "ShowGKGameCenterViewController"
class GameKitHelper: NSObject {
static let sharedInstance = GameKitHelper()
var authenticationViewController: UIViewController?
var gameCenterEnabled = false
func authenticateLocalPlayer() {
//1
let localPlayer = GKLocalPlayer()
localPlayer.authenticateHandler = {(viewController, error) in
if viewController != nil {
//2
self.authenticationViewController = viewController
NotificationCenter.default.post(name: Notification.Name(rawValue: PresentAuthenticationViewController), object: self)
} else if error == nil {
//3
self.gameCenterEnabled = true
}
}
}
func reportAchievements(_ achievements: [GKAchievement], errorHandler: ((NSError?)->Void)? = nil) {
guard gameCenterEnabled else {
return
}
GKAchievement.report(achievements, withCompletionHandler: errorHandler as! ((Error?) -> Void)?)
}
func showGKGameCenterViewController(_ viewController: UIViewController) {
guard gameCenterEnabled else {
return
}
//1
let gameCenterViewController = GKGameCenterViewController()
//2
gameCenterViewController.gameCenterDelegate = self
//3
viewController.present(gameCenterViewController, animated: true, completion: nil)
}
func reportScore(_ score: Int64, forLeaderBoardId leaderBoardId: String, errorHandler: ((NSError?)->Void)? = nil) {
guard gameCenterEnabled else {
return
}
//1
let gkScore = GKScore(leaderboardIdentifier: leaderBoardId)
gkScore.value = score
//2
GKScore.report([gkScore], withCompletionHandler: errorHandler as! ((Error?) -> Void)?)
}
}
extension GameKitHelper: GKGameCenterControllerDelegate {
func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismiss(animated: true, completion: nil)
}
}
|
gpl-3.0
|
ff8d6489c38dca7da7706396d1d01bd8
| 32.43299 | 125 | 0.732038 | 4.921093 | false | false | false | false |
chris-wood/reveiller
|
reveiller/Pods/SwiftCharts/SwiftCharts/Layers/ChartPointsScatterLayer.swift
|
6
|
5548
|
//
// ChartPointsScatterLayer.swift
// Examples
//
// Created by ischuetz on 17/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class ChartPointsScatterLayer<T: ChartPoint>: ChartPointsLayer<T> {
let itemSize: CGSize
let itemFillColor: UIColor
required init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
self.itemSize = itemSize
self.itemFillColor = itemFillColor
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay)
}
override func chartViewDrawing(context context: CGContextRef, chart: Chart) {
for chartPointModel in self.chartPointsModels {
self.drawChartPointModel(context: context, chartPointModel: chartPointModel)
}
}
func drawChartPointModel(context context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
fatalError("override")
}
}
public class ChartPointsScatterTrianglesLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override func drawChartPointModel(context context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, chartPointModel.screenLoc.x, chartPointModel.screenLoc.y - h / 2)
CGPathAddLineToPoint(path, nil, chartPointModel.screenLoc.x + w / 2, chartPointModel.screenLoc.y + h / 2)
CGPathAddLineToPoint(path, nil, chartPointModel.screenLoc.x - w / 2, chartPointModel.screenLoc.y + h / 2)
CGPathCloseSubpath(path)
CGContextSetFillColorWithColor(context, self.itemFillColor.CGColor)
CGContextAddPath(context, path)
CGContextFillPath(context)
}
}
public class ChartPointsScatterSquaresLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override func drawChartPointModel(context context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
CGContextSetFillColorWithColor(context, self.itemFillColor.CGColor)
CGContextFillRect(context, CGRectMake(chartPointModel.screenLoc.x - w / 2, chartPointModel.screenLoc.y - h / 2, w, h))
}
}
public class ChartPointsScatterCirclesLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override func drawChartPointModel(context context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
CGContextSetFillColorWithColor(context, self.itemFillColor.CGColor)
CGContextFillEllipseInRect(context, CGRectMake(chartPointModel.screenLoc.x - w / 2, chartPointModel.screenLoc.y - h / 2, w, h))
}
}
public class ChartPointsScatterCrossesLayer<T: ChartPoint>: ChartPointsScatterLayer<T> {
private let strokeWidth: CGFloat
required public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, itemSize: CGSize, itemFillColor: UIColor, strokeWidth: CGFloat = 2) {
self.strokeWidth = strokeWidth
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay, itemSize: itemSize, itemFillColor: itemFillColor)
}
override func drawChartPointModel(context context: CGContextRef, chartPointModel: ChartPointLayerModel<T>) {
let w = self.itemSize.width
let h = self.itemSize.height
func drawLine(p1X: CGFloat, p1Y: CGFloat, p2X: CGFloat, p2Y: CGFloat) {
CGContextSetStrokeColorWithColor(context, self.itemFillColor.CGColor)
CGContextSetLineWidth(context, self.strokeWidth)
CGContextMoveToPoint(context, p1X, p1Y)
CGContextAddLineToPoint(context, p2X, p2Y)
CGContextStrokePath(context)
}
drawLine(chartPointModel.screenLoc.x - w / 2, p1Y: chartPointModel.screenLoc.y - h / 2, p2X: chartPointModel.screenLoc.x + w / 2, p2Y: chartPointModel.screenLoc.y + h / 2)
drawLine(chartPointModel.screenLoc.x + w / 2, p1Y: chartPointModel.screenLoc.y - h / 2, p2X: chartPointModel.screenLoc.x - w / 2, p2Y: chartPointModel.screenLoc.y + h / 2)
}
}
|
mit
|
86b6d503a18b64e51ac547869e4ef23d
| 49.899083 | 203 | 0.718637 | 4.600332 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
WordPress/WordPressShareExtension/PostStatusPickerViewController.swift
|
2
|
3248
|
import Foundation
import UIKit
import WordPressShared
class PostStatusPickerViewController: UITableViewController {
// MARK: - Initializers
init(statuses: [String: String]) {
assert(statuses.count > 0, "Let's show at least one status!")
// Note: We'll store the sorted Post Statuses, into an array, as a (Key, Description) tuple.
self.sortedStatuses = statuses.sorted { $0.1 < $1.1 }
super.init(style: .plain)
}
required init?(coder: NSCoder) {
sortedStatuses = [(String, String)]()
super.init(coder: coder)
fatalError("Please, use the main initializer instead")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupTableView()
}
// MARK: - UITableView Methods
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sortedStatuses.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return rowHeight
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
let description = sortedStatuses[indexPath.row].1
configureCell(cell, description: description)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let status = sortedStatuses[indexPath.row]
onChange?(status.0, status.1)
_ = navigationController?.popViewController(animated: true)
}
// MARK: - Setup Helpers
fileprivate func setupView() {
title = NSLocalizedString("Post Status", comment: "Title for the Post Status Picker")
}
fileprivate func setupTableView() {
// Blur!
let blurEffect = UIBlurEffect(style: .light)
tableView.backgroundColor = UIColor.clear
tableView.backgroundView = UIVisualEffectView(effect: blurEffect)
tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect)
// Fix: Hide the cellSeparators, when the table is empty
tableView.tableFooterView = UIView()
// Cells
tableView.register(WPTableViewCellSubtitle.self, forCellReuseIdentifier: reuseIdentifier)
}
// MARK: - Private Helpers
fileprivate func configureCell(_ cell: UITableViewCell, description: String) {
// Status' Details
cell.textLabel?.text = description
// Style
WPStyleGuide.Share.configureBlogTableViewCell(cell)
}
// MARK: Typealiases
typealias PickerHandler = (_ postStatus: String, _ description: String) -> Void
// MARK: - Public Properties
var onChange: PickerHandler?
// MARK: - Private Properties
fileprivate var sortedStatuses: [(String, String)]
fileprivate var noResultsView: WPNoResultsView!
// MARK: - Private Constants
fileprivate let reuseIdentifier = "reuseIdentifier"
fileprivate let rowHeight = CGFloat(74)
}
|
gpl-2.0
|
a55303484d957891eaf49ac4f2cd8891
| 30.843137 | 109 | 0.673645 | 5.23871 | false | false | false | false |
citysite102/kapi-kaffeine
|
kapi-kaffeine/kapi-kaffeine/KPSearchHeaderView.swift
|
1
|
3246
|
//
// KPSearchHeaderView.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/4/10.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import UIKit
class KPSearchHeaderView: UIView {
var containerView: UIView!
var titleLabel: UILabel!
var searchButton: KPBounceButton!
var menuButton: KPBounceButton!
var styleButton: KPBounceButton!
var searchTagView: KPSearchTagView!
override init(frame: CGRect) {
super.init(frame: frame)
containerView = UIView()
containerView.backgroundColor = KPColorPalette.KPBackgroundColor.mainColor_light
addSubview(containerView)
containerView.addConstraints(fromStringArray: ["V:|[$self(64)]",
"H:|[$self]|"],
views: [])
titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 20.0)
titleLabel.textColor = KPColorPalette.KPTextColor.whiteColor
titleLabel.text = "找咖啡"
containerView.addSubview(titleLabel)
titleLabel.addConstraintForCenterAligningToSuperview(in: .horizontal)
titleLabel.addConstraint(from: "V:|-32-[$self]")
styleButton = KPBounceButton.init(frame: .zero, image: R.image.icon_list()!)
containerView.addSubview(styleButton)
styleButton.addConstraints(fromStringArray: ["H:[$self(30)]-5-|",
"V:[$self(30)]"])
styleButton.contentEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3)
styleButton.addConstraintForCenterAligning(to: titleLabel, in: .vertical)
styleButton.tintColor = UIColor.white
searchButton = KPBounceButton.init(frame: .zero, image: R.image.icon_search()!)
containerView.addSubview(searchButton)
searchButton.addConstraints(fromStringArray: ["H:[$self(30)]-5-[$view0]",
"V:[$self(30)]"],
views: [styleButton])
searchButton.contentEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3)
searchButton.addConstraintForCenterAligning(to: titleLabel, in: .vertical)
searchButton.tintColor = UIColor.white
searchButton.imageView?.tintColor = UIColor.white
menuButton = KPBounceButton.init(frame: .zero, image: R.image.icon_menu()!)
containerView.addSubview(menuButton)
menuButton.addConstraints(fromStringArray: ["H:|-5-[$self(30)]",
"V:[$self(30)]"])
menuButton.contentEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3)
menuButton.addConstraintForCenterAligning(to: titleLabel, in: .vertical)
menuButton.tintColor = UIColor.white
searchTagView = KPSearchTagView()
addSubview(searchTagView)
searchTagView.addConstraints(fromStringArray: ["V:[$self(40)]|",
"H:|[$self]|"])
bringSubview(toFront: containerView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
2a4f311f3bb723e36cac8ad697f1d315
| 39.974684 | 88 | 0.591906 | 5.237864 | false | false | false | false |
oskarpearson/rileylink_ios
|
MinimedKit/PumpEvents/PlaceholderPumpEvent.swift
|
1
|
1036
|
//
// PlaceholderPumpEvent.swift
// RileyLink
//
// Created by Nate Racklyeft on 6/20/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct PlaceholderPumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public init?(availableData: Data, pumpModel: PumpModel) {
length = 7
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
}
public var dictionaryRepresentation: [String: Any] {
let name: String
if let type = PumpEventType(rawValue: rawData[0] as UInt8) {
name = String(describing: type).components(separatedBy: ".").last!
} else {
name = "UnknownPumpEvent(\(rawData[0] as UInt8))"
}
return [
"_type": name,
]
}
}
|
mit
|
f28fc8d9be668cdb47e5433433e16249
| 24.243902 | 78 | 0.608696 | 4.620536 | false | false | false | false |
oskarpearson/rileylink_ios
|
MinimedKit/GlucoseEvents/CalBGForGHGlucoseEvent.swift
|
1
|
1008
|
//
// CalBGForGHGlucoseEvent.swift
// RileyLink
//
// Created by Timothy Mecklem on 10/16/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct CalBGForGHGlucoseEvent: GlucoseEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public let amount: Int
public init?(availableData: Data) {
length = 6
guard length <= availableData.count else {
return nil
}
func d(_ idx:Int) -> Int {
return Int(availableData[idx] as UInt8)
}
rawData = availableData.subdata(in: 0..<length)
timestamp = DateComponents(glucoseEventBytes: availableData.subdata(in: 1..<5))
amount = Int( (UInt16(d(3) & 0b00100000) << 3) | UInt16(d(5)) )
}
public var dictionaryRepresentation: [String: Any] {
return [
"name": "CalBGForGH",
"amount": amount
]
}
}
|
mit
|
bd4cdaebffc97c8e4137ef2e38ac441a
| 24.820513 | 87 | 0.585899 | 4.178423 | false | false | false | false |
ReactiveCocoa/ReactiveSwift
|
ReactiveSwift.playground/Pages/SignalProducer.xcplaygroundpage/Contents.swift
|
1
|
22033
|
/*:
> # IMPORTANT: To use `ReactiveSwift.playground`, please:
1. Retrieve the project dependencies using one of the following terminal commands from the ReactiveSwift project root directory:
- `git submodule update --init`
**OR**, if you have [Carthage](https://github.com/Carthage/Carthage) installed
- `carthage checkout`
1. Open `ReactiveSwift.xcworkspace`
1. Build `ReactiveSwift-macOS` scheme
1. Finally open the `ReactiveSwift.playground`
1. Choose `View > Show Debug Area`
*/
import ReactiveSwift
import Foundation
/*:
## SignalProducer
A **signal producer**, represented by the [`SignalProducer`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/SignalProducer.swift) type, creates
[signals](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/Signal.swift) and performs side effects.
They can be used to represent operations or tasks, like network
requests, where each invocation of `start()` will create a new underlying
operation, and allow the caller to observe the result(s). The
`startWithSignal()` variant gives access to the produced signal, allowing it to
be observed multiple times if desired.
Because of the behavior of `start()`, each signal created from the same
producer may see a different ordering or version of events, or the stream might
even be completely different! Unlike a plain signal, no work is started (and
thus no events are generated) until an observer is attached, and the work is
restarted anew for each additional observer.
Starting a signal producer returns a [disposable](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/Disposable.swift) that can be used to
interrupt/cancel the work associated with the produced signal.
Just like signals, signal producers can also be manipulated via primitives
like `map`, `filter`, etc.
Every signal primitive can be “lifted” to operate upon signal producers instead,
using the `lift` method.
Furthermore, there are additional primitives that control _when_ and _how_ work
is started—for example, `times`.
*/
/*:
### `Subscription`
A SignalProducer represents an operation that can be started on demand. Starting the operation returns a Signal on which the result(s) of the operation can be observed. This behavior is sometimes also called "cold".
This means that a subscriber will never miss any values sent by the SignalProducer.
*/
scopedExample("Subscription") {
let producer = SignalProducer<Int, Never> { observer, _ in
print("New subscription, starting operation")
observer.send(value: 1)
observer.send(value: 2)
}
let subscriber1 = Signal<Int, Never>.Observer(value: { print("Subscriber 1 received \($0)") })
let subscriber2 = Signal<Int, Never>.Observer(value: { print("Subscriber 2 received \($0)") })
print("Subscriber 1 subscribes to producer")
producer.start(subscriber1)
print("Subscriber 2 subscribes to producer")
// Notice, how the producer will start the work again
producer.start(subscriber2)
}
/*:
### `empty`
A producer for a Signal that will immediately complete without sending
any values.
*/
scopedExample("`empty`") {
let emptyProducer = SignalProducer<Int, Never>.empty
let observer = Signal<Int, Never>.Observer(
value: { _ in print("value not called") },
failed: { _ in print("error not called") },
completed: { print("completed called") }
)
emptyProducer.start(observer)
}
/*:
### `never`
A producer for a Signal that never sends any events to its observers.
*/
scopedExample("`never`") {
let neverProducer = SignalProducer<Int, Never>.never
let observer = Signal<Int, Never>.Observer(
value: { _ in print("value not called") },
failed: { _ in print("error not called") },
completed: { print("completed not called") }
)
neverProducer.start(observer)
}
/*:
### `startWithSignal`
Creates a Signal from the producer, passes it into the given closure,
then starts sending events on the Signal when the closure has returned.
The closure will also receive a disposable which can be used to
interrupt the work associated with the signal and immediately send an
`Interrupted` event.
*/
scopedExample("`startWithSignal`") {
var started = false
var value: Int?
SignalProducer<Int, Never>(value: 42)
.on(value: {
value = $0
})
.startWithSignal { signal, disposable in
print(value)
}
print(value)
}
/*:
### `startWithResult`
Creates a Signal from the producer, then adds exactly one observer to
the Signal, which will invoke the given callback when `value` or `failed`
events are received.
Returns a Disposable which can be used to interrupt the work associated
with the Signal, and prevent any future callbacks from being invoked.
*/
scopedExample("`startWithResult`") {
SignalProducer<Int, Never>(value: 42)
.startWithResult { result in
print(result)
}
}
/*:
### `startWithValues`
Creates a Signal from the producer, then adds exactly one observer to
the Signal, which will invoke the given callback when `value` events are
received.
This method is available only if the producer never emits error, or in
other words, has an error type of `Never`.
Returns a Disposable which can be used to interrupt the work associated
with the Signal, and prevent any future callbacks from being invoked.
*/
scopedExample("`startWithValues`") {
SignalProducer<Int, Never>(value: 42)
.startWithValues { value in
print(value)
}
}
/*:
### `startWithCompleted`
Creates a Signal from the producer, then adds exactly one observer to
the Signal, which will invoke the given callback when a `completed` event is
received.
Returns a Disposable which can be used to interrupt the work associated
with the Signal.
*/
scopedExample("`startWithCompleted`") {
SignalProducer<Int, Never>(value: 42)
.startWithCompleted {
print("completed called")
}
}
/*:
### `startWithFailed`
Creates a Signal from the producer, then adds exactly one observer to
the Signal, which will invoke the given callback when a `failed` event is
received.
Returns a Disposable which can be used to interrupt the work associated
with the Signal.
*/
scopedExample("`startWithFailed`") {
SignalProducer<Int, NSError>(error: NSError(domain: "example", code: 42, userInfo: nil))
.startWithFailed { error in
print(error)
}
}
/*:
### `startWithInterrupted`
Creates a Signal from the producer, then adds exactly one observer to
the Signal, which will invoke the given callback when an `interrupted` event
is received.
Returns a Disposable which can be used to interrupt the work associated
with the Signal.
*/
scopedExample("`startWithInterrupted`") {
let disposable = SignalProducer<Int, Never>.never
.startWithInterrupted {
print("interrupted called")
}
disposable.dispose()
}
/*:
### `lift`
Lifts an unary Signal operator to operate upon SignalProducers instead.
In other words, this will create a new SignalProducer which will apply
the given Signal operator to _every_ created Signal, just as if the
operator had been applied to each Signal yielded from start().
*/
scopedExample("`lift`") {
var counter = 0
let transform: (Signal<Int, Never>) -> Signal<Int, Never> = { signal in
counter = 42
return signal
}
SignalProducer<Int, Never>(value: 0)
.lift(transform)
.startWithValues { _ in
print(counter)
}
}
/*:
### `map`
Maps each value in the producer to a new value.
*/
scopedExample("`map`") {
SignalProducer<Int, Never>(value: 1)
.map { $0 + 41 }
.startWithValues { value in
print(value)
}
}
/*:
### `mapError`
Maps errors in the producer to a new error.
*/
scopedExample("`mapError`") {
SignalProducer<Int, NSError>(error: NSError(domain: "mapError", code: 42, userInfo: nil))
.mapError { PlaygroundError.example($0.description) }
.startWithFailed { error in
print(error)
}
}
/*:
### `filter`
Preserves only the values of the producer that pass the given predicate.
*/
scopedExample("`filter`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.filter { $0 > 3 }
.startWithValues { value in
print(value)
}
}
/*:
### `take(first:)`
Returns a producer that will yield the first `count` values from the
input producer.
*/
scopedExample("`take(first:)`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.take(first: 2)
.startWithValues { value in
print(value)
}
}
/*:
### `observe(on:)`
Forwards all events onto the given scheduler, instead of whichever
scheduler they originally arrived upon.
*/
scopedExample("`observe(on:)`") {
let baseProducer = SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
let completion = { print("is main thread? \(Thread.current.isMainThread)") }
baseProducer
.observe(on: QueueScheduler(qos: .default, name: "test"))
.startWithCompleted(completion)
baseProducer
.startWithCompleted(completion)
}
/*:
### `collect`
Returns a producer that will yield an array of values until it completes.
*/
scopedExample("`collect`") {
SignalProducer<Int, Never> { observer, disposable in
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.send(value: 4)
observer.sendCompleted()
}
.collect()
.startWithValues { value in
print(value)
}
}
/*:
### `collect(count:)`
Returns a producer that will yield an array of values until it reaches a certain count.
*/
scopedExample("`collect(count:)`") {
SignalProducer<Int, Never> { observer, disposable in
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.send(value: 4)
observer.sendCompleted()
}
.collect(count: 2)
.startWithValues { value in
print(value)
}
}
/*:
### `collect(_:)` matching values inclusively
Returns a producer that will yield an array of values based on a predicate
which matches the values collected.
When producer completes any remaining values will be sent, the last values
array may not match `predicate`. Alternatively, if were not collected any
values will sent an empty array of values.
*/
scopedExample("`collect(_:)` matching values inclusively") {
SignalProducer<Int, Never> { observer, disposable in
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.send(value: 4)
observer.sendCompleted()
}
.collect { values in values.reduce(0, +) == 3 }
.startWithValues { value in
print(value)
}
}
/*:
### `collect(_:)` matching values exclusively
Returns a producer that will yield an array of values based on a predicate
which matches the values collected and the next value.
When producer completes any remaining values will be sent, the last values
array may not match `predicate`. Alternatively, if were not collected any
values will sent an empty array of values.
*/
scopedExample("`collect(_:)` matching values exclusively") {
SignalProducer<Int, Never> { observer, disposable in
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.send(value: 4)
observer.sendCompleted()
}
.collect { values, next in next == 3 }
.startWithValues { value in
print(value)
}
}
/*:
### `combineLatest(with:)`
Combines the latest value of the receiver with the latest value from
the given producer.
The returned producer will not send a value until both inputs have sent at
least one value each. If either producer is interrupted, the returned producer
will also be interrupted.
*/
scopedExample("`combineLatest(with:)`") {
let producer1 = SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
let producer2 = SignalProducer<Int, Never>([ 1, 2 ])
producer1
.combineLatest(with: producer2)
.startWithValues { value in
print("\(value)")
}
}
/*:
### `skip(first:)`
Returns a producer that will skip the first `count` values, then forward
everything afterward.
*/
scopedExample("`skip(first:)`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.skip(first: 2)
.startWithValues { value in
print(value)
}
}
/*:
### `materialize`
Treats all Events from the input producer as plain values, allowing them to be
manipulated just like any other value.
In other words, this brings Events “into the monad.”
When a Completed or Failed event is received, the resulting producer will send
the Event itself and then complete. When an Interrupted event is received,
the resulting producer will send the Event itself and then interrupt.
*/
scopedExample("`materialize`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.materialize()
.startWithValues { value in
print(value)
}
}
/*:
### `materializeResults`
Treats all Results from the input producer as plain values, allowing them
to be manipulated just like any other value.
In other words, this brings Results “into the monad.”
When a Failed event is received, the resulting producer will
send the `Result.failure` itself and then complete.
*/
scopedExample("`materializeResults`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.materializeResults()
.startWithValues { value in
print(value)
}
}
/*:
### `sample(on:)`
Forwards the latest value from `self` whenever `sampler` sends a `value`
event.
If `sampler` fires before a value has been observed on `self`, nothing
happens.
Returns a producer that will send values from `self`, sampled (possibly
multiple times) by `sampler`, then complete once both input producers have
completed, or interrupt if either input producer is interrupted.
*/
scopedExample("`sample(on:)`") {
let baseProducer = SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
let sampledOnProducer = SignalProducer<Int, Never>([ 1, 2 ])
.map { _ in () }
baseProducer
.sample(on: sampledOnProducer)
.startWithValues { value in
print(value)
}
}
/*:
### `combinePrevious`
Forwards events from `self` with history: values of the returned producer
are a tuple whose first member is the previous value and whose second member
is the current value. `initial` is supplied as the first member when `self`
sends its first value.
*/
scopedExample("`combinePrevious`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.combinePrevious(42)
.startWithValues { value in
print("\(value)")
}
}
/*:
### `scan`
Aggregates `self`'s values into a single combined value. When `self` emits
its first value, `combine` is invoked with `initial` as the first argument and
that emitted value as the second argument. The result is emitted from the
producer returned from `scan`. That result is then passed to `combine` as the
first argument when the next value is emitted, and so on.
*/
scopedExample("`scan`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.scan(0, +)
.startWithValues { value in
print(value)
}
}
/*:
### `reduce`
Like `scan`, but sends only the final value and then immediately completes.
*/
scopedExample("`reduce`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.reduce(0, +)
.startWithValues { value in
print(value)
}
}
/*:
### `skipRepeats`
Forwards only those values from `self` which do not pass `isRepeat` with
respect to the previous value. The first value is always forwarded.
*/
scopedExample("`skipRepeats`") {
SignalProducer<Int, Never>([ 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4 ])
.skipRepeats(==)
.startWithValues { value in
print(value)
}
}
/*:
### `skip(while:)`
Does not forward any values from `self` until `predicate` returns false,
at which point the returned signal behaves exactly like `self`.
*/
scopedExample("`skip(while:)`") {
// Note that trailing closure is used for `skip(while:)`.
SignalProducer<Int, Never>([ 3, 3, 3, 3, 1, 2, 3, 4 ])
.skip { $0 > 2 }
.startWithValues { value in
print(value)
}
}
/*:
### `take(untilReplacement:)`
Forwards events from `self` until `replacement` begins sending events.
Returns a producer which passes through `value`, `failed`, and `interrupted`
events from `self` until `replacement` sends an event, at which point the
returned producer will send that event and switch to passing through events
from `replacement` instead, regardless of whether `self` has sent events
already.
*/
scopedExample("`take(untilReplacement:)`") {
let (replacementSignal, incomingReplacementObserver) = Signal<Int, Never>.pipe()
let baseProducer = SignalProducer<Int, Never> { incomingObserver, _ in
incomingObserver.send(value: 1)
incomingObserver.send(value: 2)
incomingObserver.send(value: 3)
incomingReplacementObserver.send(value: 42)
incomingObserver.send(value: 4)
incomingReplacementObserver.send(value: 42)
}
baseProducer
.take(untilReplacement: replacementSignal)
.startWithValues { value in
print(value)
}
}
/*:
### `take(last:)`
Waits until `self` completes and then forwards the final `count` values
on the returned producer.
*/
scopedExample("`take(last:)`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.take(last: 2)
.startWithValues { value in
print(value)
}
}
/*:
### `skipNil`
Unwraps non-`nil` values and forwards them on the returned signal, `nil`
values are dropped.
*/
scopedExample("`skipNil`") {
SignalProducer<Int?, Never>([ nil, 1, 2, nil, 3, 4, nil ])
.skipNil()
.startWithValues { value in
print(value)
}
}
/*:
### `zip(with:)`
Zips elements of two producers into pairs. The elements of any Nth pair
are the Nth elements of the two input producers.
*/
scopedExample("`zip(with:)`") {
let baseProducer = SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
let zippedProducer = SignalProducer<Int, Never>([ 42, 43 ])
baseProducer
.zip(with: zippedProducer)
.startWithValues { value in
print("\(value)")
}
}
/*:
### `repeat`
Repeats `self` a total of `count` times. Repeating `1` times results in
an equivalent signal producer.
*/
scopedExample("`repeat`") {
var counter = 0
SignalProducer<(), Never> { observer, disposable in
counter += 1
observer.sendCompleted()
}
.repeat(42)
.start()
print(counter)
}
/*:
### `retry(upTo:)`
Ignores failures up to `count` times.
*/
scopedExample("`retry(upTo:)`") {
var tries = 0
SignalProducer<Int, NSError> { observer, disposable in
if tries == 0 {
tries += 1
observer.send(error: NSError(domain: "retry", code: 0, userInfo: nil))
} else {
observer.send(value: 42)
observer.sendCompleted()
}
}
.retry(upTo: 1)
.startWithResult { result in
print(result)
}
}
/*:
### `then`
Waits for completion of `producer`, *then* forwards all events from
`replacement`. Any failure sent from `producer` is forwarded immediately, in
which case `replacement` will not be started, and none of its events will be
be forwarded. All values sent from `producer` are ignored.
*/
scopedExample("`then`") {
let baseProducer = SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
let thenProducer = SignalProducer<Int, Never>(value: 42)
baseProducer
.then(thenProducer)
.startWithValues { value in
print(value)
}
}
/*:
### `replayLazily(upTo:)`
Creates a new `SignalProducer` that will multicast values emitted by
the underlying producer, up to `capacity`.
This means that all clients of this `SignalProducer` will see the same version
of the emitted values/errors.
The underlying `SignalProducer` will not be started until `self` is started
for the first time. When subscribing to this producer, all previous values
(up to `capacity`) will be emitted, followed by any new values.
If you find yourself needing *the current value* (the last buffered value)
you should consider using `PropertyType` instead, which, unlike this operator,
will guarantee at compile time that there's always a buffered value.
This operator is not recommended in most cases, as it will introduce an implicit
relationship between the original client and the rest, so consider alternatives
like `PropertyType`, `SignalProducer.buffer`, or representing your stream using
a `Signal` instead.
This operator is only recommended when you absolutely need to introduce
a layer of caching in front of another `SignalProducer`.
This operator has the same semantics as `SignalProducer.buffer`.
*/
scopedExample("`replayLazily(upTo:)`") {
let baseProducer = SignalProducer<Int, Never>([ 1, 2, 3, 4, 42 ])
.replayLazily(upTo: 2)
baseProducer.startWithValues { value in
print(value)
}
baseProducer.startWithValues { value in
print(value)
}
baseProducer.startWithValues { value in
print(value)
}
}
/*:
### `flatMap(.latest)`
Maps each event from `self` to a new producer, then flattens the
resulting producers (into a producer of values), according to the
semantics of the given strategy.
If `self` or any of the created producers fail, the returned producer
will forward that failure immediately.
*/
scopedExample("`flatMap(.latest)`") {
SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
.flatMap(.latest) { SignalProducer(value: $0 + 3) }
.startWithValues { value in
print(value)
}
}
/*:
### `flatMapError`
Catches any failure that may occur on the input producer, mapping to a new producer
that starts in its place.
*/
scopedExample("`flatMapError`") {
SignalProducer<Int, NSError>(error: NSError(domain: "flatMapError", code: 42, userInfo: nil))
.flatMapError { SignalProducer<Int, Never>(value: $0.code) }
.startWithValues { value in
print(value)
}
}
/*:
### `sample(with:)`
Forwards the latest value from `self` with the value from `sampler` as a tuple,
only when `sampler` sends a `value` event.
If `sampler` fires before a value has been observed on `self`, nothing happens.
Returns a producer that will send values from `self` and `sampler`,
sampled (possibly multiple times) by `sampler`, then complete once both
input producers have completed, or interrupt if either input producer is interrupted.
*/
scopedExample("`sample(with:)`") {
let producer = SignalProducer<Int, Never>([ 1, 2, 3, 4 ])
let sampler = SignalProducer<String, Never>([ "a", "b" ])
let result = producer.sample(with: sampler)
result.startWithValues { left, right in
print("\(left) \(right)")
}
}
/*:
### `logEvents`
Logs all events that the receiver sends.
By default, it will print to the standard output.
*/
scopedExample("`log events`") {
let baseProducer = SignalProducer<Int, Never>([ 1, 2, 3, 4, 42 ])
baseProducer
.logEvents(identifier: "Playground is fun!")
.start()
}
|
mit
|
54466e6ebc3bbbc902967ca726983f5f
| 27.085459 | 215 | 0.720332 | 3.779437 | false | false | false | false |
yorcent/spdbapp
|
spdbapp/spdbapp/Models.swift
|
1
|
1261
|
//
// Models.swift
// spdbapp
//
// Created by tommy on 15/5/11.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import Foundation
protocol GBModelBaseAciton {
func Add()
func Update()
func Del()
func Find()
}
//meeting type
enum GBMeetingType {
case HANGBAN, DANGBAN, DANGWEI, DONGSHI, dangzheng, dongshihui,ALL
}
class GBBase: NSObject {
var basename = ""
}
class GBBox: GBBase {
var macId : String = "11-22-33-44-55-66"
var type : GBMeetingType?
//add new name
var name: String = ""
override init(){
super.init()
//Defualt type = HANGBAN
type = GBMeetingType.ALL
macId = GBNetwork.getMacId()
//add new name
name = ""
}
}
class GBMeeting: GBBase {
var name: String = ""
var type : GBMeetingType = .ALL
var startTime: NSDate = NSDate()
var status: Bool?
var files:[GBDoc] = []
var id: String = ""
}
class GBDoc: GBBase {
var id: String = ""
var index: Int = 0
var count: Int = 0
var type: GBMeetingType = .ALL
var status: Bool?
var pdfPath: String = ""
var size: Int = 0
var createAt: String = ""
var path: String = ""
var name: String = ""
}
|
bsd-3-clause
|
7fca53299bab13bd347e327c31d70068
| 16.732394 | 70 | 0.568705 | 3.287206 | false | false | false | false |
yangding39/swift-study
|
swift-study/FirstPlayGround.playground/section-1.swift
|
1
|
268
|
// Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var str1 = "the first playGround 程序"
var unicodeString = ""
var c in str1.utf8 {
unicodeString += c
}
unicodeString = "" + unicodeString
println(unicodeString)
|
mit
|
11c67580dbeabf8e58245fbb0fe91656
| 16.6 | 51 | 0.708333 | 3.384615 | false | false | false | false |
anbo0123/ios5-weibo
|
microblog/microblog/Classes/Tool/ABNetworkTools.swift
|
1
|
1417
|
//
// ABNetworkTools.swift
// microblog
//
// Created by 安波 on 15/10/28.
// Copyright © 2015年 anbo. All rights reserved.
//
import UIKit
import AFNetworking
class ABNetworkTools: AFHTTPSessionManager {
/// 1.创建网络单例工具(继承AFN)
static let sharedInstance: ABNetworkTools = {
// 拼接接口路径
let baseURL = NSURL(string: "https://api.weibo.com/")
// 根据baseURL创建单例工具
let tools = ABNetworkTools(baseURL: baseURL)
// 返回创建的工具
return tools
}()
// MARK: - OAuth授权
// 2.OAuth授权
/// 2.0申请应用时,分配的APPKey
private let client_id = "296455517"
/// 申请应用时,分配的AppSecret
private let client_secret = "d017505f61aa32f4a727c0bbb15bb2bb"
/// 请求的类型,填写authorization_code
private let grant_type = "authorization_code"
/// 2.1回调地址
private let redirect_uri = "http://www.baidu.com/"
/// OAuthURL 地址
func oauthURl() -> NSURL {
// 拼接测试地址: 2.0 + 2.1
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
// 返回拼接好的地址(注意:以上地址是字符型,需要转换为NSURL,且需要强制拆包处理)
return NSURL(string: urlString)!
}
}
|
apache-2.0
|
20321e3612fc6aa028327c9dd5c13741
| 23.791667 | 116 | 0.612605 | 3.371105 | false | false | false | false |
WestlakeAPC/game-off-2016
|
external/Fiber2D/Fiber2D/Renderer/bgfx/BGFXRenderer.swift
|
1
|
5501
|
//
// BGFXRenderer.swift
// Fiber2D
//
// Created by Stuart Carnie on 9/11/16.
// Copyright © 2016 s1ddok. All rights reserved.
//
import SwiftMath
import Cbgfx
import SwiftBGFX
internal let ROOT_RTT_ID = UInt8(0)
internal let ROOT_VIEW_ID = UInt8(190)
let vs_shader =
"using namespace metal; \n" +
"struct xlatMtlShaderInput { \n" +
" float4 a_position [[attribute(0)]]; \n" +
" float2 a_texcoord0 [[attribute(1)]]; \n" +
" float2 a_texcoord1 [[attribute(2)]]; \n" +
" float4 a_color0 [[attribute(3)]]; \n" +
"}; \n" +
"struct xlatMtlShaderOutput { \n" +
" float4 gl_Position [[position]]; \n" +
" float2 v_texcoord0; " +
" float2 v_texcoord1; " +
" float4 v_color0; \n" +
"}; \n" +
"struct xlatMtlShaderUniform { \n" +
" float4x4 u_modelViewProj; \n" +
"}; \n" +
"vertex xlatMtlShaderOutput xlatMtlMain (xlatMtlShaderInput _mtl_i [[stage_in]], constant xlatMtlShaderUniform& _mtl_u [[buffer(0)]]) \n" +
"{ \n" +
" xlatMtlShaderOutput _mtl_o; \n" +
" float4 tmpvar_1; \n" +
" //tmpvar_1.w = 1.0; \n" +
" tmpvar_1 = _mtl_i.a_position; \n" +
//" _mtl_o.gl_Position = (_mtl_u.u_modelViewProj * tmpvar_1); \n" +
" _mtl_o.gl_Position = _mtl_i.a_position; \n" +
" _mtl_o.v_texcoord0 = _mtl_i.a_texcoord0; \n" +
" _mtl_o.v_texcoord1 = _mtl_i.a_texcoord1; \n" +
" _mtl_o.v_color0 = _mtl_i.a_color0; \n" +
" return _mtl_o; \n" +
"} \n";
let fs_shader =
"using namespace metal; \n" +
"struct xlatMtlShaderInput { \n" +
" float4 v_color0; \n" +
"}; \n" +
"struct xlatMtlShaderOutput { \n" +
" float4 gl_FragColor; \n" +
"}; \n" +
"struct xlatMtlShaderUniform { \n" +
"}; \n" +
"fragment xlatMtlShaderOutput xlatMtlMain (xlatMtlShaderInput _mtl_i [[stage_in]], constant xlatMtlShaderUniform& _mtl_u [[buffer(0)]]) \n" +
"{ \n" +
" xlatMtlShaderOutput _mtl_o; \n" +
" _mtl_o.gl_FragColor = _mtl_i.v_color0; \n" +
" return _mtl_o; \n" +
"} \n"
let fs_texture_shader =
"using namespace metal; \n" +
"struct xlatMtlShaderInput { \n" +
" float4 v_color0; \n" +
" float2 v_texcoord0; \n" +
"}; \n" +
"struct xlatMtlShaderOutput { \n" +
" float4 gl_FragColor; \n" +
"}; \n" +
"struct xlatMtlShaderUniform { \n" +
"}; \n" +
"fragment xlatMtlShaderOutput xlatMtlMain (xlatMtlShaderInput _mtl_i [[stage_in]]," +
" constant xlatMtlShaderUniform& _mtl_u [[buffer(0)]], \n" +
" texture2d<float> u_mainTexture [[texture(0)]]," +
" sampler u_mainTextureSampler [[sampler(0)]])" +
"{ \n" +
" xlatMtlShaderOutput _mtl_o; \n" +
" _mtl_o.gl_FragColor = _mtl_i.v_color0 * u_mainTexture.sample(u_mainTextureSampler, _mtl_i.v_texcoord0); \n" +
" return _mtl_o; \n" +
"} \n"
extension Program {
public static let posColor: Program = {
let vs = Shader(source: vs_shader, language: .metal, type: .vertex)
let fs = Shader(source: fs_shader, language: .metal, type: .fragment)
return Program(vertex: vs, fragment: fs)
}()
public static let posTexture: Program = {
let vs = Shader(source: vs_shader, language: .metal, type: .vertex)
let fs = Shader(source: fs_texture_shader, language: .metal, type: .fragment)
return Program(vertex: vs, fragment: fs)
}()
}
internal class BGFXRenderer: Renderer {
internal var viewStack = [UInt8]()
internal var currentViewID = ROOT_VIEW_ID
internal var currentRenderTargetViewID = ROOT_RTT_ID
init() {
bgfx.frame()
bgfx.debug = [.text]
}
func enqueueClear(color: vec4) {
bgfx.setViewClear(viewId: currentViewID, options: [.color, .depth], rgba: 0x30_30_30_ff, depth: 1.0, stencil: 0)
}
func prepare(withProjection proj: Matrix4x4f) {
bgfx.setViewSequential(viewId: currentViewID, enabled: true)
bgfx.setViewRect(viewId: currentViewID, x: 0, y: 0, ratio: .equal)
bgfx.touch(currentViewID)
bgfx.setViewTransform(viewId: currentViewID, proj: proj)
}
public func submit(shader: Program) {
bgfx.submit(currentViewID, program: shader)
}
func flush() {
bgfx.debugTextClear()
bgfx.debugTextPrint(x: 0, y: 1, foreColor: .white, backColor: .darkGray, format: "going")
bgfx.frame()
//bgfx.renderFrame()
currentViewID = ROOT_VIEW_ID
currentRenderTargetViewID = ROOT_RTT_ID
}
func makeFrameBufferObject() -> FrameBufferObject {
return SwiftBGFX.FrameBuffer(ratio: .equal, format: .bgra8)
}
}
extension SwiftBGFX.FrameBuffer: FrameBufferObject {
}
extension RendererVertex {
static var layout: VertexLayout {
let l = VertexLayout()
l.begin()
.add(attrib: .position, num: 4, type: .float)
.add(attrib: .texCoord0, num: 2, type: .float)
.add(attrib: .texCoord1, num: 2, type: .float)
.add(attrib: .color0, num: 4, type: .float, normalized: true)
.end()
return l
}
}
|
apache-2.0
|
d7e419f0174c031f2f1c920ceabff9a7
| 33.375 | 149 | 0.547455 | 3.072626 | false | false | false | false |
jjatie/Charts
|
Source/Charts/Data/ChartDataSet/LineRadarChartDataSet.swift
|
1
|
1374
|
//
// LineRadarChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import CoreGraphics
import Foundation
public class LineRadarChartDataSet: LineScatterCandleRadarChartDataSet, LineRadarChartDataSetProtocol {
// MARK: - Styling functions and accessors
/// The object that is used for filling the area below the line.
/// **default**: nil
public var fill: Fill = ColorFill(color: .defaultDataSet)
/// The alpha value that is used for filling the line surface,
/// **default**: 0.33
public var fillAlpha = CGFloat(0.33)
/// line width of the chart (min = 0.0, max = 10)
///
/// **default**: 1
public var lineWidth: CGFloat {
get { _lineWidth }
set { _lineWidth = newValue.clamped(to: 0 ... 10) }
}
private var _lineWidth = CGFloat(1.0)
public var isDrawFilledEnabled = false
// MARK: NSCopying
override public func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone) as! LineRadarChartDataSet
copy.fill = fill
copy.fillAlpha = fillAlpha
copy.fill = fill
copy._lineWidth = _lineWidth
copy.isDrawFilledEnabled = isDrawFilledEnabled
return copy
}
}
|
apache-2.0
|
b3637873777d89b4dead5d8cf21f9ed5
| 27.625 | 103 | 0.653566 | 4.418006 | false | false | false | false |
RevenueCat/purchases-ios
|
Tests/UnitTests/Purchasing/CachingProductsManagerTests.swift
|
1
|
6125
|
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// CachingProductsManagerTests.swift
//
// Created by Nacho Soto on 9/14/22.
import Nimble
@testable import RevenueCat
import XCTest
@available(iOS 13.0, tvOS 13.0, watchOS 6.2, macOS 10.15, *)
@MainActor
class CachingProductsManagerTests: TestCase {
private var mockManager: MockProductsManager!
private var cachingManager: CachingProductsManager!
@MainActor
override func setUp() async throws {
try await super.setUp()
// `CachingProductsManager` is available on iOS 12, but tests
// make use of `async` APIs for simplicity.
try AvailabilityChecks.iOS13APIAvailableOrSkipTest()
let systemInfo = MockSystemInfo(finishTransactions: false)
self.mockManager = MockProductsManager(
systemInfo: systemInfo,
requestTimeout: Configuration.storeKitRequestTimeoutDefault
)
self.cachingManager = CachingProductsManager(manager: self.mockManager)
}
func testFetchesNotCachedProduct() async throws {
let product = self.createMockProduct()
self.mockManager.stubbedProductsCompletionResult = .success([product])
let result = try await self.cachingManager.products(withIdentifiers: [Self.productID])
expect(result.onlyElement) === product
self.expectProductsWereFetched(times: 1, for: Self.productID)
}
func testFetchesNotCachedProductsIfOneOfTheRequestedProductsIsNotCached() async throws {
let product1 = self.createMockProduct(identifier: "product1")
let product2 = self.createMockProduct(identifier: "product2")
// Cache 1 product
self.mockManager.stubbedProductsCompletionResult = .success([product1])
_ = try await self.cachingManager.products(withIdentifiers: [product1.productIdentifier])
// Request 2 products
self.mockManager.stubbedProductsCompletionResult = .success([product1, product2])
let result = try await self.cachingManager.products(withIdentifiers: [product1.productIdentifier,
product2.productIdentifier])
expect(result) == [product1, product2]
expect(self.mockManager.invokedProductsCount) == 2
expect(self.mockManager.invokedProductsParametersList) == [
Set([product1.productIdentifier]), // First product fetched
Set([product2.productIdentifier]) // Only second product fetched
]
}
func testRefetchesProductIfItFailedTheFirstTime() async throws {
self.mockManager.stubbedProductsCompletionResult = .failure(ErrorUtils.productRequestTimedOutError())
// This will fail
let failedResult = try? await self.cachingManager.products(withIdentifiers: [Self.productID])
expect(failedResult).to(beNil())
let product = self.createMockProduct()
self.mockManager.stubbedProductsCompletionResult = .success([product])
let result = try await self.cachingManager.products(withIdentifiers: [Self.productID])
expect(result.onlyElement) === product
self.expectProductsWereFetched(times: 2, for: Self.productID)
}
func testReturnsCachedProduct() async throws {
let product = self.createMockProduct()
self.mockManager.stubbedProductsCompletionResult = .success([product])
_ = try await self.cachingManager.products(withIdentifiers: [Self.productID])
let result = try await self.cachingManager.products(withIdentifiers: [Self.productID])
expect(result.onlyElement) === product
self.expectProductsWereFetched(times: 1, for: Self.productID)
}
func testRefetchesAfterClearingCache() async throws {
let product = self.createMockProduct()
self.mockManager.stubbedProductsCompletionResult = .success([product])
_ = try await self.cachingManager.products(withIdentifiers: [Self.productID])
self.cachingManager.clearCache()
let result = try await self.cachingManager.products(withIdentifiers: [Self.productID])
expect(result.onlyElement) === product
self.expectProductsWereFetched(times: 2, for: Self.productID)
}
func testReusesProductRequestsIfAlreadyInProgress() async throws {
let product = self.createMockProduct()
self.mockManager.productResultDelay = 0.01
self.mockManager.stubbedProductsCompletionResult = .success([product])
var tasks: [Task<Set<StoreProduct>, Error>] = []
for _ in 0..<5 {
tasks.append(Task { try await self.cachingManager.products(withIdentifiers: [Self.productID]) })
}
for task in tasks {
let result = try await task.value
expect(result.onlyElement) === product
}
self.expectProductsWereFetched(times: 1, for: Self.productID)
}
}
// MARK: - Private
@available(iOS 13.0, tvOS 13.0, watchOS 6.2, macOS 10.15, *)
private extension CachingProductsManagerTests {
static let productID = "com.revenuecat.product_id"
func expectProductsWereFetched(
times: Int,
for identifiers: String...,
file: FileString = #file,
line: UInt = #line
) {
expect(file: file, line: line, self.mockManager.invokedProductsCount)
.to(equal(times), description: "Products fetched an unexpected number of times")
expect(file: file, line: line, self.mockManager.invokedProductsParameters) == Set(identifiers)
}
func createMockProduct(identifier: String = CachingProductsManagerTests.productID) -> StoreProduct {
// Using SK1 products because they can be mocked, but `CachingProductsManager
// works with generic `StoreProduct`s regardless of what they contain
return StoreProduct(sk1Product: MockSK1Product(mockProductIdentifier: identifier))
}
}
|
mit
|
f673e957edaaeeeadcb1ee04c76b6387
| 37.28125 | 109 | 0.692408 | 4.601803 | false | true | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureCryptoDomain/Sources/FeatureCryptoDomainUI/SearchCryptoDomain/SearchCryptoDomainView.swift
|
1
|
6055
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import BlockchainComponentLibrary
import ComposableArchitecture
import ComposableNavigation
import DIKit
import FeatureCryptoDomainDomain
import Localization
import SwiftUI
import ToolKit
struct SearchCryptoDomainView: View {
private typealias LocalizedString = LocalizationConstants.FeatureCryptoDomain.SearchDomain
private typealias Accessibility = AccessibilityIdentifiers.SearchDomain
private let store: Store<SearchCryptoDomainState, SearchCryptoDomainAction>
init(store: Store<SearchCryptoDomainState, SearchCryptoDomainAction>) {
self.store = store
}
var body: some View {
WithViewStore(store) { viewStore in
VStack(spacing: Spacing.padding2) {
searchBar
.padding([.top, .leading, .trailing], Spacing.padding3)
alertCardDescription
.padding([.leading, .trailing], Spacing.padding3)
domainList
}
.onAppear {
viewStore.send(.onAppear)
}
.primaryNavigation(title: LocalizedString.title)
.bottomSheet(isPresented: viewStore.binding(\.$isPremiumDomainBottomSheetShown)) {
createPremiumDomainBottomSheet()
}
.navigationRoute(in: store)
}
}
private var searchBar: some View {
WithViewStore(store) { viewStore in
SearchBar(
text: viewStore.binding(\.$searchText),
isFirstResponder: viewStore.binding(\.$isSearchFieldSelected),
cancelButtonText: LocalizationConstants.cancel,
subText: viewStore.isSearchTextValid ? nil : LocalizedString.SearchBar.error,
subTextStyle: viewStore.isSearchTextValid ? .default : .error,
placeholder: LocalizedString.title,
onReturnTapped: {
viewStore.send(.set(\.$isSearchFieldSelected, false))
}
)
.accessibilityIdentifier(Accessibility.searchBar)
}
}
private var alertCardDescription: some View {
WithViewStore(store) { viewStore in
if viewStore.isAlertCardShown {
AlertCard(
title: LocalizedString.Description.title,
message: LocalizedString.Description.body,
onCloseTapped: {
viewStore.send(.set(\.$isAlertCardShown, false), animation: .linear)
}
)
.accessibilityIdentifier(Accessibility.alertCard)
}
}
}
private var domainList: some View {
WithViewStore(store) { viewStore in
ScrollView {
if viewStore.isSearchResultsLoading {
ProgressView()
} else {
LazyVStack(spacing: 0) {
ForEach(viewStore.searchResults, id: \.domainName) { result in
PrimaryDivider()
createDomainRow(result: result)
}
PrimaryDivider()
}
}
}
.simultaneousGesture(
DragGesture().onChanged { _ in
viewStore.send(.set(\.$isSearchFieldSelected, false))
}
)
.accessibilityIdentifier(Accessibility.domainList)
}
}
private func createDomainRow(result: SearchDomainResult) -> some View {
WithViewStore(store) { viewStore in
PrimaryRow(
title: result.domainName,
subtitle: result.domainType.statusLabel,
trailing: {
TagView(
text: result.domainAvailability.availabilityLabel,
variant: result.domainAvailability == .availableForFree ?
.success : result.domainAvailability == .unavailable ? .default : .infoAlt
)
},
action: {
viewStore.send(.set(\.$isSearchFieldSelected, false))
switch result.domainType {
case .free:
viewStore.send(.selectFreeDomain(result))
case .premium:
viewStore.send(.selectPremiumDomain(result))
}
}
)
.disabled(result.domainAvailability == .unavailable)
.accessibilityIdentifier(Accessibility.domainListRow)
}
}
private func createPremiumDomainBottomSheet() -> some View {
WithViewStore(store) { viewStore in
BuyDomainActionView(
domainName: viewStore.selectedPremiumDomain?.domainName ?? "",
redirectUrl: viewStore.selectedPremiumDomainRedirectUrl ?? "",
isShown: viewStore.binding(\.$isPremiumDomainBottomSheetShown)
)
}
}
}
#if DEBUG
@testable import FeatureCryptoDomainData
@testable import FeatureCryptoDomainMock
struct SearchCryptoDomainView_Previews: PreviewProvider {
static var previews: some View {
SearchCryptoDomainView(
store: .init(
initialState: .init(),
reducer: searchCryptoDomainReducer,
environment: .init(
mainQueue: .main,
analyticsRecorder: NoOpAnalyticsRecorder(),
externalAppOpener: ToLogAppOpener(),
searchDomainRepository: SearchDomainRepository(
apiClient: SearchDomainClient.mock
),
orderDomainRepository: OrderDomainRepository(
apiClient: OrderDomainClient.mock
),
userInfoProvider: { .empty() }
)
)
)
}
}
#endif
|
lgpl-3.0
|
a47d9a7165a891a72035745a32cac8b2
| 35.914634 | 102 | 0.555005 | 5.941119 | false | false | false | false |
yichizhang/YZPolygonHelper
|
YZPolygonHelperDemo/YZPolygonHelperDemo/PolygonView.swift
|
1
|
986
|
//
// PolygonView.swift
// YZPolygonHelperDemo
//
// Created by Yichi on 16/12/2014.
// Copyright (c) 2014 Yichi Zhang. All rights reserved.
//
import UIKit
class PolygonView: UIView {
var polygonsArray:Array<Polygon> = []
override func draw(_ rect: CGRect) {
super.draw(rect)
UIColor.white.setFill()
var ctx = UIGraphicsGetCurrentContext()
ctx?.fill(rect)
let path = UIBezierPath()
var idx = 0
for polygon:Polygon in self.polygonsArray {
for pointView:ControlPointView in polygon.controlPointViewsArray {
if (idx == 0){
path.move(to: pointView.center)
} else {
path.addLine(to: pointView.center)
}
idx += 1
}
}
path.close()
UIColor.purple.setStroke()
path.stroke()
}
func updatePolygons() {
for polygon:Polygon in self.polygonsArray {
polygon.updateCentroid()
}
}
func addPolygon(polygon:Polygon){
self.polygonsArray.append(polygon)
polygon.addToView(view: self)
}
}
|
mit
|
1776b2707a69c41bb4a5ec0e52695ce5
| 16.927273 | 69 | 0.658215 | 3.319865 | false | false | false | false |
apple/swift
|
stdlib/public/core/UnicodeScalar.swift
|
4
|
16480
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Unicode.Scalar Type
//===----------------------------------------------------------------------===//
extension Unicode {
/// A Unicode scalar value.
///
/// The `Unicode.Scalar` type, representing a single Unicode scalar value, is
/// the element type of a string's `unicodeScalars` collection.
///
/// You can create a `Unicode.Scalar` instance by using a string literal that
/// contains a single character representing exactly one Unicode scalar value.
///
/// let letterK: Unicode.Scalar = "K"
/// let kim: Unicode.Scalar = "김"
/// print(letterK, kim)
/// // Prints "K 김"
///
/// You can also create Unicode scalar values directly from their numeric
/// representation.
///
/// let airplane = Unicode.Scalar(9992)!
/// print(airplane)
/// // Prints "✈︎"
@frozen
public struct Scalar: Sendable {
@usableFromInline
internal var _value: UInt32
@inlinable
internal init(_value: UInt32) {
self._value = _value
}
}
}
extension Unicode.Scalar :
_ExpressibleByBuiltinUnicodeScalarLiteral,
ExpressibleByUnicodeScalarLiteral {
/// A numeric representation of the Unicode scalar.
@inlinable
public var value: UInt32 { return _value }
@_transparent
public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
self._value = UInt32(value)
}
/// Creates a Unicode scalar with the specified value.
///
/// Do not call this initializer directly. It may be used by the compiler
/// when you use a string literal to initialize a `Unicode.Scalar` instance.
///
/// let letterK: Unicode.Scalar = "K"
/// print(letterK)
/// // Prints "K"
///
/// In this example, the assignment to the `letterK` constant is handled by
/// this initializer behind the scenes.
@_transparent
public init(unicodeScalarLiteral value: Unicode.Scalar) {
self = value
}
/// Creates a Unicode scalar with the specified numeric value.
///
/// For example, the following code sample creates a `Unicode.Scalar`
/// instance with a value of an emoji character:
///
/// let codepoint: UInt32 = 127881
/// let emoji = Unicode.Scalar(codepoint)
/// print(emoji!)
/// // Prints "🎉"
///
/// In case of an invalid input value, nil is returned.
///
/// let codepoint: UInt32 = extValue // This might be an invalid value
/// if let emoji = Unicode.Scalar(codepoint) {
/// print(emoji)
/// } else {
/// // Do something else
/// }
///
/// - Parameter v: The Unicode code point to use for the scalar. The
/// initializer succeeds if `v` is a valid Unicode scalar value---that is,
/// if `v` is in the range `0...0xD7FF` or `0xE000...0x10FFFF`. If `v` is
/// an invalid Unicode scalar value, the result is `nil`.
@inlinable
public init?(_ v: UInt32) {
// Unicode 6.3.0:
//
// D9. Unicode codespace: A range of integers from 0 to 10FFFF.
//
// D76. Unicode scalar value: Any Unicode code point except
// high-surrogate and low-surrogate code points.
//
// * As a result of this definition, the set of Unicode scalar values
// consists of the ranges 0 to D7FF and E000 to 10FFFF, inclusive.
if (v < 0xD800 || v > 0xDFFF) && v <= 0x10FFFF {
self._value = v
return
}
// Return nil in case of an invalid unicode scalar value.
return nil
}
/// Creates a Unicode scalar with the specified numeric value.
///
/// For example, the following code sample creates a `Unicode.Scalar`
/// instance with a value of `"밥"`, the Korean word for rice:
///
/// let codepoint: UInt16 = 48165
/// let bap = Unicode.Scalar(codepoint)
/// print(bap!)
/// // Prints "밥"
///
/// In case of an invalid input value, the result is `nil`.
///
/// let codepoint: UInt16 = extValue // This might be an invalid value
/// if let bap = Unicode.Scalar(codepoint) {
/// print(bap)
/// } else {
/// // Do something else
/// }
///
/// - Parameter v: The Unicode code point to use for the scalar. The
/// initializer succeeds if `v` is a valid Unicode scalar value, in the
/// range `0...0xD7FF` or `0xE000...0x10FFFF`. If `v` is an invalid
/// unicode scalar value, the result is `nil`.
@inlinable
public init?(_ v: UInt16) {
self.init(UInt32(v))
}
/// Creates a Unicode scalar with the specified numeric value.
///
/// For example, the following code sample creates a `Unicode.Scalar`
/// instance with a value of `"7"`:
///
/// let codepoint: UInt8 = 55
/// let seven = Unicode.Scalar(codepoint)
/// print(seven)
/// // Prints "7"
///
/// - Parameter v: The code point to use for the scalar.
@inlinable
public init(_ v: UInt8) {
self._value = UInt32(v)
}
/// Creates a duplicate of the given Unicode scalar.
@inlinable
public init(_ v: Unicode.Scalar) {
// This constructor allows one to provide necessary type context to
// disambiguate between function overloads on 'String' and 'Unicode.Scalar'.
self = v
}
/// Returns a string representation of the Unicode scalar.
///
/// Scalar values representing characters that are normally unprintable or
/// that otherwise require escaping are escaped with a backslash.
///
/// let tab = Unicode.Scalar(9)!
/// print(tab)
/// // Prints " "
/// print(tab.escaped(asASCII: false))
/// // Prints "\t"
///
/// When the `forceASCII` parameter is `true`, a `Unicode.Scalar` instance
/// with a value greater than 127 is represented using an escaped numeric
/// value; otherwise, non-ASCII characters are represented using their
/// typical string value.
///
/// let bap = Unicode.Scalar(48165)!
/// print(bap.escaped(asASCII: false))
/// // Prints "밥"
/// print(bap.escaped(asASCII: true))
/// // Prints "\u{BC25}"
///
/// - Parameter forceASCII: Pass `true` if you need the result to use only
/// ASCII characters; otherwise, pass `false`.
/// - Returns: A string representation of the scalar.
public func escaped(asASCII forceASCII: Bool) -> String {
func lowNibbleAsHex(_ v: UInt32) -> String {
let nibble = v & 15
if nibble < 10 {
return String(Unicode.Scalar(nibble+48)!) // 48 = '0'
} else {
return String(Unicode.Scalar(nibble-10+65)!) // 65 = 'A'
}
}
if self == "\\" {
return "\\\\"
} else if self == "\'" {
return "\\\'"
} else if self == "\"" {
return "\\\""
} else if _isPrintableASCII {
return String(self)
} else if self == "\0" {
return "\\0"
} else if self == "\n" {
return "\\n"
} else if self == "\r" {
return "\\r"
} else if self == "\t" {
return "\\t"
} else if UInt32(self) < 128 {
return "\\u{"
+ lowNibbleAsHex(UInt32(self) >> 4)
+ lowNibbleAsHex(UInt32(self)) + "}"
} else if !forceASCII {
return String(self)
} else if UInt32(self) <= 0xFFFF {
var result = "\\u{"
result += lowNibbleAsHex(UInt32(self) >> 12)
result += lowNibbleAsHex(UInt32(self) >> 8)
result += lowNibbleAsHex(UInt32(self) >> 4)
result += lowNibbleAsHex(UInt32(self))
result += "}"
return result
} else {
// FIXME: Type checker performance prohibits this from being a
// single chained "+".
var result = "\\u{"
result += lowNibbleAsHex(UInt32(self) >> 28)
result += lowNibbleAsHex(UInt32(self) >> 24)
result += lowNibbleAsHex(UInt32(self) >> 20)
result += lowNibbleAsHex(UInt32(self) >> 16)
result += lowNibbleAsHex(UInt32(self) >> 12)
result += lowNibbleAsHex(UInt32(self) >> 8)
result += lowNibbleAsHex(UInt32(self) >> 4)
result += lowNibbleAsHex(UInt32(self))
result += "}"
return result
}
}
/// A Boolean value indicating whether the Unicode scalar is an ASCII
/// character.
///
/// ASCII characters have a scalar value between 0 and 127, inclusive. For
/// example:
///
/// let canyon = "Cañón"
/// for scalar in canyon.unicodeScalars {
/// print(scalar, scalar.isASCII, scalar.value)
/// }
/// // Prints "C true 67"
/// // Prints "a true 97"
/// // Prints "ñ false 241"
/// // Prints "ó false 243"
/// // Prints "n true 110"
@inlinable
public var isASCII: Bool {
return value <= 127
}
// FIXME: Unicode makes this interesting.
internal var _isPrintableASCII: Bool {
return (self >= Unicode.Scalar(0o040) && self <= Unicode.Scalar(0o176))
}
}
extension Unicode.Scalar: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the Unicode scalar.
@inlinable
public var description: String {
return String(self)
}
/// An escaped textual representation of the Unicode scalar, suitable for
/// debugging.
public var debugDescription: String {
return "\"\(escaped(asASCII: true))\""
}
}
extension Unicode.Scalar: LosslessStringConvertible {
@inlinable
public init?(_ description: String) {
let scalars = description.unicodeScalars
guard let v = scalars.first, scalars.count == 1 else {
return nil
}
self = v
}
}
extension Unicode.Scalar: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(self.value)
}
}
extension Unicode.Scalar {
/// Creates a Unicode scalar with the specified numeric value.
///
/// - Parameter v: The Unicode code point to use for the scalar. `v` must be
/// a valid Unicode scalar value, in the ranges `0...0xD7FF` or
/// `0xE000...0x10FFFF`. In case of an invalid unicode scalar value, nil is
/// returned.
///
/// For example, the following code sample creates a `Unicode.Scalar` instance
/// with a value of an emoji character:
///
/// let codepoint = 127881
/// let emoji = Unicode.Scalar(codepoint)!
/// print(emoji)
/// // Prints "🎉"
///
/// In case of an invalid input value, nil is returned.
///
/// let codepoint: UInt32 = extValue // This might be an invalid value.
/// if let emoji = Unicode.Scalar(codepoint) {
/// print(emoji)
/// } else {
/// // Do something else
/// }
@inlinable
public init?(_ v: Int) {
if let exact = UInt32(exactly: v) {
self.init(exact)
} else {
return nil
}
}
}
extension UInt8 {
/// Construct with value `v.value`.
///
/// - Precondition: `v.value` can be represented as ASCII (0..<128).
@inlinable
public init(ascii v: Unicode.Scalar) {
_precondition(v.value < 128,
"Code point value does not fit into ASCII")
self = UInt8(v.value)
}
}
extension UInt32 {
/// Construct with value `v.value`.
@inlinable
public init(_ v: Unicode.Scalar) {
self = v.value
}
}
extension UInt64 {
/// Construct with value `v.value`.
@inlinable
public init(_ v: Unicode.Scalar) {
self = UInt64(v.value)
}
}
extension Unicode.Scalar: Equatable {
@inlinable
public static func == (lhs: Unicode.Scalar, rhs: Unicode.Scalar) -> Bool {
return lhs.value == rhs.value
}
}
extension Unicode.Scalar: Comparable {
@inlinable
public static func < (lhs: Unicode.Scalar, rhs: Unicode.Scalar) -> Bool {
return lhs.value < rhs.value
}
}
extension Unicode.Scalar {
@frozen
public struct UTF16View: Sendable {
@usableFromInline
internal var value: Unicode.Scalar
@inlinable
internal init(value: Unicode.Scalar) {
self.value = value
}
}
@inlinable
public var utf16: UTF16View {
return UTF16View(value: self)
}
}
extension Unicode.Scalar.UTF16View: RandomAccessCollection {
public typealias Indices = Range<Int>
/// The position of the first code unit.
@inlinable
public var startIndex: Int {
return 0
}
/// The "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Int {
return 0 + UTF16.width(value)
}
/// Accesses the code unit at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
@inlinable
public subscript(position: Int) -> UTF16.CodeUnit {
if position == 1 { return UTF16.trailSurrogate(value) }
if endIndex == 1 { return UTF16.CodeUnit(value.value) }
return UTF16.leadSurrogate(value)
}
}
extension Unicode.Scalar {
@available(SwiftStdlib 5.1, *)
@frozen
public struct UTF8View: Sendable {
@usableFromInline
internal var value: Unicode.Scalar
@inlinable
internal init(value: Unicode.Scalar) {
self.value = value
}
}
@available(SwiftStdlib 5.1, *)
@inlinable
public var utf8: UTF8View { return UTF8View(value: self) }
}
@available(SwiftStdlib 5.1, *)
extension Unicode.Scalar.UTF8View: RandomAccessCollection {
public typealias Indices = Range<Int>
/// The position of the first code unit.
@inlinable
public var startIndex: Int { return 0 }
/// The "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Int { return 0 + UTF8.width(value) }
/// Accesses the code unit at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
@inlinable
public subscript(position: Int) -> UTF8.CodeUnit {
_precondition(position >= startIndex && position < endIndex,
"Unicode.Scalar.UTF8View index is out of bounds")
return value.withUTF8CodeUnits { $0[position] }
}
}
extension Unicode.Scalar {
internal static var _replacementCharacter: Unicode.Scalar {
return Unicode.Scalar(_value: UTF32._replacementCodeUnit)
}
}
extension Unicode.Scalar {
/// Creates an instance of the NUL scalar value.
@available(*, unavailable, message: "use 'Unicode.Scalar(0)'")
public init() {
Builtin.unreachable()
}
}
// Access the underlying code units
extension Unicode.Scalar {
// Access the scalar as encoded in UTF-16
internal func withUTF16CodeUnits<Result>(
_ body: (UnsafeBufferPointer<UInt16>) throws -> Result
) rethrows -> Result {
var codeUnits: (UInt16, UInt16) = (self.utf16[0], 0)
let utf16Count = self.utf16.count
if utf16Count > 1 {
_internalInvariant(utf16Count == 2)
codeUnits.1 = self.utf16[1]
}
return try Swift.withUnsafePointer(to: &codeUnits) {
return try $0.withMemoryRebound(to: UInt16.self, capacity: 2) {
return try body(UnsafeBufferPointer(start: $0, count: utf16Count))
}
}
}
// Access the scalar as encoded in UTF-8
@inlinable
internal func withUTF8CodeUnits<Result>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> Result
) rethrows -> Result {
let encodedScalar = UTF8.encode(self)!
var (codeUnits, utf8Count) = encodedScalar._bytes
// The first code unit is in the least significant byte of codeUnits.
codeUnits = codeUnits.littleEndian
return try Swift._withUnprotectedUnsafePointer(to: &codeUnits) {
return try $0.withMemoryRebound(to: UInt8.self, capacity: 4) {
return try body(UnsafeBufferPointer(start: $0, count: utf8Count))
}
}
}
}
|
apache-2.0
|
b83d9a0ed3cb63ae3395dbe3f8c3cc20
| 29.816479 | 81 | 0.622691 | 3.934959 | false | false | false | false |
jeffreybergier/Hipstapaper
|
Hipstapaper/Share_iOS/ShareViewController.swift
|
1
|
3504
|
//
// Created by Jeffrey Bergier on 2021/01/08.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import SwiftUI
import V3WebsiteEdit
class ShareViewController: UIViewController {
private var inputURL: URL?
private lazy var shareUIVC: UIViewController = {
let view = ShareExtension(inputURL: self.inputURL)
{ [weak extensionContext] in
extensionContext?.completeRequest(returningItems: nil,
completionHandler: nil)
}
return UIHostingController(rootView: view)
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .systemBackground
guard let context = self.extensionContext?.inputItems.first as? NSExtensionItem else {
self.configureVC()
assertionFailure("Could not get extension context")
return
}
context.urlValue() { url in
self.inputURL = url
self.configureVC()
}
}
private func configureVC() {
let vc = self.shareUIVC
vc.view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(vc.view)
self.view.addConstraints([
self.view.topAnchor.constraint(equalTo: vc.view.topAnchor, constant: 0),
self.view.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor, constant: 0),
self.view.leadingAnchor.constraint(equalTo: vc.view.leadingAnchor, constant: 0),
self.view.trailingAnchor.constraint(equalTo: vc.view.trailingAnchor, constant: 0)
])
self.addChild(vc)
}
}
#if canImport(MobileCoreServices)
import UniformTypeIdentifiers
#endif
extension NSExtensionItem {
fileprivate func urlValue(completion: @escaping (URL?) -> Void) {
let contentType = UTType.url.identifier
let _a = self.attachments?.first(where: { $0.hasItemConformingToTypeIdentifier(contentType) })
guard let attachment = _a else {
completion(nil)
return
}
attachment.loadItem(forTypeIdentifier: contentType, options: nil) { url, _ in
DispatchQueue.main.async {
guard let url = url as? URL else {
completion(nil)
return
}
completion(url)
}
}
}
}
|
mit
|
ffdd418ce87e4ccaa8a37e66ab787968
| 36.677419 | 102 | 0.656393 | 4.780355 | false | false | false | false |
AndrewBennet/readinglist
|
ReadingList/Data/UserEngagement.swift
|
1
|
5529
|
import Foundation
import StoreKit
import Firebase
import FirebaseCrashlytics
import PersistedPropertyWrapper
class UserEngagement {
static var defaultAnalyticsEnabledValue: Bool {
#if DEBUG
return false
#else
return true
#endif
}
@Persisted("sendAnalytics", defaultValue: defaultAnalyticsEnabledValue)
static var sendAnalytics: Bool
@Persisted("sendCrashReports", defaultValue: defaultAnalyticsEnabledValue)
static var sendCrashReports: Bool
static func initialiseUserAnalytics() {
guard BuildInfo.thisBuild.type == .testFlight || sendAnalytics || sendCrashReports else { return }
if FirebaseApp.app() == nil {
FirebaseApp.configure()
}
let enableCrashlyticsReporting = BuildInfo.thisBuild.type == .testFlight || sendCrashReports
Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(enableCrashlyticsReporting)
let enableAnalyticsCollection = BuildInfo.thisBuild.type == .testFlight || sendAnalytics
Analytics.setAnalyticsCollectionEnabled(enableAnalyticsCollection)
}
@Persisted("userEngagementCount", defaultValue: 0)
static var userEngagementCount: Int
private static func shouldTryRequestReview() -> Bool {
let appStartCountMinRequirement = 3
let userEngagementModulo = 10
return AppLaunchHistory.appOpenedCount >= appStartCountMinRequirement && userEngagementCount % userEngagementModulo == 0
}
static func onReviewTrigger() {
userEngagementCount += 1
if shouldTryRequestReview() {
SKStoreReviewController.requestReview()
}
}
enum Event: String {
// Add books
case searchOnline = "Search_Online"
case scanBarcode = "Scan_Barcode"
case scanBarcodeBulk = "Scan_Barcode_Bulk"
case searchOnlineMultiple = "Search_Online_Multiple"
case addManualBook = "Add_Manual_Book"
case searchForExistingBookByIsbn = "Search_For_Existing_Book_By_ISBN"
// Data
case csvImport = "CSV_Import"
case csvGoodReadsImport = "CSV_Import_Goodreads"
case csvExport = "CSV_Export"
case deleteAllData = "Delete_All_Data"
// Backup
case createBackup = "Create_Backup"
case autoBackup = "Auto_Backup"
case disableAutoBackup = "Disable_Auto_Backup"
case changeAutoBackupFrequency = "Change_Backup_Frequency"
case restoreFromBackup = "Restore_From_Backup"
case restoreFromBackupOnFirstLaunch = "First_Launch_Restore_From_Backup"
// Navigation
case searchLibrary = "Search_Library"
case searchLibrarySwitchScope = "Search_Library_Switch_Scope"
// Modify books
case transitionReadState = "Transition_Read_State"
case bulkEditReadState = "Bulk_Edit_Read_State"
case deleteBook = "Delete_Book"
case bulkDeleteBook = "Bulk_Delete_Book"
case editBook = "Edit_Book"
case updateBookFromGoogle = "Update_Book_From_Google"
case editReadState = "Edit_Read_State"
case changeSortOrder = "Change_Sort"
case moveBookToTop = "Move_Book_To_Top"
case moveBookToBottom = "Move_Book_To_Bottom"
// Lists
case createList = "Create_List"
case addBookToList = "Add_Book_To_List"
case bulkAddBookToList = "Bulk_Add_Book_To_List"
case removeBookFromList = "Remove_Book_From_List"
case reorderList = "Reorder_List"
case deleteList = "Delete_List"
case changeListSortOrder = "Change_List_Sort_Order"
case renameList = "Rename_List"
// Quick actions
case searchOnlineQuickAction = "Quick_Action_Search_Online"
case scanBarcodeQuickAction = "Quick_Action_Scan_Barcode"
// Proprietary URL launch
case openBookFromUrl = "Open_Book_From_Url"
case openEditReadLogFromUrl = "Open_Edit_Read_Log_From_Url"
case openSearchOnlineFromUrl = "Open_Search_Online_From_Url"
case openScanBarcodeFromUrl = "Open_Scan_Barcode_From_Url"
case openAddManuallyFromUrl = "Open_Add_Manually_From_Url"
// Settings changes
case disableAnalytics = "Disable_Analytics"
case enableAnalytics = "Enable_Analytics"
case disableCrashReports = "Disable_Crash_Reports"
case enableCrashReports = "Enable_Crash_Reports"
case changeTheme = "Change_Theme"
case changeSearchOnlineLanguage = "Change_Search_Online_Language"
case changeCsvImportFormat = "Change_CSV_Import_Format"
case changeCsvImportSettings = "Change_CSV_Import_Settings"
// Other
case viewOnAmazon = "View_On_Amazon"
case openCsvInApp = "Open_CSV_In_App"
}
static func logEvent(_ event: Event) {
// Note: TestFlight users are automatically enrolled in analytics reporting. This should be reflected
// on the corresponding Settings page.
guard BuildInfo.thisBuild.type == .testFlight || sendAnalytics else { return }
#if RELEASE
Analytics.logEvent(event.rawValue, parameters: nil)
#endif
}
static func logError(_ error: Error) {
// Note: TestFlight users are automatically enrolled in crash reporting. This should be reflected
// on the corresponding Settings page.
guard BuildInfo.thisBuild.type == .testFlight || sendCrashReports else { return }
Crashlytics.crashlytics().record(error: error)
}
}
|
gpl-3.0
|
f48edf590797a7093cf8a000b73fecc9
| 37.664336 | 128 | 0.677699 | 4.506112 | false | false | false | false |
vector-im/vector-ios
|
RiotSwiftUI/Modules/Spaces/SpaceCreation/SpaceCreationPostProcess/Service/Mock/MockSpaceCreationPostProcessService.swift
|
1
|
3554
|
// File created from SimpleUserProfileExample
// $ createScreen.sh Spaces/SpaceCreation/SpaceCreationPostProcess SpaceCreationPostProcess
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Combine
import UIKit
@available(iOS 14.0, *)
class MockSpaceCreationPostProcessService: SpaceCreationPostProcessServiceProtocol {
static let defaultTasks: [SpaceCreationPostProcessTask] = [
SpaceCreationPostProcessTask(type: .createSpace, title: "Space creation", state: .success),
SpaceCreationPostProcessTask(type: .createRoom("Room#1"), title: "Room#1 creation", state: .failure),
SpaceCreationPostProcessTask(type: .createRoom("Room#2"), title: "Room#2 creation", state: .started),
SpaceCreationPostProcessTask(type: .createRoom("Room#3"), title: "Room#3 creation", state: .none)
]
static let nextStepTasks: [SpaceCreationPostProcessTask] = [
SpaceCreationPostProcessTask(type: .createSpace, title: "Space creation", state: .success),
SpaceCreationPostProcessTask(type: .createRoom("Room#1"), title: "Room#1 creation", state: .failure),
SpaceCreationPostProcessTask(type: .createRoom("Room#2"), title: "Room#2 creation", state: .failure),
SpaceCreationPostProcessTask(type: .createRoom("Room#3"), title: "Room#3 creation", state: .started)
]
static let lastTaskDoneWithError: [SpaceCreationPostProcessTask] = [
SpaceCreationPostProcessTask(type: .createSpace, title: "Space creation", state: .success),
SpaceCreationPostProcessTask(type: .createRoom("Room#1"), title: "Room#1 creation", state: .failure),
SpaceCreationPostProcessTask(type: .createRoom("Room#2"), title: "Room#2 creation", state: .failure),
SpaceCreationPostProcessTask(type: .createRoom("Room#3"), title: "Room#3 creation", state: .success)
]
static let lastTaskDoneSuccesfully: [SpaceCreationPostProcessTask] = [
SpaceCreationPostProcessTask(type: .createSpace, title: "Space creation", state: .success),
SpaceCreationPostProcessTask(type: .createRoom("Room#1"), title: "Room#1 creation", state: .success),
SpaceCreationPostProcessTask(type: .createRoom("Room#2"), title: "Room#2 creation", state: .success),
SpaceCreationPostProcessTask(type: .createRoom("Room#3"), title: "Room#3 creation", state: .success)
]
var tasksSubject: CurrentValueSubject<[SpaceCreationPostProcessTask], Never>
private(set) var createdSpaceId: String?
var avatar: AvatarInput {
return AvatarInput(mxContentUri: nil, matrixItemId: "", displayName: "Some space")
}
var avatarImage: UIImage? {
return nil
}
init(
tasks: [SpaceCreationPostProcessTask] = defaultTasks
) {
self.tasksSubject = CurrentValueSubject<[SpaceCreationPostProcessTask], Never>(tasks)
}
func simulateUpdate(tasks: [SpaceCreationPostProcessTask]) {
self.tasksSubject.send(tasks)
}
func run() {
}
}
|
apache-2.0
|
8ffb93fd1e9de4e0d417220065bb2175
| 46.386667 | 109 | 0.715813 | 4.225922 | false | false | false | false |
warren-gavin/OBehave
|
OBehave/Classes/Tools/BarCodeScanner/OBBarCodeScannerBehavior.swift
|
1
|
4777
|
//
// OBBarCodeScannerBehavior.swift
// OBehave
//
// Created by Warren Gavin on 06/11/15.
// Copyright © 2015 Apokrupto. All rights reserved.
//
import UIKit
import AVFoundation
public enum OBBarCodeScannerError {
case unauthorized
case unknown
}
public protocol OBBarCodeScannerBehaviorDelegate: OBBehaviorDelegate {
func barCodeScanner(_ scanner: OBBarCodeScannerBehavior, didScanBarCodeString string: String, frame: CGRect)
func barCodeScanner(_ scanner: OBBarCodeScannerBehavior, didFailWithError error: OBBarCodeScannerError)
}
public final class OBBarCodeScannerBehavior: OBBehavior {
@IBOutlet public var containerView: UIView? {
didSet {
containerView?.layer.insertSublayer(cameraPreviewLayer, at: 0)
containerBoundsObserver = containerView?.observe(\.bounds, options: .new) { [unowned self] (_, _) in
self.updateCameraPreviewLayer()
}
}
}
private let supportedBarCodes: [AVMetadataObject.ObjectType] = [
.upce,
.code39,
.code39Mod43,
.ean13,
.ean8,
.code93,
.code128,
.pdf417,
.qr,
.aztec,
.interleaved2of5,
.itf14,
.dataMatrix
]
private lazy var session: AVCaptureSession = AVCaptureSession()
private var containerBoundsObserver: NSKeyValueObservation?
private lazy var cameraPreviewLayer: AVCaptureVideoPreviewLayer = {
var layer = AVCaptureVideoPreviewLayer(session: self.session)
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
return layer
}()
// MARK: Public
override public func setup() {
super.setup()
checkCameraAccess(completion: setupBarCodeScanner)
}
deinit {
session.stopRunning()
cameraPreviewLayer.removeFromSuperlayer()
}
/// The scanner is running by default. This method isn't necessary
/// unless you have previously called `stop()`
public func start() {
session.startRunning()
}
public func stop() {
session.stopRunning()
}
}
private extension OBBarCodeScannerBehavior {
func updateCameraPreviewLayer() {
if let containerView = containerView {
cameraPreviewLayer.frame = containerView.bounds
}
}
func checkCameraAccess(completion: @escaping (Bool) -> Void) {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
completion(true)
case .restricted, .denied:
completion(false)
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { authorized in
DispatchQueue.main.async {
completion(authorized)
}
}
@unknown default:
completion(false)
}
}
func setupBarCodeScanner(authorized: Bool) {
guard
authorized,
let device = AVCaptureDevice.default(for: AVMediaType.video),
let input = try? AVCaptureDeviceInput(device: device)
else {
let delegate: OBBarCodeScannerBehaviorDelegate? = getDelegate()
delegate?.barCodeScanner(self, didFailWithError: authorized ? .unknown : .unauthorized)
return
}
session.addInput(input)
let output = AVCaptureMetadataOutput()
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
session.addOutput(output)
output.metadataObjectTypes = output.availableMetadataObjectTypes
session.startRunning()
}
}
// MARK: AVCaptureMetadataOutputObjectsDelegate
extension OBBarCodeScannerBehavior: AVCaptureMetadataOutputObjectsDelegate {
public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
var barCodeBounds = CGRect.zero
var barCodeString = ""
for metadata in metadataObjects {
for type in supportedBarCodes {
if metadata.type == type,
let bounds = cameraPreviewLayer.transformedMetadataObject(for: metadata)?.bounds,
let stringValue = (metadata as? AVMetadataMachineReadableCodeObject)?.stringValue {
barCodeBounds = bounds
barCodeString = stringValue
break
}
}
}
let delegate: OBBarCodeScannerBehaviorDelegate? = getDelegate()
delegate?.barCodeScanner(self, didScanBarCodeString: barCodeString, frame: barCodeBounds)
}
}
|
mit
|
41ddcfb9ee82239e59f44cea5f25db31
| 30.421053 | 152 | 0.627722 | 5.553488 | false | false | false | false |
zmeyc/GRDB.swift
|
Tests/GRDBTests/RowTestCase.swift
|
1
|
5106
|
import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
class RowTestCase: GRDBTestCase {
func assertRowRawValueEqual<T: Equatable>(_ row: Row, index: Int, value: T) {
// form 1
let v = row.value(atIndex: index)
XCTAssertEqual(v as! T, value)
// form 2
XCTAssertEqual(row.value(atIndex: index) as! T, value)
// form 3
if let v = row.value(atIndex: index) as? T {
XCTAssertEqual(v, value)
} else {
XCTFail("expected succesful extraction")
}
}
func assertRowRawValueEqual<T: Equatable>(_ row: Row, name: String, value: T) {
// form 1
let v = row.value(named: name)
XCTAssertEqual(v as! T, value)
// form 2
XCTAssertEqual(row.value(named: name) as! T, value)
// form 3
if let v = row.value(named: name) as? T {
XCTAssertEqual(v, value)
} else {
XCTFail("expected succesful extraction")
}
}
func assertRowRawValueEqual<T: Equatable>(_ row: Row, column: Column, value: T) {
// form 1
let v = row.value(column)
XCTAssertEqual(v as! T, value)
// form 2
XCTAssertEqual(row.value(column) as! T, value)
// form 3
if let v = row.value(column) as? T {
XCTAssertEqual(v, value)
} else {
XCTFail("expected succesful extraction")
}
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible>(_ row: Row, index: Int, value: T) {
// form 1
XCTAssertEqual(row.value(atIndex: index) as T, value)
// form 2
XCTAssertEqual(row.value(atIndex: index)! as T, value)
// form 3
XCTAssertEqual((row.value(atIndex: index) as T?)!, value)
// form 4
if let v = row.value(atIndex: index) as T? {
XCTAssertEqual(v, value)
} else {
XCTFail("expected succesful extraction")
}
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible>(_ row: Row, name: String, value: T) {
// form 1
XCTAssertEqual(row.value(named: name) as T, value)
// form 2
XCTAssertEqual(row.value(named: name)! as T, value)
// form 3
XCTAssertEqual((row.value(named: name) as T?)!, value)
// form 4
if let v = row.value(named: name) as T? {
XCTAssertEqual(v, value)
} else {
XCTFail("expected succesful extraction")
}
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible>(_ row: Row, column: Column, value: T) {
// form 1
XCTAssertEqual(row.value(column) as T, value)
// form 2
XCTAssertEqual(row.value(column)! as T, value)
// form 3
XCTAssertEqual((row.value(column) as T?)!, value)
// form 4
if let v = row.value(column) as T? {
XCTAssertEqual(v, value)
} else {
XCTFail("expected succesful extraction")
}
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible & StatementColumnConvertible>(_ row: Row, index: Int, value: T) {
// form 1
XCTAssertEqual(row.value(atIndex: index) as T, value)
// form 2
XCTAssertEqual(row.value(atIndex: index)! as T, value)
// form 3
XCTAssertEqual((row.value(atIndex: index) as T?)!, value)
// form 4
if let v = row.value(atIndex: index) as T? {
XCTAssertEqual(v, value)
} else {
XCTFail("expected succesful extraction")
}
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible & StatementColumnConvertible>(_ row: Row, name: String, value: T) {
// form 1
XCTAssertEqual(row.value(named: name) as T, value)
// form 2
XCTAssertEqual(row.value(named: name)! as T, value)
// form 3
XCTAssertEqual((row.value(named: name) as T?)!, value)
// form 4
if let v = row.value(named: name) as T? {
XCTAssertEqual(v, value)
} else {
XCTFail("expected succesful extraction")
}
}
func assertRowConvertedValueEqual<T: Equatable & DatabaseValueConvertible & StatementColumnConvertible>(_ row: Row, column: Column, value: T) {
// form 1
XCTAssertEqual(row.value(column) as T, value)
// form 2
XCTAssertEqual(row.value(column)! as T, value)
// form 3
XCTAssertEqual((row.value(column) as T?)!, value)
// form 4
if let v = row.value(column) as T? {
XCTAssertEqual(v, value)
} else {
XCTFail("expected succesful extraction")
}
}
}
|
mit
|
1f80283cd72412783b5168b1ff13f427
| 29.57485 | 147 | 0.546024 | 4.563003 | false | false | false | false |
jegumhon/URMovingTransitionAnimator
|
Source/URMovingTransitionAnimator/URMovingTransitionMakable.swift
|
1
|
4057
|
//
// URMovingTransitionViewController.swift
// URMovingTransitionAnimator
//
// Created by jegumhon on 2017. 2. 8..
// Copyright © 2017년 chbreeze. All rights reserved.
//
import UIKit
public protocol URMovingTransitionMakable: class {
var panGesture: UIScreenEdgePanGestureRecognizer! { get set }
var animator: UIViewControllerAnimatedTransitioning? { get set }
var interactionController: UIPercentDrivenInteractiveTransition! { get set }
var movingTransitionDelegate: URMovingTransitionAnimatorDelegate! { get set }
var navigationController: UINavigationController? { get }
var isPopableViewController: Bool { get }
func makeTransitionAnimator(target: UIView, baseOn: UIView, duration: Double, needClipToBounds: Bool, scale: CGFloat, finishingDuration: TimeInterval, finishingDurationForPop: TimeInterval, isLazyCompletion: Bool)
func makeBlurredTransitionAnimator(target: UIView, baseOn: UIView, duration: Double, needClipToBounds: Bool, scale: CGFloat, finishingDuration: TimeInterval, finishingDurationForPop: TimeInterval, isLazyCompletion: Bool)
}
extension URMovingTransitionMakable where Self: UIViewController {
var navigationController: UINavigationController? {
return self.navigationController
}
public var isPopableViewController: Bool {
guard let navigationController = self.navigationController else { return false }
let navigationStackCount = navigationController.viewControllers.count
if navigationStackCount > 1 {
if navigationController.viewControllers[navigationStackCount - 2] is URMovingTransitionMakable {
return true
}
}
return false
}
/// recommend to call at viewDidLoad
public func initMovingTrasitionGesture() {
self.movingTransitionDelegate = URMovingTransitionAnimatorDelegate(movingTransitionViewController: self)
self.panGesture = self.movingTransitionDelegate.makeGesture()
self.navigationController?.view.addGestureRecognizer(self.panGesture)
self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}
/// need to call at viewWillAppear
public func initMovingTransitionNavigationDelegate() {
self.navigationController?.delegate = self.movingTransitionDelegate
}
/// recommend to call at deinit
public func removeMovingTransitionGesture() {
self.navigationController?.view.removeGestureRecognizer(self.panGesture)
}
public func makeTransitionAnimator(target: UIView, baseOn: UIView, duration: Double, needClipToBounds: Bool = false, scale: CGFloat = 1.0, finishingDuration: TimeInterval = 0.8, finishingDurationForPop: TimeInterval = 0.2, isLazyCompletion: Bool = false) {
if let _ = self.navigationController?.delegate as? URMovingTransitionAnimatorDelegate {
self.animator = URMoveTransitioningAnimator(target: target, basedOn: baseOn, needClipToBounds: needClipToBounds, duration: duration, finishingDuration: finishingDuration, finishingDurationForPop: finishingDurationForPop, isLazyCompletion: isLazyCompletion)
if scale != 1.0 {
(self.animator as! URMoveTransitioningAnimator).scale = scale
}
}
}
public func makeBlurredTransitionAnimator(target: UIView, baseOn: UIView, duration: Double, needClipToBounds: Bool = false, scale: CGFloat = 1.0, finishingDuration: TimeInterval = 0.8, finishingDurationForPop: TimeInterval = 0.2, isLazyCompletion: Bool = false) {
if let _ = self.navigationController?.delegate as? URMovingTransitionAnimatorDelegate {
self.animator = URMoveBlurredTransitioningAnimator(target: target, basedOn: baseOn, needClipToBounds: needClipToBounds, duration: duration, finishingDuration: finishingDuration, finishingDurationForPop: finishingDurationForPop, isLazyCompletion: isLazyCompletion)
if scale != 1.0 {
(self.animator as! URMoveTransitioningAnimator).scale = scale
}
}
}
}
|
mit
|
b4722c1bdd52531e252b61a03ff325a4
| 48.439024 | 275 | 0.747657 | 5.177522 | false | false | false | false |
Ryukie/Ryubo
|
Ryubo/Ryubo/Classes/Tools/RYEmotion/RYEmotionModel.swift
|
1
|
1988
|
//
// RYEmotionModel.swift
// Ryubo
//
// Created by 王荣庆 on 16/2/24.
// Copyright © 2016年 Ryukie. All rights reserved.
//
import UIKit
class RYEmotionModel: NSObject {
var id : String?
/// 表情文字
var chs: String?
/// 表情图片文件名
var png: String? {
didSet {
//一个模型 只需要计算一次
//给imagePath赋值
//NSBundle.mainBundle().bundlePath + "/Emoticons.bundle/" + "\(bundleId)/" + "\(png)"
// if let bundleId = id, imageName = png {
if let imageName = png {
// imagePath = NSBundle.mainBundle().bundlePath + "/Emoticons.bundle/" + "\(bundleId)/" + "\(imageName)"
imagePath = NSBundle.mainBundle().bundlePath + "/Emoticons.bundle/" + "\(imageName)"
}
}
}
/// emoji 编码
var code: String? {
didSet {
emoji = code?.emoji
}
}
/// emoji 字符串
var emoji: String?
/// 完整的图像路径 //定义图片绝对路径的属性 计算型属性 每次都会进行计算
var imagePath: String?
// {
// return png == nil ? "" : NSBundle.mainBundle().bundlePath + "/Emoticons.bundle/" + png!
// }
/// 是否删除按钮
var isRemoved = false
// MARK: - 构造函数
init(isRemoved: Bool) {
self.isRemoved = isRemoved
super.init()
}
/// 是否空白按钮
var isEmpty = false
// MARK: - 构造函数
init(isEmpty: Bool) {
self.isEmpty = isEmpty
super.init()
}
init(dict: [String: AnyObject],id:String) {
self.id = id
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
override var description: String {
let keys = ["chs", "png", "code"]
return dictionaryWithValuesForKeys(keys).description
}
}
|
mit
|
927c9a651c97e27c9ba190aca915225e
| 24.236111 | 119 | 0.535498 | 4.055804 | false | false | false | false |
lexrus/LexNightmare
|
LexNightmare/GameViewControllerWithAds.swift
|
1
|
3931
|
//
// GameViewControllerWithAds.swift
// LexNightmare
//
// Created by Lex on 3/15/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
import StoreKit
import iAd
class GameViewControllerWithAds: GameViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver , ADBannerViewDelegate {
@IBOutlet weak var restoreButton: UIButton!
@IBOutlet weak var removeAdsButton: UIButton!
@IBOutlet weak var adBanner: ADBannerView!
var inAppProductIdentifiers = NSSet()
let removeAdsProductIdentifier = "com.LexTang.LexNightmare.remove_ads"
override func viewDidLoad() {
super.viewDidLoad()
if GameDefaults.sharedDefaults.removeAds {
removeAdsButton.hidden = true
restoreButton.hidden = true
adBanner.removeFromSuperview()
}
restoreButton.titleLabel!.text = NSLocalizedString("Restore previous purchase", comment: "Restore button title")
removeAdsButton.titleLabel!.text = NSLocalizedString("Remove ads", comment: "Remove ads button title")
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
}
func fetchProducts()
{
if SKPaymentQueue.canMakePayments() {
var productsRequest = SKProductsRequest(productIdentifiers: Set(arrayLiteral: removeAdsProductIdentifier) as Set<NSObject>)
productsRequest.delegate = self
productsRequest.start()
}
}
func buyProduct(product: SKProduct) {
println("Sending the Payment Request to Apple")
var payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addPayment(payment)
}
@IBAction func restoreCompletedTransactions() {
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}
@IBAction func didTapRemoveAds(sender: UIButton) {
fetchProducts()
}
func removeAds() {
removeAdsButton.hidden = true
restoreButton.hidden = true
adBanner.hidden = true
}
// MARK: - Delegate methods of IAP
func productsRequest(request: SKProductsRequest!, didReceiveResponse response: SKProductsResponse!) {
var count = response.products.count
if count > 0 {
var validProducts = response.products
var validProduct = response.products.first as! SKProduct!
if validProduct.productIdentifier == removeAdsProductIdentifier {
buyProduct(validProduct)
}
}
}
func request(request: SKRequest!, didFailWithError error: NSError!) {
}
func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) {
for transaction in transactions {
if let trans = transaction as? SKPaymentTransaction {
switch trans.transactionState {
case .Purchased, .Restored:
println("Product purchased.")
SKPaymentQueue.defaultQueue().finishTransaction(trans)
removeAds()
break
case .Purchased:
self.restoreCompletedTransactions()
SKPaymentQueue.defaultQueue().finishTransaction(trans)
removeAds()
case .Failed:
SKPaymentQueue.defaultQueue().finishTransaction(trans)
break
default:
()
}
}
}
}
func paymentQueue(queue: SKPaymentQueue!, removedTransactions transactions: [AnyObject]!) {
}
// MARK: - Ad delegate
func bannerViewDidLoadAd(banner: ADBannerView!) {
banner.alpha = 1.0
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
banner.alpha = 0.0
}
}
|
mit
|
6cb496ca4e561a569a146a8e8a36c2d7
| 31.487603 | 135 | 0.622234 | 5.738686 | false | false | false | false |
HTWDD/HTWDresden-iOS
|
HTWDD/Components/Exams/Main/ExamViewController.swift
|
1
|
5936
|
//
// ExamViewController.swift
// HTWDD
//
// Created by Mustafa Karademir on 07.08.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import UIKit
import RxSwift
import RealmSwift
import Action
class ExamViewController: UITableViewController, HasSideBarItem {
// MARK: - Properties
var context: ExamsCoordinator.Services!
private var items: [ExamRealm] = []
private var notificationToken: NotificationToken? = nil
private lazy var action: Action<Void, [Exam]> = Action { [weak self] (_) -> Observable<[Exam]> in
guard let self = self else { return Observable.empty() }
return self.context.examService.loadExams().observeOn(MainScheduler.instance)
}
private let stateView: EmptyResultsView = {
return EmptyResultsView().also {
$0.isHidden = true
}
}()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
observeExams()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.apply {
$0.estimatedRowHeight = 200
$0.rowHeight = UITableView.automaticDimension
}
self.stateView.setup(with: EmptyResultsView.Configuration(icon: "🤯", title: R.string.localizable.examsNoResultsTitle(), message: R.string.localizable.examsCurrentlyUnavailableMessage(), hint: nil, action: nil))
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.contentInset = UIEdgeInsets(top: 4, left: 0, bottom: 4, right: 0)
}
deinit {
notificationToken?.invalidate()
}
}
// MARK: - Setup
extension ExamViewController {
private func setup() {
refreshControl = UIRefreshControl().also {
$0.tintColor = .white
$0.rx.bind(to: action, input: ())
}
title = R.string.localizable.examsTitle()
tableView.apply {
$0.separatorStyle = .none
$0.backgroundColor = UIColor.htw.veryLightGrey
$0.backgroundView = stateView
$0.register(ExamViewCell.self)
}
}
@objc private func load() {
action.elements.subscribe { [weak self] event in
guard let self = self else { return }
if let exams = event.element {
ExamRealm.save(from: exams)
self.stateView.isHidden = true
if exams.isEmpty {
self.stateView.setup(with: EmptyResultsView.Configuration(icon: "🥺", title: R.string.localizable.examsNoResultsTitle(), message: R.string.localizable.examsNoResultsHint(), hint: nil, action: nil))
}
}
}.disposed(by: rx_disposeBag)
action.errors.subscribe { [weak self] error in
guard let self = self else { return }
self.stateView.setup(with: EmptyResultsView.Configuration(icon: "🤯", title: R.string.localizable.examsNoCredentialsTitle(), message: R.string.localizable.examsNoCredentialsMessage(), hint: R.string.localizable.add(), action: UITapGestureRecognizer(target: self, action: #selector(self.onTap))))
}.disposed(by: rx_disposeBag)
action.execute()
}
}
// MARK: - Table Datasource
extension ExamViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = .clear
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(ExamViewCell.self, for: indexPath)!.also {
$0.setup(with: items[indexPath.row])
}
}
@objc private func onTap() {
let viewController = R.storyboard.onboarding.studyGroupViewController()!
viewController.context = self.context
viewController.modalPresentationStyle = .overCurrentContext
viewController.modalTransitionStyle = .crossDissolve
viewController.delegateClosure = { [weak self] in
guard let self = self else { return }
self.load()
}
present(viewController, animated: true, completion: nil)
}
}
// MARK: - Realm Data Obsering
extension ExamViewController {
private func observeExams() {
let realm = try! Realm()
let results = realm.objects(ExamRealm.self).sorted(byKeyPath: "day")
items = results.map { $0 }
// Observe
notificationToken = results.observe { [weak self] (changes: RealmCollectionChange) in
guard let self = self else { return }
switch changes {
case .initial:
self.tableView.reloadData()
case .update(let collectionResults, let deletions, let insertions, let modifications):
guard let tableView = self.tableView else { return }
if self.items == collectionResults.sorted(byKeyPath: "day").map { $0 } {
return
}
self.items = collectionResults.sorted(byKeyPath: "day").map { $0 }
tableView.beginUpdates()
tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }), with: .automatic)
tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}), with: .automatic)
tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }), with: .none)
tableView.endUpdates()
case .error(let error):
Log.error(error)
}
}
}
}
|
gpl-2.0
|
1af6e2c85bc451093df38a1b2983f59d
| 35.355828 | 306 | 0.610024 | 4.756019 | false | false | false | false |
kperson/FSwift
|
FSwiftTests/Concurrency/StreamTests.swift
|
1
|
6943
|
//
// StreamTests.swift
// FSwift
//
// Created by Kelton Person on 4/8/15.
// Copyright (c) 2015 Kelton. All rights reserved.
//
import Foundation
import XCTest
class StreamTests : XCTestCase {
func testDefaultState() {
let stream = Stream<String>()
XCTAssertTrue(stream.isOpen, "stream should be open by default")
}
func testClearSubscriptions() {
let stream = Stream<String>()
let _ = stream.subscribe(nil) { x in Void() }
let _ = stream.clearSubscriptions()
XCTAssertTrue(stream.subscriptions.isEmpty, "clearSubscriptions should empty the stream")
}
func testSubscribeBinding() {
let stream = Stream<String>()
let _ = stream.clearSubscriptions()
let _ = stream.subscribe(nil) { x in Void() }
XCTAssertFalse(stream.subscriptions.first!.shouldExecute, "streams only execute if the bind is not nil")
let _ = stream.clearSubscriptions()
let _ = stream.subscribe({ nil } ) { x in Void() }
XCTAssertFalse(stream.subscriptions.first!.shouldExecute, "streams only execute if the bind is not nil")
let _ = stream.clearSubscriptions()
let _ = stream.subscribe(false) { x in Void() }
XCTAssertFalse(stream.subscriptions.first!.shouldExecute, "streams only execute if the bind is true")
let _ = stream.clearSubscriptions()
let _ = stream.subscribe(true) { x in Void() }
XCTAssertTrue(stream.subscriptions.first!.shouldExecute, "streams only execute if the bind is true")
let _ = stream.clearSubscriptions()
let _ = stream.subscribe() { x in Void() }
XCTAssertTrue(stream.subscriptions.first!.shouldExecute, "subscribe should default to allowing execution")
}
func testOpenPublishAndSubscribe() {
var ct = 0
let numPublishes = 4
let numSubscribers = 2
let value = UUID().uuidString
let exp = expectation(description: "testOpenPublishAndSubscribe")
let stream = Stream<String>()
for _ in 0...numSubscribers - 1 {
let _ = stream.subscribe { str in
XCTAssertEqual(value, str, "stream must publish the correct value")
ct = ct + 1
if ct == numPublishes * numSubscribers {
exp.fulfill()
}
}
for _ in 0...numPublishes - 1 {
let _ = stream.publish(value)
}
}
waitForExpectations(timeout: 2.seconds, handler: nil)
}
func testExplicitSubscriptionCancel() {
let subscription = Subscription<String>(action: { x in Void() }, callbackQueue: OperationQueue.main, executionCheck: { true })
XCTAssertTrue(subscription.shouldExecute, "subscription should be active if execution check returns true and cancel has not been called")
subscription.cancel()
XCTAssertFalse(subscription.shouldExecute, "subscription should deactivate if cancel is called")
let stream = Stream<String>()
let subscription2 = Subscription<String>(action: { x in Void() }, callbackQueue: OperationQueue.main, executionCheck: { true })
let _ = stream.subscribe(subscription2)
subscription2.cancel()
XCTAssertTrue(stream.subscriptions.isEmpty, "cancel should immediately remove subscription from the stream")
}
func testClosedPublishAndSubscribe() {
let exp = expectation(description: "testClosedPublishAndSubscribe")
let stream = Stream<String>()
let _ = stream.subscribe() { x in XCTAssertTrue(false, "this line should never execute since the stream is closed")
exp.fulfill()
}
stream.close()
let _ = stream.publish("hello")
let _ = stream.clearSubscriptions()
stream.open()
let _ = stream.subscribe() { x in
XCTAssertTrue(true, "this line should execute since the stream in open")
exp.fulfill()
}
let _ = stream.publish("hello")
waitForExpectations(timeout: 2.seconds, handler: nil)
}
func testAutoCancel() {
let exp = expectation(description: "testAutoCancel")
let stream = Stream<String>()
let _ = stream.subscribe(nil) { x in Void() }
let _ = stream.subscribe("car") { x in Void() }
let _ = stream.subscribe("hello") { x in
XCTAssertTrue(true, "this line should execute since the stream in open")
exp.fulfill()
}
let _ = stream.publish("bob")
waitForExpectations(timeout: 2.seconds, handler: { err in
XCTAssertEqual(stream.subscriptions.count, 2, "cancelled subscriptions should automatically be cleared from callback list")
})
}
func testFutureTryPiping() {
var publishCt = 0
let message = "hello"
let exp = expectation(description: "testFuturePiping")
let stream = Stream<String>()
let _ = stream.subscribe { x in
publishCt = publishCt + 1
XCTAssertTrue(true, "this line should execute since we are publishing via future pipe")
XCTAssertEqual(message, x, "pipe must generate the correct message")
exp.fulfill()
}
let _ = future {
Try.success(message)
}.pipeTo(stream)
waitForExpectations(timeout: 2.seconds, handler:nil)
}
func testFutureTryPipingFailure() {
var publishCt = 0
let exp = expectation(description: "testFuturePiping")
let stream = Stream<Try<String>>()
let _ = stream.subscribe { x in
publishCt = publishCt + 1
XCTAssertTrue(true, "this line should execute since we are publishing via future pipe")
XCTAssertNil(x.value, "try must be passed on failure")
exp.fulfill()
}
let err = NSError(domain: "A", code: 0, userInfo: nil)
let _ = future {
Try<String>.failure(err)
}.pipeTo(stream)
waitForExpectations(timeout: 2.seconds, handler:nil)
}
func testFutureTryPipingSuccess() {
var publishCt = 0
let message = "hello"
let exp = expectation(description: "testFuturePiping")
let stream = Stream<Try<String>>()
let _ = stream.subscribe { x in
publishCt = publishCt + 1
XCTAssertTrue(true, "this line should execute since we are publishing via future pipe")
XCTAssertNil(x.error, "try must be passed on success")
exp.fulfill()
}
let _ = future {
Try<String>.success(message)
}.pipeTo(stream)
waitForExpectations(timeout: 2.seconds, handler:nil)
}
}
|
mit
|
216712b942ddbc75e9761a422e3f82bf
| 35.73545 | 145 | 0.596428 | 4.755479 | false | true | false | false |
GalacticSmarties/electra
|
Electra/Electra/ViewController.swift
|
1
|
4030
|
//
// ViewController.swift
// Electra
//
// Created by Kristin Harkness on 11/12/16.
// Copyright © 2016 GSI. All rights reserved.
//
import UIKit
import MapKit
import CoreBluetooth
class ViewController: UIViewController, CLLocationManagerDelegate, CBCentralManagerDelegate {
var locationManager = CLLocationManager()
var centralManager: CBCentralManager?
var peripheral: CBPeripheral?
let semblee: [CBUUID] = [CBUUID(string: "FE84")]
@IBOutlet weak var map: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
centralManager = CBCentralManager(delegate: self, queue: nil)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last! as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.006, longitudeDelta: 0.006))
self.map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
//CoreBluetooth methods
func centralManagerDidUpdateState(_ central: CBCentralManager)
{
if (central.state == CBManagerState.poweredOn)
{
NSLog("Fired up! Ready to go!")
// for now, look for ANYBODY!!!
self.centralManager?.scanForPeripherals(withServices: semblee, options: nil)
}
else
{
// do something like alert the user that ble is not on
NSLog("BLE does not seem to be on")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
let deviceName: NSString = "Electra"
let nameOfDeviceFound = (advertisementData as NSDictionary).object(forKey: CBAdvertisementDataLocalNameKey) as? NSString
if (nameOfDeviceFound == deviceName) {
// Update Status Label
NSLog( "Electra Found")
// Stop scanning
self.centralManager?.stopScan()
// Set as the peripheral to use and establish connection
self.peripheral = peripheral
self.centralManager?.connect(peripheral, options: nil)
// show where the flash cavalry needs to go
if (CLLocationManager.locationServicesEnabled())
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
else {
NSLog("Electra Not Found")
}
// Discover services of the peripheral
func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {
NSLog( "Discovering peripheral services")
peripheral.discoverServices(nil)
}
// Check if the service discovered is a valid IR Temperature Service
func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) {
NSLog( "Looking at peripheral services")
for service in peripheral.services! {
let thisService = service as CBService
if service.uuid == semblee[0] {
// Discover characteristics of Semblee Service
peripheral.discoverCharacteristics(nil, for: thisService)
}
// Uncomment to print list of UUIDs
//println(thisService.UUID)
}
}
}
}
|
mit
|
c1d3add78930bd36676b8299f20c0e82
| 34.034783 | 148 | 0.607099 | 5.847605 | false | false | false | false |
bomjkolyadun/goeuro-test
|
GoEuro/GoEuro/ViewControllers/GETransitTableControllerTableViewController.swift
|
1
|
1241
|
//
// GETransitTableControllerTableViewController.swift
// GoEuro
//
// Created by Dmitry Osipa on 7/30/17.
// Copyright © 2017 Dmitry Osipa. All rights reserved.
//
import UIKit
class GETransitTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate {
private static let popoverCellSegue = "popoverCell"
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = true
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: GETransitTableViewController.popoverCellSegue, sender: nil)
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == GETransitTableViewController.popoverCellSegue {
let popoverViewController = segue.destination
popoverViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
//popoverViewController.popoverPresentationController!.delegate = self
}
}
}
|
apache-2.0
|
c4725e7ab09775c7495c414bfb58adbe
| 33.444444 | 106 | 0.748387 | 5.876777 | false | false | false | false |
snark/jumpcut
|
Jumpcut/Jumpcut/Clippings.swift
|
1
|
7746
|
//
// Clippings.swift
// Jumpcut
//
// Created by Steve Cook on 7/24/21.
//
/*
A clipping is a snippet of text with some simple operators
to get it in a form that's useful for display.
A clipping store is a list of clippings, with a persistance backing.
A clipping stack is an overlay on such a list with a positional index
which may be adjusted. (In practice, this is done via the keyboard-based
interface in our bezel.
*/
import Cocoa
struct JCEngine: Codable {
// displayLen is a duplicative property from older versions of
// Jumpcut and may safely be ignored--even more so than the other
// values beyond jcList, which aren't being used for anything.
var displayLen: Int?
var displayNum: Int
var jcList: [JCListItem]
var rememberNum: Int
var version: String
}
// These names are from our original Objective-C implementation.
// swiftlint:disable identifier_name
struct JCListItem: Codable {
let Contents: String
let Position: Int
let `Type`: String
}
// swiftlint:enable identifier_name
public class ClippingStack: NSObject {
private var store: ClippingStore
public var position: Int = 0
public var count: Int {
return store.count
}
override init() {
self.store = ClippingStore()
super.init()
self.store.maxLength = UserDefaults.standard.value(
forKey: SettingsPath.rememberNum.rawValue
) as? Int ?? 99
}
func setSkipSave(value: Bool) {
store.skipSave = value
}
func isEmpty() -> Bool {
return store.count == 0
}
// swiftlint:disable:next identifier_name
func firstItems(n: Int) -> ArraySlice<Clipping> {
return store.firstItems(n: n)
}
func clear() {
store.clear()
}
func delete() {
deleteAt(position: self.position)
}
func add(item: String) {
store.add(item: item)
}
func deleteAt(position: Int) {
guard position < store.count else {
return
}
store.removeItem(position: position)
if store.count == 0 {
self.position = 0
} else if self.position > 0 && self.position >= position {
// If we're deleting at or above the stack position,
// move up.
self.position -= 1
}
}
func down() {
let newPosition = position + 1
if newPosition < store.count {
position = newPosition
} else {
if let wraparound = UserDefaults.standard.value(forKey: SettingsPath.wraparoundBezel.rawValue) as? Bool {
if wraparound {
position = 0
}
}
}
}
func itemAt(position: Int) -> Clipping? {
return store.itemAt(position: position)
}
func up() {
let newPosition = position - 1
if newPosition >= 0 {
position = newPosition
} else {
if let wraparound = UserDefaults.standard.value(forKey: SettingsPath.wraparoundBezel.rawValue) as? Bool {
if wraparound {
position = store.count - 1
}
}
}
}
}
public class Clipping: NSObject {
public let fullText: String
public var shortenedText: String
public var length: Int
private let defaultLength = 40
init(string: String) {
fullText = string
length = defaultLength
shortenedText = fullText.trimmingCharacters(in: .whitespacesAndNewlines)
shortenedText = shortenedText.components(separatedBy: .newlines)[0]
if shortenedText.count > length {
shortenedText = String(shortenedText.prefix(length)) + "…"
}
}
}
private class ClippingStore: NSObject {
// TK: Back with sqlite3 for persistence
private var clippings: [Clipping] = []
private var _maxLength = 99
private let plistPath: String
fileprivate var skipSave: Bool
fileprivate var maxLength: Int {
get { return _maxLength }
set {
let newValueWithMin = newValue < 10 ? 10 : newValue
clippings = Array(self.firstItems(n: newValueWithMin))
_maxLength = newValueWithMin
}
}
override init() {
// TK: We will eventually be switching this out to use SQLite3, but for
// now we'll use a hardcoded path to a property list.
skipSave = UserDefaults.standard.value(forKey: SettingsPath.skipSave.rawValue) as? Bool ?? false
plistPath = NSString(string: "~/Library/Application Support/Jumpcut/JCEngine.save").expandingTildeInPath
super.init()
if !skipSave {
loadFromPlist(path: plistPath)
}
}
func loadFromPlist(path: String) {
let fullPath = NSString(string: path).expandingTildeInPath
let url = URL(fileURLWithPath: fullPath)
var savedValues: JCEngine
if let data = try? Data(contentsOf: url) {
do {
savedValues = try PropertyListDecoder().decode(JCEngine.self, from: data)
for clipDict in savedValues.jcList.reversed() {
if !clipDict.Contents.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
self.add(item: clipDict.Contents)
}
}
} catch {
print("Unable to load clippings store plist")
}
}
}
var count: Int {
return clippings.count
}
private func writeClippings() {
guard !skipSave else {
return
}
var items: [JCListItem] = []
var counter = 0
for clip in clippings {
items.append(JCListItem(Contents: clip.fullText, Position: counter, Type: "NSStringPboardType"))
counter += 1
}
let data = JCEngine(
displayNum: UserDefaults.standard.value(forKey: SettingsPath.displayNum.rawValue) as? Int ?? 10,
jcList: items,
rememberNum: UserDefaults.standard.value(forKey: SettingsPath.displayNum.rawValue) as? Int ?? 99,
version: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"
)
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
do {
let newData = try encoder.encode(data)
let url = URL(fileURLWithPath: plistPath)
try newData.write(to: url)
} catch {
print("Unable to write clippings store plist file")
}
}
func add(item: String) {
clippings.insert(Clipping(string: item), at: 0)
if clippings.count > maxLength {
clippings.removeLast()
}
// TK: When we have SQLite backing, we'll want to change this.
writeClippings()
}
func clear() {
clippings = []
// TK: When we have SQLite backing, we'll want to change this.
writeClippings()
}
func itemAt(position: Int) -> Clipping? {
if clippings.isEmpty || position > clippings.count {
return nil
}
return clippings[position]
}
func removeItem(position: Int) {
if clippings.isEmpty || position > clippings.count {
return
}
clippings.remove(at: position)
// TK: When we have SQLite backing, we'll want to change this.
writeClippings()
}
// swiftlint:disable:next identifier_name
func firstItems(n: Int) -> ArraySlice<Clipping> {
var slice: ArraySlice<Clipping>
if n > clippings.count {
slice = clippings[...]
} else {
slice = clippings[0 ..< n]
}
return slice
}
}
|
mit
|
706a2b7e87906078e52a736d61efa409
| 28.784615 | 117 | 0.591426 | 4.504945 | false | false | false | false |
MrZoidberg/metapp
|
metapp/Pods/Carpaccio/Carpaccio/ImageMetadataLoaderProtocol.swift
|
1
|
9278
|
//
// ImageMetadataLoaderProtocol.swift
// Carpaccio
//
// Created by Mikhail Merkulov on 11/4/16.
// Copyright © 2016 Matias Piipari & Co. All rights reserved.
//
import Foundation
import CoreGraphics
import CoreImage
import ImageIO
public enum ImageMetadataLoadError: Error {
case cannotFindImageProperties(msg: String)
case imageUrlIsInvalid(msg: String)
}
public protocol ImageMetadataLoader {
func loadImageMetadata(imageSource: CGImageSource) throws -> ImageMetadata
}
public class RAWImageMetadataLoader: ImageMetadataLoader {
public init() {
}
public func loadImageMetadata(imageSource: CGImageSource) throws -> ImageMetadata {
return try getImageMetadata(imageSource)
}
public func loadImageMetadata(imageUrl: URL) throws -> ImageMetadata {
let options = [String(kCGImageSourceShouldCache): false, String(kCGImageSourceShouldAllowFloat): true] as NSDictionary as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(imageUrl as CFURL, options) else {
throw ImageMetadataLoadError.imageUrlIsInvalid(msg: "Url \(imageUrl.absoluteString) is invalid or doesn't contain an CGImage")
}
return try getImageMetadata(imageSource)
}
// See ImageMetadata.timestamp for known caveats about EXIF/TIFF
// date metadata, as interpreted by this date formatter.
private static let EXIFDateFormatter: DateFormatter =
{
let formatter = DateFormatter()
formatter.dateFormat = "yyyy:MM:dd HH:mm:ss"
return formatter
}()
private func getImageMetadata(_ imageSource: CGImageSource) throws -> ImageMetadata {
func getString(_ from: NSDictionary, _ key: CFString) -> String? {
return from[key as String] as? String
}
func getDouble(_ from: NSDictionary, _ key: CFString) -> Double? {
return (from[key as String] as? NSNumber)?.doubleValue
}
func getInt(_ from: NSDictionary, _ key: CFString) -> Int? {
return (from[key as String] as? NSNumber)?.intValue
}
func getBool(_ from: NSDictionary, _ key: CFString) -> Bool? {
guard let val = (from[key as String] as? NSNumber)?.doubleValue else {
return nil
}
return val == 1 ? true : false
}
func getEnum<T, KEYT>(_ from: NSDictionary, _ key: CFString, _ matches: [KEYT: T]) -> T? {
guard let val = from[key as String] as? KEYT else {
return nil
}
let enumValue: T? = matches[val];
guard (enumValue != nil) else {
return nil
}
return enumValue
}
func getArray<T>(_ from: NSDictionary, _ key: CFString) -> [T]? {
guard let ar = from[key as String] as? [T] else {
return nil
}
return ar
}
guard let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) else {
throw ImageMetadataLoadError.cannotFindImageProperties(msg: "Cannot find image properties")
}
let properties = NSDictionary(dictionary: imageProperties)
// Examine EXIF metadata
var exifMetadata: ExifMetadata? = nil
if let EXIF = properties[kCGImagePropertyExifDictionary as String] as? NSDictionary
{
var fNumber: Double? = nil, focalLength: Double? = nil, focalLength35mm: Double? = nil, ISO: Double? = nil, shutterSpeed: Double? = nil
var colorSpace: CGColorSpace? = nil
var width: CGFloat? = nil, height: CGFloat? = nil
var imageId: String? = nil
var bodySerialNumber: String? = nil, lensSpecs: String? = nil, lensMake: String? = nil, lensModel: String? = nil,lensSerialNumber: String? = nil
var originalTimestamp: Date? = nil, digitizedTimestamp: Date? = nil
var subjectDistance: Double? = nil
var subjectArea: [Double]? = nil
var flashMode: FlashMode? = nil
imageId = getString(EXIF, kCGImagePropertyExifImageUniqueID)
fNumber = getDouble(EXIF, kCGImagePropertyExifFNumber)
if let colorSpaceName = getString(EXIF, kCGImagePropertyExifColorSpace) {
colorSpace = CGColorSpace(name: colorSpaceName as CFString)
}
focalLength = getDouble(EXIF, kCGImagePropertyExifFocalLength)
focalLength35mm = getDouble(EXIF, kCGImagePropertyExifFocalLenIn35mmFilm)
if let ISOs = EXIF[kCGImagePropertyExifISOSpeedRatings as String]
{
let ISOArray = NSArray(array: ISOs as! CFArray)
if ISOArray.count > 0 {
ISO = (ISOArray[0] as? NSNumber)?.doubleValue
}
}
shutterSpeed = getDouble(EXIF, kCGImagePropertyExifExposureTime)
if let w = getDouble(EXIF, kCGImagePropertyExifPixelXDimension) {
width = CGFloat(w)
}
if let h = getDouble(EXIF, kCGImagePropertyExifPixelYDimension) {
height = CGFloat(h)
}
bodySerialNumber = getString(EXIF, kCGImagePropertyExifBodySerialNumber)
lensSpecs = getString(EXIF, kCGImagePropertyExifLensSpecification)
lensMake = getString(EXIF, kCGImagePropertyExifLensMake)
lensModel = getString(EXIF, kCGImagePropertyExifLensModel)
lensSerialNumber = getString(EXIF, kCGImagePropertyExifLensSerialNumber)
if originalTimestamp == nil, let dateTimeString = getString(EXIF, kCGImagePropertyExifDateTimeOriginal) {
originalTimestamp = RAWImageMetadataLoader.EXIFDateFormatter.date(from: dateTimeString)
}
if digitizedTimestamp == nil, let dateTimeString = getString(EXIF, kCGImagePropertyExifDateTimeDigitized) {
digitizedTimestamp = RAWImageMetadataLoader.EXIFDateFormatter.date(from: dateTimeString)
}
subjectDistance = getDouble(EXIF, kCGImagePropertyExifSubjectDistance)
subjectArea = getArray(EXIF, kCGImagePropertyExifSubjectArea)
let flashModeInt = getInt(EXIF, kCGImagePropertyExifFlash)
if (flashModeInt != nil) {
flashMode = FlashMode(rawValue: flashModeInt!)
}
/*
If image dimension didn't appear in metadata (can happen with some RAW files like Nikon NEFs), take one more step:
open the actual image. This thankfully doesn't appear to immediately load image data.
*/
if width == nil || height == nil
{
let options: CFDictionary = [String(kCGImageSourceShouldCache): false] as NSDictionary as CFDictionary
let image = CGImageSourceCreateImageAtIndex(imageSource, 0, options)
width = CGFloat((image?.width)!)
height = CGFloat((image?.height)!)
}
exifMetadata = ExifMetadata(imageId: imageId, bodySerialNumber: bodySerialNumber, lensSpecification: lensSpecs, lensMake: lensMake, lensModel: lensModel, lensSerialNumber: lensSerialNumber, colorSpace: colorSpace, fNumber: fNumber, focalLength: focalLength, focalLength35mmEquivalent: focalLength35mm, iso: ISO, shutterSpeed: shutterSpeed, nativeSize: CGSize(width: width!, height: height!), originalTimestamp: originalTimestamp, digitizedTimestamp: digitizedTimestamp, subjectDistance: subjectDistance, subjectArea: subjectArea, flashMode: flashMode)
}
// Examine TIFF metadata
var tiffMetadata: TIFFMetadata? = nil
if let TIFF = properties[kCGImagePropertyTIFFDictionary as String] as? NSDictionary
{
var cameraMaker: String? = nil, cameraModel: String? = nil, orientation: CGImagePropertyOrientation? = nil, timestamp: Date? = nil
cameraMaker = getString(TIFF, kCGImagePropertyTIFFMake)
cameraModel = getString(TIFF, kCGImagePropertyTIFFModel)
orientation = CGImagePropertyOrientation(rawValue: (TIFF[kCGImagePropertyTIFFOrientation as String] as? NSNumber)?.uint32Value ?? CGImagePropertyOrientation.up.rawValue)
if timestamp == nil, let dateTimeString = getString(TIFF, kCGImagePropertyTIFFDateTime) {
timestamp = RAWImageMetadataLoader.EXIFDateFormatter.date(from: dateTimeString)
}
tiffMetadata = TIFFMetadata(cameraMaker: cameraMaker, cameraModel: cameraModel, nativeOrientation: (orientation)!, timestamp: timestamp)
}
// Examine GPS metadata
var gpsMetadata: GpsMetadata? = nil
if let GPS = properties[kCGImagePropertyGPSDictionary as String] as? NSDictionary
{
let gpsVersion: String? = getString(GPS, kCGImagePropertyGPSVersion)
let latitudeRef: LatitudeRef? = getEnum(GPS, kCGImagePropertyGPSLatitudeRef, ["N": LatitudeRef.north, "S": LatitudeRef.south])
let latitude: Double? = getDouble(GPS, kCGImagePropertyGPSLatitude)
let longtitudeRef: LongtitudeRef? = getEnum(GPS, kCGImagePropertyGPSLongitudeRef, ["E": LongtitudeRef.east, "W": LongtitudeRef.west])
let longtitude: Double? = getDouble(GPS, kCGImagePropertyGPSLongitude)
let altitudeRef: AltitudeRef? = getEnum(GPS, kCGImagePropertyGPSAltitudeRef, [0: AltitudeRef.aboveSeaLevel, 1: AltitudeRef.belowSeaLevel])
let altitude: Double? = getDouble(GPS, kCGImagePropertyGPSAltitude)
var gpsTimestamp: Date? = nil
if gpsTimestamp == nil, let dateTimeString = getString(GPS, kCGImagePropertyGPSTimeStamp) {
gpsTimestamp = RAWImageMetadataLoader.EXIFDateFormatter.date(from: dateTimeString)
}
let imgDirection: String? = getString(GPS, kCGImagePropertyGPSImgDirection)
gpsMetadata = GpsMetadata(gpsVersion: gpsVersion, latitudeRef: latitudeRef, latitude: latitude, longtitudeRef: longtitudeRef, longtitude: longtitude, altitudeRef: altitudeRef, altitude: altitude, timestamp: gpsTimestamp, imgDirection: imgDirection)
}
let metadata = ImageMetadata(exif: exifMetadata!, tiff: tiffMetadata, gps: gpsMetadata)
return metadata
}
}
|
mpl-2.0
|
f55007bfa20177f0a9695055447dc0b6
| 40.600897 | 554 | 0.736014 | 4.042266 | false | false | false | false |
saeta/penguin
|
Sources/PenguinStructures/Either.swift
|
1
|
6804
|
// Copyright 2020 Penguin Authors
//
// 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.
// TODO: Consider adding `ABiasedEither` and `BBiasedEither` for biased projection wrapper types of
// `Either`.
/// An unbiased [tagged union or sum type](https://en.wikipedia.org/wiki/Tagged_union) of exactly
/// two possible cases, `.a` and `.b`, having types `A` and `B` respectively.
///
/// **When _NOT_ to use Either**: if there are asymmetrical semantics (e.g. `A` is special in some
/// manner), or when there are better names (i.e. meaning) that can be attached to the cases, a
/// domain-specific `enum` often results in more maintainable code and easier to use APIs.
///
/// **When to use Either**: good applications of `Either` come up in generic programming where there
/// are no defined semantics or information that can be gained from naming or biasing one of the two
/// cases.
public enum Either<A, B> {
case a(A)
case b(B)
/// `x` iff the value of `self` is `.a(x)` for some `x`; `nil` otherwise.
public var a: A? { if case .a(let x) = self { return x } else {return nil } }
/// `x` iff the value of `self` is `.b(x)` for some `x`; `nil` otherwise.
public var b: B? { if case .b(let x) = self { return x } else {return nil } }
}
extension Either: Equatable where A: Equatable, B: Equatable {
/// True iff `lhs` is equivalent to `rhs`.
public static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.a(let lhs), .a(let rhs)): return lhs == rhs
case (.b(let lhs), .b(let rhs)): return lhs == rhs
default: return false
}
}
}
// Note: while there are other possible orderings that could make sense, until Swift has reasonable
// rules and tools to resolve typeclass incoherency, we define a single broadly applicable ordering
// here.
extension Either: Comparable where A: Comparable, B: Comparable {
/// True iff `lhs` comes before `rhs` in an ordering where every `.a(x)`s is ordered before any
/// `.b(y)`, `.a(x)`s are ordered by increasing `x`, and `.b(y)`s are ordered by increasing `y`.
public static func < (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.a(let lhs), .a(let rhs)): return lhs < rhs
case (.a, _): return true
case (.b(let lhs), .b(let rhs)): return lhs < rhs
default: return false
}
}
}
extension Either: Hashable where A: Hashable, B: Hashable {
/// Hashes `self` into `hasher`.
public func hash(into hasher: inout Hasher) {
switch self {
case .a(let a): a.hash(into: &hasher)
case .b(let b): b.hash(into: &hasher)
}
}
}
extension Either: CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
switch self {
case .a(let x): return "Either.a(\(x))"
case .b(let x): return "Either.b(\(x))"
}
}
}
/// A sequence backed by one of two sequence types.
///
/// An `EitherSequence` can sometimes be used an alternative to `AnySequence`. Advantages of
/// `EitherSequence` include higher performance, as more information is available at compile time,
/// enabling more effective static optimizations.
///
/// Tip: if code uses `AnySequence`, but most of the time is used with a particular collection type
/// `T` (e.g. `Array<MyThings>`), consider using an `EitherSequence<T, AnySequence>`.
public typealias EitherSequence<A: Sequence, B: Sequence> = Either<A, B>
where A.Element == B.Element
extension EitherSequence {
/// A type that provides the sequence’s iteration interface and encapsulates its iteration state.
public struct Iterator: IteratorProtocol {
// Note: although we would ideally use `var underlying = Either<A.Iterator, B.Iterator>`, this
// would result in accidentally quadratic behavior due to the extra copies required. (Enums
// cannot be modified in-place, resulting in a lot of extra copies.)
//
// Future optimization: avoid needing to reserve space for both `a` and `b` iterators.
/// An iterator for the `A` collection.
var a: A.Iterator?
/// An iterator for the `A` collection.
var b: B.Iterator?
/// The type of element traversed by the iterator.
public typealias Element = A.Element
/// Advances to the next element and returns it, or `nil` if no next element exists.
public mutating func next() -> Element? {
a?.next() ?? b?.next()
}
}
}
extension EitherSequence: Sequence {
/// A type representing the sequence’s elements.
public typealias Element = A.Element
/// Returns an iterator over the elements of this sequence.
public func makeIterator() -> Iterator {
switch self {
case .a(let a): return Iterator(a: a.makeIterator(), b: nil)
case .b(let b): return Iterator(a: nil, b: b.makeIterator())
}
}
}
/// A collection of one of two collection types.
///
/// - SeeAlso: `EitherSequence`.
public typealias EitherCollection<A: Collection, B: Collection> = Either<A, B>
where A.Element == B.Element
extension EitherCollection: Collection {
/// A type that represents a position in the collection.
public typealias Index = Either<A.Index, B.Index>
/// The position of the first element in a nonempty collection.
public var startIndex: Index {
switch self {
case .a(let c): return .a(c.startIndex)
case .b(let c): return .b(c.startIndex)
}
}
/// The collection’s “past the end” position—that is, the position one greater than the last valid
/// subscript argument.
public var endIndex: Index {
switch self {
case .a(let c): return .a(c.endIndex)
case .b(let c): return .b(c.endIndex)
}
}
/// Returns the position immediately after the given index.
public func index(after i: Index) -> Index {
switch (i, self) {
case (.a(let i), .a(let c)): return .a(c.index(after: i))
case (.b(let i), .b(let c)): return .b(c.index(after: i))
default: fatalError("Invalid index \(i) used with \(self).")
}
}
/// Accesses the element at the specified position.
public subscript(position: Index) -> Element {
switch (position, self) {
case (.a(let i), .a(let c)): return c[i]
case (.b(let i), .b(let c)): return c[i]
default: fatalError("Invalid index \(position) used with \(self).")
}
}
}
// TODO: Bidirectional & RandomAccess conformances
|
apache-2.0
|
d7e774fcb761a0b76e25d600428d0017
| 36.524862 | 100 | 0.669759 | 3.742149 | false | false | false | false |
tidepool-org/nutshell-ios
|
Nutshell/Third Party/ENSideMenu/ENSideMenu.swift
|
1
|
18951
|
//
// SideMenu.swift
// SwiftSideMenu
//
// Created by Evgeny on 24.07.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
@objc public protocol ENSideMenuDelegate {
@objc optional func sideMenuWillOpen()
@objc optional func sideMenuWillClose()
@objc optional func sideMenuDidOpen()
@objc optional func sideMenuDidClose()
@objc optional func sideMenuShouldOpenSideMenu () -> Bool
}
@objc public protocol ENSideMenuProtocol {
var sideMenu : ENSideMenu? { get }
func setContentViewController(_ contentViewController: UIViewController)
}
public enum ENSideMenuAnimation : Int {
case none
case `default`
}
/**
The position of the side view on the screen.
- Left: Left side of the screen
- Right: Right side of the screen
*/
public enum ENSideMenuPosition : Int {
case left
case right
}
public extension UIViewController {
/**
Changes current state of side menu view.
*/
public func toggleSideMenuView () {
sideMenuController()?.sideMenu?.toggleMenu()
}
/**
Hides the side menu view.
*/
public func hideSideMenuView () {
sideMenuController()?.sideMenu?.hideSideMenu()
}
/**
Shows the side menu view.
*/
public func showSideMenuView () {
sideMenuController()?.sideMenu?.showSideMenu()
}
/**
Returns a Boolean value indicating whether the side menu is showed.
:returns: BOOL value
*/
public func isSideMenuOpen () -> Bool {
let sieMenuOpen = self.sideMenuController()?.sideMenu?.isMenuOpen
return sieMenuOpen!
}
/**
* You must call this method from viewDidLayoutSubviews in your content view controlers so it fixes size and position of the side menu when the screen
* rotates.
* A convenient way to do it might be creating a subclass of UIViewController that does precisely that and then subclassing your view controllers from it.
*/
func fixSideMenuSize() {
if let navController = self.navigationController as? ENSideMenuNavigationController {
navController.sideMenu?.updateFrame()
}
}
/**
Returns a view controller containing a side menu
:returns: A `UIViewController`responding to `ENSideMenuProtocol` protocol
*/
public func sideMenuController () -> ENSideMenuProtocol? {
var iteration : UIViewController? = self.parent
if (iteration == nil) {
return topMostController()
}
repeat {
if (iteration is ENSideMenuProtocol) {
return iteration as? ENSideMenuProtocol
} else if (iteration?.parent != nil && iteration?.parent != iteration) {
iteration = iteration!.parent
} else {
iteration = nil
}
} while (iteration != nil)
return iteration as? ENSideMenuProtocol
}
internal func topMostController () -> ENSideMenuProtocol? {
var topController : UIViewController? = UIApplication.shared.keyWindow?.rootViewController
if (topController is UITabBarController) {
topController = (topController as! UITabBarController).selectedViewController
}
while (topController?.presentedViewController is ENSideMenuProtocol) {
topController = topController?.presentedViewController
}
return topController as? ENSideMenuProtocol
}
}
open class ENSideMenu : NSObject, UIGestureRecognizerDelegate {
/// The width of the side menu view. The default value is 160.
open var menuWidth : CGFloat = 160.0 {
didSet {
needUpdateApperance = true
updateSideMenuApperanceIfNeeded()
updateFrame()
}
}
fileprivate var menuPosition:ENSideMenuPosition = .left
fileprivate var blurStyle: UIBlurEffectStyle = .light
/// A Boolean value indicating whether the bouncing effect is enabled. The default value is TRUE.
open var bouncingEnabled :Bool = true
/// The duration of the slide animation. Used only when `bouncingEnabled` is FALSE.
open var animationDuration = 0.4
fileprivate let sideMenuContainerView = UIView()
fileprivate(set) var menuViewController : UIViewController!
fileprivate var animator : UIDynamicAnimator!
fileprivate var sourceView : UIView!
fileprivate var needUpdateApperance : Bool = false
/// The delegate of the side menu
open weak var delegate : ENSideMenuDelegate?
fileprivate(set) var isMenuOpen : Bool = false
/// A Boolean value indicating whether the left swipe is enabled.
open var allowLeftSwipe : Bool = true
/// A Boolean value indicating whether the right swipe is enabled.
open var allowRightSwipe : Bool = true
open var allowPanGesture : Bool = true
fileprivate var panRecognizer : UIPanGestureRecognizer?
/**
Initializes an instance of a `ENSideMenu` object.
:param: sourceView The parent view of the side menu view.
:param: menuPosition The position of the side menu view.
:returns: An initialized `ENSideMenu` object, added to the specified view.
*/
public init(sourceView: UIView, menuPosition: ENSideMenuPosition, blurStyle: UIBlurEffectStyle = .light) {
super.init()
self.sourceView = sourceView
self.menuPosition = menuPosition
self.blurStyle = blurStyle
self.setupMenuView()
animator = UIDynamicAnimator(referenceView:sourceView)
animator.delegate = self
self.panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ENSideMenu.handlePan(_:)))
panRecognizer!.delegate = self
sourceView.addGestureRecognizer(panRecognizer!)
// Add right swipe gesture recognizer
let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(ENSideMenu.handleGesture(_:)))
rightSwipeGestureRecognizer.delegate = self
rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.right
// Add left swipe gesture recognizer
let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(ENSideMenu.handleGesture(_:)))
leftSwipeGestureRecognizer.delegate = self
leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.left
if (menuPosition == .left) {
sourceView.addGestureRecognizer(rightSwipeGestureRecognizer)
sideMenuContainerView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
else {
sideMenuContainerView.addGestureRecognizer(rightSwipeGestureRecognizer)
sourceView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
}
/**
Initializes an instance of a `ENSideMenu` object.
:param: sourceView The parent view of the side menu view.
:param: menuViewController A menu view controller object which will be placed in the side menu view.
:param: menuPosition The position of the side menu view.
:returns: An initialized `ENSideMenu` object, added to the specified view, containing the specified menu view controller.
*/
public convenience init(sourceView: UIView, menuViewController: UIViewController, menuPosition: ENSideMenuPosition, blurStyle: UIBlurEffectStyle = .light) {
self.init(sourceView: sourceView, menuPosition: menuPosition, blurStyle: blurStyle)
self.menuViewController = menuViewController
self.menuViewController.view.frame = sideMenuContainerView.bounds
self.menuViewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
sideMenuContainerView.addSubview(self.menuViewController.view)
}
/*
public convenience init(sourceView: UIView, view: UIView, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
view.frame = sideMenuContainerView.bounds
view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(view)
}
*/
/**
Updates the frame of the side menu view.
*/
func updateFrame() {
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
let menuFrame = CGRect(
x: (menuPosition == .left) ?
isMenuOpen ? 0 : -menuWidth-1.0 :
isMenuOpen ? width - menuWidth : width+1.0,
y: sourceView.frame.origin.y,
width: menuWidth,
height: height
)
sideMenuContainerView.frame = menuFrame
}
fileprivate func adjustFrameDimensions( _ width: CGFloat, height: CGFloat ) -> (CGFloat,CGFloat) {
if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1 &&
(UIApplication.shared.statusBarOrientation == UIInterfaceOrientation.landscapeRight ||
UIApplication.shared.statusBarOrientation == UIInterfaceOrientation.landscapeLeft) {
// iOS 7.1 or lower and landscape mode -> interchange width and height
return (height, width)
}
else {
return (width, height)
}
}
fileprivate func setupMenuView() {
// Configure side menu container
updateFrame()
sideMenuContainerView.backgroundColor = UIColor.clear
sideMenuContainerView.clipsToBounds = false
sideMenuContainerView.layer.masksToBounds = false
sideMenuContainerView.layer.shadowOffset = (menuPosition == .left) ? CGSize(width: 1.0, height: 1.0) : CGSize(width: -1.0, height: -1.0)
sideMenuContainerView.layer.shadowRadius = 1.0
sideMenuContainerView.layer.shadowOpacity = 0.125
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).cgPath
sourceView.addSubview(sideMenuContainerView)
if (NSClassFromString("UIVisualEffectView") != nil) {
// Add blur view
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle)) as UIVisualEffectView
visualEffectView.frame = sideMenuContainerView.bounds
visualEffectView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
sideMenuContainerView.addSubview(visualEffectView)
}
else {
// TODO: add blur for ios 7
}
}
fileprivate func toggleMenu (_ shouldOpen: Bool) {
if (shouldOpen && delegate?.sideMenuShouldOpenSideMenu?() == false) {
return
}
updateSideMenuApperanceIfNeeded()
isMenuOpen = shouldOpen
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
if (bouncingEnabled) {
animator.removeAllBehaviors()
var gravityDirectionX: CGFloat
var pushMagnitude: CGFloat
var boundaryPointX: CGFloat
var boundaryPointY: CGFloat
if (menuPosition == .left) {
// Left side menu
gravityDirectionX = (shouldOpen) ? 1 : -1
pushMagnitude = (shouldOpen) ? 35 : -35
boundaryPointX = (shouldOpen) ? menuWidth : -menuWidth-2
boundaryPointY = 25
}
else {
// Right side menu
gravityDirectionX = (shouldOpen) ? -1 : 1
pushMagnitude = (shouldOpen) ? -35 : 35
boundaryPointX = (shouldOpen) ? width-menuWidth : width+menuWidth+2
boundaryPointY = -25
}
let gravityBehavior = UIGravityBehavior(items: [sideMenuContainerView])
gravityBehavior.gravityDirection = CGVector(dx: gravityDirectionX, dy: 0)
animator.addBehavior(gravityBehavior)
let collisionBehavior = UICollisionBehavior(items: [sideMenuContainerView])
collisionBehavior.addBoundary(withIdentifier: "menuBoundary" as NSCopying, from: CGPoint(x: boundaryPointX, y: boundaryPointY),
to: CGPoint(x: boundaryPointX, y: height))
animator.addBehavior(collisionBehavior)
let pushBehavior = UIPushBehavior(items: [sideMenuContainerView], mode: UIPushBehaviorMode.instantaneous)
pushBehavior.magnitude = pushMagnitude
animator.addBehavior(pushBehavior)
let menuViewBehavior = UIDynamicItemBehavior(items: [sideMenuContainerView])
menuViewBehavior.elasticity = 0.25
animator.addBehavior(menuViewBehavior)
}
else {
var destFrame :CGRect
if (menuPosition == .left) {
destFrame = CGRect(x: (shouldOpen) ? -2.0 : -menuWidth, y: 0, width: menuWidth, height: height)
}
else {
destFrame = CGRect(x: (shouldOpen) ? width-menuWidth : width+2.0,
y: 0,
width: menuWidth,
height: height)
}
UIView.animate(
withDuration: animationDuration,
animations: { () -> Void in
self.sideMenuContainerView.frame = destFrame
},
completion: { (Bool) -> Void in
if (self.isMenuOpen) {
self.delegate?.sideMenuDidOpen?()
} else {
self.delegate?.sideMenuDidClose?()
}
})
}
if (shouldOpen) {
delegate?.sideMenuWillOpen?()
} else {
delegate?.sideMenuWillClose?()
}
}
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if delegate?.sideMenuShouldOpenSideMenu?() == false {
return false
}
if gestureRecognizer is UISwipeGestureRecognizer {
let swipeGestureRecognizer = gestureRecognizer as! UISwipeGestureRecognizer
if !self.allowLeftSwipe {
if swipeGestureRecognizer.direction == .left {
return false
}
}
if !self.allowRightSwipe {
if swipeGestureRecognizer.direction == .right {
return false
}
}
}
else if gestureRecognizer.isEqual(panRecognizer) {
if allowPanGesture == false {
return false
}
animator.removeAllBehaviors()
let touchPosition = gestureRecognizer.location(ofTouch: 0, in: sourceView)
if menuPosition == .left {
if isMenuOpen {
if touchPosition.x < menuWidth {
return true
}
}
else {
if touchPosition.x < 25 {
return true
}
}
}
else {
if isMenuOpen {
if touchPosition.x > sourceView.frame.width - menuWidth {
return true
}
}
else {
if touchPosition.x > sourceView.frame.width-25 {
return true
}
}
}
return false
}
return true
}
internal func handleGesture(_ gesture: UISwipeGestureRecognizer) {
toggleMenu((self.menuPosition == .right && gesture.direction == .left)
|| (self.menuPosition == .left && gesture.direction == .right))
}
internal func handlePan(_ recognizer : UIPanGestureRecognizer){
let leftToRight = recognizer.velocity(in: recognizer.view).x > 0
switch recognizer.state {
case .began:
break
case .changed:
let translation = recognizer.translation(in: sourceView).x
let xPoint : CGFloat = sideMenuContainerView.center.x + translation + (menuPosition == .left ? 1 : -1) * menuWidth / 2
if menuPosition == .left {
if xPoint <= 0 || xPoint > self.sideMenuContainerView.frame.width {
return
}
}else{
if xPoint <= sourceView.frame.size.width - menuWidth || xPoint >= sourceView.frame.size.width
{
return
}
}
sideMenuContainerView.center.x = sideMenuContainerView.center.x + translation
recognizer.setTranslation(CGPoint.zero, in: sourceView)
default:
let shouldClose = menuPosition == .left ? !leftToRight && sideMenuContainerView.frame.maxX < menuWidth : leftToRight && sideMenuContainerView.frame.minX > (sourceView.frame.size.width - menuWidth)
toggleMenu(!shouldClose)
}
}
fileprivate func updateSideMenuApperanceIfNeeded () {
if (needUpdateApperance) {
var frame = sideMenuContainerView.frame
frame.size.width = menuWidth
sideMenuContainerView.frame = frame
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).cgPath
needUpdateApperance = false
}
}
/**
Toggles the state of the side menu.
*/
open func toggleMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
else {
updateSideMenuApperanceIfNeeded()
toggleMenu(true)
}
}
/**
Shows the side menu if the menu is hidden.
*/
open func showSideMenu () {
if (!isMenuOpen) {
toggleMenu(true)
}
}
/**
Hides the side menu if the menu is showed.
*/
open func hideSideMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
}
}
extension ENSideMenu: UIDynamicAnimatorDelegate {
public func dynamicAnimatorDidPause(_ animator: UIDynamicAnimator) {
if (self.isMenuOpen) {
self.delegate?.sideMenuDidOpen?()
} else {
self.delegate?.sideMenuDidClose?()
}
}
public func dynamicAnimatorWillResume(_ animator: UIDynamicAnimator) {
//print("resume")
}
}
|
bsd-2-clause
|
8566bfb86ea395b1f3043ea49e09d8e4
| 36.452569 | 209 | 0.603662 | 5.81319 | false | false | false | false |
wunshine/FoodStyle
|
FoodStyle/FoodStyle/Classes/Viewcontroller/MailRegisteViewController.swift
|
1
|
6463
|
//
// MailRegisteViewController.swift
// FoodStyle
//
// Created by Woz Wong on 16/3/5.
// Copyright © 2016年 code4Fun. All rights reserved.
//
import UIKit
class MailRegisteViewController: UIViewController {
lazy var scrollView:UIScrollView = {
var scrollView = UIScrollView()
scrollView.backgroundColor = UIColor.clearColor()
scrollView.frame = SCREEN_RECT()
scrollView.contentSize = CGSizeMake(SCREEN_RECT().width,SCREEN_RECT().height+20)
return scrollView
}()
lazy var mail:WXTextField = {
var mail = WXTextField()
mail.clearButtonMode = .WhileEditing
mail.backgroundColor = UIColor.whiteColor()
mail.tintColor = UIColor.redColor()
mail.placeholder = "邮箱"
return mail
}()
lazy var passWord:WXTextField = {
var pwd = WXTextField()
pwd.clearButtonMode = .WhileEditing
pwd.backgroundColor = UIColor.whiteColor()
pwd.tintColor = UIColor.redColor()
pwd.secureTextEntry = true
pwd.placeholder = "密码"
return pwd
}()
lazy var name:WXTextField = {
var name = WXTextField()
name.clearButtonMode = .WhileEditing
name.backgroundColor = UIColor.whiteColor()
name.tintColor = UIColor.redColor()
name.placeholder = "昵称"
return name
}()
lazy var seperator1:UIView = {
var sep = UIView()
sep.backgroundColor = UIColor.lightGrayColor()
return sep
}()
lazy var seperator2:UIView = {
var sep = UIView()
sep.backgroundColor = UIColor.lightGrayColor()
return sep
}()
lazy var container:UIView = {
var contain = UIView()
contain.backgroundColor = UIColor.clearColor()
return contain
}()
lazy var verifyImage:UIButton = {
var vry = UIButton()
vry.backgroundColor = UIColor(red: 0.95, green: 0.84, blue: 0.36, alpha: 1)
vry.addTarget(self, action: "refreshCode", forControlEvents: .TouchDown)
return vry
}()
lazy var refreshButton : UIButton = {
var ref = UIButton()
ref.setImage(UIImage(named: "captcha_refresh_normal"), forState: UIControlState.Normal)
ref.setImage(UIImage(named: "captcha_refresh_hl"), forState: UIControlState.Highlighted)
ref.addTarget(self, action: "refreshCode", forControlEvents: .TouchDown)
return ref
}()
lazy var verifyField:UITextField = {
var vf = UITextField()
vf.backgroundColor = UIColor.whiteColor()
vf.clearButtonMode = .WhileEditing
vf.font = UIFont.systemFontOfSize(12.0)
vf.textAlignment = .Center
vf.placeholder = "输入验证码"
vf.tintColor = GLOBAL_COLOR()
return vf
}()
lazy var registeButton:UIButton = {
var registe = UIButton()
registe.titleLabel?.font = UIFont.systemFontOfSize(12.0)
registe.setTitle("注册", forState: UIControlState.Normal)
registe.addTarget(self, action: "registe", forControlEvents: .TouchDown)
registe.setBackgroundImage(UIImage().imageWithColor(GLOBAL_COLOR()), forState: UIControlState.Normal)
return registe
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "邮箱注册"
self.view.backgroundColor = UIColor.lightGrayColor()
view.addSubview(self.scrollView)
scrollView.addSubview(self.mail)
scrollView.addSubview(self.passWord)
scrollView.addSubview(self.name)
scrollView.addSubview(self.seperator1)
scrollView.addSubview(self.seperator2)
scrollView.addSubview(self.container)
container.addSubview(self.verifyImage)
container.addSubview(self.refreshButton)
container.addSubview(self.verifyField)
scrollView.addSubview(self.registeButton)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
mail.snp_makeConstraints { (make) -> Void in
make.width.equalTo(SCREEN_RECT().width)
make.height.equalTo(35.0)
make.top.equalTo(20.0)
}
seperator1.snp_makeConstraints { (make) -> Void in
make.height.equalTo(0.5)
make.top.equalTo(mail.snp_bottom)
}
passWord.snp_makeConstraints { (make) -> Void in
make.width.equalTo(SCREEN_RECT().width)
make.height.equalTo(35.0)
make.top.equalTo(seperator1.snp_bottom)
}
seperator2.snp_makeConstraints { (make) -> Void in
make.width.equalTo(SCREEN_RECT().width)
make.height.equalTo(0.5)
make.top.equalTo(passWord.snp_bottom)
}
name.snp_makeConstraints { (make) -> Void in
make.width.equalTo(SCREEN_RECT().width)
make.height.equalTo(35.0)
make.top.equalTo(seperator2.snp_bottom)
}
container.snp_makeConstraints { (make) -> Void in
make.width.equalTo(SCREEN_RECT().width - 2*20)
make.centerX.equalTo(view.snp_centerX)
make.height.equalTo(30.0)
make.top.equalTo(name.snp_bottom).offset(20.0)
}
verifyImage.snp_makeConstraints { (make) -> Void in
make.width.equalTo(100.0)
make.height.equalTo(30.0)
make.left.equalTo(container)
make.top.equalTo(container)
}
refreshButton.snp_makeConstraints { (make) -> Void in
make.width.equalTo(30.0)
make.height.equalTo(30.0)
make.top.equalTo(container)
make.centerX.equalTo(container.snp_centerX)
}
verifyField.snp_makeConstraints { (make) -> Void in
make.width.equalTo(10*MARGIN())
make.height.equalTo(3*MARGIN())
make.top.equalTo(container)
make.right.equalTo(container)
}
registeButton.snp_makeConstraints { (make) -> Void in
make.width.equalTo(SCREEN_RECT().width - 2*2*MARGIN())
make.height.equalTo(35.0)
make.centerX.equalTo(view.snp_centerX)
make.top.equalTo(container.snp_bottom).offset(2*MARGIN())
}
}
@objc func refreshCode(){
}
@objc func registe(){
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
ae6863a01f05ef67af709eed4539663d
| 31.454545 | 109 | 0.615468 | 4.389344 | false | false | false | false |
justindhill/Facets
|
Facets/Presentation Controllers/OZLDropdownPresentationController.swift
|
1
|
7860
|
//
// OZLDropdownPresentationController.swift
// Facets
//
// Created by Justin Hill on 5/27/16.
// Copyright © 2016 Justin Hill. All rights reserved.
//
import UIKit
class OZLDropdownPresentationController: UIPresentationController, UIGestureRecognizerDelegate {
fileprivate(set) var dimmingLayer = CAShapeLayer()
fileprivate var backgroundTapRecognizer: UITapGestureRecognizer?
fileprivate(set) var navigationController: UINavigationController
fileprivate var presentedOriginY: CGFloat {
let navBar = self.navigationController.navigationBar
return navBar.frame.origin.y + navBar.frame.size.height + (1 / self.traitCollection.displayScale)
}
fileprivate var presentedOriginX: CGFloat {
let navBar = self.navigationController.navigationBar
guard let converted = navBar.superview?.convert(navBar.frame, to: nil) else {
return 0
}
return converted.origin.x
}
init(presentedViewController: UIViewController, presentingViewController: UIViewController?, navigationController: UINavigationController) {
self.navigationController = navigationController
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
}
override var shouldPresentInFullscreen : Bool {
return false
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (context) in
self.presentedViewController.view.frame = CGRect(x: self.presentedOriginX, y: self.presentedOriginY, width: self.navigationController.view.frame.size.width, height: self.presentedViewController.preferredContentSize.height)
let toPath = self.computeDimmingLayerPath(CGSize(width: self.navigationController.view.frame.size.width, height: self.presentedOriginY + self.presentedViewController.preferredContentSize.height))
let AnimKey = "pathAnim"
CATransaction.begin()
CATransaction.setCompletionBlock {
self.dimmingLayer.path = toPath
self.dimmingLayer.removeAnimation(forKey: AnimKey)
}
CATransaction.setAnimationDuration(coordinator.transitionDuration)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
let anim = CABasicAnimation(keyPath: "path")
anim.toValue = toPath
anim.fillMode = kCAFillModeForwards
anim.isRemovedOnCompletion = false
self.dimmingLayer.add(anim, forKey: AnimKey)
}, completion: nil)
}
override func presentationTransitionWillBegin() {
if let containerView = self.containerView {
self.dimmingLayer.frame = containerView.bounds
self.dimmingLayer.fillColor = UIColor.clear.cgColor
self.dimmingLayer.opacity = 0.3
self.dimmingLayer.fillRule = kCAFillRuleEvenOdd
let initialPath = self.computeDimmingLayerPath(CGSize(width: self.navigationController.view.frame.size.width, height: self.presentedOriginY))
self.dimmingLayer.path = initialPath
self.presentedViewController.viewWillAppear(true)
let finalPath = self.computeDimmingLayerPath(CGSize(width: self.navigationController.view.frame.size.width, height: self.presentedOriginY + self.presentedViewController.preferredContentSize.height))
containerView.isUserInteractionEnabled = true
self.backgroundTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(backgroundTapAction))
self.backgroundTapRecognizer?.delegate = self
containerView.addGestureRecognizer(self.backgroundTapRecognizer!)
containerView.layer.addSublayer(self.dimmingLayer)
self.presentingViewController.transitionCoordinator?.animate(alongsideTransition: { (context) in
CATransaction.begin()
CATransaction.setCompletionBlock({
self.dimmingLayer.fillColor = UIColor.black.cgColor
self.dimmingLayer.path = finalPath
self.dimmingLayer.removeAllAnimations()
})
let group = CAAnimationGroup()
group.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
group.duration = context.transitionDuration
group.fillMode = kCAFillModeForwards
group.isRemovedOnCompletion = false
let fillColorAnim = CABasicAnimation(keyPath: "fillColor")
fillColorAnim.fromValue = UIColor.clear.cgColor
fillColorAnim.toValue = UIColor.black.cgColor
let pathAnim = CABasicAnimation(keyPath: "path")
pathAnim.fromValue = initialPath
pathAnim.toValue = finalPath
group.animations = [fillColorAnim, pathAnim]
self.dimmingLayer.add(group, forKey: nil)
CATransaction.commit()
}, completion: nil)
}
}
override func dismissalTransitionWillBegin() {
self.presentingViewController.transitionCoordinator?.animate(alongsideTransition: { (context) in
CATransaction.begin()
CATransaction.setCompletionBlock({
self.dimmingLayer.fillColor = UIColor.clear.cgColor
self.dimmingLayer.removeAllAnimations()
})
let initialPath = self.dimmingLayer.path
let finalPath = self.computeDimmingLayerPath(CGSize(width: self.navigationController.view.frame.size.width, height: self.presentedOriginY))
let group = CAAnimationGroup()
group.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
group.duration = context.transitionDuration
group.fillMode = kCAFillModeForwards
group.isRemovedOnCompletion = false
let fillColorAnim = CABasicAnimation(keyPath: "fillColor")
fillColorAnim.fromValue = UIColor.black.cgColor
fillColorAnim.toValue = UIColor.clear.cgColor
let pathAnim = CABasicAnimation(keyPath: "path")
pathAnim.fromValue = initialPath
pathAnim.toValue = finalPath
group.animations = [fillColorAnim, pathAnim]
self.dimmingLayer.add(group, forKey: nil)
CATransaction.commit()
}, completion: nil)
}
func computeDimmingLayerPath(_ cutoutSize: CGSize) -> CGPath {
let screenBounds = UIScreen.main.bounds
let sideLen = max(screenBounds.size.height, screenBounds.size.width)
let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: sideLen, height: sideLen))
path.usesEvenOddFillRule = true
path.append(UIBezierPath(rect: CGRect(x: self.presentedOriginX, y: 0, width: cutoutSize.width, height: cutoutSize.height)))
return path.cgPath
}
@objc func backgroundTapAction() {
self.presentingViewController.dismiss(animated: true, completion: nil)
}
override var frameOfPresentedViewInContainerView : CGRect {
return CGRect(x: self.presentedOriginX, y: self.presentedOriginY, width: self.navigationController.view.frame.size.width, height: self.presentedViewController.preferredContentSize.height)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if self.containerView?.hitTest(touch.location(in: self.containerView), with: nil) != self.containerView {
return false
}
return true
}
}
|
mit
|
ece01ba23a93f38f5544cbeac3ce48a7
| 42.905028 | 234 | 0.67973 | 5.707335 | false | false | false | false |
adamdahan/GraphKit
|
Source/OrderedDictionary.swift
|
1
|
10111
|
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
public class OrderedDictionary<Key : Comparable, Value> : Probability<Key>, CollectionType, Equatable, Printable {
public typealias Generator = GeneratorOf<(key: Key, value: Value?)>
public typealias OrderedKey = OrderedSet<Key>
public typealias OrderedValue = Array<Value>
public typealias OrderedIndex = RedBlackTree<Key, Int>
public typealias OrderedSearch = OrderedDictionary<Key, Value>
internal typealias OrderedNode = RedBlackNode<Key, Value>
/**
:name: tree
:description: Internal storage of (key, value) pairs.
:returns: RedBlackTree<Key, Value>
*/
internal var tree: RedBlackTree<Key, Value>
/**
:name: description
:description: Conforms to the Printable Protocol. Outputs the
data in the OrderedDictionary in a readable format.
:returns: String
*/
public var description: String {
return tree.internalDescription
}
/**
:name: first
:description: Get the first (key, value) pair.
k1 <= k2 <= K3 ... <= Kn
:returns: (key: Key, value: Value?)?
*/
public var first: (key: Key, value: Value?)? {
return tree.first
}
/**
:name: last
:description: Get the last (key, value) pair.
k1 <= k2 <= K3 ... <= Kn
:returns: (key: Key, value: Value?)?
*/
public var last: (key: Key, value: Value?)? {
return tree.last
}
/**
:name: isEmpty
:description: A boolean of whether the OrderedDictionary is empty.
:returns: Bool
*/
public var isEmpty: Bool {
return 0 == count
}
/**
:name: startIndex
:description: Conforms to the CollectionType Protocol.
:returns: Int
*/
public var startIndex: Int {
return 0
}
/**
:name: endIndex
:description: Conforms to the CollectionType Protocol.
:returns: Int
*/
public var endIndex: Int {
return count
}
/**
:name: keys
:description: Returns an array of the key values in ordered.
:returns: OrderedDictionary.OrderedKey
*/
public var keys: OrderedDictionary.OrderedKey {
let s: OrderedKey = OrderedKey()
for x in self {
s.insert(x.key)
}
return s
}
/**
:name: values
:description: Returns an array of the values that are ordered based
on the key ordering.
:returns: OrderedDictionary.OrderedValue
*/
public var values: OrderedDictionary.OrderedValue {
var s: OrderedValue = OrderedValue()
for x in self {
s.append(x.value!)
}
return s
}
/**
:name: init
:description: Constructor.
*/
public override init() {
tree = RedBlackTree<Key, Value>(uniqueKeys: true)
}
/**
:name: init
:description: Constructor.
:param: elements (Key, Value?)... Initiates with a given list of elements.
*/
public convenience init(elements: (Key, Value?)...) {
self.init(elements: elements)
}
/**
:name: init
:description: Constructor.
:param: elements Array<(Key, Value?)> Initiates with a given array of elements.
*/
public convenience init(elements: Array<(Key, Value?)>) {
self.init()
insert(elements)
}
//
// :name: generate
// :description: Conforms to the SequenceType Protocol. Returns
// the next value in the sequence of nodes using
// index values [0...n-1].
// :returns: OrderedDictionary.Generator
//
public func generate() -> OrderedDictionary.Generator {
var index = startIndex
return GeneratorOf {
if index < self.endIndex {
return self[index++]
}
return nil
}
}
/**
:name: operator [key 1...key n]
:description: Property key mapping. If the key type is a
String, this feature allows access like a
Dictionary.
:returns: Value?
*/
public subscript(key: Key) -> Value? {
get {
return tree[key]
}
set(value) {
tree[key] = value
}
}
/**
:name: operator [0...count - 1]
:description: Allows array like access of the index.
Items are kept in order, so when iterating
through the items, they are returned in their
ordered form.
:returns: (key: Key, value: Value?)
*/
public subscript(index: Int) -> (key: Key, value: Value?) {
get {
return tree[index]
}
set(value) {
tree[index] = value
}
}
/**
:name: indexOf
:description: Returns the Index of a given member, or nil if the member is not present in the set.
:returns: OrderedDictionary.OrderedIndex
*/
public func indexOf(keys: Key...) -> OrderedDictionary.OrderedIndex {
return indexOf(keys)
}
/**
:name: indexOf
:description: Returns the Index of a given member, or nil if the member is not present in the set.
:returns: OrderedDictionary.OrderedIndex
*/
public func indexOf(keys: Array<Key>) -> OrderedDictionary.OrderedIndex {
return tree.indexOf(keys)
}
/**
:name: countOf
:description: Conforms to ProbabilityType protocol.
:returns: Int
*/
public override func countOf(keys: Key...) -> Int {
return tree.countOf(keys)
}
/**
:name: countOf
:description: Conforms to ProbabilityType protocol.
:returns: Int
*/
public override func countOf(keys: Array<Key>) -> Int {
return tree.countOf(keys)
}
/**
:name: insert
:description: Insert a key / value pair.
:returns: Bool
*/
public func insert(key: Key, value: Value?) -> Bool {
let result: Bool = tree.insert(key, value: value)
count = tree.count
return result
}
/**
:name: insert
:description: Inserts a list of (Key, Value?) pairs.
:param: elements (Key, Value?)... Elements to insert.
*/
public func insert(elements: (Key, Value?)...) {
insert(elements)
}
/**
:name: insert
:description: Inserts an array of (Key, Value?) pairs.
:param: elements Array<(Key, Value?)> Elements to insert.
*/
public func insert(elements: Array<(Key, Value?)>) {
tree.insert(elements)
count = tree.count
}
/**
:name: removeValueForKeys
:description: Removes key / value pairs based on the key value given.
:returns: OrderedDictionary<Key, Value>?
*/
public func removeValueForKeys(keys: Key...) -> OrderedDictionary<Key, Value>? {
return removeValueForKeys(keys)
}
/**
:name: removeValueForKeys
:description: Removes key / value pairs based on the key value given.
:returns: OrderedDictionary<Key, Value>?
*/
public func removeValueForKeys(keys: Array<Key>) -> OrderedDictionary<Key, Value>? {
if let r: RedBlackTree<Key, Value> = tree.removeValueForKeys(keys) {
let d: OrderedDictionary<Key, Value> = OrderedDictionary<Key, Value>()
for (k, v) in r {
d.insert(k, value: v)
}
count = tree.count
return d
}
return nil
}
/**
:name: removeAll
:description: Remove all nodes from the tree.
*/
public func removeAll() {
tree.removeAll()
count = tree.count
}
/**
:name: updateValue
:description: Updates a node for the given key value.
*/
public func updateValue(value: Value?, forKey: Key) {
tree.updateValue(value, forKey: forKey)
}
/**
:name: findValueForKey
:description: Finds the value for key passed.
:param: key Key The key to find.
:returns: Value?
*/
public func findValueForKey(key: Key) -> Value? {
return tree.findValueForKey(key)
}
/**
:name: search
:description: Accepts a list of keys and returns a subset
OrderedDictionary with the given values if they exist.
:returns: OrderedDictionary.OrderedSearch
*/
public func search(keys: Key...) -> OrderedDictionary.OrderedSearch {
return search(keys)
}
/**
:name: search
:description: Accepts an array of keys and returns a subset
OrderedDictionary with the given values if they exist.
:returns: OrderedDictionary.OrderedSearch
*/
public func search(keys: Array<Key>) -> OrderedDictionary.OrderedSearch {
var dict: OrderedSearch = OrderedSearch()
for key: Key in keys {
traverse(key, node: tree.root, dict: &dict)
}
return dict
}
/**
:name: traverse
:description: Traverses the OrderedDictionary, looking for a key match.
*/
internal func traverse(key: Key, node: OrderedDictionary.OrderedNode, inout dict: OrderedDictionary.OrderedSearch) {
if tree.sentinel !== node {
if key == node.key {
dict.insert((key, node.value))
}
traverse(key, node: node.left, dict: &dict)
traverse(key, node: node.right, dict: &dict)
}
}
}
public func ==<Key : Comparable, Value>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool {
if lhs.count != rhs.count {
return false
}
for var i: Int = lhs.count - 1; 0 <= i; --i {
if lhs[i].key != rhs[i].key {
return false
}
}
return true
}
public func +<Key : Comparable, Value>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> OrderedDictionary<Key, Value> {
let t: OrderedDictionary<Key, Value> = OrderedDictionary<Key, Value>()
for var i: Int = lhs.count - 1; 0 <= i; --i {
let n: (key: Key, value: Value?) = lhs[i]
t.insert((n.key, n.value))
}
for var i: Int = rhs.count - 1; 0 <= i; --i {
let n: (key: Key, value: Value?) = rhs[i]
t.insert((n.key, n.value))
}
return t
}
public func -<Key : Comparable, Value>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> OrderedDictionary<Key, Value> {
let t: OrderedDictionary<Key, Value> = OrderedDictionary<Key, Value>()
for var i: Int = lhs.count - 1; 0 <= i; --i {
let n: (key: Key, value: Value?) = lhs[i]
t.insert((n.key, n.value))
}
for var i: Int = rhs.count - 1; 0 <= i; --i {
let n: (key: Key, value: Value?) = rhs[i]
t.insert((n.key, n.value))
}
return t
}
|
agpl-3.0
|
dcc2161ab7711da05ee1e8d89b8882a6
| 24.925641 | 145 | 0.676194 | 3.20171 | false | false | false | false |
stevethomp/VIDIA-GameplayKit
|
StateMachines/StateMachines/StatefulImageView.swift
|
1
|
2548
|
//
// StatefulImageView.swift
// StateMachines
//
// Created by Steven Thompson on 2016-06-08.
// Copyright © 2016 stevethomp. All rights reserved.
//
import UIKit
import GameplayKit
class StatefulImageView: UIImageView {
var stateMachine: GKStateMachine?
var timer: NSTimer?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
stateMachine = GKStateMachine(states: [ReadyState(imageView: self), UploadState(imageView: self), CompletedState(imageView: self), FailureState(imageView: self)])
stateMachine?.enterState(ReadyState.self)
}
func startTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: #selector(completed), userInfo: nil, repeats: false)
}
func completed() {
if GKARC4RandomSource().nextBool() {
stateMachine?.enterState(CompletedState.self)
} else {
stateMachine?.enterState(FailureState.self)
}
}
}
class ImageState: GKState {
var imageView: StatefulImageView!
init(imageView: StatefulImageView) {
self.imageView = imageView
}
override func willExitWithNextState(nextState: GKState) {
print("Entering " + String(nextState))
}
}
class ReadyState: ImageState {
override func didEnterWithPreviousState(previousState: GKState?) {
imageView.backgroundColor = .grayColor()
}
override func isValidNextState(stateClass: AnyClass) -> Bool {
return stateClass is UploadState.Type
}
}
class UploadState: ImageState {
override func didEnterWithPreviousState(previousState: GKState?) {
imageView.backgroundColor = .blueColor()
imageView.startTimer()
}
override func isValidNextState(stateClass: AnyClass) -> Bool {
return stateClass is CompletedState.Type || stateClass is FailureState.Type || stateClass is ReadyState.Type
}
}
class CompletedState: ImageState {
override func didEnterWithPreviousState(previousState: GKState?) {
imageView.backgroundColor = .greenColor()
}
override func isValidNextState(stateClass: AnyClass) -> Bool {
return stateClass is ReadyState.Type
}
}
class FailureState: ImageState {
override func didEnterWithPreviousState(previousState: GKState?) {
imageView.backgroundColor = .redColor()
}
override func isValidNextState(stateClass: AnyClass) -> Bool {
return stateClass is UploadState.Type || stateClass is ReadyState.Type
}
}
|
apache-2.0
|
1f87d9ea2345c7238cd8bf93cb32de4b
| 28.287356 | 170 | 0.688261 | 4.778612 | false | false | false | false |
mssun/pass-ios
|
pass/Controllers/SSHKeyURLImportTableViewController..swift
|
1
|
2411
|
//
// SSHKeyURLImportTableViewController.swift
// pass
//
// Created by Mingshen Sun on 25/1/2017.
// Copyright © 2017 Bob Sun. All rights reserved.
//
import passKit
import SVProgressHUD
class SSHKeyURLImportTableViewController: AutoCellHeightUITableViewController {
@IBOutlet var privateKeyURLTextField: UITextField!
var sshPrivateKeyURL: URL?
override func viewDidLoad() {
super.viewDidLoad()
privateKeyURLTextField.text = Defaults.gitSSHPrivateKeyURL?.absoluteString
}
@IBAction
private func doneButtonTapped(_: UIButton) {
guard let text = privateKeyURLTextField.text,
let privateKeyURL = URL(string: text) else {
Utils.alert(title: "CannotSave".localize(), message: "SetPrivateKeyUrl.".localize(), controller: self)
return
}
if privateKeyURL.scheme?.lowercased() == "http" {
let savePassphraseAlert = UIAlertController(title: "HttpNotSecure".localize(), message: "ReallyUseHttp?".localize(), preferredStyle: .alert)
savePassphraseAlert.addAction(UIAlertAction(title: "No".localize(), style: .default) { _ in })
savePassphraseAlert.addAction(
UIAlertAction(title: "Yes".localize(), style: .destructive) { _ in
self.performSegue(withIdentifier: "importSSHKeySegue", sender: self)
}
)
return present(savePassphraseAlert, animated: true)
}
sshPrivateKeyURL = privateKeyURL
performSegue(withIdentifier: "importSSHKeySegue", sender: self)
}
}
extension SSHKeyURLImportTableViewController: KeyImporter {
static let keySource = KeySource.url
static let label = "DownloadFromUrl".localize()
func isReadyToUse() -> Bool {
guard let url = sshPrivateKeyURL else {
Utils.alert(title: "CannotSave".localize(), message: "SetPrivateKeyUrl.".localize(), controller: self)
return false
}
guard url.scheme == "https" || url.scheme == "http" else {
Utils.alert(title: "CannotSave".localize(), message: "UseEitherHttpsOrHttp.".localize(), controller: self)
return false
}
return true
}
func importKeys() throws {
Defaults.gitSSHPrivateKeyURL = sshPrivateKeyURL
try KeyFileManager.PrivateSSH.importKey(from: Defaults.gitSSHPrivateKeyURL!)
}
}
|
mit
|
3e7ed084c350d7e4f2dcc54253832988
| 36.076923 | 152 | 0.659336 | 4.697856 | false | false | false | false |
kathypizza330/RamMap
|
ARKit+CoreLocation/Source/SCNNode+Extensions.swift
|
1
|
1691
|
//
// SCNNode+Extensions.swift
// ARKit+CoreLocation
//
// Created by Andrew Hart on 09/07/2017.
// Copyright © 2017 Project Dent. All rights reserved.
//
import SceneKit
extension SCNNode {
class func axesNode(quiverLength: CGFloat, quiverThickness: CGFloat) -> SCNNode {
let quiverThickness = (quiverLength / 50.0) * quiverThickness
let chamferRadius = quiverThickness / 2.0
let xQuiverBox = SCNBox(width: quiverLength, height: quiverThickness, length: quiverThickness, chamferRadius: chamferRadius)
xQuiverBox.firstMaterial?.diffuse.contents = UIColor.red
let xQuiverNode = SCNNode(geometry: xQuiverBox)
xQuiverNode.position = SCNVector3Make(Float(quiverLength / 2.0), 0.0, 0.0)
let yQuiverBox = SCNBox(width: quiverThickness, height: quiverLength, length: quiverThickness, chamferRadius: chamferRadius)
yQuiverBox.firstMaterial?.diffuse.contents = UIColor.green
let yQuiverNode = SCNNode(geometry: yQuiverBox)
yQuiverNode.position = SCNVector3Make(0.0, Float(quiverLength / 2.0), 0.0)
let zQuiverBox = SCNBox(width: quiverThickness, height: quiverThickness, length: quiverLength, chamferRadius: chamferRadius)
zQuiverBox.firstMaterial?.diffuse.contents = UIColor.blue
let zQuiverNode = SCNNode(geometry: zQuiverBox)
zQuiverNode.position = SCNVector3Make(0.0, 0.0, Float(quiverLength / 2.0))
let quiverNode = SCNNode()
quiverNode.addChildNode(xQuiverNode)
quiverNode.addChildNode(yQuiverNode)
quiverNode.addChildNode(zQuiverNode)
quiverNode.name = "Axes"
return quiverNode
}
}
|
mit
|
1ab7204084c71fa0e8ebabf25062ec11
| 43.473684 | 132 | 0.699408 | 4.567568 | false | false | false | false |
Eonil/EditorLegacy
|
Modules/Editor/Sources/Documents/RustProjectDocument.swift
|
1
|
3195
|
////
//// RustProjectDocument.swift
//// RustCodeEditor
////
//// Created by Hoon H. on 11/11/14.
//// Copyright (c) 2014 Eonil. All rights reserved.
////
//
//import Foundation
//import AppKit
//import PrecompilationOfExternalToolSupport
//
//class RustProjectDocument : NSDocument {
// let projectWindowController = PlainFileFolderWindowController()
// let programExecutionController = RustProgramExecutionController()
//
// override func makeWindowControllers() {
// super.makeWindowControllers()
// self.addWindowController(projectWindowController)
// }
//
// override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? {
// let s1 = projectWindowController.codeEditingViewController.codeTextViewController.codeTextView.string!
// let d1 = s1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
// return d1
// }
//
// override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
// let s1 = NSString(data: data, encoding: NSUTF8StringEncoding)!
// projectWindowController.codeEditingViewController.codeTextViewController.codeTextView.string = s1
//// let p2 = self.fileURL!.path!
//// let p3 = p2.stringByDeletingLastPathComponent
//// projectWindowController.mainViewController.navigationViewController.fileTreeViewController.pathRepresentation = p3
//
// let u2 = self.fileURL!.URLByDeletingLastPathComponent
// projectWindowController.mainViewController.navigationViewController.fileTreeViewController.URLRepresentation = u2
// return true
// }
//
//
//
// override func saveDocument(sender: AnyObject?) {
// // Do not route save messages to current document.
// // Saving of a project will be done at somewhere else, and this makes annoying alerts.
// /// This prevents the alerts.
//// super.saveDocument(sender)
//
// projectWindowController.codeEditingViewController.trySavingInPlace()
// }
//
//
//
//
//
// override class func autosavesInPlace() -> Bool {
// return false
// }
//}
//
//extension RustProjectDocument {
//
// @IBAction
// func menuProjectRun(sender:AnyObject?) {
// if let u1 = self.fileURL {
// self.saveDocument(self)
// let srcFilePath1 = u1.path!
// let srcDirPath1 = srcFilePath1.stringByDeletingLastPathComponent
// let outFilePath1 = srcDirPath1.stringByAppendingPathComponent("program.executable")
// let conf1 = RustProgramExecutionController.Configuration(sourceFilePaths: [srcFilePath1], outputFilePath: outFilePath1, extraArguments: ["-Z", "verbose"])
// // let s1 = mainEditorWindowController.splitter.codeEditingViewController.textViewController.textView.string!
// let r1 = programExecutionController.execute(conf1)
// projectWindowController.commandConsoleViewController.textView.string = r1
//
// let ss1 = RustCompilerIssueParsing.process(r1, sourceFilePath: srcFilePath1)
// projectWindowController.mainViewController.navigationViewController.issueListingViewController.issues = ss1
//
// } else {
// NSAlert(error: NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "This file has not been save yet. Cannot compile now."])).runModal()
// }
// }
//
//}
//
//
//
|
mit
|
d7a487c4b0b238b81c2d7979d2bd34c4
| 36.588235 | 161 | 0.746792 | 3.606095 | false | false | false | false |
laurentVeliscek/AudioKit
|
AudioKit/Common/Playgrounds/Effects.playground/Pages/Tremolo.xcplaygroundpage/Contents.swift
|
2
|
1275
|
//: ## Tremolo
//: ###
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
var tremolo = AKTremolo(player, waveform: AKTable(.PositiveSine))
tremolo.depth = 0.5
tremolo.frequency = 8
AudioKit.output = tremolo
AudioKit.start()
player.play()
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Tremolo")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: processingPlaygroundFiles))
addSubview(AKPropertySlider(
property: "Frequency",
format: "%0.3f Hz",
value: tremolo.frequency, maximum: 20,
color: AKColor.greenColor()
) { sliderValue in
tremolo.frequency = sliderValue
})
addSubview(AKPropertySlider(
property: "Depth",
value: tremolo.depth,
color: AKColor.redColor()
) { sliderValue in
tremolo.depth = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
|
mit
|
cda08770e4e878120d16d16c73fa6ad0
| 24.5 | 70 | 0.632157 | 4.6875 | false | false | false | false |
alessiobrozzi/firefox-ios
|
Client/Helpers/SpotlightHelper.swift
|
1
|
4446
|
/* 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 CoreSpotlight
import MobileCoreServices
import WebKit
private let log = Logger.browserLogger
private let browsingActivityType: String = "org.mozilla.ios.firefox.browsing"
class SpotlightHelper: NSObject {
fileprivate(set) var activity: NSUserActivity? {
willSet {
activity?.invalidate()
}
didSet {
activity?.delegate = self
}
}
fileprivate var urlForThumbnail: URL?
fileprivate var thumbnailImage: UIImage?
fileprivate let createNewTab: ((_ url: URL) -> Void)?
fileprivate weak var tab: Tab?
init(tab: Tab, openURL: ((_ url: URL) -> Void)? = nil) {
createNewTab = openURL
self.tab = tab
if let path = Bundle.main.path(forResource: "SpotlightHelper", ofType: "js") {
if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
tab.webView!.configuration.userContentController.addUserScript(userScript)
}
}
}
deinit {
// Invalidate the currently held user activity (in willSet)
// and release it.
self.activity = nil
}
func update(_ pageContent: [String: String], forURL url: URL) {
guard url.isWebPage(includeDataURIs: false) else {
return
}
var activity: NSUserActivity
if let currentActivity = self.activity, currentActivity.webpageURL == url {
activity = currentActivity
} else {
activity = createUserActivity()
self.activity = activity
activity.webpageURL = url
}
activity.title = pageContent["title"]
if !(tab?.isPrivate ?? true) {
let attrs = CSSearchableItemAttributeSet(itemContentType: kUTTypeHTML as String)
attrs.contentDescription = pageContent["description"]
attrs.contentURL = url
activity.contentAttributeSet = attrs
activity.isEligibleForSearch = true
}
// We can't be certain that the favicon isn't already available.
// If it is, for this URL, then update the activity with the favicon now.
if urlForThumbnail == url {
updateImage(thumbnailImage, forURL: url)
}
}
func updateImage(_ image: UIImage? = nil, forURL url: URL) {
guard let currentActivity = self.activity, currentActivity.webpageURL == url else {
// We've got a favicon, but not for this URL.
// Let's store it until we can get the title and description.
urlForThumbnail = url
thumbnailImage = image
return
}
if let image = image {
activity?.contentAttributeSet?.thumbnailData = UIImagePNGRepresentation(image)
}
urlForThumbnail = nil
thumbnailImage = nil
becomeCurrent()
}
func becomeCurrent() {
activity?.becomeCurrent()
}
func createUserActivity() -> NSUserActivity {
return NSUserActivity(activityType: browsingActivityType)
}
}
extension SpotlightHelper: NSUserActivityDelegate {
@objc func userActivityWasContinued(_ userActivity: NSUserActivity) {
if let url = userActivity.webpageURL {
createNewTab?(url)
}
}
}
extension SpotlightHelper: TabHelper {
static func name() -> String {
return "SpotlightHelper"
}
func scriptMessageHandlerName() -> String? {
return "spotlightMessageHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let tab = self.tab,
let url = tab.url,
let payload = message.body as? [String: String] {
update(payload, forURL: url as URL)
}
}
}
extension SpotlightHelper {
class func clearSearchIndex(completionHandler: ((Error?) -> Void)? = nil) {
CSSearchableIndex.default().deleteAllSearchableItems(completionHandler: completionHandler)
}
}
|
mpl-2.0
|
e56c35bbdb7ef061746100e29680d6c6
| 30.985612 | 141 | 0.636302 | 5.128028 | false | false | false | false |
josefdolezal/fit-cvut
|
BI-IOS/practice-5/bi-ios-recognizers/PanelView.swift
|
1
|
4791
|
//
// PanelView.swift
// bi-ios-recognizers
//
// Created by Dominik Vesely on 03/11/15.
// Copyright © 2015 Ackee s.r.o. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
class PanelView : UIView {
var delegate : PanelViewDelegate?
// closure, anonymni funkce
var onSliderChange : ((CGFloat) -> ())?
var syncValue : Double = 0 {
didSet {
if !uswitch.on {
syncValue = oldValue
}
slider.value = Float(syncValue)
stepper.value = syncValue
}
}
weak var slider : UISlider!
weak var stepper : UIStepper!
weak var uswitch : UISwitch!
weak var segment : UISegmentedControl!
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.lightGrayColor()
let slider = UISlider()
slider.minimumValue = 0
slider.maximumValue = 15
slider.addTarget(self, action: "sliderChanged:", forControlEvents: UIControlEvents.ValueChanged)
addSubview(slider)
self.slider = slider
let stepper = UIStepper()
stepper.minimumValue = 0;
stepper.maximumValue = 15;
stepper.stepValue = 0.5;
stepper.addTarget(self, action: "stepperChanged:", forControlEvents: UIControlEvents.ValueChanged)
addSubview(stepper)
self.stepper = stepper
let uswitch = UISwitch()
uswitch.setOn(true, animated: false)
addSubview( uswitch )
self.uswitch = uswitch
let segment = UISegmentedControl(items: ["Red", "Green", "Blue"])
segment.selectedSegmentIndex = 0
segment.addTarget(self, action: "colorChanged:", forControlEvents: .ValueChanged );
addSubview(segment)
self.segment = segment
// Automaticky se spusti, vola funkci fireTimer na self
let timer = NSTimer.scheduledTimerWithTimeInterval(1/30, target: self, selector: "fireTimer:", userInfo: nil, repeats: true)
//timer.performSelector("invalidate", withObject: nil, afterDelay: 5)
// nelze volat selector (protoze nebere argument) -> musim si udelat vlastni metodu
// po 5 vterinach zavola invalidateTimer
self.performSelector("invalidateTimer:", withObject: timer, afterDelay: 5)
}
// Nastavuje natvrdo velikost views
override func layoutSubviews() {
super.layoutSubviews()
uswitch.snp_makeConstraints { make in
make.top.equalTo(self).offset(8)
make.left.equalTo(self).offset(8)
}
segment.snp_makeConstraints { make in
make.top.equalTo(self).offset(8)
make.right.equalTo(self).offset(-8)
}
slider.snp_makeConstraints { make in
make.top.equalTo(segment).offset(10)
make.left.equalTo(self).offset(8)
}
stepper.snp_makeConstraints { make in
make.top.equalTo(segment).offset(10)
//make.right.equalTo(self).offset(-8)
//make.left.equalTo(slider).offset(8)
}
//self.stepper.frame = CGRectMake(CGRectGetWidth(slider.bounds) + 16, 59, CGRectGetWidth(self.bounds), 44)
//self.slider.frame = CGRectMake(8, 8+44, CGRectGetWidth(self.bounds) - CGRectGetWidth(stepper.bounds) - 24, 44)
}
func invalidateTimer(timer: NSTimer) {
timer.invalidate()
}
//MARK: Action
func fireTimer(timer:NSTimer) {
syncValue = Double(self.slider.value + 0.01)
delegate?.syncedValueChanged(syncValue, panel: self)
}
func sliderChanged(slider : UISlider) {
syncValue = Double(slider.value)
delegate?.syncedValueChanged(syncValue, panel: self)
}
func stepperChanged(stepper: UIStepper) {
syncValue = stepper.value
delegate?.syncedValueChanged(syncValue, panel: self)
}
func colorChanged(segment: UISegmentedControl) {
let color : [UIColor] = [ .redColor(), .greenColor(), .blueColor() ]
if segment.selectedSegmentIndex < color.count {
delegate?.selectedColorChanged(color[segment.selectedSegmentIndex], panel: self)
return
}
delegate?.selectedColorChanged(.blackColor(), panel: self)
}
// Kvuli prepisovani initializeru
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
protocol PanelViewDelegate {
func syncedValueChanged(syncedValue : Double, panel: PanelView)
func selectedColorChanged(color: UIColor, panel: PanelView )
}
|
mit
|
0e5cc847853b327c2940f6b9318a0869
| 30.30719 | 132 | 0.608559 | 4.557564 | false | false | false | false |
azadibogolubov/InterestDestroyer
|
iOS Version/Interest Destroyer/Charts/Classes/Data/CandleChartDataEntry.swift
|
17
|
2102
|
//
// CandleChartDataEntry.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class CandleChartDataEntry: ChartDataEntry
{
/// shadow-high value
public var high = Double(0.0)
/// shadow-low value
public var low = Double(0.0)
/// close value
public var close = Double(0.0)
/// open value
public var open = Double(0.0)
public init(xIndex: Int, shadowH: Double, shadowL: Double, open: Double, close: Double)
{
super.init(value: (shadowH + shadowL) / 2.0, xIndex: xIndex)
self.high = shadowH
self.low = shadowL
self.open = open
self.close = close
}
public init(xIndex: Int, shadowH: Double, shadowL: Double, open: Double, close: Double, data: AnyObject?)
{
super.init(value: (shadowH + shadowL) / 2.0, xIndex: xIndex, data: data)
self.high = shadowH
self.low = shadowL
self.open = open
self.close = close
}
/// - returns: the overall range (difference) between shadow-high and shadow-low.
public var shadowRange: Double
{
return abs(high - low)
}
/// - returns: the body size (difference between open and close).
public var bodyRange: Double
{
return abs(open - close)
}
/// the center value of the candle. (Middle value between high and low)
public override var value: Double
{
get
{
return super.value
}
set
{
super.value = (high + low) / 2.0
}
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! CandleChartDataEntry
copy.high = high
copy.high = low
copy.high = open
copy.high = close
return copy
}
}
|
apache-2.0
|
36dc2a927c60bbd2a50fb2f5198d59cb
| 23.453488 | 109 | 0.578972 | 4.121569 | false | false | false | false |
noremac/DataSource
|
Example/ViewController.swift
|
1
|
3269
|
/*
The MIT License (MIT)
Copyright (c) 2017 Cameron Pulsford
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
import DataSource
class TableViewController: UITableViewController, TableViewDataSourceDelegate {
let dataSource = DataSource<DataItem>()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.configure(tableView: tableView, delegate: self)
// Verbosely create a section
var item1 = DataItem()
item1.title = "Item 1"
var item2 = DataItem()
item2.title = "Item 2"
var item3 = DataItem()
item3.title = "Item 3"
let section1 = Section(items: [item1, item2, item3])
dataSource.append(section: section1)
// With array and string literal convertibles, the above code can be identically acheived like this:
dataSource.append(section: ["Item 1", "Item 2", "Item 3"])
// Now let's use a custom cell class
// Register the cell class in the `registerCells` protocol method. (implemented below)
let fancyItems: [DataItem] = (1...3).map {
var item = DataItem()
item.title = "Item \($0)"
item.subtitle = "Subtitle \($0)"
item.cellType = 1 // Don't forget to set the cell type
return item
}
var section3 = Section(items: fancyItems)
section3.headerTitle = "custom cells!" // set a header if you'd like
dataSource.append(section: section3)
}
func registerCells() {
dataSource.register(cellKind: CustomCellClass.self, for: 1)
}
func configure(cell: UITableViewCell, atIndexPath indexPath: IndexPath) {
guard let item = dataSource.item(for: indexPath) else {
return
}
cell.textLabel?.text = item.title
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
class CustomCellClass: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
fde3123dd946ef37b5b5182935736a94
| 36.147727 | 108 | 0.691343 | 4.643466 | false | false | false | false |
djtone/VIPER
|
VIPER-SWIFT/Classes/Common/Store/CoreDataStore.swift
|
2
|
2811
|
//
// CoreDataStore.swift
// VIPER-SWIFT
//
// Created by Conrad Stoll on 6/4/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
import CoreData
extension Array {
func lastObject() -> T {
let endIndex = self.endIndex
let lastItemIndex = endIndex - 1
return self[lastItemIndex]
}
}
class CoreDataStore : NSObject {
var persistentStoreCoordinator : NSPersistentStoreCoordinator?
var managedObjectModel : NSManagedObjectModel?
var managedObjectContext : NSManagedObjectContext?
override init() {
managedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil)
persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel!)
let domains = NSSearchPathDomainMask.UserDomainMask
let directory = NSSearchPathDirectory.DocumentDirectory
let error = NSError()
let applicationDocumentsDirectory : AnyObject = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domains).lastObject()
let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true]
let storeURL = applicationDocumentsDirectory.URLByAppendingPathComponent("VIPER-SWIFT.sqlite")
persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: "", URL: storeURL, options: options, error: nil)
managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext!.persistentStoreCoordinator = persistentStoreCoordinator
managedObjectContext!.undoManager = nil
super.init()
}
func fetchEntriesWithPredicate(predicate: NSPredicate, sortDescriptors: [AnyObject], completionBlock: (([ManagedTodoItem]) -> Void)!) {
let fetchRequest = NSFetchRequest(entityName: "TodoItem")
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = []
managedObjectContext?.performBlock {
let queryResults = self.managedObjectContext?.executeFetchRequest(fetchRequest, error: nil)
let managedResults = queryResults! as! [ManagedTodoItem]
completionBlock(managedResults)
}
}
func newTodoItem() -> ManagedTodoItem {
let entityDescription = NSEntityDescription.entityForName("TodoItem", inManagedObjectContext: managedObjectContext!)
let newEntry = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext) as! ManagedTodoItem
return newEntry
}
func save() {
managedObjectContext?.save(nil)
}
}
|
mit
|
5a2d2fd47f782deabd2e84d375ccaa6d
| 38.605634 | 147 | 0.716827 | 6.757212 | false | false | false | false |
EasySwift/EasySwift
|
Carthage/Checkouts/RainbowNavigation/RainbowNavigationSample/MainTableViewController.swift
|
2
|
2087
|
//
// MainTableViewController.swift
// RainbowNavigationSample
//
// Created by Danis on 15/12/30.
// Copyright © 2015年 danis. All rights reserved.
//
import UIKit
import RainbowNavigation
class MainTableViewController: UITableViewController, RainbowColorSource {
lazy var rainbowNavigation = RainbowNavigation()
let navColor = UIColor(red: 201/255.0, green: 115/255.0, blue: 228/255.0, alpha: 1.0)
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.df_setBackgroundColor(navColor)
self.navigationController?.navigationBar.df_setStatusBarMaskColor(UIColor(white: 0, alpha: 0.2))
if let navigationController = navigationController {
rainbowNavigation.wireTo(navigationController: navigationController)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SampleCell", for: indexPath as IndexPath)
switch indexPath.row {
case 0:
cell.textLabel?.text = "Color"
case 1:
cell.textLabel?.text = "Transparent"
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
performSegue(withIdentifier: "PushColorVC", sender: self)
case 1:
performSegue(withIdentifier: "PushTransparentVC", sender: self)
default:
break
}
}
// MARK: - RainbowColorSource
func navigationBarInColor() -> UIColor {
return navColor
}
}
|
apache-2.0
|
db8dabedf86070a3f0db5d58ca172587
| 30.104478 | 109 | 0.650672 | 5.021687 | false | false | false | false |
cemolcay/ChordDetector
|
ChordDetectorTests/ChordDetectorTests.swift
|
1
|
1984
|
//
// ChordDetectorTests.swift
// ChordDetectorTests
//
// Created by Cem Olcay on 31/03/2017.
// Copyright © 2017 cemolcay. All rights reserved.
//
import XCTest
import WebKit
@testable import Chord_Detector
class ChordDetectorTests: XCTestCase, WKNavigationDelegate {
var webView = WKWebView()
var wkExpectation = XCTestExpectation(description: "WKNavigationDelegate")
let artist = "The Animals"
let song = "House Of The Rising Sun"
func testUltimateGuitarParse() {
var url = "https://www.ultimate-guitar.com/search.php?search_type=title&order=&value="
url += "\(artist.replacingOccurrences(of: " ", with: "+"))+"
url += "\(song.replacingOccurrences(of: " ", with: "+"))"
guard let chordUrl = URL(string: url) else { return XCTFail("URL not parsed.") }
webView.navigationDelegate = self
webView.load(URLRequest(url: chordUrl))
wait(for: [wkExpectation], timeout: 10.0)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let js = """
window.UGAPP.store.page.data.results
.filter(function(item){ return (item.type == "Chords") })
.sort(function(a, b){ return b.rating > a.rating })[0]
"""
webView.evaluateJavaScript(js, completionHandler: { result, error in
guard let json = result as? [String: Any],
error == nil
else { XCTFail("Can not evaluate javascript"); return }
guard let url = json["tab_url"] as? String,
let artist = json["artist_name"] as? String,
let song = json["song_name"] as? String,
let item = UGItem(dict: json)
else { XCTFail("Can not serialize javascript object"); return }
XCTAssertEqual(self.artist, artist)
XCTAssertEqual(self.song, song)
XCTAssertNotNil(URL(string: url), "Url is nil")
XCTAssertEqual(self.artist, item.artist)
XCTAssertEqual(self.song, item.song)
XCTAssertEqual(url, item.url.absoluteString)
self.wkExpectation.fulfill()
})
}
}
|
mit
|
712ce663f6459fcebe3bb5ed5cd6ee0f
| 34.410714 | 90 | 0.666162 | 3.934524 | false | true | false | false |
afaan5556/toolbelt
|
xcode-toolbelt/ToolBelt/Pods/Alamofire/Source/ServerTrustPolicy.swift
|
235
|
13070
|
//
// ServerTrustPolicy.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
public class ServerTrustPolicyManager {
/// The dictionary of policies mapped to a particular host.
public let policies: [String: ServerTrustPolicy]
/**
Initializes the `ServerTrustPolicyManager` instance with the given policies.
Since different servers and web services can have different leaf certificates, intermediate and even root
certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
pinning for host3 and disabling evaluation for host4.
- parameter policies: A dictionary of all policies mapped to a particular host.
- returns: The new `ServerTrustPolicyManager` instance.
*/
public init(policies: [String: ServerTrustPolicy]) {
self.policies = policies
}
/**
Returns the `ServerTrustPolicy` for the given host if applicable.
By default, this method will return the policy that perfectly matches the given host. Subclasses could override
this method and implement more complex mapping implementations such as wildcards.
- parameter host: The host to use when searching for a matching policy.
- returns: The server trust policy for the given host if found.
*/
public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
return policies[host]
}
}
// MARK: -
extension NSURLSession {
private struct AssociatedKeys {
static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
}
var serverTrustPolicyManager: ServerTrustPolicyManager? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
}
set (manager) {
objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - ServerTrustPolicy
/**
The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
with a given set of criteria to determine whether the server trust is valid and the connection should be made.
Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
to route all communication over an HTTPS connection with pinning enabled.
- PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
validate the host provided by the challenge. Applications are encouraged to always
validate the host in production environments to guarantee the validity of the server's
certificate chain.
- PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
considered valid if one of the pinned certificates match one of the server certificates.
By validating both the certificate chain and host, certificate pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
valid if one of the pinned public keys match one of the server certificate public keys.
By validating both the certificate chain and host, public key pinning provides a very
secure form of server trust validation mitigating most, if not all, MITM attacks.
Applications are encouraged to always validate the host and require a valid certificate
chain in production environments.
- DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
- CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
*/
public enum ServerTrustPolicy {
case PerformDefaultEvaluation(validateHost: Bool)
case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
case DisableEvaluation
case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool)
// MARK: - Bundle Location
/**
Returns all certificates within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `.cer` files.
- returns: All certificates within the given bundle.
*/
public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] {
var certificates: [SecCertificate] = []
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil)
}.flatten())
for path in paths {
if let
certificateData = NSData(contentsOfFile: path),
certificate = SecCertificateCreateWithData(nil, certificateData)
{
certificates.append(certificate)
}
}
return certificates
}
/**
Returns all public keys within the given bundle with a `.cer` file extension.
- parameter bundle: The bundle to search for all `*.cer` files.
- returns: All public keys within the given bundle.
*/
public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] {
var publicKeys: [SecKey] = []
for certificate in certificatesInBundle(bundle) {
if let publicKey = publicKeyForCertificate(certificate) {
publicKeys.append(publicKey)
}
}
return publicKeys
}
// MARK: - Evaluation
/**
Evaluates whether the server trust is valid for the given host.
- parameter serverTrust: The server trust to evaluate.
- parameter host: The host of the challenge protection space.
- returns: Whether the server trust is valid.
*/
public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool {
var serverTrustIsValid = false
switch self {
case let .PerformDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy])
serverTrustIsValid = trustIsValid(serverTrust)
case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy])
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
serverTrustIsValid = trustIsValid(serverTrust)
} else {
let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates)
outerLoop: for serverCertificateData in serverCertificatesDataArray {
for pinnedCertificateData in pinnedCertificatesDataArray {
if serverCertificateData.isEqualToData(pinnedCertificateData) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
var certificateChainEvaluationPassed = true
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, [policy])
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
if certificateChainEvaluationPassed {
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
if serverPublicKey.isEqual(pinnedPublicKey) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case .DisableEvaluation:
serverTrustIsValid = true
case let .CustomEvaluation(closure):
serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
}
return serverTrustIsValid
}
// MARK: - Private - Trust Validation
private func trustIsValid(trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType(kSecTrustResultInvalid)
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
let proceed = SecTrustResultType(kSecTrustResultProceed)
isValid = result == unspecified || result == proceed
}
return isValid
}
// MARK: - Private - Certificate Data
private func certificateDataForTrust(trust: SecTrust) -> [NSData] {
var certificates: [SecCertificate] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
certificates.append(certificate)
}
}
return certificateDataForCertificates(certificates)
}
private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] {
return certificates.map { SecCertificateCopyData($0) as NSData }
}
// MARK: - Private - Public Key Extraction
private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] {
var publicKeys: [SecKey] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let
certificate = SecTrustGetCertificateAtIndex(trust, index),
publicKey = publicKeyForCertificate(certificate)
{
publicKeys.append(publicKey)
}
}
return publicKeys
}
private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust where trustCreationStatus == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust)
}
return publicKey
}
}
|
mit
|
be400c878056ae4e8db6d7de3d105bde
| 41.993421 | 121 | 0.660291 | 6.039741 | false | false | false | false |
MediaBrowser/Emby.ApiClient.Swift
|
Emby.ApiClient/model/dto/BaseItemDto.swift
|
1
|
11355
|
//
// BaseItemDto.swift
// Emby.ApiClient
//
import Foundation
public class BaseItemDto : JSONSerializable {
public var name: String?
public var serverId: String?
public var id: String?
public var etag: String?
public var playlistItemid: String?
public var dateCreated: NSDate?
public var dateLastMediaAdded: NSDate?
public var extraType: ExtraType?
public var airsBeforeSeasonNumber: Int?
public var airsAfterSeasonNumber: Int?
public var airsBeforeEpisodeNumber: Int?
public var absoluteEpisodeNumber: Int?
public var displaySpecialWithSeasons: Bool?
public var canDelete: Bool?
public var canDownload: Bool?
public var hasSubtitles: Bool?
public var preferredMetadataLanguage: String?
public var preferredMetadataCountryCode: String?
public var awardSummary: String?
public var shareUrl: String?
public var metascore: Float?
public var hasDynamicCategories: Bool?
public var animeSeriesIndex: Int?
public var supportsSync: Bool?
public var hasSyncJob: Bool?
public var isSynced: Bool?
public var syncStatus: SyncJobStatus?
public var syncPercent: Double?
public var dvdSeasonNumber: Int?
public var dvdEpisodeNumber: Int?
public var sortName: String?
public var forcedSortName: String?
public var video3dFormat: Video3DFormat?
public var premierDate: NSDate?
public var externalUrls: [ExternalUrl]?
public var mediaSources: [MediaSourceInfo]?
public var criticRating: Float?
public var gameSystem: String?
public var criticRatingSummary: String?
public var multiPartGameFiles: [String]?
public var path: String?
public var officialRating: String?
public var customRating: String?
public var channelId: String?
public var channelName: String?
public var overview: String?
public var shortOverview: String?
public var tmdbCollectionName: String?
public var tagLines: [String]?
public var genres: [String]?
public var seriesGenres: [String]?
public var communityRating: Float?
public var voteCount: Int?
public var cumulativeRunTimeTicks: Int?
public var originalRunTimeTicks: Int?
public var runTimeTicks: Int?
public var playAccess: PlayAccess?
public var aspectRation: String?
public var productionYear: Int?
public var players: Int?
public var isPlaceHolder: Bool?
public var indexNumber: Int?
public var indexNumberEnd: Int?
public var parentIndexNumber: Int?
public var remoteTrailers: [MediaUrl]?
public var soundtrackIds: [String]?
public var providerIds: [String:String]?
public var isHd: Bool?
public var isFolder: Bool?
public var parentId: String?
public var type: String?
public var people: [BaseItemPerson]?
public var studios: [StudioDto]?
public var parentLogoItemId: String?
public var parentBackdropItemId: String?
public var parentBackdropImageTags: [String]?
public var localTrailerCount: Int?
public var userData: UserItemDataDto?
public var seasonUserData: UserItemDataDto?
public var recursiveItemCount: Int?
public var childCount: Int?
public var seriesName: String?
public var seriesId: String?
public var seasonId: String?
public var specialFeatureCount: Int?
public var displayPreferencesId: String?
public var status: String?
public var seriesStatus: SeriesStatus? {
get {
if let status = self.status {
return SeriesStatus(rawValue: status)
} else {
return nil
}
}
set {
status = newValue!.rawValue
}
}
public var recordingStatus: RecordingStatus? {
get {
if let status = self.status {
return RecordingStatus(rawValue: status)
} else {
return nil
}
}
set {
status = newValue!.rawValue
}
}
public var airTime: String?
public var airDays: [String]?
public var indexOptions: [String]?
public var tags: [String]?
public var keywords: [String]?
public var primaryImageAspectRatio: Double?
public var originalPrimaryImageAspectRatio: Double?
public var artists: [String]?
public var artistItems: [NameIdPair]?
public var album: String?
public var collectionType: String?
public var displayOrder: String?
public var albumId: String?
public var albumPrimaryImageTag: String?
public var seriesPrimaryImageTag: String?
public var albumArtist: String?
public var albumArtists: [NameIdPair]?
public var seasonName: String?
public var mediaStreams: [MediaStream]?
public var videoType: VideoType?
public var displayMediaType: String?
public var partCount: Int?
public var mediaSourceCount: Int?
public var supportsPlayLists: Bool {
get {
return (runTimeTicks != nil) || ((isFolder != nil) && isFolder!) || isGenre || isMusicGenre || isArtist
}
}
public func isType(type: String) -> Bool {
return self.type == type
}
public var imageTags: [ImageType: String]?
public var backdropImageTags: [String]?
public var screenshotImageTags: [String]?
public var parentLogoImageTag: String?
public var parentArtItemId: String?
public var parentArtImageTag: String?
public var seriesThumbImageTag: String?
public var seriesStudio: String?
public var parentThumbItemId: String?
public var parentThumbImageTag: String?
public var parentPrimaryImageItemId: String?
public var parentPrimaryImageTag: String?
public var chapters: [ChapterInfoDto]?
public var locationType: LocationType?
public var isoType: IsoType?
public var mediaType: String?
public var endDate: NSDate?
public var homePageUrl: String?
public var productionLocations: [String]?
public var budget: Double?
public var revenue: Double?
public var lockedFields: [MetadataFields]?
public var movieCount: Int?
public var seriesCount: Int?
public var episodeCount: Int?
public var gameCount: Int?
public var songCount: Int?
public var albumCount: Int?
public var musicVideoCount: Int?
public var lockData: Bool?
public var width: Int?
public var height: Int?
public var cameraMake: String?
public var cameraModel: String?
public var software: String?
public var exposureTime: Double?
public var focalLength: Double?
public var imageOrientation: ImageOrientation?
public var aperture: Double?
public var shutterSpeed: Double?
public var latitude: Double?
public var longitude: Double?
public var altitude: Double?
public var isoSpeedRating: Int?
public var recordingCount: Int?
public var seriesTimerId: String?
public var canResume: Bool {
get {
if let playbackPositionTicks = userData?.playbackPositionTicks {
return playbackPositionTicks > 0
} else {
return false
}
}
}
public var resumePositionTicks: Int {
get {
if let playbackPositionTicks = userData?.playbackPositionTicks {
return playbackPositionTicks
} else {
return 0
}
}
}
public var backdropCount: Int {
get {
return (backdropImageTags != nil) ? backdropImageTags!.count : 0
}
}
public var screenshotCount: Int {
get {
return (screenshotImageTags != nil) ? screenshotImageTags!.count : 0
}
}
public var hasBanner: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Banner] != nil : false
}
}
public var hasArtImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Art] != nil : false
}
}
public var hasLogo: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Logo] != nil : false
}
}
public var hasThumb: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Thumb] != nil : false
}
}
public var hasPrimaryImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Primary] != nil : false
}
}
public var hasDiscImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Disc] != nil : false
}
}
public var hasBoxImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Box] != nil : false
}
}
public var hasBoxRearImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.BoxRear] != nil : false
}
}
public var hasMenuImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Menu] != nil : false
}
}
public var isVideo: Bool {
get {
return mediaType == MediaType.Video.rawValue
}
}
public var isGame: Bool {
get {
return mediaType == MediaType.Game.rawValue
}
}
public var isPerson: Bool {
get {
return mediaType == "Person"
}
}
public var isRoot: Bool {
get {
return mediaType == "AggregateFolder"
}
}
public var isMusicGenre: Bool {
get {
return mediaType == "MusicGenre"
}
}
public var isGameGenre: Bool {
get {
return mediaType == "GameGenre"
}
}
public var isGenre: Bool {
get {
return mediaType == "Genre"
}
}
public var isArtist: Bool {
get {
return mediaType == "MusicArtist"
}
}
public var isAlbum: Bool {
get {
return mediaType == "MusicAlbum"
}
}
public var IsStudio: Bool {
get {
return mediaType == "Studio"
}
}
public var supportsSimilarItems: Bool {
get {
return isType(type: "Movie") || isType(type: "Series") || isType(type: "MusicAlbum") || isType(type: "MusicArtist") || isType(type: "Program") || isType(type: "Recording") || isType(type: "ChannelVideoItem") || isType(type: "Game")
}
}
public var programId: String?
public var channelPrimaryImageTag: String?
public var startDate: NSDate?
public var completionPercentage: Double?
public var isRepeat: Bool?
public var episodeTitle: String?
public var channelType: ChannelType?
public var audio: ProgramAudio?
public var isMovie: Bool?
public var isSports: Bool?
public var isSeries: Bool?
public var isLive: Bool?
public var isNews: Bool?
public var isKids: Bool?
public var isPremiere: Bool?
public var timerId: String?
public var currentProgram: BaseItemDto?
public required init?(jSON: JSON_Object) {
//fatalError("init(jSON:) has not been implemented: \(jSON)")
self.name = jSON["Name"] as? String
}
}
|
mit
|
e3d0fb99e91451108c6970aa35b1e558
| 29.039683 | 243 | 0.624571 | 4.516706 | false | false | false | false |
lynnx4869/LYAutoPhotoPickers
|
Classes/Classes/LYAutoAlbumsController.swift
|
1
|
5640
|
//
// LYAutoAlbumsController.swift
// LYAutoPhotoPickers
//
// Created by xianing on 2017/6/30.
// Copyright © 2017年 lyning. All rights reserved.
//
import UIKit
import Photos
class LYAutoAlbumModel {
var assetCollection: PHAssetCollection!
var title: String!
var count: Int!
var image: UIImage!
}
class LYAutoAlbumsController: LYAutoPhotoBasicController, UITableViewDelegate, UITableViewDataSource {
private var array = [LYAutoAlbumModel]()
private var tableView: UITableView!
private var userLibrary: PHAssetCollection!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .white
navigationItem.title = "照片"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消",
style: .done,
target: self,
action: #selector(goBack(_:)))
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(UINib(nibName: "LYAutoAlbumCell",
bundle: Bundle(for: LYAutoPhotoPickers.self)),
forCellReuseIdentifier: "LYAutoAlbumCellId")
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(tableView)
DispatchQueue.global().async {
[weak self] in
let sysAssetCollections = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: nil)
sysAssetCollections.enumerateObjects({ (assetCollection, idx, info) in
let assets = PHAsset.fetchAssets(in: assetCollection, options: nil)
if assets.count != 0 {
let albumModel = LYAutoAlbumModel()
albumModel.assetCollection = assetCollection
self?.array.append(albumModel)
}
if assetCollection.assetCollectionSubtype == .smartAlbumUserLibrary {
self?.userLibrary = assetCollection
}
})
let userAssetCollections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
userAssetCollections.enumerateObjects({ (assetCollection, idx, info) in
let assets = PHAsset.fetchAssets(in: assetCollection, options: nil)
if assets.count != 0 {
let albumModel = LYAutoAlbumModel()
albumModel.assetCollection = assetCollection
self?.array.append(albumModel)
}
})
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
if let userLibrary = self?.userLibrary {
self?.gotoOneAlbum(assetCollection: userLibrary, animated: false)
}
self?.tableView.reloadData()
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
debugPrint("albums view controller dealloc")
}
@objc private func goBack(_ item: UIBarButtonItem) {
block(nil)
navigationController?.dismiss(animated: true, completion: nil)
}
//MARK: - UITableViewDelegate
internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
internal func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LYAutoAlbumCellId") as! LYAutoAlbumCell
let cellModel = array[indexPath.row]
if cellModel.image == nil {
let assets = PHAsset.fetchAssets(in: cellModel.assetCollection, options: nil)
let asset = assets.lastObject
cellModel.title = cellModel.assetCollection.localizedTitle!
cellModel.count = assets.count
cellModel.image = asset?.getTumAssetImage()
}
cell.albumTitle.text = cellModel.title
cell.albumCount.text = String(cellModel.count)
cell.albumImage.image = cellModel.image
return cell
}
internal func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let assetCollection = array[indexPath.row].assetCollection
gotoOneAlbum(assetCollection: assetCollection!, animated: true)
}
private func gotoOneAlbum(assetCollection: PHAssetCollection, animated: Bool) {
let pvc = LYAutoPhotosController(nibName: "LYAutoPhotosController", bundle: Bundle(for: LYAutoPhotoPickers.self))
pvc.assetCollection = assetCollection
pvc.maxSelects = maxSelects
pvc.isRateTailor = isRateTailor
pvc.tailoringRate = tailoringRate
pvc.block = block
navigationController?.pushViewController(pvc, animated: animated)
}
}
|
mit
|
9bb9171ed4793b9f22a1595b343b8cb5
| 36.526667 | 130 | 0.596376 | 5.617764 | false | false | false | false |
gottesmm/swift
|
test/SILOptimizer/devirt_contravariant_args.swift
|
4
|
1790
|
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -O -primary-file %s -emit-sil -sil-inline-threshold 1000 -sil-verify-all | %FileCheck %s
// Make sure that we can dig all the way through the class hierarchy and
// protocol conformances.
// CHECK-LABEL: sil hidden @_T025devirt_contravariant_args6driveryyF : $@convention(thin) () -> () {
// CHECK: function_ref unknownC2
// CHECK: function_ref unknownC1
// CHECK: function_ref unknownC0
// CHECK: return
// CHECK-NEXT: }
@_silgen_name("unknownC0")
func unknownC0(_ c : C0) -> ()
@_silgen_name("unknownC1")
func unknownC1(_ c : C1) -> ()
@_silgen_name("unknownC2")
func unknownC2(_ c : C2) -> ()
protocol P {}
class C0 : P {}
class C1 : C0 {}
class C2 : C1 {}
class B<T> {
func performSomething(_ p : P) {
doSomething(p as! C2)
}
func doSomething(_ c : C2) {
unknownC2(c)
}
// See comment in protocol P
//class func doSomethingMeta() {
// unknown1b()
//}
}
class B2<T> : B<T> {
override func performSomething(_ p : P) {
doSomething(p as! C1)
}
// When we have covariance in protocols, change this to B2.
// We do not specialize typealias correctly now.
//typealias X = B
override func doSomething(_ c : C1) {
unknownC1(c)
}
// See comment in protocol P
//override class func doSomethingMeta() {
// unknown2b()
//}
}
class B3<T> : B2<T> {
override func performSomething(_ p : P) {
doSomething(p as! C0)
}
override func doSomething(_ c : C0) {
unknownC0(c)
}
}
func doSomething<T : P>(_ b : B<T>, _ t : T) {
b.performSomething(t)
}
func driver() -> () {
let b = B<C2>()
let b2 = B2<C1>()
let b3 = B3<C0>()
let c0 = C0()
let c1 = C1()
let c2 = C2()
doSomething(b, c2)
doSomething(b2, c1)
doSomething(b3, c0)
}
driver()
|
apache-2.0
|
7f3cfcb4bc35236999cc348f8026748e
| 19.11236 | 150 | 0.617318 | 2.89644 | false | false | false | false |
vojto/NiceKit
|
NiceKit/NKTextField.Mac.swift
|
1
|
6178
|
//
// NKTextField.swift
// Pomodoro X
//
// Created by Vojtech Rinik on 07/12/15.
// Copyright © 2015 Vojtech Rinik. All rights reserved.
//
import Foundation
import Cocoa
import CoreGraphics
public enum NKAutocorrectionType {
case no
}
public enum NKAutocapitalizationType {
case none
}
public enum NKKeyboardType {
case numberPad
}
open class NKTextField: NSTextField, NKViewable {
var transientDelegate: NKTextFieldDelegate
open var style: NKStyle
open var placeholderStyle: NKStyle
open var classes = Set<String>()
open var onChange: NKSimpleCallback?
open var onCancel: NKSimpleCallback?
open var onBlur: NKSimpleCallback?
open var onFocus: NKSimpleCallback?
open var onSubmit: NKSimpleCallback?
open var onTab: NKSimpleCallback?
open var onAction: NKSimpleCallback? {
get { return onClick }
set { onClick = newValue }
}
open var onClick: NKSimpleCallback?
open var onMouseDown: ((NSEvent) -> Void)?
open var onMouseUp: ((NSEvent) -> Void)?
open var autocorrectionType: NKAutocorrectionType?
open var autocapitalizationType: NKAutocapitalizationType?
open var keyboardType: NKKeyboardType?
open var fieldType: NKFieldType?
open var secureValue: String = ""
open override var placeholder: String? {
get { return super.placeholder }
set {
let str = NSMutableAttributedString(string: newValue!)
str.font = placeholderStyle.font
str.textColor = placeholderStyle.textColor?.color
super.placeholderAttributedString = str
}
}
// override var text: String? {
// get { return super.text }
// set {
// super.text = newValue
// applyStyle()
// }
// }
// MARK: - Lifecycle
// ----------------------------------------------------------------------
public override init(frame frameRect: NSRect) {
self.style = NKStylesheet.styleForView(type(of: self))
self.placeholderStyle = NKStylesheet.styleForView(type(of: self), classes: ["placeholder"])
self.transientDelegate = NKTextFieldDelegate()
super.init(frame: frameRect)
self.delegate = self.transientDelegate
self.transientDelegate.textField = self
// self.drawsBackground = false
// self.backgroundColor = XColor.clear
// self.isBordered = false
// self.focusRingType = .none
// applyStyle()
}
open func setup() {
}
public convenience init(placeholder: String) {
self.init(frame: CGRect.zero)
self.placeholder = placeholder
}
required public init?(coder: NSCoder) {
self.transientDelegate = NKTextFieldDelegate()
self.style = NKStylesheet.styleForView(type(of: self))
self.placeholderStyle = NKStylesheet.styleForView(type(of: self), classes: ["placeholder"])
super.init(coder: coder)
self.delegate = self.transientDelegate
self.transientDelegate.textField = self
}
// MARK: - Style support
// ----------------------------------------------------------------------
open func applyStyle() {
font = style.font
if let color = style.textColor {
self.textColor = color.color
}
if let opacity = style.opacity {
self.alpha = opacity
} else {
self.alpha = 1
}
if let align = style.textAlign {
switch(align) {
case .Left: textAlignment = .left
case .Center: textAlignment = .center
case .Right: textAlignment = .right
}
}
if let background = style.background {
self.backgroundColor = background.color
self.drawsBackground = true
}
// let text = style.prepareAttributedString(self.text!)
// self.attributedStringValue = text
}
// MARK: - Events
// ----------------------------------------------------------------------
open func handleClickFromTable(_ event: NSEvent) {
if self.isEditable {
self.window?.makeFirstResponder(self)
}
}
override open func textDidEndEditing(_ notification: Notification) {
super.textDidEndEditing(notification)
onBlur?()
}
override open func textDidBeginEditing(_ notification: Notification) {
super.textDidBeginEditing(notification)
onFocus?()
}
open func blur() {
window?.makeFirstResponder(nil)
}
open func focus() {
window?.makeFirstResponder(self)
}
var hasClickHandler: Bool {
return onMouseDown != nil || onMouseUp != nil || onClick != nil
}
open override func mouseDown(with theEvent: NSEvent) {
super.mouseDown(with: theEvent)
onMouseDown?(theEvent)
}
open override func mouseUp(with theEvent: NSEvent) {
super.mouseUp(with: theEvent)
onMouseUp?(theEvent)
onClick?()
}
open func triggerChange() {
self.onChange?()
}
var lastValue: String = ""
open override var stringValue: String {
get {
return super.stringValue
}
set {
self.lastValue = newValue
super.stringValue = newValue
}
}
}
class NKTextFieldDelegate: NSObject, NSTextFieldDelegate {
var textField: NKTextField!
override func controlTextDidChange(_ notification: Notification) {
textField.triggerChange()
}
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if let onTab = textField.onTab, String(describing: commandSelector) == "insertTab:" {
onTab()
return true
} else if String(describing: commandSelector) == "cancelOperation:" {
textField.onCancel?()
return true
} else if String(describing: commandSelector) == "insertNewline:" {
textField.onSubmit?()
return true
}
return false
}
}
|
mit
|
cfe064a936ab44e89a2dba155714c9de
| 25.063291 | 109 | 0.590902 | 4.9416 | false | false | false | false |
rectinajh/leetCode_Swift
|
Spiral_Matrix_ii/Spiral_Matrix_ii/Spiral_Matrix_ii.swift
|
1
|
4045
|
//
// Spiral_Matrix_ii.swift
// Spiral_Matrix_ii
//
// Created by hua on 16/8/18.
// Copyright © 2016年 212. All rights reserved.
//
import Foundation
/*
https://leetcode.com/problems/spiral-matrix-ii/
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Inspired by @yike at https://leetcode.com/discuss/21677/simple-c-solution-with-explaination
*/
class Solution_I {
func generateMatrix(n:Int) -> [[Int]] {
var res = Array<Array<Int>>(count:n,repeatedValue:[Int](count:n,repeatedValue:0))
// var matrix = [[Int]](count:n,repeatedValue:[Int](count:n,repeatedValue:0))
var k = 1
var i = 0
while k <= n * n {
var j = i
// 1. horizonal, left to right
while j < n - i {
res[i][j] = k
j += 1
k += 1
}
j = i + 1
// 2. vertical, top to bottom
while j < n - i {
res[j][n-i-1] = k
j += 1
k += 1
}
j = n - i - 2
// 3. horizonal, right to left
while j > i {
res[n-i-1][j] = k
j -= 1
k += 1
}
j = n - i - 1
// 4. vertical, bottom to top
while j > i {
res[j][i] = k
j -= 1
k += 1
}
i += 1
}
return res
}
}
//第二种方法
class Solution_II {
func generateMatrix(n:Int) -> [[Int]] {
guard n > 0 else {
return [[Int]]()
}
var num = 1
var res = Array(count: n, repeatedValue: Array(count: n, repeatedValue: 0))
var start = 0
var end = 0
var offset = 0
for layer in 0 ..< n / 2 {
start = layer
end = n - layer - 1
// top
for i in start ..< end {
res[start][i] = num
num += 1
}
// right
for i in start ..< end {
res[i][end] = num
num += 1
}
// bottom
for i in end.stride(to: start, by: -1) {
res[end][i] = num
num += 1
}
// left
for i in end.stride(to: start, by: -1) {
res[i][start] = num
num += 1
}
}
// handle the center one
if n % 2 != 0 {
res[n / 2][n / 2] = n * n
}
return res
}
}
//
//struct Spiral_Matrix_II {
// static func generateMatrix( n: Int) -> [[Int]] {
// var res = Array<Array<Int>>(count: n,repeatedValue: [Int](count:0,repeatedValue:0))
// var k = 1
// var i = 0
// while k <= n * n {
// var j = i
// // 1. horizonal, left to right
// while j < n - i {
// res[i][j] = k
// j += 1
// k += 1
// }
// j = i + 1
// // 2. vertical, top to bottom
// while j < n - i {
// res[j][n-i-1] = k
// j += 1
// k += 1
// }
// j = n - i - 2
// // 3. horizonal, right to left
// while j > i {
// res[n-i-1][j] = k
// j -= 1
// k += 1
// }
// j = n - i - 1
// // 4. vertical, bottom to top
// while j > i {
// res[j][i] = k
// j -= 1
// k += 1
// }
// // next loop
// i += 1
// }
// return res
// }
//}
|
mit
|
412e96943c9c55c7a6b4c51993c90c55
| 22.44186 | 96 | 0.349454 | 3.789474 | false | false | false | false |
RxSwiftCommunity/RxTask
|
Tests/RxTaskTests/TaskTests.swift
|
1
|
4026
|
//
// TaskTests.swift
// RxTask
//
// Created by Scott Hoyt on 2/20/17.
//
//
import XCTest
@testable import RxTask
import RxSwift
import RxBlocking
class TaskTests: XCTestCase {
func testStdOut() throws {
let script = try ScriptFile(commands: [
"echo hello world",
"sleep 0.1"
])
let events = try getEvents(for: script)
XCTAssertEqual(events.count, 3)
XCTAssertEqual(events[0], .launch(command: script.path))
XCTAssertEqual(events[1], .stdOut("hello world\n".data(using: .utf8)!))
XCTAssertEqual(events[2], .exit(statusCode: 0))
}
func testStdErr() throws {
let script = try ScriptFile(commands: [
"echo hello world 1>&2",
"sleep 0.1"
])
let events = try getEvents(for: script)
XCTAssertEqual(events.count, 3)
XCTAssertEqual(events[0], .launch(command: script.path))
XCTAssertEqual(events[1], .stdErr("hello world\n".data(using: .utf8)!))
XCTAssertEqual(events[2], .exit(statusCode: 0))
}
func testExitsWithFailingStatusErrors() throws {
let script = try ScriptFile(commands: ["exit 100"])
do {
_ = try getEvents(for: script)
// If we get this far it is a failure
XCTFail()
} catch {
if let error = error as? TaskError {
XCTAssertEqual(error, .exit(statusCode: 100))
} else {
XCTFail()
}
}
}
func testUncaughtSignalErrors() throws {
let script = try ScriptFile(commands: [
"kill $$",
"sleep 10"
])
do {
_ = try getEvents(for: script)
// If we get this far it is a failure
XCTFail()
} catch {
if let error = error as? TaskError {
XCTAssertEqual(error, .uncaughtSignal)
} else {
XCTFail()
}
}
}
func testStdIn() throws {
let script = try ScriptFile(commands: [
"read var1",
"echo $var1",
"sleep 0.1",
"read var2",
"echo $var2",
"sleep 0.1"
])
let stdIn = Observable.of("hello\n", "world\n").map { $0.data(using: .utf8) ?? Data() }
let events = try Task(launchPath: script.path)
.launch(stdIn: stdIn)
.toBlocking()
.toArray()
XCTAssertEqual(events.count, 4)
XCTAssertEqual(events[0], .launch(command: script.path))
XCTAssertEqual(events[1], .stdOut("hello\n".data(using: .utf8)!))
XCTAssertEqual(events[2], .stdOut("world\n".data(using: .utf8)!))
XCTAssertEqual(events[3], .exit(statusCode: 0))
}
func testTaskEquality() {
let task1 = Task(launchPath: "/bin/echo", arguments: ["$MESSAGE"], workingDirectory: "/", environment: ["MESSAGE": "Hello World!"])
let task2 = Task(launchPath: "/bin/echo", arguments: ["$MESSAGE"], workingDirectory: "/", environment: ["MESSAGE": "Hello World!"])
let task3 = Task(launchPath: "/bin/echo", arguments: ["$MESSAGE"], workingDirectory: "/")
let task4 = Task(launchPath: "/bin/echo", arguments: ["$MESSAGE"], workingDirectory: "/")
XCTAssertEqual(task1, task2)
XCTAssertEqual(task3, task4)
XCTAssertNotEqual(task1, task3)
}
static var allTests: [(String, (TaskTests) -> () throws -> Void)] {
return [
("testStdOut", testStdOut),
("testStdErr", testStdErr),
("testExitsWithFailingStatusErrors", testExitsWithFailingStatusErrors),
("testUncaughtSignalErrors", testUncaughtSignalErrors)
]
}
// MARK: Helpers
func getEvents(for script: ScriptFile) throws -> [TaskEvent] {
return try Task(launchPath: script.path).launch()
.toBlocking()
.toArray()
}
}
|
mit
|
e7e88c0d5a5a17e9656c3406b5af21c9
| 29.5 | 139 | 0.544213 | 4.246835 | false | true | false | false |
dymx101/NiuBiBookCity
|
BookMountain/BookMountainEngine/BookParsingPatterns.swift
|
1
|
1134
|
//
// BookParsingPatterns.swift
// BookMountain
//
// Created by Yiming Dong on 26/05/2017.
// Copyright © 2017 Yiming Dong. All rights reserved.
//
import Foundation
/// BookParsingPatterns 用于配置图书解析时的正则表达式
class BookParsingPatterns:BaseModel {
var getSearchBookResult:GetBookListPatterns? = nil
var getBookChapterList:BookParsingItem? = nil
var getBookChapterDetail:BookParsingItem? = nil
var getCategoryBooksResult:GetBookListPatterns? = nil
override func loadFromDic(key:String,dic:NSDictionary)
{
if(key == "getSearchBookResult")
{
self.getSearchBookResult = GetBookListPatterns(dict: dic)
}
else if(key == "getBookChapterList")
{
self.getBookChapterList = BookParsingItem(dict: dic)
}
else if(key == "getBookChapterDetail")
{
self.getBookChapterDetail = BookParsingItem(dict: dic)
}
else if(key == "getCategoryBooksResult")
{
self.getCategoryBooksResult = GetBookListPatterns(dict: dic)
}
}
}
|
gpl-3.0
|
cc09e434a8ae7bd544e4a5d64665545a
| 25.261905 | 72 | 0.641886 | 4.162264 | false | false | false | false |
hirohisa/RxSwift
|
RxDataSourceStarterKit/DataSources/RxCollectionViewSectionedDataSource.swift
|
4
|
5743
|
//
// RxCollectionViewSectionedDataSource.swift
// RxExample
//
// Created by Krunoslav Zaher on 7/2/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
public class _RxCollectionViewSectionedDataSource : NSObject
, UICollectionViewDataSource {
func _numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 0
}
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return _numberOfSectionsInCollectionView(collectionView)
}
func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _collectionView(collectionView, numberOfItemsInSection: section)
}
func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return (nil as UICollectionViewCell?)!
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return _collectionView(collectionView, cellForItemAtIndexPath: indexPath)
}
func _collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return (nil as UICollectionReusableView?)!
}
public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return _collectionView(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath)
}
}
public class RxCollectionViewSectionedDataSource<S: SectionModelType> : _RxCollectionViewSectionedDataSource {
public typealias I = S.Item
public typealias Section = S
public typealias CellFactory = (UICollectionView, NSIndexPath, I) -> UICollectionViewCell
public typealias SupplementaryViewFactory = (UICollectionView, String, NSIndexPath) -> UICollectionReusableView
public typealias IncrementalUpdateObserver = ObserverOf<Changeset<S>>
public typealias IncrementalUpdateDisposeKey = Bag<IncrementalUpdateObserver>.KeyType
// This structure exists because model can be mutable
// In that case current state value should be preserved.
// The state that needs to be preserved is ordering of items in section
// and their relationship with section.
// If particular item is mutable, that is irrelevant for this logic to function
// properly.
public typealias SectionModelSnapshot = SectionModel<S, I>
var sectionModels: [SectionModelSnapshot] = []
public func sectionAtIndex(section: Int) -> S {
return self.sectionModels[section].model
}
public func itemAtIndexPath(indexPath: NSIndexPath) -> I {
return self.sectionModels[indexPath.section].items[indexPath.item]
}
var incrementalUpdateObservers: Bag<IncrementalUpdateObserver> = Bag()
public func setSections(sections: [S]) {
self.sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) }
}
public var cellFactory: CellFactory! = nil
public var supplementaryViewFactory: SupplementaryViewFactory
public override init() {
self.cellFactory = { _, _, _ in castOrFail(nil).get() }
self.supplementaryViewFactory = { _, _, _ in castOrFail(nil).get() }
super.init()
self.cellFactory = { [weak self] _ in
precondition(false, "There is a minor problem. `cellFactory` property on \(self!) was not set. Please set it manually, or use one of the `rx_subscribeTo` methods.")
return (nil as UICollectionViewCell!)!
}
self.supplementaryViewFactory = { [weak self] _, _, _ in
precondition(false, "There is a minor problem. `supplementaryViewFactory` property on \(self!) was not set.")
return (nil as UICollectionReusableView?)!
}
}
// observers
public func addIncrementalUpdatesObserver(observer: IncrementalUpdateObserver) -> IncrementalUpdateDisposeKey {
return incrementalUpdateObservers.put(observer)
}
public func removeIncrementalUpdatesObserver(key: IncrementalUpdateDisposeKey) {
let element = incrementalUpdateObservers.removeKey(key)
precondition(element != nil, "Element removal failed")
}
// UITableViewDataSource
override func _numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return sectionModels.count
}
override func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sectionModels[section].items.count
}
override func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
precondition(indexPath.item < sectionModels[indexPath.section].items.count)
return cellFactory(collectionView, indexPath, itemAtIndexPath(indexPath))
}
override func _collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return supplementaryViewFactory(collectionView, kind, indexPath)
}
}
|
mit
|
23054f07d72a17af1cc038e446b6d533
| 41.235294 | 181 | 0.717917 | 5.890256 | false | false | false | false |
minaatefmaf/Meme-Me
|
Meme Me/MemesTableViewController.swift
|
1
|
5684
|
//
// MemesTableViewController.swift
// Meme Me
//
// Created by Mina Atef on 5/25/15.
// Copyright (c) 2015 minaatefmaf. All rights reserved.
//
import UIKit
import CoreData
class MemesTableViewController: CoreDataTableViewController {
// The right bar buttons
private var addNewMemeButton: UIBarButtonItem!
private var editTableItemsButton: UIBarButtonItem!
// Set the core data stack variable
private let delegate = UIApplication.shared.delegate as! AppDelegate
private var coreDataStack: CoreDataStack!
override func viewDidLoad() {
super.viewDidLoad()
// Get the core data stack
coreDataStack = delegate.coreDataStack
// Add the right bar buttons
addNewMemeButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MemesTableViewController.navigateToMemeEditorView))
editTableItemsButton = self.editButtonItem // Returns a bar button item that toggles its title and associated state between Edit and Done
self.navigationItem.setRightBarButtonItems([addNewMemeButton, editTableItemsButton], animated: false)
// Create a fetchrequest
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Meme.Keys.EntityName)
// Sort the items by the meme creation date
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: coreDataStack.context,
sectionNameKeyPath: nil,
cacheName: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Switch to the meme creation scene if the table is empty
switchToMemeCreationIfEmptyResults()
// Save the current tab index to the user defaults
saveRootTabReference(currentTabIndex: 0)
// Configure the UI
configureUI()
}
// MARK: - UITableView Methods
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Get the meme
let meme = fetchedResultsController!.object(at: indexPath) as! Meme
// Create the cell
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
// Set the text
cell.labelTop.text = meme.topText
cell.labelBottom.text = meme.bottomText
// Set the date
let formatter = DateFormatter()
formatter.dateStyle = .medium
let dateString = formatter.string(from: meme.createdAt as! Date)
cell.dateLabel.text = dateString
// Set the image
cell.memedImageView.image = meme.getThumbnailImage()
// Add a little curvature to the image corners to make a rounded corners
cell.memedImageView.layer.cornerRadius = 8.0
cell.memedImageView.clipsToBounds = true
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
switch (editingStyle) {
case .delete:
if let context = fetchedResultsController?.managedObjectContext,
let memeToBeDeleted = fetchedResultsController?.object(at: indexPath as IndexPath) as? Meme {
context.delete(memeToBeDeleted)
}
// Persist the context to the disk
coreDataStack.save()
// Switch to the meme creation scene if the table is empty
switchToMemeCreationIfEmptyResults()
default:
break
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailController = self.storyboard!.instantiateViewController(withIdentifier: "MemesDetailViewController") as! MemesDetailViewController
// Set the meme
detailController.meme = fetchedResultsController!.object(at: indexPath) as! Meme
self.navigationController!.pushViewController(detailController, animated: true)
}
// MARK: - Helper Methods
// Navigate to the MemeEditor when needed
@objc private func navigateToMemeEditorView() {
var controller: MemeEditorViewController
controller = self.storyboard?.instantiateViewController(withIdentifier: "MemeEditorViewController") as! MemeEditorViewController
self.present(controller, animated: true, completion: nil)
}
private func switchToMemeCreationIfEmptyResults() {
// If there are no results for the fetch, navigate to the meme creation scene
if fetchedResultsController?.sections![0].numberOfObjects == 0 {
navigateToMemeEditorView()
}
}
private func saveRootTabReference(currentTabIndex: Int) {
let defaults = UserDefaults.standard
defaults.set(currentTabIndex, forKey: "rootTabReference")
}
// MARK: - UI Configurations
private func configureUI() {
// Show the navigation bar
navigationController?.navigationBar.isHidden = false
// Show the tab bar
self.tabBarController?.tabBar.isHidden = false
}
}
|
mit
|
6edefb4d1a53da6d04122e21a14f5261
| 37.147651 | 153 | 0.643033 | 5.927007 | false | false | false | false |
ta2yak/loqui
|
loqui/Models/AlertMessage.swift
|
1
|
561
|
//
// AlertMessage.swift
// loqui
//
// Created by Kawasaki Tatsuya on 2017/09/05.
// Copyright © 2017年 Kawasaki Tatsuya. All rights reserved.
//
class AlertMessage {
var title:String! = ""
var message:String! = ""
var isEmpty = true
required init(title:String, message:String) {
self.title = title
self.message = message
self.isEmpty = (title == "" && message == "") ? true : false
}
static func emptyObject() -> AlertMessage {
return AlertMessage(title: "", message: "")
}
}
|
mit
|
8d7de4754794001949e23e4bc453635e
| 21.32 | 68 | 0.584229 | 4.014388 | false | false | false | false |
daniel-barros/TV-Calendar
|
TV Calendar/CalendarSettingsManager.swift
|
1
|
37109
|
//
// CalendarSettingsManager.swift
// TV Calendar
//
// Created by Daniel Barros López on 2/7/17.
// Copyright © 2017 Daniel Barros. All rights reserved.
//
import ExtendedFoundation
import RealmSwift
/// A protocol that defines confirmation actions. An object conforming to this protocol is needed by `CalendarSettingsManager` in order to perform some settings updates.
///
/// The CalendarSettingsManager may provide some info about the consequences of performing an action, which might be useful for the confirmer to know (it can show this info to the user for example).
protocol CalendarSettingsUpdateConfirmer: class {
/// - parameter completion: A closure that takes two booleans: first one indicates the confirmation, the second one if existing events should not be deleted from the calendar (if the specified `UpdateActionType` is not `.deletion`, it won't have any effect).
func confirmSetCreateCalendarEvents(withConsequentActionType: CalendarSettingsManager.UpdateActionType,
numberOfAffectedEvents: Int?,
completion: @escaping (_ confirmed: Bool, _ keepingExistingEvents: Bool) -> ())
func confirmSetUseLocalCalendar(to newValue: Bool, completion: @escaping (_ confirmed: Bool) -> ())
func confirmSetEventsName(completion: @escaping (_ confirmed: Bool) -> ())
func confirmSetAlarm(completion: @escaping (_ confirmed: Bool) -> ())
/// - parameter completion: A closure that takes two booleans: first one indicates the confirmation, the second one if all shows should be reset to the default settings instead of just one.
func confirmResetToDefaultSettings(completion: @escaping (_ confirmed: Bool, _ resetAllShows: Bool) -> ())
func confirmSetCreateEventsForAllSeasons(to newValue: Bool, completion: @escaping (_ confirmed: Bool) -> ())
}
protocol CalendarSettingsUpdateResponder: class {
func didStartCalendarSettingsUpdate(settingsManager: CalendarSettingsManager)
func didFinishCalendarSettingsUpdate(result: BooleanResult<CalendarSettingsManager.UpdateError>, settingsManager: CalendarSettingsManager)
}
/// Manages the update and retrieval of settings related to calendar events, including default settings and show-specific settings.
///
/// It makes proper calendar changes related to settings updates via CalendarEventsManager. For this reason, you should use the CalendarSettingsManager instead of changing default or show-specific calendar settings directly.
/// - warning: Make sure that CalendarEventsManager has the proper authorization, otherwise you shouldn't use this.
/// - warning: Not thread-safe.
class CalendarSettingsManager {
enum UpdateActionType {
case addition, deletion
}
enum UpdateError: Error {
case calendarFailure, persistenceFailure, userCancellation
}
typealias CalendarUpdateCompletion = (BooleanResult<UpdateError>) -> ()
let trackRealm: Realm
let trackedShows: Results<Show>
let eventsManager: CalendarEventsManager
weak var delegate: (CalendarSettingsUpdateResponder & CalendarSettingsUpdateConfirmer)?
init(realm: Realm, trackedShows: Results<Show>, eventsManager: CalendarEventsManager) {
self.trackRealm = realm
self.trackedShows = trackedShows
self.eventsManager = eventsManager
}
/// Updates the `show`'s `setting` with `value`, and performs the `completion` closure with a `BooleanResult<UpdateError>` indicating if the update was successful and possible reasons for failure, also notifying its delegate with the same information.
///
/// If setting is `.eventsName` or `.useLocalCalendar` the default settings will be updated instead, since these can't be set for individual shows.
///
/// Changing the alarm types won't affect past events.
///
/// If set, the delegate might be asked to confirm the operation.
///
/// - warning: Make sure you pass a `value` with the correct type. Most settings take a `Bool`, except `.eventsName`, which takes a `EventTitleFormat` and `.setAlarms`, which takes a `AlarmSettings.NotAllDay` or `AlarmSettings.AllDay`.
func set(_ setting: CalendarSettings, to value: Any, for show: Show, completion: CalendarUpdateCompletion?) {
delegate?.didStartCalendarSettingsUpdate(settingsManager: self)
let fixedCompletion = completionAddingFinishDelegateCall(to: completion)
switch setting {
case .createCalendarEvents:
guard let value = assertedBool(value) else { fixedCompletion(.failure(nil)); return }
setCreateCalendarEvents(to: value, for: show, completion: fixedCompletion)
case .useNetworkAsLocation:
guard let value = assertedBool(value) else { fixedCompletion(.failure(nil)); return }
setUseNetworkAsLocation(to: value, for: show, completion: fixedCompletion)
case .createAllDayEvents:
guard let value = assertedBool(value) else { fixedCompletion(.failure(nil)); return }
setCreateAllDayEvents(to: value, for: show, completion: fixedCompletion)
case .useOriginalTimeZone:
guard let value = assertedBool(value) else { fixedCompletion(.failure(nil)); return }
setUseOriginalTimeZone(to: value, for: show, completion: fixedCompletion)
case .createEventsForAllSeasons:
guard let value = assertedBool(value) else { fixedCompletion(.failure(nil)); return }
setCreateEventsForAllSeasons(to: value, for: show, completion: fixedCompletion)
case .eventsName:
guard let value = assertedTitleFormat(value) else { fixedCompletion(.failure(nil)); return }
setEventsName(to: value, for: show, completion: fixedCompletion)
case .setAlarms:
if self.boolValue(of: .createAllDayEvents, for: show) {
guard let value = assertedAllDayAlarmType(value) else { fixedCompletion(.failure(nil)); return }
setAlarmForAllDayEvents(to: value, for: show, completion: fixedCompletion)
} else {
guard let value = assertedNotAllDayAlarmType(value) else { fixedCompletion(.failure(nil)); return }
setAlarmForNotAllDayEvents(to: value, for: show, completion: fixedCompletion)
}
}
}
/// Returns the value of the setting for the specified show if exists, otherwise the default settings value.
/// The returned value will be of type `Bool`, , except `.eventsName`, which returns a `EventTitleFormat` and `.setAlarms`, which returns a `AlarmSettings.NotAllDay` or `AlarmSettings.AllDay`.
///
/// It is safer and more convenient to use `boolValue(of:for:)`, `alarmType(for:)` or `eventTitleFormat(for:)`.
func value(of setting: CalendarSettings, for show: Show) -> Any {
return CalendarSettingsManager.value(of: setting, for: show)
}
/// Returns the value of the setting for the specified show if exists, otherwise the default settings value.
/// - warning: The behavior when passing `.eventsName` or `.setAlarms` is not defined. Use `alarmType(for:)` and `eventTitleFormat(for:)` for those instead.
func boolValue(of setting: CalendarSettings, for show: Show) -> Bool {
return CalendarSettingsManager.boolValue(of: setting, for: show)
}
/// Returns the value of the setting for the specified show if exists, otherwise the default settings value.
func alarmType(for show: Show) -> AlarmType {
return CalendarSettingsManager.alarmType(for: show)
}
/// Returns the value of the setting for the specified show if exists, otherwise the default settings value.
func eventTitleFormat(for show: Show) -> EventTitleFormat {
return CalendarSettingsManager.eventTitleFormat(for: show)
}
/// Returns the value of the setting for the specified show if exists, otherwise the default settings value.
/// The returned value will be of type `Bool`, , except `.eventsName`, which returns a `EventTitleFormat` and `.setAlarms`, which returns a `AlarmSettings.NotAllDay` or `AlarmSettings.AllDay`.
///
/// It is safer and more convenient to use `boolValue(of:for:)`, `alarmType(for:)` or `eventTitleFormat(for:)`.
static func value(of setting: CalendarSettings, for show: Show) -> Any {
switch setting {
case .createCalendarEvents:
return show.createsCalendarEvents.value ?? DefaultSettings.createsCalendarEvents
case .eventsName:
let seasonType = DefaultSettings.TitleFormat.seasonType
let episodeNumberType = DefaultSettings.TitleFormat.episodeNumberType
let episodeTitleType = DefaultSettings.TitleFormat.episodeTitleType
return (seasonType, episodeNumberType, episodeTitleType)
case .useNetworkAsLocation:
return show.usesNetworkAsLocation.value ?? DefaultSettings.usesNetworkAsLocation
case .setAlarms:
if show.createsAllDayEvents.value ?? DefaultSettings.createsAllDayEvents {
return CalendarSettings.AlarmSettings.AllDay(rawValue: show.alarmForAllDayEvents.value ?? -1)
?? DefaultSettings.Alarm.allDayEvents
} else {
return CalendarSettings.AlarmSettings.NotAllDay(rawValue: show.alarmForNotAllDayEvents.value ?? -1)
?? DefaultSettings.Alarm.notAllDayEvents
}
case .createAllDayEvents:
return show.createsAllDayEvents.value ?? DefaultSettings.createsAllDayEvents
case .useOriginalTimeZone:
return show.usesOriginalTimeZone.value ?? DefaultSettings.usesOriginalTimeZone
case .createEventsForAllSeasons:
return show.createsEventsForAllSeasons.value ?? DefaultSettings.createsEventsForAllSeasons
}
}
/// Returns the value of the setting for the specified show if exists, otherwise the default settings value.
/// - warning: The behavior when passing `.eventsName` or `.setAlarms` is not defined. Use `alarmType(for:)` and `eventTitleFormat(for:)` for those instead.
static func boolValue(of setting: CalendarSettings, for show: Show) -> Bool {
return value(of: setting, for: show) as? Bool ?? false
}
/// Returns the value of the setting for the specified show if exists, otherwise the default settings value.
static func alarmType(for show: Show) -> AlarmType {
return value(of: .setAlarms, for: show) as! AlarmType
}
/// Returns the value of the setting for the specified show if exists, otherwise the default settings value.
static func eventTitleFormat(for show: Show) -> EventTitleFormat {
return value(of: .eventsName, for: show) as! EventTitleFormat
}
/// Resets the show's settings to the default (setting all the show's specific settings values to nil).
///
/// The delegate will be given the option to apply this to all shows instead of this single one, making all shows use the default settings.
func resetShowToDefaultSettings(_ show: Show, completion: CalendarUpdateCompletion?) {
delegate?.didStartCalendarSettingsUpdate(settingsManager: self)
let fixedCompletion = completionAddingFinishDelegateCall(to: completion)
resetToDefaultSettings(show, completion: fixedCompletion)
}
/// Updates the default settings with the specific setting of the show. It does not update the `createsCalendarEvents` setting (See `disableCalendarEventsForAllShows()` and `enableCalendarEventsForAllShows()` for that).
///
/// The delegate will be asked to confirm updates that have major effects on calendar events.
func setDefaultSettings(usingSettingsOf show: Show, completion: CalendarUpdateCompletion?) {
delegate?.didStartCalendarSettingsUpdate(settingsManager: self)
let fixedCompletion = completionAddingFinishDelegateCall(to: completion)
// Update defaults
setAllDefaultSettingsExceptCreateCalendarEvents(usingSettingsOf: show)
{ result in
// Set the show to use the defaults
if result.isSuccessful {
_ = show.realmSafeUpdate {
show.usesNetworkAsLocation.value = nil
show.usesOriginalTimeZone.value = nil
show.createsAllDayEvents.value = nil
show.createsEventsForAllSeasons.value = nil
show.alarmForAllDayEvents.value = nil
show.alarmForNotAllDayEvents.value = nil
}
}
fixedCompletion(result)
}
}
/// Sets the default setting for `createCalendarEvents` to `false` and resets this setting for all the shows, making the proper calendar updates via `CalendarEventsManager`.
///
/// The delegate will be asked to confirm the action and given a chance to keep existing events in calendar.
func disableCalendarEventsForAllShows(completion: CalendarUpdateCompletion?) {
delegate?.didStartCalendarSettingsUpdate(settingsManager: self)
let fixedCompletion = completionAddingFinishDelegateCall(to: completion)
setDefaultCreateCalendarEventsAndResetAllShows(to: false, completion: fixedCompletion)
}
/// Sets the default setting for `createCalendarEvents` to `true` and resets this setting for all the shows, making the proper calendar updates via `CalendarEventsManager`.
///
/// The delegate will be asked to confirm the action.
func enableCalendarEventsForAllShows(completion: CalendarUpdateCompletion?) {
delegate?.didStartCalendarSettingsUpdate(settingsManager: self)
let fixedCompletion = completionAddingFinishDelegateCall(to: completion)
setDefaultCreateCalendarEventsAndResetAllShows(to: true, completion: fixedCompletion)
}
/// `true` if the show does not have any show-specific settings but uses the defaults.
/// - warning: Do not confuse with `showHasSameSettingsAsDefault(_:)`.
func showHasDefaultSettings(_ show: Show) -> Bool {
return CalendarSettingsManager.showHasDefaultSettings(show)
}
/// `true` if the show does not have show-specific settings or if its settings match the default settings.
/// - warning: Do not confuse with `showHasDefaultSettings(_:)`.
func showHasSameSettingsAsDefault(_ show: Show) -> Bool {
return CalendarSettingsManager.showHasSameSettingsAsDefault(show)
}
/// `true` if the show does not have any show-specific settings but uses the defaults.
/// - warning: Do not confuse with `showHasSameSettingsAsDefault(_:)`.
static func showHasDefaultSettings(_ show: Show) -> Bool {
return show.usesNetworkAsLocation.value == nil
&& show.usesOriginalTimeZone.value == nil
&& show.createsAllDayEvents.value == nil
&& show.createsEventsForAllSeasons.value == nil
&& (boolValue(of: .createAllDayEvents, for: show) ?
show.alarmForAllDayEvents.value == nil : show.alarmForNotAllDayEvents.value == nil)
}
/// `true` if the show does not have show-specific settings or if its settings match the default settings.
/// - warning: Do not confuse with `showHasDefaultSettings(_:)`.
static func showHasSameSettingsAsDefault(_ show: Show) -> Bool {
return showHasDefaultSettings(show) ||
DefaultSettings.usesNetworkAsLocation == boolValue(of: .useNetworkAsLocation, for: show)
&& DefaultSettings.usesOriginalTimeZone == boolValue(of: .useOriginalTimeZone, for: show)
&& DefaultSettings.createsAllDayEvents == boolValue(of: .createAllDayEvents, for: show)
&& DefaultSettings.createsEventsForAllSeasons == boolValue(of: .createEventsForAllSeasons, for: show)
&& (boolValue(of: .createAllDayEvents, for: show) ?
DefaultSettings.Alarm.allDayEvents.rawValue :
DefaultSettings.Alarm.notAllDayEvents.rawValue) == alarmType(for: show).rawValue
}
var isCreateCalendarEventsDefaultAndEnabledForAllShows: Bool {
if !DefaultSettings.createsCalendarEvents {
return false
}
for show in trackedShows {
if show.createsCalendarEvents.value == false {
return false
}
}
return true
}
}
// MARK: Checking settings types
fileprivate extension CalendarSettingsManager {
/// Tries to cast a `value` as a Bool. If successful it returns it, otherwise it causes an assertion failure and returns nil.
func assertedBool(_ value: Any) -> Bool? {
return assertedType(value)
}
/// Tries to cast a `value` as a `EventTitleFormat`. If successful it returns it, otherwise it causes an assertion failure and returns nil.
func assertedTitleFormat(_ value: Any) -> EventTitleFormat? {
return assertedType(value)
}
/// Tries to cast a `value` as a `CalendarSettings.AlarmSettings.AllDay`. If successful it returns it, otherwise it causes an assertion failure and returns nil.
func assertedAllDayAlarmType(_ value: Any) -> CalendarSettings.AlarmSettings.AllDay? {
return assertedType(value)
}
/// Tries to cast a `value` as a `CalendarSettings.AlarmSettings.NotAllDay`. If successful it returns it, otherwise it causes an assertion failure and returns nil.
func assertedNotAllDayAlarmType(_ value: Any) -> CalendarSettings.AlarmSettings.NotAllDay? {
return assertedType(value)
}
private func assertedType<T>(_ value: Any) -> T? {
if let value = value as? T {
return value
} else {
assertionFailure("Wrong value type for the setting")
return nil
}
}
}
// MARK: Default settings updates
fileprivate extension CalendarSettingsManager {
/// Sets a new value for createCalendarEvents default setting and removes and show-specific value for this setting.
func setDefaultCreateCalendarEventsAndResetAllShows(to newValue: Bool, completion: CalendarUpdateCompletion?) {
func makeUpdates(confirmed: Bool, keepingExistingEvents: Bool) {
guard confirmed else {
completion?(.failure(.userCancellation)); return
}
// Update setting
DefaultSettings.createsCalendarEvents = newValue
let success = trackRealm.safeUpdate {
for show in trackedShows {
show.createsCalendarEvents.value = nil
}
}
// Make calendar updates
if success {
do {
if newValue {
for show in trackedShows {
try eventsManager.updateEvents(for: show)
}
}
else if !keepingExistingEvents {
try eventsManager.removeShowsCalendar()
}
completion?(.success)
} catch {
completion?(.failure(.calendarFailure))
}
} else { completion?(.failure(.persistenceFailure)) }
}
// Ask delegate to confirm, or just go ahead
let numberOfEvents = newValue ? nil : eventsManager.totalNumberOfEvents()
if let delegate = delegate {
delegate.confirmSetCreateCalendarEvents(withConsequentActionType: newValue ? .addition : .deletion,
numberOfAffectedEvents: numberOfEvents,
completion: makeUpdates)
} else {
makeUpdates(confirmed: true, keepingExistingEvents: false)
}
}
func setEventsName(to newValue: EventTitleFormat, for show: Show, completion: CalendarUpdateCompletion?) {
func makeUpdates(confirmed: Bool) {
guard confirmed else {
completion?(.failure(.userCancellation)); return
}
// Update settings
DefaultSettings.TitleFormat.seasonType = newValue.0
DefaultSettings.TitleFormat.episodeNumberType = newValue.1
DefaultSettings.TitleFormat.episodeTitleType = newValue.2
// Make calendar updates
do {
// TODO: Create a new func in CalendarEventsManager updateAllExistingEvents() and use it here?
for show in trackedShows where self.boolValue(of: .createCalendarEvents, for: show) {
try eventsManager.updateEvents(for: show, allEvents: true, onlyExisting: true, forcingUpdate: true)
}
completion?(.success)
} catch {
completion?(.failure(.calendarFailure))
}
}
// Ask delegate to confirm, or just go ahead
if let delegate = delegate {
delegate.confirmSetEventsName(completion: makeUpdates)
} else {
makeUpdates(confirmed: true)
}
}
/// Updates the default settings with the specific setting of the show. It does not update the `createsCalendarEvents`. It updates calendar events for all shows which depended on the default settings affected.
func setAllDefaultSettingsExceptCreateCalendarEvents(usingSettingsOf show: Show, completion: CalendarUpdateCompletion?) {
// Assess changes
let alarmChange: Bool
if boolValue(of: .createAllDayEvents, for: show),
let showAlarmValue = show.alarmForAllDayEvents.value {
alarmChange = DefaultSettings.Alarm.allDayEvents.rawValue != showAlarmValue
} else if !boolValue(of: .createAllDayEvents, for: show),
let showAlarmValue = show.alarmForNotAllDayEvents.value {
alarmChange = DefaultSettings.Alarm.notAllDayEvents.rawValue != showAlarmValue
} else {
alarmChange = false
}
let eventForAllSeasonsChange = DefaultSettings.createsEventsForAllSeasons != boolValue(of: .createEventsForAllSeasons, for: show)
let networkAsLocationChange = DefaultSettings.usesNetworkAsLocation != boolValue(of: .useNetworkAsLocation, for: show)
let originalTimeZoneChange = DefaultSettings.usesOriginalTimeZone != boolValue(of: .useOriginalTimeZone, for: show)
let allDayEventsChange = DefaultSettings.createsAllDayEvents != boolValue(of: .createAllDayEvents, for: show)
// The updates
func makeUpdates(confirmed: Bool) {
guard confirmed else {
completion?(.failure(.userCancellation)); return
}
// Update default settings
DefaultSettings.usesNetworkAsLocation =? show.usesNetworkAsLocation.value
DefaultSettings.usesOriginalTimeZone =? show.usesOriginalTimeZone.value
DefaultSettings.createsAllDayEvents =? show.createsAllDayEvents.value
DefaultSettings.createsEventsForAllSeasons =? show.createsEventsForAllSeasons.value
if boolValue(of: .createAllDayEvents, for: show),
let showAlarmValue = show.alarmForAllDayEvents.value {
DefaultSettings.Alarm.allDayEvents =? CalendarSettings.AlarmSettings.AllDay(rawValue: showAlarmValue)
} else if !boolValue(of: .createAllDayEvents, for: show),
let showAlarmValue = show.alarmForNotAllDayEvents.value {
DefaultSettings.Alarm.notAllDayEvents =? CalendarSettings.AlarmSettings.NotAllDay(rawValue: showAlarmValue)
}
// Make calendar updates
do {
for trackedShow in trackedShows where boolValue(of: .createCalendarEvents, for: show) {
// Only alarm or all seasons changed, need to force update if trackedShow uses default settings for alarm or all seasons
if !(networkAsLocationChange || originalTimeZoneChange || allDayEventsChange) {
if (alarmChange && (trackedShow.alarmForAllDayEvents.value == nil || trackedShow.alarmForNotAllDayEvents.value == nil))
|| (eventForAllSeasonsChange && trackedShow.createsEventsForAllSeasons.value == nil) {
try eventsManager.updateEvents(for: trackedShow, forcingUpdate: true)
}
}
else {
// For other changes, need to force update of all existing episodes (you want to make these changes to all events, but not create events for all seasons if that's not the setting)
if (networkAsLocationChange && trackedShow.usesNetworkAsLocation.value == nil)
|| (originalTimeZoneChange && trackedShow.usesOriginalTimeZone.value == nil)
|| (allDayEventsChange && trackedShow.createsAllDayEvents.value == nil)
|| alarmChange && (trackedShow.alarmForAllDayEvents.value == nil || trackedShow.alarmForNotAllDayEvents.value == nil) {
// If all-day events changes we need to remove custom alarm types
if allDayEventsChange && trackedShow.createsAllDayEvents.value == nil {
let success = trackedShow.realmSafeUpdate {
trackedShow.alarmForAllDayEvents.value = nil
trackedShow.alarmForNotAllDayEvents.value = nil
}
if !success { } // Not important enough to stop the process or send an error
}
try eventsManager.updateEvents(for: trackedShow, allEvents: true, onlyExisting: true, forcingUpdate: true)
}
// After that, need to force update if all seasons changed, since this requires creating NEW events (alarms are already updated before to avoid inconsistencies (they would have been updated anyway for a show with other changes plus default setting for alarm, so we just update them all))
if eventForAllSeasonsChange && trackedShow.createsEventsForAllSeasons.value == nil {
try eventsManager.updateEvents(for: trackedShow)
}
}
}
completion?(.success)
} catch {
completion?(.failure(.calendarFailure))
}
}
// We ask to confirm only if alarm settings will change
// We could ask confirmation for setting events for all seasons too, but right now it shows only an explanation of its effects, which the user will be familiar with by now.
if alarmChange, let delegate = delegate {
delegate.confirmSetAlarm(completion: makeUpdates)
} else {
makeUpdates(confirmed: true)
}
}
/// The delegate will be given the option to reset the settings of all shows instead of a single one.
func resetToDefaultSettings(_ show: Show, completion: CalendarUpdateCompletion?) {
func makeUpdates(confirmed: Bool, resetAllShows: Bool) {
guard confirmed else {
completion?(.failure(.userCancellation)); return
}
// Update settings
let success: Bool
if resetAllShows {
success = trackRealm.safeUpdate {
for show in trackedShows {
show.usesNetworkAsLocation.value = nil
show.usesOriginalTimeZone.value = nil
show.createsAllDayEvents.value = nil
show.createsEventsForAllSeasons.value = nil
show.alarmForAllDayEvents.value = nil
show.alarmForNotAllDayEvents.value = nil
}
}
} else {
success = show.realmSafeUpdate {
show.usesNetworkAsLocation.value = nil
show.usesOriginalTimeZone.value = nil
show.createsAllDayEvents.value = nil
show.createsEventsForAllSeasons.value = nil
show.alarmForAllDayEvents.value = nil
show.alarmForNotAllDayEvents.value = nil
}
}
if !success {
completion?(.failure(.persistenceFailure))
return
}
// Make calendar updates
do {
// (This is a hard reset, it probably can be more efficient)
if resetAllShows {
for show in trackedShows where self.boolValue(of: .createCalendarEvents, for: show) {
try eventsManager.updateEvents(for: show, allEvents: true, onlyExisting: true, forcingUpdate: true)
try eventsManager.updateEvents(for: show)
}
} else {
try eventsManager.updateEvents(for: show, allEvents: true, onlyExisting: true, forcingUpdate: true)
try eventsManager.updateEvents(for: show)
}
completion?(.success)
} catch {
completion?(.failure(.calendarFailure))
}
}
// Ask delegate to confirm, or just go ahead
if let delegate = delegate {
delegate.confirmResetToDefaultSettings(completion: makeUpdates)
} else {
makeUpdates(confirmed: true, resetAllShows: false)
}
}
}
// MARK: Show-specific settings updates
fileprivate extension CalendarSettingsManager {
func setCreateCalendarEvents(to newValue: Bool, for show: Show, completion: CalendarUpdateCompletion?) {
func makeUpdates(confirmed: Bool, keepingExistingEvents: Bool) {
guard confirmed else {
completion?(.failure(.userCancellation)); return
}
// Update setting
let success = show.realmSafeUpdate {
show.createsCalendarEvents.value = newValue
}
// Make calendar updates
if success {
if newValue {
forceUpdateOfEvents(for: show, completion: completion)
} else {
if !keepingExistingEvents {
do { try eventsManager.removeEvents(for: show) }
catch { completion?(.failure(.calendarFailure)) }
}
completion?(.success)
}
} else { completion?(.failure(.persistenceFailure)) }
}
// If setting to false confirm before updating
if !newValue, let delegate = delegate {
delegate.confirmSetCreateCalendarEvents(withConsequentActionType: .deletion,
numberOfAffectedEvents: CalendarEventsManager.numberOfEvents(for: show),
completion: makeUpdates)
}
// Otherwise create events without confirmation
else {
makeUpdates(confirmed: true, keepingExistingEvents: true)
}
}
func setUseNetworkAsLocation(to newValue: Bool, for show: Show, completion: CalendarUpdateCompletion?) {
// Update setting
let success = show.realmSafeUpdate {
show.usesNetworkAsLocation.value = newValue
}
// Make calendar updates
if success { forceUpdateOfAllExistingEvents(for: show, completion: completion) }
else { completion?(.failure(.persistenceFailure)) }
}
/// Sets the `createsAllDayEvents` and removes custom alarm type for all-day or not-all-day events, depending on the new value.
func setCreateAllDayEvents(to newValue: Bool, for show: Show, completion: CalendarUpdateCompletion?) {
// Update setting
let success = show.realmSafeUpdate {
show.createsAllDayEvents.value = newValue
if newValue {
show.alarmForNotAllDayEvents.value = nil
} else {
show.alarmForAllDayEvents.value = nil
}
}
// Make calendar updates
if success { forceUpdateOfAllExistingEvents(for: show, completion: completion) }
else { completion?(.failure(.persistenceFailure)) }
}
func setUseOriginalTimeZone(to newValue: Bool, for show: Show, completion: CalendarUpdateCompletion?) {
// Update setting
let success = show.realmSafeUpdate {
show.usesOriginalTimeZone.value = newValue
}
// Make calendar updates
if success { forceUpdateOfAllExistingEvents(for: show, completion: completion) }
else { completion?(.failure(.persistenceFailure)) }
}
func setCreateEventsForAllSeasons(to newValue: Bool, for show: Show, completion: CalendarUpdateCompletion?) {
func makeUpdates(confirmed: Bool) {
guard confirmed else {
completion?(.failure(.userCancellation)); return
}
// Update setting
let success = show.realmSafeUpdate {
show.createsEventsForAllSeasons.value = newValue
}
// Make calendar updates
if success {
if newValue { self.forceUpdateOfEvents(for: show, completion: completion) }
else { completion?(.success) } // If newValue is false, existing events for previous seasons are kept anyway
} else { completion?(.failure(.persistenceFailure)) }
}
// Ask delegate to confirm, or just go ahead
if let delegate = delegate {
delegate.confirmSetCreateEventsForAllSeasons(to: newValue, completion: makeUpdates)
} else {
makeUpdates(confirmed: true)
}
}
func setAlarmForAllDayEvents(to newValue: CalendarSettings.AlarmSettings.AllDay, for show: Show, completion: CalendarUpdateCompletion?) {
func makeUpdates(confirmed: Bool) {
guard confirmed else {
completion?(.failure(.userCancellation)); return
}
// Update setting
let success = show.realmSafeUpdate {
show.alarmForAllDayEvents.value = newValue.rawValue
}
// Make calendar updates
if success { self.forceUpdateOfEvents(for: show, completion: completion) }
else { completion?(.failure(.persistenceFailure)) }
}
// Ask delegate to confirm, or just go ahead
if let delegate = delegate {
delegate.confirmSetAlarm(completion: makeUpdates)
} else {
makeUpdates(confirmed: true)
}
}
func setAlarmForNotAllDayEvents(to newValue: CalendarSettings.AlarmSettings.NotAllDay, for show: Show, completion: CalendarUpdateCompletion?) {
func makeUpdates(confirmed: Bool) {
guard confirmed else {
completion?(.failure(.userCancellation)); return
}
// Update setting
let success = show.realmSafeUpdate {
show.alarmForNotAllDayEvents.value = newValue.rawValue
}
// Make calendar updates
if success { self.forceUpdateOfEvents(for: show, completion: completion) }
else { completion?(.failure(.persistenceFailure)) }
}
// Ask delegate to confirm, or just go ahead
if let delegate = delegate {
delegate.confirmSetAlarm(completion: makeUpdates)
} else {
makeUpdates(confirmed: true)
}
}
}
// MARK: Helpers
fileprivate extension CalendarSettingsManager {
func completionAddingFinishDelegateCall(to completion: CalendarUpdateCompletion?) -> CalendarUpdateCompletion {
return { result in
self.delegate?.didFinishCalendarSettingsUpdate(result: result, settingsManager: self)
completion?(result)
}
}
func forceUpdateOfEvents(for show: Show, completion: CalendarUpdateCompletion?) {
do {
try eventsManager.updateEvents(for: show, forcingUpdate: true)
completion?(.success)
} catch {
completion?(.failure(.calendarFailure))
}
}
func forceUpdateOfAllExistingEvents<T>(for shows: T, completion: CalendarUpdateCompletion?) where T: Sequence, T.Iterator.Element == Show {
}
func forceUpdateOfAllExistingEvents(for show: Show, completion: CalendarUpdateCompletion?) {
do {
try eventsManager.updateEvents(for: show, allEvents: true, onlyExisting: true, forcingUpdate: true)
completion?(.success)
} catch {
completion?(.failure(.calendarFailure))
}
}
}
|
gpl-3.0
|
a49b57928d5b893523dc188b9708199e
| 51.783784 | 311 | 0.644245 | 5.234448 | false | false | false | false |
ravirani/algorithms
|
Sorting/QuickSort.swift
|
1
|
1473
|
//
// QuickSort.swift
//
// Pick a pivot (there are variety of ways with pros/cons and some might be
// suitable over others if the incoming data is constrained or behavior is known
// but we take the last element as pivot below for simplicity)
// and move all lower values to left and higher values to right. Then recursively
// do the above for left sub-array minus the pivot and right sub-array minus the pivot.
//
//
import Foundation
func quickSort(_ inputArray: inout [Int], lowerIndex: Int, upperIndex: Int) {
guard lowerIndex < upperIndex && lowerIndex >= 0 else {
return
}
let pivot = inputArray[upperIndex]
var newIndexForPivot = 0
for index in 0..<upperIndex {
if inputArray[index] < pivot {
if newIndexForPivot != index {
swap(&inputArray[newIndexForPivot], &inputArray[index])
}
newIndexForPivot += 1
}
}
if upperIndex != newIndexForPivot {
swap(&inputArray[upperIndex], &inputArray[newIndexForPivot])
}
quickSort(&inputArray, lowerIndex: lowerIndex, upperIndex: newIndexForPivot - 1)
quickSort(&inputArray, lowerIndex: newIndexForPivot + 1, upperIndex: upperIndex)
}
// Base case
var arr = [4, 8, 1, 10, 9, 38, 48]
quickSort(&arr, lowerIndex: 0, upperIndex: arr.count - 1)
assert(arr == [1, 4, 8, 9, 10, 38, 48])
// Case where array consists of only two elements
var arr1 = [14, 8]
quickSort(&arr1, lowerIndex: 0, upperIndex: arr1.count - 1)
assert(arr1 == [8, 14])
|
mit
|
d32847542def2db2545e615a7aed9863
| 29.6875 | 88 | 0.686354 | 3.738579 | false | false | false | false |
creatubbles/ctb-api-swift
|
CreatubblesAPIClient/Sources/DAO/BatchFetch/Galleries/FavoriteGalleriesBatchFetchOperation.swift
|
1
|
2237
|
//
// FavoriteGalleriesBatchFetchOperation.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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.
//
class FavoriteGalleriesBatchFetchOperation: ConcurrentOperation {
private let requestSender: RequestSender
let pagingData: PagingData
private(set) var galleries: Array<Gallery>?
private var requestHandler: RequestHandler?
init(requestSender: RequestSender, pagingData: PagingData, complete: OperationCompleteClosure?) {
self.requestSender = requestSender
self.pagingData = pagingData
super.init(complete: complete)
}
override func main() {
guard isCancelled == false else { return }
let request = FavoriteGalleriesRequest(page: pagingData.page, perPage: pagingData.pageSize)
let handler = GalleriesResponseHandler {
[weak self](galleries, _, error) -> (Void) in
self?.galleries = galleries
self?.finish(error)
}
requestHandler = requestSender.send(request, withResponseHandler: handler)
}
override func cancel() {
requestHandler?.cancel()
super.cancel()
}
}
|
mit
|
bdc9c4adc0affd8dfa5516009c223804
| 38.946429 | 101 | 0.717926 | 4.650728 | false | false | false | false |
hw3308/SwiftBase3.0-EN
|
Swift3Basics/Category/Notifications.swift
|
1
|
1639
|
//
// Notifications.swift
// SwiftBasics
//
// Created by 侯伟 on 17/1/11.
// Copyright © 2017年 侯伟. All rights reserved.
//
import Foundation
public struct Notifications {
public static let notificationCenter = NotificationCenter.default
public static let reachabilityChanged = Proxy(name: "ReachabilityChanged")
open class Proxy {
fileprivate let name: String
public init(name: String) {
self.name = name
}
open func post(_ object: AnyObject? = nil, userInfo: [String: AnyObject]? = nil) {
Log.info("@N>\(name) object=\(String(describing: object)) userInfo=\(String(describing: userInfo))")
async {
notificationCenter.post(name: Notification.Name(rawValue: self.name), object: object, userInfo: userInfo)
}
}
open func addObserver(_ observer: AnyObject, selector: Selector, sender object: AnyObject? = nil) {
Log.info("@N+\(name) \(selector)@\(observer)")
notificationCenter.addObserver(observer, selector: selector, name: NSNotification.Name(rawValue: name), object: object)
}
open func removeObserver(_ observer: AnyObject, sender object: AnyObject? = nil) {
Log.info("@N-\(name) \(observer)")
notificationCenter.removeObserver(observer, name: NSNotification.Name(rawValue: name), object: object)
}
}
public static func removeAll(forObserver observer: AnyObject) {
Log.info("@N#\(observer)")
notificationCenter.removeObserver(observer)
}
}
|
mit
|
5f399a1179e23ddb4abc9f7bc1bdfa94
| 34.391304 | 131 | 0.621007 | 4.774194 | false | false | false | false |
abellono/IssueReporter
|
IssueReporter/Core/Extensions/UIBarButtonItem+CustomBarButton.swift
|
1
|
1332
|
//
// UIBarButtonItem+CustomBarButton.swift
// IssueReporter
//
// Created by Hakon Hanesand on 10/6/16.
// Copyright © 2017 abello. All rights reserved.
//
//
import Foundation
import UIKit
internal extension UIBarButtonItem {
private static let kABECloseButtonImage = "close"
private static let kABESaveButtonImage = "save"
static func backButton(_ target: AnyObject, action: Selector, color: UIColor) -> UIBarButtonItem {
let cocoapodsBundle = Bundle.bundleForLibrary()
let image = UIImage(named: UIBarButtonItem.kABECloseButtonImage, in: cocoapodsBundle, compatibleWith: nil)
let button = UIBarButtonItem(image: image, style: .plain, target: target, action: action)
button.tintColor = color
return button
}
static func saveButton(_ target: AnyObject, action: Selector) -> UIBarButtonItem {
let cocoapodsBundle = Bundle.bundleForLibrary()
let image = UIImage(named: UIBarButtonItem.kABESaveButtonImage, in: cocoapodsBundle, compatibleWith: nil)
let button = UIBarButtonItem(image: image, style: .plain, target: target, action: action)
button.imageInsets = UIEdgeInsets(top: 3, left: -6, bottom: 0, right: 0)
button.tintColor = UIColor.white
return button
}
}
|
mit
|
42826ea522d0608ff9bb473f46f8b69e
| 34.026316 | 114 | 0.681443 | 4.589655 | false | false | false | false |
love-everyday/ExCommentPugin
|
ExtComment/ExtCommentCommand.swift
|
1
|
3483
|
// extCommentCommand.swift
// ExtXcode8
//
import Foundation
import XcodeKit
class ExtCommentCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void) {
var lines = invocation.buffer.lines
let selections = invocation.buffer.selections
for selection in selections {
if let textRange = selection as? XCSourceTextRange, textRange.start.line != lines.count {
if textRange.start.line == textRange.end.line {
let lineIndex = textRange.start.line
let line = lines[lineIndex] as! String
lines.replaceObject(at: lineIndex, with: select(aLine: line))
}else {
lines = select(lines: lines, inRange: textRange.start.line...textRange.end.line)
}
}
}
completionHandler(nil)
}
/// 选中了多行要注释的字符串
///
/// - parameter lines: 多行字符串范围
/// - parameter inRange: 要注释的字符串所在的数组
///
/// - returns: 注释后的字符串所在的数组
func select(lines:NSMutableArray, inRange range:ClosedRange<Int>) -> NSMutableArray {
var line: String
var lineCount = 0
let doubleCommentStr = "//"
for lineIndex in range.lowerBound...range.upperBound {
line = lines[lineIndex] as! String
if line.hasPrefix(doubleCommentStr) {
lineCount += 1
}
}
let maxCount = range.upperBound - range.lowerBound + 1
for lineIndex in range.lowerBound...range.upperBound {
line = lines[lineIndex] as! String
if lineCount == maxCount {
line.removeSubrange(doubleCommentStr.startIndex...doubleCommentStr.endIndex)
}else {
line = doubleCommentStr + line
}
lines.replaceObject(at: lineIndex, with: line)
}
return lines
}
/// 选中了一行要注释的字符串
///
/// - parameter aLine: 要注释的字符串
///
/// - returns: 注释后的字符串
func select(aLine string:String) -> String {
var line = string
let doubleCommentStr = "//"
let newLineStr: Character = "\n"
let commentStr: Character = "/"
let spaceStr: Character = " "
var charIndex = line.startIndex
while line[charIndex] == spaceStr {
charIndex = line.index(after: charIndex)
}
let currentChar = line[charIndex]
if currentChar == newLineStr {
line = doubleCommentStr + line
}else {
let nextChar = line[line.index(after: charIndex)]
if currentChar == commentStr, nextChar == commentStr {
line.removeSubrange(charIndex...line.index(after: charIndex))
}else if currentChar == commentStr, nextChar != commentStr {
if charIndex == line.startIndex {
line.insert(commentStr, at: charIndex)
}else {
line.replaceSubrange(line.index(before: charIndex)...charIndex, with: doubleCommentStr)
}
}else {
line = doubleCommentStr + line
}
}
return line
}
}
|
mit
|
93abe4ef28dbb85d93956b03dbff0b5d
| 26.644628 | 115 | 0.554858 | 4.883212 | false | false | false | false |
zhubofei/IGListKit
|
Examples/Examples-macOS/IGListKitExamples/Models/User.swift
|
4
|
1212
|
/**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
final class User: ListDiffable {
let pk: Int
let name: String
init(pk: Int, name: String) {
self.pk = pk
self.name = name
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
return pk as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
guard self !== object else { return true }
guard let object = object as? User else { return false }
return name == object.name
}
}
|
mit
|
de7bbf7712ec597a69ddbd25a262230a
| 29.3 | 80 | 0.707096 | 4.752941 | false | false | false | false |
thierrybucco/Eureka
|
Source/Rows/SwitchRow.swift
|
7
|
2644
|
// SwitchRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: SwitchCell
open class SwitchCell: Cell<Bool>, CellType {
@IBOutlet public weak var switchControl: UISwitch!
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let switchC = UISwitch()
switchControl = switchC
accessoryView = switchControl
editingAccessoryView = accessoryView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func setup() {
super.setup()
selectionStyle = .none
switchControl.addTarget(self, action: #selector(SwitchCell.valueChanged), for: .valueChanged)
}
deinit {
switchControl?.removeTarget(self, action: nil, for: .allEvents)
}
open override func update() {
super.update()
switchControl.isOn = row.value ?? false
switchControl.isEnabled = !row.isDisabled
}
func valueChanged() {
row.value = switchControl?.isOn ?? false
}
}
// MARK: SwitchRow
open class _SwitchRow: Row<SwitchCell> {
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
}
/// Boolean row that has a UISwitch as accessoryType
public final class SwitchRow: _SwitchRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
|
mit
|
f10826a7eb2f42eca5822b4415882329
| 32.05 | 101 | 0.698941 | 4.574394 | false | false | false | false |
STShenZhaoliang/STWeiBo
|
STWeiBo/STWeiBo/Classes/Home/Popover/PopoverAnimator.swift
|
1
|
4722
|
//
// PopoverAnimator.swift
// STWeiBo
//
// Created by ST on 15/11/14.
// Copyright © 2015年 ST. All rights reserved.
//
import UIKit
// 定义常量保存通知的名称
let STPopoverAnimatorWillShow = "STPopoverAnimatorWillShow"
let STPopoverAnimatorWilldismiss = "STPopoverAnimatorWilldismiss"
class PopoverAnimator: NSObject , UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning
{
/// 记录当前是否是展开
var isPresent: Bool = false
/// 定义属性保存菜单的大小
var presentFrame = CGRectZero
// 实现代理方法, 告诉系统谁来负责转场动画
// UIPresentationController iOS8推出的专门用于负责转场动画的
func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController?
{
let pc = PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting)
// 设置菜单的大小
pc.presentFrame = presentFrame
return pc
}
// MARK: - 只要实现了一下方法, 那么系统自带的默认动画就没有了, "所有"东西都需要程序员自己来实现
/**
告诉系统谁来负责Modal的展现动画
:param: presented 被展现视图
:param: presenting 发起的视图
:returns: 谁来负责
*/
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
isPresent = true
// 发送通知, 通知控制器即将展开
NSNotificationCenter.defaultCenter().postNotificationName(STPopoverAnimatorWillShow, object: self)
return self
}
/**
告诉系统谁来负责Modal的消失动画
:param: dismissed 被关闭的视图
:returns: 谁来负责
*/
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
isPresent = false
// 发送通知, 通知控制器即将消失
NSNotificationCenter.defaultCenter().postNotificationName(STPopoverAnimatorWilldismiss, object: self)
return self
}
// MARK: - UIViewControllerAnimatedTransitioning
/**
返回动画时长
:param: transitionContext 上下文, 里面保存了动画需要的所有参数
:returns: 动画时长
*/
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval
{
return 0.5
}
/**
告诉系统如何动画, 无论是展现还是消失都会调用这个方法
:param: transitionContext 上下文, 里面保存了动画需要的所有参数
*/
func animateTransition(transitionContext: UIViewControllerContextTransitioning)
{
// 1.拿到展现视图
if isPresent
{
// 展开
print("展开")
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
toView.transform = CGAffineTransformMakeScale(1.0, 0.0);
// 注意: 一定要将视图添加到容器上
transitionContext.containerView()?.addSubview(toView)
// 设置锚点
toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
// 2.执行动画
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
// 2.1清空transform
toView.transform = CGAffineTransformIdentity
}) { (_) -> Void in
// 2.2动画执行完毕, 一定要告诉系统
// 如果不写, 可能导致一些未知错误
transitionContext.completeTransition(true)
}
}else
{
// 关闭
print("关闭")
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
// 注意:由于CGFloat是不准确的, 所以如果写0.0会没有动画
// 压扁
fromView?.transform = CGAffineTransformMakeScale(1.0, 0.000001)
}, completion: { (_) -> Void in
// 如果不写, 可能导致一些未知错误
transitionContext.completeTransition(true)
})
}
}
}
|
mit
|
146208fd2eea6899eb84103244c760d7
| 31.609756 | 217 | 0.63999 | 5.051637 | false | false | false | false |
lukasgit/flutter_contacts
|
ios/Classes/SwiftContactsServicePlugin.swift
|
1
|
27262
|
import Flutter
import UIKit
import Contacts
import ContactsUI
@available(iOS 9.0, *)
public class SwiftContactsServicePlugin: NSObject, FlutterPlugin, CNContactViewControllerDelegate, CNContactPickerDelegate {
private var result: FlutterResult? = nil
private var localizedLabels: Bool = true
private let rootViewController: UIViewController
static let FORM_OPERATION_CANCELED: Int = 1
static let FORM_COULD_NOT_BE_OPEN: Int = 2
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "github.com/clovisnicolas/flutter_contacts", binaryMessenger: registrar.messenger())
let rootViewController = UIApplication.shared.delegate!.window!!.rootViewController!;
let instance = SwiftContactsServicePlugin(rootViewController)
registrar.addMethodCallDelegate(instance, channel: channel)
instance.preLoadContactView()
}
init(_ rootViewController: UIViewController) {
self.rootViewController = rootViewController
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getContacts":
let arguments = call.arguments as! [String:Any]
result(getContacts(query: (arguments["query"] as? String), withThumbnails: arguments["withThumbnails"] as! Bool,
photoHighResolution: arguments["photoHighResolution"] as! Bool, phoneQuery: false, orderByGivenName: arguments["orderByGivenName"] as! Bool,
localizedLabels: arguments["iOSLocalizedLabels"] as! Bool ))
case "getContactsForPhone":
let arguments = call.arguments as! [String:Any]
result(
getContacts(
query: (arguments["phone"] as? String),
withThumbnails: arguments["withThumbnails"] as! Bool,
photoHighResolution: arguments["photoHighResolution"] as! Bool,
phoneQuery: true,
orderByGivenName: arguments["orderByGivenName"] as! Bool,
localizedLabels: arguments["iOSLocalizedLabels"] as! Bool
)
)
case "getContactsForEmail":
let arguments = call.arguments as! [String:Any]
result(
getContacts(
query: (arguments["email"] as? String),
withThumbnails: arguments["withThumbnails"] as! Bool,
photoHighResolution: arguments["photoHighResolution"] as! Bool,
phoneQuery: false,
emailQuery: true,
orderByGivenName: arguments["orderByGivenName"] as! Bool,
localizedLabels: arguments["iOSLocalizedLabels"] as! Bool
)
)
case "addContact":
let contact = dictionaryToContact(dictionary: call.arguments as! [String : Any])
let addResult = addContact(contact: contact)
if (addResult == "") {
result(nil)
}
else {
result(FlutterError(code: "", message: addResult, details: nil))
}
case "deleteContact":
if(deleteContact(dictionary: call.arguments as! [String : Any])){
result(nil)
}
else{
result(FlutterError(code: "", message: "Failed to delete contact, make sure it has a valid identifier", details: nil))
}
case "updateContact":
if(updateContact(dictionary: call.arguments as! [String: Any])) {
result(nil)
}
else {
result(FlutterError(code: "", message: "Failed to update contact, make sure it has a valid identifier", details: nil))
}
case "openContactForm":
let arguments = call.arguments as! [String:Any]
localizedLabels = arguments["iOSLocalizedLabels"] as! Bool
self.result = result
_ = openContactForm()
case "openExistingContact":
let arguments = call.arguments as! [String : Any]
let contact = arguments["contact"] as! [String : Any]
localizedLabels = arguments["iOSLocalizedLabels"] as! Bool
self.result = result
_ = openExistingContact(contact: contact, result: result)
case "openDeviceContactPicker":
let arguments = call.arguments as! [String : Any]
openDeviceContactPicker(arguments: arguments, result: result);
default:
result(FlutterMethodNotImplemented)
}
}
func getContacts(query : String?, withThumbnails: Bool, photoHighResolution: Bool, phoneQuery: Bool, emailQuery: Bool = false, orderByGivenName: Bool, localizedLabels: Bool) -> [[String:Any]]{
var contacts : [CNContact] = []
var result = [[String:Any]]()
//Create the store, keys & fetch request
let store = CNContactStore()
var keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactEmailAddressesKey,
CNContactPhoneNumbersKey,
CNContactFamilyNameKey,
CNContactGivenNameKey,
CNContactMiddleNameKey,
CNContactNamePrefixKey,
CNContactNameSuffixKey,
CNContactPostalAddressesKey,
CNContactOrganizationNameKey,
CNContactJobTitleKey,
CNContactBirthdayKey] as [Any]
if(withThumbnails){
if(photoHighResolution){
keys.append(CNContactImageDataKey)
} else {
keys.append(CNContactThumbnailImageDataKey)
}
}
let fetchRequest = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
// Set the predicate if there is a query
if query != nil && !phoneQuery && !emailQuery {
fetchRequest.predicate = CNContact.predicateForContacts(matchingName: query!)
}
if #available(iOS 11, *) {
if query != nil && phoneQuery {
let phoneNumberPredicate = CNPhoneNumber(stringValue: query!)
fetchRequest.predicate = CNContact.predicateForContacts(matching: phoneNumberPredicate)
} else if query != nil && emailQuery {
fetchRequest.predicate = CNContact.predicateForContacts(matchingEmailAddress: query!)
}
}
// Fetch contacts
do{
try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in
if phoneQuery {
if #available(iOS 11, *) {
contacts.append(contact)
} else if query != nil && self.has(contact: contact, phone: query!){
contacts.append(contact)
}
} else if emailQuery {
if #available(iOS 11, *) {
contacts.append(contact)
} else if query != nil && (contact.emailAddresses.contains { $0.value.caseInsensitiveCompare(query!) == .orderedSame}) {
contacts.append(contact)
}
} else {
contacts.append(contact)
}
})
}
catch let error as NSError {
print(error.localizedDescription)
return result
}
if (orderByGivenName) {
contacts = contacts.sorted { (contactA, contactB) -> Bool in
contactA.givenName.lowercased() < contactB.givenName.lowercased()
}
}
// Transform the CNContacts into dictionaries
for contact : CNContact in contacts{
result.append(contactToDictionary(contact: contact, localizedLabels: localizedLabels))
}
return result
}
private func has(contact: CNContact, phone: String) -> Bool {
if (!contact.phoneNumbers.isEmpty) {
let phoneNumberToCompareAgainst = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
for phoneNumber in contact.phoneNumbers {
if let phoneNumberStruct = phoneNumber.value as CNPhoneNumber? {
let phoneNumberString = phoneNumberStruct.stringValue
let phoneNumberToCompare = phoneNumberString.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
if phoneNumberToCompare == phoneNumberToCompareAgainst {
return true
}
}
}
}
return false
}
func addContact(contact : CNMutableContact) -> String {
let store = CNContactStore()
do {
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
try store.execute(saveRequest)
}
catch {
return error.localizedDescription
}
return ""
}
func openContactForm() -> [String:Any]? {
let contact = CNMutableContact.init()
let controller = CNContactViewController.init(forNewContact:contact)
controller.delegate = self
DispatchQueue.main.async {
let navigation = UINavigationController .init(rootViewController: controller)
let viewController : UIViewController? = UIApplication.shared.delegate?.window??.rootViewController
viewController?.present(navigation, animated:true, completion: nil)
}
return nil
}
func preLoadContactView() {
DispatchQueue.main.asyncAfter(deadline: .now()+5) {
NSLog("Preloading CNContactViewController")
let contactViewController = CNContactViewController.init(forNewContact: nil)
}
}
@objc func cancelContactForm() {
if let result = self.result {
let viewController : UIViewController? = UIApplication.shared.delegate?.window??.rootViewController
viewController?.dismiss(animated: true, completion: nil)
result(SwiftContactsServicePlugin.FORM_OPERATION_CANCELED)
self.result = nil
}
}
public func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
viewController.dismiss(animated: true, completion: nil)
if let result = self.result {
if let contact = contact {
result(contactToDictionary(contact: contact, localizedLabels: localizedLabels))
} else {
result(SwiftContactsServicePlugin.FORM_OPERATION_CANCELED)
}
self.result = nil
}
}
func openExistingContact(contact: [String:Any], result: FlutterResult ) -> [String:Any]? {
let store = CNContactStore()
do {
// Check to make sure dictionary has an identifier
guard let identifier = contact["identifier"] as? String else{
result(SwiftContactsServicePlugin.FORM_COULD_NOT_BE_OPEN)
return nil;
}
let backTitle = contact["backTitle"] as? String
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactIdentifierKey,
CNContactEmailAddressesKey,
CNContactBirthdayKey,
CNContactImageDataKey,
CNContactPhoneNumbersKey,
CNContactViewController.descriptorForRequiredKeys()
] as! [CNKeyDescriptor]
let cnContact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keysToFetch)
let viewController = CNContactViewController(for: cnContact)
viewController.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: backTitle == nil ? "Cancel" : backTitle, style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancelContactForm))
viewController.delegate = self
DispatchQueue.main.async {
let navigation = UINavigationController .init(rootViewController: viewController)
var currentViewController = UIApplication.shared.keyWindow?.rootViewController
while let nextView = currentViewController?.presentedViewController {
currentViewController = nextView
}
let activityIndicatorView = UIActivityIndicatorView.init(style: UIActivityIndicatorView.Style.gray)
activityIndicatorView.frame = (UIApplication.shared.keyWindow?.frame)!
activityIndicatorView.startAnimating()
activityIndicatorView.backgroundColor = UIColor.white
navigation.view.addSubview(activityIndicatorView)
currentViewController!.present(navigation, animated: true, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now()+0.5 ){
activityIndicatorView.removeFromSuperview()
}
}
return nil
} catch {
NSLog(error.localizedDescription)
result(SwiftContactsServicePlugin.FORM_COULD_NOT_BE_OPEN)
return nil
}
}
func openDeviceContactPicker(arguments: [String:Any], result: @escaping FlutterResult) {
localizedLabels = arguments["iOSLocalizedLabels"] as! Bool
self.result = result
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self
//contactPicker!.displayedPropertyKeys = [CNContactPhoneNumbersKey];
DispatchQueue.main.async {
self.rootViewController.present(contactPicker, animated: true, completion: nil)
}
}
//MARK:- CNContactPickerDelegate Method
public func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
if let result = self.result {
result(contactToDictionary(contact: contact, localizedLabels: localizedLabels))
self.result = nil
}
}
public func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
if let result = self.result {
result(SwiftContactsServicePlugin.FORM_OPERATION_CANCELED)
self.result = nil
}
}
func deleteContact(dictionary : [String:Any]) -> Bool{
guard let identifier = dictionary["identifier"] as? String else{
return false;
}
let store = CNContactStore()
let keys = [CNContactIdentifierKey as NSString]
do{
if let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keys).mutableCopy() as? CNMutableContact{
let request = CNSaveRequest()
request.delete(contact)
try store.execute(request)
}
}
catch{
print(error.localizedDescription)
return false;
}
return true;
}
func updateContact(dictionary : [String:Any]) -> Bool{
// Check to make sure dictionary has an identifier
guard let identifier = dictionary["identifier"] as? String else{
return false;
}
let store = CNContactStore()
let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactEmailAddressesKey,
CNContactPhoneNumbersKey,
CNContactFamilyNameKey,
CNContactGivenNameKey,
CNContactMiddleNameKey,
CNContactNamePrefixKey,
CNContactNameSuffixKey,
CNContactPostalAddressesKey,
CNContactOrganizationNameKey,
CNContactImageDataKey,
CNContactJobTitleKey] as [Any]
do {
// Check if the contact exists
if let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keys as! [CNKeyDescriptor]).mutableCopy() as? CNMutableContact{
/// Update the contact that was retrieved from the store
//Simple fields
contact.givenName = dictionary["givenName"] as? String ?? ""
contact.familyName = dictionary["familyName"] as? String ?? ""
contact.middleName = dictionary["middleName"] as? String ?? ""
contact.namePrefix = dictionary["prefix"] as? String ?? ""
contact.nameSuffix = dictionary["suffix"] as? String ?? ""
contact.organizationName = dictionary["company"] as? String ?? ""
contact.jobTitle = dictionary["jobTitle"] as? String ?? ""
contact.imageData = (dictionary["avatar"] as? FlutterStandardTypedData)?.data
//Phone numbers
if let phoneNumbers = dictionary["phones"] as? [[String:String]]{
var updatedPhoneNumbers = [CNLabeledValue<CNPhoneNumber>]()
for phone in phoneNumbers where phone["value"] != nil {
updatedPhoneNumbers.append(CNLabeledValue(label:getPhoneLabel(label: phone["label"]),value:CNPhoneNumber(stringValue: phone["value"]!)))
}
contact.phoneNumbers = updatedPhoneNumbers
}
//Emails
if let emails = dictionary["emails"] as? [[String:String]]{
var updatedEmails = [CNLabeledValue<NSString>]()
for email in emails where nil != email["value"] {
let emailLabel = email["label"] ?? ""
updatedEmails.append(CNLabeledValue(label: getCommonLabel(label: emailLabel), value: email["value"]! as NSString))
}
contact.emailAddresses = updatedEmails
}
//Postal addresses
if let postalAddresses = dictionary["postalAddresses"] as? [[String:String]]{
var updatedPostalAddresses = [CNLabeledValue<CNPostalAddress>]()
for postalAddress in postalAddresses{
let newAddress = CNMutablePostalAddress()
newAddress.street = postalAddress["street"] ?? ""
newAddress.city = postalAddress["city"] ?? ""
newAddress.postalCode = postalAddress["postcode"] ?? ""
newAddress.country = postalAddress["country"] ?? ""
newAddress.state = postalAddress["region"] ?? ""
let label = postalAddress["label"] ?? ""
updatedPostalAddresses.append(CNLabeledValue(label: getCommonLabel(label: label), value: newAddress))
}
contact.postalAddresses = updatedPostalAddresses
}
// Attempt to update the contact
let request = CNSaveRequest()
request.update(contact)
try store.execute(request)
}
}
catch {
print(error.localizedDescription)
return false;
}
return true;
}
func dictionaryToContact(dictionary : [String:Any]) -> CNMutableContact{
let contact = CNMutableContact()
//Simple fields
contact.givenName = dictionary["givenName"] as? String ?? ""
contact.familyName = dictionary["familyName"] as? String ?? ""
contact.middleName = dictionary["middleName"] as? String ?? ""
contact.namePrefix = dictionary["prefix"] as? String ?? ""
contact.nameSuffix = dictionary["suffix"] as? String ?? ""
contact.organizationName = dictionary["company"] as? String ?? ""
contact.jobTitle = dictionary["jobTitle"] as? String ?? ""
if let avatarData = (dictionary["avatar"] as? FlutterStandardTypedData)?.data {
contact.imageData = avatarData
}
//Phone numbers
if let phoneNumbers = dictionary["phones"] as? [[String:String]]{
for phone in phoneNumbers where phone["value"] != nil {
contact.phoneNumbers.append(CNLabeledValue(label:getPhoneLabel(label:phone["label"]),value:CNPhoneNumber(stringValue:phone["value"]!)))
}
}
//Emails
if let emails = dictionary["emails"] as? [[String:String]]{
for email in emails where nil != email["value"] {
let emailLabel = email["label"] ?? ""
contact.emailAddresses.append(CNLabeledValue(label:getCommonLabel(label: emailLabel), value:email["value"]! as NSString))
}
}
//Postal addresses
if let postalAddresses = dictionary["postalAddresses"] as? [[String:String]]{
for postalAddress in postalAddresses{
let newAddress = CNMutablePostalAddress()
newAddress.street = postalAddress["street"] ?? ""
newAddress.city = postalAddress["city"] ?? ""
newAddress.postalCode = postalAddress["postcode"] ?? ""
newAddress.country = postalAddress["country"] ?? ""
newAddress.state = postalAddress["region"] ?? ""
let label = postalAddress["label"] ?? ""
contact.postalAddresses.append(CNLabeledValue(label: getCommonLabel(label: label), value: newAddress))
}
}
//BIRTHDAY
if let birthday = dictionary["birthday"] as? String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.date(from: birthday)!
contact.birthday = Calendar.current.dateComponents([.year, .month, .day], from: date)
}
return contact
}
func contactToDictionary(contact: CNContact, localizedLabels: Bool) -> [String:Any]{
var result = [String:Any]()
//Simple fields
result["identifier"] = contact.identifier
result["displayName"] = CNContactFormatter.string(from: contact, style: CNContactFormatterStyle.fullName)
result["givenName"] = contact.givenName
result["familyName"] = contact.familyName
result["middleName"] = contact.middleName
result["prefix"] = contact.namePrefix
result["suffix"] = contact.nameSuffix
result["company"] = contact.organizationName
result["jobTitle"] = contact.jobTitle
if contact.isKeyAvailable(CNContactThumbnailImageDataKey) {
if let avatarData = contact.thumbnailImageData {
result["avatar"] = FlutterStandardTypedData(bytes: avatarData)
}
}
if contact.isKeyAvailable(CNContactImageDataKey) {
if let avatarData = contact.imageData {
result["avatar"] = FlutterStandardTypedData(bytes: avatarData)
}
}
//Phone numbers
var phoneNumbers = [[String:String]]()
for phone in contact.phoneNumbers{
var phoneDictionary = [String:String]()
phoneDictionary["value"] = phone.value.stringValue
phoneDictionary["label"] = "other"
if let label = phone.label{
phoneDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawPhoneLabel(label);
}
phoneNumbers.append(phoneDictionary)
}
result["phones"] = phoneNumbers
//Emails
var emailAddresses = [[String:String]]()
for email in contact.emailAddresses{
var emailDictionary = [String:String]()
emailDictionary["value"] = String(email.value)
emailDictionary["label"] = "other"
if let label = email.label{
emailDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawCommonLabel(label);
}
emailAddresses.append(emailDictionary)
}
result["emails"] = emailAddresses
//Postal addresses
var postalAddresses = [[String:String]]()
for address in contact.postalAddresses{
var addressDictionary = [String:String]()
addressDictionary["label"] = ""
if let label = address.label{
addressDictionary["label"] = localizedLabels ? CNLabeledValue<NSString>.localizedString(forLabel: label) : getRawCommonLabel(label);
}
addressDictionary["street"] = address.value.street
addressDictionary["city"] = address.value.city
addressDictionary["postcode"] = address.value.postalCode
addressDictionary["region"] = address.value.state
addressDictionary["country"] = address.value.country
postalAddresses.append(addressDictionary)
}
result["postalAddresses"] = postalAddresses
//BIRTHDAY
if let birthday : Date = contact.birthday?.date {
let formatter = DateFormatter()
let year = Calendar.current.component(.year, from: birthday)
formatter.dateFormat = year == 1 ? "--MM-dd" : "yyyy-MM-dd";
result["birthday"] = formatter.string(from: birthday)
}
return result
}
func getPhoneLabel(label: String?) -> String{
let labelValue = label ?? ""
switch(labelValue){
case "main": return CNLabelPhoneNumberMain
case "mobile": return CNLabelPhoneNumberMobile
case "iPhone": return CNLabelPhoneNumberiPhone
case "work": return CNLabelWork
case "home": return CNLabelHome
case "other": return CNLabelOther
default: return labelValue
}
}
func getCommonLabel(label:String?) -> String{
let labelValue = label ?? ""
switch(labelValue){
case "work": return CNLabelWork
case "home": return CNLabelHome
case "other": return CNLabelOther
default: return labelValue
}
}
func getRawPhoneLabel(_ label: String?) -> String{
let labelValue = label ?? ""
switch(labelValue){
case CNLabelPhoneNumberMain: return "main"
case CNLabelPhoneNumberMobile: return "mobile"
case CNLabelPhoneNumberiPhone: return "iPhone"
case CNLabelWork: return "work"
case CNLabelHome: return "home"
case CNLabelOther: return "other"
default: return labelValue
}
}
func getRawCommonLabel(_ label: String?) -> String{
let labelValue = label ?? ""
switch(labelValue){
case CNLabelWork: return "work"
case CNLabelHome: return "home"
case CNLabelOther: return "other"
default: return labelValue
}
}
}
|
mit
|
f2739d46b3d7cfd96c35ed5328a0b672
| 43.256494 | 218 | 0.591226 | 5.446953 | false | false | false | false |
Harley-xk/SimpleDataKit
|
Example/Pods/Comet/Comet/Extensions/UIVIew+Comet.swift
|
1
|
1248
|
//
// UIVIew+Comet.swift
// Comet
//
// Created by Harley on 2016/11/8.
//
//
import Foundation
public extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return self.layer.borderWidth
}
set {
self.layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
if let color = self.layer.borderColor {
return UIColor(cgColor: color)
}
return nil
}
set {
self.layer.borderColor = newValue?.cgColor
}
}
}
public extension Bundle {
/// 从 xib 文件创建视图
///
/// - Parameter name: xib 文件名,默认为指定视图类名
public func createView<T: UIView>(_ name: String? = nil, owner: Any? = nil, options: [AnyHashable : Any]? = nil) -> T {
let nibName = name ?? T.classNameWithoutModule
let view = loadNibNamed(nibName, owner: owner, options: options)![0] as! T
return view
}
}
|
mit
|
b77b2e91369c3a190c5f34c2a95f3bab
| 20.571429 | 123 | 0.536424 | 4.376812 | false | false | false | false |
randymarsh77/crystal
|
Sources/Crystal/streamserver.swift
|
1
|
1618
|
import Foundation
import IDisposable
import Scope
import Sockets
import Time
public class StreamServer : IDisposable
{
let stream: SynchronizedDataStreamWithMetadata<Time>
let synchronizer = TimeSynchronizer()
var tcpServer: TCPServer?
var connections = [Connection]()
public init(stream: SynchronizedDataStreamWithMetadata<Time>, port: UInt16) throws
{
self.stream = stream
self.tcpServer = try TCPServer(options: ServerOptions(port: .Specific(port))) { (socket) in
self.addConnection(socket: socket)
}
}
public func dispose() -> Void
{
for connection in self.connections {
connection.dispose()
}
self.connections.removeAll()
self.tcpServer?.dispose()
self.tcpServer = nil
}
func addConnection(socket: Socket) -> Void
{
let token = self.synchronizer.addTarget(socket)
let subscription = self.stream.addSubscriber { (data, metadata) in
let synchronization = self.synchronizer.syncTarget(token: token, time: metadata)
let header = SNSUtility.GenerateHeader(synchronization: synchronization)
socket.write(header)
socket.write(data)
}
connections.append(Connection(streamSubscription: subscription, socket: socket))
}
class Connection
{
var subscription: Scope
var socket: Socket
var onErrorScope: Scope?
internal init(streamSubscription: Scope, socket: Socket)
{
self.subscription = streamSubscription
self.socket = socket
self.onErrorScope = self.socket.registerErrorHandler() {
print("socket error")
self.dispose()
}
}
internal func dispose() -> Void
{
self.subscription.dispose()
self.socket.dispose()
}
}
}
|
mit
|
11aaf25a39b805f59f7395fe06234ab2
| 23.515152 | 93 | 0.73733 | 3.668934 | false | false | false | false |
DiligentRobot/WKWebViewExample
|
WKWebKitExample/ViewController+WKNavigationDelegate.swift
|
1
|
1574
|
//
// ViewController+WKNavigationDelegate.swift
// WKWebKitExample
//
// Created by Scotty on 01/10/2017.
// Copyright © 2017 Diligent Robot. All rights reserved.
//
import UIKit
import WebKit
extension ViewController: WKNavigationDelegate {
/// When a navigation action occurs for a link to wikipedia, ensure it gets
/// Moved out to the default browser.
func webView(_: WKWebView, decidePolicyFor: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// If we are loading for any reason other than a link activated
// then just process it.
guard decidePolicyFor.navigationType == .linkActivated else {
decisionHandler(.allow)
return
}
// Reroute any request for wikipedia out to the default browser
// then cancel the request.
let request = decidePolicyFor.request
if let url = request.url, let host = url.host, host == "en.m.wikipedia.org" {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
decisionHandler(.cancel)
return
}
// By default allow the other requests to continue
decisionHandler(.allow)
}
/// When the first load of the initial html page is finished
/// Call the filter JavaScript within the page.
func webView(_: WKWebView, didFinish: WKNavigation!) {
guard didFinish == initialLoadAction else { return }
self.filterTowns(filter: searchField.text ?? "")
}
}
|
mit
|
5e0ba51db6bc4a9a70ca32a893957eb1
| 33.195652 | 132 | 0.644628 | 5.090615 | false | false | false | false |
ihomway/RayWenderlichCourses
|
Beginning Swift 3/Beginning Swift 3.playground/Pages/Types.xcplaygroundpage/Contents.swift
|
1
|
412
|
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
var greeting = "Hello World"
var anotherGreeting: String = "Hello String"
var cost = 60
var anotherCost: Int = 60
var pi = 3.141
var morePi: Double = 3.141
var myFloat: Float = Float(morePi)
var emoji: Character = "😀"
var likeSwift: Bool = true
Double(cost) + morePi
cost + Int(morePi)
"I like " + String(morePi)
//: [Next](@next)
|
mit
|
7d3834febf3abe39e14615b6cfbe5de3
| 19.45 | 44 | 0.689487 | 3.075188 | false | false | false | false |
vkedwardli/SignalR-Swift
|
SignalR-Swift/Transports/ServerSentEventsTransport.swift
|
2
|
7150
|
//
// ServerSentEventsTransport.swift
// SignalR-Swift
//
// Created by Vladimir Kushelkov on 19/07/2017.
// Copyright © 2017 Jordan Camara. All rights reserved.
//
import Foundation
import Alamofire
private typealias CompletionHandler = (_ respomce: Any?, _ error: Error?) -> ()
public class ServerSentEventsTransport: HttpTransport {
private var stop = false
private var connectTimeoutOperation: BlockOperation?
private var completionHandler: CompletionHandler?
private let sseQueue = DispatchQueue(label: "com.autosoftdms.SignalR-Swift.serverSentEvents", qos: .userInitiated)
var reconnectDelay: TimeInterval = 2.0
override public var name: String? {
return "serverSentEvents"
}
override public var supportsKeepAlive: Bool {
return true
}
override public func negotiate(connection: ConnectionProtocol, connectionData: String?, completionHandler: ((NegotiationResponse?, Error?) -> ())?) {
super.negotiate(connection: connection, connectionData: connectionData, completionHandler: nil)
}
override public func start(connection: ConnectionProtocol, connectionData: String?, completionHandler: ((Any?, Error?) -> ())?) {
self.completionHandler = completionHandler
self.connectTimeoutOperation = BlockOperation { [weak self] in
guard let strongSelf = self, let completionHandler = strongSelf.completionHandler else { return }
let userInfo = [
NSLocalizedDescriptionKey: NSLocalizedString("Connection timed out.", comment: "timeout error description"),
NSLocalizedFailureReasonErrorKey: NSLocalizedString("Connection did not receive initialized message before the timeout.", comment: "timeout error reason"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString("Retry or switch transports.", comment: "timeout error retry suggestion")
]
let error = NSError(domain: "com.autosoftdms.SignalR-Swift.\(type(of: strongSelf))", code: NSURLErrorTimedOut, userInfo: userInfo)
completionHandler(nil, error)
strongSelf.completionHandler = nil
}
self.connectTimeoutOperation!.perform(#selector(BlockOperation.start), with: nil, afterDelay: connection.transportConnectTimeout)
self.open(connection: connection, connectionData: connectionData, isReconnecting: false)
}
override public func send(connection: ConnectionProtocol, data: Any, connectionData: String?, completionHandler: ((Any?, Error?) -> ())?) {
super.send(connection: connection, data: data, connectionData: connectionData, completionHandler: completionHandler)
}
override public func abort(connection: ConnectionProtocol, timeout: Double, connectionData: String?) {
self.stop = true
super.abort(connection: connection, timeout: timeout, connectionData: connectionData)
}
override public func lostConnection(connection: ConnectionProtocol) {
}
// MARK: - SSE Transport
private let buffer = ChunkBuffer()
private func open(connection: ConnectionProtocol, connectionData: String?, isReconnecting: Bool) {
var parameters = connection.queryString ?? [:]
parameters["transport"] = self.name!
parameters["connectionToken"] = connection.connectionToken ?? ""
parameters["messageId"] = connection.messageId ?? ""
parameters["groupsToken"] = connection.groupsToken ?? ""
parameters["connectionData"] = connectionData ?? ""
let url = isReconnecting ? connection.url.appending("reconnect") : connection.url.appending("connect")
connection.getRequest(url: url,
httpMethod: .get,
encoding: URLEncoding.default,
parameters: parameters,
timeout: 240,
headers: ["Connection": "Keep-Alive"])
.stream { [weak self] data in
self?.sseQueue.async { [weak connection] in
guard let strongSelf = self, let strongConnection = connection else { return }
strongSelf.buffer.append(data: data)
while let line = strongSelf.buffer.readLine() {
guard let message = ServerSentEvent.tryParse(line: line) else { continue }
DispatchQueue.main.async { strongSelf.process(message: message, connection: strongConnection) }
}
}
}.validate().response() { [weak self, weak connection] dataResponse in
guard let strongSelf = self, let strongConnection = connection else { return }
strongSelf.cancelTimeoutOperation()
if let error = dataResponse.error as NSError?, error.code != NSURLErrorCancelled {
strongConnection.didReceiveError(error: error)
}
if strongSelf.stop {
strongSelf.completeAbort()
} else if !strongSelf.tryCompleteAbort() && !isReconnecting {
strongSelf.reconnect(connection: strongConnection, data: connectionData)
}
}
}
private func process(message: ServerSentEvent, connection: ConnectionProtocol) {
guard message.event == .data else { return }
if message.data == "initialized" {
if connection.changeState(oldState: .reconnecting, toState: .connected) {
connection.didReconnect()
}
return
}
guard let data = message.data?.data(using: .utf8) else { return }
var shouldReconnect = false
var disconnected = false
connection.processResponse(response: data, shouldReconnect: &shouldReconnect, disconnected: &disconnected)
cancelTimeoutOperation()
if disconnected {
stop = true
connection.disconnect()
}
}
private func cancelTimeoutOperation() {
guard let completionHandler = self.completionHandler,
let timeoutOperation = connectTimeoutOperation else { return }
NSObject.cancelPreviousPerformRequests(withTarget: timeoutOperation, selector: #selector(BlockOperation.start), object: nil)
connectTimeoutOperation = nil
completionHandler(nil, nil)
self.completionHandler = nil
}
private func reconnect(connection: ConnectionProtocol, data: String?) {
_ = BlockOperation { [weak self, weak connection] in
if let strongSelf = self, let strongConnection = connection,
strongConnection.state != .disconnected, Connection.ensureReconnecting(connection: strongConnection) {
strongSelf.open(connection: strongConnection, connectionData: data, isReconnecting: true)
}
}.perform(#selector(BlockOperation.start), with: nil, afterDelay: self.reconnectDelay)
}
}
|
mit
|
c3f1d5984546e24115fa9883f95ff54b
| 43.962264 | 171 | 0.63953 | 5.61146 | false | false | false | false |
lexchou/swallow
|
stdlib/core/OperatorAdd.swift
|
1
|
2697
|
prefix func +(x: Double) -> Double {
return 0//TODO
}
func +(lhs: Float, rhs: Float) -> Float {
return 0//TODO
}
func + <T>(lhs: Int, rhs: UnsafePointer<T>) -> UnsafePointer<T> {
return lhs//TODO
}
prefix func +(x: Float) -> Float {
return 0//TODO
}
func +(lhs: Int, rhs: Int) -> Int {
return 0//TODO
}
func + <T>(lhs: UnsafePointer<T>, rhs: Int) -> UnsafePointer<T> {
return lhs//TODO
}
func +(lhs: UInt, rhs: UInt) -> UInt {
return 0//TODO
}
func +(lhs: Int64, rhs: Int64) -> Int64 {
return 0//TODO
}
func +(lhs: UInt64, rhs: UInt64) -> UInt64 {
return 0//TODO
}
func + <T>(lhs: Int, rhs: UnsafeMutablePointer<T>) -> UnsafeMutablePointer<T> {
return lhs//TODO
}
func + <T>(lhs: UnsafeMutablePointer<T>, rhs: Int) -> UnsafeMutablePointer<T> {
return lhs//TODO
}
func +(lhs: Int32, rhs: Int32) -> Int32 {
return 0//TODO
}
func +(lhs: UInt32, rhs: UInt32) -> UInt32 {
return 0//TODO
}
func +(lhs: Int16, rhs: Int16) -> Int16 {
return 0//TODO
}
func +(lhs: UInt16, rhs: UInt16) -> UInt16 {
return 0//TODO
}
func +(lhs: Int8, rhs: Int8) -> Int8 {
return 0//TODO
}
func +(lhs: UInt8, rhs: UInt8) -> UInt8 {
return 0//TODO
}
func +(lhs: Double, rhs: Double) -> Double {
return 0//TODO
}
func +(lhs: String, rhs: String) -> String {
return lhs//TODO
}
prefix func +(x: Float80) -> Float80 {
return 0//TODO
}
func +(lhs: Float80, rhs: Float80) -> Float80 {
return 0//TODO
}
/// Add `lhs` and `rhs`, returning a result and trapping in case of
/// arithmetic overflow (except in -Ounchecked builds).
func + <T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T {
return lhs//TODO
}
prefix func + <T : _SignedNumberType>(x: T) -> T {
return 0//TODO
}
func + <C : _ExtensibleCollectionType, S : SequenceType where S.Generator.Element == S.Generator.Element>(lhs: C, rhs: S) -> C {
return lhs//TODO
}
func + <C : _ExtensibleCollectionType, S : SequenceType where S.Generator.Element == S.Generator.Element>(lhs: S, rhs: C) -> C {
return lhs//TODO
}
func + <T : Strideable>(lhs: T.Stride, rhs: T) -> T {
return lhs//TODO
}
func + <C : _ExtensibleCollectionType, S : CollectionType where S.Generator.Element == S.Generator.Element>(lhs: C, rhs: S) -> C {
return lhs//TODO
}
func + <EC1 : _ExtensibleCollectionType, EC2 : _ExtensibleCollectionType where EC1.Generator.Element == EC1.Generator.Element>(lhs: EC1, rhs: EC2) -> EC1 {
return lhs//TODO
}
func + <T : Strideable>(lhs: T, rhs: T.Stride) -> T {
return lhs//TODO
}
/// add `lhs` and `rhs`, silently discarding any overflow.
func &+ <T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T {
return lhs//TODO
}
|
bsd-3-clause
|
7be637bc8efbd14f219ed928e558fed0
| 20.070313 | 155 | 0.614757 | 3.023543 | false | false | false | false |
JornWu/ZhiBo_Swift
|
ZhiBo_Swift/Class/Mine/ViewController/MineViewController.swift
|
1
|
9742
|
//
// MineViewController.swift
// ZhiBo_Swift
//
// Created by JornWu on 2017/2/27.
// Copyright © 2017年 Jorn.Wu([email protected]). All rights reserved.
//
import UIKit
class MineViewController:
BaseViewController,
UITableViewDelegate,
UITableViewDataSource {
private lazy var itemsTitle: Array = {
return [
["我的喵币", "直播间管理", "号外!做任务赢礼包~"],
["我的收益", "游戏中心"],
["设置"]
]
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = VIEW_BACKGROUND_COLOR
self.setupContentView()
}
private func setupContentView() {
///
/// main tableView
///
let tableView = { () -> UITableView in
let tbView = UITableView(frame: .zero, style: .grouped)
tbView.backgroundColor = UIColor.white
tbView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
self.view.addSubview(tbView)
tbView.snp.makeConstraints({ (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
make.top.equalTo(-21)
})
tbView.dataSource = self
tbView.delegate = self
return tbView
}()
///
/// profile view
///
let headerView = { () -> UIView in
let view = UIView(frame: CGRect(x: 0,
y: 0,
width: self.view.bounds.width,
height: self.view.bounds.height * 2 / 5))
view.backgroundColor = VIEW_BACKGROUND_COLOR
tableView.tableHeaderView = view
return view
}()
let iconBtn = { () -> UIButton in
let profileIcon = UIButton()
profileIcon.setImage(#imageLiteral(resourceName: "jiaIcon"), for: .normal)
headerView.addSubview(profileIcon)
profileIcon.layer.cornerRadius = 50
profileIcon.layer.borderWidth = 2
profileIcon.layer.borderColor = UIColor.white.cgColor
profileIcon.clipsToBounds = true
profileIcon.isHighlighted = false
profileIcon.snp.makeConstraints({ (make) in
make.left.equalTo(30)
make.top.equalTo(80)
make.size.equalTo(CGSize(width: 100, height: 100))
})
let tips = UILabel()
tips.text = "Edit..."
tips.font = UIFont.systemFont(ofSize: 11)
tips.backgroundColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 0.7)
tips.textColor = UIColor.black
tips.textAlignment = .center
//tips.isHidden = true
profileIcon.addSubview(tips)
tips.snp.makeConstraints({ (make) in
make.left.bottom.right.equalToSuperview()
make.height.equalTo(20)
})
profileIcon.reactive.controlEvents(.touchUpInside).observeValues({ (btn) in
///从相册中获取新图片
//btn.setImage(#imageLiteral(resourceName: "toolbar_me_sel"), for: .normal)
})
return profileIcon
}()
let nameLB = { () -> UILabel in
let name = UILabel()
name.text = "24K纯帅"
name.font = UIFont.systemFont(ofSize: 20)
headerView.addSubview(name)
name.snp.makeConstraints({ (make) in
make.top.equalTo(iconBtn.snp.top).offset(-10)
make.left.equalTo(iconBtn.snp.right).offset(15)
make.right.equalToSuperview().offset(-80)
make.height.equalTo(30)
})
return name
}()
let expView = { () -> UIView in
let experience = UIView()
experience.clipsToBounds = true
headerView.addSubview(experience)
experience.snp.makeConstraints({ (make) in
make.top.equalTo(nameLB.snp.bottom).offset(5)
make.left.equalTo(nameLB.snp.left)
make.right.equalTo(-30)
make.height.equalTo(10)
})
experience.layer.cornerRadius = 5
experience.layer.backgroundColor = UIColor.gray.cgColor
///可以用UIView,同时可以用snpkit
let expLayer = CALayer()
expLayer.backgroundColor = THEME_COLOR.cgColor
experience.layer.addSublayer(expLayer)
expLayer.frame = CGRect(x: 0, y: 0, width: 100, height: 10)
return experience
}()
let idLB = { () -> UILabel in
let id = UILabel()
id.text = "IDX: 12345678"
id.font = UIFont.systemFont(ofSize: 15)
headerView.addSubview(id)
id.snp.makeConstraints({ (make) in
make.top.equalTo(expView.snp.bottom).offset(5)
make.left.equalTo(nameLB.snp.left)
make.right.equalToSuperview().offset(-20)
make.height.equalTo(30)
})
return id
}()
let describeLB = { () -> UILabel in
let describe = UILabel()
describe.text = "欢迎来到英雄联盟,敌军还有30秒钟到达战场。"
describe.font = UIFont.systemFont(ofSize: 14)
describe.numberOfLines = 0
headerView.addSubview(describe)
describe.snp.makeConstraints({ (make) in
make.top.equalTo(idLB.snp.bottom).offset(5)
make.left.equalTo(nameLB.snp.left)
make.right.equalToSuperview().offset(-15)
make.height.equalTo(50)
})
return describe
}()
_ = {
let container = UIView()
headerView.addSubview(container)
container.snp.makeConstraints({ (make) in
make.left.bottom.right.equalToSuperview()
make.top.equalTo(describeLB.snp.bottom)
})
let subscribeNum = UIButton()
subscribeNum.setTitle("关注:103", for: .normal)
subscribeNum.titleLabel?.font = UIFont.systemFont(ofSize: 14)
container.addSubview(subscribeNum)
subscribeNum.snp.makeConstraints({ (make) in
make.top.left.bottom.equalToSuperview()
make.width.equalToSuperview().dividedBy(3.33)
})
let fansNum = UIButton()
fansNum.setTitle("粉丝:4508万", for: .normal)
fansNum.titleLabel?.font = UIFont.systemFont(ofSize: 14)
container.addSubview(fansNum)
fansNum.snp.makeConstraints({ (make) in
make.top.bottom.equalToSuperview()
make.left.equalTo(subscribeNum.snp.right)
make.width.equalToSuperview().dividedBy(3.33)
})
let liveHour = UIButton()
liveHour.setTitle("直播时长:342小时", for: .normal)
liveHour.titleLabel?.font = UIFont.systemFont(ofSize: 14)
container.addSubview(liveHour)
liveHour.snp.makeConstraints({ (make) in
make.top.bottom.equalToSuperview()
make.left.equalTo(fansNum.snp.right)
make.right.equalToSuperview()
})
}()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 3
case 1:
return 2
default:
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
///no resuse
let cell = UITableViewCell(style: .value1, reuseIdentifier: "mineCell")
cell.textLabel?.text = self.itemsTitle[indexPath.section][indexPath.row]
cell.accessoryType = .disclosureIndicator
cell.selectionStyle = .none
if indexPath.section == 0 && indexPath.row == 0 {
cell.imageView?.image = #imageLiteral(resourceName: "me_new_zhanghao")
cell.detailTextLabel?.text = "130~ Billion"
cell.detailTextLabel?.textColor = NORMAL_TEXT_COLOR
cell.detailTextLabel?.font = UIFont.systemFont(ofSize: 12)
}
else if indexPath.section == 1 && indexPath.row == 0 {
cell.imageView?.image = #imageLiteral(resourceName: "me_new_shouyi")
cell.detailTextLabel?.text = "20~ million"
cell.detailTextLabel?.textColor = NORMAL_TEXT_COLOR
cell.detailTextLabel?.font = UIFont.systemFont(ofSize: 12)
}
else {
cell.imageView?.image = #imageLiteral(resourceName: "good5_30x30")
}
return cell
}
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.
}
*/
}
|
mit
|
1ce47353059d5dff5f48c528f1f5273b
| 35.291667 | 106 | 0.541906 | 4.788106 | false | false | false | false |
eeschimosu/ActionButton
|
Example/ActionButton/ViewController.swift
|
2
|
1930
|
// ViewController.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 ActionButton
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class ViewController: UIViewController {
var actionButton: ActionButton!
override func viewDidLoad() {
super.viewDidLoad()
let twitterImage = UIImage(named: "twitter_icon.png")!
let plusImage = UIImage(named: "googleplus_icon.png")!
let twitter = ActionButtonItem(title: "Twitter", image: twitterImage)
twitter.action = { item in println("Twitter...") }
let google = ActionButtonItem(title: "Google Plus", image: plusImage)
google.action = { item in println("Google Plus...") }
actionButton = ActionButton(attachedToView: self.view, items: [twitter, google])
actionButton.action = { button in button.toggleMenu() }
}
}
|
mit
|
116ce7817c1a62a69d349778482b6396
| 40.06383 | 88 | 0.706736 | 4.673123 | false | false | false | false |
Roommate-App/roomy
|
roomy/Pods/IBAnimatable/Sources/Enums/BorderSide.swift
|
3
|
1443
|
//
// Created by Jake Lin on 12/9/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import Foundation
public enum BorderSide: String {
case top
case right
case bottom
case left
}
public struct BorderSides: OptionSet {
public let rawValue: Int
public static let unknown = BorderSides(rawValue: 0)
public static let top = BorderSides(rawValue: 1)
public static let right = BorderSides(rawValue: 1 << 1)
public static let bottom = BorderSides(rawValue: 1 << 2)
public static let left = BorderSides(rawValue: 1 << 3)
public static let AllSides: BorderSides = [.top, .right, .bottom, .left]
public init(rawValue: Int) {
self.rawValue = rawValue
}
init(rawValue: String?) {
guard let rawValue = rawValue, !rawValue.isEmpty else {
self = .AllSides
return
}
let sideElements = rawValue.lowercased().characters.split(separator: ",")
.map(String.init)
.map { BorderSide(rawValue: $0.trimmingCharacters(in: CharacterSet.whitespaces)) }
.map { BorderSides(side: $0) }
guard !sideElements.contains(.unknown) else {
self = .AllSides
return
}
self = BorderSides(sideElements)
}
init(side: BorderSide?) {
guard let side = side else {
self = .unknown
return
}
switch side {
case .top: self = .top
case .right: self = .right
case .bottom: self = .bottom
case .left: self = .left
}
}
}
|
mit
|
a45eb4c2782bde392a13561d0a58818c
| 21.888889 | 88 | 0.649098 | 3.835106 | false | false | false | false |
algolia/algoliasearch-client-swift
|
Sources/AlgoliaSearchClient/Helpers/Coding/Wrappers/StringNumberContainer.swift
|
1
|
1024
|
//
// StringNumberContainer.swift
//
//
// Created by Vladislav Fitc on 06/04/2020.
//
import Foundation
/**
Helper structure ensuring the decoding of a number value from a "volatile" JSON
occasionally providing number values in the form of String
*/
struct StringNumberContainer: RawRepresentable, Codable {
let rawValue: Double
var intValue: Int {
return Int(rawValue)
}
var floatValue: Float {
return Float(rawValue)
}
init(rawValue: Double) {
self.rawValue = rawValue
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let doubleValue = try? container.decode(Double.self) {
self.rawValue = doubleValue
return
}
if let doubleFromString = Double(try container.decode(String.self)) {
self.rawValue = doubleFromString
return
}
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Value cannot be decoded neither to Double nor to String representing Double value")
}
}
|
mit
|
4954d8774b186eb032db6586f6c76cd8
| 22.813953 | 160 | 0.708984 | 4.471616 | false | false | false | false |
HideOnBushTuT/AutoLayoutViewsTest
|
AutoLayoutViewsTest/AutoLayoutViewsTest/ViewController.swift
|
1
|
2838
|
//
// ViewController.swift
// AutoLayoutViewsTest
//
// Created by HideOnBush on 2017/5/27.
// Copyright © 2017年 HideOnBush. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController {
private var views: [UIView]? = [UIView]()
private var numberOfViews: Int? {
didSet {
scrollView.contentSize = CGSize(width: 0, height: numberOfViews! * 240 + 20)
addViews()
}
}
override func viewDidLoad() {
super.viewDidLoad()
layoutViews()
}
private func layoutViews() {
view.addSubview(scrollView)
scrollView.snp.makeConstraints { (make) in
make.left.right.bottom.equalToSuperview().offset(0)
make.top.equalToSuperview().offset(20)
}
}
fileprivate lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.isScrollEnabled = true
return scrollView
}()
private func addViews() {
for index in 0..<(numberOfViews ?? 1) {
let vview = UIView()
vview.tag = 100 + index
vview.backgroundColor = .orange
//将view添加到数组中
views?.append(vview)
//将view添加到scrollview中
scrollView.addSubview(vview)
}
for index in 0..<(views?.count)! {
if index == 0 {
let view = views?[index]
view?.snp.makeConstraints({ (make) in
make.top.equalToSuperview().offset(20)
make.centerX.equalToSuperview()
make.width.height.equalTo(202)
})
} else if index == ((views?.count)! - 1) {
let preView = views?[index - 1]
let newView = views?[index]
newView?.snp.makeConstraints({ (make) in
make.bottom.equalToSuperview().offset(-20)
make.top.equalTo((preView?.snp.bottom)!).offset(20)
make.centerX.equalToSuperview()
make.width.equalTo(202)
make.height.equalTo((preView?.snp.height)!)
})
} else {
let preView = views?[index - 1]
let newView = views?[index]
newView?.snp.makeConstraints({ (make) in
make.top.equalTo((preView?.snp.bottom)!).offset(20)
make.centerX.equalToSuperview()
make.height.equalTo((preView?.snp.height)!)
make.width.equalTo(202)
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
4073d39f3143f595876a7b3b64e8ed38
| 29.89011 | 88 | 0.523301 | 4.922942 | false | false | false | false |
collinsrj/QRCodeReader
|
QRCodeReader/ViewController.swift
|
1
|
3483
|
//
// ViewController.swift
// QRCodeReader
//
// Created by Robert Collins on 30/11/2015.
// Copyright © 2015 Robert Collins. All rights reserved.
//
import UIKit
import AVFoundation
import Dispatch
class ViewController: UIViewController {
private var captureSession: AVCaptureSession?
private var videoPreviewLayer: AVCaptureVideoPreviewLayer?
private var isReading: Bool = false {
didSet {
let buttonText = isReading ? "Stop" : "Start"
startStopButton.setTitle(buttonText, for: .normal)
}
}
@IBOutlet weak var previewView: UIView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var startStopButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func start() {
if isReading {
stopReading()
} else {
let _ = startReading()
self.statusLabel.text = ""
}
}
/**
Setup the capture session and display the preview allowing users to locate the QR code.
*/
private func startReading() -> Bool {
guard let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else {
return false
}
let input = getCaptureDeviceInput(device: captureDevice)
let captureSession = AVCaptureSession()
captureSession.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession.addOutput(captureMetadataOutput)
let dispatchQueue = DispatchQueue(label:"myQueue", attributes: .concurrent)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatchQueue)
captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
videoPreviewLayer = AVCaptureVideoPreviewLayer.init(session: captureSession)
videoPreviewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer?.frame = previewView.layer.bounds
previewView.layer.addSublayer(videoPreviewLayer!)
captureSession.startRunning()
isReading = true
return true
}
/**
Stop reading from the capture session.
*/
func stopReading() {
guard let _ = captureSession else {
return
}
captureSession?.stopRunning()
captureSession = nil
videoPreviewLayer?.removeFromSuperlayer()
isReading = false
}
/**
Get the input from the device.
- parameter device: A capture device
- returns: An optional input from the capture device
*/
private func getCaptureDeviceInput(device: AVCaptureDevice) -> AVCaptureDeviceInput? {
do {
let input = try AVCaptureDeviceInput.init(device: device)
return input
} catch {
return nil
}
}
}
extension ViewController: AVCaptureMetadataOutputObjectsDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
guard metadataObjects.count > 0, let metadataObject = metadataObjects[0] as? AVMetadataMachineReadableCodeObject, metadataObject.type == AVMetadataObjectTypeQRCode else {
return
}
DispatchQueue.main.async {
self.stopReading()
self.statusLabel.text = metadataObject.stringValue
}
}
}
|
apache-2.0
|
8f0b2935eb358009fcff20752658fd0a
| 30.654545 | 178 | 0.656232 | 5.911715 | false | false | false | false |
teroxik/open-muvr
|
ios/Lift/LiveSessionController.swift
|
3
|
7814
|
import Foundation
import UIKit
@objc
protocol MultiDeviceSessionSettable {
func multiDeviceSessionEncoding(session: MultiDeviceSession)
func mutliDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedBetween start: CFAbsoluteTime, and end: CFAbsoluteTime)
}
class LiveSessionController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, ExerciseSessionSettable,
DeviceSessionDelegate, DeviceDelegate, MultiDeviceSessionDelegate {
private var multi: MultiDeviceSession?
private var timer: NSTimer?
private var startTime: NSDate?
private var exerciseSession: ExerciseSession?
private var pageViewControllers: [UIViewController] = []
private var pageControl: UIPageControl!
@IBOutlet var stopSessionButton: UIBarButtonItem!
// MARK: main
override func viewWillDisappear(animated: Bool) {
if let x = timer { x.invalidate() }
navigationItem.prompt = nil
pageControl.removeFromSuperview()
pageControl = nil
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction
func stopSession() {
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Really?".localized()
stopSessionButton.tag = 3
} else {
end()
}
}
func end() {
if let x = exerciseSession {
x.end(const(()))
self.exerciseSession = nil
} else {
NSLog("[WARN] LiveSessionController.end() with sessionId == nil")
}
multi?.stop()
UIApplication.sharedApplication().idleTimerDisabled = false
if let x = navigationController {
x.popToRootViewControllerAnimated(true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
let pagesStoryboard = UIStoryboard(name: "LiveSession", bundle: nil)
pageViewControllers = ["classification", "devices", "sensorDataGroup"].map { pagesStoryboard.instantiateViewControllerWithIdentifier($0) as UIViewController }
setViewControllers([pageViewControllers.first!], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
if let nc = navigationController {
let navBarSize = nc.navigationBar.bounds.size
let origin = CGPoint(x: navBarSize.width / 2, y: navBarSize.height / 2 + navBarSize.height / 4)
pageControl = UIPageControl(frame: CGRect(x: origin.x, y: origin.y, width: 0, height: 0))
pageControl.numberOfPages = 3
nc.navigationBar.addSubview(pageControl)
}
multiDeviceSessionEncoding(multi)
// propagate to children
if let session = exerciseSession {
pageViewControllers.foreach { e in
if let s = e as? ExerciseSessionSettable {
s.setExerciseSession(session)
}
}
}
startTime = NSDate()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "tick", userInfo: nil, repeats: true)
}
func tick() {
let elapsed = Int(NSDate().timeIntervalSinceDate(startTime!))
let minutes: Int = elapsed / 60
let seconds: Int = elapsed - minutes * 60
navigationItem.prompt = "LiveSessionController.elapsed".localized(minutes, seconds)
stopSessionButton.tag -= 1
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Stop".localized()
}
}
// MARK: ExerciseSessionSettable
func setExerciseSession(session: ExerciseSession) {
self.exerciseSession = session
multi = MultiDeviceSession(delegate: self, deviceDelegate: self, deviceSessionDelegate: self)
multi!.start()
UIApplication.sharedApplication().idleTimerDisabled = true
}
private func multiDeviceSessionEncoding(session: MultiDeviceSession?) {
if let x = session {
viewControllers.foreach { e in
if let s = e as? MultiDeviceSessionSettable {
s.multiDeviceSessionEncoding(x)
}
}
}
}
private func multiDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedBetween start: CFAbsoluteTime, and end: CFAbsoluteTime) {
viewControllers.foreach { e in
if let s = e as? MultiDeviceSessionSettable {
s.mutliDeviceSession(session, continuousSensorDataEncodedBetween: start, and: end)
}
}
}
// MARK: UIPageViewControllerDataSource
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
if let x = (pageViewControllers.indexOf { $0 === viewController }) {
if x < pageViewControllers.count - 1 { return pageViewControllers[x + 1] }
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
if let x = (pageViewControllers.indexOf { $0 === viewController }) {
if x > 0 { return pageViewControllers[x - 1] }
}
return nil
}
// MARK: UIPageViewControllerDelegate
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [AnyObject], transitionCompleted completed: Bool) {
if let x = (pageViewControllers.indexOf { $0 === pageViewController.viewControllers.first! }) {
pageControl.currentPage = x
}
}
// MARK: MultiDeviceSessionDelegate
func multiDeviceSession(session: MultiDeviceSession, encodingSensorDataGroup group: SensorDataGroup) {
multiDeviceSessionEncoding(multi)
}
func multiDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedRange range: TimeRange) {
multiDeviceSession(session, continuousSensorDataEncodedBetween: range.start, and: range.end)
}
// MARK: DeviceSessionDelegate
func deviceSession(session: DeviceSession, endedFrom deviceId: DeviceId) {
end()
}
func deviceSession(session: DeviceSession, sensorDataNotReceivedFrom deviceId: DeviceId) {
// ???
}
func deviceSession(session: DeviceSession, sensorDataReceivedFrom deviceId: DeviceId, atDeviceTime: CFAbsoluteTime, data: NSData) {
if let x = exerciseSession {
x.submitData(data, f: const(()))
if UIApplication.sharedApplication().applicationState != UIApplicationState.Background {
multiDeviceSessionEncoding(multi)
}
} else {
RKDropdownAlert.title("Internal inconsistency", message: "AD received, but no sessionId.", backgroundColor: UIColor.orangeColor(), textColor: UIColor.blackColor(), time: 3)
}
}
// MARK: DeviceDelegate
func deviceGotDeviceInfo(deviceId: DeviceId, deviceInfo: DeviceInfo) {
multiDeviceSessionEncoding(multi)
}
func deviceGotDeviceInfoDetail(deviceId: DeviceId, detail: DeviceInfo.Detail) {
multiDeviceSessionEncoding(multi)
}
func deviceAppLaunched(deviceId: DeviceId) {
//
}
func deviceAppLaunchFailed(deviceId: DeviceId, error: NSError) {
//
}
func deviceDidNotConnect(error: NSError) {
multiDeviceSessionEncoding(multi)
}
func deviceDisconnected(deviceId: DeviceId) {
multiDeviceSessionEncoding(multi)
}
}
|
apache-2.0
|
4b43f583a67b2e3a1ac943878a95474e
| 36.932039 | 184 | 0.658178 | 5.437717 | false | false | false | false |
mckaskle/FlintKit
|
FlintKit/UIKit/UIColor+FlintKit.swift
|
1
|
3237
|
//
// MIT License
//
// UIColor+FlintKit.swift
//
// Copyright (c) 2017 Devin McKaskle
//
// 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
fileprivate enum UIColorError: Error {
case couldNotGenerateImage
}
extension UIColor {
// MARK: - Object Lifecycle
/// Supported formats are: #abc, #abcf, #aabbcc, #aabbccff where:
/// - a: red
/// - b: blue
/// - c: green
/// - f: alpha
public convenience init?(hexadecimal: String) {
var normalized = hexadecimal
if normalized.hasPrefix("#") {
normalized = String(normalized.dropFirst())
}
var characterCount = normalized.count
if characterCount == 3 || characterCount == 4 {
// Double each character.
normalized = normalized.lazy.map { "\($0)\($0)" }.joined()
// Character count has doubled.
characterCount *= 2
}
if characterCount == 6 {
// If alpha was not included, add it.
normalized.append("ff")
characterCount += 2
}
// If the string is not 8 characters at this point, it could not be normalized.
guard characterCount == 8 else { return nil }
let scanner = Scanner(string: normalized)
var value: UInt32 = 0
guard scanner.scanHexInt32(&value) else { return nil }
let red = CGFloat((value & 0xFF000000) >> 24) / 255
let green = CGFloat((value & 0xFF0000) >> 16) / 255
let blue = CGFloat((value & 0xFF00) >> 8) / 255
let alpha = CGFloat(value & 0xFF) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
// MARK: - Public Methods
public func image(withSize size: CGSize) throws -> UIImage {
var alpha: CGFloat = 1
if !getRed(nil, green: nil, blue: nil, alpha: &alpha) {
alpha = 1
}
UIGraphicsBeginImageContextWithOptions(size, alpha == 1, 0)
defer { UIGraphicsEndImageContext() }
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(cgColor)
context?.fill(CGRect(origin: .zero, size: size))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
throw UIColorError.couldNotGenerateImage
}
return image
}
}
|
mit
|
6003d75b972015c02a9d4225b831877b
| 30.735294 | 83 | 0.670683 | 4.304521 | false | false | false | false |
beobyte/UpdateLocStrings
|
UpdateLocStrings/MergeService/MergeService.swift
|
1
|
4487
|
//
// MergeService.swift
// UpdateLocStrings
//
// Created by Anton Grachev on 27/06/2017.
// Copyright © 2017 Anton Grachev. All rights reserved.
//
import Foundation
final public class MergeService {
// MARK: - Private properties
private let outputDirectory: String
private let stringsFileExtension = ".strings"
private let backupFileExtension = ".backup"
// MARK: - Init
init(outputDirectory: String) {
self.outputDirectory = outputDirectory
}
// MARK: - Public methods
func prepareForMerge() throws {
let originalFiles = findFiles(with: stringsFileExtension)
guard originalFiles.count > 0 else {
return
}
try backupStringsFiles(originalFiles)
}
func performMerge() throws {
let stringsFiles = findFiles(with: stringsFileExtension)
for file in stringsFiles {
let filePath = outputDirectory.appending("/\(file)")
let backupFilePath = filePath.appending(backupFileExtension)
try mergeFile(atPath: filePath, withBackupPath: backupFilePath)
}
try completeMerge()
}
// MARK: - Private methods
// MARK: Work with files
private func findFiles(with fileExtension: String) -> [String] {
do {
let files = try FileManager.default.contentsOfDirectory(atPath: outputDirectory)
return files.filter { $0.hasSuffix(fileExtension) }
}
catch {
print("\(type(of: self)): \(error)")
return []
}
}
private func backupStringsFiles(_ files: [String]) throws {
for file in files {
let filePath = outputDirectory.appending("/\(file)")
let backupPath = filePath.appending(backupFileExtension)
try FileManager.default.moveItem(atPath: filePath, toPath: backupPath)
}
}
private func moveUnusedBackupFiles(_ files: [String]) throws {
for backupFile in files {
let fileName = backupFile.replacingOccurrences(of: backupFileExtension, with: "")
try FileManager.default.moveItem(atPath: outputDirectory.appending("/\(backupFile)"),
toPath: outputDirectory.appending("/\(fileName)"))
}
}
// MARK: Merge
private func mergeFile(atPath path: String, withBackupPath backupPath: String) throws {
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: path), fileManager.fileExists(atPath: backupPath) else {
return
}
let localizedStrings = try StringsFileParser.parse(contentOf: path)
let backupStrings = try StringsFileParser.parse(contentOf: backupPath)
var resultStrings: [LocalizedString] = []
for string in localizedStrings {
let updatedString = updateStringIfNeeded(string, with: backupStrings)
resultStrings.append(updatedString)
}
try serializeStrings(resultStrings, to: path)
try fileManager.removeItem(atPath: backupPath)
}
private func updateStringIfNeeded(_ string: LocalizedString, with backupStrings: [LocalizedString]) -> LocalizedString {
if let existString = findLocalizedString(with: string.key, in: backupStrings) {
let updatedString = LocalizedString(comment: string.comment, key: string.key, value: existString.value)
return updatedString
}
return string
}
private func findLocalizedString(with key: String, in strings: [LocalizedString]) -> LocalizedString? {
for string in strings {
if string.key == key {
return string
}
}
return nil
}
private func serializeStrings(_ strings: [LocalizedString], to filePath: String) throws {
var content = ""
strings.forEach {
content.append($0.description)
content.append("\n\n")
}
try content.write(toFile: filePath, atomically: true, encoding: .utf16)
}
private func completeMerge() throws {
let backupFiles = findFiles(with: backupFileExtension)
guard backupFiles.count > 0 else {
return
}
try moveUnusedBackupFiles(backupFiles)
}
}
|
mit
|
75b28a11a9544fd8b49f5aa78a420000
| 30.815603 | 124 | 0.604993 | 5.277647 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.