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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
L3-DANT/findme-app | findme/Controller/RegisterViewController.swift | 1 | 5853 | //
// RegisterViewController.swift
// findme
//
// Created by Maxime Signoret on 05/05/16.
// Copyright © 2016 Maxime Signoret. All rights reserved.
//
import UIKit
class RegisterViewController: UIViewController {
let wsBaseUrl = APICommunicator.getInstance.getBaseUrl()
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var phoneNumberField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var confirmPasswordField: UITextField!
@IBOutlet weak var pulseView: UIImageView!
@IBOutlet weak var registerAnimationView: UIImageView!
@IBAction func registerButton(sender: AnyObject) {
let username:NSString = self.usernameField.text!
let phoneNumber:NSString = self.phoneNumberField.text!
let password:NSString = self.passwordField.text!
let confirm_password:NSString = self.confirmPasswordField.text!
if (username.isEqualToString("") || phoneNumber.isEqualToString("") || password.isEqualToString("") || confirm_password.isEqualToString("")) {
UIAlert("Sign Up Failed!", message: "Please enter Username and Password")
} else if ( !password.isEqual(confirm_password) ) {
UIAlert("Sign Up Failed!", message: "Passwords doesn't Match")
}
if (!checkPhoneNumber(phoneNumber as String)) {
UIAlert("Sign Up Failed!", message: "Invalid phone number")
} else {
do {
let params: [String: String] = ["pseudo": username as String, "phoneNumber": phoneNumber as String, "password": password as String]
let apiService = APIService()
apiService.signUp(params, onCompletion: { user, err in
dispatch_async(dispatch_get_main_queue()) {
if user != nil {
let vc : UIViewController = (self.storyboard!.instantiateViewControllerWithIdentifier("MapViewController") as? MapViewController)!
self.showViewController(vc as UIViewController, sender: vc)
} else {
self.UIAlert("Sign Up Failed!", message: "Wrong username or password")
}
}
})
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
var imageName : String = ""
var imageList : [UIImage] = []
for i in 0...9 {
imageName = "FindMe_intro_0000\(i)"
imageList.append(UIImage(named: imageName)!)
}
for i in 10...69 {
imageName = "FindMe_intro_000\(i)"
imageList.append(UIImage(named: imageName)!)
}
self.registerAnimationView.animationImages = imageList
startAniamtion()
}
func checkPhoneNumber(phoneNumber: String) -> Bool {
let PHONE_REGEX = "(0|(\\+33)|(0033))[1-9][0-9]{8}"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluateWithObject(phoneNumber)
return result
}
func startAniamtion() {
self.registerAnimationView.animationDuration = 2
self.registerAnimationView.animationRepeatCount = 1
self.registerAnimationView.startAnimating()
_ = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(self.startPulse), userInfo: nil, repeats: false)
}
func startPulse() {
let pulseEffect = PulseAnimation(repeatCount: Float.infinity, radius:100, position: CGPoint(x: self.pulseView.center.x-72, y: self.pulseView.center.y-20))
pulseEffect.backgroundColor = UIColor(colorLiteralRed: 0.33, green: 0.69, blue: 0.69, alpha: 1).CGColor
view.layer.insertSublayer(pulseEffect, below: self.registerAnimationView.layer)
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBarHidden = true
}
func keyboardWillShow(notification: NSNotification) {
let userInfo: [NSObject : AnyObject] = notification.userInfo!
let keyboardSize: CGSize = userInfo[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
let offset: CGSize = userInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue.size
if keyboardSize.height == offset.height {
if self.view.frame.origin.y == 0 {
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.view.frame.origin.y -= keyboardSize.height
})
}
} else {
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.view.frame.origin.y += keyboardSize.height - offset.height
})
}
print(self.view.frame.origin.y)
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
self.view.frame.origin.y += keyboardSize.height
}
}
func UIAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
}
| mit | c6bb7c87f97780bb8266ad22b4ad93c3 | 42.348148 | 176 | 0.62782 | 5.146878 | false | false | false | false |
liuchungui/BGPhotoPickerController | BGPhotoPickerController/Views/BGPhotoGrideCell.swift | 1 | 1245 | //
// BGPhotoGrideCell.swift
// BGPhotoPickerControllerDemo
//
// Created by user on 15/10/13.
// Copyright © 2015年 BG. All rights reserved.
//
import UIKit
class BGPhotoGrideCell: UICollectionViewCell {
private var isDidSelect = false
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var selectImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.borderWidth = 0.3
self.layer.masksToBounds = true
self.isSelect = false
self.selectImageView.hidden = false
}
//MARK: var value
var image: UIImage? {
get {
return self.imageView.image
}
set(newImage) {
self.imageView.image = newImage
}
}
var isSelect: Bool {
get {
return self.isDidSelect
}
set(newValue) {
self.isDidSelect = newValue
if newValue {
self.selectImageView.image = UIImage(named: "ImageSelectedOn.png")
}
else {
self.selectImageView.image = UIImage(named: "ImageSelectedOff.png")
}
}
}
}
| mit | 86a67f3739c85efb1c9e65af008e88b6 | 24.875 | 83 | 0.582126 | 4.583026 | false | false | false | false |
yuByte/SwiftGo | Examples/Examples.playground/Pages/16. Chinese Whispers.xcplaygroundpage/Contents.swift | 4 | 542 | import SwiftGo
//: Chinese Whispers
//: ----------------
//:
//: 
func whisper(left: ReceivingChannel<Int>, _ right: SendingChannel<Int>) {
left <- 1 + !<-right
}
let numberOfWhispers = 100
let leftmost = Channel<Int>()
var right = leftmost
var left = leftmost
for _ in 0 ..< numberOfWhispers {
right = Channel<Int>()
go(whisper(left.receivingChannel, right.sendingChannel))
left = right
}
go(right <- 1)
print(!<-leftmost)
| mit | 88a808a38b1dbbe114952c814ae9ce37 | 22.565217 | 102 | 0.669742 | 3.325153 | false | false | false | false |
warumono-for-develop/SwiftPageViewController | SwiftPageViewController/SwiftPageViewController/IntroViewController.swift | 1 | 2078 | //
// IntroViewController.swift
// Maniau1
//
// Created by kevin on 2017. 2. 24..
// Copyright © 2017년 warumono. All rights reserved.
//
import UIKit
class IntroViewController: UIViewController
{
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var containerView: UIView!
fileprivate var introPageViewController: IntroPageViewController?
{
didSet
{
introPageViewController?.introPageViewControllerDataSource = self
introPageViewController?.introPageViewControllerDelegate = self
}
}
override var preferredStatusBarStyle: UIStatusBarStyle
{
return .lightContent
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
pageControl.addTarget(self, action: #selector(IntroViewController.didChangePage), for: .valueChanged)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if let introPageViewController = segue.destination as? IntroPageViewController
{
self.introPageViewController = introPageViewController
}
}
}
extension IntroViewController
{
@IBAction func didTouch(_ sender: UIButton)
{
if sender.tag == 0
{
if pageControl.numberOfPages <= pageControl.currentPage + 1
{
return
}
introPageViewController?.pageTo(at: pageControl.numberOfPages - 1)
}
else if sender.tag == 1
{
introPageViewController?.next()
}
}
@objc fileprivate func didChangePage()
{
introPageViewController?.pageTo(at: pageControl.currentPage)
}
}
extension IntroViewController: IntroPageViewControllerDataSource
{
func introPageViewController(_ pageViewController: IntroPageViewController, numberOfPages pages: Int)
{
pageControl.numberOfPages = pages
}
}
extension IntroViewController: IntroPageViewControllerDelegate
{
func introPageViewController(_ pageViewController: IntroPageViewController, didChangePageIndex index: Int)
{
pageControl.currentPage = index
}
}
| mit | 2dddf7d357d54e30ad4f8ecaee123dd9 | 21.311828 | 107 | 0.760482 | 4.350105 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Sources/FeatureKYCUI/Identity Verification/KYCResubmitIdentityRouter.swift | 1 | 994 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import FeatureKYCDomain
import PlatformKit
import PlatformUIKit
/// Router for handling the KYC document resubmission flow
public final class KYCResubmitIdentityRouter: DeepLinkRouting {
private let settings: KYCSettingsAPI
private let kycRouter: KYCRouterAPI
public init(
settings: KYCSettingsAPI = resolve(),
kycRouter: KYCRouterAPI = resolve()
) {
self.settings = settings
self.kycRouter = kycRouter
}
public func routeIfNeeded() -> Bool {
// Only route if the user actually tapped on the resubmission link
guard settings.didTapOnDocumentResubmissionDeepLink else {
return false
}
guard let viewController = UIApplication.shared.topMostViewController else {
return false
}
kycRouter.start(tier: .tier2, parentFlow: .resubmission, from: viewController)
return true
}
}
| lgpl-3.0 | 0d36f2d4526d481fb7fa12124f6e59e1 | 28.205882 | 86 | 0.690836 | 5.118557 | false | false | false | false |
eternityz/RWScrollChart | RWScrollChart/RWSCAppearance.swift | 1 | 1974 | //
// RWSCAppearance.swift
// RWScrollChartDemo
//
// Created by Zhang Bin on 2015-08-04.
// Copyright (c) 2015年 Zhang Bin. All rights reserved.
//
import UIKit
struct RWSCAppearance {
var backgroundColor = UIColor.clearColor()
var contentMargins = UIEdgeInsets(top: 0.0, left: 15.0, bottom: 5.0, right: 30.0)
var backgroundLineWidth: CGFloat = 0.5
var horizontalLineColor = UIColor(white: 1.0, alpha: 0.1)
var showSectionTitles = true
var showSectionSeparator = true
var sectionPadding: CGFloat = 1.0
var sectionTitleFont = UIFont.systemFontOfSize(12.0)
var sectionTitleInsets = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 10.0, right: 5.0)
var sectionTitleColor = UIColor.whiteColor()
var sectionSeparatorColor = UIColor(white: 1.0, alpha: 0.5)
var truncateSectionTitleWhenNeeded = false
var itemPadding: CGFloat = 1.0
var itemWidth: CGFloat = 15.0
var showFocus = true
var focusTextFont = UIFont.systemFontOfSize(12.0)
var focusTextColor = UIColor(white: 0.2, alpha: 1.0)
var focusTextBackgroundColor = UIColor.whiteColor()
var focusTextMargin = CGPoint(x: 6.0, y: 1.0)
var focusTextLineCount = 1
var focusIndicatorRadius: CGFloat = 4.0
var focusColor = UIColor.whiteColor()
var focusStrokeWidth: CGFloat = 1.0
var focusNeedleLength: CGFloat = 5.0
var focusBubbleRoundedRadius: CGFloat = 2.0
var showAxis = true
var axisTextFont = UIFont.systemFontOfSize(10.0)
var axisTextColor = UIColor.whiteColor()
var axisBackgroundColor = UIColor(white: 0, alpha: 0.2)
var axisTextMargin = CGPoint(x: 5.0, y: 2.0)
var axisAreaWidthForViewWith: CGFloat -> CGFloat = { min(50.0, 0.2 * $0) }
var axisLineColor = UIColor(white: 1.0, alpha: 0.05)
var axisLineWidth: CGFloat = 1.0
enum InitialPosition {
case FirstItem
case LastItem
}
var initialPosition: InitialPosition = .LastItem
}
| mit | 5eef9a2a9a5cbea6d26ffeb420320238 | 33 | 88 | 0.685091 | 3.741935 | false | false | false | false |
BellAppLab/SequencePlayer | Source/SequencePlayer.swift | 1 | 22828 | import UIKit
import AVFoundation
//MARK: Consts
private var sequencePlayerContext = 0
//MARK: - Delegate and Data Source
protocol SequencePlayerDelegate: class {
func sequencePlayerStateDidChange(_ player: SequencePlayer)
func sequencePlayerDidEnd(_ player: SequencePlayer)
}
@objc protocol SequencePlayerDataSource: class {
func numberOfItemsInSequencePlayer(_ player: SequencePlayer) -> Int
func sequencePlayer(_ player: SequencePlayer, itemURLAtIndex index: Int) -> URL
@objc optional func sequencePlayerView(forSequencePlayer player: SequencePlayer) -> SequencePlayerView
}
//MARK: - Player Controls
//MARK: -
extension SequencePlayer
{
func play(atIndex index: Int? = nil) {
guard self.state != .playing else { return }
var didChangeIndex = false
if let i = index {
guard i > -1 && i < self.dataSource.numberOfItemsInSequencePlayer(self) else {
fatalError("Sequence Player index out of bounds... Index: \(index)")
}
self.currentIndex = i
didChangeIndex = true
} else {
if self.currentIndex == NSNotFound {
self.currentIndex = 0
didChangeIndex = true
}
}
if self.player == nil {
self.player = AVQueuePlayer()
}
self.dataSource.sequencePlayerView?(forSequencePlayer: self).player = self.player
if didChangeIndex {
self.player?.pause()
}
if let _ = self.player?.currentItem {
self.player?.play()
self.state = .playing
return
}
self.prefetch()
}
func pause() {
self.player?.pause()
self.state = .paused
}
func next() {
guard self.dataSource.numberOfItemsInSequencePlayer(self) > self.currentIndex + 1 else { self.reload(); return }
self.play(atIndex: self.currentIndex + 1)
}
func previous() {
guard self.currentIndex - 1 > -1 else { self.reload(); return }
self.play(atIndex: self.currentIndex - 1)
}
fileprivate func resumePlayback() {
if state != .playing {
// self.isProgressTimerActive = true
self.play()
}
}
}
//MARK: - Main Implementation
//MARK: -
class SequencePlayer: NSObject
{
//MARK:
enum State: Int, CustomStringConvertible
{
case ready = 0
case playing
case paused
case loading
case failed
var description: String {
get{
switch self
{
case .ready:
return "Ready"
case .playing:
return "Playing"
case .failed:
return "Failed"
case .paused:
return "Paused"
case .loading:
return "Loading"
}
}
}
}
fileprivate(set) var state: State = .ready {
didSet {
guard state != oldValue else { return }
switch state {
case .failed, .ready:
self.isBackgroundTaskActive = false
self.isAudioSessionActive = false
default:
self.isBackgroundTaskActive = true
self.isAudioSessionActive = true
}
self.delegate?.sequencePlayerStateDidChange(self)
}
}
//MARK: - Setup
static var cacheAge: TimeInterval = 3600 * 24 * 7
static var numberOfItemsToPrefetch = 3
deinit{
self.pause()
self.currentIndex = NSNotFound
self.isAudioSessionActive = false
// self.isProgressTimerActive = false
self.isBackgroundTaskActive = false
NotificationCenter.default.removeObserver(self)
self.playerItems.forEach { (item) in
item.removeObserver(self,
forKeyPath: #keyPath(AVPlayerItem.status),
context: &sequencePlayerContext)
}
}
init(withDataSource dataSource: SequencePlayerDataSource, andDelegate delegate: SequencePlayerDelegate? = nil) {
self.dataSource = dataSource
self.delegate = delegate
}
private(set) weak var dataSource: SequencePlayerDataSource!
private(set) weak var delegate: SequencePlayerDelegate?
fileprivate var hasSetUp = false
func reload() {
self.pause()
self.state = .ready
self.currentIndex = NSNotFound
self.isAudioSessionActive = false
// self.isProgressTimerActive = false
self.isBackgroundTaskActive = false
NotificationCenter.default.removeObserver(self)
self.playerItems.forEach { (item) in
item.removeObserver(self,
forKeyPath: #keyPath(AVPlayerItem.status),
context: &sequencePlayerContext)
}
self.playerItems = []
self.player?.removeAllItems()
self.currentlyDownloadingURLs = []
}
//MARK: - Playing
fileprivate var player: AVQueuePlayer?
var items: [AVPlayerItem]? {
return self.player?.items()
}
var currentItem: AVPlayerItem? {
return self.player?.currentItem
}
fileprivate(set) var currentIndex: Int = NSNotFound {
didSet {
guard currentIndex != oldValue && currentIndex != NSNotFound else { return }
func shouldStartLoading() -> Bool {
if oldValue == NSNotFound {
return true
}
return abs(currentIndex - oldValue) >= SequencePlayer.numberOfItemsToPrefetch
}
if shouldStartLoading() {
self.state = .loading
}
}
}
var volume: Float {
get {
return self.player?.volume ?? 0
}
set {
self.player?.volume = newValue
}
}
//MARK: Progress
// private var progressObserver: AnyObject!
//
// fileprivate var isProgressTimerActive: Bool = false {
// didSet {
// guard isProgressTimerActive != oldValue else { return }
//
// if isProgressTimerActive {
// guard let currentItem = self.currentItem, currentItem.duration.isValid == true else { return }
// self.progressObserver = self.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(0.05, Int32(NSEC_PER_SEC)),
// queue: nil)
// { [weak self] (time : CMTime) -> Void in
// self?.timerAction(withTime: time)
// } as AnyObject!
// } else {
// guard let player = self.player, let observer = self.progressObserver else { return }
// player.removeTimeObserver(observer)
// self.progressObserver = nil
// }
// }
// }
//MARK: - Background Task Id
private var backgroundTaskId = UIBackgroundTaskInvalid
fileprivate var isBackgroundTaskActive: Bool = false {
didSet {
guard (self.backgroundTaskId == UIBackgroundTaskInvalid && isBackgroundTaskActive) || (self.backgroundTaskId != UIBackgroundTaskInvalid && !isBackgroundTaskActive) else { return }
guard isBackgroundTaskActive != oldValue else { return }
if isBackgroundTaskActive {
self.backgroundTaskId = UIApplication.shared.beginBackgroundTask { [weak self] _ in
guard let identifier = self?.backgroundTaskId else { return }
UIApplication.shared.endBackgroundTask(identifier)
self?.backgroundTaskId = UIBackgroundTaskInvalid
}
} else {
UIApplication.shared.endBackgroundTask(self.backgroundTaskId)
self.backgroundTaskId = UIBackgroundTaskInvalid
}
}
}
//MARK: - Audio Session
fileprivate var isAudioSessionActive: Bool = false {
didSet {
guard isAudioSessionActive != oldValue else { return }
if isAudioSessionActive {
NotificationCenter.default.addObserver(self,
selector: #selector(handleStall),
name: NSNotification.Name.AVPlayerItemPlaybackStalled,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(handleAudioSessionInterruption),
name: NSNotification.Name.AVAudioSessionInterruption,
object: AVAudioSession.sharedInstance())
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setMode(AVAudioSessionModeDefault)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("Audio Session Activation Error: \(error)")
}
} else {
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name.AVPlayerItemPlaybackStalled,
object: nil)
NotificationCenter.default.removeObserver(self,
name: NSNotification.Name.AVAudioSessionInterruption,
object: AVAudioSession.sharedInstance())
do {
try AVAudioSession.sharedInstance().setActive(false)
} catch {
print("Audio Session Deactivation Error: \(error)")
}
}
}
}
@objc private func handleStall() {
self.player?.pause()
self.player?.play()
}
// private func timerAction(withTime time: CMTime) {
// guard self.currentItem != nil else { return }
// self.delegate?.player(self,
// progressDidChangeWithTime: time)
// }
@objc private func handleAudioSessionInterruption(_ notification : Notification) {
guard let userInfo = notification.userInfo as? [String: AnyObject] else { return }
guard let rawInterruptionType = userInfo[AVAudioSessionInterruptionTypeKey] as? NSNumber else { return }
guard let interruptionType = AVAudioSessionInterruptionType(rawValue: rawInterruptionType.uintValue) else { return }
switch interruptionType {
case .began: //interruption started
self.player?.pause()
case .ended: //interruption ended
if let rawInterruptionOption = userInfo[AVAudioSessionInterruptionOptionKey] as? NSNumber {
let interruptionOption = AVAudioSessionInterruptionOptions(rawValue: rawInterruptionOption.uintValue)
if interruptionOption == AVAudioSessionInterruptionOptions.shouldResume {
self.resumePlayback()
}
}
}
}
//MARK: - Downloading
fileprivate lazy var downloadQueue: OperationQueue = {
let result = OperationQueue()
result.name = "SequencePlayerQueue"
result.maxConcurrentOperationCount = 1
return result
}()
fileprivate lazy var fileQueue: OperationQueue = {
let result = OperationQueue()
result.name = "SequencePlayerFileQueue"
result.maxConcurrentOperationCount = 1
return result
}()
fileprivate(set) lazy var urlSession: URLSession = {
let configuration = URLSessionConfiguration.background(withIdentifier: "SequencePlayer")
configuration.requestCachePolicy = .returnCacheDataElseLoad
configuration.networkServiceType = .video
let result = URLSession(configuration: configuration,
delegate: self,
delegateQueue: self.downloadQueue)
return result
}()
fileprivate lazy var currentlyDownloadingURLs = [URL]()
//MARK: - KVO
fileprivate lazy var playerItems = [AVPlayerItem]()
@objc fileprivate func itemDidPlayToEnd(_ notification: Notification) {
guard self.currentIndex + 1 < self.dataSource.numberOfItemsInSequencePlayer(self) else {
self.delegate?.sequencePlayerDidEnd(self)
self.reload()
return
}
self.currentIndex += 1
self.prefetch()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// Only handle observations for the playerItemContext
guard context == &sequencePlayerContext else {
super.observeValue(forKeyPath: keyPath,
of: object,
change: change,
context: context)
return
}
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
// Get the status change from the change dictionary
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
// Switch over the status
switch status {
case .readyToPlay:
// Player item is ready to play.
if self.state != .playing {
self.player?.play()
self.state = .playing
}
case .failed:
if self.state == .playing {
self.pause()
}
case .unknown:
// Player item is not yet ready.
break
}
}
}
}
//MARK: - Downloading
//MARK: -
fileprivate extension SequencePlayer
{
var documentsURL: URL? {
let bundleId = Bundle.main.bundleIdentifier ?? "com.bellapplab"
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last?.appendingPathComponent("\(bundleId).SequencePlayer").standardizedFileURL
}
func prefetch() {
guard self.currentIndex != NSNotFound else { fatalError("Sequence Player: We need to set the current index before prefetching!") }
guard let documentsURL = self.documentsURL, let dataSource = self.dataSource else { return }
let currentIndex = self.currentIndex
let total = self.dataSource.numberOfItemsInSequencePlayer(self)
let manager = FileManager.default
func setUpCacheFolder() {
guard !self.hasSetUp else { return }
if !manager.fileExists(atPath: documentsURL.path) {
do {
try manager.createDirectory(at: documentsURL, withIntermediateDirectories: true, attributes: nil)
} catch {
fatalError("Sequence Player couldn't not create its root folder... \(error)")
}
}
do {
let files = try manager.contentsOfDirectory(at: documentsURL,
includingPropertiesForKeys: [.contentAccessDateKey],
options: [.skipsPackageDescendants, .skipsSubdirectoryDescendants, .skipsHiddenFiles])
let cacheDate = Date(timeIntervalSinceNow: -1 * SequencePlayer.cacheAge)
for file in files {
if let date = try file.resourceValues(forKeys: [.contentAccessDateKey]).contentAccessDate {
if date.timeIntervalSince(cacheDate) <= 0 {
try manager.removeItem(at: file)
}
}
}
} catch {
fatalError("Sequence Player: Something went wrong while enumerating files... \(error)")
}
self.hasSetUp = true
}
func isAlreadyDownloading(_ remoteURL: URL) -> Bool {
for url in self.currentlyDownloadingURLs {
if url == remoteURL {
return true
}
}
return false
}
func isAlreadyInPlayer(_ localURL: URL) -> Bool {
guard let player = self.player else { return false }
for item in player.items() {
if let asset = item.asset as? AVURLAsset {
if asset.url == localURL {
return true
}
}
}
return false
}
self.fileQueue.addOperation { [weak self] _ in
setUpCacheFolder()
var i = 0
var operations = [Operation]()
while i < SequencePlayer.numberOfItemsToPrefetch && currentIndex + i < total {
let remoteURL = dataSource.sequencePlayer(self!, itemURLAtIndex: currentIndex + i)
let localURL = documentsURL.appendingPathComponent(remoteURL.lastPathComponent)
if !isAlreadyDownloading(remoteURL) && !manager.fileExists(atPath: localURL.path) {
self?.currentlyDownloadingURLs.append(remoteURL)
let task = self?.urlSession.downloadTask(with: remoteURL)
operations.append(BlockOperation(block: {
task?.resume()
}))
} else if !isAlreadyInPlayer(localURL) {
self?.didFinishDownloadingFile(toURL: localURL)
}
i += 1
}
self?.downloadQueue.addOperations(operations, waitUntilFinished: false)
}
}
func didFinishDownloadingFile(toURL url: URL) {
let item = AVPlayerItem(asset: AVURLAsset(url: url))
self.playerItems.append(item)
self.player?.insert(item, after: nil)
item.addObserver(self,
forKeyPath: #keyPath(AVPlayerItem.status),
options: [.new],
context: &sequencePlayerContext)
NotificationCenter.default.addObserver(self,
selector: #selector(SequencePlayer.itemDidPlayToEnd(_:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: item)
}
}
//MARK: URL Session Data Delegate
extension SequencePlayer: URLSessionDataDelegate, URLSessionDownloadDelegate
{
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
guard let response = proposedResponse.response as? HTTPURLResponse, let url = response.url, var headers = response.allHeaderFields as? [String: String] else { return }
var cachedResponse: CachedURLResponse
if response.allHeaderFields["Cache-Control"] == nil {
headers["Cache-Control"] = "max-age=\(SequencePlayer.cacheAge)"
if let newResponse = HTTPURLResponse(url: url,
statusCode: response.statusCode,
httpVersion: "HTTP/1.1",
headerFields: headers)
{
cachedResponse = CachedURLResponse(response: newResponse,
data: proposedResponse.data,
userInfo: proposedResponse.userInfo,
storagePolicy: proposedResponse.storagePolicy)
} else {
cachedResponse = proposedResponse
}
} else {
cachedResponse = proposedResponse
}
completionHandler(cachedResponse)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let data = try? Data(contentsOf: location), let documentsURL = self.documentsURL, let fileName = downloadTask.originalRequest?.url?.lastPathComponent else { return }
let manager = FileManager.default
let finalURL = documentsURL.appendingPathComponent(fileName)
manager.createFile(atPath: finalURL.path, contents: data, attributes: nil)
for (index, existingURL) in self.currentlyDownloadingURLs.enumerated() {
if finalURL == existingURL {
self.currentlyDownloadingURLs.remove(at: index)
}
}
DispatchQueue.main.async { [weak self] _ in
self?.didFinishDownloadingFile(toURL: finalURL)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
dLog("Sequence Player Download error: \(error)")
}
}
}
//MARK: - Player View
//MARK: -
class SequencePlayerView: UIView
{
var player: AVPlayer? {
get {
return playerLayer.player
}
set {
playerLayer.player = newValue
}
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
// Override UIView property
override static var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
//MARK: - Aux
//MARK: -
public func dLog(_ message: @autoclosure () -> String, filename: String = #file, function: String = #function, line: Int = #line) {
#if DEBUG
debugPrint("[\(URL(string: filename)?.lastPathComponent):\(line)]", "\(function)", message(), separator: " - ")
#else
#endif
}
| mit | b28b8125894afe926a20b950f9e53375 | 36.361702 | 191 | 0.546259 | 6.090715 | false | false | false | false |
lacklock/NiceGesture | NiceGesture/NCGesturePromise.swift | 1 | 2652 | //
// NCGesturePromise.swift
// NiceGesture
//
// Created by 卓同学 on 16/4/3.
// Copyright © 2016年 zhuo. All rights reserved.
//
import UIKit
public class NCGesturePromise<T:UIGestureRecognizer>: NSObject {
public typealias ncGestureHandler = (gestureRecognizer:T)->Void
var beganHandler:ncGestureHandler = { _ in }
var cancelledHandler:ncGestureHandler = { _ in }
var changedHandler:ncGestureHandler = { _ in }
var endedHandler:ncGestureHandler = { _ in }
var failedHandler:ncGestureHandler = { _ in }
override init(){
super.init()
}
func gesureRecognizerHandler(gestureRecognizer:UIGestureRecognizer){
switch gestureRecognizer.state {
case .Began:
beganHandler(gestureRecognizer: gestureRecognizer as! T)
case .Cancelled:
cancelledHandler(gestureRecognizer: gestureRecognizer as! T)
case .Changed:
changedHandler(gestureRecognizer: gestureRecognizer as! T)
case .Ended:
endedHandler(gestureRecognizer: gestureRecognizer as! T)
case .Failed:
failedHandler(gestureRecognizer: gestureRecognizer as! T)
case .Possible:
break
}
}
/**
one handler for many states
- parameter states: UIGestureRecognizerStates
*/
public func whenStatesHappend(states:[UIGestureRecognizerState],handler:ncGestureHandler)->NCGesturePromise<T>{
for state in states{
switch state {
case .Began:
beganHandler=handler
case .Cancelled:
cancelledHandler=handler
case .Changed:
changedHandler=handler
case .Ended:
endedHandler=handler
case .Failed:
failedHandler=handler
case .Possible:
break
}
}
return self
}
public func whenBegan(handler:ncGestureHandler)->NCGesturePromise<T>{
beganHandler=handler
return self
}
public func whenCancelled(handler:ncGestureHandler)->NCGesturePromise<T>{
cancelledHandler=handler
return self
}
public func whenChanged(handler:ncGestureHandler)->NCGesturePromise<T>{
changedHandler=handler
return self
}
public func whenEnded(handler:ncGestureHandler)->NCGesturePromise<T>{
endedHandler=handler
return self
}
public func whenFailed(handler:ncGestureHandler)->NCGesturePromise<T>{
failedHandler=handler
return self
}
}
| mit | bbdadfdea82f36c5180c84c63342f6ba | 26.53125 | 115 | 0.617102 | 5.50625 | false | false | false | false |
swipe-org/swipe | network/SwipePrefetcher.swift | 2 | 5443 | //
// SwipePrefetcher.swift
// sample
//
// Created by satoshi on 10/12/15.
// Copyright © 2015 Satoshi Nakajima. All rights reserved.
//
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
private func MyLog(_ text:String, level:Int = 0) {
let s_verbosLevel = 0
if level <= s_verbosLevel {
NSLog(text)
}
}
class SwipePrefetcher {
private var urls = [URL:String]()
private var urlsFetching = [URL]()
private var urlsFetched = [URL:URL]()
private var urlsFailed = [URL]()
private var errors = [NSError]()
private var fComplete = false
private var _progress = Float(0)
var progress:Float {
return _progress
}
init(urls:[URL:String]) {
self.urls = urls
}
func start(_ callback:@escaping (Bool, [URL], [NSError]) -> Void) {
if fComplete {
MyLog("SWPrefe already completed", level:1)
callback(true, self.urlsFailed, self.errors)
return
}
let manager = SwipeAssetManager.sharedInstance()
var count = 0
_progress = 0
let fileManager = FileManager.default
for (url,prefix) in urls {
if url.scheme == "file" {
if fileManager.fileExists(atPath: url.path) {
urlsFetched[url] = url
} else {
// On-demand resource support
urlsFetched[url] = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil)
MyLog("SWPrefe onDemand resource at \(String(describing:urlsFetched[url])) instead of \(url)", level:1)
}
} else {
count += 1
urlsFetching.append(url)
manager.loadAsset(url, prefix: prefix, bypassCache:false, callback: { (urlLocal:URL?, error:NSError?) -> Void in
if let urlL = urlLocal {
self.urlsFetched[url] = urlL
} else {
self.urlsFailed.append(url)
if let error = error {
self.errors.append(error)
}
}
count -= 1
if (count == 0) {
self.fComplete = true
self._progress = 1
MyLog("SWPrefe completed \(self.urlsFetched.count)", level: 1)
callback(true, self.urlsFailed, self.errors)
} else {
self._progress = Float(self.urls.count - count) / Float(self.urls.count)
callback(false, self.urlsFailed, self.errors)
}
})
}
}
if count == 0 {
self.fComplete = true
self._progress = 1
callback(true, urlsFailed, errors)
}
}
func append(_ urls:[URL:String], callback:@escaping (Bool, [URL], [NSError]) -> Void) {
let manager = SwipeAssetManager.sharedInstance()
var count = 0
_progress = 0
let fileManager = FileManager.default
for (url,prefix) in urls {
self.urls[url] = prefix
if url.scheme == "file" {
if fileManager.fileExists(atPath: url.path) {
urlsFetched[url] = url
} else {
// On-demand resource support
urlsFetched[url] = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil)
MyLog("SWPrefe onDemand resource at \(String(describing: urlsFetched[url])) instead of \(url)", level:1)
}
} else {
count += 1
urlsFetching.append(url)
manager.loadAsset(url, prefix: prefix, bypassCache:false, callback: { (urlLocal:URL?, error:NSError?) -> Void in
if let urlL = urlLocal {
self.urlsFetched[url] = urlL
} else if let error = error {
self.urlsFailed.append(url)
self.errors.append(error)
}
count -= 1
if (count == 0) {
self.fComplete = true
self._progress = 1
MyLog("SWPrefe completed \(self.urlsFetched.count)", level: 1)
callback(true, self.urlsFailed, self.errors)
} else {
self._progress = Float(self.urls.count - count) / Float(self.urls.count)
callback(false, self.urlsFailed, self.errors)
}
})
}
}
if count == 0 {
self.fComplete = true
self._progress = 1
callback(true, urlsFailed, errors)
}
}
func map(_ url:URL) -> URL? {
return urlsFetched[url]
}
static func extensionForType(_ memeType:String) -> String {
let ext:String
if memeType == "video/quicktime" {
ext = ".mov"
} else if memeType == "video/mp4" {
ext = ".mp4"
} else {
ext = ""
}
return ext
}
static func isMovie(_ mimeType:String) -> Bool {
return mimeType == "video/quicktime" || mimeType == "video/mp4"
}
}
| mit | c90bd6f42eed6ee704ea55e442a45844 | 34.109677 | 128 | 0.483462 | 4.876344 | false | false | false | false |
niceagency/Contentful | Contentful/Contentful/ContentfulTypes.swift | 1 | 2775 | //
// ContentfulTypes.swift
// DeviceManagement
//
// Created by Sam Woolf on 24/10/2017.
// Copyright © 2017 Nice Agency. All rights reserved.
//
import Foundation
public typealias UnboxedFields = [String:Any?]
public typealias FieldMapping = [String:(UnboxedType,Bool)]
public typealias WriteRequest = (data: Data?, endpoint: String, headers: [(String,String)], method: HttpMethod)
public protocol Readable {
static func contentfulEntryType() -> String
static func unboxer() -> (FieldMapping)
static func creator(withFields fields: UnboxedFields) -> Self
}
public protocol Writeable {
var contentful_id: String { get }
var contentful_version: Int { get}
}
public typealias Encodable = Swift.Encodable & Writeable
public enum HttpMethod {
case put
case post
case delete
}
public enum ReferenceType : String {
case entry = "Entry"
}
public struct Reference : Codable {
private struct Sys: Codable {
let type: String = "Link"
let linkType : String
let id : String
}
private let sys: Sys
public var id: String {
return sys.id
}
public func getObjectWithId<T: Writeable> (fromCandidates candidates: [T]) -> T? {
return candidates.first(where: { $0.contentful_id == self.id })
}
public init (forObject object: Writeable, type: ReferenceType = .entry ) {
self.sys = Sys(linkType: type.rawValue, id: object.contentful_id)
}
init (withId id: String, type: String) {
self.sys = Sys(linkType: type, id: id )
}
}
public enum DecodingError: Error {
case typeMismatch(String, UnboxedType)
case requiredKeyMissing(String)
case fieldFormatError(String)
case missingRequiredFields([String])
public func errorMessage() -> String {
switch self {
case .typeMismatch(let type):
return ("wrong type: \(String(describing: type))")
case .requiredKeyMissing(let string):
return ("missing required field \(string)")
case .fieldFormatError:
return ("field format error")
case .missingRequiredFields(let fields ):
return ("missing required fields \(fields)")
}
}
}
public enum Result<T> {
case success(T)
case error(Swift.DecodingError)
}
public struct SysData {
public let id: String
public let version: Int
}
public struct PagedResult<T> {
public let validItems: [T]
public let failedItems: [(Int, DecodingError)]
public let page: Page
}
public enum ItemResult<T> {
case success(T)
case error (DecodingError)
}
public enum UnboxedType {
case string
case int
case date
case decimal
case bool
case oneToOneRef
case oneToManyRef
}
| mit | 4cd41a9fdf500815d68844b7e38d676d | 23.548673 | 113 | 0.652848 | 4.190332 | false | false | false | false |
SwiftStudies/OysterKit | Sources/STLR/Generators/Framework/TextFile.swift | 1 | 3807 | // Copyright (c) 2018, RED When Excited
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
/// Captures the output of a source generator
public class TextFile : Operation {
/// Writes the file at the specified location
public func perform(in context: OperationContext) throws {
let writeTo = context.workingDirectory.appendingPathComponent(name)
do {
try content.write(to: writeTo, atomically: true, encoding: .utf8)
} catch {
throw OperationError.error(message: "Failed to write file \(writeTo) \(error.localizedDescription)")
}
context.report("Wrote \(writeTo.path)")
}
/// The desired name of the file, including an extension. Any path elements will be considered relative
/// a location known by the consumer of the TextFile
public var name : String
public private(set) var content : String = ""
private var tabDepth : Int = 0
/**
Creates a new instance
- Parameter name: The name of the textfile
*/
public init(_ name:String){
self.name = name
}
/**
Appends the supplied items to the text file at the current tab depth
- Parameter terminator: An optional terminator to use. By default it is \n
- Parameter separator: An optional separator to use between items/ Defaults to a newline
- Parameter prefix: An optional prefex to add to each supplied item
- Parameter items: One or more Strings to be appended to the file
- Returns: Itself for chaining
*/
@discardableResult
public func print(terminator:String = "\n", separator:String = "\n", prefix : String = "", _ items:String...)->TextFile{
var first = true
for item in items {
if !first {
content += separator
} else {
first = false
}
content += "\(String(repeating: " ", count: tabDepth))\(prefix)\(item)"
}
content += terminator
return self
}
/// Indents subsequent output
/// - Returns: Itself for chaining
@discardableResult
public func indent()->TextFile{
tabDepth += 1
return self
}
/// Outdents subsequent output
/// - Returns: Itself for chaining
@discardableResult
public func outdent()->TextFile{
tabDepth -= 1
return self
}
}
| bsd-2-clause | 2da0e4ebf36110de29b29d6c30d38b35 | 36.323529 | 124 | 0.65222 | 4.931347 | false | false | false | false |
roambotics/swift | test/Reflection/typeref_decoding.swift | 2 | 27556 | // REQUIRES: no_asan
// rdar://100805115
// UNSUPPORTED: CPU=arm64e
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -enable-anonymous-context-mangled-names %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect)
// RUN: %target-build-swift -Xfrontend -enable-anonymous-context-mangled-names %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift %S/Inputs/main.swift -emit-module -emit-executable -module-name TypesToReflect -o %t/TypesToReflect
// RUN: %target-swift-reflection-dump %t/%target-library-name(TypesToReflect) | %FileCheck %s
// RUN: %target-swift-reflection-dump %t/TypesToReflect | %FileCheck %s
// CHECK: FIELDS:
// CHECK: =======
// CHECK: TypesToReflect.Box
// CHECK: ------------------
// CHECK: item: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: anEnum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: aTupleWithLabels: (a: TypesToReflect.C, s: TypesToReflect.S, e: TypesToReflect.E)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithVarArgs: (TypesToReflect.C, TypesToReflect.S...) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (variadic
// CHECK: (struct TypesToReflect.S))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout1: (inout TypesToReflect.C) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (inout
// CHECK: (class TypesToReflect.C))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout2: (TypesToReflect.C, inout Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (inout
// CHECK: (struct Swift.Int))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout3: (inout TypesToReflect.C, inout Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (inout
// CHECK: (class TypesToReflect.C))
// CHECK: (inout
// CHECK: (struct Swift.Int))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithShared: (__shared TypesToReflect.C) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (shared
// CHECK: (class TypesToReflect.C))
// CHECK: (result
// CHECK: (tuple))
// CHECK: TypesToReflect.S
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.Box<TypesToReflect.S>, TypesToReflect.Box<TypesToReflect.E>, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: (struct Swift.Int))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithThinRepresentation: @convention(thin) () -> ()
// CHECK: (function convention=thin
// CHECK: (tuple))
// CHECK: aFunctionWithCRepresentation: @convention(c) () -> ()
// CHECK: (function convention=c
// CHECK: (tuple))
// CHECK: TypesToReflect.S.NestedS
// CHECK: ------------------------
// CHECK: aField: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: TypesToReflect.E
// CHECK: ----------------
// CHECK: Class: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: Struct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: Enum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: Function: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (tuple))
// CHECK: Tuple: (TypesToReflect.C, TypesToReflect.S, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (struct Swift.Int))
// CHECK: IndirectTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: NestedStruct: TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S))
// CHECK: Metatype
// CHECK: EmptyCase
// CHECK: TypesToReflect.References
// CHECK: -------------------------
// CHECK: strongRef: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: weakRef: weak Swift.Optional<TypesToReflect.C>
// CHECK: (weak_storage
// CHECK: (bound_generic_enum Swift.Optional
// CHECK: (class TypesToReflect.C)))
// CHECK: unownedRef: unowned TypesToReflect.C
// CHECK: (unowned_storage
// CHECK: (class TypesToReflect.C))
// CHECK: unownedUnsafeRef: unowned(unsafe) TypesToReflect.C
// CHECK: (unmanaged_storage
// CHECK: (class TypesToReflect.C))
// CHECK: TypesToReflect.(PrivateStructField
// CHECK: ----------------------------------
// CHECK: TypesToReflect.HasArrayOfPrivateStructField
// CHECK: -------------------------------------------
// CHECK: x: Swift.Array<TypesToReflect.(PrivateStructField{{.*}})>
// CHECK: TypesToReflect.C1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, TypesToReflect.E1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: dependentMember: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, TypesToReflect.E2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.C3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, TypesToReflect.E3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.TypesToReflect.P2.Outer
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.C4
// CHECK: -----------------
// CHECK: TypesToReflect.S1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.Box<TypesToReflect.S1<A>>, TypesToReflect.Box<TypesToReflect.E1<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.S2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C2<A>) -> (TypesToReflect.S2<A>) -> (TypesToReflect.E2<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.Box<TypesToReflect.S2<A>>, TypesToReflect.Box<TypesToReflect.E2<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.S3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.Box<TypesToReflect.S3<A>>, TypesToReflect.Box<TypesToReflect.E3<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.TypesToReflect.P2.Outer
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.S4
// CHECK: -----------------
// CHECK: TypesToReflect.E1
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Int: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: Function: (A) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: Metatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E2
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S2<A>
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E2<A>
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberInner: A.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: ExistentialMetatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E3
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (metatype
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberOuter: A.TypesToReflect.P2.Outer
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: DependentMemberInner: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner
// CHECK: (dependent_member protocol=14TypesToReflect2P1P
// CHECK: (dependent_member protocol=14TypesToReflect2P2P
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.E4
// CHECK: -----------------
// CHECK: TypesToReflect.P1
// CHECK: -----------------
// CHECK: TypesToReflect.P2
// CHECK: -----------------
// CHECK: TypesToReflect.P3
// CHECK: -----------------
// CHECK: TypesToReflect.P4
// CHECK: -----------------
// CHECK: TypesToReflect.ClassBoundP
// CHECK: --------------------------
// CHECK: TypesToReflect.(FileprivateProtocol in {{.*}})
// CHECK: -------------------------------------------------------------------------
// CHECK: TypesToReflect.HasFileprivateProtocol
// CHECK: -------------------------------------
// CHECK: x: TypesToReflect.(FileprivateProtocol in {{.*}})
// CHECK: (protocol_composition
// CHECK-NEXT: (protocol TypesToReflect.(FileprivateProtocol in {{.*}})))
// CHECK: ASSOCIATED TYPES:
// CHECK: =================
// CHECK: - TypesToReflect.C1 : TypesToReflect.ClassBoundP
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P2
// CHECK: typealias Outer = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P3
// CHECK: typealias First = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: typealias Second = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.S : TypesToReflect.P4
// CHECK: typealias Result = Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: BUILTIN TYPES:
// CHECK: ==============
// CHECK: CAPTURE DESCRIPTORS:
// CHECK: ====================
// CHECK: - Capture types:
//CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (closure_binding index=1)
// CHECK: - Capture types:
// CHECK: (struct Swift.Int)
// CHECK: - Metadata sources:
// CHECK: - Capture types:
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=1))
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (generic_argument index=0
// CHECK: (reference_capture index=0))
| apache-2.0 | f25e97ada2dfd2db632050d17cc711d6 | 35.987919 | 331 | 0.667985 | 3.401975 | false | false | false | false |
livechat/chat-window-ios | Sources/ChatView.swift | 1 | 15848 | //
// ChatView.swift
// Example-Swift
//
// Created by Łukasz Jerciński on 06/03/2017.
// Copyright © 2017 LiveChat Inc. All rights reserved.
//
import Foundation
import WebKit
import UIKit
@objc protocol ChatViewDelegate : NSObjectProtocol {
func closedChatView()
func handle(URL: URL)
}
let iOSMessageHandlerName = "iosMobileWidget"
class ChatView : UIView, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler, UIScrollViewDelegate, LoadingViewDelegate {
private var webView : WKWebView?
private let loadingView = LoadingView()
weak var delegate : ChatViewDelegate?
private let jsonCache = JSONRequestCache()
private var animating = false
var configuration : LiveChatConfiguration? {
didSet {
if let configuration = configuration {
if oldValue != configuration {
reloadWithDelay()
}
}
}
}
var customVariables : CustomVariables? {
didSet {
reloadWithDelay()
}
}
var webViewBridge : WebViewBridge? {
didSet {
if let webViewBridge = webViewBridge {
webViewBridge.webView = webView
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(frame: CGRect) {
super.init(frame: frame)
let configuration = WKWebViewConfiguration()
configuration.mediaTypesRequiringUserActionForPlayback = []
configuration.allowsInlineMediaPlayback = true
let contentController = WKUserContentController()
contentController.add(self, name:iOSMessageHandlerName)
configuration.userContentController = contentController
#if SwiftPM
let bundle = Bundle.module
#else
let bundle = Bundle(for: ChatView.self)
#endif
var scriptContent : String?
do {
if let path = bundle.path(forResource: "LiveChatWidget", ofType: "js") {
scriptContent = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
}
} catch {
print("Exception while injecting LiveChatWidget.js script")
}
let script = WKUserScript(source: scriptContent!, injectionTime: .atDocumentStart, forMainFrameOnly: true)
contentController.addUserScript(script)
webView = WKWebView(frame: frame, configuration: configuration)
if let webView = webView {
addSubview(webView)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
webView.uiDelegate = self
webView.scrollView.minimumZoomScale = 1.0
webView.scrollView.maximumZoomScale = 1.0
webView.isOpaque = false
webView.backgroundColor = UIColor.white
webView.frame = frame
webView.alpha = 0
}
backgroundColor = UIColor.clear
loadingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
loadingView.delegate = self
loadingView.frame = bounds
loadingView.startAnimation()
addSubview(loadingView)
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(applicationDidBecomeActiveNotification), name: UIApplication.didBecomeActiveNotification
, object: nil)
nc.addObserver(self, selector: #selector(applicationWillResignActiveNotification), name: UIApplication.willResignActiveNotification, object: nil)
}
deinit {
if let webView = webView {
webView.scrollView.delegate = nil
webView.stopLoading()
webView.configuration.userContentController.removeScriptMessageHandler(forName:(iOSMessageHandlerName))
}
}
override func layoutSubviews() {
super.layoutSubviews()
if let webView = webView {
loadingView.frame = webView.frame
}
}
// MARK: Public Methods
func presentChat(animated: Bool, completion: ((Bool) -> Void)? = nil) {
guard let wv = webView else { return }
if !LiveChatState.isChatOpenedBefore() {
delayed_reload()
}
LiveChatState.markChatAsOpened()
let animations = {
wv.frame = self.frameForSafeAreaInsets()
self.loadingView.frame = wv.frame
wv.alpha = 1
}
let completion = { (finished : Bool) in
let fr = self.frameForSafeAreaInsets()
wv.frame = CGRect(origin: fr.origin, size: CGSize(width: fr.size.width, height: fr.size.height - 1))
DispatchQueue.main.asyncAfter(deadline:.now() + 0.1, execute: { [weak self] in
if let `self` = self {
if wv.alpha > 0 {
wv.frame = self.frameForSafeAreaInsets()
}
}
})
self.animating = false
if finished {
self.webViewBridge?.postFocusEvent()
}
if let completion = completion {
completion(finished)
}
}
if animated {
animating = true
wv.frame = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: bounds.size.height)
loadingView.frame = wv.frame
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [],
animations: animations,
completion: completion)
} else {
animations()
completion(true)
}
}
func dismissChat(animated: Bool, completion: ((Bool) -> Void)? = nil) {
guard let wv = webView else { return }
if animating {
return
}
wv.endEditing(true)
let animations = {
wv.frame = CGRect(x: 0, y: self.bounds.size.height, width: self.bounds.size.width, height: self.bounds.size.height)
self.loadingView.frame = wv.frame
wv.alpha = 0
}
let completion = { (finished : Bool) in
self.animating = false
if finished {
self.webViewBridge?.postBlurEvent()
self.chatHidden()
}
if let completion = completion {
completion(finished)
}
}
if animated {
animating = true
UIView.animate(withDuration: 0.2,
delay: 0,
options: [.curveEaseOut],
animations: animations,
completion: completion)
} else {
animations()
completion(true)
}
}
func clearSession() {
let dataStore = WKWebsiteDataStore.default()
dataStore.fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { (records) in
for record in records {
if record.displayName.contains("livechat") || record.displayName.contains("chat.io") {
dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), for: [record], completionHandler: {
self.reloadWithDelay()
})
}
}
}
}
private func chatHidden() {
delegate?.closedChatView()
}
// MARK: Application state management
@objc func applicationDidBecomeActiveNotification(_ notification: Notification) {
if let webView = self.webView, webView.alpha > 0 {
self.webViewBridge?.postFocusEvent()
}
}
@objc func applicationWillResignActiveNotification(_ notification: Notification) {
if let webView = self.webView, webView.alpha > 0 {
self.webViewBridge?.postBlurEvent()
}
}
// MARK: Keyboard frame changes
private func frameForSafeAreaInsets() -> CGRect {
var safeAreaInsets = UIEdgeInsets.zero
if #available(iOS 11.0, *) {
safeAreaInsets = self.safeAreaInsets
} else {
safeAreaInsets = UIEdgeInsets.init(top: UIApplication.shared.statusBarFrame.size.height, left: 0, bottom: 0, right: 0)
}
let frameForSafeAreaInsets = CGRect(x: safeAreaInsets.left, y: safeAreaInsets.top, width: bounds.size.width - safeAreaInsets.left - safeAreaInsets.right, height: bounds.size.height - safeAreaInsets.top - safeAreaInsets.bottom)
return frameForSafeAreaInsets
}
private func displayLoadingError(withMessage message: String) {
DispatchQueue.main.async(execute: { [weak self] in
if let `self` = self {
self.loadingView.displayLoadingError(withMessage: message)
}
})
}
@objc func delayed_reload() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(delayed_reload), object: nil)
if jsonCache.currentTask == nil || jsonCache.currentTask?.state != .running {
loadingView.alpha = 1.0
loadingView.startAnimation()
jsonCache.request(withCompletionHandler: { [weak self] (templateURL, error) in
DispatchQueue.main.async(execute: { [weak self] in
if let `self` = self {
if let error = error {
self.displayLoadingError(withMessage: error.localizedDescription)
return
}
guard let templateURL = templateURL else {
self.displayLoadingError(withMessage: "Template URL not provided.")
return
}
guard let configuration = self.configuration else {
self.displayLoadingError(withMessage: "Configuration not provided.")
return
}
let url = buildUrl(templateURL: templateURL, configuration: configuration, customVariables: self.customVariables, maxLength: 2000)
if let url = url, let wv = self.webView {
let request = URLRequest(url: url)
if #available(iOS 9.0, *) {
// Changing UserAgent string:
wv.evaluateJavaScript("navigator.userAgent") {(result, error) in
DispatchQueue.main.async(execute: {
if let userAgent = result as? String {
wv.customUserAgent = userAgent + " WebView_Widget_iOS/2.0.7"
if LiveChatState.isChatOpenedBefore() {
wv.load(request)
}
}
})
}
} else {
if LiveChatState.isChatOpenedBefore() {
wv.load(request)
}
}
} else {
print("error: Invalid url")
self.displayLoadingError(withMessage: "Invalid url")
}
}
})
})
}
}
// MARK: LoadingViewDelegate
func reloadWithDelay() {
self.perform(#selector(delayed_reload), with: nil, afterDelay: 0.2)
}
func reload() {
if let webView = webView {
self.loadingView.alpha = 1.0
self.loadingView.startAnimation()
webView.reload()
}
}
@objc func close() {
dismissChat(animated: true) { (finished) in
if finished {
if let delegate = self.delegate {
delegate.closedChatView()
}
}
}
}
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return nil // No zooming
}
// MARK: WKNavigationDelegate
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("Did fail navigation error: " + error.localizedDescription)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
if let URL = navigationAction.request.url ,
UIApplication.shared.canOpenURL(URL) {
if let delegate = self.delegate {
delegate.handle(URL: URL)
}
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
} else {
decisionHandler(.allow)
}
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
let error = error as NSError
loadingView.alpha = 1.0
if !(error.domain == NSURLErrorDomain && error.code == -999) {
loadingView.displayLoadingError(withMessage: error.localizedDescription)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if let webView = self.webView, webView.alpha == 0 {
self.webViewBridge?.postBlurEvent()
}
UIView.animate(withDuration: 0.3,
delay: 1.0,
options: UIView.AnimationOptions(),
animations: {
self.loadingView.alpha = 0
},
completion: { (finished) in
})
}
// MARK: WKUIDelegate
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if (navigationAction.targetFrame == nil) {
let popup = WKWebView(frame: webView.frame, configuration: configuration)
popup.uiDelegate = self
self.addSubview(popup)
return popup
}
return nil;
}
func webViewDidClose(_ webView: WKWebView) {
webView.removeFromSuperview()
}
@available(iOS 10.0, *)
func webView(_ webView: WKWebView, shouldPreviewElement elementInfo: WKPreviewElementInfo) -> Bool {
return false
}
// MARK: WKScriptMessageHandler
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if (message.body is NSDictionary) {
webViewBridge?.handle(message.body as! NSDictionary);
}
}
}
| mit | 6344d865f3d5a428ef49906419c53d87 | 35.011364 | 234 | 0.533165 | 5.868519 | false | false | false | false |
gaoleegin/DamaiPlayBusinessnormal | DamaiPlayBusinessPhone/DamaiPlayBusinessPhone/Classes/Tools/DMNetwork.swift | 1 | 1185 | //
// DMNetWork.swift
// DamaiPlayBusinessPhone
//
// Created by 高李军 on 15/10/28.
// Copyright © 2015年 DamaiPlayBusinessPhone. All rights reserved.
//
import UIKit
import Alamofire
import SVProgressHUD
class DMNetwork: NSObject {
class func requestJSON(method:Alamofire.Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
completion:(JSON: AnyObject?)->()){
//添加辅助参数
var mutaParams: [String: AnyObject] = ["platform":1,"source":10000,"version":10100]
for (key,value) in parameters! {
mutaParams[key] = value
}
Alamofire.request(method, URLString, parameters: mutaParams).responseJSON { (Response) in
if Response.result.isSuccess == false || Response.result.error != nil || Response.result.value == nil{
SVProgressHUD.showInfoWithStatus("数据出错")
}else{
completion(JSON: Response.result.value)
}
print(Response.debugDescription)
}
}
}
| apache-2.0 | 59a069e77e6154c4f5b9c46744947070 | 28.641026 | 118 | 0.564014 | 4.699187 | false | false | false | false |
artyom-stv/TextInputKit | TextInputKit/TextInputKit/Code/SpecializedTextInput/BankCardNumber/BankCardNumber.swift | 1 | 3633 | //
// BankCardNumber.swift
// TextInputKit
//
// Created by Artem Starosvetskiy on 25/11/2016.
// Copyright © 2016 Artem Starosvetskiy. All rights reserved.
//
import Foundation
public struct BankCardNumber {
/// An error thrown by `BankCardNumber` initializers.
///
/// - unexpectedCharacters: The provided string contains unexpected characters.
public enum InitializationError : Error {
case unexpectedCharacters
}
public let digitsString: String
public let formattedString: String
public let cardBrand: BankCardBrand?
/// Creates a `BankCardNumber` by string representation.
///
/// - Parameters:
/// - digitsString: The string of digits which represents a bank card number.
/// - Throws: `InitializationError.unexpectedCharacters` if the provided string contains non-digit characters.
public init(digitsString: String) throws {
guard digitsString.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil else {
throw InitializationError.unexpectedCharacters
}
let digitsStringView = digitsString.unicodeScalars
let digitsStringLength = digitsStringView.count
let iinRange = Utils.iinRange(
fromDigitsString: digitsString,
withLength: digitsStringLength)
let iinRangeInfo = Utils.info(forIinRange: iinRange)
let sortedSpacesPositions = Utils.sortedSpacesPositions(for: iinRangeInfo?.cardBrand)
let formattedStringView = Utils.cardNumberStringView(
fromDigits: digitsStringView,
withLength: digitsStringLength,
sortedSpacesPositions: sortedSpacesPositions)
self.init(
digitsString: digitsString,
formattedString: String(formattedStringView),
cardBrand: iinRangeInfo?.cardBrand)
}
fileprivate typealias Utils = BankCardNumberUtils
/// The memberwise initializer with reduced access level.
fileprivate init(
digitsString: String,
formattedString: String,
cardBrand: BankCardBrand?) {
self.digitsString = digitsString
self.formattedString = formattedString
self.cardBrand = cardBrand
}
}
extension BankCardNumber {
/// Creates a `BankCardNumber` by a formatted string which represents a bank card number.
///
/// - Note: For the internal use only.
///
/// - Parameters:
/// - formattedString: The formatted string which represents a bank card number.
init(formattedString: String) {
guard let digitsStringView = Utils.cardNumberDigitsStringView(from: formattedString.unicodeScalars) else {
fatalError("Unexpected characters in `formattedString` argument.")
}
let digitsString = String(digitsStringView)
// Length of ASCII string is similar in `characters` and in `unicodeScalars`.
let digitsStringLength = digitsStringView.count
let iinRange = Utils.iinRange(
fromDigitsString: digitsString,
withLength: digitsStringLength)
let iinRangeInfo = Utils.info(forIinRange: iinRange)
self.init(
digitsString: digitsString,
formattedString: formattedString,
cardBrand: iinRangeInfo?.cardBrand)
}
}
extension BankCardNumber: Equatable {
public static func ==(lhs: BankCardNumber, rhs: BankCardNumber) -> Bool {
return lhs.digitsString == rhs.digitsString
}
}
extension BankCardNumber: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(digitsString)
}
}
| mit | ca3ff977a949ce34f996ed4f1be9fdfc | 30.042735 | 114 | 0.681718 | 5.420896 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/ReferenceViewController.swift | 1 | 2784 | import Foundation
protocol ReferenceViewControllerDelegate: AnyObject {
var referenceWebViewBackgroundTapGestureRecognizer: UITapGestureRecognizer { get }
func referenceViewControllerUserDidTapClose(_ vc: ReferenceViewController)
func referenceViewControllerUserDidNavigateBackToReference(_ vc: ReferenceViewController)
}
class ReferenceViewController: ViewController {
weak var delegate: ReferenceViewControllerDelegate?
var referenceId: String? = nil
var referenceLinkText: String? = nil {
didSet {
updateTitle()
}
}
func updateTitle() {
guard let referenceLinkText = referenceLinkText else {
return
}
let titleFormat = WMFLocalizedString("article-reference-view-title", value: "Reference %@", comment: "Title for the reference view. %@ is replaced by the reference link name, for example [1].")
navigationItem.title = String.localizedStringWithFormat(titleFormat, referenceLinkText)
}
func setupNavbar() {
navigationBar.displayType = .modal
updateTitle()
navigationItem.rightBarButtonItem = closeButton
navigationItem.leftBarButtonItem = backToReferenceButton
apply(theme: self.theme)
}
// MARK: View Lifecycle
override func viewDidLoad() {
navigationMode = .forceBar
super.viewDidLoad()
setupNavbar()
}
// MARK: Actions
lazy var backToReferenceButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: UIImage(named: "references"), style: .plain, target: self, action: #selector(goBackToReference))
button.accessibilityLabel = WMFLocalizedString("reference-section-button-accessibility-label", value: "Jump to reference section", comment: "Voiceover label for the top button (that jumps to article's reference section) when viewing a reference's details")
return button
}()
lazy var closeButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: UIImage(named: "close-inverse"), style: .plain, target: self, action: #selector(closeButtonPressed))
button.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
return button
}()
@objc func closeButtonPressed() {
delegate?.referenceViewControllerUserDidTapClose(self)
}
@objc func goBackToReference() {
delegate?.referenceViewControllerUserDidNavigateBackToReference(self)
}
// MARK: Theme
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
closeButton.tintColor = theme.colors.secondaryText
backToReferenceButton.tintColor = theme.colors.link
}
}
| mit | 368d329335190e801046d854a01361f7 | 36.621622 | 264 | 0.69181 | 5.491124 | false | false | false | false |
intrahouse/aerogear-ios-http | AeroGearHttp/Http.swift | 1 | 30639 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/**
The HTTP method verb:
- GET: GET http verb
- HEAD: HEAD http verb
- DELETE: DELETE http verb
- POST: POST http verb
- PUT: PUT http verb
*/
public enum HttpMethod: String {
case get = "GET"
case head = "HEAD"
case delete = "DELETE"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
}
/**
The file request type:
- Download: Download request
- Upload: Upload request
*/
enum FileRequestType {
case download(String?)
case upload(UploadType)
}
/**
The Upload enum type:
- Data: for a generic NSData object
- File: for File passing the URL of the local file to upload
- Stream: for a Stream request passing the actual NSInputStream
*/
enum UploadType {
case data(Foundation.Data)
case file(URL)
case stream(InputStream)
}
/**
Error domain.
**/
public let HttpErrorDomain: String = "HttpDomain"
/**
Request error.
**/
public let NetworkingOperationFailingURLRequestErrorKey = "NetworkingOperationFailingURLRequestErrorKey"
/**
Response error.
**/
public let NetworkingOperationFailingURLResponseErrorKey = "NetworkingOperationFailingURLResponseErrorKey"
public typealias ProgressBlock = (Int64, Int64, Int64) -> Void
public typealias CompletionBlock = (Any?, NSError?) -> Void
/**
Main class for performing HTTP operations across RESTful resources.
*/
open class Http {
var baseURL: String?
var session: URLSession
var requestSerializer: RequestSerializer
var responseSerializer: ResponseSerializer
open var authzModule: AuthzModule?
open var disableServerTrust: Bool = false
fileprivate var delegate: SessionDelegate
/**
Initialize an HTTP object.
:param: baseURL the remote base URL of the application (optional).
:param: sessionConfig the SessionConfiguration object (by default it uses a defaultSessionConfiguration).
:param: requestSerializer the actual request serializer to use when performing requests.
:param: responseSerializer the actual response serializer to use upon receiving a response.
:returns: the newly intitialized HTTP object
*/
public init(baseURL: String? = nil,
sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default,
requestSerializer: RequestSerializer = JsonRequestSerializer(),
responseSerializer: ResponseSerializer = JsonResponseSerializer()) {
self.baseURL = baseURL
self.delegate = SessionDelegate()
self.session = URLSession(configuration: sessionConfig, delegate: self.delegate, delegateQueue: OperationQueue.main)
self.requestSerializer = requestSerializer
self.responseSerializer = responseSerializer
}
public init(baseURL: String? = nil,
sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default,
requestSerializer: RequestSerializer = JsonRequestSerializer(),
responseSerializer: ResponseSerializer = JsonResponseSerializer(),
disableServerTrust: Bool) {
self.baseURL = baseURL
self.delegate = SessionDelegate()
self.session = URLSession(configuration: sessionConfig, delegate: self.delegate, delegateQueue: OperationQueue.main)
self.requestSerializer = requestSerializer
self.responseSerializer = responseSerializer
self.disableServerTrust = disableServerTrust
self.delegate.disableServerTrust = disableServerTrust
}
deinit {
self.session.finishTasksAndInvalidate()
}
open func activateDisableServerTrust(){
disableServerTrust = true
self.delegate = SessionDelegate()
}
/**
Gateway to perform different http requests including multipart.
:param: url the url of the resource.
:param: parameters the request parameters.
:param: method the method to be used.
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func request(method: HttpMethod, path: String, parameters: [String: Any]? = nil, credential: URLCredential? = nil, responseSerializer: ResponseSerializer? = nil, completionHandler: @escaping CompletionBlock) {
let block: () -> Void = {
let finalOptURL = self.calculateURL(baseURL: self.baseURL, url: path)
guard let finalURL = finalOptURL else {
let error = NSError(domain: "AeroGearHttp", code: 0, userInfo: [NSLocalizedDescriptionKey: "Malformed URL"])
completionHandler(nil, error)
return
}
var request: URLRequest
var task: URLSessionTask?
var delegate: TaskDataDelegate
// Merge headers
let headers = merge(self.requestSerializer.headers, self.authzModule?.authorizationFields())
// care for multipart request is multipart data are set
if (self.hasMultiPartData(httpParams: parameters)) {
request = self.requestSerializer.multipartRequest(url: finalURL, method: method, parameters: parameters, headers: headers)
task = self.session.uploadTask(withStreamedRequest: request)
delegate = TaskUploadDelegate()
} else {
request = self.requestSerializer.request(url: finalURL, method: method, parameters: parameters, headers: headers)
task = self.session.dataTask(with: request);
delegate = TaskDataDelegate()
}
delegate.completionHandler = completionHandler
delegate.responseSerializer = responseSerializer == nil ? self.responseSerializer : responseSerializer
delegate.credential = credential
self.delegate[task] = delegate
if let task = task {task.resume()}
}
// cater for authz and pre-authorize prior to performing request
if (self.authzModule != nil) {
self.authzModule?.requestAccess(completionHandler: { (response, error ) in
// if there was an error during authz, no need to continue
if (error != nil) {
completionHandler(nil, error)
return
}
// ..otherwise proceed normally
block();
})
} else {
block()
}
}
/**
Gateway to perform different file requests either download or upload.
:param: url the url of the resource.
:param: parameters the request parameters.
:param: method the method to be used.
:param: responseSerializer the actual response serializer to use upon receiving a response
:param: type the file request type
:param: progress a block that will be invoked to report progress during either download or upload.
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
fileprivate func fileRequest(_ url: String, parameters: [String: Any]? = nil, method: HttpMethod, credential: URLCredential? = nil, responseSerializer: ResponseSerializer? = nil, type: FileRequestType, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
let block: () -> Void = {
let finalOptURL = self.calculateURL(baseURL: self.baseURL, url: url)
guard let finalURL = finalOptURL else {
let error = NSError(domain: "AeroGearHttp", code: 0, userInfo: [NSLocalizedDescriptionKey: "Malformed URL"])
completionHandler(nil, error)
return
}
var request: URLRequest
// Merge headers
let headers = merge(self.requestSerializer.headers, self.authzModule?.authorizationFields())
// care for multipart request is multipart data are set
if (self.hasMultiPartData(httpParams: parameters)) {
request = self.requestSerializer.multipartRequest(url: finalURL, method: method, parameters: parameters, headers: headers)
} else {
request = self.requestSerializer.request(url: finalURL, method: method, parameters: parameters, headers: headers)
}
var task: URLSessionTask?
switch type {
case .download(let destinationDirectory):
task = self.session.downloadTask(with: request)
let delegate = TaskDownloadDelegate()
delegate.downloadProgress = progress
delegate.destinationDirectory = destinationDirectory as NSString?;
delegate.completionHandler = completionHandler
delegate.credential = credential
delegate.responseSerializer = responseSerializer == nil ? self.responseSerializer : responseSerializer
self.delegate[task] = delegate
case .upload(let uploadType):
switch uploadType {
case .data(let data):
task = self.session.uploadTask(with: request, from: data)
case .file(let url):
task = self.session.uploadTask(with: request, fromFile: url)
case .stream(_):
task = self.session.uploadTask(withStreamedRequest: request)
}
let delegate = TaskUploadDelegate()
delegate.uploadProgress = progress
delegate.completionHandler = completionHandler
delegate.credential = credential
delegate.responseSerializer = responseSerializer
self.delegate[task] = delegate
}
if let task = task {task.resume()}
}
// cater for authz and pre-authorize prior to performing request
if (self.authzModule != nil) {
self.authzModule?.requestAccess(completionHandler: { (response, error ) in
// if there was an error during authz, no need to continue
if (error != nil) {
completionHandler(nil, error)
return
}
// ..otherwise proceed normally
block();
})
} else {
block()
}
}
/**
Request to download a file.
:param: url the URL of the downloadable resource.
:param: destinationDirectory the destination directory where the file would be stored, if not specified. application's default '.Documents' directory would be used.
:param: parameters the request parameters.
:param: credential the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
:param: method the method to be used, by default a .GET request.
:param: progress a block that will be invoked to report progress during download.
:param: completionHandler a block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func download(url: String, destinationDirectory: String? = nil, parameters: [String: Any]? = nil, credential: URLCredential? = nil, method: HttpMethod = .get, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
fileRequest(url, parameters: parameters, method: method, credential: credential, type: .download(destinationDirectory), progress: progress, completionHandler: completionHandler)
}
/**
Request to upload a file using an NURL of a local file.
:param: url the URL to upload resource into.
:param: file the URL of the local file to be uploaded.
:param: parameters the request parameters.
:param: credential the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
:param: method the method to be used, by default a .POST request.
:param: responseSerializer the actual response serializer to use upon receiving a response.
:param: progress a block that will be invoked to report progress during upload.
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func upload(url: String, file: URL, parameters: [String: Any]? = nil, credential: URLCredential? = nil, method: HttpMethod = .post, responseSerializer: ResponseSerializer? = nil, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
fileRequest(url, parameters: parameters, method: method, credential: credential, responseSerializer: responseSerializer, type: .upload(.file(file)), progress: progress, completionHandler: completionHandler)
}
/**
Request to upload a file using a raw NSData object.
:param: url the URL to upload resource into.
:param: data the data to be uploaded.
:param: parameters the request parameters.
:param: credential the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
:param: method the method to be used, by default a .POST request.
:param: responseSerializer the actual response serializer to use upon receiving a response.
:param: progress a block that will be invoked to report progress during upload.
:param: completionHandler A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func upload(url: String, data: Data, parameters: [String: Any]? = nil, credential: URLCredential? = nil, method: HttpMethod = .post, responseSerializer: ResponseSerializer? = nil, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
fileRequest(url, parameters: parameters, method: method, credential: credential, responseSerializer: responseSerializer, type: .upload(.data(data)), progress: progress, completionHandler: completionHandler)
}
/**
Request to upload a file using an NSInputStream object.
- parameter url: the URL to upload resource into.
- parameter stream: the stream that will be used for uploading.
- parameter parameters: the request parameters.
- parameter credential: the credentials to use for basic/digest auth (Note: it is advised that HTTPS should be used by default).
- parameter method: the method to be used, by default a .POST request.
- parameter responseSerializer: the actual response serializer to use upon receiving a response.
- parameter progress: a block that will be invoked to report progress during upload.
- parameter completionHandler: A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: The object created from the response data of request and the `NSError` object describing the network or parsing error that occurred.
*/
open func upload(url: String, stream: InputStream, parameters: [String: AnyObject]? = nil, credential: URLCredential? = nil, method: HttpMethod = .post, responseSerializer: ResponseSerializer? = nil, progress: ProgressBlock?, completionHandler: @escaping CompletionBlock) {
fileRequest(url, parameters: parameters, method: method, credential: credential, responseSerializer: responseSerializer, type: .upload(.stream(stream)), progress: progress, completionHandler: completionHandler)
}
// MARK: Private API
// MARK: SessionDelegate
class SessionDelegate: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate, URLSessionDownloadDelegate {
fileprivate var delegates: [Int: TaskDelegate]
open var disableServerTrust: Bool = false
fileprivate subscript(task: URLSessionTask?) -> TaskDelegate? {
get {
guard let task = task else {
return nil
}
return self.delegates[task.taskIdentifier]
}
set (newValue) {
guard let task = task else {
return
}
self.delegates[task.taskIdentifier] = newValue
}
}
required override init() {
self.delegates = Dictionary()
super.init()
}
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
// TODO
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if (disableServerTrust) {
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!))
} else {
completionHandler(.performDefaultHandling, nil)
}
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
// TODO
}
// MARK: NSURLSessionTaskDelegate
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
if let delegate = self[task] {
delegate.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request, completionHandler: completionHandler)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if let delegate = self[task] {
delegate.urlSession(session, task: task, didReceive: challenge, completionHandler: completionHandler)
} else {
self.urlSession(session, didReceive: challenge, completionHandler: completionHandler)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
if let delegate = self[task] {
delegate.urlSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? TaskUploadDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let delegate = self[task] {
delegate.urlSession(session, task: task, didCompleteWithError: error)
self[task] = nil
}
}
// MARK: NSURLSessionDataDelegate
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) {
let downloadDelegate = TaskDownloadDelegate()
self[downloadTask] = downloadDelegate
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let delegate = self[dataTask] as? TaskDataDelegate {
delegate.urlSession(session, dataTask: dataTask, didReceive: data)
}
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
completionHandler(proposedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if let delegate = self[downloadTask] as? TaskDownloadDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? TaskDownloadDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? TaskDownloadDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
}
}
// MARK: NSURLSessionTaskDelegate
class TaskDelegate: NSObject, URLSessionTaskDelegate {
var data: Data? { return nil }
var completionHandler: ((Any?, NSError?) -> Void)?
var responseSerializer: ResponseSerializer?
var credential: URLCredential?
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
completionHandler(request)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
var disposition: Foundation.URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
completionHandler(disposition, credential)
}
func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: (@escaping (InputStream?) -> Void)) {
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error != nil {
completionHandler?(nil, error as NSError?)
return
}
let response = task.response as! HTTPURLResponse
if let _ = task as? URLSessionDownloadTask {
completionHandler?(response, error as NSError?)
return
}
var responseObject: Any? = nil
do {
if let data = data {
try self.responseSerializer?.validation(response, data)
responseObject = self.responseSerializer?.response(data, response.statusCode)
completionHandler?(responseObject, nil)
}
} catch let error as NSError {
var userInfo = error.userInfo
userInfo["StatusCode"] = response.statusCode
let errorToRethrow = NSError(domain: error.domain, code: error.code, userInfo: userInfo)
completionHandler?(responseObject, errorToRethrow)
}
}
}
// MARK: NSURLSessionDataDelegate
class TaskDataDelegate: TaskDelegate, URLSessionDataDelegate {
fileprivate var mutableData: NSMutableData
override var data: Data? {
return self.mutableData as Data
}
override init() {
self.mutableData = NSMutableData()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.mutableData.append(data)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
let cachedResponse = proposedResponse
completionHandler(cachedResponse)
}
}
// MARK: NSURLSessionDownloadDelegate
class TaskDownloadDelegate: TaskDelegate, URLSessionDownloadDelegate {
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: Data?
var destinationDirectory: NSString?
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let filename = downloadTask.response?.suggestedFilename
// calculate final destination
var finalDestination: URL
if (destinationDirectory == nil) { // use 'default documents' directory if not set
// use default documents directory
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
finalDestination = documentsDirectory.appendingPathComponent(filename!)
} else {
// check that the directory exists
let path = destinationDirectory?.appendingPathComponent(filename!)
finalDestination = URL(fileURLWithPath: path!)
}
do {
try FileManager.default.moveItem(at: location, to: finalDestination)
} catch _ {
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
self.downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
}
}
// MARK: NSURLSessionTaskDelegate
class TaskUploadDelegate: TaskDataDelegate {
var uploadProgress: ((Int64, Int64, Int64) -> Void)?
func URLSession(_ session: Foundation.URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
self.uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
// MARK: Utility methods
open func calculateURL(baseURL: String?, url: String) -> URL? {
var url = url
if (baseURL == nil || url.hasPrefix("http")) {
return URL(string: url)!
}
guard let finalURL = URL(string: baseURL!) else {return nil}
if (url.hasPrefix("/")) {
url = url.substring(from: url.characters.index(url.startIndex, offsetBy: 1))
}
return finalURL.appendingPathComponent(url);
}
func hasMultiPartData(httpParams parameters: [String: Any]?) -> Bool {
if (parameters == nil) {
return false
}
var isMultiPart = false
for (_, value) in parameters! {
if value is MultiPartData {
isMultiPart = true
break
}
}
return isMultiPart
}
}
| apache-2.0 | ee1bf25daf492c6e492d915e7f0f187a | 47.174528 | 305 | 0.646203 | 5.857197 | false | false | false | false |
tidepool-org/nutshell-ios | Nutshell/ViewControllers/EventListViewController.swift | 1 | 18725 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* 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 License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
import CoreData
class EventListViewController: BaseUIViewController, ENSideMenuDelegate {
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet weak var searchTextField: NutshellUITextField!
@IBOutlet weak var searchPlaceholderLabel: NutshellUILabel!
@IBOutlet weak var tableView: NutshellUITableView!
@IBOutlet weak var coverView: UIControl!
fileprivate var sortedNutEvents = [(String, NutEvent)]()
fileprivate var filteredNutEvents = [(String, NutEvent)]()
fileprivate var filterString = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = "All events"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
// Add a notification for when the database changes
let moc = NutDataController.controller().mocForNutEvents()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(EventListViewController.databaseChanged(_:)), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: moc)
notificationCenter.addObserver(self, selector: #selector(EventListViewController.textFieldDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
if let sideMenu = self.sideMenuController()?.sideMenu {
sideMenu.delegate = self
menuButton.target = self
menuButton.action = #selector(EventListViewController.toggleSideMenu(_:))
let revealWidth = min(ceil((240.0/320.0) * self.view.bounds.width), 281.0)
sideMenu.menuWidth = revealWidth
sideMenu.bouncingEnabled = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate var viewIsForeground: Bool = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewIsForeground = true
configureSearchUI()
if let sideMenu = self.sideMenuController()?.sideMenu {
sideMenu.allowLeftSwipe = true
sideMenu.allowRightSwipe = true
sideMenu.allowPanGesture = true
}
if sortedNutEvents.isEmpty || eventListNeedsUpdate {
eventListNeedsUpdate = false
getNutEvents()
}
checkNotifyUserOfTestMode()
// periodically check for authentication issues in case we need to force a new login
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.checkConnection()
APIConnector.connector().trackMetric("Viewed Home Screen (Home Screen)")
}
// each first time launch of app, let user know we are still in test mode!
fileprivate func checkNotifyUserOfTestMode() {
if AppDelegate.testMode && !AppDelegate.testModeNotification {
AppDelegate.testModeNotification = true
let alert = UIAlertController(title: "Test Mode", message: "Nutshell has Test Mode enabled!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { Void in
return
}))
alert.addAction(UIAlertAction(title: "Turn Off", style: .default, handler: { Void in
AppDelegate.testMode = false
}))
self.present(alert, animated: true, completion: nil)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchTextField.resignFirstResponder()
viewIsForeground = false
if let sideMenu = self.sideMenuController()?.sideMenu {
//NSLog("swipe disabled")
sideMenu.allowLeftSwipe = false
sideMenu.allowRightSwipe = false
sideMenu.allowPanGesture = false
}
}
@IBAction func toggleSideMenu(_ sender: AnyObject) {
APIConnector.connector().trackMetric("Clicked Hamburger (Home Screen)")
toggleSideMenuView()
}
//
// MARK: - ENSideMenu Delegate
//
fileprivate func configureForMenuOpen(_ open: Bool) {
if open {
if let sideMenuController = self.sideMenuController()?.sideMenu?.menuViewController as? MenuAccountSettingsViewController {
// give sidebar a chance to update
// TODO: this should really be in ENSideMenu!
sideMenuController.menuWillOpen()
}
}
tableView.isUserInteractionEnabled = !open
self.navigationItem.rightBarButtonItem?.isEnabled = !open
coverView.isHidden = !open
}
func sideMenuWillOpen() {
//NSLog("EventList sideMenuWillOpen")
configureForMenuOpen(true)
}
func sideMenuWillClose() {
//NSLog("EventList sideMenuWillClose")
configureForMenuOpen(false)
}
func sideMenuShouldOpenSideMenu() -> Bool {
//NSLog("EventList sideMenuShouldOpenSideMenu")
return true
}
func sideMenuDidClose() {
//NSLog("EventList sideMenuDidClose")
configureForMenuOpen(false)
}
func sideMenuDidOpen() {
//NSLog("EventList sideMenuDidOpen")
configureForMenuOpen(true)
APIConnector.connector().trackMetric("Viewed Hamburger Menu (Hamburger)")
}
//
// 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.
super.prepare(for: segue, sender: sender)
if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.EventGroupSegue {
let cell = sender as! EventListTableViewCell
let eventGroupVC = segue.destination as! EventGroupTableViewController
eventGroupVC.eventGroup = cell.eventGroup!
APIConnector.connector().trackMetric("Clicked a Meal (Home screen)")
} else if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.EventItemDetailSegue {
let cell = sender as! EventListTableViewCell
let eventDetailVC = segue.destination as! EventDetailViewController
let group = cell.eventGroup!
eventDetailVC.eventGroup = group
eventDetailVC.eventItem = group.itemArray[0]
APIConnector.connector().trackMetric("Clicked a Meal (Home screen)")
} else if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.HomeToAddEventSegue {
APIConnector.connector().trackMetric("Click Add (Home screen)")
} else {
NSLog("Unprepped segue from eventList \(segue.identifier)")
}
}
// Back button from group or detail viewer.
@IBAction func done(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList done!")
}
// Multiple VC's on the navigation stack return all the way back to this initial VC via this segue, when nut events go away due to deletion, for test purposes, etc.
@IBAction func home(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList home!")
}
// The add/edit VC will return here when a meal event is deleted, and detail vc was transitioned to directly from this vc (i.e., the Nut event contained a single meal event which was deleted).
@IBAction func doneItemDeleted(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList doneItemDeleted")
}
@IBAction func cancel(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventList cancel")
}
fileprivate var eventListNeedsUpdate: Bool = false
func databaseChanged(_ note: Notification) {
NSLog("EventList: Database Change Notification")
if viewIsForeground {
getNutEvents()
} else {
eventListNeedsUpdate = true
}
}
func getNutEvents() {
var nutEvents = [String: NutEvent]()
func addNewEvent(_ newEvent: EventItem) {
/// TODO: TEMP UPGRADE CODE, REMOVE BEFORE SHIPPING!
if newEvent.userid == nil {
newEvent.userid = NutDataController.controller().currentUserId
if let moc = newEvent.managedObjectContext {
NSLog("NOTE: Updated nil userid to \(newEvent.userid)")
moc.refresh(newEvent, mergeChanges: true)
_ = DatabaseUtils.databaseSave(moc)
}
}
/// TODO: TEMP UPGRADE CODE, REMOVE BEFORE SHIPPING!
let newEventId = newEvent.nutEventIdString()
if let existingNutEvent = nutEvents[newEventId] {
_ = existingNutEvent.addEvent(newEvent)
//NSLog("appending new event: \(newEvent.notes)")
//existingNutEvent.printNutEvent()
} else {
nutEvents[newEventId] = NutEvent(firstEvent: newEvent)
}
}
sortedNutEvents = [(String, NutEvent)]()
filteredNutEvents = [(String, NutEvent)]()
filterString = ""
// Get all Food and Activity events, chronologically; this will result in an unsorted dictionary of NutEvents.
do {
let nutEvents = try DatabaseUtils.getAllNutEvents()
for event in nutEvents {
//if let event = event as? Workout {
// NSLog("Event type: \(event.type), id: \(event.id), time: \(event.time), created time: \(event.createdTime!.timeIntervalSinceDate(event.time!)), duration: \(event.duration), title: \(event.title), notes: \(event.notes), userid: \(event.userid), timezone offset:\(event.timezoneOffset)")
//}
addNewEvent(event)
}
} catch let error as NSError {
NSLog("Error: \(error)")
}
sortedNutEvents = nutEvents.sorted() { $0.1.mostRecent.compare($1.1.mostRecent as Date) == ComparisonResult.orderedDescending }
updateFilteredAndReload()
// One time orphan check after application load
EventListViewController.checkAndDeleteOrphans(sortedNutEvents)
}
static var _checkedForOrphanPhotos = false
class func checkAndDeleteOrphans(_ allNutEvents: [(String, NutEvent)]) {
if _checkedForOrphanPhotos {
return
}
_checkedForOrphanPhotos = true
if let photoDirPath = NutUtils.photosDirectoryPath() {
var allLocalPhotos = [String: Bool]()
let fm = FileManager.default
do {
let dirContents = try fm.contentsOfDirectory(atPath: photoDirPath)
//NSLog("Photos dir: \(dirContents)")
if !dirContents.isEmpty {
for file in dirContents {
allLocalPhotos[file] = false
}
for (_, nutEvent) in allNutEvents {
for event in nutEvent.itemArray {
for url in event.photoUrlArray() {
if url.hasPrefix("file_") {
//NSLog("\(NutUtils.photoInfo(url))")
allLocalPhotos[url] = true
}
}
}
}
}
} catch let error as NSError {
NSLog("Error accessing photos at \(photoDirPath), error: \(error)")
}
let orphans = allLocalPhotos.filter() { $1 == false }
for (url, _) in orphans {
NSLog("Deleting orphaned photo: \(url)")
NutUtils.deleteLocalPhoto(url)
}
}
}
// MARK: - Search
@IBAction func dismissKeyboard(_ sender: AnyObject) {
searchTextField.resignFirstResponder()
}
func textFieldDidChange() {
updateFilteredAndReload()
}
@IBAction func searchEditingDidEnd(_ sender: AnyObject) {
configureSearchUI()
}
@IBAction func searchEditingDidBegin(_ sender: AnyObject) {
configureSearchUI()
APIConnector.connector().trackMetric("Typed into Search (Home Screen)")
}
fileprivate func searchMode() -> Bool {
var searchMode = false
if searchTextField.isFirstResponder {
searchMode = true
} else if let searchText = searchTextField.text {
if !searchText.isEmpty {
searchMode = true
}
}
return searchMode
}
fileprivate func configureSearchUI() {
let searchOn = searchMode()
searchPlaceholderLabel.isHidden = searchOn
self.title = searchOn && !filterString.isEmpty ? "Events" : "All events"
}
fileprivate func updateFilteredAndReload() {
if !searchMode() {
filteredNutEvents = sortedNutEvents
filterString = ""
} else if let searchText = searchTextField.text {
if !searchText.isEmpty {
if searchText.localizedCaseInsensitiveContains(filterString) {
// if the search is just getting longer, no need to check already filtered out items
filteredNutEvents = filteredNutEvents.filter() {
$1.containsSearchString(searchText)
}
} else {
filteredNutEvents = sortedNutEvents.filter() {
$1.containsSearchString(searchText)
}
}
filterString = searchText
} else {
filteredNutEvents = sortedNutEvents
filterString = ""
}
// Do this last, after filterString is configured
configureSearchUI()
}
tableView.reloadData()
}
}
//
// MARK: - Table view delegate
//
extension EventListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt estimatedHeightForRowAtIndexPath: IndexPath) -> CGFloat {
return 102.0;
}
func tableView(_ tableView: UITableView, heightForRowAt heightForRowAtIndexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let tuple = self.filteredNutEvents[indexPath.item]
let nutEvent = tuple.1
let cell = tableView.cellForRow(at: indexPath)
if nutEvent.itemArray.count == 1 {
self.performSegue(withIdentifier: EventViewStoryboard.SegueIdentifiers.EventItemDetailSegue, sender: cell)
} else if nutEvent.itemArray.count > 1 {
self.performSegue(withIdentifier: EventViewStoryboard.SegueIdentifiers.EventGroupSegue, sender: cell)
}
}
}
//
// MARK: - Table view data source
//
extension EventListViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredNutEvents.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Note: two different list cells are used depending upon whether a location will be shown or not.
var cellId = EventViewStoryboard.TableViewCellIdentifiers.eventListCellNoLoc
var nutEvent: NutEvent?
if (indexPath.item < filteredNutEvents.count) {
let tuple = self.filteredNutEvents[indexPath.item]
nutEvent = tuple.1
if !nutEvent!.location.isEmpty {
cellId = EventViewStoryboard.TableViewCellIdentifiers.eventListCellWithLoc
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! EventListTableViewCell
if let nutEvent = nutEvent {
cell.configureCell(nutEvent)
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
}
| bsd-2-clause | b43a49c0ff9357cb579cce91ff1df059 | 38.587738 | 305 | 0.628785 | 5.64006 | false | false | false | false |
IWU-CIS-396-Wearable-computing/WatchOS2CounterSwift | WatchOS2CounterSwift/ViewController.swift | 1 | 1038 | //
// ViewController.swift
// WatchOS2CounterSwift
//
// Created by Thai, Kristina on 6/20/15.
// Copyright © 2015 Kristina Thai. All rights reserved.
//
import UIKit
import WatchConnectivity
class ViewController: UIViewController, UITableViewDataSource {
var counterData = [String]()
@IBOutlet weak var mainTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.mainTableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return counterData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "CounterCell"
let cell = self.mainTableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
let counterValueString = self.counterData[indexPath.row]
cell.textLabel?.text = counterValueString
return cell
}
}
| mit | 5f39bc24a29012cca3086a602293bebd | 25.589744 | 112 | 0.689489 | 5.237374 | false | false | false | false |
AlbertXYZ/HDCP | HDCP/Pods/SnapKit/Source/Constraint.swift | 1 | 11778 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class Constraint {
internal let sourceLocation: (String, UInt)
internal let label: String?
private let from: ConstraintItem
private let to: ConstraintItem
private let relation: ConstraintRelation
private let multiplier: ConstraintMultiplierTarget
private var constant: ConstraintConstantTarget {
didSet {
self.updateConstantAndPriorityIfNeeded()
}
}
private var priority: ConstraintPriorityTarget {
didSet {
self.updateConstantAndPriorityIfNeeded()
}
}
private var layoutConstraints: [LayoutConstraint]
// MARK: Initialization
internal init(from: ConstraintItem,
to: ConstraintItem,
relation: ConstraintRelation,
sourceLocation: (String, UInt),
label: String?,
multiplier: ConstraintMultiplierTarget,
constant: ConstraintConstantTarget,
priority: ConstraintPriorityTarget) {
self.from = from
self.to = to
self.relation = relation
self.sourceLocation = sourceLocation
self.label = label
self.multiplier = multiplier
self.constant = constant
self.priority = priority
self.layoutConstraints = []
// get attributes
let layoutFromAttributes = self.from.attributes.layoutAttributes
let layoutToAttributes = self.to.attributes.layoutAttributes
// get layout from
let layoutFrom: ConstraintView = self.from.view!
// get relation
let layoutRelation = self.relation.layoutRelation
for layoutFromAttribute in layoutFromAttributes {
// get layout to attribute
let layoutToAttribute: NSLayoutAttribute
#if os(iOS) || os(tvOS)
if layoutToAttributes.count > 0 {
if self.from.attributes == .edges && self.to.attributes == .margins {
switch layoutFromAttribute {
case .left:
layoutToAttribute = .leftMargin
case .right:
layoutToAttribute = .rightMargin
case .top:
layoutToAttribute = .topMargin
case .bottom:
layoutToAttribute = .bottomMargin
default:
fatalError()
}
} else if self.from.attributes == .margins && self.to.attributes == .edges {
switch layoutFromAttribute {
case .leftMargin:
layoutToAttribute = .left
case .rightMargin:
layoutToAttribute = .right
case .topMargin:
layoutToAttribute = .top
case .bottomMargin:
layoutToAttribute = .bottom
default:
fatalError()
}
} else if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else {
layoutToAttribute = layoutToAttributes[0]
}
} else {
if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) {
layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top
} else {
layoutToAttribute = layoutFromAttribute
}
}
#else
if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else if layoutToAttributes.count > 0 {
layoutToAttribute = layoutToAttributes[0]
} else {
layoutToAttribute = layoutFromAttribute
}
#endif
// get layout constant
let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutToAttribute)
// get layout to
var layoutTo: AnyObject? = self.to.target
// use superview if possible
if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height {
layoutTo = layoutFrom.superview
}
// create layout constraint
let layoutConstraint = LayoutConstraint(
item: layoutFrom,
attribute: layoutFromAttribute,
relatedBy: layoutRelation,
toItem: layoutTo,
attribute: layoutToAttribute,
multiplier: self.multiplier.constraintMultiplierTargetValue,
constant: layoutConstant
)
// set label
layoutConstraint.label = self.label
// set priority
layoutConstraint.priority = self.priority.constraintPriorityTargetValue
// set constraint
layoutConstraint.constraint = self
// append
self.layoutConstraints.append(layoutConstraint)
}
}
// MARK: Public
@available(*, deprecated:3.0, message:"Use activate().")
public func install() {
self.activate()
}
@available(*, deprecated:3.0, message:"Use deactivate().")
public func uninstall() {
self.deactivate()
}
public func activate() {
self.activateIfNeeded()
}
public func deactivate() {
self.deactivateIfNeeded()
}
@discardableResult
public func update(offset: ConstraintOffsetTarget) -> Constraint {
self.constant = offset.constraintOffsetTargetValue
return self
}
@discardableResult
public func update(inset: ConstraintInsetTarget) -> Constraint {
self.constant = inset.constraintInsetTargetValue
return self
}
@discardableResult
public func update(priority: ConstraintPriorityTarget) -> Constraint {
self.priority = priority.constraintPriorityTargetValue
return self
}
@available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.")
public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) }
@available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.")
public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) }
@available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityRequired() -> Void {}
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
// MARK: Internal
internal func updateConstantAndPriorityIfNeeded() {
for layoutConstraint in self.layoutConstraints {
let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(attribute)
#if os(iOS) || os(tvOS)
let requiredPriority: UILayoutPriority = UILayoutPriorityRequired
#else
let requiredPriority: Float = 1000.0
#endif
if (layoutConstraint.priority < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) {
layoutConstraint.priority = self.priority.constraintPriorityTargetValue
}
}
}
internal func activateIfNeeded(updatingExisting: Bool = false) {
guard let view = self.from.view else {
print("WARNING: SnapKit failed to get from view from constraint. Activate will be a no-op.")
return
}
let layoutConstraints = self.layoutConstraints
let existingLayoutConstraints = view.snp.constraints.map({ $0.layoutConstraints }).reduce([]) { $0 + $1 }
if updatingExisting {
for layoutConstraint in layoutConstraints {
let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint }
guard let updateLayoutConstraint = existingLayoutConstraint else {
fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)")
}
let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute
updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(updateLayoutAttribute)
}
} else {
NSLayoutConstraint.activate(layoutConstraints)
view.snp.add(constraints: [self])
}
}
internal func deactivateIfNeeded() {
guard let view = self.from.view else {
print("WARNING: SnapKit failed to get from view from constraint. Deactivate will be a no-op.")
return
}
let layoutConstraints = self.layoutConstraints
NSLayoutConstraint.deactivate(layoutConstraints)
view.snp.remove(constraints: [self])
}
}
| mit | 3e6fbdc161b8138041f3b409589a8417 | 40.765957 | 184 | 0.600696 | 6.052415 | false | false | false | false |
dvaughn1712/perfect-routing | PerfectLib/NotificationPusher.swift | 2 | 13151 | //
// NotificationPusher.swift
// PerfectLib
//
// Created by Kyle Jessup on 2016-02-16.
// Copyright © 2016 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
/**
Example code:
// BEGIN one-time initialization code
let configurationName = "My configuration name - can be whatever"
NotificationPusher.addConfigurationIOS(configurationName) {
(net:NetTCPSSL) in
// This code will be called whenever a new connection to the APNS service is required.
// Configure the SSL related settings.
net.keyFilePassword = "if you have password protected key file"
guard net.useCertificateChainFile("path/to/entrust_2048_ca.cer") &&
net.useCertificateFile("path/to/aps_development.pem") &&
net.usePrivateKeyFile("path/to/key.pem") &&
net.checkPrivateKey() else {
let code = Int32(net.errorCode())
print("Error validating private key file: \(net.errorStr(code))")
return
}
}
NotificationPusher.development = true // set to toggle to the APNS sandbox server
// END one-time initialization code
// BEGIN - individual notification push
let deviceId = "hex string device id"
let ary = [IOSNotificationItem.AlertBody("This is the message"), IOSNotificationItem.Sound("default")]
let n = NotificationPusher()
n.apnsTopic = "com.company.my-app"
n.pushIOS(configurationName, deviceToken: deviceId, expiration: 0, priority: 10, notificationItems: ary) {
response in
print("NotificationResponse: \(response.code) \(response.body)")
}
// END - individual notification push
*/
/// Items to configure an individual notification push.
/// These correspond to what is described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html
public enum IOSNotificationItem {
case AlertBody(String)
case AlertTitle(String)
case AlertTitleLoc(String, [String]?)
case AlertActionLoc(String)
case AlertLoc(String, [String]?)
case AlertLaunchImage(String)
case Badge(Int)
case Sound(String)
case ContentAvailable
case Category(String)
case CustomPayload(String, Any)
}
enum IOSItemId: UInt8 {
case DeviceToken = 1
case Payload = 2
case NotificationIdentifier = 3
case ExpirationDate = 4
case Priority = 5
}
private let iosDeviceIdLength = 32
private let iosNotificationCommand = UInt8(2)
private let iosNotificationPort = UInt16(443)
private let iosNotificationDevelopmentHost = "api.development.push.apple.com"
private let iosNotificationProductionHost = "api.push.apple.com"
struct IOSNotificationError {
let code: UInt8
let identifier: UInt32
}
class NotificationConfiguration {
let configurator: NotificationPusher.netConfigurator
let lock = Threading.Lock()
var streams = [NotificationHTTP2Client]()
init(configurator: NotificationPusher.netConfigurator) {
self.configurator = configurator
}
}
class NotificationHTTP2Client: HTTP2Client {
let id: Int
init(id: Int) {
self.id = id
}
}
/// The response object given after a push attempt.
public struct NotificationResponse {
/// The response code for the request.
public let code: Int
/// The response body data bytes.
public let body: [UInt8]
/// The body data bytes interpreted as JSON and decoded into a Dictionary.
public var jsonObjectBody: [String:Any] {
do {
if let json = try self.stringBody.jsonDecode() as? [String:Any] {
return json
}
}
catch {}
return [String:Any]()
}
/// The body data bytes converted to String.
public var stringBody: String {
return UTF8Encoding.encode(self.body)
}
}
/// The interface for APNS notifications.
public class NotificationPusher {
/// On-demand configuration for SSL related functions.
public typealias netConfigurator = (NetTCPSSL) -> ()
/// Toggle development or production on a global basis.
public static var development = false
/// Sets the apns-topic which will be used for iOS notifications.
public var apnsTopic: String?
var responses = [NotificationResponse]()
static var idCounter = 0
static var notificationHostIOS: String {
if self.development {
return iosNotificationDevelopmentHost
}
return iosNotificationProductionHost
}
static let configurationsLock = Threading.Lock()
static var iosConfigurations = [String:NotificationConfiguration]()
static var activeStreams = [Int:NotificationHTTP2Client]()
/// Add a configuration given a name and a callback.
/// A particular configuration will generally correspond to an individual app.
/// The configuration callback will be called each time a new connection is initiated to the APNS.
/// Within the callback you will want to set:
/// 1. Path to chain file as provided by Apple: net.useCertificateChainFile("path/to/entrust_2048_ca.cer")
/// 2. Path to push notification certificate as obtained from Apple: net.useCertificateFile("path/to/aps.pem")
/// 3a. Password for the certificate's private key file, if it is password protected: net.keyFilePassword = "password"
/// 3b. Path to the certificate's private key file: net.usePrivateKeyFile("path/to/key.pem")
public static func addConfigurationIOS(name: String, configurator: netConfigurator) {
self.configurationsLock.doWithLock {
self.iosConfigurations[name] = NotificationConfiguration(configurator: configurator)
}
}
static func getStreamIOS(configurationName: String, callback: (HTTP2Client?) -> ()) {
var conf: NotificationConfiguration?
self.configurationsLock.doWithLock {
conf = self.iosConfigurations[configurationName]
}
if let c = conf {
var net: NotificationHTTP2Client?
var needsConnect = false
c.lock.doWithLock {
if c.streams.count > 0 {
net = c.streams.removeLast()
} else {
needsConnect = true
net = NotificationHTTP2Client(id: idCounter)
activeStreams[idCounter] = net
idCounter = idCounter &+ 1
}
}
if !needsConnect {
callback(net!)
} else {
// add a new connected stream
c.configurator(net!.net)
net!.connect(self.notificationHostIOS, port: iosNotificationPort, ssl: true, timeoutSeconds: 5.0) {
b in
if b {
callback(net!)
} else {
callback(nil)
}
}
}
} else {
callback(nil)
}
}
static func releaseStreamIOS(configurationName: String, net: HTTP2Client) {
var conf: NotificationConfiguration?
self.configurationsLock.doWithLock {
conf = self.iosConfigurations[configurationName]
}
if let c = conf, n = net as? NotificationHTTP2Client {
c.lock.doWithLock {
activeStreams.removeValueForKey(n.id)
if net.isConnected {
c.streams.append(n)
}
}
} else {
net.close()
}
}
public init() {
}
/// Initialize given iOS apns-topic string.
/// This can be set after initialization on the X.apnsTopic property.
public init(apnsTopic: String) {
self.apnsTopic = apnsTopic
}
func resetResponses() {
self.responses.removeAll()
}
/// Push one message to one device.
/// Provide the previously set configuration name, device token.
/// Provide the expiration and priority as described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
/// Provide a list of IOSNotificationItems.
/// Provide a callback with which to receive the response.
public func pushIOS(configurationName: String, deviceToken: String, expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: (NotificationResponse) -> ()) {
NotificationPusher.getStreamIOS(configurationName) {
client in
if let c = client {
self.pushIOS(c, deviceTokens: [deviceToken], expiration: expiration, priority: priority, notificationItems: notificationItems) {
responses in
NotificationPusher.releaseStreamIOS(configurationName, net: c)
if responses.count == 1 {
callback(responses.first!)
} else {
callback(NotificationResponse(code: -1, body: [UInt8]()))
}
}
} else {
callback(NotificationResponse(code: -1, body: [UInt8]()))
}
}
}
/// Push one message to multiple devices.
/// Provide the previously set configuration name, and zero or more device tokens. The same message will be sent to each device.
/// Provide the expiration and priority as described here:
/// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
/// Provide a list of IOSNotificationItems.
/// Provide a callback with which to receive the responses.
public func pushIOS(configurationName: String, deviceTokens: [String], expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: ([NotificationResponse]) -> ()) {
NotificationPusher.getStreamIOS(configurationName) {
client in
if let c = client {
self.pushIOS(c, deviceTokens: deviceTokens, expiration: expiration, priority: priority, notificationItems: notificationItems) {
responses in
NotificationPusher.releaseStreamIOS(configurationName, net: c)
if responses.count == 1 {
callback(responses)
} else {
callback([NotificationResponse(code: -1, body: [UInt8]())])
}
}
} else {
callback([NotificationResponse(code: -1, body: [UInt8]())])
}
}
}
func pushIOS(net: HTTP2Client, deviceToken: String, expiration: UInt32, priority: UInt8, notificationJson: [UInt8], callback: (NotificationResponse) -> ()) {
let request = net.createRequest()
request.setRequestMethod("POST")
request.postBodyBytes = notificationJson
request.headers["content-type"] = "application/json; charset=utf-8"
request.headers["apns-expiration"] = "\(expiration)"
request.headers["apns-priority"] = "\(priority)"
if let apnsTopic = apnsTopic {
request.headers["apns-topic"] = apnsTopic
}
request.setRequestURI("/3/device/\(deviceToken)")
net.sendRequest(request) {
response, msg in
if let r = response {
let code = r.getStatus().0
callback(NotificationResponse(code: code, body: r.bodyData))
} else {
callback(NotificationResponse(code: -1, body: UTF8Encoding.decode("No response")))
}
}
}
func pushIOS(client: HTTP2Client, deviceTokens: IndexingGenerator<[String]>, expiration: UInt32, priority: UInt8, notificationJson: [UInt8], callback: ([NotificationResponse]) -> ()) {
var g = deviceTokens
if let next = g.next() {
pushIOS(client, deviceToken: next, expiration: expiration, priority: priority, notificationJson: notificationJson) {
response in
self.responses.append(response)
self.pushIOS(client, deviceTokens: g, expiration: expiration, priority: priority, notificationJson: notificationJson, callback: callback)
}
} else {
callback(self.responses)
}
}
func pushIOS(client: HTTP2Client, deviceTokens: [String], expiration: UInt32, priority: UInt8, notificationItems: [IOSNotificationItem], callback: ([NotificationResponse]) -> ()) {
self.resetResponses()
let g = deviceTokens.generate()
let jsond = UTF8Encoding.decode(self.itemsToPayloadString(notificationItems))
self.pushIOS(client, deviceTokens: g, expiration: expiration, priority: priority, notificationJson: jsond, callback: callback)
}
func itemsToPayloadString(notificationItems: [IOSNotificationItem]) -> String {
var dict = [String:Any]()
var aps = [String:Any]()
var alert = [String:Any]()
var alertBody: String?
for item in notificationItems {
switch item {
case .AlertBody(let s):
alertBody = s
case .AlertTitle(let s):
alert["title"] = s
case .AlertTitleLoc(let s, let a):
alert["title-loc-key"] = s
if let titleLocArgs = a {
alert["title-loc-args"] = titleLocArgs
}
case .AlertActionLoc(let s):
alert["action-loc-key"] = s
case .AlertLoc(let s, let a):
alert["loc-key"] = s
if let locArgs = a {
alert["loc-args"] = locArgs
}
case .AlertLaunchImage(let s):
alert["launch-image"] = s
case .Badge(let i):
aps["badge"] = i
case .Sound(let s):
aps["sound"] = s
case .ContentAvailable:
aps["content-available"] = 1
case .Category(let s):
aps["category"] = s
case .CustomPayload(let s, let a):
dict[s] = a
}
}
if let ab = alertBody {
if alert.count == 0 { // just a string alert
aps["alert"] = ab
} else { // a dict alert
alert["body"] = ab
aps["alert"] = alert
}
}
dict["aps"] = aps
do {
return try dict.jsonEncodedString()
}
catch {}
return "{}"
}
}
private func jsonSerialize(o: Any) -> String? {
do {
return try jsonEncodedStringWorkAround(o)
} catch let e as JSONConversionError {
print("Could not convert to JSON: \(e)")
} catch {}
return nil
} | unlicense | ee29f0ee9a7ad088cccdf5c0d3eb5249 | 29.655012 | 194 | 0.703878 | 3.826011 | false | true | false | false |
marcelganczak/swift-js-transpiler | test/weheartswift/loops-18.swift | 1 | 325 | var number = 10
print("\(number) = ")
var isFirst = true
for i in 2...number {
if number % i == 0 {
while (number % i == 0) {
number /= i
if isFirst {
isFirst = false
} else {
print(" * ")
}
print(i)
}
}
} | mit | 66407d3c9b3ac55a23f84cfbf8f771d6 | 15.3 | 33 | 0.353846 | 4.166667 | false | false | false | false |
CoderLiLe/Swift | 内存相关/main.swift | 1 | 3324 | //
// main.swift
// 内存相关
//
// Created by LiLe on 15/4/5.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
Swift内存管理:
管理引用类型的内存, 不会管理值类型, 值类型不需要管理
内存管理原则: 当没有任何强引用指向对象, 系统会自动销毁对象
(默认情况下所有的引用都是强引用)
如果做到该原则: ARC
*/
class Person {
var name:String
init(name:String){
self.name = name
}
deinit{
print("deinit")
}
}
var p:Person? = Person(name: "lnj")
//p = nil
/*
weak弱引用
*/
class Person2 {
var name:String
init(name:String){
self.name = name
}
deinit{
print("deinit")
}
}
// 强引用, 引用计数+1
var strongP = Person2(name: "lnj") // 1
var strongP2 = strongP // 2
// 弱引用, 引用计数不变
// 如果利用weak修饰变量, 当对象释放后会自动将变量设置为nil
// 所以利用weak修饰的变量必定是一个可选类型, 因为只有可选类型才能设置为nil
weak var weakP:Person2? = Person2(name: "lnj")
if let p = weakP{
print(p)
}else
{
print(weakP)
}
/*
unowned无主引用 , 相当于OC unsafe_unretained
unowned和weak的区别:
1.利用unowned修饰的变量, 对象释放后不会设置为nil. 不安全
利用weak修饰的变量, 对象释放后会设置为nil
2.利用unowned修饰的变量, 不是可选类型
利用weak修饰的变量, 是可选类型
什么时候使用weak?
什么时候使用unowned?
*/
class Person3 {
var name:String
init(name:String){
self.name = name
}
deinit{
print("deinit")
}
}
unowned var weakP3:Person3 = Person3(name: "lnj")
/*
循环引用
ARC不是万能的, 它可以很好的解决内存问题, 但是在某些场合不能很好的解决内存泄露问题
例如两个或多个对象之间的循环引用问题
*/
class Person4 {
let name:String // 姓名
// 人不一定有公寓
weak var apartment: Apartment? // 公寓
init(name:String){
self.name = name
}
deinit{
print("\(self.name) deinit")
}
}
class Apartment {
let number: Int // 房间号
var tenant: Person4? // 租客
init(number:Int){
self.number = number
}
deinit{
print("\(self.number) deinit")
}
}
var p4:Person4? = Person4(name: "lnj")
var a4:Apartment? = Apartment(number:888)
p4!.apartment = a4 // 人有一套公寓
a4!.tenant = p4! // 公寓中住着一个人
// 两个对象没有被销毁, 但是我们没有办法访问他们了. 内存泄露
p4 = nil
a4 = nil
class Person5 {
let name:String // 姓名
// 人不一定有信用卡
var card: CreditCard?
init(name:String){
self.name = name
}
deinit{
print("\(self.name) deinit")
}
}
class CreditCard{
let number: Int
// 信用卡必须有所属用户
// 当某一个变量/常量必须有值, 一直有值, 那么可以使用unowned修饰
unowned let person: Person5
init(number:Int, person: Person5){
self.number = number
self.person = person
}
deinit{
print("\(self.number) deinit")
}
}
var p5:Person5? = Person5(name: "lnj")
var cc:CreditCard? = CreditCard(number: 8888888, person: p5!)
p5 = nil
cc = nil
| mit | f9385172518789847f816f4eb4589c90 | 15.966443 | 61 | 0.619462 | 2.765864 | false | false | false | false |
firebase/firebase-ios-sdk | ReleaseTooling/Sources/Utils/ShellUtils.swift | 2 | 8515 | /*
* Copyright 2019 Google
*
* 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
/// Convenience function for calling functions in the Shell. This should be used sparingly and only
/// when interacting with tools that can't be accessed directly in Swift (i.e. CocoaPods,
/// xcodebuild, etc). Intentionally empty, this enum is used as a namespace.
public enum Shell {}
public extension Shell {
/// A type to represent the result of running a shell command.
enum Result {
/// The command was successfully run (based on the output code), with the output string as the
/// associated value.
case success(output: String)
/// The command failed with a given exit code and output.
case error(code: Int32, output: String)
}
/// Log without executing the shell commands.
static var logOnly = false
static func setLogOnly() {
logOnly = true
}
/// Execute a command in the user's shell. This creates a temporary shell script and runs the
/// command from there, instead of calling via `Process()` directly in order to include the
/// appropriate environment variables. This is mostly for CocoaPods commands, but doesn't hurt
/// other commands.
///
/// - Parameters:
/// - command: The command to run in the shell.
/// - outputToConsole: A flag if the command output should be written to the console as well.
/// - workingDir: An optional working directory to run the shell command in.
/// - Returns: A Result containing output information from the command.
static func executeCommandFromScript(_ command: String,
outputToConsole: Bool = true,
workingDir: URL? = nil) -> Result {
let scriptPath: URL
do {
let tempScriptsDir = FileManager.default.temporaryDirectory(withName: "temp_scripts")
try FileManager.default.createDirectory(at: tempScriptsDir,
withIntermediateDirectories: true,
attributes: nil)
scriptPath = tempScriptsDir.appendingPathComponent("wrapper.sh")
// Write the temporary script contents to the script's path. CocoaPods complains when LANG
// isn't set in the environment, so explicitly set it here. The `/usr/local/git/current/bin`
// is to allow the `sso` protocol if it's there.
let contents = """
export PATH="/usr/local/bin:/usr/local/git/current/bin:$PATH"
export LANG="en_US.UTF-8"
source ~/.bash_profile
\(command)
"""
try contents.write(to: scriptPath, atomically: true, encoding: .utf8)
} catch let FileManager.FileError.failedToCreateDirectory(path, error) {
fatalError("Could not execute shell command: \(command) - could not create temporary " +
"script directory at \(path). \(error)")
} catch {
fatalError("Could not execute shell command: \(command) - unexpected error. \(error)")
}
// Remove the temporary script at the end of this function. If it fails, it's not a big deal
// since it will be over-written next time and won't affect the Zip file, so we can ignore
// any failure.
defer { try? FileManager.default.removeItem(at: scriptPath) }
// Let the process call directly into the temporary shell script we created.
let task = Process()
task.arguments = [scriptPath.path]
if #available(OSX 10.13, *) {
if let workingDir = workingDir {
task.currentDirectoryURL = workingDir
}
// Explicitly use `/bin/bash`. Investigate whether or not we can use `/usr/local/env`
task.executableURL = URL(fileURLWithPath: "/bin/bash")
} else {
// Assign the old `currentDirectoryPath` property if `currentDirectoryURL` isn't available.
if let workingDir = workingDir {
task.currentDirectoryPath = workingDir.path
}
task.launchPath = "/bin/bash"
}
// Assign a pipe to read as soon as data is available, log it to the console if requested, but
// also keep an array of the output in memory so we can pass it back to functions.
// Assign a pipe to grab the output, and handle it differently if we want to stream the results
// to the console or not.
let pipe = Pipe()
task.standardOutput = pipe
let outHandle = pipe.fileHandleForReading
var output: [String] = []
// If we want to output to the console, create a readabilityHandler and save each line along the
// way. Otherwise, we can just read the pipe at the end. By disabling outputToConsole, some
// commands (such as any xcodebuild) can run much, much faster.
if outputToConsole {
outHandle.readabilityHandler = { pipe in
// This will be run any time data is sent to the pipe. We want to print it and store it for
// later. Ignore any non-valid Strings.
guard let line = String(data: pipe.availableData, encoding: .utf8) else {
print("Could not get data from pipe for command \(command): \(pipe.availableData)")
return
}
if line != "" {
output.append(line)
}
print(line)
}
// Also set the termination handler on the task in order to stop the readabilityHandler from
// parsing any more data from the task.
task.terminationHandler = { t in
guard let stdOut = t.standardOutput as? Pipe else { return }
stdOut.fileHandleForReading.readabilityHandler = nil
}
}
// Launch the task and wait for it to exit. This will trigger the above readabilityHandler
// method and will redirect the command output back to the console for quick feedback.
if outputToConsole {
print("Running command: \(command).")
print("----------------- COMMAND OUTPUT -----------------")
}
task.launch()
task.waitUntilExit()
if outputToConsole { print("----------------- END COMMAND OUTPUT -----------------") }
let fullOutput: String
if outputToConsole {
fullOutput = output.joined(separator: "\n")
} else {
let outData = outHandle.readDataToEndOfFile()
// Force unwrapping since we know it's UTF8 coming from the console.
fullOutput = String(data: outData, encoding: .utf8)!
}
// Check if the task succeeded or not, and return the failure code if it didn't.
guard task.terminationStatus == 0 else {
return Result.error(code: task.terminationStatus, output: fullOutput)
}
// The command was successful, return the output.
return Result.success(output: fullOutput)
}
/// Execute a command in the user's shell. This creates a temporary shell script and runs the
/// command from there, instead of calling via `Process()` directly in order to include the
/// appropriate environment variables. This is mostly for CocoaPods commands, but doesn't hurt
/// other commands.
///
/// This is a variation of `executeCommandFromScript` that also does error handling internally.
///
/// - Parameters:
/// - command: The command to run in the shell.
/// - outputToConsole: A flag if the command output should be written to the console as well.
/// - workingDir: An optional working directory to run the shell command in.
/// - Returns: A Result containing output information from the command.
static func executeCommand(_ command: String,
outputToConsole: Bool = true,
workingDir: URL? = nil) {
if logOnly {
print(command)
return
}
let result = Shell.executeCommandFromScript(command, workingDir: workingDir)
switch result {
case let .error(code, output):
fatalError("""
`\(command)` failed with exit code \(code) while trying to install pods:
Output from `\(command)`:
\(output)
""")
case let .success(output):
// Print the output to the console and return the information for all installed pods.
print(output)
}
}
}
| apache-2.0 | 2be6797f2b12615d25a90f2d79325891 | 42.005051 | 100 | 0.660951 | 4.676002 | false | false | false | false |
sachin004/firefox-ios | Sync/Synchronizers/Synchronizer.swift | 5 | 8986 | /* 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 Storage
import XCGLogger
private let log = Logger.syncLogger
/**
* This exists to pass in external context: e.g., the UIApplication can
* expose notification functionality in this way.
*/
public protocol SyncDelegate {
func displaySentTabForURL(URL: NSURL, title: String)
// TODO: storage.
}
/**
* We sometimes want to make a synchronizer start from scratch: to throw away any
* metadata and reset storage to match, allowing us to respond to significant server
* changes.
*
* But instantiating a Synchronizer is a lot of work if we simply want to change some
* persistent state. This protocol describes a static func that fits most synchronizers.
*
* When the returned `Deferred` is filled with a success value, the supplied prefs and
* storage are ready to sync from scratch.
*
* Persisted long-term/local data is kept, and will later be reconciled as appropriate.
*/
public protocol ResettableSynchronizer {
static func resetSynchronizerWithStorage(storage: ResettableSyncStorage, basePrefs: Prefs, collection: String) -> Success
}
// TODO: return values?
/**
* A Synchronizer is (unavoidably) entirely in charge of what it does within a sync.
* For example, it might make incremental progress in building a local cache of remote records, never actually performing an upload or modifying local storage.
* It might only upload data. Etc.
*
* Eventually I envision an intent-like approach, or additional methods, to specify preferences and constraints
* (e.g., "do what you can in a few seconds", or "do a full sync, no matter how long it takes"), but that'll come in time.
*
* A Synchronizer is a two-stage beast. It needs to support synchronization, of course; that
* needs a completely configured client, which can only be obtained from Ready. But it also
* needs to be able to do certain things beforehand:
*
* * Wipe its collections from the server (presumably via a delegate from the state machine).
* * Prepare to sync from scratch ("reset") in response to a changed set of keys, syncID, or node assignment.
* * Wipe local storage ("wipeClient").
*
* Those imply that some kind of 'Synchronizer' exists throughout the state machine. We *could*
* pickle instructions for eventual delivery next time one is made and synchronized…
*/
public protocol Synchronizer {
init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs)
/**
* Return a reason if the current state of this synchronizer -- particularly prefs and scratchpad --
* prevent a routine sync from occurring.
*/
func reasonToNotSync(_: Sync15StorageClient) -> SyncNotStartedReason?
}
/**
* We sometimes wish to return something more nuanced than simple success or failure.
* For example, refusing to sync because the engine was disabled isn't success (nothing was transferred!)
* but it also isn't an error.
*
* To do this we model real failures -- something went wrong -- as failures in the Result, and
* everything else in this status enum. This will grow as we return more details from a sync to allow
* for batch scheduling, success-case backoff and so on.
*/
public enum SyncStatus {
case Completed // TODO: we pick up a bunch of info along the way. Pass it along.
case NotStarted(SyncNotStartedReason)
public var description: String {
switch self {
case .Completed:
return "Completed"
case let .NotStarted(reason):
return "Not started: \(reason.description)"
}
}
}
typealias DeferredTimestamp = Deferred<Maybe<Timestamp>>
public typealias SyncResult = Deferred<Maybe<SyncStatus>>
public enum SyncNotStartedReason {
case NoAccount
case Offline
case Backoff(remainingSeconds: Int)
case EngineRemotelyNotEnabled(collection: String)
case EngineFormatOutdated(needs: Int)
case EngineFormatTooNew(expected: Int) // This'll disappear eventually; we'll wipe the server and upload m/g.
case StorageFormatOutdated(needs: Int)
case StorageFormatTooNew(expected: Int) // This'll disappear eventually; we'll wipe the server and upload m/g.
case StateMachineNotReady // Because we're not done implementing.
var description: String {
switch self {
case .NoAccount:
return "no account"
case let .Backoff(remaining):
return "in backoff: \(remaining) seconds remaining"
default:
return "undescribed reason"
}
}
}
public class FatalError: SyncError {
let message: String
init(message: String) {
self.message = message
}
public var description: String {
return self.message
}
}
public protocol SingleCollectionSynchronizer {
func remoteHasChanges(info: InfoCollections) -> Bool
}
public class BaseCollectionSynchronizer {
let collection: String
let scratchpad: Scratchpad
let delegate: SyncDelegate
let prefs: Prefs
static func prefsForCollection(collection: String, withBasePrefs basePrefs: Prefs) -> Prefs {
let branchName = "synchronizer." + collection + "."
return basePrefs.branch(branchName)
}
init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, collection: String) {
self.scratchpad = scratchpad
self.delegate = delegate
self.collection = collection
self.prefs = BaseCollectionSynchronizer.prefsForCollection(collection, withBasePrefs: basePrefs)
log.info("Synchronizer configured with prefs '\(self.prefs.getBranchPrefix()).'")
}
var storageVersion: Int {
assert(false, "Override me!")
return 0
}
public func reasonToNotSync(client: Sync15StorageClient) -> SyncNotStartedReason? {
let now = NSDate.now()
if let until = client.backoff.isInBackoff(now) {
let remaining = (until - now) / 1000
return .Backoff(remainingSeconds: Int(remaining))
}
if let metaGlobal = self.scratchpad.global?.value {
// There's no need to check the global storage format here; the state machine will already have
// done so.
if let engineMeta = metaGlobal.engines[collection] {
if engineMeta.version > self.storageVersion {
return .EngineFormatOutdated(needs: engineMeta.version)
}
if engineMeta.version < self.storageVersion {
return .EngineFormatTooNew(expected: engineMeta.version)
}
} else {
return .EngineRemotelyNotEnabled(collection: self.collection)
}
} else {
// But a missing meta/global is a real problem.
return .StateMachineNotReady
}
// Success!
return nil
}
func encrypter<T>(encoder: RecordEncoder<T>) -> RecordEncrypter<T>? {
return self.scratchpad.keys?.value.encrypter(self.collection, encoder: encoder)
}
func collectionClient<T>(encoder: RecordEncoder<T>, storageClient: Sync15StorageClient) -> Sync15CollectionClient<T>? {
if let encrypter = self.encrypter(encoder) {
return storageClient.clientForCollection(self.collection, encrypter: encrypter)
}
return nil
}
}
/**
* Tracks a lastFetched timestamp, uses it to decide if there are any
* remote changes, and exposes a method to fast-forward after upload.
*/
public class TimestampedSingleCollectionSynchronizer: BaseCollectionSynchronizer, SingleCollectionSynchronizer {
var lastFetched: Timestamp {
set(value) {
self.prefs.setLong(value, forKey: "lastFetched")
}
get {
return self.prefs.unsignedLongForKey("lastFetched") ?? 0
}
}
func setTimestamp(timestamp: Timestamp) {
log.debug("Setting post-upload lastFetched to \(timestamp).")
self.lastFetched = timestamp
}
public func remoteHasChanges(info: InfoCollections) -> Bool {
return info.modified(self.collection) > self.lastFetched
}
}
extension BaseCollectionSynchronizer: ResettableSynchronizer {
public static func resetSynchronizerWithStorage(storage: ResettableSyncStorage, basePrefs: Prefs, collection: String) -> Success {
let synchronizerPrefs = BaseCollectionSynchronizer.prefsForCollection(collection, withBasePrefs: basePrefs)
synchronizerPrefs.removeObjectForKey("lastFetched")
// Not all synchronizers use a batching downloader, but it's
// convenient to just always reset it here.
return storage.resetClient()
>>> effect({ BatchingDownloader.resetDownloaderWithPrefs(synchronizerPrefs, collection: collection) })
}
} | mpl-2.0 | fb2d63762172be1210a16b6e0368b992 | 37.072034 | 159 | 0.6939 | 4.843127 | false | false | false | false |
sambhav7890/SSChartView | SSChartView/Classes/Graph/Graph.swift | 1 | 11343 | //
// Graph.swift
// Graphs
//
// Created by Sambhav Shah on 2016/09/02.
// Copyright © 2016 S. All rights reserved.
//
import UIKit
public enum GraphType {
case bar
// case line
// case pie
}
open class Graph<T: Hashable, U: NumericType> {
public typealias GraphTextDisplayHandler = (_ unit: GraphUnit<T, U>, _ totalValue: U) -> String?
let kind: GraphKind<T, U>
init(barGraph: BarGraph<T, U>) {
self.kind = GraphKind<T, U>.bar(barGraph)
}
// init(lineGraph: LineGraph<T, U>) {
// self.kind = GraphKind<T, U>.line(lineGraph)
// }
// init(pieGraph: PieGraph<T, U>) {
// self.kind = GraphKind<T, U>.pie(pieGraph)
// }
}
public extension Graph {
public convenience init<S: GraphData>(type: GraphType, data: [S], min minOrNil: U? = nil, max maxOrNil: U? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) where S.GraphDataKey == T, S.GraphDataValue == U {
let range = {() -> GraphRange<U>? in
if let min = minOrNil, let max = maxOrNil {
return GraphRange(min: min, max: max)
}
return nil
}
self.init(type: type, data: data, range: range(), textDisplayHandler: textDisplayHandler)
}
public convenience init<S: GraphData>(type: GraphType, data: [S], range rangeOrNil: GraphRange<U>? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) where S.GraphDataKey == T, S.GraphDataValue == U {
let r = {() -> GraphRange<U> in
if let r = rangeOrNil { return r }
let sorted = data.sorted { $0.value < $1.value }
return GraphRange<U>(
min: sorted.first?.value ?? U(0),
max: sorted.last?.value ?? U(0)
)
}
switch type {
case .bar:
self.init(barGraph:BarGraph<T, U>(
units: data.map { GraphUnit<T, U>(key: $0.key, value: $0.value) },
range: r(),
textDisplayHandler: textDisplayHandler
))
// case .line:
//
// self.init(lineGraph: LineGraph<T, U>(
// units: data.map { GraphUnit<T, U>(key: $0.key, value: $0.value) },
// range: r(),
// textDisplayHandler: textDisplayHandler
// ))
// case .pie:
//
// self.init(pieGraph: PieGraph<T, U>(
// units: data.map { GraphUnit<T, U>(key: $0.key, value: $0.value) },
// textDisplayHandler: textDisplayHandler
// ))
}
}
public convenience init(type: GraphType, array: [U], min minOrNil: U? = nil, max maxOrNil: U? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) {
let range = {() -> GraphRange<U>? in
if let min = minOrNil, let max = maxOrNil {
return GraphRange(min: min, max: max)
}
return nil
}
self.init(type: type, array: array, range: range(), textDisplayHandler: textDisplayHandler)
}
public convenience init(type: GraphType, array: [U], range rangeOrNil: GraphRange<U>? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) {
let r = {() -> GraphRange<U> in
if let r = rangeOrNil { return r }
let sorted = array.sorted { $0 < $1 }
return GraphRange<U>(
min: sorted.first ?? U(0),
max: sorted.last ?? U(0)
)
}
switch type {
case .bar:
self.init(barGraph:BarGraph<T, U>(
units: array.map { GraphUnit<T, U>(key: nil, value: $0) },
range: r(),
textDisplayHandler: textDisplayHandler
))
// case .line:
// self.init(lineGraph: LineGraph<T, U>(
// units: array.map { GraphUnit<T, U>(key: nil, value: $0) },
// range: r(),
// textDisplayHandler: textDisplayHandler
// ))
// case .pie:
// self.init(pieGraph: PieGraph<T, U>(
// units: array.map { GraphUnit<T, U>(key: nil, value: $0) },
// textDisplayHandler: textDisplayHandler
// ))
}
}
}
public extension Graph {
public convenience init(type: GraphType, dictionary: [T: U], min minOrNil: U? = nil, max maxOrNil: U? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) {
let range = {() -> GraphRange<U>? in
if let min = minOrNil, let max = maxOrNil {
return GraphRange(min: min, max: max)
}
return nil
}
self.init(type: type, dictionary: dictionary, range: range(), textDisplayHandler: textDisplayHandler)
}
public convenience init(type: GraphType, dictionary: [T: U], range rangeOrNil: GraphRange<U>? = nil, textDisplayHandler: GraphTextDisplayHandler? = nil) {
let sorted = dictionary.sorted { $0.1 < $1.1 }
let r = {() -> GraphRange<U> in
if let r = rangeOrNil { return r }
return GraphRange<U>(
min: sorted.first?.1 ?? U(0),
max: sorted.last?.1 ?? U(0)
)
}
switch type {
case .bar:
self.init(barGraph:BarGraph<T, U>(
units: sorted.map { GraphUnit<T, U>(key: $0.0, value: $0.1) },
range: r(),
textDisplayHandler: textDisplayHandler
))
// case .line:
//
// self.init(lineGraph: LineGraph<T, U>(
// units: sorted.map { GraphUnit<T, U>(key: $0.0, value: $0.1) },
// range: r(),
// textDisplayHandler: textDisplayHandler
// ))
// case .pie:
//
// self.init(pieGraph: PieGraph<T, U>(
// units: sorted.map { GraphUnit<T, U>(key: $0.0, value: $0.1) },
// textDisplayHandler: textDisplayHandler
// ))
//
}
}
}
public extension Graph {
public func view(_ frame: CGRect) -> GraphView<T, U> {
return GraphView(frame: frame, graph: self)
}
}
enum GraphKind<T: Hashable, U: NumericType> {
case bar(BarGraph<T, U>)
// case line(LineGraph<T, U>)
// case pie(PieGraph<T, U>)
internal static func barGraph(_ units: [GraphUnit<T, U>], range: GraphRange<U>) -> GraphKind<T, U> {
return GraphKind<T, U>.bar(BarGraph(units: units, range: range))
}
// internal static func lineGraph(_ units: [GraphUnit<T, U>], range: GraphRange<U>) -> GraphKind<T, U> {
// return GraphKind<T, U>.line(LineGraph(units: units, range: range))
// }
//
// internal static func pieGraph(_ units: [GraphUnit<T, U>]) -> GraphKind<T, U> {
// return GraphKind<T, U>.pie(PieGraph(units: units))
// }
}
public protocol GraphBase {
associatedtype UnitsType
associatedtype RangeType
associatedtype GraphTextDisplayHandler
var units: UnitsType { get }
var textDisplayHandler: GraphTextDisplayHandler? { get }
}
internal struct BarGraph<T: Hashable, U: NumericType>: GraphBase {
typealias GraphView = BarGraphView<T, U>
typealias UnitsType = [GraphUnit<T, U>]
typealias RangeType = GraphRange<U>
typealias GraphTextDisplayHandler = Graph<T, U>.GraphTextDisplayHandler
var units: [GraphUnit<T, U>]
var range: GraphRange<U>
var textDisplayHandler: GraphTextDisplayHandler?
internal init(
units: [GraphUnit<T, U>],
range: GraphRange<U>,
textDisplayHandler: GraphTextDisplayHandler? = nil
) {
self.units = units
self.range = range
self.textDisplayHandler = textDisplayHandler
}
func view(_ frame: CGRect) -> GraphView? {
return BarGraphView<T, U>(
frame: frame,
graph: self
)
}
func graphTextDisplay() -> GraphTextDisplayHandler {
if let f = textDisplayHandler {
return f
}
return { (unit, total) -> String? in String(describing: unit.value) }
}
}
//internal struct MultiBarGraph<T: Hashable, U: NumericType>: GraphBase {
//
// typealias UnitsType = [[GraphUnit<T, U>]]
// typealias RangeType = GraphRange<U>
// typealias GraphTextDisplayHandler = Graph<T, U>.GraphTextDisplayHandler
//
// var units: [[GraphUnit<T, U>]]
// var range: GraphRange<U>
// var textDisplayHandler: GraphTextDisplayHandler?
//
// func graphTextDisplay() -> GraphTextDisplayHandler {
// if let f = textDisplayHandler {
// return f
// }
// return { (unit, total) -> String? in String(describing: unit.value) }
// }
//}
//internal struct LineGraph<T: Hashable, U: NumericType>: GraphBase {
//
// typealias GraphView = LineGraphView<T, U>
// typealias UnitsType = [GraphUnit<T, U>]
// typealias RangeType = GraphRange<U>
// typealias GraphTextDisplayHandler = Graph<T, U>.GraphTextDisplayHandler
//
// var units: [GraphUnit<T, U>]
// var range: GraphRange<U>
// var textDisplayHandler: GraphTextDisplayHandler?
//
// init(
// units: [GraphUnit<T, U>],
// range: GraphRange<U>,
// textDisplayHandler: GraphTextDisplayHandler? = nil
// ) {
// self.units = units
// self.range = range
// self.textDisplayHandler = textDisplayHandler
// }
//
// func view(_ frame: CGRect) -> GraphView? {
// return LineGraphView(frame: frame, graph: self)
// }
//
// func graphTextDisplay() -> GraphTextDisplayHandler {
// if let f = textDisplayHandler {
// return f
// }
// return { (unit, total) -> String? in String(describing: unit.value) }
// }
//}
//internal struct PieGraph<T: Hashable, U: NumericType>: GraphBase {
//
// typealias GraphView = PieGraphView<T, U>
// typealias UnitsType = [GraphUnit<T, U>]
// typealias RangeType = GraphRange<U>
// typealias GraphTextDisplayHandler = Graph<T, U>.GraphTextDisplayHandler
//
// var units: [GraphUnit<T, U>]
// var textDisplayHandler: GraphTextDisplayHandler?
//
// init(
// units: [GraphUnit<T, U>],
// textDisplayHandler: GraphTextDisplayHandler? = nil
// ) {
// self.units = units
// self.textDisplayHandler = textDisplayHandler
// }
//
// func view(_ frame: CGRect) -> GraphView? {
// return PieGraphView(frame: frame, graph: self)
// }
//
// func graphTextDisplay() -> GraphTextDisplayHandler {
// if let f = textDisplayHandler {
// return f
// }
// return { (unit, total) -> String? in
// let f = unit.value.floatValue() / total.floatValue()
// return String(describing: unit.value) + " : " + String(format: "%.0f%%", f * 100.0)
// }
// }
//}
public struct GraphUnit<T: Hashable, U: NumericType> {
public let key: T?
public let value: U
public init(key: T?, value: U) {
self.key = key
self.value = value
}
}
public struct GraphRange<T: NumericType> {
let min: T
let max: T
public init(min: T, max: T) {
assert(min <= max)
self.min = min
self.max = max
}
}
public struct BarGraphApperance {
public let barColor: UIColor
public let barWidthScale: CGFloat
public let valueTextAttributes: GraphTextAttributes?
init(
barColor: UIColor?,
barWidthScale: CGFloat?,
valueTextAttributes: GraphTextAttributes?
) {
self.barColor = barColor ?? DefaultColorType.bar.color()
self.barWidthScale = barWidthScale ?? 0.8
self.valueTextAttributes = valueTextAttributes
}
}
public struct GraphTextAttributes {
public let font: UIFont
public let textColor: UIColor
public let textAlign: NSTextAlignment
init(
font: UIFont?,
textColor: UIColor?,
textAlign: NSTextAlignment?
) {
self.font = font ?? UIFont.systemFont(ofSize: 10.0)
self.textColor = textColor ?? UIColor.gray
self.textAlign = textAlign ?? .center
}
}
| mit | 2c218cc121f1c19ec6bb6047b27804fb | 27.56927 | 220 | 0.605008 | 3.706536 | false | false | false | false |
magicien/GLTFSceneKit | Sample/macOS/GameViewController.swift | 1 | 4652 | //
// GameViewController.swift
// GameSample
//
// Created by magicien on 2017/08/17.
// Copyright © 2017年 DarkHorse. All rights reserved.
//
import SceneKit
import QuartzCore
import GLTFSceneKit
class GameViewController: NSViewController {
@IBOutlet weak var gameView: GameView!
@IBOutlet weak var openFileButton: NSButton!
@IBOutlet weak var cameraSelect: NSPopUpButton!
var cameraNodes: [SCNNode] = []
let defaultCameraTag: Int = 99
override func awakeFromNib(){
super.awakeFromNib()
var scene: SCNScene
do {
let sceneSource = try GLTFSceneSource(named: "art.scnassets/GlassVase/Wayfair-GlassVase-BCHH2364.glb")
scene = try sceneSource.scene()
} catch {
print("\(error.localizedDescription)")
return
}
self.setScene(scene)
self.gameView!.autoenablesDefaultLighting = true
// allows the user to manipulate the camera
self.gameView!.allowsCameraControl = true
// show statistics such as fps and timing information
self.gameView!.showsStatistics = true
// configure the view
self.gameView!.backgroundColor = NSColor.gray
self.gameView!.addObserver(self, forKeyPath: "pointOfView", options: [.new], context: nil)
self.gameView!.delegate = self
}
func setScene(_ scene: SCNScene) {
// update camera names
self.cameraNodes = scene.rootNode.childNodes(passingTest: { (node, finish) -> Bool in
return node.camera != nil
})
// set the scene to the view
self.gameView!.scene = scene
// set the camera menu
self.cameraSelect.menu?.removeAllItems()
if self.cameraNodes.count > 0 {
self.cameraSelect.removeAllItems()
let titles = self.cameraNodes.map { $0.camera?.name ?? "untitled" }
for title in titles {
self.cameraSelect.menu?.addItem(withTitle: title, action: nil, keyEquivalent: "")
}
self.gameView!.pointOfView = self.cameraNodes[0]
}
//to give nice reflections :)
scene.lightingEnvironment.contents = "art.scnassets/shinyRoom.jpg"
scene.lightingEnvironment.intensity = 2;
let defaultCameraItem = NSMenuItem(title: "SCNViewFreeCamera", action: nil, keyEquivalent: "")
defaultCameraItem.tag = self.defaultCameraTag
defaultCameraItem.isEnabled = false
self.cameraSelect.menu?.addItem(defaultCameraItem)
self.cameraSelect.autoenablesItems = false
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "pointOfView", let change = change {
if let cameraNode = change[.newKey] as? SCNNode {
// It must use the main thread to change the UI.
DispatchQueue.main.async {
if let index = self.cameraNodes.index(of: cameraNode) {
self.cameraSelect.selectItem(at: index)
} else {
self.cameraSelect.selectItem(withTag: self.defaultCameraTag)
}
}
}
}
}
@IBAction func openFileButtonClicked(_ sender: Any) {
let openPanel = NSOpenPanel()
openPanel.canChooseFiles = true
openPanel.canChooseDirectories = false
openPanel.allowsMultipleSelection = false
openPanel.allowedFileTypes = ["gltf", "glb", "vrm"]
openPanel.message = "Choose glTF file"
openPanel.begin { (response) in
if response == .OK {
guard let url = openPanel.url else { return }
do {
let sceneSource = GLTFSceneSource.init(url: url)
let scene = try sceneSource.scene()
self.setScene(scene)
} catch {
print("\(error.localizedDescription)")
}
}
}
}
@IBAction func selectCamera(_ sender: Any) {
let index = self.cameraSelect.indexOfSelectedItem
let cameraNode = self.cameraNodes[index]
self.gameView!.pointOfView = cameraNode
}
}
extension GameViewController: SCNSceneRendererDelegate {
func renderer(_ renderer: SCNSceneRenderer, didApplyAnimationsAtTime time: TimeInterval) {
self.gameView.scene?.rootNode.updateVRMSpringBones(time: time)
}
}
| mit | deb591256c11b01884741d0345b2c1b8 | 34.48855 | 151 | 0.598838 | 5.097588 | false | false | false | false |
naithar/Kitura | Sources/Kitura/FileResourceServer.swift | 1 | 3402 | /*
* Copyright IBM Corporation 2016, 2017
*
* 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 LoggerAPI
class FileResourceServer {
/// if file found - send it in response
func sendIfFound(resource: String, usingResponse response: RouterResponse) {
guard let resourceFileName = getFilePath(for: resource) else {
do {
try response.send("Cannot find resource: \(resource)").status(.notFound).end()
} catch {
Log.error("failed to send not found response for resource: \(resource)")
}
return
}
do {
try response.send(fileName: resourceFileName)
try response.status(.OK).end()
} catch {
Log.error("failed to send response with resource \(resourceFileName)")
}
}
private func getFilePath(for resource: String) -> String? {
let fileManager = FileManager.default
var potentialResource = getResourcePathBasedOnSourceLocation(for: resource)
if potentialResource.hasSuffix("/") {
potentialResource += "index.html"
}
let fileExists = fileManager.fileExists(atPath: potentialResource)
if fileExists {
return potentialResource
} else {
return getResourcePathBasedOnCurrentDirectory(for: resource, withFileManager: fileManager)
}
}
private func getResourcePathBasedOnSourceLocation(for resource: String) -> String {
let fileName = NSString(string: #file)
let resourceFilePrefixRange: NSRange
let lastSlash = fileName.range(of: "/", options: .backwards)
if lastSlash.location != NSNotFound {
resourceFilePrefixRange = NSRange(location: 0, length: lastSlash.location+1)
} else {
resourceFilePrefixRange = NSRange(location: 0, length: fileName.length)
}
return fileName.substring(with: resourceFilePrefixRange) + "resources/" + resource
}
private func getResourcePathBasedOnCurrentDirectory(for resource: String, withFileManager fileManager: FileManager) -> String? {
for suffix in ["/Packages", "/.build/checkouts"] {
let packagePath = fileManager.currentDirectoryPath + suffix
do {
let packages = try fileManager.contentsOfDirectory(atPath: packagePath)
for package in packages {
let potentialResource = "\(packagePath)/\(package)/Sources/Kitura/resources/\(resource)"
let resourceExists = fileManager.fileExists(atPath: potentialResource)
if resourceExists {
return potentialResource
}
}
} catch {
Log.error("No packages found in \(packagePath)")
}
}
return nil
}
}
| apache-2.0 | 3377d2866fa279a30323cdc64cb8be6b | 38.103448 | 132 | 0.634333 | 5.25 | false | false | false | false |
BrandonMA/SwifterUI | SwifterUI/SwifterUI/ChatKit/Model/SFUser.swift | 1 | 6116 | //
// SFChatUser.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 8/28/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
import Kingfisher
import DeepDiff
public enum SFUserNotification: String {
case deleted
}
open class SFUser: SFDataType, Codable {
public var diffId: Int {
return identifier.hashValue
}
public static func compareContent(_ a: SFUser, _ b: SFUser) -> Bool {
return a.identifier == b.identifier
}
public func hash(into hasher: inout Hasher) {
hasher.combine(identifier.hashValue)
}
public enum CodingKeys: String, CodingKey {
case identifier
case name
case lastName
case profilePictureURL
}
// MARK: - Static Methods
public static func == (lhs: SFUser, rhs: SFUser) -> Bool {
return lhs.identifier == rhs.identifier &&
lhs.name == rhs.name &&
lhs.lastName == rhs.lastName &&
lhs.profilePictureURL == rhs.profilePictureURL
}
// MARK: - Instance Properties
open var identifier: String
open var name: String
open var lastName: String
open var profilePictureURL: String?
open var contactsManager = SFDataManager<SFUser>()
open var chatsManager = SFDataManager<SFChat>()
// MARK: - Initializers
public init(identifier: String = UUID().uuidString,
name: String,
lastName: String,
profilePictureURL: String? = nil) {
self.identifier = identifier
self.name = name
self.lastName = lastName
self.profilePictureURL = profilePictureURL
}
public required init(from decoder: Decoder) throws {
let data = try decoder.container(keyedBy: CodingKeys.self)
identifier = try data.decode(String.self, forKey: CodingKeys.identifier)
name = try data.decode(String.self, forKey: CodingKeys.name)
lastName = try data.decode(String.self, forKey: CodingKeys.lastName)
profilePictureURL = try data.decode(String?.self, forKey: CodingKeys.profilePictureURL)
}
// MARK: - Instance Methods
open func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(identifier, forKey: CodingKeys.identifier)
try container.encode(name, forKey: CodingKeys.name)
try container.encode(lastName, forKey: CodingKeys.lastName)
try container.encode(profilePictureURL, forKey: CodingKeys.profilePictureURL)
}
open func addNew(chat: SFChat) {
if !chatsManager.contains(item: chat) {
var inserted = false
for (index, currentChat) in chatsManager.flatData.enumerated() where chat.modificationDate > currentChat.modificationDate {
chatsManager.insertItem(chat, at: IndexPath(item: index, section: 0))
inserted = true
break
}
if !inserted {
chatsManager.insertItem(chat)
}
}
}
open func addNew(contact: SFUser) {
if contactsManager.contains(item: contact) == false &&
contact.identifier != identifier {
if let sectionIndex = contactsManager.firstIndex(where: {
$0.identifier.contains(contact.name.uppercased().first!)
}) {
for (index, _) in contactsManager[sectionIndex].enumerated() {
contactsManager.insertItem(contact, at: IndexPath(item: index, section: sectionIndex))
break
}
contactsManager[sectionIndex].content.sortByLastname()
} else {
let newSection = SFDataSection<SFUser>(content: [contact], identifier: "\(contact.name.uppercased().first!)")
if contactsManager.isEmpty {
contactsManager.insertSection(newSection)
} else {
var inserted = false
for (index, section) in contactsManager.enumerated() where section.identifier > newSection.identifier {
contactsManager.insertSection(newSection, at: index)
inserted = true
break
}
if (!inserted) {
contactsManager.insertSection(newSection)
}
}
}
}
}
}
public extension Array where Element: SFDataSection<SFUser> {
mutating func sortByInitial() {
sort(by: { return $0.identifier < $1.identifier }) // Each identifier is a letter in the alphabet
}
mutating func sortByLastname() {
forEach { (section) in
section.content.sort(by: { return $0.lastName < $1.lastName })
}
}
}
public extension Array where Element: SFUser {
mutating func sortByInitial() {
sort(by: { return $0.identifier < $1.identifier }) // Each identifier is a letter in the alphabet
}
mutating func sortByLastname() {
sort(by: { return $0.lastName < $1.lastName })
}
func createDataSections() -> [SFDataSection<SFUser>] {
var sections: [SFDataSection<SFUser>] = []
for contact in self {
if let index = sections.firstIndex(where: {
$0.identifier.contains(contact.name.uppercased().first!)
}) {
sections[index].content.append(contact)
} else {
let section = SFDataSection<SFUser>(content: [contact], identifier: "\(contact.name.uppercased().first!)")
sections.append(section)
}
}
return sections
}
func ordered() -> [SFDataSection<SFUser>] {
var sections = createDataSections()
sections.sortByInitial()
sections.sortByLastname()
return sections
}
}
| mit | b4411ca182ffb7428f844be8243333dd | 31.876344 | 135 | 0.581684 | 5.173435 | false | false | false | false |
HTWDD/htwcampus | HTWDD/Components/Exams/Models/Exam.swift | 1 | 2693 | //
// Exam.swift
// HTWDD
//
// Created by Benjamin Herzog on 05.11.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
import RxSwift
struct Exam: Codable, Identifiable, Equatable {
enum ExamType: Codable, Equatable {
case s, m, a, other(String)
init(from decoder: Decoder) throws {
let content = try decoder.singleValueContainer().decode(String.self)
switch content {
case "SP": self = .s
case "MP": self = .m
case "APL": self = .a
default: self = .other(content)
}
}
func encode(to encoder: Encoder) throws {
let c: String
switch self {
case .s: c = "SP"
case .m: c = "MP"
case .a: c = "APL"
case .other(let content): c = content
}
var container = encoder.singleValueContainer()
try container.encode(c)
}
var displayName: String {
switch self {
case .s:
return Loca.Exams.ExamType.written
case .m:
return Loca.Exams.ExamType.oral
case .a:
return Loca.Exams.ExamType.apl
case .other(let c):
return c
}
}
static func ==(lhs: ExamType, rhs: ExamType) -> Bool {
return lhs.displayName == rhs.displayName
}
}
let title: String
let type: ExamType
let branch: String
let examiner: String
let rooms: [String]
// TODO: This should be improved, just to show something
let day: String
let start: String
let end: String
private enum CodingKeys: String, CodingKey {
case title = "Title"
case type = "ExamType"
case branch = "StudyBranch"
case examiner = "Examiner"
case rooms = "Rooms"
case day = "Day"
case start = "StartTime"
case end = "EndTime"
}
static func ==(lhs: Exam, rhs: Exam) -> Bool {
return lhs.title == rhs.title && lhs.type == rhs.type && lhs.branch == rhs.branch && lhs.examiner == rhs.examiner && lhs.rooms == rhs.rooms
}
static let url = "https://www2.htw-dresden.de/~app/API/GetExams.php"
static func get(network: Network, auth: ScheduleService.Auth) -> Observable<[Exam]> {
let absc: String
switch auth.degree {
case .bachelor: absc = "B"
case .diplom: absc = "D"
case .master: absc = "M"
}
return network.getArray(url: url, params: [
"StgJhr": auth.year,
"Stg": auth.major,
"AbSc": absc,
"StgNr": auth.group
])
}
}
| mit | b74f2fa01df6c6b02fd7383de5b6e9f3 | 26.191919 | 147 | 0.535661 | 3.958824 | false | false | false | false |
AndreMuis/Algorithms | OneEditAway.playground/Contents.swift | 1 | 2464 | //
// Check if one string is one edit (insertion, removal, replacement) away from another string
//
import Foundation
func oneEditAway(first first : String, second : String) -> Bool
{
var oneAway : Bool = false
if first.characters.count == second.characters.count
{
oneAway = oneReplacementAway(string1: first, string2: second)
}
else if first.characters.count == second.characters.count + 1
{
oneAway = oneInsertAway(string1: second, string2: first)
}
else if first.characters.count + 1 == second.characters.count
{
oneAway = oneInsertAway(string1: first, string2: second)
}
return oneAway
}
func oneReplacementAway(string1 string1 : String, string2 : String) -> Bool
{
var index : String.CharacterView.Index = string1.startIndex
var nonMatchingCharactersCount = 0
while index < string1.endIndex
{
if string1[index] != string2[index]
{
nonMatchingCharactersCount += 1
}
index = index.successor()
}
return nonMatchingCharactersCount == 1
}
func oneInsertAway(string1 string1 : String, string2 : String) -> Bool
{
var index1 : String.CharacterView.Index = string1.startIndex
var index2 : String.CharacterView.Index = string2.startIndex
var oneAway : Bool = false
while index1 < string1.endIndex && index2 < string2.endIndex
{
if (string1[index1] == string2[index2])
{
index1 = index1.successor()
index2 = index2.successor()
}
else
{
if (index1 == index2)
{
oneAway = true
index2 = index2.successor()
}
else
{
oneAway = false
break
}
}
}
return oneAway
}
var first : String = "cart"
var second : String = "bart"
oneEditAway(first: first, second: second)
first = "brain"
second = "bran"
oneEditAway(first: first, second: second)
first = "favor"
second = "flavor"
oneEditAway(first: first, second: second)
first = "abcdefg"
second = "abcdefg"
oneEditAway(first: first, second: second)
first = "abcdefg"
second = "abxdefx"
oneEditAway(first: first, second: second)
first = "abcdefg"
second = "abcdefgxx"
oneEditAway(first: first, second: second)
first = "abcdefg"
second = "abcde"
oneEditAway(first: first, second: second)
| mit | 1af5104aaff1cf08e4962d13d1893029 | 19.881356 | 93 | 0.60836 | 4.059308 | false | false | false | false |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/Client/Client_Discover.swift | 1 | 6968 | //
// Client.swift
// TheMovieDbSwiftWrapper
//
// Created by George Kye on 2016-02-05.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
extension Client {
// COMBINATION OF ALL PARAMS, MOVIES & TV
static func discover(baseURL: String, params: [DiscoverParam], completion: @escaping (ClientReturn) -> Void) {
var parameters: [String: AnyObject] = [:]
for param in params {
switch param {
case .sort_by(let sort_by):
if sort_by != nil {
parameters["sort_by"] = sort_by as AnyObject?
}
case .certification_country(let certification_country):
if certification_country != nil {
parameters["certification_country"] = certification_country as AnyObject?
}
case .certification(let certification):
if certification != nil {
parameters["certification"] = certification as AnyObject?
}
case .certification_lte(let certification_lte):
if certification_lte != nil {
parameters["certification_lte"] = certification_lte as AnyObject?
}
case . include_adult(let include_adult):
if include_adult != nil {
parameters["include_adult"] = include_adult as AnyObject?
}
case .include_video(let include_video):
if include_video != nil {
parameters["include_video"] = include_video as AnyObject?
}
case .primary_release_year(let primary_release_year):
if primary_release_year != nil {
parameters["primary_release_year"] = primary_release_year as AnyObject?
}
case .primary_release_date_gte(let primary_release_date_gte):
if primary_release_date_gte != nil {
parameters["primary_release_date.gte"] = primary_release_date_gte as AnyObject?
}
case .primary_release_date_lte(let primary_release_date_lte):
if primary_release_date_lte != nil {
parameters["primary_release_date.lte"] = primary_release_date_lte as AnyObject?
}
case .release_date_gte(let release_date_gte):
if release_date_gte != nil {
parameters["release_date.gte"] = release_date_gte as AnyObject?
}
case .release_date_lte(let release_date_lte):
if release_date_lte != nil {
parameters["release_date.lte"] = release_date_lte as AnyObject?
}
case . air_date_gte(let air_date_gte):
if air_date_gte != nil {
parameters["air_date.gte"] = air_date_gte as AnyObject?
}
case .air_date_lte(let air_date_lte):
if air_date_lte != nil {
parameters["air_date.lte"] = air_date_lte as AnyObject?
}
case .first_air_date_gte(let first_air_date_gte):
if first_air_date_gte != nil {
parameters["first_air_date.gte"] = first_air_date_gte as AnyObject?
}
case .first_air_date_lte(let first_air_date_lte):
if first_air_date_lte != nil {
parameters["first_air_date.lte"] = first_air_date_lte as AnyObject?
}
case .first_air_date_year(let first_air_date_year):
if first_air_date_year != nil {
parameters["first_air_date_year"] = first_air_date_year as AnyObject?
}
case .language(let language):
if language != nil {
parameters["language"] = language as AnyObject?
}
case .page(let page):
if page != nil {
parameters["page"] = page as AnyObject?
}
case .timezone(let timezone):
if timezone != nil {
parameters["timezone"] = timezone as AnyObject?
}
case .vote_average_gte(let vote_average_gte):
if vote_average_gte != nil {
parameters["vote_average.gte"] = vote_average_gte as AnyObject?
}
case .vote_average_lte(let vote_average_lte):
if vote_average_lte != nil {
parameters["vote_average.lte"] = vote_average_lte as AnyObject?
}
case .vote_count_gte(let vote_count_gte):
if vote_count_gte != nil {
parameters["vote_count.gte"] = vote_count_gte as AnyObject?
}
case .vote_count_lte(let vote_count_lte):
if vote_count_lte != nil {
parameters["vote_count.lte"] = vote_count_lte as AnyObject?
}
case .with_genres(let with_genres):
if with_genres != nil {
parameters["with_genres"] = with_genres as AnyObject?
}
case .with_cast(let with_cast):
if with_cast != nil {
parameters["with_cast"] = with_cast as AnyObject?
}
case .with_crew(let with_crew):
if with_crew != nil {
parameters["with_crew"] = with_crew as AnyObject?
}
case .with_companies(let with_companies):
if with_companies != nil {
parameters["with_companies"] = with_companies as AnyObject?
}
case .with_keywords(let with_keywords):
if with_keywords != nil {
parameters["with_keywords"] = with_keywords as AnyObject?
}
case .with_people(let with_people):
if with_people != nil {
parameters["with_people"] = with_people as AnyObject?
}
case . with_networks(let with_networks):
if with_networks != nil {
parameters["with_networks"] = with_networks as AnyObject?
}
case .year(let year):
if year != nil {
parameters["year"] = year as AnyObject?
}
case .certification_gte(let certification_gte):
if certification_gte != nil {
parameters["certification_gte"] = certification_gte as AnyObject?
}
}
}
let url = "https://api.themoviedb.org/3/discover/" + baseURL
networkRequest(url: url, parameters: parameters) { apiReturn in
if apiReturn.error == nil {
completion(apiReturn)
}
}
}
}
| mit | 3949c898f073af3b444b941e6015a3af | 43.660256 | 114 | 0.499211 | 4.713802 | false | false | false | false |
sourcebitsllc/Asset-Generator-Mac | XCAssetGenerator/ProgressViewController.swift | 1 | 2757 | //
// ProgressController.swift
// XCAssetGenerator
//
// Created by Bader on 5/18/15.
// Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved.
//
import Foundation
import Cocoa
import ReactiveCocoa
class ProgressViewController: NSViewController {
var progressView: ProgressLineView
let viewModel: ProgressIndicationViewModel
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init?(viewModel: ProgressIndicationViewModel, width: CGFloat) {
self.viewModel = viewModel
progressView = ProgressLineView(width: width)
let lineWidth = viewModel.lineWidth // TODO: right now this is ignored.
super.init(nibName: nil, bundle: nil)
view = progressView
/// RAC3
viewModel.progress
|> observeOn(QueueScheduler.mainQueueScheduler)
|> observe(next: { progress in
self.viewModel.animating.put(true)
switch progress {
case .Ongoing(let amount):
self.progressView.animateTo(progress: amount)
case .Finished:
self.resetUI()
case .Started:
self.progressView.initiateProgress()
}
})
viewModel.color.producer
|> observeOn(QueueScheduler.mainQueueScheduler)
|> start(next: { color in
self.progressView.color = color
})
}
func resetProgress(completion: () -> Void) {
NSAnimationContext.runAnimationGroup({ (context: NSAnimationContext!) -> Void in
self.progressView.forceAnimateFullProgress()
}, completionHandler: { () -> Void in
NSAnimationContext.runAnimationGroup({ (context: NSAnimationContext!) -> Void in
self.progressView.animateFadeOut()
}, completionHandler: { () -> Void in
self.progressView.resetProgress()
completion()
})
})
}
func resetUI() {
NSAnimationContext.runAnimationGroup({ (context: NSAnimationContext!) -> Void in
self.progressView.forceAnimateFullProgress()
}, completionHandler: { () -> Void in
NSAnimationContext.runAnimationGroup({ (context: NSAnimationContext!) -> Void in
self.progressView.animateFadeOut()
}, completionHandler: { () -> Void in
self.progressView.resetProgress()
self.viewModel.animating.put(false)
})
})
}
} | mit | 30eec3e1023c8319d40d1d2001b36ca0 | 33.049383 | 96 | 0.556765 | 5.853503 | false | false | false | false |
moqada/swift-sandbox | tutorials/FoodTracker/FoodTracker/Meal.swift | 1 | 1748 | //
// Meal.swift
// FoodTracker
//
// Created by Masahiko Okada on 2015/10/03.
//
//
import UIKit
class Meal: NSObject, NSCoding {
// MARK: Properties
var name: String
var photo: UIImage?
var rating: Int
// MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("meals")
// MARK: Types
struct PropertyKey {
static let nameKey = "name"
static let photoKey = "photo"
static let ratingKey = "rating"
}
// MARK: Initialization
init?(name: String, photo: UIImage?, rating: Int) {
self.name = name
self.photo = photo
self.rating = rating
super.init()
// Inititialization should fail if there is no name or if the rating is negative.
if name.isEmpty || rating < 0 {
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
aCoder.encodeObject(photo, forKey: PropertyKey.photoKey)
aCoder.encodeInteger(rating, forKey: PropertyKey.ratingKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String
// Because photo is an optional property of Meal, use conditional cast.
let photo = aDecoder.decodeObjectForKey(PropertyKey.photoKey) as! UIImage
let rating = aDecoder.decodeIntegerForKey(PropertyKey.ratingKey)
// Must call designated initializer.
self.init(name: name, photo: photo, rating: rating)
}
}
| mit | 361192df112f849792d01537c69bb689 | 28.133333 | 123 | 0.658467 | 4.648936 | false | false | false | false |
AnRanScheme/magiGlobe | magi/magiGlobe/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift | 79 | 5000 | //
// ObservableType+Extensions.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Subscribes an event handler to an observable sequence.
- parameter on: Action to invoke for each event in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(_ on: @escaping (Event<E>) -> Void)
-> Disposable {
let observer = AnonymousObserver { e in
on(e)
}
return self.subscribeSafe(observer)
}
#if DEBUG
/**
Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is canceled by disposing subscription).
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(file: String = #file, line: UInt = #line, function: String = #function, onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
-> Disposable {
let disposable: Disposable
if let disposed = onDisposed {
disposable = Disposables.create(with: disposed)
}
else {
disposable = Disposables.create()
}
#if DEBUG
let _synchronizationTracker = SynchronizationTracker()
#endif
let observer = AnonymousObserver<E> { e in
#if DEBUG
_synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { _synchronizationTracker.unregister() }
#endif
switch e {
case .next(let value):
onNext?(value)
case .error(let e):
if let onError = onError {
onError(e)
}
else {
print("Received unhandled error: \(file):\(line):\(function) -> \(e)")
}
disposable.dispose()
case .completed:
onCompleted?()
disposable.dispose()
}
}
return Disposables.create(
self.subscribeSafe(observer),
disposable
)
}
#else
/**
Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is canceled by disposing subscription).
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)
-> Disposable {
let disposable: Disposable
if let disposed = onDisposed {
disposable = Disposables.create(with: disposed)
}
else {
disposable = Disposables.create()
}
let observer = AnonymousObserver<E> { e in
switch e {
case .next(let value):
onNext?(value)
case .error(let e):
onError?(e)
disposable.dispose()
case .completed:
onCompleted?()
disposable.dispose()
}
}
return Disposables.create(
self.subscribeSafe(observer),
disposable
)
}
#endif
}
extension ObservableType {
/// All internal subscribe calls go through this method.
fileprivate func subscribeSafe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
return self.asObservable().subscribe(observer)
}
}
| mit | 5daa31b629afcafae5ad2c85db6cd066 | 38.674603 | 239 | 0.565913 | 5.616854 | false | false | false | false |
jlecomte/EarthquakeTracker | EarthquakeTracker/Seismometer/SeismoModel.swift | 1 | 1984 | //
// SeismoModel.swift
// EarthquakeTracker
//
// Created by Andrew Folta on 10/11/14.
// Copyright (c) 2014 Andrew Folta. All rights reserved.
//
import UIKit
import CoreMotion
let SEISMO_UPDATE_INTERVAL = 1.0 / 20.0
@objc protocol SeismoModelDelegate {
func reportMagnitude(magnitude: Double)
func reportNoAccelerometer()
}
@objc class SeismoModel {
var delegate: SeismoModelDelegate?
init() {}
// start listening for seismic activity
func start() {
var first = true
if motionManager == nil {
motionManager = CMMotionManager()
}
if !motionManager!.accelerometerAvailable {
delegate?.reportNoAccelerometer()
return
}
motionManager!.accelerometerUpdateInterval = SEISMO_UPDATE_INTERVAL
motionManager!.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: {
(data: CMAccelerometerData?, error: NSError?) -> Void in
if error != nil {
// FUTURE -- handle error
self.motionManager!.stopAccelerometerUpdates()
}
if data != nil {
var magnitude = sqrt(
(data!.acceleration.x * data!.acceleration.x) +
(data!.acceleration.y * data!.acceleration.y) +
(data!.acceleration.z * data!.acceleration.z)
)
if first {
self.lastMagnitude = magnitude
first = false
}
dispatch_async(dispatch_get_main_queue(), {
self.delegate?.reportMagnitude(magnitude - self.lastMagnitude)
self.lastMagnitude = magnitude
})
}
})
}
// stop listening for seismic activity
func stop() {
motionManager?.stopAccelerometerUpdates()
}
private var motionManager: CMMotionManager?
private var lastMagnitude = 0.0
}
| mit | 17922c83f46d5f23e7e1562e281e3e4a | 27.342857 | 90 | 0.572077 | 5.139896 | false | false | false | false |
tiagomartinho/swift-corelibs-xctest | Sources/XCTest/Public/XCTestCase+Performance.swift | 1 | 9812 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//
// XCTestCase+Performance.swift
// Methods on XCTestCase for testing the performance of code blocks.
//
public struct XCTPerformanceMetric : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(_ lhs: XCTPerformanceMetric, _ rhs: XCTPerformanceMetric) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
public extension XCTPerformanceMetric {
/// Records wall clock time in seconds between `startMeasuring`/`stopMeasuring`.
public static let wallClockTime = XCTPerformanceMetric(rawValue: WallClockTimeMetric.name)
}
/// The following methods are called from within a test method to carry out
/// performance testing on blocks of code.
public extension XCTestCase {
/// The names of the performance metrics to measure when invoking `measure(block:)`.
/// Returns `XCTPerformanceMetric_WallClockTime` by default. Subclasses can
/// override this to change the behavior of `measure(block:)`
class var defaultPerformanceMetrics: [XCTPerformanceMetric] {
return [.wallClockTime]
}
/// Call from a test method to measure resources (`defaultPerformanceMetrics`)
/// used by the block in the current process.
///
/// func testPerformanceOfMyFunction() {
/// measure {
/// // Do that thing you want to measure.
/// MyFunction();
/// }
/// }
///
/// - Parameter block: A block whose performance to measure.
/// - Bug: The `block` param should have no external label, but there seems
/// to be a swiftc bug that causes issues when such a parameter comes
/// after a defaulted arg. See https://bugs.swift.org/browse/SR-1483 This
/// API incompatibility with Apple XCTest can be worked around in practice
/// by using trailing closure syntax when calling this method.
/// - ToDo: The `block` param should be marked @noescape once Apple XCTest
/// has been updated to do so rdar://26224596
/// - Note: Whereas Apple XCTest determines the file and line number of
/// measurements by using symbolication, this implementation opts to take
/// `file` and `line` as parameters instead. As a result, the interface to
/// these methods are not exactly identical between these environments. To
/// ensure compatibility of tests between swift-corelibs-xctest and Apple
/// XCTest, it is not recommended to pass explicit values for `file` and `line`.
func measure(file: StaticString = #file, line: Int = #line, block: () -> Void) {
measureMetrics(type(of: self).defaultPerformanceMetrics,
automaticallyStartMeasuring: true,
file: file,
line: line,
for: block)
}
/// Call from a test method to measure resources (XCTPerformanceMetrics) used
/// by the block in the current process. Each metric will be measured across
/// calls to the block. The number of times the block will be called is undefined
/// and may change in the future. For one example of why, as long as the requested
/// performance metrics do not interfere with each other the API will measure
/// all metrics across the same calls to the block. If the performance metrics
/// may interfere the API will measure them separately.
///
/// func testMyFunction2_WallClockTime() {
/// measureMetrics(type(of: self).defaultPerformanceMetrics, automaticallyStartMeasuring: false) {
///
/// // Do setup work that needs to be done for every iteration but
/// // you don't want to measure before the call to `startMeasuring()`
/// SetupSomething();
/// self.startMeasuring()
///
/// // Do that thing you want to measure.
/// MyFunction()
/// self.stopMeasuring()
///
/// // Do teardown work that needs to be done for every iteration
/// // but you don't want to measure after the call to `stopMeasuring()`
/// TeardownSomething()
/// }
/// }
///
/// Caveats:
/// * If `true` was passed for `automaticallyStartMeasuring` and `startMeasuring()`
/// is called anyway, the test will fail.
/// * If `false` was passed for `automaticallyStartMeasuring` then `startMeasuring()`
/// must be called once and only once before the end of the block or the test will fail.
/// * If `stopMeasuring()` is called multiple times during the block the test will fail.
///
/// - Parameter metrics: An array of Strings (XCTPerformanceMetrics) to measure.
/// Providing an unrecognized string is a test failure.
/// - Parameter automaticallyStartMeasuring: If `false`, `XCTestCase` will
/// not take any measurements until -startMeasuring is called.
/// - Parameter block: A block whose performance to measure.
/// - ToDo: The `block` param should be marked @noescape once Apple XCTest
/// has been updated to do so. rdar://26224596
/// - Note: Whereas Apple XCTest determines the file and line number of
/// measurements by using symbolication, this implementation opts to take
/// `file` and `line` as parameters instead. As a result, the interface to
/// these methods are not exactly identical between these environments. To
/// ensure compatibility of tests between swift-corelibs-xctest and Apple
/// XCTest, it is not recommended to pass explicit values for `file` and `line`.
func measureMetrics(_ metrics: [XCTPerformanceMetric], automaticallyStartMeasuring: Bool, file: StaticString = #file, line: Int = #line, for block: () -> Void) {
guard _performanceMeter == nil else {
return recordAPIViolation(description: "Can only record one set of metrics per test method.", file: file, line: line)
}
PerformanceMeter.measureMetrics(metrics.map({ $0.rawValue }), delegate: self, file: file, line: line) { meter in
self._performanceMeter = meter
if automaticallyStartMeasuring {
meter.startMeasuring(file: file, line: line)
}
block()
}
}
/// Call this from within a measure block to set the beginning of the critical
/// section. Measurement of metrics will start at this point.
/// - Note: Whereas Apple XCTest determines the file and line number of
/// measurements by using symbolication, this implementation opts to take
/// `file` and `line` as parameters instead. As a result, the interface to
/// these methods are not exactly identical between these environments. To
/// ensure compatibility of tests between swift-corelibs-xctest and Apple
/// XCTest, it is not recommended to pass explicit values for `file` and `line`.
func startMeasuring(file: StaticString = #file, line: Int = #line) {
guard let performanceMeter = _performanceMeter, !performanceMeter.didFinishMeasuring else {
return recordAPIViolation(description: "Cannot start measuring. startMeasuring() is only supported from a block passed to measureMetrics(...).", file: file, line: line)
}
performanceMeter.startMeasuring(file: file, line: line)
}
/// Call this from within a measure block to set the ending of the critical
/// section. Measurement of metrics will stop at this point.
/// - Note: Whereas Apple XCTest determines the file and line number of
/// measurements by using symbolication, this implementation opts to take
/// `file` and `line` as parameters instead. As a result, the interface to
/// these methods are not exactly identical between these environments. To
/// ensure compatibility of tests between swift-corelibs-xctest and Apple
/// XCTest, it is not recommended to pass explicit values for `file` and `line`.
func stopMeasuring(file: StaticString = #file, line: Int = #line) {
guard let performanceMeter = _performanceMeter, !performanceMeter.didFinishMeasuring else {
return recordAPIViolation(description: "Cannot stop measuring. stopMeasuring() is only supported from a block passed to measureMetrics(...).", file: file, line: line)
}
performanceMeter.stopMeasuring(file: file, line: line)
}
}
extension XCTestCase: PerformanceMeterDelegate {
internal func recordAPIViolation(description: String, file: StaticString, line: Int) {
recordFailure(withDescription: "API violation - \(description)",
inFile: String(describing: file),
atLine: line,
expected: false)
}
internal func recordMeasurements(results: String, file: StaticString, line: Int) {
XCTestObservationCenter.shared.testCase(self, didMeasurePerformanceResults: results, file: file, line: line)
}
internal func recordFailure(description: String, file: StaticString, line: Int) {
recordFailure(withDescription: "failed: " + description, inFile: String(describing: file), atLine: line, expected: true)
}
}
| apache-2.0 | 2cc71464f3cb54aa4f289f63a96d318b | 51.191489 | 180 | 0.665206 | 4.940584 | false | true | false | false |
darioalessandro/Theater | Pods/Nimble/Sources/Nimble/Matchers/PostNotification.swift | 6 | 4168 | import Foundation
internal class NotificationCollector {
private(set) var observedNotifications: [Notification]
private let notificationCenter: NotificationCenter
private var token: NSObjectProtocol?
required init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
self.observedNotifications = []
}
func startObserving() {
// swiftlint:disable:next line_length
self.token = self.notificationCenter.addObserver(forName: nil, object: nil, queue: nil) { [weak self] notification in
// linux-swift gets confused by .append(n)
self?.observedNotifications.append(notification)
}
}
deinit {
if let token = self.token {
self.notificationCenter.removeObserver(token)
}
}
}
private let mainThread = pthread_self()
public func postNotifications(
_ predicate: Predicate<[Notification]>,
from center: NotificationCenter = .default
) -> Predicate<Any> {
_ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center)
collector.startObserving()
var once: Bool = false
return Predicate { actualExpression in
let collectorNotificationsExpression = Expression(
memoizedExpression: { _ in
return collector.observedNotifications
},
location: actualExpression.location,
withoutCaching: true
)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let actualValue: String
if collector.observedNotifications.isEmpty {
actualValue = "no notifications"
} else {
actualValue = "<\(stringify(collector.observedNotifications))>"
}
var result = try predicate.satisfies(collectorNotificationsExpression)
result.message = result.message.replacedExpectation { message in
return .expectedCustomValueTo(message.expectedMessage, actualValue)
}
return result
}
}
@available(*, deprecated, renamed: "postNotifications(_:from:)")
public func postNotifications(
_ predicate: Predicate<[Notification]>,
fromNotificationCenter center: NotificationCenter
) -> Predicate<Any> {
return postNotifications(predicate, from: center)
}
public func postNotifications<T>(
_ notificationsMatcher: T,
from center: NotificationCenter = .default
)-> Predicate<Any> where T: Matcher, T.ValueType == [Notification] {
_ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center)
collector.startObserving()
var once: Bool = false
return Predicate { actualExpression in
let collectorNotificationsExpression = Expression(memoizedExpression: { _ in
return collector.observedNotifications
}, location: actualExpression.location, withoutCaching: true)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let failureMessage = FailureMessage()
let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage)
if collector.observedNotifications.isEmpty {
failureMessage.actualValue = "no notifications"
} else {
failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>"
}
return PredicateResult(bool: match, message: failureMessage.toExpectationMessage())
}
}
@available(*, deprecated, renamed: "postNotifications(_:from:)")
public func postNotifications<T>(
_ notificationsMatcher: T,
fromNotificationCenter center: NotificationCenter
)-> Predicate<Any> where T: Matcher, T.ValueType == [Notification] {
return postNotifications(notificationsMatcher, from: center)
}
| apache-2.0 | 87989e56da2c8d6adfbc97711c89d065 | 35.561404 | 125 | 0.680662 | 5.557333 | false | false | false | false |
idapgroup/IDPDesign | Tests/iOS/iOSTests/Extensions/CATransform3D+Equatable.swift | 1 | 719 | //
// CATransform3D+Equatable.swift
// iOSTests
//
// Created by Oleksa 'trimm' Korin on 10/3/17.
// Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved.
//
import UIKit
extension CATransform3D: Equatable {
public static func ==(lhs: CATransform3D, rhs: CATransform3D) -> Bool {
let getters: [(CATransform3D) -> CGFloat] = [
{ $0.m11 }, { $0.m12 }, { $0.m13 }, { $0.m14 },
{ $0.m21 }, { $0.m22 }, { $0.m23 }, { $0.m24 },
{ $0.m31 }, { $0.m32 }, { $0.m33 }, { $0.m34 },
{ $0.m41 }, { $0.m42 }, { $0.m43 }, { $0.m44 }
]
return getters
.map { $0(lhs) == $0(rhs) }
.reduce(true) { $0 && $1 }
}
}
| bsd-3-clause | 4ea76bc5575da56252af04d25bdc6038 | 28.916667 | 75 | 0.469359 | 2.826772 | false | false | false | false |
heitorgcosta/Quiver | Quiver/Validating/Default Validators/ComparatorValidator.swift | 1 | 1623 | //
// ComparatorValidator.swift
// Quiver
//
// Created by Heitor Costa on 19/09/17.
// Copyright © 2017 Heitor Costa. All rights reserved.
//
class ComparatorValidator<T>: Validator where T: Comparable {
typealias ComparationOperator = (T, T) -> Bool
private var value: T
private var operation: ComparationOperator
init(value: T, operation: @escaping ComparationOperator) {
self.value = value
self.operation = operation
}
override func validate(with object: Any?) throws -> Bool {
if object == nil {
return true
}
if let value = object {
print(value)
}
guard let value = object as? T else {
throw ValidationErrorType.typeMismatch(expected: T.self, actual: type(of: object!))
}
return operation(value, self.value)
}
}
class ComparatorEnumValidator<T>: Validator where T: RawRepresentable, T.RawValue: Equatable {
typealias ComparationOperator = (T, T) -> Bool
private var value: T
private var operation: ComparationOperator
init(value: T, operation: @escaping ComparationOperator) {
self.value = value
self.operation = operation
}
override func validate(with object: Any?) throws -> Bool {
if object == nil {
return true
}
guard let value = object! as? T else {
throw ValidationErrorType.typeMismatch(expected: T.self, actual: type(of: object!))
}
return operation(value, self.value)
}
}
| mit | aa952417b9e1c68dd21911a345d6d2eb | 26.033333 | 95 | 0.594945 | 4.728863 | false | false | false | false |
jrendel/SwiftKeychainWrapper | SwiftKeychainWrapperTests/KeychainWrapperDeleteTests.swift | 1 | 2178 | //
// KeychainWrapperDeleteTests.swift
// SwiftKeychainWrapper
//
// Created by Jason Rendel on 3/25/16.
// Copyright © 2016 Jason Rendel. All rights reserved.
//
import XCTest
import SwiftKeychainWrapper
class KeychainWrapperDeleteTests: XCTestCase {
let testKey = "deleteTestKey"
let testString = "This is a test"
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRemoveAllKeysDeletesSpecificKey() {
// save a value we can test delete on
let stringSaved = KeychainWrapper.standard.set(testString, forKey: testKey)
XCTAssertTrue(stringSaved, "String did not save to Keychain")
// delete all
let removeSuccessful = KeychainWrapper.standard.removeAllKeys()
XCTAssertTrue(removeSuccessful, "Failed to remove all Keys")
// confirm our test value was deleted
let retrievedValue = KeychainWrapper.standard.string(forKey: testKey)
XCTAssertNil(retrievedValue, "Test value was not deleted")
}
func testWipeKeychainDeletesSpecificKey() {
// save a value we can test delete on
let stringSaved = KeychainWrapper.standard.set(testString, forKey: testKey)
XCTAssertTrue(stringSaved, "String did not save to Keychain")
// delete all
KeychainWrapper.wipeKeychain()
// confirm our test value was deleted
let retrievedValue = KeychainWrapper.standard.string(forKey: testKey)
XCTAssertNil(retrievedValue, "Test value was not deleted")
// clean up keychain
KeychainWrapper.standard.removeObject(forKey: testKey)
}
// func testRemoveAllKeysOnlyRemovesKeysForCurrentServiceName() {
//
// }
//
// func testRemoveAllKeysOnlyRemovesKeysForCurrentAccessGroup() {
//
// }
}
| mit | d58b9038379a3b04e7cf2e424e621446 | 31.014706 | 111 | 0.652733 | 5.098361 | false | true | false | false |
threemonkee/VCLabs | VCLabs/NavMenuVC.swift | 1 | 3436 | //
// NavMenuVC.swift
// VCLabs
//
// Created by Victor Chandra on 2/01/2016.
// Copyright © 2016 Victor. All rights reserved.
//
import UIKit
import RESideMenu
class NavMenuVC: UITableViewController, NavContentDelegate
{
let arrayMenu = [
"Navigation Bar",
"Tab Bar",
"Side Menu"
]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return arrayMenu.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = arrayMenu[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
switch arrayMenu[indexPath.row]
{
case "Navigation Bar":
openNavigationBar()
case "Tab Bar":
openTabBar()
case "Side Menu":
openSideMenu()
default:
break;
}
}
// MARK: -
func navContentClose(content: NavContentVC?, message: String?)
{
dismissViewControllerAnimated(true, completion: nil)
}
func openNavigationBar ()
{
let navContent = NavContentVC()
navContent.navigationItem.title = "Navigation Bar"
navContent.label.text = "This is Navigation Bar mechanism provided by Apple's UIKit"
navContent.delegate = self
let navMenuController = UINavigationController(rootViewController: navContent)
presentViewController(navMenuController, animated: true, completion: nil)
}
func openTabBar ()
{
let navContentLeft = NavContentVC()
navContentLeft.label.text = "Left Tab Bar. This is Tab Bar mechanism provided by Apple's UIKit"
navContentLeft.tabBarItem = UITabBarItem(tabBarSystemItem: .Favorites, tag: 0)
navContentLeft.delegate = self
let navContentRight = NavContentVC()
navContentRight.label.text = "Right Tab Bar. This is Tab Bar mechanism provided by Apple's UIKit"
navContentRight.tabBarItem = UITabBarItem(tabBarSystemItem: .Bookmarks, tag: 1)
navContentRight.delegate = self
let navMenuController = UITabBarController()
navMenuController.viewControllers = [navContentLeft, navContentRight]
presentViewController(navMenuController, animated: true, completion: nil)
}
func openSideMenu ()
{
let contentVC = SideMenuFirstVC()
let navCon = UINavigationController(rootViewController: contentVC)
let leftVC = SideMenuLeftVC()
let rightVC = SideMenuRightVC()
let reSideMenu = RESideMenu.init(contentViewController: navCon, leftMenuViewController: leftVC, rightMenuViewController: rightVC)
reSideMenu.backgroundImage = UIImage(named: "Stars")
presentViewController(reSideMenu, animated: true, completion: nil)
}
}
| gpl-2.0 | 9dd4a16b97a15fe28ffa25dcd0c9c801 | 32.349515 | 137 | 0.67016 | 5.23628 | false | false | false | false |
kfix/MacPin | Sources/MacPin/WebViewController.swift | 1 | 2713 | /// MacPin WebViewController
///
/// Interlocute WebViews to general app UI
import WebKit
import WebKitPrivates
import JavaScriptCore
// https://github.com/apple/swift-evolution/blob/master/proposals/0160-objc-inference.md#re-enabling-objc-inference-within-a-class-hierarchy
@objcMembers
class WebViewController: ViewController { //, WebViewControllerScriptExports {
@objc unowned var webview: MPWebView
#if os(OSX)
override func loadView() { view = NSView() } // NIBless
#endif
let browsingReactor = AppScriptRuntime.shared
// ^ this is a simple object that can re-broadcast events from the webview and return with confirmation that those events were "handled" or not.
// this lets the controller know whether it should perform "reasonable browser-like actions" or to defer to the Reactor's business logic.
required init?(coder: NSCoder) { self.webview = MPWebView(); super.init(coder: coder); } // required by NSCoding protocol
#if os(OSX)
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { self.webview = MPWebView(); super.init(nibName:nil, bundle:nil) } //calls loadView
#endif
required init(webview: MPWebView) {
self.webview = webview
super.init(nibName: nil, bundle: nil)
webview.navigationDelegate = self // allows/denies navigation actions: see WebViewDelegates
webview._inputDelegate = self
webview._findDelegate = self
if WebKit_version >= (603, 1, 17) {
// STP 57, Safari 12
webview._iconLoadingDelegate = self
}
//webview._historyDelegate = self
#if DEBUG
//webview._diagnosticLoggingDelegate = self
#endif
webview.configuration.processPool._downloadDelegate = self
webview.configuration.processPool._setCanHandleHTTPSServerTrustEvaluation(true)
WebViewUICallbacks.subscribe(webview)
#if os(OSX)
representedObject = webview // OSX omnibox/browser uses KVC to interrogate webview
view.addSubview(webview, positioned: .below, relativeTo: nil)
// must retain the empty parent view for the inspector to co-attach to alongside the webview
#elseif os(iOS)
view = webview
#endif
}
override func viewDidLoad() {
super.viewDidLoad()
}
@objc func askToOpenCurrentURL() { askToOpenURL(webview.url as URL?) }
// sugar for delgates' opening a new tab in parent browser VC
func popup(_ webview: MPWebView) -> WebViewController {
let wvc = type(of: self).init(webview: webview)
parent?.addChild(wvc)
return wvc
}
@objc dynamic func focus() { warn("method not implemented by \(type(of: self))!") }
@objc dynamic func dismiss() { warn("method not implemented by \(type(of: self))!") }
@objc dynamic func close() { warn("method not implemented by \(type(of: self))!") }
deinit {
warn(description)
}
}
| gpl-3.0 | 600deb8efc148892e622fa0d2bfd92fd | 33.782051 | 166 | 0.7453 | 3.837341 | false | false | false | false |
divljiboy/IOSChatApp | Quick-Chat/Pods/BulletinBoard/Sources/Support/BulletinViewController.swift | 1 | 20098 | /**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* A view controller that displays a card at the bottom of the screen.
*/
final class BulletinViewController: UIViewController, UIGestureRecognizerDelegate {
/// The object managing the view controller.
weak var manager: BLTNItemManager?
// MARK: - UI Elements
/// The subview that contains the contents of the card.
let contentView = RoundedView()
/// The button that allows the users to close the bulletin.
let closeButton = BulletinCloseButton()
/**
* The stack view displaying the content of the card.
*
* - warning: You should not customize the distribution, axis and alignment of the stack, as this
* may break the layout of the card.
*/
let contentStackView = UIStackView()
/// The view covering the content. Generated in `loadBackgroundView`.
var backgroundView: BulletinBackgroundView!
/// The activity indicator.
let activityIndicator = ActivityIndicator()
// MARK: - Dismissal Support Properties
/// Indicates whether the bulletin can be dismissed by a tap outside the card.
var isDismissable: Bool = false
/// The snapshot view of the content used during dismissal.
var activeSnapshotView: UIView?
/// The active swipe interaction controller.
var swipeInteractionController: BulletinSwipeInteractionController!
// MARK: - Private Interface Elements
// Compact constraints
fileprivate var leadingConstraint: NSLayoutConstraint!
fileprivate var trailingConstraint: NSLayoutConstraint!
fileprivate var centerXConstraint: NSLayoutConstraint!
fileprivate var maxWidthConstraint: NSLayoutConstraint!
// Regular constraints
fileprivate var widthConstraint: NSLayoutConstraint!
fileprivate var centerYConstraint: NSLayoutConstraint!
// Stack view constraints
fileprivate var stackLeadingConstraint: NSLayoutConstraint!
fileprivate var stackTrailingConstraint: NSLayoutConstraint!
fileprivate var stackBottomConstraint: NSLayoutConstraint!
// Position constraints
fileprivate var minYConstraint: NSLayoutConstraint!
fileprivate var contentTopConstraint: NSLayoutConstraint!
fileprivate var contentBottomConstraint: NSLayoutConstraint!
// MARK: - Deinit
deinit {
cleanUpKeyboardLogic()
}
}
// MARK: - Lifecycle
extension BulletinViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setUpLayout(with: traitCollection)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
/// Animate status bar appearance when hiding
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
self.setNeedsStatusBarAppearanceUpdate()
})
}
override func loadView() {
super.loadView()
view.backgroundColor = .clear
let recognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
recognizer.delegate = self
recognizer.cancelsTouchesInView = false
recognizer.delaysTouchesEnded = false
view.addGestureRecognizer(recognizer)
contentView.accessibilityViewIsModal = true
contentView.translatesAutoresizingMaskIntoConstraints = false
contentStackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(contentView)
// Content View
centerXConstraint = contentView.centerXAnchor.constraint(equalTo: view.safeCenterXAnchor)
centerYConstraint = contentView.centerYAnchor.constraint(equalTo: view.safeCenterYAnchor)
centerYConstraint.constant = 2500
widthConstraint = contentView.widthAnchor.constraint(equalToConstant: 444)
widthConstraint.priority = UILayoutPriorityRequired
// Close button
contentView.addSubview(closeButton)
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12).isActive = true
closeButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -12).isActive = true
closeButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
closeButton.widthAnchor.constraint(equalToConstant: 44).isActive = true
closeButton.isUserInteractionEnabled = true
closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
// Content Stack View
contentView.addSubview(contentStackView)
stackLeadingConstraint = contentStackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
stackLeadingConstraint.isActive = true
stackTrailingConstraint = contentStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
stackTrailingConstraint.isActive = true
minYConstraint = contentView.topAnchor.constraint(greaterThanOrEqualTo: view.safeTopAnchor)
minYConstraint.isActive = true
minYConstraint.priority = UILayoutPriorityRequired
contentStackView.axis = .vertical
contentStackView.alignment = .fill
contentStackView.distribution = .fill
// Activity Indicator
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(activityIndicator)
activityIndicator.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
activityIndicator.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
activityIndicator.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
activityIndicator.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
activityIndicator.activityIndicatorViewStyle = .whiteLarge
activityIndicator.color = .black
activityIndicator.isUserInteractionEnabled = false
activityIndicator.alpha = 0
// Vertical Position
stackBottomConstraint = contentStackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
contentTopConstraint = contentView.topAnchor.constraint(equalTo: contentStackView.topAnchor)
stackBottomConstraint.isActive = true
contentTopConstraint.isActive = true
// Configuration
configureContentView()
setUpKeyboardLogic()
contentView.bringSubview(toFront: closeButton)
}
@available(iOS 11.0, *)
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
updateCornerRadius()
setUpLayout(with: traitCollection)
}
/// Configure content view with customizations.
fileprivate func configureContentView() {
guard let manager = self.manager else {
fatalError("Trying to set up the content view, but the BulletinViewController is not managed.")
}
contentView.backgroundColor = manager.backgroundColor
contentView.cornerRadius = CGFloat((manager.cardCornerRadius ?? 12).doubleValue)
closeButton.updateColors(isDarkBackground: manager.backgroundColor.needsDarkText == false)
let cardPadding = manager.edgeSpacing.rawValue
// Set left and right padding
leadingConstraint = contentView.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor,
constant: cardPadding)
trailingConstraint = contentView.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor,
constant: -cardPadding)
// Set maximum width with padding
maxWidthConstraint = contentView.widthAnchor.constraint(lessThanOrEqualTo: view.safeWidthAnchor,
constant: -(cardPadding * 2))
maxWidthConstraint.priority = UILayoutPriorityRequired
maxWidthConstraint.isActive = true
if manager.hidesHomeIndicator {
contentBottomConstraint = contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
} else {
contentBottomConstraint = contentView.bottomAnchor.constraint(equalTo: view.safeBottomAnchor)
}
contentBottomConstraint.constant = 1000
contentBottomConstraint.isActive = true
}
// MARK: - Gesture Recognizer
internal func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view?.isDescendant(of: contentView) == true {
return false
}
return true
}
}
// MARK: - Layout
extension BulletinViewController {
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { _ in
self.setUpLayout(with: newCollection)
})
}
fileprivate func setUpLayout(with traitCollection: UITraitCollection) {
switch traitCollection.horizontalSizeClass {
case .regular:
leadingConstraint.isActive = false
trailingConstraint.isActive = false
contentBottomConstraint.isActive = false
centerXConstraint.isActive = true
centerYConstraint.isActive = true
widthConstraint.isActive = true
case .compact:
leadingConstraint.isActive = true
trailingConstraint.isActive = true
contentBottomConstraint.isActive = true
centerXConstraint.isActive = false
centerYConstraint.isActive = false
widthConstraint.isActive = false
default:
break
}
switch (traitCollection.verticalSizeClass, traitCollection.horizontalSizeClass) {
case (.regular, .regular):
stackLeadingConstraint.constant = 32
stackTrailingConstraint.constant = -32
stackBottomConstraint.constant = -32
contentTopConstraint.constant = -32
contentStackView.spacing = 32
default:
stackLeadingConstraint.constant = 24
stackTrailingConstraint.constant = -24
stackBottomConstraint.constant = -24
contentTopConstraint.constant = -24
contentStackView.spacing = 24
}
}
// MARK: - Transition Adaptivity
var defaultBottomMargin: CGFloat {
return manager?.edgeSpacing.rawValue ?? 12
}
func bottomMargin() -> CGFloat {
if #available(iOS 11, *) {
if view.safeAreaInsets.bottom > 0 {
return 0
}
}
var bottomMargin: CGFloat = manager?.edgeSpacing.rawValue ?? 12
if manager?.hidesHomeIndicator == true {
bottomMargin = manager?.edgeSpacing.rawValue == 0 ? 0 : 6
}
return bottomMargin
}
/// Moves the content view to its final location on the screen. Use during presentation.
func moveIntoPlace() {
contentBottomConstraint.constant = -bottomMargin()
centerYConstraint.constant = 0
view.layoutIfNeeded()
contentView.layoutIfNeeded()
backgroundView.layoutIfNeeded()
}
// MARK: - Presentation/Dismissal
/// Dismisses the presnted BulletinViewController if `isDissmisable` is set to `true`.
@discardableResult
func dismissIfPossible() -> Bool {
guard isDismissable else {
return false
}
manager?.dismissBulletin(animated: true)
return true
}
// MARK: - Touch Events
@objc fileprivate func handleTap(recognizer: UITapGestureRecognizer) {
dismissIfPossible()
}
// MARK: - Accessibility
override func accessibilityPerformEscape() -> Bool {
return dismissIfPossible()
}
}
// MARK: - System Elements
extension BulletinViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
if let manager = manager {
switch manager.statusBarAppearance {
case .lightContent:
return .lightContent
case .automatic:
return manager.backgroundViewStyle.rawValue.isDark ? .lightContent : .default
default:
break
}
}
return .default
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return manager?.statusBarAnimation ?? .fade
}
override var prefersStatusBarHidden: Bool {
return manager?.statusBarAppearance == .hidden
}
@available(iOS 11.0, *)
override func prefersHomeIndicatorAutoHidden() -> Bool {
return manager?.hidesHomeIndicator ?? false
}
}
// MARK: - Safe Area
extension BulletinViewController {
@available(iOS 11.0, *)
fileprivate var screenHasRoundedCorners: Bool {
return view.safeAreaInsets.bottom > 0
}
fileprivate func updateCornerRadius() {
if manager?.edgeSpacing.rawValue == 0 {
contentView.cornerRadius = 0
return
}
var defaultRadius: NSNumber = 12
if #available(iOS 11.0, *) {
defaultRadius = screenHasRoundedCorners ? 36 : 12
}
contentView.cornerRadius = CGFloat((manager?.cardCornerRadius ?? defaultRadius).doubleValue)
}
}
// MARK: - Background
extension BulletinViewController {
/// Creates a new background view for the bulletin.
func loadBackgroundView() {
backgroundView = BulletinBackgroundView(style: manager?.backgroundViewStyle ?? .dimmed)
}
}
// MARK: - Activity Indicator
extension BulletinViewController {
/// Displays the activity indicator.
func displayActivityIndicator(color: UIColor) {
activityIndicator.color = color
activityIndicator.startAnimating()
let animations = {
self.activityIndicator.alpha = 1
self.contentStackView.alpha = 0
self.closeButton.alpha = 0
}
UIView.animate(withDuration: 0.25, animations: animations) { _ in
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, self.activityIndicator)
}
}
/// Hides the activity indicator.
func hideActivityIndicator() {
activityIndicator.stopAnimating()
activityIndicator.alpha = 0
let needsCloseButton = manager?.needsCloseButton == true
let animations = {
self.activityIndicator.alpha = 0
self.updateCloseButton(isRequired: needsCloseButton)
}
UIView.animate(withDuration: 0.25, animations: animations)
}
}
// MARK: - Close Button
extension BulletinViewController {
func updateCloseButton(isRequired: Bool) {
isRequired ? showCloseButton() : hideCloseButton()
}
func showCloseButton() {
closeButton.alpha = 1
}
func hideCloseButton() {
closeButton.alpha = 0
}
@objc func closeButtonTapped() {
manager?.dismissBulletin(animated: true)
}
}
// MARK: - Transitions
extension BulletinViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return BulletinPresentationAnimationController(style: manager?.backgroundViewStyle ?? .dimmed)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return BulletinDismissAnimationController()
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning)
-> UIViewControllerInteractiveTransitioning? {
guard manager?.allowsSwipeInteraction == true else {
return nil
}
let isEligible = swipeInteractionController.isInteractionInProgress
return isEligible ? swipeInteractionController : nil
}
/// Creates a new view swipe interaction controller and wires it to the content view.
func refreshSwipeInteractionController() {
guard manager?.allowsSwipeInteraction == true else {
return
}
swipeInteractionController = BulletinSwipeInteractionController()
swipeInteractionController.wire(to: self)
}
/// Prepares the view controller for dismissal.
func prepareForDismissal(displaying snapshot: UIView) {
activeSnapshotView = snapshot
}
}
// MARK: - Keyboard
extension BulletinViewController {
func setUpKeyboardLogic() {
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardHide), name: .UIKeyboardWillHide, object: nil)
}
func cleanUpKeyboardLogic() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
@objc func onKeyboardShow(_ notification: Notification) {
guard manager?.currentItem.shouldRespondToKeyboardChanges == true else {
return
}
guard let userInfo = notification.userInfo,
let keyboardFrameFinal = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
let curveInt = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? Int
else {
return
}
let animationCurve = UIViewAnimationCurve(rawValue: curveInt) ?? .linear
let animationOptions = UIViewAnimationOptions(curve: animationCurve)
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: {
var bottomSpacing = -(keyboardFrameFinal.size.height + self.defaultBottomMargin)
if #available(iOS 11.0, *) {
if self.manager?.hidesHomeIndicator == false {
bottomSpacing += self.view.safeAreaInsets.bottom
}
}
self.minYConstraint.isActive = false
self.contentBottomConstraint.constant = bottomSpacing
self.centerYConstraint.constant = -(keyboardFrameFinal.size.height + 12) / 2
self.contentView.superview?.layoutIfNeeded()
}, completion: nil)
}
@objc func onKeyboardHide(_ notification: Notification) {
guard manager?.currentItem.shouldRespondToKeyboardChanges == true else {
return
}
guard let userInfo = notification.userInfo,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
let curveInt = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? Int
else {
return
}
let animationCurve = UIViewAnimationCurve(rawValue: curveInt) ?? .linear
let animationOptions = UIViewAnimationOptions(curve: animationCurve)
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: {
self.minYConstraint.isActive = true
self.contentBottomConstraint.constant = -self.bottomMargin()
self.centerYConstraint.constant = 0
self.contentView.superview?.layoutIfNeeded()
}, completion: nil)
}
}
extension UIViewAnimationOptions {
init(curve: UIViewAnimationCurve) {
self = UIViewAnimationOptions(rawValue: UInt(curve.rawValue << 16))
}
}
// MARK: - Swift Compatibility
#if swift(>=4.0)
let UILayoutPriorityRequired = UILayoutPriority.required
let UILayoutPriorityDefaultHigh = UILayoutPriority.defaultHigh
let UILayoutPriorityDefaultLow = UILayoutPriority.defaultLow
#endif
| mit | 546382a2f6a0cc2bdefe7d8212422b09 | 30.600629 | 170 | 0.6836 | 6.092149 | false | false | false | false |
oneSwiftSprite/Swiftris | Swiftris/Switftris.swift | 1 | 7967 | //
// Switftris.swift
// Swiftris
//
// Created by Adriana Gustavson on 1/21/15.
// Copyright (c) 2015 Adriana Gustavson. All rights reserved.
//
// #1
let NumColumns = 10
let NumRows = 20
let StartingColumn = 4
let StartingRow = 0
let PreviewColumn = 12
let PreviewRow = 1
let PointsPerLine = 10
let LevelThreshold = 1000
protocol SwiftrisDelegate {
// invoked when the cirrent round of Swiftris ends
func gameDidEnd(swiftris: Swiftris)
// invoked immeditely after a new game has begun
func gameDidBegin(swiftris: Swiftris)
// invoked when the falling shape has become part of the game board
func gameShapeDidLand(swiftris: Swiftris)
// invoked when the falling shape has changed its location
func gameShapeDidMove(swiftris: Swiftris)
// invoked when the galling shape has changed its location after being dropped
func gameShapeDidDrop(swiftris: Swiftris)
// invoked when the game has reached a new level
func gameDidLevelUp(swiftris: Swiftris)
}
class Swiftris {
var blockArray: Array2D<Block>
var nextShape: Shape?
var fallingShape: Shape?
var delegate:SwiftrisDelegate?
var score: Int
var level: Int
init() {
score = 0
level = 1
fallingShape = nil
nextShape = nil
blockArray = Array2D<Block>(columns: NumColumns, rows: NumRows)
}
func beginGame() {
if (nextShape == nil) {
nextShape = Shape.random(PreviewColumn, startingRow: PreviewRow)
}
delegate?.gameDidBegin(self)
}
// #2
func newShape() -> (fallingShape: Shape?, nextShape: Shape?) {
fallingShape = nextShape
nextShape = Shape.random(PreviewColumn, startingRow: PreviewRow)
fallingShape?.moveTo(StartingColumn, row: StartingRow)
// #1 (playing by the rules)
if detectIllegalPlacement() {
nextShape = fallingShape
nextShape!.moveTo(PreviewColumn, row: PreviewRow)
endGame()
return (nil, nil)
}
return (fallingShape, nextShape)
}
// #2 (playing by the rulles)
func detectIllegalPlacement() -> Bool {
if let shape = fallingShape {
for block in shape.blocks {
if block.column < 0 || block.column >= NumColumns
|| block.row < 0 || block.row >= NumRows {
return true
} else if blockArray[block.column, block.row] != nil {
return true
}
}
}
return false
}
// #1 (1.3 playing by the rules)
func settleShape() {
if let shape = fallingShape {
for block in shape.blocks {
blockArray[block.column, block.row] = block
}
fallingShape = nil
delegate?.gameShapeDidLand(self)
}
}
// #2 (2.3 playing by the rules)
func detectTouch() -> Bool {
if let shape = fallingShape {
for bottomBlock in shape.bottomBlocks {
if bottomBlock.row == NumRows - 1 ||
blockArray[bottomBlock.column, bottomBlock.row + 1] != nil {
return true
}
}
}
return false
}
func endGame() {
score = 0
level = 1
delegate?.gameDidEnd(self)
}
// #1 (1.4 playing by the rules)
func removeCompletedLines() -> (linesRemoved: Array<Array<Block>>, fallenBlocks: Array<Array<Block>>) {
var removedLines = Array<Array<Block>>()
for var row = NumRows - 1; row > 0; row-- {
var rowOfBlocks = Array<Block>()
//#2 (2.4 playing by the rules)
for column in 0..<NumColumns {
if let block = blockArray[column, row] {
rowOfBlocks.append(block)
}
}
if rowOfBlocks.count == NumColumns {
removedLines.append(rowOfBlocks)
for block in rowOfBlocks {
blockArray[block.column, block.row] = nil
}
}
}
// #3 (3.4 playing by the rules)
if removedLines.count == 0 {
return ([], [])
}
let pointsEarned = removedLines.count * PointsPerLine * level
score += pointsEarned
if score >= level * LevelThreshold {
level += 1
delegate?.gameDidLevelUp(self)
}
var fallenBlocks = Array<Array<Block>>()
for column in 0..<NumColumns {
var fallenBlocksArray = Array<Block>()
// #5 (5.4 playing by the rules)
for var row = removedLines[0][0].row - 1; row > 0; row-- {
if let block = blockArray[column, row] {
var newRow = row
while (newRow < NumRows - 1 && blockArray[column, newRow + 1] == nil) {
newRow++
}
block.row = newRow
blockArray[column, row] = nil
blockArray[column, newRow] = block
fallenBlocksArray.append(block)
}
}
if fallenBlocksArray.count > 0 {
fallenBlocks.append(fallenBlocksArray)
}
}
return (removedLines, fallenBlocks)
}
func removeAllBlocks() -> Array<Array<Block>> {
var allBlocks = Array<Array<Block>>()
for row in 0..<NumRows {
var rowOfBlocks = Array<Block>()
for column in 0..<NumColumns {
if let block = blockArray[column, row] {
rowOfBlocks.append(block)
blockArray[column, row] = nil
}
}
allBlocks.append(rowOfBlocks)
}
return allBlocks
}
// #1 (#1.2 playing by the rules)
func dropShape() {
if let shape = fallingShape {
while detectIllegalPlacement() == false {
shape.lowerShapeByOneRow()
}
shape.raiseShapeByOneRow()
delegate?.gameShapeDidDrop(self)
}
}
// #2 (#2.2 playing by the rules)
func letShapeFall() {
if let shape = fallingShape {
shape.lowerShapeByOneRow()
if detectIllegalPlacement() {
shape.raiseShapeByOneRow()
if detectIllegalPlacement() {
endGame()
} else {
settleShape()
}
} else {
delegate?.gameShapeDidMove(self)
if detectTouch() {
settleShape()
}
}
}
}
// #3 (3.2 playing by the rules)
func rotateShape() {
if let shape = fallingShape {
shape.rotateClockwise()
if detectIllegalPlacement() {
shape.rotateCounterClockwise()
} else {
delegate?.gameShapeDidMove(self)
}
}
}
// #4 (4.2 playing by the rules)
func moveShapeLeft() {
if let shape = fallingShape {
shape.shiftLeftByOneColumn()
if detectIllegalPlacement() {
shape.shiftRightByOneColumn()
return
}
delegate?.gameShapeDidMove(self)
}
}
func moveShapeRight() {
if let shape = fallingShape {
shape.shiftRightByOneColumn()
if detectIllegalPlacement() {
shape.shiftLeftByOneColumn()
return
}
delegate?.gameShapeDidMove(self)
}
}
// end Swiftris class
}
| mit | c717e85d33fc444ecebd826de6f5a884 | 25.824916 | 107 | 0.509728 | 5.026498 | false | false | false | false |
citypay/apple-pay-sdk | CityPayKit/CityPayResponse.swift | 1 | 6879 | //
// CPResponse.swift
// CityPayKit
//
// Created by Gary Feltham on 27/08/2015.
// Copyright (c) 2015 CityPay Limited. All rights reserved.
//
import UIKit
import CommonCrypto
/**
The CPResponse models the response object from the gateway for generic processing
using the **CityPay HTTP PayPOST API**.
To determine if a transaction has been accepted review the *authorised* parameter and ensure you know if you are in *test* mode or *live*
Initialisation of a CPResponse instance is provided by the API as a JSON packet which can be reinstated
using standard JSON serialization methods and
let jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error:&parseError)
if let json = jsonObject as? NSDictionary {
let response = CPResponse(json)
} else {
// error checking code.
}
*/
public class CityPayResponse: NSObject {
public let amount: Int
public let currency: String
public let authcode: String?
public let authorised: Bool
public let AvsResponse: String?
public let CscResponse: String?
public let errorcode: String
public let errormsg: String
public let expMonth: Int
public let expYear: Int
public let identifier: String
public let maskedPan: String
public let merchantId: Int
public let mode: String
public let result: Int
public let sha256: String
public let status: String
public let title: String?
public let firstname:String?
public let lastname:String?
public let email: String?
public let postcode: String?
public let transno: Int
private func b64_sha256(data : NSData) -> String {
var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA256(data.bytes, CC_LONG(data.length), &hash)
let res = NSData(bytes: hash, length: Int(CC_SHA256_DIGEST_LENGTH))
return res.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
}
func log() -> String {
return "RS:\(identifier),amount=\(amount),card=\(maskedPan),\(expMonth)\(expYear),authorised=\(authorised),mode=\(mode)"
}
/// Determines if the data provided is valid based on the sha256 value. The licence key provides a salt
/// into the hash function
public func isValid(licenceKey: String) -> Bool {
var str = authcode ?? ""
str += toString(amount) +
errorcode +
toString(merchantId) +
toString(transno) +
identifier +
licenceKey
if let data = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
let b64 = b64_sha256(data)
return b64 == sha256
}
return false
}
// Creates a rejected CPResponse from this response. This allows the object cycle to be rejected
// by workflow such as an invalid digest information.
func rejectAuth(licenceKey: String, errormsg: String) -> CityPayResponse {
NSLog("Rejecting auth \(errormsg)")
// recreate digest
let ec = "099"
var str = authcode ?? ""
str += toString(amount) +
ec +
toString(merchantId) +
toString(transno) +
identifier +
licenceKey
let data = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
let digest = b64_sha256(data)
return CityPayResponse(
amount:amount, currency:currency, authcode:authcode, authorised:false,
AvsResponse:AvsResponse, CscResponse:CscResponse, errorcode:ec, errormsg:errormsg,
expMonth:expMonth, expYear:expYear, identifier:identifier, maskedPan:maskedPan,
merchantId:merchantId, mode:mode, result:2, sha256:digest,
status:status, title:title, firstname:firstname, lastname:lastname,
email:email, postcode:postcode, transno:transno)
}
init(amount: Int, currency: String, authcode: String?, authorised: Bool,
AvsResponse: String?, CscResponse: String?, errorcode: String, errormsg: String,
expMonth: Int, expYear: Int, identifier: String, maskedPan: String,
merchantId: Int, mode: String, result: Int, sha256: String,
status: String, title: String?, firstname:String?, lastname:String?,
email: String?,postcode: String?,transno: Int) {
self.amount = amount
self.currency = currency
self.authcode = authcode
self.authorised = authorised
self.AvsResponse = AvsResponse
self.CscResponse = CscResponse
self.errorcode = errorcode
self.errormsg = errormsg
self.expMonth = expMonth
self.expYear = expYear
self.identifier = identifier
self.maskedPan = maskedPan
self.merchantId = merchantId
self.mode = mode
self.result = result
self.sha256 = sha256
self.status = status
self.title = title
self.firstname = firstname
self.lastname = lastname
self.email = email
self.postcode = postcode
self.transno = transno
}
/// only way to initialise is via a JSON packet
public init(data: NSData) {
var e: NSError?
let json = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: &e)
if let error = e {
NSLog("Error parsing JSON \(error)")
}
self.amount = json["amount"].int ?? 0
self.currency = json["currency"].stringValue
self.authcode = json["authcode"].string
self.authorised = json["authorised"].bool ?? false
self.AvsResponse = json["AVSResponse"].string
self.CscResponse = json["CSCResponse"].string
self.errorcode = json["errorcode"].string ?? "F007"
self.errormsg = json["errormessage"].string ?? "No valid response from JSON packet"
self.expMonth = json["expMonth"].int ?? 0
self.expYear = json["expYear"].int ?? 0
self.identifier = json["identifier"].string ?? "unknown"
self.maskedPan = json["maskedPan"].string ?? "n/a"
self.merchantId = json["merchantid"].int ?? 0
self.mode = json["mode"].string ?? "?"
self.result = json["result"].int ?? 20 // unknown
self.sha256 = json["sha256"].string ?? ""
self.status = json["status"].string ?? "?" // unknown
self.title = json["title"].string
self.firstname = json["firstname"].string
self.lastname = json["lastname"].string
self.email = json["email"].string
self.postcode = json["postcode"].string
self.transno = json["transno"].int ?? -1
}
}
| mit | f92524f0666341d42deb99df07270901 | 37.216667 | 141 | 0.624073 | 4.519711 | false | false | false | false |
kansaraprateek/WebService | WebService/Classes/DocumentHandler.swift | 1 | 16975 | //
// DocumentHandler.swift
// WebService
//
// Created by Prateek Kansara on 30/05/16.
// Copyright © 2016 Prateek. All rights reserved.
//
import Foundation
import MobileCoreServices
import UIKit
extension URL {
// var typeIdentifier: String {
// guard isFileURL else { return "unknown" }
// var uniformTypeIdentifier: AnyObject?
// do {
// try getResourceValue(&uniformTypeIdentifier, forKey: URLResourceKey.typeIdentifierKey)
// return uniformTypeIdentifier as? String ?? "unknown"
// } catch let error as NSError {
// print(error.debugDescription)
// return "unknown"
// }
// }
}
private var globalFileManager : FileManager! {
if FileManager.default.fileExists(atPath: globalDestinationDocPath as String) {
do{
try FileManager.default.createDirectory(atPath: globalDestinationDocPath as String, withIntermediateDirectories: false, attributes: nil)
}
catch{
print("failed to create common doc folder")
}
}
return FileManager.default
}
private var globalPaths : NSArray! {
return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray!
}
private var globalDocumentDirectoryPath : NSString! {
return globalPaths.object(at: 0) as! NSString
}
private var globalDestinationDocPath : NSString! {
return globalDocumentDirectoryPath.appendingPathComponent("/Docs") as NSString!
}
@objc protocol DocumentHandlerDelegate : NSObjectProtocol{
func DocumentUplaodedSuccessfully(_ data : Data)
func DocumentUploadFailed(_ error : NSError)
}
private let FILEBOUNDARY = "--ARCFormBoundarym9l3512x3aexw29"
open class DocumentHandler : NSObject {
var delegate : DocumentHandlerDelegate{
set {
self.delegate = newValue
}
get{
return self.delegate
}
}
open var fileName : NSString!
open class var sharedInstance: DocumentHandler {
struct Singleton {
static let instance = DocumentHandler()
}
return Singleton.instance
}
open
func setDefaultHeaders(_ headers : NSMutableDictionary) {
let headersClass = HTTPHeaders.sharedInstance
headersClass.setDefaultDocumentHeaders(headers)
}
open var httpHeaders : NSDictionary?
open func downloadDocument(_ urlString : NSString, documentID : NSString, Progress: @escaping (_ bytesWritten : Int64, _ totalBytesWritten : Int64, _ remaining : Int64) -> Void, Success : @escaping (_ location : URL, _ taskDescription : NSString) -> Void, Error : @escaping (_ respones : HTTPURLResponse, _ error : NSError?) -> Void) {
let documetDownlaodSession : DocumentDownloader = DocumentDownloader.init(lURLString: urlString, lRequestType: "GET")
documetDownlaodSession.uniqueID = documentID
documetDownlaodSession.headerValues = httpHeaders
documetDownlaodSession.downloadDocumentWithProgress(Progress, Success: Success, Error: Error)
}
open func uploadDocumentWithURl(_ urlString : NSString, parameters : NSDictionary?, documentPath : NSArray, fieldName : String, Progress : @escaping (_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void, Success : @escaping (_ response : HTTPURLResponse, Any) -> Void, Error : @escaping (_ response : HTTPURLResponse, _ error : Any?) -> Void) {
let data : Data = createBodyWithBoundary(FILEBOUNDARY, parameters: parameters, paths: documentPath, fieldName: fieldName)
let uploadDocument : DocumentUploader = DocumentUploader()
if httpHeaders != nil {
uploadDocument.headerValues = NSMutableDictionary.init(dictionary: httpHeaders!)
}
uploadDocument.uploadDocumentWithURl(urlString, formData: data, uniqueID: self.fileName, Progress: Progress, Success: Success, Error: Error)
}
fileprivate func createBodyWithBoundary(_ boundary : String, parameters : NSDictionary?, paths : NSArray, fieldName : String) -> Data {
let httpBody : NSMutableData = NSMutableData()
parameters?.enumerateKeysAndObjects({
paramKey, paramValue, _ in
httpBody.append(String(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8)!)
httpBody.append(String(format: "Content-Disposition: form-data; name=\"%@\"\r\n\r\n", paramKey as! String).data(using: String.Encoding.utf8)!)
httpBody.append(String(format: "%@\r\n", paramValue as! String).data(using: String.Encoding.utf8)!)
})
for path in paths {
let fileName : NSString = (path as! NSString).lastPathComponent as NSString
let data : Data = try! Data(contentsOf: URL(fileURLWithPath: path as! String))
let mimeType : NSString = fileName.pathExtension as NSString
// (URL(string: path as! String)?.lastPathComponent)! as NSString
httpBody.append(String(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8)!)
httpBody.append(String(format: "Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fieldName, fileName).data(using: String.Encoding.utf8)!)
httpBody.append(String(format: "Content-Type: %@\r\n\r\n", mimeType).data(using: String.Encoding.utf8)!)
httpBody.append(data)
httpBody.append(String(format: "\r\n").data(using: String.Encoding.utf8)!)
}
httpBody.append(String(format: "--%@--\r\n", boundary).data(using: String.Encoding.utf8)!)
return httpBody as Data
}
fileprivate func mimeTypeForPath(_ path : NSString) -> NSString {
let docExtension : CFString = path.pathExtension as CFString
let UTI : CFString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, docExtension, nil) as! CFString
// assert(UTI != nil)
let mimeType = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType)!
let mimeString = convertCfTypeToString(cfValue: mimeType)
return mimeString!
}
private func convertCfTypeToString(cfValue: Unmanaged<CFString>!) -> NSString?{
/* Coded by Vandad Nahavandipoor */
let value = Unmanaged.fromOpaque(
cfValue.toOpaque()).takeUnretainedValue() as CFString
if CFGetTypeID(value) == CFStringGetTypeID(){
return value as NSString
} else {
return nil
}
}
}
extension DocumentHandler: UINavigationControllerDelegate {
}
// MARK: - Document session class
private class DocumentDownloader: NSObject {
fileprivate var uniqueID : NSString!
fileprivate var urlString : NSString!
fileprivate var requestType : NSString!
fileprivate var backgroundSession : Foundation.URLSession!
fileprivate var inProgress : ((_ bytesWritten : Int64, _ totalBytesWritten : Int64, _ remaining : Int64) -> Void)?
fileprivate var onSuccess : ((_ location : URL, _ taskDescription : NSString) -> Void)?
fileprivate var onError : ((_ response : HTTPURLResponse, _ error : NSError?) -> Void)?
fileprivate var headerValues : NSDictionary?
fileprivate var gResponse : HTTPURLResponse!
fileprivate var mutableRequest : URLRequest! {
set{
self.mutableRequest = newValue
}
get {
var lMutableRequest : URLRequest = URLRequest(url: URL(string: self.urlString as String)!)
lMutableRequest.httpMethod = "GET"
lMutableRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let httpHeaderClass = HTTPHeaders.sharedInstance
if headerValues == nil {
if httpHeaderClass.getDocumentHeaders() == nil {
headerValues = httpHeaderClass.getHTTPHeaders()
}
else{
headerValues = httpHeaderClass.getDocumentHeaders()
}
}
headerValues?.enumerateKeysAndObjects({
key, value, _ in
lMutableRequest.setValue(value as? String, forHTTPHeaderField: key as! String)
})
return lMutableRequest
}
}
fileprivate var sessionConfiguration : URLSessionConfiguration! {
set {
self.sessionConfiguration = newValue
}
get{
let sessionConfig = URLSessionConfiguration.background(withIdentifier: self.uniqueID as String)
// let additionalHeaderDictionary : NSMutableDictionary = NSMutableDictionary ()
// additionalHeaderDictionary.setValue("application/json", forKey: "Content-Type")
// sessionConfig.HTTPAdditionalHeaders = additionalHeaderDictionary
return sessionConfig
}
}
override init() {
super.init()
}
convenience init(lURLString : NSString, lRequestType : NSString) {
self.init()
requestType = lRequestType
urlString = lURLString
}
fileprivate func downloadDocumentWithProgress(_ Progress : @escaping (_ bytesWritten : Int64, _ totalBytesWritten : Int64, _ remaining : Int64) -> Void, Success: @escaping (_ location : URL, _ taskDescription : NSString) -> Void, Error : @escaping (_ response : HTTPURLResponse, _ error : NSError?) -> Void) {
onError = Error
onSuccess = Success
inProgress = Progress
backgroundSession = Foundation.URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue:OperationQueue.main)
let downloadTask = backgroundSession.downloadTask(with: mutableRequest)
downloadTask.resume()
}
}
extension DocumentDownloader: URLSessionDataDelegate{
func urlSession(_ session: Foundation.URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (Foundation.URLSession.ResponseDisposition) -> Void) {
gResponse = response as? HTTPURLResponse
completionHandler(.allow);
}
}
extension DocumentDownloader : URLSessionDownloadDelegate{
@objc func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// if gResponse.statusCode == 200{
self.onSuccess!(location, "Downloaded")
// }
// else{
// self.onError!(response: gResponse, error: nil)
// }
}
@objc func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
self.inProgress!(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
fileprivate func URLSession(_ session: Foundation.URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
self.onError!(gResponse, error)
}
}
private class DocumentUploader : NSObject {
fileprivate var gURl : NSString!
fileprivate var gRequestType : NSString!
fileprivate var uniqueID : NSString!
fileprivate var onSuccess : ((_ response : HTTPURLResponse, Any) -> Void)?
fileprivate var onError : ((_ response : HTTPURLResponse, Any?) -> Void)?
fileprivate var inProgress : ((_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void)?
fileprivate var recievedData : Data!
fileprivate var headerValues : NSMutableDictionary?
fileprivate var gResponse : HTTPURLResponse!
fileprivate var backgroundUploadSession : Foundation.URLSession!
fileprivate var mutableRequest : NSMutableURLRequest! {
set{
self.mutableRequest = newValue
}
get {
let lMutableRequest : NSMutableURLRequest = NSMutableURLRequest(url: URL(string: self.gURl as String)!)
lMutableRequest.httpMethod = gRequestType as String
let httpHeaderClass = HTTPHeaders.sharedInstance
if headerValues == nil {
if httpHeaderClass.getDocumentHeaders() == nil {
if httpHeaderClass.getHTTPHeaders() == nil {
print("Set header values")
}
else
{
headerValues = NSMutableDictionary.init(dictionary: httpHeaderClass.getHTTPHeaders()!)
}
}
else{
headerValues = NSMutableDictionary.init(dictionary: httpHeaderClass.getDocumentHeaders()!)
}
}
headerValues?.enumerateKeysAndObjects({
key, value, _ in
lMutableRequest.setValue(value as? String, forHTTPHeaderField: key as! String)
})
if gRequestType.isEqual("POST") || gRequestType.isEqual("PUT"){
let mutipartContentType = NSString(format: "multipart/form-data; boundary=%@", FILEBOUNDARY)
lMutableRequest.setValue(mutipartContentType as String, forHTTPHeaderField: "Content-Type")
}
return lMutableRequest
}
}
fileprivate func uploadDocumentWithURl(_ urlString : NSString, formData : Data, uniqueID : NSString, Progress : @escaping (_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64) -> Void, Success : @escaping (_ response : HTTPURLResponse, Any) -> Void, Error : @escaping (_ response : HTTPURLResponse, _ error : Any?) -> Void) {
self.gRequestType = "POST"
self.gURl = urlString
self.uniqueID = uniqueID
inProgress = Progress
onSuccess = Success
onError = Error
let sessionConfig : URLSessionConfiguration = URLSessionConfiguration.default
backgroundUploadSession = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue:OperationQueue.main)
let uploadTask : URLSessionUploadTask = backgroundUploadSession.uploadTask(with: mutableRequest as URLRequest, from: formData)
uploadTask.resume()
}
}
extension DocumentUploader: URLSessionDataDelegate{
func urlSession(_ session: Foundation.URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (Foundation.URLSession.ResponseDisposition) -> Void) {
gResponse = response as? HTTPURLResponse
recievedData = Data()
// print("\(gResponse)")
completionHandler(.allow);
}
fileprivate func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
recievedData.append(data)
}
}
extension DocumentUploader : URLSessionTaskDelegate{
@objc func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
// print("session \(session) task : \(task) error : \(error)")
if (error == nil) {
let responseDict : Any!
do{
responseDict = try JSONSerialization.jsonObject(with: recievedData, options: .allowFragments)
// print(responseDict)
}
catch{
print("serialization failed")
let error : NSError = NSError.init(domain: "SerializationFailed", code: 0, userInfo: nil)
if gResponse!.statusCode == 200 {
if (recievedData != nil) {
onSuccess!(gResponse, recievedData)
}else{
onSuccess!(gResponse, ["message" : "success"])
}
}
else{
onError!(gResponse, error)
}
return
}
if gResponse!.statusCode == 200 {
onSuccess!(gResponse, responseDict)
}
else{
onError!(gResponse, responseDict)
}
}
else{
onError!(gResponse ?? HTTPURLResponse(), error!)
}
}
@objc func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
// print("byte send \(bytesSent) expected : \(totalBytesExpectedToSend) ")
self.inProgress!(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
| mit | 149d6fb651d1c3022b8a3bef6fea0c19 | 39.033019 | 383 | 0.626016 | 5.596439 | false | false | false | false |
petrmanek/revolver | Examples/ExampleCar/ExampleCar/NSBezierPath+toCGPath.swift | 1 | 1127 | import AppKit
// Courtesy of https://gist.github.com/jorgenisaksson/76a8dae54fd3dc4e31c2
extension NSBezierPath {
func toCGPath () -> CGPath? {
if self.elementCount == 0 {
return nil
}
let path = CGPathCreateMutable()
var didClosePath = false
for i in 0...self.elementCount-1 {
var points = [NSPoint](count: 3, repeatedValue: NSZeroPoint)
switch self.elementAtIndex(i, associatedPoints: &points) {
case .MoveToBezierPathElement:CGPathMoveToPoint(path, nil, points[0].x, points[0].y)
case .LineToBezierPathElement:CGPathAddLineToPoint(path, nil, points[0].x, points[0].y)
case .CurveToBezierPathElement:CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y)
case .ClosePathBezierPathElement:CGPathCloseSubpath(path)
didClosePath = true;
}
}
if !didClosePath {
CGPathCloseSubpath(path)
}
return CGPathCreateCopy(path)
}
}
| mit | 0e8e43c3e621422c8bdf388f6b83ae13 | 34.21875 | 153 | 0.598935 | 4.268939 | false | false | false | false |
ddaguro/clintonconcord | OIMApp/DashboardCell.swift | 1 | 1807 | //
// DashboardCell.swift
// OIMApp
//
// Created by Linh NGUYEN on 7/6/15.
// Copyright (c) 2015 Persistent Systems. All rights reserved.
//
import UIKit
class DashboardCell: UITableViewCell {
@IBOutlet var profileImage: UIImageView!
@IBOutlet var titleLabel : UILabel!
@IBOutlet var statusLabel: UILabel!
@IBOutlet var assigneeHeadingLabel: UILabel!
@IBOutlet var assigneeLabel: UILabel!
@IBOutlet var clockImage: UIImageView!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var descriptionLabel: UILabel!
//@IBOutlet var approverLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.font = UIFont(name: MegaTheme.fontName, size: 16)
titleLabel.textColor = UIColor.blackColor()
statusLabel.layer.cornerRadius = 8
statusLabel.layer.masksToBounds = true
statusLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
statusLabel.textColor = UIColor.whiteColor()
assigneeHeadingLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
assigneeHeadingLabel.textColor = MegaTheme.darkColor
assigneeLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
assigneeLabel.textColor = MegaTheme.lightColor
clockImage.image = UIImage(named: "clock")
clockImage.alpha = 0.20
dateLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
dateLabel.textColor = MegaTheme.lightColor
descriptionLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
descriptionLabel.textColor = MegaTheme.lightColor
//approverLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
//approverLabel.textColor = MegaTheme.lightColor
}
}
| mit | fdb639c785499fcb4c2bde3d0eebc6ec | 33.75 | 78 | 0.670725 | 4.831551 | false | false | false | false |
shirai/SwiftLearning | iOSTraining/Subject5/Dandori/Dandori/Controller/DandoriListViewController/DandoriListViewController.swift | 1 | 2619 | //
// DandoriListViewController.swift
// Dandori
//
// Created by 白井 誠 on 2017/09/06.
// Copyright © 2017年 Sample. All rights reserved.
//
import UIKit
class DandoriListCell: UITableViewCell {
// MARK: - IBOutlets
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var checkButton: UIButton!
@IBOutlet weak var genderSegment: UISegmentedControl!
// MARK: - IBActions
@IBAction func didTappedCheckButton(_ sender: UIButton) {
}
@IBAction func didChangedGenderSegment(_ sender: UISegmentedControl) {
}
}
class DandoriListViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let indexPathForSelectedRow = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPathForSelectedRow, animated: true)
}
}
}
extension DandoriListViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "分類Aのダンドリ 3"
case 1:
return "分類Bのダンドリ 10"
default:
return nil
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "dandoriCell", for: indexPath) as! DandoriListCell
switch indexPath.section {
case 0:
cell.titleLabel.text = "A-\(indexPath.row + 1)のダンドリ"
case 1:
cell.titleLabel.text = "B-\(indexPath.row + 1)のダンドリ"
default:
break
}
cell.dateLabel.text = "2017/09/1\(indexPath.row + 3)"
if indexPath.row > 1 {
cell.genderSegment.selectedSegmentIndex = 1
} else {
cell.checkButton.titleLabel?.text = "■"
}
return cell
}
}
extension DandoriListViewController: UITableViewDelegate {
}
| mit | 2c88c0ab2dc093d0a6460018474b83dd | 27.431818 | 115 | 0.625899 | 4.738636 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Data Offers/HATDataOfferClaim.swift | 1 | 2643 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* 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 SwiftyJSON
// MARK: Struct
public struct HATDataOfferClaim: HATObject {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `claimStatus` in JSON is `status`
* `isClaimConfirmed` in JSON is `confirmed`
* `dateCreated` in JSON is `dateCreated`
* `dataDebitID` in JSON is `dataDebitId`
*/
private enum CodingKeys: String, CodingKey {
case claimStatus = "status"
case isClaimConfirmed = "confirmed"
case dateCreated = "dateCreated"
case dataDebitID = "dataDebitId"
}
// MARK: - Variables
/// The data offer claim status. Can be `confirmed`, `claimed` and `completed`
public var claimStatus: String = ""
/// A flag indicating if the claim was confirmed
public var isClaimConfirmed: Bool = false
/// The date that the offer has been claimed as a unix time stamp
public var dateCreated: Int = -1
/// The `Data Debit` id that the offer is attached to
public var dataDebitID: String = ""
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
claimStatus = ""
isClaimConfirmed = false
dateCreated = -1
dataDebitID = ""
}
/**
It initialises everything from the received JSON file from the HAT
- dictionary: The JSON file received
*/
public init(dictionary: Dictionary<String, JSON>) {
if let tempStatus: String = dictionary[HATDataOfferClaim.CodingKeys.claimStatus.rawValue]?.string {
claimStatus = tempStatus
}
if let tempConfirmed: Bool = dictionary[HATDataOfferClaim.CodingKeys.isClaimConfirmed.rawValue]?.bool {
isClaimConfirmed = tempConfirmed
}
if let tempDataDebitID: String = dictionary[HATDataOfferClaim.CodingKeys.dataDebitID.rawValue]?.string {
dataDebitID = tempDataDebitID
}
if let tempDateStamp: Int = dictionary[HATDataOfferClaim.CodingKeys.dateCreated.rawValue]?.int {
dateCreated = tempDateStamp
}
}
}
| mpl-2.0 | 73205b2bc494dfb52d57e78076f32b02 | 28.696629 | 112 | 0.61748 | 4.779385 | false | false | false | false |
xdliu002/TAC_communication | PodsDemo/PodsDemo/LeftMenuViewController.swift | 1 | 3237 | //
// LeftMenuViewController.swift
// PodsDemo
//
// Created by Harold LIU on 3/16/16.
// Copyright © 2016 Tongji Apple Club. All rights reserved.
//
import UIKit
import RESideMenu
class LeftMenuViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,RESideMenuDelegate{
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
let tableView = UITableView(frame: CGRect(x: 0, y: (view.frame.size.height - 54*5)/2.0, width: view.frame.size.width, height: 54*5), style: UITableViewStyle.Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.separatorStyle = .None
tableView.bounces = false
tableView.scrollsToTop = false
view.addSubview(tableView)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView .deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row
{
case 0:
sideMenuViewController.setContentViewController(UINavigationController(rootViewController: (storyboard?.instantiateViewControllerWithIdentifier("firstViewController"))!), animated: true)
sideMenuViewController.hideMenuViewController()
break;
case 1:
sideMenuViewController.setContentViewController(UINavigationController(rootViewController: (storyboard?.instantiateViewControllerWithIdentifier("secondViewController"))!), animated: true)
sideMenuViewController.hideMenuViewController()
break;
default:
break;
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("LeftCell")
if cell == nil
{
cell = UITableViewCell(style: .Default, reuseIdentifier: "LeftCell")
cell?.backgroundColor = UIColor.clearColor()
cell?.textLabel?.textColor = UIColor.whiteColor()
cell?.textLabel?.highlightedTextColor = UIColor.grayColor()
cell?.selectedBackgroundView = UIView()
}
let titles = ["Home", "Calendar", "Profile", "Settings", "Log Out"]
let images = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconEmpty"]
cell?.textLabel?.text = titles[indexPath.row]
cell?.imageView?.image = UIImage(named: images[indexPath.row])
return cell!
}
}
| mit | 1d16a0b68771944a79d0127907f0b467 | 34.56044 | 199 | 0.630717 | 5.778571 | false | false | false | false |
johnno1962/eidolon | Kiosk/Bid Fulfillment/StripeManager.swift | 1 | 1590 | import Foundation
import RxSwift
import Stripe
class StripeManager: NSObject {
var stripeClient = STPAPIClient.sharedClient()
func registerCard(digits: String, month: UInt, year: UInt, securityCode: String, postalCode: String) -> Observable<STPToken> {
let card = STPCard()
card.number = digits
card.expMonth = month
card.expYear = year
card.cvc = securityCode
card.addressZip = postalCode
return Observable.create { [weak self] observer in
guard let me = self else {
observer.onCompleted()
return NopDisposable.instance
}
me.stripeClient.createTokenWithCard(card) { (token, error) in
if (token as STPToken?).hasValue {
observer.onNext(token!)
observer.onCompleted()
} else {
observer.onError(error!)
}
}
return NopDisposable.instance
}
}
func stringIsCreditCard(cardNumber: String) -> Bool {
return STPCard.validateCardNumber(cardNumber)
}
}
extension STPCardBrand {
var name: String? {
switch self {
case .Visa:
return "Visa"
case .Amex:
return "American Express"
case .MasterCard:
return "MasterCard"
case .Discover:
return "Discover"
case .JCB:
return "JCB"
case .DinersClub:
return "Diners Club"
default:
return nil
}
}
}
| mit | cf7251a0d9c822bbe5f87a0ecb734095 | 25.949153 | 130 | 0.545283 | 5.063694 | false | false | false | false |
jiapan1984/swift-datastructures-algorithms | RingBuffer.swift | 1 | 1425 | // 一个简单的环形缓冲区数据结构
#if swift(>=4.0)
print("Hello, Swift 4!")
public struct RingBuffer<T> {
fileprivate var array:[T?]
fileprivate var readIndex = 0
fileprivate var writeIndex = 0
public init(_ count: Int) {
array = [T?](repeating:nil, count:count)
}
public mutating func write(_ element: T) -> Bool {
if isFull {
return false
} else {
array[writeIndex % array.count] = element
writeIndex += 1
return true
}
}
public mutating func read() -> T? {
if !isEmpty {
let elem = array[readIndex % array.count]
array[readIndex % array.count] = nil
readIndex += 1
return elem
} else {
return nil
}
}
public var isFull: Bool {
return (writeIndex - readIndex) == array.count
}
public var isEmpty: Bool {
return writeIndex == readIndex
}
}
var a = RingBuffer<Int>(5)
for i in 1...5 {
_ = a.write(i)
}
assert(a.write(6) == false)
assert(a.write(7) == false)
assert(a.read() == 1)
assert(a.read() == 2)
assert(a.write(7))
assert(a.write(8))
assert(a.read() == 3)
assert(a.read() == 4)
assert(a.write(9))
assert(a.write(10))
assert(a.read() == 5)
assert(a.read() == 7)
assert(a.read() == 8)
assert(a.read() == 9)
assert(a.read() == 10)
assert(a.read() == nil)
#endif
| mit | 07ce370f1f631904626818f0922c2dd7 | 21.901639 | 54 | 0.544023 | 3.3026 | false | false | false | false |
fluidsonic/JetPack | Sources/Measures/Measure.swift | 1 | 1961 | public protocol Measure: Comparable, CustomDebugStringConvertible, CustomStringConvertible, Hashable {
associatedtype UnitType: Unit
init(rawValue: Double)
init(_ value: Double, unit: UnitType)
static var name: String { get }
static var rawUnit: UnitType { get }
var rawValue: Double { get mutating set }
func valueInUnit(_ unit: UnitType) -> Double
}
public extension Measure { // CustomDebugStringConvertible
var debugDescription: String {
return "\(rawValue.description) \(Self.rawUnit.debugDescription)"
}
}
public extension Measure { // CustomStringConvertible
var description: String {
return "\(rawValue.description) \(Self.rawUnit.abbreviation)"
}
}
public extension Measure { // Hashable
func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
}
public prefix func + <M: Measure>(measure: M) -> M {
return measure
}
public prefix func - <M: Measure>(measure: M) -> M {
return M(rawValue: -measure.rawValue)
}
public func + <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue + b.rawValue)
}
public func += <M: Measure>(a: inout M, b: M) {
a.rawValue += b.rawValue
}
public func - <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue - b.rawValue)
}
public func -= <M: Measure>(a: inout M, b: M) {
a.rawValue -= b.rawValue
}
public func * <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue * b.rawValue)
}
public func *= <M: Measure>(a: inout M, b: M) {
a.rawValue *= b.rawValue
}
public func / <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue / b.rawValue)
}
public func /= <M: Measure>(a: inout M, b: M) {
a.rawValue /= b.rawValue
}
public func % <M: Measure>(a: M, b: M) -> M {
return M(rawValue: a.rawValue.truncatingRemainder(dividingBy: b.rawValue))
}
public func == <M: Measure>(a: M, b: M) -> Bool {
return (a.rawValue == b.rawValue)
}
public func < <M: Measure>(a: M, b: M) -> Bool {
return (a.rawValue < b.rawValue)
}
| mit | bcf48f0ecca7b345f151d9bb74df9562 | 18.038835 | 102 | 0.658848 | 3.09306 | false | false | false | false |
gb-6k-house/YsSwift | Sources/Peacock/UIKit/YSPopView/YSBubbleView.swift | 1 | 20359 | /******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: 说明
** Copyright © 2017年 尧尚信息科技(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import SnapKit
enum YSBubbleDiretcion: Int {
case top
case left
case bottom
case right
case topLeft
case topRight
case leftTop
case leftBottom
case bottomLeft
case bottomRight
case rightTop
case rightBottom
case automatic
}
open class YSBubbleView: YSPopupView {
fileprivate(set) var cellAction: [YSActionItem] = [YSActionItem]()
let tableView = UITableView()
fileprivate let arrowView = UIImageView()
fileprivate var anchorView = UIView()
fileprivate var anchorDirection = YSBubbleDiretcion.automatic
fileprivate var popWidth: CGFloat = 0
fileprivate override init(frame: CGRect = CGRect.zero) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience init(anchorView: UIView, titles: [String], anchorDirection: YSBubbleDiretcion = .automatic, action: @escaping ((_ index: Int) -> Void), width: CGFloat) {
var actions: [YSActionItem] = [YSActionItem]()
for title in titles {
let action = YSActionItem(title: title, action: action)
actions.append(action)
}
self.init(anchorView: anchorView, anchorDirection: anchorDirection, cellAction: actions, width: width)
}
convenience init(anchorView: UIView, titles: [String], anchorDirection: YSBubbleDiretcion = .automatic, action: @escaping ((_ index: Int) -> Void)) {
var actions: [YSActionItem] = [YSActionItem]()
for title in titles {
let action = YSActionItem(title: title, action: action)
actions.append(action)
}
self.init(anchorView: anchorView, anchorDirection: anchorDirection, cellAction: actions, width: YSBubbleViewConfig.width)
}
convenience init(anchorView: UIView, anchorDirection: YSBubbleDiretcion = .automatic, cellAction: [YSActionItem]) {
self.init(anchorView: anchorView, anchorDirection: anchorDirection, cellAction: cellAction, width: YSBubbleViewConfig.width)
}
convenience init(anchorView: UIView, anchorDirection: YSBubbleDiretcion = .automatic, cellAction: [YSActionItem], width: CGFloat) {
self.init(frame: CGRect.zero)
self.anchorView = anchorView
self.cellAction = cellAction
self.anchorDirection = anchorDirection
self.popWidth = width
if self.anchorDirection == .automatic {
self.anchorDirection = self.getAnchorDirection(self.anchorView)
}
self.buildUI()
}
fileprivate func buildUI() {
assert(self.cellAction.count > 0, "Need at least 1 action")
self.targetView = YSBubbleWindow
typealias Config = YSBubbleViewConfig
self.type = .custom
self.snp.makeConstraints { (make) in
make.width.equalTo(self.popWidth)
}
self.setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical)
self.setContentHuggingPriority(UILayoutPriority.fittingSizeLevel, for: .horizontal)
({ (view: UIImageView) in
view.contentMode = .center
view.image = UIImage.YS_rhombusWithSize(CGSize(width: Config.arrowWidth + Config.cornerRadius, height: Config.arrowWidth + Config.cornerRadius), color: Config.cellBackgroundNormalColor)
self.addSubview(view)
}(self.arrowView))
({ (view: UITableView) in
view.delegate = self
view.dataSource = self
view.separatorStyle = .none
view.register(YSBubbleViewCell.self, forCellReuseIdentifier: "YSBubbleViewCell")
view.isScrollEnabled = self.cellAction.count > Config.maxNumberOfItems
view.canCancelContentTouches = false
view.delaysContentTouches = false
view.backgroundColor = Config.cellBackgroundNormalColor
view.layer.cornerRadius = Config.cornerRadius
view.layer.masksToBounds = true
view.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.0000001))
self.addSubview(view)
}(self.tableView))
self.tableView.snp.makeConstraints { (make) in
make.top.leading.bottom.trailing.equalTo(self).inset(UIEdgeInsets(top: Config.arrowWidth, left: Config.arrowWidth, bottom: Config.arrowWidth, right: Config.arrowWidth))
let count = CGFloat(min(CGFloat(Config.maxNumberOfItems) + 0.5, CGFloat(self.cellAction.count)))
make.height.equalTo(Config.cellHeight * count).priority(750)
}
self.layoutIfNeeded()
}
fileprivate func getAnchorWindow(_ anchorView: UIView) -> UIWindow {
var sv = anchorView.superview
while sv != nil {
if sv!.isKind(of: UIWindow.self) {
break
}
sv = sv!.superview
}
assert(sv != nil, "fatal: anchorView should be on some window")
let window = sv as! UIWindow
return window
}
fileprivate func getAnchorPosition(_ anchorView: UIView) -> CGPoint {
let window = self.getAnchorWindow(anchorView)
let center = CGPoint(x: anchorView.frame.width / 2.0, y: anchorView.frame.height / 2.0)
return anchorView.convert(center, to: window)
}
fileprivate func getAnchorDirection(_ anchorView: UIView) -> YSBubbleDiretcion {
let position = self.getAnchorPosition(anchorView)
let xRatio: CGFloat = position.x / UIScreen.main.bounds.width
let yRatio: CGFloat = position.y / UIScreen.main.bounds.height
switch (xRatio, yRatio) {
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(0.0 / 6.0)..<CGFloat(1.0 / 6.0)):
return .topLeft
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(0.0 / 6.0)..<CGFloat(1.0 / 6.0)):
return .topRight
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(1.0 / 6.0)..<CGFloat(2.0 / 6.0)):
return .leftTop
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(1.0 / 6.0)..<CGFloat(2.0 / 6.0)):
return .rightTop
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(2.0 / 6.0)..<CGFloat(4.0 / 6.0)):
return .left
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(2.0 / 6.0)..<CGFloat(4.0 / 6.0)):
return .right
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(4.0 / 6.0)..<CGFloat(5.0 / 6.0)):
return .leftBottom
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(4.0 / 6.0)..<CGFloat(5.0 / 6.0)):
return .rightBottom
case (CGFloat(0.0 / 3.0)..<CGFloat(1.0 / 3.0),
CGFloat(5.0 / 6.0)...CGFloat(6.0 / 6.0)):
return .bottomLeft
case (CGFloat(2.0 / 3.0)...CGFloat(3.0 / 3.0),
CGFloat(5.0 / 6.0)...CGFloat(6.0 / 6.0)):
return .bottomRight
case (CGFloat(1.0 / 3.0)...CGFloat(2.0 / 3.0),
CGFloat(0.0 / 6.0)..<CGFloat(4.0 / 6.0)):
return .top
case (CGFloat(1.0 / 3.0)...CGFloat(2.0 / 3.0),
CGFloat(4.0 / 6.0)...CGFloat(6.0 / 6.0)):
return .bottom
default:
print("warning: anchorView is out of screen")
return .top
}
}
override func showAnimation(completion closure: ((_ popupView: YSPopupView, _ finished: Bool) -> Void)?) {
if self.superview == nil {
self.targetView!.YS_dimBackgroundView.addSubview(self)
self.targetView!.YS_dimBackgroundView.layoutIfNeeded()
self.targetView!.YS_dimBackgroundAnimatingDuration = 0.15
self.duration = self.targetView!.YS_dimBackgroundAnimatingDuration
}
typealias Config = YSBubbleViewConfig
let center = self.getAnchorPosition(self.anchorView)
let widthOffset = self.anchorView.frame.size.width / 2.0
let heightOffset = self.anchorView.frame.size.height / 2.0
let arrowOffset = Config.arrowWidth * 2 + Config.cornerRadius
let xOffsetRatio = arrowOffset / self.frame.width
let yOffsetRatio = arrowOffset / self.frame.height
switch self.anchorDirection {
case .topLeft:
self.layer.anchorPoint = CGPoint(x: xOffsetRatio, y: 0.0)
self.layer.position = CGPoint(x: center.x, y: center.y + heightOffset)
case .leftTop:
self.layer.anchorPoint = CGPoint(x: 0.0, y: yOffsetRatio)
self.layer.position = CGPoint(x: center.x + widthOffset, y: center.y)
case .topRight:
self.layer.anchorPoint = CGPoint(x: 1.0 - xOffsetRatio, y: 0.0)
self.layer.position = CGPoint(x: center.x, y: center.y + heightOffset)
case .rightTop:
self.layer.anchorPoint = CGPoint(x: 1.0, y: yOffsetRatio)
self.layer.position = CGPoint(x: center.x - widthOffset, y: center.y)
case .bottomLeft:
self.layer.anchorPoint = CGPoint(x: xOffsetRatio, y: 1.0)
self.layer.position = CGPoint(x: center.x, y: center.y - heightOffset)
case .leftBottom:
self.layer.anchorPoint = CGPoint(x: 0.0, y: 1.0 - yOffsetRatio)
self.layer.position = CGPoint(x: center.x + widthOffset, y: center.y)
case .bottomRight:
self.layer.anchorPoint = CGPoint(x: 1.0 - xOffsetRatio, y: 1.0)
self.layer.position = CGPoint(x: center.x, y: center.y - heightOffset)
case .rightBottom:
self.layer.anchorPoint = CGPoint(x: 1.0, y: 1.0 - yOffsetRatio)
self.layer.position = CGPoint(x: center.x - widthOffset, y: center.y)
case .top:
self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0)
self.layer.position = CGPoint(x: center.x, y: center.y + heightOffset)
case .bottom:
self.layer.anchorPoint = CGPoint(x: 0.5, y: 1.0)
self.layer.position = CGPoint(x: center.x, y: center.y - heightOffset)
case .left:
self.layer.anchorPoint = CGPoint(x: 0.0, y: 0.5)
self.layer.position = CGPoint(x: center.x + widthOffset, y: center.y)
case .right:
self.layer.anchorPoint = CGPoint(x: 1.0, y: 0.5)
self.layer.position = CGPoint(x: center.x - widthOffset, y: center.y)
default:
break
}
self.arrowView.snp.makeConstraints { (make) in
make.size.equalTo(CGSize(width: 2.0 * (Config.arrowWidth + Config.cornerRadius), height: 2.0 * (Config.arrowWidth + Config.cornerRadius)))
switch self.anchorDirection {
case .topLeft:
make.centerY.equalTo(self.tableView.snp.top)
make.left.equalTo(self.tableView.snp.left)
case .leftTop:
make.centerX.equalTo(self.tableView.snp.left)
make.top.equalTo(self.tableView.snp.top)
case .topRight:
make.centerY.equalTo(self.tableView.snp.top)
make.right.equalTo(self.tableView.snp.right)
case .rightTop:
make.centerX.equalTo(self.tableView.snp.right)
make.top.equalTo(self.tableView.snp.top)
case .bottomLeft:
make.centerY.equalTo(self.tableView.snp.bottom)
make.left.equalTo(self.tableView.snp.left)
case .leftBottom:
make.centerX.equalTo(self.tableView.snp.left)
make.bottom.equalTo(self.tableView.snp.bottom)
case .bottomRight:
make.centerY.equalTo(self.tableView.snp.bottom)
make.right.equalTo(self.tableView.snp.right)
case .rightBottom:
make.centerX.equalTo(self.tableView.snp.right)
make.bottom.equalTo(self.tableView.snp.bottom)
case .top:
make.centerY.equalTo(self.tableView.snp.top)
make.centerX.equalTo(self.tableView.snp.centerX)
case .bottom:
make.centerY.equalTo(self.tableView.snp.bottom)
make.centerX.equalTo(self.tableView.snp.centerX)
case .left:
make.centerY.equalTo(self.tableView.snp.centerY)
make.centerX.equalTo(self.tableView.snp.left)
case .right:
make.centerY.equalTo(self.tableView.snp.centerY)
make.centerX.equalTo(self.tableView.snp.right)
default:
break
}
}
self.layer.transform = CATransform3DMakeScale(0.01, 0.01, 1.0)
UIView.animate(
withDuration: self.duration,
delay: 0.0,
options: [
UIViewAnimationOptions.curveEaseOut,
UIViewAnimationOptions.beginFromCurrentState
],
animations: {
self.layer.transform = CATransform3DIdentity
},
completion: { (finished: Bool) in
if let completionClosure = closure {
completionClosure(self, finished)
}
})
}
override func hideAnimation(completion closure: ((_ popupView: YSPopupView, _ finished: Bool) -> Void)?) {
UIView.animate(
withDuration: self.duration,
delay: 0.0,
options: [
UIViewAnimationOptions.curveEaseIn,
UIViewAnimationOptions.beginFromCurrentState
],
animations: {
self.layer.transform = CATransform3DMakeScale(0.01, 0.01, 1.0)
},
completion: { (finished: Bool) in
if finished {
self.removeFromSuperview()
}
if let completionClosure = closure {
completionClosure(self, finished)
}
})
}
}
extension YSBubbleView: UITableViewDelegate, UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cellAction.count
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return YSBubbleViewConfig.cellHeight
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "YSBubbleViewCell", for: indexPath) as! YSBubbleViewCell
let item = self.cellAction[indexPath.row]
cell.titleLabel.text = item.title
cell.showIcon = item.image != nil
cell.iconView.image = item.image
cell.split.isHidden = indexPath.row == self.cellAction.count - 1
return cell
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.cellAction[indexPath.row]
self.hide()
if let action = item.action {
action(indexPath.row)
}
}
}
private extension UIImage {
static func YS_rhombusWithSize(_ size: CGSize, color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
let path = UIBezierPath()
path.move(to: CGPoint(x: size.width / 2.0, y: 0.0))
path.addLine(to: CGPoint(x: size.width, y: size.height / 2.0))
path.addLine(to: CGPoint(x: size.width / 2.0, y: size.height))
path.addLine(to: CGPoint(x: 0, y: size.height / 2.0))
path.addLine(to: CGPoint(x: size.width / 2.0, y: 0.0))
path.close()
path.fill()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
private class YSBubbleViewCell: UITableViewCell {
var showIcon = false {
didSet {
self.iconView.isHidden = !showIcon
self.titleLabel.snp.updateConstraints { (make) in
make.leading.equalTo(self.iconView.snp.trailing).offset(self.showIcon ? YSBubbleViewConfig.innerPadding : -YSBubbleViewConfig.iconSize.width)
}
}
}
let iconView = UIImageView()
let titleLabel = UILabel()
let split = UIView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
typealias Config = YSBubbleViewConfig
self.selectionStyle = .none
self.contentView.backgroundColor = Config.cellBackgroundNormalColor
({ (view: UIImageView) in
self.contentView.addSubview(view)
}(self.iconView))
({ (view: UILabel) in
view.textColor = Config.cellTitleColor
view.font = Config.cellTitleFont
view.textAlignment = Config.cellTitleAlignment
view.adjustsFontSizeToFitWidth = true
self.contentView.addSubview(view)
}(self.titleLabel))
({ (view: UIView) in
view.backgroundColor = Config.cellSplitColor
self.contentView.addSubview(view)
}(self.split))
self.iconView.snp.makeConstraints { (make) in
make.centerY.equalTo(self.contentView)
make.leading.equalTo(self.contentView.snp.leading).offset(Config.innerPadding)
make.size.equalTo(Config.iconSize)
}
self.titleLabel.snp.makeConstraints { (make) in
make.leading.equalTo(self.iconView.snp.trailing).offset(self.showIcon ? Config.innerPadding : -Config.iconSize.width)
make.top.bottom.trailing.equalTo(self.contentView).inset(UIEdgeInsets(top: 0, left: Config.innerPadding, bottom: 0, right: Config.innerPadding))
}
self.split.snp.makeConstraints { (make) in
make.leading.bottom.trailing.equalTo(self.contentView)
make.height.equalTo(Config.splitWidth)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.contentView.backgroundColor = YSBubbleViewConfig.cellBackgroundHighlightedColor
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
self.contentView.backgroundColor = YSBubbleViewConfig.cellBackgroundNormalColor
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
self.contentView.backgroundColor = YSBubbleViewConfig.cellBackgroundNormalColor
}
}
public struct YSBubbleViewConfig {
static var maxNumberOfItems = 5
static var width: CGFloat = 120.0
static var cornerRadius: CGFloat = 5.0
static var cellHeight: CGFloat = 50.0
static var innerPadding: CGFloat = 10.0
static var splitWidth: CGFloat = 1.0 / UIScreen.main.scale
static var iconSize: CGSize = CGSize(width: 25, height: 25)
static var arrowWidth: CGFloat = 10.0
static var cellTitleAlignment: NSTextAlignment = .left
static var cellTitleFont: UIFont = UIFont.systemFont(ofSize: 14)
static var cellTitleColor: UIColor = UIColor.YS_hexColor(0x333333FF)
static var cellSplitColor: UIColor = UIColor.YS_hexColor(0xCCCCCCFF)
static var cellBackgroundNormalColor: UIColor = UIColor.YS_hexColor(0xFFFFFFFF)
static var cellBackgroundHighlightedColor: UIColor = UIColor.YS_hexColor(0xCCCCCCFF)
static var cellImageColor: UIColor = UIColor.YS_hexColor(0xFFFFFFFF)
}
| mit | 0b6a330dc2b64c3ab84f3c0b8c56ed2f | 37.449905 | 197 | 0.608505 | 4.432338 | false | true | false | false |
coaoac/GridView | CustomGridView/GridViewController.swift | 1 | 2151 | // Created by Amine Chaouki on 10/05/15.
// Copyright (c) 2015 chaouki. All rights reserved.
//
import UIKit
//Section = row, item = column
public class GridViewController: UICollectionViewController {
// let titleCellIdentifier = "TitleCellIdentifier"
// let contentCellIdentifier = "ContentCellIdentifier"
public var dataSource: GridViewLayoutDataSource!
//@IBOutlet weak var layout: GridViewLayout!
weak var layout: GridViewLayout!
public override func viewDidLoad() {
super.viewDidLoad()
layout = collectionViewLayout as! GridViewLayout
layout.dataSource = dataSource
}
// MARK - UICollectionViewDataSource
public override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return dataSource.numberOfRows() + dataSource.numberOfColumnTitles()
}
public override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.numberOfColumns() + dataSource.numberOfRowTitles()
}
public override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let row = indexPath.section
let column = indexPath.item
switch (row, column) {
case (0..<dataSource.numberOfColumnTitles(), 0..<dataSource.numberOfRowTitles()):
return dataSource.cornerCellForIndexPath(indexPath, cornerColumnIndex: column, cornerRowIndex: row)
case (_, 0..<dataSource.numberOfRowTitles()):
return dataSource.rowTitleCellForIndexPath(indexPath, rowtitleCellIndex: column, rowIndex: row - dataSource.numberOfColumnTitles())
case (0..<dataSource.numberOfColumnTitles(), _):
return dataSource.columnTitleCellForIndexPath(indexPath, columnTitleCellIndex: row, columnIndex: column - dataSource.numberOfRowTitles())
default:
return dataSource.contentCellForIndexPath(indexPath, columnIndex: column - dataSource.numberOfRowTitles(), rowIndex: row - dataSource.numberOfColumnTitles())
}
}
}
| mit | 00fcf1e0e29bbb20a5ec09fd9edd6e5d | 32.092308 | 169 | 0.72292 | 5.660526 | false | false | false | false |
jtsmrd/Intrview | ViewControllers/BusinessProfileInfoEditVC.swift | 1 | 7039 | //
// BusinessProfileInfoEditVC.swift
// SnapInterview
//
// Created by JT Smrdel on 1/16/17.
// Copyright © 2017 SmrdelJT. All rights reserved.
//
import UIKit
class BusinessProfileInfoEditVC: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var profileImageView: ProfileImageView!
@IBOutlet weak var addReplaceImageButton: UIButton!
@IBOutlet weak var companyNameTextField: UITextField!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var contactEmailTextField: UITextField!
@IBOutlet weak var websiteTextField: UITextField!
@IBOutlet weak var scrollView: UIScrollView!
let imageStore = ImageStore()
var profile = (UIApplication.shared.delegate as! AppDelegate).profile
var currentFirstResponder: UIView!
var navToolBar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
let saveBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveButtonAction))
saveBarButtonItem.tintColor = UIColor.white
navigationItem.rightBarButtonItem = saveBarButtonItem
let backBarButtonItem = UIBarButtonItem(image: UIImage(named: "left_icon"), style: .plain, target: self, action: #selector(backButtonAction))
backBarButtonItem.tintColor = UIColor.white
navigationItem.leftBarButtonItem = backBarButtonItem
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
navToolBar = createKeyboardToolBar()
configureView()
}
@objc func saveButtonAction() {
profile.businessProfile?.name = companyNameTextField.text
profile.businessProfile?.location = locationTextField.text
profile.businessProfile?.contactEmail = contactEmailTextField.text
profile.businessProfile?.website = websiteTextField.text
profile.save()
let _ = navigationController?.popViewController(animated: true)
}
@objc func backButtonAction() {
let _ = navigationController?.popViewController(animated: true)
}
@IBAction func addReplaceImageButtonAction(_ sender: Any) {
addProfileImage()
}
private func configureView() {
self.companyNameTextField.text = profile.businessProfile?.name
self.locationTextField.text = profile.businessProfile?.location
self.contactEmailTextField.text = profile.businessProfile?.contactEmail
self.websiteTextField.text = profile.businessProfile?.website
if let image = profile.businessProfile?.profileImage {
profileImageView.image = image
addReplaceImageButton.setTitle("Replace Image", for: .normal)
}
else {
profileImageView.image = UIImage(named: "default_profile_image")
addReplaceImageButton.setTitle("Add Image", for: .normal)
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
currentFirstResponder = textField
textField.inputAccessoryView = navToolBar
}
@objc func keyboardWillShow(notification: NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardHeight = keyboardFrame.cgRectValue.height
let currentTextFieldOrigin = currentFirstResponder.frame.origin
let currentTextFieldHeight = currentFirstResponder.frame.size.height
var visibleRect = view.frame
visibleRect.size.height -= keyboardHeight
let scrollPoint = CGPoint(x: 0.0, y: currentTextFieldOrigin.y - visibleRect.size.height + (currentTextFieldHeight * 3))
scrollView.setContentOffset(scrollPoint, animated: true)
}
@objc func keyboardWillHide(notification: NSNotification) {
scrollView.setContentOffset(CGPoint.zero, animated: true)
}
// MARK: - ImageView Delegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageKey = UUID().uuidString
profileImageView.image = image
imageStore.setImage(image, forKey: imageKey)
profile.businessProfile?.profileImage = image
profile.businessProfile?.saveImage(tempImageKey: imageKey)
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func addProfileImage() {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
// MARK: - Keyboard toolbar
@objc func doneAction() {
if currentFirstResponder != nil {
currentFirstResponder.resignFirstResponder()
}
}
@objc func previousAction() {
if let previousField = currentFirstResponder.superview!.viewWithTag(currentFirstResponder.tag - 100) {
previousField.becomeFirstResponder()
}
}
@objc func nextAction() {
if let nextField = currentFirstResponder.superview!.viewWithTag(currentFirstResponder.tag + 100) {
nextField.becomeFirstResponder()
}
}
fileprivate func createKeyboardToolBar() -> UIToolbar {
let keyboardToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))
keyboardToolBar.barStyle = .default
let previous = UIBarButtonItem(image: UIImage(named: "left_icon"), style: .plain, target: self, action: #selector(previousAction))
previous.width = 50
previous.tintColor = Global.greenColor
let next = UIBarButtonItem(image: UIImage(named: "right_icon"), style: .plain, target: self, action: #selector(nextAction))
next.width = 50
next.tintColor = Global.greenColor
let done = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneAction))
done.tintColor = Global.greenColor
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
keyboardToolBar.items = [previous, next, flexSpace, done]
keyboardToolBar.sizeToFit()
return keyboardToolBar
}
}
| mit | 9987cda8e4c4ae52bba4f4437743009b | 38.762712 | 165 | 0.684143 | 5.616919 | false | false | false | false |
knutigro/AppReviews | AppReviews/ReviewPieChartController.swift | 1 | 1776 | //
// PieChart.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-05-04.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import AppKit
class ReviewPieChartController: NSViewController {
@IBOutlet weak var pieChart: PieChart?
var slices = [Float]()
var sliceColors: [NSColor]!
override func viewDidLoad() {
super.viewDidLoad()
sliceColors = [NSColor.reviewRed(), NSColor.reviewOrange(), NSColor.reviewYellow(), NSColor.reviewGreen(), NSColor.reviewBlue()]
if let pieChart = pieChart {
pieChart.dataSource = self
pieChart.delegate = self
pieChart.pieCenter = CGPointMake(240, 240)
pieChart.showPercentage = false
}
}
}
extension ReviewPieChartController: PieChartDataSource {
func numberOfSlicesInPieChart(pieChart: PieChart!) -> UInt {
return UInt(slices.count)
}
func pieChart(pieChart: PieChart!, valueForSliceAtIndex index: UInt) -> CGFloat {
return CGFloat(slices[Int(index)])
}
func pieChart(pieChart: PieChart!, colorForSliceAtIndex index: UInt) -> NSColor! {
return sliceColors[Int(index) % sliceColors.count]
}
func pieChart(pieChart: PieChart!, textForSliceAtIndex index: UInt) -> String! {
return (NSString(format: NSLocalizedString("%i Stars", comment: "review.slice.tooltip"), index + 1) as String)
}
}
extension ReviewPieChartController: PieChartDelegate {
func pieChart(pieChart: PieChart!, toopTipStringAtIndex index: UInt) -> String! {
let number = slices[Int(index)]
return (NSString(format: NSLocalizedString("Number of ratings: ", comment: "review.slice.tooltip"), number) as String)
}
}
| gpl-3.0 | 1cfa3299e8761889dff35f3ca0cd2e92 | 30.157895 | 136 | 0.657095 | 4.519084 | false | false | false | false |
OHeroJ/twicebook | Sources/App/Models/UserToken.swift | 1 | 1189 | //
// UserToken.swift
// seesometop
//
// Created by laijihua on 29/08/2017.
//
//
import Foundation
import Vapor
import FluentProvider
final class UserToken: Model {
var token: String
var userId: Identifier
let storage: Storage = Storage()
struct Key {
static let token = "token"
static let userId = "user_id"
}
var user: Parent<UserToken, User> {
return parent(id: userId)
}
init(token: String, userId: Identifier) {
self.token = token
self.userId = userId
}
init(row: Row) throws {
token = try row.get(Key.token)
userId = try row.get(Key.userId)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Key.token, token)
try row.set(Key.userId, userId)
return row
}
}
extension UserToken: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self, closure: { (builder) in
builder.id()
builder.string(Key.token)
builder.parent(User.self)
})
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
| mit | a961948b95895d3895066ec97b95b212 | 19.859649 | 57 | 0.585366 | 3.885621 | false | false | false | false |
Pyroh/Fluor | Fluor/Models/Enums.swift | 1 | 4282 | //
// Enums.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// 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 DefaultsWrapper
@objc enum FKeyMode: Int {
case media = 0
case function
var behavior: AppBehavior {
switch self {
case .media:
return .media
case .function:
return .function
}
}
var counterPart: FKeyMode {
switch self {
case .media: return .function
case .function: return .media
}
}
var label: String {
switch self {
case .media:
return NSLocalizedString("Media keys", comment: "")
case .function:
return NSLocalizedString("Function keys", comment: "")
}
}
}
@objc enum AppBehavior: Int {
case inferred = 0
case media
case function
var counterPart: AppBehavior {
switch self {
case .media:
return .function
case .function:
return .media
default:
return .inferred
}
}
var label: String {
switch self {
case .inferred:
return NSLocalizedString("Same as default", comment: "")
case .media:
return NSLocalizedString("Media keys", comment: "")
case .function:
return NSLocalizedString("Function keys", comment: "")
}
}
}
@objc enum SwitchMethod: Int {
case window = 0
case hybrid
case key
}
enum ItemKind {
case rule
case runningApp
var source: NotificationSource {
switch self {
case .rule:
return .rule
case .runningApp:
return .runningApp
}
}
}
enum NotificationSource {
case rule
case runningApp
case mainMenu
case fnKey
case behaviorManager
case undefined
}
struct UserNotificationEnablement: OptionSet {
let rawValue: Int
static let appSwitch: Self = .init(rawValue: 1 << 0)
static let appKey: Self = .init(rawValue: 1 << 1)
static let globalKey: Self = .init(rawValue: 1 << 2)
static let all: Self = [.appSwitch, .appKey, .globalKey]
static let none: Self = []
static func from(_ vc: UserNotificationEnablementViewController) -> Self {
guard !vc.everytime else { return .all }
return Self.none
.union(vc.activeAppSwitch ? .appSwitch : .none)
.union(vc.activeAppFnKey ? .appKey : .none)
.union(vc.globalFnKey ? .globalKey : .none)
}
func apply(to vc: UserNotificationEnablementViewController) {
if self == .all {
vc.everytime = true
vc.activeAppSwitch = true
vc.activeAppFnKey = true
vc.globalFnKey = true
} else if self == .none {
vc.everytime = false
vc.activeAppSwitch = false
vc.activeAppFnKey = false
vc.globalFnKey = false
} else {
vc.everytime = false
vc.activeAppSwitch = self.contains(.appSwitch)
vc.activeAppFnKey = self.contains(.appKey)
vc.globalFnKey = self.contains(.globalKey)
}
}
}
| mit | d06793b27505854d7d47e6c9fd17738b | 26.805195 | 82 | 0.606259 | 4.48377 | false | false | false | false |
adelinofaria/Buildasaur | Buildasaur/AppDelegate.swift | 2 | 2528 | //
// AppDelegate.swift
// Buildasaur
//
// Created by Honza Dvorsky on 12/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Cocoa
/*
Please report any crashes on GitHub, I may optionally ask you to email them to me. Thanks!
You can find them at ~/Library/Logs/DiagnosticReports/Buildasaur-*
Also, you can find the log at ~/Library/Application Support/Buildasaur/Builda.log
*/
import BuildaUtils
import XcodeServerSDK
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let menuItemManager = MenuItemManager()
func applicationDidFinishLaunching(aNotification: NSNotification) {
self.setupLogging()
self.menuItemManager.setupMenuBarItem()
}
func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
self.showMainWindow()
return true
}
func applicationDidBecomeActive(notification: NSNotification) {
self.showMainWindow()
}
func applicationWillTerminate(aNotification: NSNotification) {
StorageManager.sharedInstance.stop()
}
//MARK: Showing Window on Reactivation
func showMainWindow(){
NSApp.activateIgnoringOtherApps(true)
//first window. i wish there was a nicer way (please some tell me there is)
if let window = NSApplication.sharedApplication().windows.first as? NSWindow {
window.makeKeyAndOrderFront(self)
}
}
//MARK: Logging
func setupLogging() {
let path = Persistence.buildaApplicationSupportFolderURL().URLByAppendingPathComponent("Builda.log", isDirectory: false)
let fileLogger = FileLogger(filePath: path)
let consoleLogger = ConsoleLogger()
let loggers: [Logger] = [
consoleLogger,
fileLogger
]
Log.addLoggers(loggers)
let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
let ascii =
" ____ _ _ _\n" +
"| _ \\ (_) | | |\n" +
"| |_) |_ _ _| | __| | __ _ ___ __ _ _ _ _ __\n" +
"| _ <| | | | | |/ _` |/ _` / __|/ _` | | | | '__|\n" +
"| |_) | |_| | | | (_| | (_| \\__ \\ (_| | |_| | |\n" +
"|____/ \\__,_|_|_|\\__,_|\\__,_|___/\\__,_|\\__,_|_|\n"
Log.untouched("*\n*\n*\n\(ascii)\nBuildasaur \(version) launched at \(NSDate()).\n*\n*\n*\n")
}
}
| mit | 720a34bec4c78c0429a483233af25ebd | 29.457831 | 128 | 0.572785 | 4.435088 | false | false | false | false |
PSSWD/psswd-ios | psswd/AuthSigninMasterpassVC.swift | 1 | 1359 | //
// AuthSigninMasterpassVC.swift
// psswd
//
// Created by Daniil on 09.01.15.
// Copyright (c) 2015 kirick. All rights reserved.
//
import UIKit
class AuthSigninMasterpassVC: UITableViewController
{
@IBOutlet weak var masterpassField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
}
@IBAction func nextPressed(sender: AnyObject) {
var masterpass = masterpassField.text!
var masterpass_getCodes_public = Crypto.Bytes(fromString: masterpass).append(API.constants.salt_masterpass_getcodes_public).getSHA1()
var params = [
"email": Storage.getString("email")!,
"masterpass_getcodes_public": masterpass_getCodes_public,
"app_id": API.app.app_id,
"app_secret": API.app.app_secret
] as [String: AnyObject]
API.call("device.create", params: params, callback: { rdata in
let code = rdata["code"] as! Int
switch code {
case 0:
Storage.set(rdata["data"] as! String, forKey: "device_id")
var vc = self.storyboard?.instantiateViewControllerWithIdentifier("AuthSigninConfirmVC") as! AuthSigninConfirmVC
vc.masterpass = masterpass
self.navigationController!.pushViewController(vc, animated: true)
case 201:
Funcs.message("Неверный мастерпароль.")
self.masterpassField.text = ""
default:
API.unknownCode(rdata)
}
})
}
}
| gpl-2.0 | ae56dee2d27accc74aea860b24c16c78 | 25.78 | 135 | 0.70127 | 3.398477 | false | false | false | false |
PJayRushton/stats | Stats/SwipeTransitionDelegate.swift | 2 | 2735 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import UIKit
public class SwipeTransitionDelegate: NSObject {
public var targetEdge: UIRectEdge
public var edgeForDragging: UIRectEdge
public var gestureRecognizer: UIPanGestureRecognizer?
public var scrollView: UIScrollView?
public var presentingCornerRadius: CGFloat
public var dimmingBackgroundColor: UIColor?
public init(targetEdge: UIRectEdge, edgeForDragging: UIRectEdge? = nil, gestureRecognizer: UIPanGestureRecognizer? = nil, scrollView: UIScrollView? = nil, presentingCornerRadius: CGFloat = 0.0, dimmingBackgroundColor: UIColor? = nil) {
self.targetEdge = targetEdge
if let edgeForDragging = edgeForDragging {
self.edgeForDragging = edgeForDragging
} else {
self.edgeForDragging = targetEdge
}
self.gestureRecognizer = gestureRecognizer
self.scrollView = scrollView
self.presentingCornerRadius = presentingCornerRadius
self.dimmingBackgroundColor = dimmingBackgroundColor
}
}
// MARK: - View controller transitioning delegate
extension SwipeTransitionDelegate: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SwipeTransitionAnimator(targetEdge: targetEdge, presentingCornerRadius: presentingCornerRadius, dimmingBackgroundColor: dimmingBackgroundColor)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SwipeTransitionAnimator(targetEdge: targetEdge, presentingCornerRadius: presentingCornerRadius, dimmingBackgroundColor: dimmingBackgroundColor)
}
public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if let gestureRecognizer = gestureRecognizer {
return SwipeTransitionInteractionController(edgeForDragging: edgeForDragging, gestureRecognizer: gestureRecognizer, scrollView: scrollView)
}
return nil
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if let gestureRecognizer = gestureRecognizer {
return SwipeTransitionInteractionController(edgeForDragging: edgeForDragging, gestureRecognizer: gestureRecognizer, scrollView: scrollView)
}
return nil
}
}
| mit | 37f51ef44c3384c0da1d614b43eae78a | 43.344262 | 239 | 0.737893 | 6.935897 | false | false | false | false |
ludoded/ReceiptBot | Pods/Material/Sources/iOS/View.swift | 3 | 6116 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
open class View: UIView {
open override var intrinsicContentSize: CGSize {
return CGSize(width: width, height: height)
}
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
open let visualLayer = CAShapeLayer()
/**
A property that manages an image for the visualLayer's contents
property. Images should not be set to the backing layer's contents
property to avoid conflicts when using clipsToBounds.
*/
@IBInspectable
open var image: UIImage? {
get {
guard let v = visualLayer.contents else {
return nil
}
return UIImage(cgImage: v as! CGImage)
}
set(value) {
visualLayer.contents = value?.cgImage
}
}
/**
Allows a relative subrectangle within the range of 0 to 1 to be
specified for the visualLayer's contents property. This allows
much greater flexibility than the contentsGravity property in
terms of how the image is cropped and stretched.
*/
@IBInspectable
open var contentsRect: CGRect {
get {
return visualLayer.contentsRect
}
set(value) {
visualLayer.contentsRect = value
}
}
/**
A CGRect that defines a stretchable region inside the visualLayer
with a fixed border around the edge.
*/
@IBInspectable
open var contentsCenter: CGRect {
get {
return visualLayer.contentsCenter
}
set(value) {
visualLayer.contentsCenter = value
}
}
/**
A floating point value that defines a ratio between the pixel
dimensions of the visualLayer's contents property and the size
of the view. By default, this value is set to the Screen.scale.
*/
@IBInspectable
open var contentsScale: CGFloat {
get {
return visualLayer.contentsScale
}
set(value) {
visualLayer.contentsScale = value
}
}
/// A Preset for the contentsGravity property.
@IBInspectable
open var contentsGravityPreset: Gravity {
didSet {
contentsGravity = GravityToValue(gravity: contentsGravityPreset)
}
}
/// Determines how content should be aligned within the visualLayer's bounds.
@IBInspectable
open var contentsGravity: String {
get {
return visualLayer.contentsGravity
}
set(value) {
visualLayer.contentsGravity = value
}
}
/// A property that accesses the backing layer's background
@IBInspectable
open override var backgroundColor: UIColor? {
didSet {
layer.backgroundColor = backgroundColor?.cgColor
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
contentsGravityPreset = .resizeAspectFill
super.init(coder: aDecoder)
prepare()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
contentsGravityPreset = .resizeAspectFill
super.init(frame: frame)
prepare()
}
/// Convenience initializer.
public convenience init() {
self.init(frame: .zero)
prepare()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutShape()
layoutVisualLayer()
layoutShadowPath()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
contentScaleFactor = Screen.scale
backgroundColor = .white
prepareVisualLayer()
}
}
extension View {
/// Prepares the visualLayer property.
fileprivate func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
layer.addSublayer(visualLayer)
}
}
extension View {
/// Manages the layout for the visualLayer property.
fileprivate func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.cornerRadius = cornerRadius
}
}
| lgpl-3.0 | 739cf7b93d1fe2b2bd0e705bd94ed09b | 29.427861 | 88 | 0.702093 | 4.72278 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/CGFloatExtensions.swift | 1 | 3656 | //
// CGFloatExtensions.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/14/19.
//
import Foundation
import QuartzCore
extension CGFloat {
func isInRangeOrEqual(_ from: CGFloat, _ to: CGFloat) -> Bool {
return (from <= self && self <= to)
}
func isInRange(_ from: CGFloat, _ to: CGFloat) -> Bool {
return (from < self && self < to)
}
var squared: CGFloat {
return self * self
}
var cubed: CGFloat {
return self * self * self
}
var cubicRoot: CGFloat {
return CGFloat(pow(Double(self), 1.0 / 3.0))
}
fileprivate static func SolveQuadratic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat) -> CGFloat {
var result = (-b + sqrt(b.squared - 4 * a * c)) / (2 * a);
guard !result.isInRangeOrEqual(0, 1) else {
return result
}
result = (-b - sqrt(b.squared - 4 * a * c)) / (2 * a);
guard !result.isInRangeOrEqual(0, 1) else {
return result
}
return -1;
}
fileprivate static func SolveCubic(_ a: CGFloat, _ b: CGFloat, _ c: CGFloat, _ d: CGFloat) -> CGFloat {
if (a == 0) {
return SolveQuadratic(b, c, d)
}
if (d == 0) {
return 0
}
let a = a
var b = b
var c = c
var d = d
b /= a
c /= a
d /= a
var q = (3.0 * c - b.squared) / 9.0
let r = (-27.0 * d + b * (9.0 * c - 2.0 * b.squared)) / 54.0
let disc = q.cubed + r.squared
let term1 = b / 3.0
if (disc > 0) {
var s = r + sqrt(disc)
s = (s < 0) ? -((-s).cubicRoot) : s.cubicRoot
var t = r - sqrt(disc)
t = (t < 0) ? -((-t).cubicRoot) : t.cubicRoot
let result = -term1 + s + t;
if result.isInRangeOrEqual(0, 1) {
return result
}
} else if (disc == 0) {
let r13 = (r < 0) ? -((-r).cubicRoot) : r.cubicRoot;
var result = -term1 + 2.0 * r13;
if result.isInRangeOrEqual(0, 1) {
return result
}
result = -(r13 + term1);
if result.isInRangeOrEqual(0, 1) {
return result
}
} else {
q = -q;
var dum1 = q * q * q;
dum1 = acos(r / sqrt(dum1));
let r13 = 2.0 * sqrt(q);
var result = -term1 + r13 * cos(dum1 / 3.0);
if result.isInRangeOrEqual(0, 1) {
return result
}
result = -term1 + r13 * cos((dum1 + 2.0 * .pi) / 3.0);
if result.isInRangeOrEqual(0, 1) {
return result
}
result = -term1 + r13 * cos((dum1 + 4.0 * .pi) / 3.0);
if result.isInRangeOrEqual(0, 1) {
return result
}
}
return -1;
}
func cubicBezierInterpolate(_ P0: CGPoint, _ P1: CGPoint, _ P2: CGPoint, _ P3: CGPoint) -> CGFloat {
var t: CGFloat
if (self == P0.x) {
// Handle corner cases explicitly to prevent rounding errors
t = 0
} else if (self == P3.x) {
t = 1
} else {
// Calculate t
let a = -P0.x + 3 * P1.x - 3 * P2.x + P3.x;
let b = 3 * P0.x - 6 * P1.x + 3 * P2.x;
let c = -3 * P0.x + 3 * P1.x;
let d = P0.x - self;
let tTemp = CGFloat.SolveCubic(a, b, c, d);
if (tTemp == -1) {
return -1;
}
t = tTemp
}
// Calculate y from t
return (1 - t).cubed * P0.y + 3 * t * (1 - t).squared * P1.y + 3 * t.squared * (1 - t) * P2.y + t.cubed * P3.y;
}
func cubicBezier(_ t: CGFloat, _ c1: CGFloat, _ c2: CGFloat, _ end: CGFloat) -> CGFloat {
let t_ = (1.0 - t)
let tt_ = t_ * t_
let ttt_ = t_ * t_ * t_
let tt = t * t
let ttt = t * t * t
return self * ttt_
+ 3.0 * c1 * tt_ * t
+ 3.0 * c2 * t_ * tt
+ end * ttt;
}
}
| mit | 7f3b258b8a5f27dcab758402e74427eb | 23.536913 | 115 | 0.484136 | 3.014015 | false | false | false | false |
volodg/iAsync.utils | Sources/Array/HashableArray.swift | 1 | 2147 | //
// HashableArray.swift
// iAsync_utils
//
// Created by Vladimir Gorbenko on 02.10.14.
// Copyright © 2014 EmbeddedSources. All rights reserved.
//
import Foundation
public struct HashableArray<T: Equatable> : Hashable, Collection/*, MutableCollectionType*/, CustomStringConvertible, ExpressibleByArrayLiteral {
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return array.index(after: i)
}
public var array: Array<T>
// typealias SubSequence = MutableSlice<Self>
// public subscript (position: Self.Index) -> Self.Generator.Element { get set }
// public subscript (bounds: Range<Self.Index>) -> Self.SubSequence { get set }
public var last: T? {
return array.last
}
public typealias Iterator = Array<T>.Iterator
public typealias Index = Array<T>.Index
// public typealias Generator = Array<T>.Generator
public typealias Element = Array<T>.Element
public typealias _Element = Array<T>._Element
public var startIndex: Index { return array.startIndex }
public var endIndex: Index { return array.endIndex }
public subscript (position: Index) -> _Element {
return array[position]
}
public func makeIterator() -> Iterator {
return array.makeIterator()
}
public mutating func removeAll() {
array.removeAll()
}
public mutating func append(_ el: T) {
array.append(el)
}
public var hashValue: Int {
return array.count
}
public init(_ array: [T]) {
self.array = array
}
public init(arrayLiteral elements: Element...) {
self.init(Array(elements))
}
public init() {
self.init([])
}
public var description: String {
return "iAsync.utils.HashableArray: \(array)"
}
}
public func ==<T: Equatable>(lhs: HashableArray<T>, rhs: HashableArray<T>) -> Bool {
return lhs.array == rhs.array
}
| mit | 6486a21da6abc99f48ede9221e288244 | 24.547619 | 145 | 0.638863 | 4.283433 | false | false | false | false |
sunfei/realm-cocoa | examples/ios/swift-2.0/Backlink/AppDelegate.swift | 3 | 2243 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import UIKit
import RealmSwift
class Dog: Object {
dynamic var name = ""
dynamic var age = 0
var owners: [Person] {
// Realm doesn't persist this property because it only has a getter defined
// Define "owners" as the inverse relationship to Person.dogs
return linkingObjects(Person.self, forProperty: "dogs")
}
}
class Person: Object {
dynamic var name = ""
let dogs = List<Dog>()
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
do {
try NSFileManager.defaultManager().removeItemAtPath(Realm.Configuration.defaultConfiguration.path!)
} catch {}
let realm = try! Realm()
realm.write {
realm.create(Person.self, value: ["John", [["Fido", 1]]])
realm.create(Person.self, value: ["Mary", [["Rex", 2]]])
}
// Log all dogs and their owners using the "owners" inverse relationship
let allDogs = realm.objects(Dog)
for dog in allDogs {
let ownerNames = dog.owners.map { $0.name }
print("\(dog.name) has \(ownerNames.count) owners (\(ownerNames))")
}
return true
}
}
| apache-2.0 | 3e5278105463c70d2176869f1cdfb792 | 32.984848 | 128 | 0.616139 | 4.823656 | false | false | false | false |
ZakariyyaSv/LYNetwork | LYNetwork/Source/LYNetworkPrivate.swift | 1 | 9150 | //
// LYNetworkPrivate.swift
//
// Copyright (c) 2017 LYNetwork https://github.com/ZakariyyaSv/LYNetwork
//
// 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: - Debug Logger
func lyDebugPrintLog<T>(message: T,
file: String = #file,
method: String = #function,
line: Int = #line) {
#if DEBUG
if !LYNetworkConfig.shared.debugLogEnabled {
return
}
print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
#endif
}
// MARK: - RequestAccessory
extension LYBaseRequest {
public func toggleAccessoriesWillStartCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStart(self)
})
}
}
public func toggleAccessoriesWillStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStop(self)
})
}
}
public func toggleAccessoriesDidStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestDidStop(self)
})
}
}
}
extension LYBatchRequest {
public func toggleAccessoriesWillStartCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStart(self)
})
}
}
public func toggleAccessoriesWillStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStop(self)
})
}
}
public func toggleAccessoriesDidStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestDidStop(self)
})
}
}
}
extension LYChainRequest {
public func toggleAccessoriesWillStartCallBack() {
if self.requestAccessories != nil {
self.requestAccessories?.forEach({ (accessory) in
accessory.requestWillStart(self)
})
}
}
public func toggleAccessoriesWillStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestWillStop(self)
})
}
}
public func toggleAccessoriesDidStopCallBack() {
if self.requestAccessories != nil {
self.requestAccessories!.forEach({ (accessory) in
accessory.requestDidStop(self)
})
}
}
}
// MARK: - Equatable
extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func remove(_ object: Element) {
if let index = index(of: object) {
remove(at: index)
}
}
}
extension LYBatchRequest: Equatable {
public static func ==(lhs: LYBatchRequest, rhs: LYBatchRequest) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
extension LYChainRequest: Equatable {
public static func ==(lhs: LYChainRequest, rhs: LYChainRequest) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
// MARK: - LYNetworkError
open class LYNetworkError {
open class func summaryFrom(error: Error, response: HTTPURLResponse?) -> String {
if let statusCode = response?.statusCode {
switch statusCode {
case 400..<500: // Client Errors
return "客户端错误(HTTP错误代码: \(statusCode))"
case 500..<600: // Server Errors
return "网络异常,请重试(HTTP错误代码: \(statusCode))"
default:
break
}
}
let nsError: NSError = error as NSError
return nsError.lyDescription()
}
}
public extension String {
public func MD5String() -> String? {
return MD5(self)
}
}
public extension NSError {
// This description should cover NSURLErrorDomain & CFNetworkErrors and
// give a easy understanding description with error code.
// view the details on http://nshipster.com/nserror/
func lyDescription() -> String {
switch self.domain {
case NSURLErrorDomain:
switch self.code {
case -1..<110: // Network Errors
return "网络异常,请重试(错误代码:\(self.code))"
case 110..<119: //SOCKS4 Errors
return "网络异常,请重试(错误代码:\(self.code))"
case 120..<130: //SOCKS5 Errors
return "网络异常,请重试(错误代码:\(self.code))"
case 200..<300: // FTP Errors
return "网络异常,请重试(错误代码:\(self.code))"
case 300..<400: // HTTP Errors
return "网络异常,请重试(错误代码:\(self.code))"
case -998: // kCFURLErrorUnknown An unknown error occurred.
return "网络异常,请重试(错误代码:\(self.code))"
case -999: // kCFURLErrorCancelled/NSURLErrorCancelled The connection was cancelled.
return ""
case -1000: // kCFURLErrorBadURL/NSURLErrorBadURL
return ""
case -1001: // kCFURLErrorTimedOut/NSURLErrorTimedOut
return ""
case -1002: // kCFURLErrorUnsupportedURL/NSURLErrorUnsupportedURL
return ""
case -1003: // kCFURLErrorCannotFindHost/NSURLErrorCannotFindHost
return ""
case -1004: // kCFURLErrorCannotConnectToHost/NSURLErrorCannotConnectToHost
return ""
case -1005: // kCFURLErrorNetworkConnectionLost/NSURLErrorNetworkConnectionLost
return ""
case -1006: // kCFURLErrorDNSLookupFailed/NSURLErrorDNSLookupFailed
return ""
case -1007: // kCFURLErrorHTTPTooManyRedirects/NSURLErrorHTTPTooManyRedirects
return ""
case -1008..<(-999): // CFURLConnection & CFURLProtocol Errors
return "网络异常,请重试(错误代码:\(self.code))"
case -1009: // kCFURLErrorNotConnectedToInternet/NSURLErrorNotConnectedToInternet The connection failed because the device is not connected to the internet.
return "网络连接错误,请检查网络设置"
case -1010: // kCFURLErrorRedirectToNonExistentLocation/NSURLErrorRedirectToNonExistentLocation The connection was redirected to a nonexistent location
return "网络异常,请重试(错误代码:\(self.code))"
case -1011: // kCFURLErrorBadServerResponse/NSURLErrorBadServerResponse
return ""
case -1012: // kCFURLErrorUserCancelledAuthentication/NSURLErrorUserCancelledAuthentication
return ""
case -1013: // kCFURLErrorUserAuthenticationRequired/NSURLErrorUserAuthenticationRequired
return ""
case -1014: // kCFURLErrorZeroByteResource/NSURLErrorZeroByteResource
return ""
case -1015: // kCFURLErrorCannotDecodeRawData/NSURLErrorCannotDecodeRawData
return ""
case -1016: // kCFURLErrorCannotDecodeContentData/NSURLErrorCannotDecodeContentData
return ""
case -1017: // kCFURLErrorCannotParseResponse/NSURLErrorCannotParseResponse
return ""
case -1018: // kCFURLErrorInternationalRoamingOff 国际漫游
return ""
case -1019: // kCFURLErrorCallIsActive
return ""
case -1020: // kCFURLErrorDataNotAllowed
return ""
case -1021: // kCFURLErrorRequestBodyStreamExhausted
return ""
case -1022: // kCFURLErrorAppTransportSecurityRequiresSecureConnection
return ""
case -1103..<(-1099): // FTP Errors
return "手机系统异常,请重装应用(错误代码:\(self.code))"
case -1999..<(-1199): // SSL Errors
return "网络异常,请重试(错误代码:\(self.code))"
case -3007..<(-1999): // Download and File I/O Errors
return "手机系统异常,请重装应用(错误代码:\(self.code))"
case -4000: // Cookie errors
return "网络异常,请重启应用(错误代码:\(self.code))"
case -73000..<(-71000): // CFNetServices Errors
return "网络异常,请重试(错误代码:\(self.code))"
default:
return self.localizedDescription
}
default:
return self.localizedDescription
}
}
}
| mit | b49107606186fe10cb64d0a37473ab51 | 33.283465 | 162 | 0.677997 | 4.75847 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/NativeComponents/Detectors/FaceDetector/FaceDetectorOutput.swift | 1 | 6518 | //
// FaceDetectorOutput.swift
// StripeIdentity
//
// Created by Mel Ludowise on 5/10/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import CoreGraphics
import CoreML
import Foundation
@_spi(STP) import StripeCameraCore
import Vision
/// Represents the output from the FaceDetector ML model.
struct FaceDetectorOutput: Equatable {
let predictions: [FaceDetectorPrediction]
}
struct FaceDetectorPrediction: Equatable {
/// The bounding box of the detected face
let rect: CGRect
/// The score of the detected face
let score: Float
}
// MARK: MLBoundingBox
extension FaceDetectorPrediction: MLBoundingBox {
// FaceDetector has no classification, so each prediction has the same classIndex
var classIndex: Int {
return 0
}
}
// MARK: - MultiArray
extension FaceDetectorOutput: VisionBasedDetectorOutput {
/// We want to know if 0, 1, or > 1 faces are returned by the model, so tell
/// NMS to return a max of 2 results.
static let nmsMaxResults: Int = 2
/// Expected feature names from the ML model output
private enum FeatureNames: String {
case scores
case boxes
}
init(
detector: FaceDetector,
observations: [VNObservation],
originalImageSize: CGSize
) throws {
let featureValueObservations = observations.compactMap {
$0 as? VNCoreMLFeatureValueObservation
}
guard
let scoresObservation = featureValueObservations.first(where: {
$0.featureName == FeatureNames.scores.rawValue
}),
let boxesObservation = featureValueObservations.first(where: {
$0.featureName == FeatureNames.boxes.rawValue
}),
let scoresMultiArray = scoresObservation.featureValue.multiArrayValue,
let boxesMultiArray = boxesObservation.featureValue.multiArrayValue,
FaceDetectorOutput.isValidShape(boxes: boxesMultiArray, scores: scoresMultiArray)
else {
throw MLModelUnexpectedOutputError(observations: featureValueObservations)
}
self.init(
boxes: boxesMultiArray,
scores: scoresMultiArray,
originalImageSize: originalImageSize,
configuration: detector.configuration
)
}
/// Initializes `FaceDetectorOutput` from multi arrays of boxes and scores using
/// the non-maximum-suppression algorithm to determine the best scores and
/// bounding boxes.
/// - Parameters:
/// - boxes: The multi array of the "boxes" with a shape of
/// 1 x numPredictions x 4 where `boxes[0][n]` returns an array of
/// `[minX, minY, maxX, maxY]`
/// - scores: The multi array of the "scores" with a shape of
/// 1 x numPredictions x 1
init(
boxes: MLMultiArray,
scores: MLMultiArray,
originalImageSize: CGSize,
configuration: FaceDetector.Configuration
) {
let numPredictions = scores.shape[1].intValue
let predictions: [FaceDetectorPrediction] = (0..<numPredictions).compactMap { index in
let score = scores[[0, index, 0]].floatValue
// Discard results that have a score lower than minScore
guard score >= configuration.minScore else {
return nil
}
let rect = CGRect(
x: boxes[[0, index, 0]].doubleValue,
y: boxes[[0, index, 1]].doubleValue,
width: boxes[[0, index, 2]].doubleValue,
height: boxes[[0, index, 3]].doubleValue
)
// Discard results that are outside the bounds of the image
guard CGRect.normalizedBounds.contains(rect) else {
return nil
}
return .init(
rect: rect,
score: score
)
}
// Use NMS to get the best bounding boxes
// NOTE: The result of `nonMaxSuppression` will be sorted by score
let bestPredictions = nonMaxSuppression(
boundingBoxes: predictions,
iouThreshold: configuration.minIOU,
maxBoxes: FaceDetectorOutput.nmsMaxResults
).map { index in
return predictions[index]
}
self.init(
centerCroppedSquarePredictions: bestPredictions,
originalImageSize: originalImageSize
)
}
/// Initializes `FaceDetectorOutput` from a list of predictions using a
/// center-cropped square coordinate space.
///
/// - Note:
/// Because the FaceDetector model is only scanning the center-cropped
/// square region of the original image, the bounding box returned by
/// the model is going to be relative to the center-cropped square.
/// We need to convert the bounding box into coordinates relative to
/// the original image size.
///
/// - Parameters:
/// - predictions: A list of predictions using a center-cropped square coordinate space.
/// - originalImageSize: The size of the original image.
init(
centerCroppedSquarePredictions predictions: [FaceDetectorPrediction],
originalImageSize: CGSize
) {
self.init(
predictions: predictions.map {
.init(
rect: $0.rect.convertFromNormalizedCenterCropSquare(
toOriginalSize: originalImageSize
),
score: $0.score
)
}
)
}
/// Determines if the multi-arrays output by the FaceDetector's ML model have a
/// valid shape that can be parsed into a list of predictions.
///
/// - Parameters:
/// - boxes: The multi array of the "boxes" with a shape of
/// 1 x numPredictions x 4 where `boxes[0][n]` returns an array of
/// `[minX, minY, maxX, maxY]`
/// - scores: The multi array of the "scores" with a shape of
/// 1 x numPredictions x 1
///
/// - Returns: True if the multi-arrays have a valid shape that can be parsed into predictions.
static func isValidShape(
boxes: MLMultiArray,
scores: MLMultiArray
) -> Bool {
return boxes.shape.count == 3 && boxes.shape[0] == 1 && boxes.shape[2] == 4
&& scores.shape.count == 3 && scores.shape[0] == 1 && scores.shape[2] == 1
&& boxes.shape[1] == scores.shape[1]
}
}
| mit | dabdbe344b8e5bf20d1228c29a2a0c85 | 33.664894 | 99 | 0.608716 | 4.955894 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/Show/ShowStepViewController.swift | 1 | 3326 | //
// ShowStepViewController.swift
// Yep
//
// Created by nixzhu on 15/8/12.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import Ruler
class ShowStepViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet private weak var titleLabelBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet private weak var subTitleLabelBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.textColor = UIColor.yepTintColor()
titleLabelBottomConstraint.constant = Ruler.iPhoneVertical(20, 30, 30, 30).value
subTitleLabelBottomConstraint.constant = Ruler.iPhoneVertical(120, 140, 160, 180).value
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
view.alpha = 0
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.view.alpha = 1
}, completion: { _ in })
}
func repeatAnimate(view: UIView, alongWithPath path: UIBezierPath, duration: CFTimeInterval, autoreverses: Bool = false) {
let animation = CAKeyframeAnimation(keyPath: "position")
animation.calculationMode = kCAAnimationPaced
animation.fillMode = kCAFillModeForwards
animation.duration = duration
animation.repeatCount = Float.infinity
animation.autoreverses = autoreverses
if autoreverses {
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
} else {
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
}
animation.path = path.CGPath
view.layer.addAnimation(animation, forKey: "Animation")
}
func animate(view: UIView, offset: UInt32, duration: CFTimeInterval) {
let path = UIBezierPath()
func flip() -> CGFloat {
return arc4random() % 2 == 0 ? -1 : 1
}
let beginPoint = CGPoint(x: view.center.x + CGFloat(arc4random() % offset) * flip(), y: view.center.y + CGFloat(arc4random() % offset) * 0.5 * flip())
let endPoint = CGPoint(x: view.center.x + CGFloat(arc4random() % offset) * flip(), y: view.center.y + CGFloat(arc4random() % offset) * 0.5 * flip())
path.moveToPoint(beginPoint)
path.addLineToPoint(endPoint)
repeatAnimate(view, alongWithPath: path, duration: duration, autoreverses: true)
repeatRotate(view, fromValue: -0.1, toValue: 0.1, duration: duration)
}
private func repeatRotate(view: UIView, fromValue: AnyObject, toValue: AnyObject, duration: CFTimeInterval) {
let rotate = CABasicAnimation(keyPath: "transform.rotation.z")
rotate.fromValue = fromValue
rotate.toValue = toValue
rotate.duration = duration
rotate.repeatCount = Float.infinity
rotate.autoreverses = true
rotate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
view.layer.allowsEdgeAntialiasing = true
view.layer.addAnimation(rotate, forKey: "Rotate")
}
}
| mit | 1006acc6cdfd857374e1f4cb4a30e3a2 | 32.575758 | 158 | 0.679603 | 4.789625 | false | false | false | false |
Zewo/HTTP | Sources/HTTP/Content/Response+Content.swift | 5 | 2192 | import Axis
extension Response {
public var content: Map? {
get {
return storage["content"] as? Map
}
set(content) {
storage["content"] = content
}
}
}
extension Response {
public init<T : MapRepresentable>(status: Status = .ok, headers: Headers = [:], content: T, contentType: MediaType? = nil) {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = content.map
if let contentType = contentType {
self.contentType = contentType
}
}
public init<T : MapRepresentable>(status: Status = .ok, headers: Headers = [:], content: T?, contentType: MediaType? = nil) {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = content.map
if let contentType = contentType {
self.contentType = contentType
}
}
public init<T : MapRepresentable>(status: Status = .ok, headers: Headers = [:], content: [T], contentType: MediaType? = nil) {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = content.map
if let contentType = contentType {
self.contentType = contentType
}
}
public init<T : MapRepresentable>(status: Status = .ok, headers: Headers = [:], content: [String: T], contentType: MediaType? = nil) {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = content.map
if let contentType = contentType {
self.contentType = contentType
}
}
public init<T : MapFallibleRepresentable>(status: Status = .ok, headers: Headers = [:], content: T, contentType: MediaType? = nil) throws {
self.init(
status: status,
headers: headers,
body: Buffer()
)
self.content = try content.asMap()
if let contentType = contentType {
self.contentType = contentType
}
}
}
| mit | c4997b6b4afe8c1754bb454347fa5435 | 24.788235 | 143 | 0.532391 | 4.765217 | false | false | false | false |
cdtschange/SwiftMKit | SwiftMKit/UI/Schema/BaseKitWebViewController.swift | 1 | 28382 | //
// BaseKitWebViewController.swift
// SwiftMKitDemo
//
// Created by Mao on 4/28/16.
// Copyright © 2016 cdts. All rights reserved.
//
import UIKit
import SnapKit
import CocoaLumberjack
import MJRefresh
import WebKit
import WebViewJavascriptBridge
@objcMembers
open class BaseKitWebViewController: BaseKitViewController, WKNavigationDelegate, SharePannelViewDelegate, UIScrollViewDelegate {
struct InnerConst {
static let RootViewBackgroundColor : UIColor = UIColor(hex6: 0xefeff4)
static let WebViewBackgroundColor : UIColor = UIColor.clear
static let PannelTitleColor : UIColor = UIColor.gray
static let BackGroundTitleColor : UIColor = UIColor.darkGray
}
weak var _webView: WKWebView?
public var webView: WKWebView {
if let webV = _webView {
return webV
}
let webV = self.createWebView()
_webView = webV
return webV
}
private func createWebView() -> WKWebView {
let wkContentVc = WKUserContentController()
let cookieScript = WKUserScript(source: "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);", injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
// let wkUScript = WKUserScript.init(source: "", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
wkContentVc.addUserScript(cookieScript)
let config = WKWebViewConfiguration()
config.userContentController = wkContentVc
let _webView = WKWebView(frame: CGRect.zero, configuration: config)
//声明scrollView的位置 添加下面代码
if #available(iOS 11.0, *) {
_webView.scrollView.contentInsetAdjustmentBehavior = .never
}
_webView.backgroundColor = InnerConst.WebViewBackgroundColor
self.view.addSubview(_webView)
if let progressView = self.progressView {
self.view.bringSubview(toFront: progressView)
}
_webView.scrollView.delegate = self
_webView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
return _webView
}
open lazy var webViewBridge: WKWebViewJavascriptBridge = {
var bridge: WKWebViewJavascriptBridge = WKWebViewJavascriptBridge(for: self.webView)
bridge.setWebViewDelegate(self)
return bridge
}()
open var userAgent: String? {
get {
if #available(iOS 9.0, *) {
return webView.customUserAgent
} else {
var ua: String?
let semaphore = DispatchSemaphore(value: 0)
webView.evaluateJavaScript("navigator.userAgent", completionHandler: { (result, error) in
ua = result as? String
semaphore.signal()
})
semaphore.wait()
return ua
}
}
set(value) {
if #available(iOS 9.0, *) {
webView.customUserAgent = value
} else {
webView.evaluateJavaScript("navigator.userAgent") { [weak self] (result, error) in
UserDefaults.standard.register(defaults: ["UserAgent": value ?? ""])
if let wv = self?.createWebView() {
self?._webView = wv
_ = self?.webViewBridge
self?.webView.evaluateJavaScript("navigator.userAgent", completionHandler: {_,_ in})
}
}
}
}
}
open var requestHeader: [String: String]? {
get {
return nil
}
}
open var progressView : UIProgressView?
let keyPathForProgress : String = "estimatedProgress"
let keyPathForTitle : String = "title"
open var needBackRefresh:Bool = false
open var disableUserSelect = false
open var disableLongTouch = false
open var showRefreshHeader: Bool = true
open var showBackgroundLab:Bool = true
open var showNavigationBarTopLeftCloseButton: Bool = true
open var shouldAllowRirectToUrlInView: Bool = true
open var showNavRightToolPannelItem: Bool = true {
didSet {
self.refreshNavigationBarTopRightMoreButton()
}
}
open var recordOffset: Bool = true
open static var webOffsets: [String: CGFloat] = [:]
open var url: String?
open var moreUrlTitle: String? {
get {
if let host = URL(string: url ?? "")?.host {
return host
}
return url
}
}
private var isTitleFixed: Bool = false
var webViewToolsPannelView :SharePannelView?
var needRefreshCallBack: WVJBResponseCallback?
var isAutoUpdateTitle:Bool = true
///跳转前用
var beforRouteBlock:(() -> UIViewController?)?
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
webViewToolsPannelView?.tappedCancel()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if needBackRefresh { //跳转到原生页面,返回时是否需要刷新
needBackRefresh = false
self.loadData()
}
if let needRefreshCallBack = needRefreshCallBack { //如果有刷新回调,调用之
needRefreshCallBack(nil)
self.needRefreshCallBack = nil
}
}
/// webView加载失败后,显示网络错误页面(如果有)
open func setupBadNetworkView() -> UIView? {
return nil
}
private var isBadNetwork = false
private func showBadNetworkView() {
guard let badNetwork_view = setupBadNetworkView() else { return }
guard badNetwork_view.superview == nil else { return }
badNetwork_view.frame = view.bounds
view.addSubview(badNetwork_view)
}
private func removeBadNetworkView() {
if let badNetwork_view = setupBadNetworkView() {
badNetwork_view.removeFromSuperview()
}
}
open override func setupUI() {
super.setupUI()
NetworkListener.listen()
isTitleFixed = (self.title?.length ?? 0) > 0
self.view.backgroundColor = InnerConst.RootViewBackgroundColor
if showBackgroundLab {
self.view.addSubview(self.getBackgroundLab())
}
progressView = UIProgressView(frame: CGRect(x: 0, y: 0, width: self.screenW, height: 0))
progressView?.trackTintColor = UIColor.clear
self.view.addSubview(progressView!)
webView.addObserver(self, forKeyPath: keyPathForProgress, options: [NSKeyValueObservingOptions.new, NSKeyValueObservingOptions.old], context: nil)
webView.addObserver(self, forKeyPath: keyPathForTitle, options: [NSKeyValueObservingOptions.new], context: nil)
_ = self.webViewBridge
bindEvents()
if showRefreshHeader {
self.webView.scrollView.mj_header = self.webViewWithRefreshingBlock { [weak self] in
self?.loadData()
}
}
loadData()
NetworkListener.networkStatus.producer.startWithValues {[weak self](sender) in
if sender == .reachableViaWWAN || sender == .reachableViaWiFi {
DDLogInfo("[Network Status] WIFI或者蜂窝网络, status: \(sender)")
if self?.isBadNetwork == true {
self?.isBadNetwork = false
self?.removeBadNetworkView()
self?.loadData()
}
} else {
DDLogInfo("[Network Status] 无网络, status: \(sender)")
self?.isBadNetwork = true
self?.showBadNetworkView()
}
}
}
open override func setupNavigation() {
super.setupNavigation()
if let btnBack = navBtnBack() {
self.navigationItem.leftBarButtonItems = [btnBack]
}
self.refreshNavigationBarTopRightMoreButton()
}
open func webViewWithRefreshingBlock(_ refreshingBlock:@escaping MJRefreshComponentRefreshingBlock)->MJRefreshHeader{
let header = MJRefreshNormalHeader(refreshingBlock:refreshingBlock);
header?.activityIndicatorViewStyle = .gray
header?.labelLeftInset = 0
header?.setTitle("", for: .idle)
header?.setTitle("", for: .pulling)
header?.setTitle("", for: .refreshing)
header?.lastUpdatedTimeLabel.text = ""
header?.lastUpdatedTimeText = { _ in return "" }
return header!
}
open override func loadData() {
super.loadData()
if url != nil {
requestUrl(url: self.url)
}
}
open func requestUrl(url: String?) {
let url = url?.trimmingCharacters(in: .whitespaces) //去除前后空格
guard let urlStr = url, urlStr.length > 0 ,let urlResult = URL(string: urlStr), UIApplication.shared.canOpenURL(urlResult) else {
DDLogError("Request Invalid Url: \(url ?? "")")
return
}
DDLogInfo("Request url: \(urlStr)")
//清除旧数据
webView.evaluateJavaScript("document.body.innerHTML='';") { [weak self] _,_ in
let request = URLRequest(url: urlResult)
if let request = self?.willLoadRequest(request) {
self?.webView.load(request)
}
}
}
open func willLoadRequest(_ request: URLRequest) -> URLRequest {
var request = request
if let header = requestHeader {
for (key, value) in header {
request.setValue(value, forHTTPHeaderField: key)
}
}
return request
}
///是否需要跳到热修复,只给 goToSomewhere用
///可以在自己项目中重写该方法
func needRouteHotfix(controllerName:String, params:[String:Any]? = [:], pop:Bool? = false, needBlock:()->(), notNeedBlock:()->()) {
//默认不需要热修复
notNeedBlock()
///重写示例
// let needRouteHotfix:Bool
// if needRouteHotfix {
// needBlock()
// }else {
// notNeedBlock()
// }
}
open func bindEvents() {
/**
* H5跳转到任意原生页面
* 事件名:goToSomewhere
* 参数:
* name:String 用.分割sbName和vcName,例如: sbName.vcName
* refresh:Bool 跳转到原生页面,返回时是否需要刷新
* pop:Bool 是否present方式弹出
* params:[String:Any] 作为控制器的params
*/
self.bindEvent("goToSomewhere", handler: { [weak self] data , responseCallback in
if let dic = data as? [String:Any] {
if let name = dic["name"] as? String , name.length > 0{
//获得Controller名和Sb名
var (sbName,vcName) = (self?.getVcAndSbName(name: name) ?? (nil,nil))
if let vcName = vcName , vcName.length > 0 {
let refresh = (dic["refresh"] as? Bool) ?? false
let pop = (dic["pop"] as? Bool) ?? false
sbName = (sbName?.length ?? 0) > 0 ? sbName : nil
//是否是热切换页面
self?.needRouteHotfix(controllerName:vcName,
params:dic["params"] as? [String:Any],
pop:pop,
needBlock: {
self?.needBackRefresh = refresh
self?.needRefreshCallBack = responseCallback
}, notNeedBlock: {
if let vc = self?.initialedViewController(vcName, storyboardName: sbName){
//获得需要的参数
let paramsDic = dic["params"] as? [String:Any]
self?.setObjectParams(vc: vc, paramsDic: paramsDic)
self?.needBackRefresh = refresh
self?.needRefreshCallBack = responseCallback
if let topViewController = self?.beforRouteBlock?() {
topViewController.toNextViewController(viewController: vc, pop: pop)
}else {
self?.toNextViewController(viewController: vc, pop: pop)
}
}
})
}
}
}
})
/**
* H5给Native的单例或者静态变量赋值,
* 不支持同时改变静态属性和成员变量。需要调用多次依次修改
* 事件名: changeVariables
* 参数:
* name:String 用.分割类名和单例变量名,例如: BaseService.sharedBaseService(.sharedBaseService为空时,表示修改静态属性)
* params:[String:Any] 要修改的参数列表 (注意:修改静态属性时params中的key一定是存在的静态属性,否则会奔溃,因为无法映射静态属性列表判断有无该属性)
*/
self.bindEvent("changeVariables", handler: {[weak self] data , responseCallback in
if let dic = data as? [String:Any] {
if let name = dic["name"] as? String, let paramsDic = dic["params"] as? [String:Any], name.length > 0{
let (className , instanceName):(String?,String?) = (self?.getClassAndInstance(name: name) ?? (nil,nil))
guard let objcName = className ,objcName.length > 0 else{
return
}
guard let instanceClass:NSObject.Type = NSObject.fullClassName(objcName) else { return }
if let instanceKey = instanceName ,instanceKey.length > 0{ //单例赋值
if let instance:NSObject = instanceClass.value(forKey: instanceKey) as? NSObject {
SwiftReflectionTool.setParams(paramsDic, for: instance)
}
}else { //静态属性赋值
for (key,value) in paramsDic {
instanceClass.setValue(value, forKey: key)
}
}
}
}
})
}
open func bindEvent(_ eventName: String, handler: @escaping WVJBHandler) {
webViewBridge.registerHandler(eventName, handler: handler)
}
/** 计算进度条 */
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if ((object as AnyObject).isEqual(webView) && ((keyPath ?? "") == keyPathForProgress)) {
let newProgress = (change?[NSKeyValueChangeKey.newKey] as AnyObject).floatValue ?? 0
let oldProgress = (change?[NSKeyValueChangeKey.oldKey] as AnyObject).floatValue ?? 0
if newProgress < oldProgress {
return
}
if newProgress >= 1 {
Async.main({ [weak self] in
self?.progressView?.isHidden = true
self?.progressView?.setProgress(0, animated: false)
})
} else {
Async.main({ [weak self] in
self?.progressView?.isHidden = false
self?.progressView?.setProgress(newProgress, animated: true)
})
}
} else if ((object as AnyObject).isEqual(webView) && ((keyPath ?? "") == keyPathForTitle)) {
if isAutoUpdateTitle {
if (!isTitleFixed && (object as AnyObject).isEqual(webView)) {
self.title = self.webView.title;
}
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void){
//存储返回的cookie
if let response = navigationResponse.response as? HTTPURLResponse, let url = response.url{
let cookies = HTTPCookie.cookies(withResponseHeaderFields: (response.allHeaderFields as? [String : String]) ?? [:] , for: url)
for cookie in cookies {
// DDLogInfo("保存的ResponseCookie Name:\(cookie.name) value:\(cookie.value)")
HTTPCookieStorage.shared.setCookie(cookie)
}
}
decisionHandler(.allow)
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
var ret = true
let urlStr = navigationAction.request.url?.absoluteString.removingPercentEncoding
if shouldAllowRirectToUrlInView {
DDLogInfo("Web view direct to url: \(urlStr ?? "")")
ret = true
} else {
DDLogWarn("Web view direct to url forbidden: \(urlStr ?? "")")
ret = false
}
//1.0 判断是不是打开App Store
if urlStr?.hasPrefix("itms-appss://") == true || urlStr?.hasPrefix("itms-apps://") == true{
if let url = navigationAction.request.url {
UIApplication.shared.openURL(url)
ret = false
}
}else if urlStr?.hasPrefix("http") == false && urlStr?.hasPrefix("https") == false{ // 2.0 判断是不是打开其他app,例如支付宝
if let url = navigationAction.request.url {
UIApplication.shared.openURL(url)
ret = false
}
}
//2.0 Cookie
//获得cookie
var cookStr = ""
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
cookStr += "document.cookie = '\(cookie.name)=\(cookie.value);domain=\(cookie.domain);sessionOnly=\(cookie.isSessionOnly);path=\(cookie.path);isSecure=\(cookie.isSecure)';"
}
}
//设置cookie
if cookStr.length > 0 {
let sc = WKUserScript(source:cookStr, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
webView.configuration.userContentController.addUserScript(sc)
}
if (navigationAction.targetFrame == nil) { //新窗口打不开的bug
webView.load(navigationAction.request)
}
refreshNavigationBarTopLeftCloseButton()
decisionHandler(ret ? .allow : .cancel)
}
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if let header = self.webView.scrollView.mj_header {
header.endRefreshing()//结束下拉刷新
}
if disableUserSelect {
webView.evaluateJavaScript("document.documentElement.style.webkitUserSelect='none';") {_,_ in}
}
if disableLongTouch {
webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';") {_,_ in}
}
refreshNavigationBarTopLeftCloseButton()
url = webView.url?.absoluteString
if recordOffset {
if let offset = BaseKitWebViewController.webOffsets[url ?? ""] {
webView.scrollView.setContentOffset(CGPoint(x: 0, y: offset), animated: false)
}
}
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
let tip = error.localizedDescription
if ((error as NSError).code == URLError.cancelled.rawValue){
return
}
self.showTip(tip)
showBadNetworkView()
}
open func refreshNavigationBarTopLeftCloseButton() {
if showNavigationBarTopLeftCloseButton {
if webView.canGoBack {
if self.navigationItem.leftBarButtonItems != nil {
if let btnBack = navBtnBack() {
if let btnClose = navBtnClose() {
self.navigationItem.leftBarButtonItems = [btnBack, btnClose]
}
}
}
} else {
if let btnBack = navBtnBack() {
self.navigationItem.leftBarButtonItems = [btnBack]
}
}
}
}
open func refreshNavigationBarTopRightMoreButton() {
if showNavRightToolPannelItem {
if let btnMore : UIBarButtonItem = navBtnMore() {
self.navigationItem.rightBarButtonItem = btnMore
}
} else {
self.navigationItem.rightBarButtonItem = nil
}
}
open func navBtnBack() -> UIBarButtonItem? {
if let btnBack = self.navigationItem.leftBarButtonItems?.first {
return btnBack
}
return UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(BaseKitWebViewController.click_nav_back(_:)))
}
open func navBtnClose() -> UIBarButtonItem? {
return UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(BaseKitWebViewController.click_nav_close(_:)))
}
open func navBtnMore() -> UIBarButtonItem? {
return UIBarButtonItem(title: "•••", style: .plain, target: self, action: #selector(BaseKitWebViewController.click_nav_more(_:)))
}
open func getToolMoreHeaderView() -> UIView {
let labHeaderView : UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.w, height: 30))
labHeaderView.clipsToBounds = true
if let urlTitle = moreUrlTitle {
labHeaderView.font = UIFont.systemFont(ofSize: 10)
labHeaderView.text = "网页由 \(urlTitle) 提供"
labHeaderView.textColor = InnerConst.PannelTitleColor
labHeaderView.textAlignment = NSTextAlignment.center
} else {
labHeaderView.h = 0
}
return labHeaderView
}
open func getBackgroundLab() -> UIView {
let labBackground : UILabel = UILabel(frame: CGRect(x: 0, y: 10, width: self.screenW, height: 30))
labBackground.clipsToBounds = true
if let urlTitle = moreUrlTitle {
labBackground.font = UIFont.systemFont(ofSize: 10)
labBackground.text = "网页由 \(urlTitle) 提供"
labBackground.textColor = InnerConst.BackGroundTitleColor
labBackground.textAlignment = NSTextAlignment.center
} else {
labBackground.h = 0
}
return labBackground
}
@objc open func click_nav_back(_ sender: UIBarButtonItem) {
if webView.canGoBack {
webView.goBack()
} else {
self.routeBack()
}
}
@objc open func click_nav_close(_ sender: UIBarButtonItem) {
self.routeBack()
}
@objc open func click_nav_more(_ sender: UIBarButtonItem) {
webViewToolsPannelView = SharePannelView(frame: CGRect(x: 0, y: 0, width: self.view.w, height: self.view.h+64))
webViewToolsPannelView?.delegate = self
webViewToolsPannelView!.headerView = getToolMoreHeaderView()
webViewToolsPannelView!.toolsArray =
[[
ToolsModel(image: "pannel_icon_safari", highlightedImage: "pannel_icon_safari", title: "在Safari中\n打开", shareObjectType: .webPage, used: .openBySafari),
ToolsModel(image: "pannel_icon_link", highlightedImage: "pannel_icon_link", title: "复制链接",shareObjectType: .webPage, used: .copyLink),
ToolsModel(image: "pannel_icon_refresh", highlightedImage: "pannel_icon_refresh", title: "刷新",shareObjectType: .webPage, used: .webRefresh)]]
self.navigationController?.view.addSubview(webViewToolsPannelView!)
}
//MARK : - WebViewToolsPannelViewDelegate
func sharePannelViewButtonAction(_ webViewToolsPannelView: SharePannelView, model: ToolsModel) {
switch model.used {
case .openBySafari:
if #available(iOS 10.0, *) {
UIApplication.shared.open((webView.url)!, options: [:], completionHandler: nil)
}else{
UIApplication.shared.openURL((webView.url)!)
}
break
case .copyLink:
UIPasteboard.general.string = url
self.showTip("已复制链接到剪切版")
break
case .webRefresh:
if showRefreshHeader {
self.webView.scrollView.mj_header.beginRefreshing()
}else{
webView.reload()
}
break
default:
break
}
}
fileprivate func saveWebOffsetY (_ scrollView : UIScrollView){
if let key_url = url {
BaseKitWebViewController.webOffsets[key_url] = scrollView.contentOffset.y
}
}
//MARK : - ScrollViewDelegate
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.saveWebOffsetY(scrollView)
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.saveWebOffsetY(scrollView)
}
//MARK: - Priavte
//MARK:用.分割vcName和sbName
func getVcAndSbName(name:String) -> (String?,String?) {
let nameList = name.split(".")
var vcName:String?
var sbName:String?
if nameList.count >= 2 {
sbName = nameList.first
vcName = nameList[1]
}else if nameList.count == 1 {
vcName = nameList.first
sbName = nil
}
return (sbName,vcName)
}
//MARK:用.分割 类名和单例名
func getClassAndInstance(name:String) -> (String?,String?) {
let nameList = name.split(".")
var className:String?
var instanceName:String?
if nameList.count >= 2 {
className = nameList.first
instanceName = nameList[1]
}else if nameList.count == 1 {
className = nameList.first
}
return (className,instanceName)
}
//MARK: 给对象赋值 ,传过来的paramsDic是[String:kindOfStirng]
func setObjectParams(vc: NSObject, paramsDic:[String:Any]?) {
if let paramsDic = paramsDic {
for (key,value) in paramsDic {
let type = vc.getTypeOfProperty(key)
if type == NSNull.Type.self{ //未找到
print("VC没有该参数")
}else if type == Bool.self || type == Bool?.self{
let toValue = (value as? String)?.toBool() ?? false
vc.setValue(toValue, forKey: key)
}else if type == Int.self || type == Int?.self{
let toValue = (value as? String)?.toInt() ?? 0
vc.setValue(toValue, forKey: key)
}else if type == Double.self || type == Double?.self{
let toValue = (value as? String)?.toDouble() ?? 0.0
vc.setValue(toValue, forKey: key)
}else if type == Float.self || type == Float?.self{
let toValue = (value as? String)?.toFloat() ?? 0.0
vc.setValue(toValue, forKey: key)
}else {
vc.setValue(value, forKey: key)
}
}
}
}
deinit {
_webView?.removeObserver(self, forKeyPath: keyPathForProgress)
_webView?.removeObserver(self, forKeyPath: keyPathForTitle)
_webView?.scrollView.delegate = nil
}
}
| mit | b280a286667b56fb9b8340f1086770ec | 40.333835 | 342 | 0.570852 | 5.035171 | false | false | false | false |
limsangjin12/Hero | Sources/Extensions/UIKit+Hero.swift | 4 | 2130 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
fileprivate let parameterRegex = "(?:\\-?\\d+(\\.?\\d+)?)|\\w+"
fileprivate let modifiersRegex = "(\\w+)(?:\\(([^\\)]*)\\))?"
internal extension NSObject {
func copyWithArchiver() -> Any? {
return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))!
}
}
internal extension UIImage {
class func imageWithView(view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
internal extension UIColor {
var components:(r:CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
}
var alphaComponent: CGFloat {
return components.a
}
}
| mit | 76744728afa6623959b6170e65653e6d | 37.035714 | 103 | 0.716901 | 4.243028 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Editor/ProfileEditorHeaderView.swift | 1 | 22156 | //
// ProfileEditorHeaderView.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
import ProfilePayloads
class ProfileEditorHeaderView: NSObject {
// MARK: -
// MARK: Variables
weak var profile: Profile?
let headerView = NSView()
let textFieldTitle = NSTextField()
let textFieldTitleTopIndent: CGFloat = 28.0
let textFieldDescription = NSTextField()
let textFieldDescriptionTopIndent: CGFloat = 4.0
let textFieldPlatforms = NSTextField()
let textFieldScope = NSTextField()
let popUpButtonAppVersion = NSPopUpButton()
let imageViewIcon = NSImageView()
let buttonAddRemove = NSButton()
let buttonTitleEnable = NSLocalizedString("Add", comment: "")
let buttonTitleDisable = NSLocalizedString("Remove", comment: "")
var height: CGFloat = 0.0
var layoutConstraintHeight: NSLayoutConstraint?
weak var selectedPayloadPlaceholder: PayloadPlaceholder?
weak var profileEditor: ProfileEditor?
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(profile: Profile) {
super.init()
// ---------------------------------------------------------------------
// Setup Variables
// ---------------------------------------------------------------------
self.profile = profile
var constraints = [NSLayoutConstraint]()
// ---------------------------------------------------------------------
// Setup Notification Observers
// ---------------------------------------------------------------------
NotificationCenter.default.addObserver(self, selector: #selector(self.didChangePayloadSelected(_:)), name: .didChangePayloadSelected, object: nil)
// ---------------------------------------------------------------------
// Add subviews to headerView
// ---------------------------------------------------------------------
self.setupHeaderView(constraints: &constraints)
self.setupTextFieldTitle(constraints: &constraints)
self.setupTextFieldDescription(constraints: &constraints)
self.setupTextFieldPlatforms(constraints: &constraints)
self.setupTextFieldScope(constraints: &constraints)
self.setupPopUpButtonAppVersion(constraints: &constraints)
self.setupButtonAddRemove(constraints: &constraints)
// ---------------------------------------------------------------------
// Activate layout constraints
// ---------------------------------------------------------------------
NSLayoutConstraint.activate(constraints)
}
// MARK: -
// MARK: Private Functions
private func updateHeight(_ height: CGFloat) {
self.height += height
}
// MARK: -
// MARK: Functions
@objc func didChangePayloadSelected(_ notification: NSNotification?) {
guard
let userInfo = notification?.userInfo,
let payloadPlaceholder = userInfo[NotificationKey.payloadPlaceholder] as? PayloadPlaceholder,
let selected = userInfo[NotificationKey.payloadSelected] as? Bool else { return }
if self.selectedPayloadPlaceholder == payloadPlaceholder {
self.setButtonState(enabled: selected)
}
}
func setButtonState(enabled: Bool) {
if enabled {
self.buttonAddRemove.attributedTitle = NSAttributedString(string: self.buttonTitleDisable, attributes: [ .foregroundColor: NSColor.systemRed ])
} else {
self.buttonAddRemove.title = self.buttonTitleEnable // attributedTitle = NSAttributedString(string: "Add", attributes: [ NSAttributedStringKey.foregroundColor : NSColor.green ])
}
}
@objc func clicked(button: NSButton) {
if let selectedPayloadPlaceholder = self.selectedPayloadPlaceholder {
NotificationCenter.default.post(name: .changePayloadSelected, object: self, userInfo: [NotificationKey.payloadPlaceholder: selectedPayloadPlaceholder ])
}
}
@objc func toggleTitle(sender: NSGestureRecognizer) {
if let toolTip = self.textFieldTitle.toolTip {
self.textFieldTitle.toolTip = self.textFieldTitle.stringValue
self.textFieldTitle.stringValue = toolTip
}
}
func select(payloadPlaceholder: PayloadPlaceholder) {
if self.selectedPayloadPlaceholder != payloadPlaceholder {
self.selectedPayloadPlaceholder = payloadPlaceholder
// Hide button if it's the general settings
if payloadPlaceholder.payloadType == .custom || ( payloadPlaceholder.domain == kManifestDomainConfiguration && payloadPlaceholder.payloadType == .manifestsApple ) {
self.buttonAddRemove.isHidden = true
} else if let profile = self.profile {
self.buttonAddRemove.isHidden = false
self.setButtonState(enabled: profile.settings.isIncludedInProfile(payload: payloadPlaceholder.payload))
} else {
self.buttonAddRemove.isHidden = true
}
self.textFieldTitle.stringValue = payloadPlaceholder.title
if payloadPlaceholder.domain != kManifestDomainConfiguration {
self.textFieldTitle.toolTip = payloadPlaceholder.domain
} else { self.textFieldTitle.toolTip = nil }
self.textFieldDescription.stringValue = payloadPlaceholder.description
self.popUpButtonAppVersion.removeAllItems()
if payloadPlaceholder.payloadType == .managedPreferencesApplications, let payload = payloadPlaceholder.payload as? PayloadManagedPreference {
if let appVersions = payload.appVersions {
self.popUpButtonAppVersion.addItems(withTitles: appVersions)
}
}
self.textFieldPlatforms.stringValue = PayloadUtility.string(fromPlatforms: payloadPlaceholder.payload.platforms, separator: " ")
self.textFieldScope.stringValue = PayloadUtility.string(fromTargets: payloadPlaceholder.payload.targets, separator: " ")
}
}
}
// MARK: -
// MARK: Setup NSLayoutConstraints
extension ProfileEditorHeaderView {
private func setupHeaderView(constraints: inout [NSLayoutConstraint]) {
self.headerView.translatesAutoresizingMaskIntoConstraints = false
}
private func setupButtonAddRemove(constraints: inout [NSLayoutConstraint]) {
self.buttonAddRemove.translatesAutoresizingMaskIntoConstraints = false
self.buttonAddRemove.title = self.buttonTitleEnable
self.buttonAddRemove.bezelStyle = .roundRect
self.buttonAddRemove.setButtonType(.momentaryPushIn)
self.buttonAddRemove.isBordered = true
self.buttonAddRemove.isTransparent = false
self.buttonAddRemove.action = #selector(self.clicked(button:))
self.buttonAddRemove.target = self
// ---------------------------------------------------------------------
// Add Button to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.buttonAddRemove)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.buttonAddRemove,
attribute: .top,
relatedBy: .equal,
toItem: self.headerView,
attribute: .top,
multiplier: 1.0,
constant: self.textFieldTitleTopIndent))
// Trailing
constraints.append(NSLayoutConstraint(item: self.headerView,
attribute: .trailing,
relatedBy: .equal,
toItem: self.buttonAddRemove,
attribute: .trailing,
multiplier: 1.0,
constant: 24.0))
}
private func setupTextFieldPlatforms(constraints: inout [NSLayoutConstraint]) {
self.textFieldPlatforms.translatesAutoresizingMaskIntoConstraints = false
self.textFieldPlatforms.lineBreakMode = .byWordWrapping
self.textFieldPlatforms.isBordered = false
self.textFieldPlatforms.isBezeled = false
self.textFieldPlatforms.drawsBackground = false
self.textFieldPlatforms.isEditable = false
self.textFieldPlatforms.isSelectable = false
self.textFieldPlatforms.textColor = .secondaryLabelColor
self.textFieldPlatforms.preferredMaxLayoutWidth = kEditorTableViewColumnPayloadWidth
self.textFieldPlatforms.alignment = .right
self.textFieldPlatforms.font = NSFont.systemFont(ofSize: 12, weight: .regular)
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.textFieldPlatforms)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.textFieldPlatforms,
attribute: .top,
relatedBy: .equal,
toItem: self.buttonAddRemove,
attribute: .bottom,
multiplier: 1.0,
constant: 6.0))
// Width
constraints.append(NSLayoutConstraint(item: self.textFieldPlatforms,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 97.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.headerView,
attribute: .trailing,
relatedBy: .equal,
toItem: self.textFieldPlatforms,
attribute: .trailing,
multiplier: 1.0,
constant: 24.0))
}
private func setupTextFieldScope(constraints: inout [NSLayoutConstraint]) {
self.textFieldScope.translatesAutoresizingMaskIntoConstraints = false
self.textFieldScope.lineBreakMode = .byWordWrapping
self.textFieldScope.isBordered = false
self.textFieldScope.isBezeled = false
self.textFieldScope.drawsBackground = false
self.textFieldScope.isEditable = false
self.textFieldScope.isSelectable = false
self.textFieldScope.textColor = .secondaryLabelColor
self.textFieldScope.preferredMaxLayoutWidth = kEditorTableViewColumnPayloadWidth
self.textFieldScope.alignment = .right
self.textFieldScope.font = NSFont.systemFont(ofSize: 12, weight: .regular)
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.textFieldScope)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.textFieldScope,
attribute: .top,
relatedBy: .equal,
toItem: self.textFieldPlatforms,
attribute: .bottom,
multiplier: 1.0,
constant: 1.0))
// Width
constraints.append(NSLayoutConstraint(item: self.textFieldScope,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 76.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.headerView,
attribute: .trailing,
relatedBy: .equal,
toItem: self.textFieldScope,
attribute: .trailing,
multiplier: 1.0,
constant: 24.0))
}
private func setupTextFieldTitle(constraints: inout [NSLayoutConstraint]) {
self.textFieldTitle.translatesAutoresizingMaskIntoConstraints = false
self.textFieldTitle.lineBreakMode = .byWordWrapping
self.textFieldTitle.isBordered = false
self.textFieldTitle.isBezeled = false
self.textFieldTitle.drawsBackground = false
self.textFieldTitle.isEditable = false
self.textFieldTitle.isSelectable = false
self.textFieldTitle.textColor = .labelColor
self.textFieldTitle.alignment = .left
self.textFieldTitle.stringValue = "Title"
self.textFieldTitle.font = NSFont.systemFont(ofSize: 28, weight: .heavy)
self.textFieldTitle.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
// ---------------------------------------------------------------------
// Setup GestureRecognizer
// ---------------------------------------------------------------------
let gesture = NSClickGestureRecognizer()
gesture.numberOfClicksRequired = 1
gesture.target = self
gesture.action = #selector(self.toggleTitle(sender:))
self.textFieldTitle.addGestureRecognizer(gesture)
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.textFieldTitle)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.textFieldTitle,
attribute: .top,
relatedBy: .equal,
toItem: self.headerView,
attribute: .top,
multiplier: 1.0,
constant: self.textFieldTitleTopIndent))
// Leading
constraints.append(NSLayoutConstraint(item: self.textFieldTitle,
attribute: .leading,
relatedBy: .equal,
toItem: self.headerView,
attribute: .leading,
multiplier: 1.0,
constant: 24.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.textFieldPlatforms,
attribute: .leading,
relatedBy: .equal,
toItem: self.textFieldTitle,
attribute: .trailing,
multiplier: 1.0,
constant: 4.0))
}
private func setupPopUpButtonAppVersion(constraints: inout [NSLayoutConstraint]) {
self.popUpButtonAppVersion.translatesAutoresizingMaskIntoConstraints = false
self.popUpButtonAppVersion.isHidden = true
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.popUpButtonAppVersion)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.popUpButtonAppVersion,
attribute: .centerY,
relatedBy: .equal,
toItem: self.textFieldScope,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.popUpButtonAppVersion,
attribute: .trailing,
relatedBy: .equal,
toItem: self.textFieldScope,
attribute: .leading,
multiplier: 1.0,
constant: 4.0))
}
private func setupTextFieldDescription(constraints: inout [NSLayoutConstraint]) {
self.textFieldDescription.translatesAutoresizingMaskIntoConstraints = false
self.textFieldDescription.lineBreakMode = .byWordWrapping
self.textFieldDescription.isBordered = false
self.textFieldDescription.isBezeled = false
self.textFieldDescription.drawsBackground = false
self.textFieldDescription.isEditable = false
self.textFieldDescription.isSelectable = false
self.textFieldDescription.textColor = .labelColor
self.textFieldDescription.alignment = .left
self.textFieldDescription.stringValue = "Description"
self.textFieldDescription.font = NSFont.systemFont(ofSize: 17, weight: .ultraLight)
self.textFieldDescription.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
self.headerView.addSubview(self.textFieldDescription)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Top
constraints.append(NSLayoutConstraint(item: self.textFieldDescription,
attribute: .top,
relatedBy: .equal,
toItem: self.textFieldTitle,
attribute: .bottom,
multiplier: 1.0,
constant: self.textFieldDescriptionTopIndent))
// Leading
constraints.append(NSLayoutConstraint(item: self.textFieldDescription,
attribute: .leading,
relatedBy: .equal,
toItem: self.headerView,
attribute: .leading,
multiplier: 1.0,
constant: 24.0))
// Trailing
constraints.append(NSLayoutConstraint(item: self.textFieldPlatforms,
attribute: .leading,
relatedBy: .equal,
toItem: self.textFieldDescription,
attribute: .trailing,
multiplier: 1.0,
constant: 4.0))
// Bottom
constraints.append(NSLayoutConstraint(item: self.headerView,
attribute: .bottom,
relatedBy: .equal,
toItem: self.textFieldDescription,
attribute: .bottom,
multiplier: 1.0,
constant: 12.0))
//self.updateHeight(description.intrinsicContentSize.height)
}
}
| mit | cccd64f1df2f1ab836129a88dfc55292 | 48.233333 | 189 | 0.47425 | 7.538278 | false | false | false | false |
TonyStark106/NiceKit | Example/Pods/Siren/Sources/Siren.swift | 1 | 24326 | //
// Siren.swift
// Siren
//
// Created by Arthur Sabintsev on 1/3/15.
// Copyright (c) 2015 Sabintsev iOS Projects. All rights reserved.
//
import UIKit
// MARK: - Siren
/// The Siren Class. A singleton that is initialized using the shared() method.
public final class Siren: NSObject {
/// Current installed version of your app.
internal var currentInstalledVersion: String? = {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}()
/// The error domain for all errors created by Siren.
public let SirenErrorDomain = "Siren Error Domain"
/// The SirenDelegate variable, which should be set if you'd like to be notified:
///
/// When a user views or interacts with the alert
/// - sirenDidShowUpdateDialog(alertType: AlertType)
/// - sirenUserDidLaunchAppStore()
/// - sirenUserDidSkipVersion()
/// - sirenUserDidCancel()
///
/// When a new version has been detected, and you would like to present a localized message in a custom UI. use this delegate method:
/// - sirenDidDetectNewVersionWithoutAlert(message: String)
public weak var delegate: SirenDelegate?
/// The debug flag, which is disabled by default.
/// When enabled, a stream of println() statements are logged to your console when a version check is performed.
public lazy var debugEnabled = false
/// Determines the type of alert that should be shown.
/// See the Siren.AlertType enum for full details.
public var alertType = AlertType.option {
didSet {
majorUpdateAlertType = alertType
minorUpdateAlertType = alertType
patchUpdateAlertType = alertType
revisionUpdateAlertType = alertType
}
}
/// Determines the type of alert that should be shown for major version updates: A.b.c
/// Defaults to Siren.AlertType.option.
/// See the Siren.AlertType enum for full details.
public lazy var majorUpdateAlertType = AlertType.option
/// Determines the type of alert that should be shown for minor version updates: a.B.c
/// Defaults to Siren.AlertType.option.
/// See the Siren.AlertType enum for full details.
public lazy var minorUpdateAlertType = AlertType.option
/// Determines the type of alert that should be shown for minor patch updates: a.b.C
/// Defaults to Siren.AlertType.option.
/// See the Siren.AlertType enum for full details.
public lazy var patchUpdateAlertType = AlertType.option
/// Determines the type of alert that should be shown for revision updates: a.b.c.D
/// Defaults to Siren.AlertType.option.
/// See the Siren.AlertType enum for full details.
public lazy var revisionUpdateAlertType = AlertType.option
/// The name of your app.
/// By default, it's set to the name of the app that's stored in your plist.
public lazy var appName: String = Bundle.main.bestMatchingAppName()
/// The region or country of an App Store in which your app is available.
/// By default, all version checks are performed against the US App Store.
/// If your app is not available in the US App Store, set it to the identifier of at least one App Store within which it is available.
public var countryCode: String?
/// Overrides the default localization of a user's device when presenting the update message and button titles in the alert.
/// See the Siren.LanguageType enum for more details.
public var forceLanguageLocalization: Siren.LanguageType?
/// Overrides the tint color for UIAlertController.
public var alertControllerTintColor: UIColor?
/// When this is set, the alert will only show up if the current version has already been released for X days
/// Defaults to 1 day to avoid an issue where Apple updates the JSON faster than the app binary propogates to the App Store.
public var showAlertAfterCurrentVersionHasBeenReleasedForDays: Int = 1
/// The current version of your app that is available for download on the App Store
public internal(set) var currentAppStoreVersion: String?
internal var updaterWindow: UIWindow?
fileprivate var appID: Int?
fileprivate var lastVersionCheckPerformedOnDate: Date?
fileprivate lazy var alertViewIsVisible: Bool = false
/// The App's Singleton
public static let shared = Siren()
@available(*, deprecated: 1.2.0, unavailable, renamed: "shared")
public static let sharedInstance = Siren()
override init() {
lastVersionCheckPerformedOnDate = UserDefaults.standard.object(forKey: SirenDefaults.StoredVersionCheckDate.rawValue) as? Date
}
/// Checks the currently installed version of your app against the App Store.
/// The default check is against the US App Store, but if your app is not listed in the US,
/// you should set the `countryCode` property before calling this method. Please refer to the countryCode property for more information.
///
/// - Parameters:
/// - checkType: The frequency in days in which you want a check to be performed. Please refer to the Siren.VersionCheckType enum for more details.
public func checkVersion(checkType: VersionCheckType) {
guard let _ = Bundle.bundleID() else {
printMessage(message: "Please make sure that you have set a `Bundle Identifier` in your project.")
return
}
if checkType == .immediately {
performVersionCheck()
} else {
guard let lastVersionCheckPerformedOnDate = lastVersionCheckPerformedOnDate else {
performVersionCheck()
return
}
if Date.days(since: lastVersionCheckPerformedOnDate) >= checkType.rawValue {
performVersionCheck()
} else {
postError(.recentlyCheckedAlready, underlyingError: nil)
}
}
}
}
// MARK: - Helpers (Networking)
private extension Siren {
func performVersionCheck() {
do {
let url = try iTunesURLFromString()
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 30)
URLSession.shared.dataTask(with: request, completionHandler: { [unowned self] (data, response, error) in
self.processResults(withData: data, response: response, error: error)
}).resume()
} catch let error as NSError {
postError(.malformedURL, underlyingError: error)
}
}
func processResults(withData data: Data?, response: URLResponse?, error: Error?) {
if let error = error {
postError(.appStoreDataRetrievalFailure, underlyingError: error)
} else {
guard let data = data else {
postError(.appStoreDataRetrievalFailure, underlyingError: nil)
return
}
do {
let jsonData = try JSONSerialization.jsonObject(with: data, options: [])
guard let appData = jsonData as? [String: Any],
isUpdateCompatibleWithDeviceOS(appData: appData) else {
postError(.appStoreJSONParsingFailure, underlyingError: nil)
return
}
DispatchQueue.main.async { [unowned self] in
// Print iTunesLookup results from appData
self.printMessage(message: "JSON results: \(appData)")
// Process Results (e.g., extract current version that is available on the AppStore)
self.processVersionCheck(with: appData)
}
} catch let error as NSError {
postError(.appStoreDataRetrievalFailure, underlyingError: error)
}
}
}
func processVersionCheck(with payload: [String: Any]) {
storeVersionCheckDate() // Store version comparison date
guard let results = payload[JSONKeys.results] as? [[String: Any]] else {
postError(.appStoreVersionNumberFailure, underlyingError: nil)
return
}
/// Condition satisfied when app not in App Store
guard !results.isEmpty else {
postError(.appStoreDataRetrievalFailure, underlyingError: nil)
return
}
guard let info = results.first else {
postError(.appStoreDataRetrievalFailure, underlyingError: nil)
return
}
guard let appID = info[JSONKeys.appID] as? Int else {
postError(.appStoreAppIDFailure, underlyingError: nil)
return
}
self.appID = appID
guard let currentAppStoreVersion = info[JSONKeys.version] as? String else {
postError(.appStoreVersionArrayFailure, underlyingError: nil)
return
}
self.currentAppStoreVersion = currentAppStoreVersion
guard isAppStoreVersionNewer() else {
delegate?.sirenLatestVersionInstalled()
postError(.noUpdateAvailable, underlyingError: nil)
return
}
guard let currentVersionReleaseDate = info[JSONKeys.currentVersionReleaseDate] as? String,
let daysSinceRelease = Date.days(since: currentVersionReleaseDate) else {
return
}
guard daysSinceRelease >= showAlertAfterCurrentVersionHasBeenReleasedForDays else {
let message = "Your app has been released for \(daysSinceRelease) days, but Siren cannot prompt the user until \(showAlertAfterCurrentVersionHasBeenReleasedForDays) days have passed."
self.printMessage(message: message)
return
}
showAlertIfCurrentAppStoreVersionNotSkipped()
}
func iTunesURLFromString() throws -> URL {
var components = URLComponents()
components.scheme = "https"
components.host = "itunes.apple.com"
components.path = "/lookup"
var items: [URLQueryItem] = [URLQueryItem(name: "bundleId", value: Bundle.bundleID())]
if let countryCode = countryCode {
let item = URLQueryItem(name: "country", value: countryCode)
items.append(item)
}
components.queryItems = items
guard let url = components.url, !url.absoluteString.isEmpty else {
throw SirenError.malformedURL
}
return url
}
}
// MARK: - Helpers (Alert)
private extension Siren {
func showAlertIfCurrentAppStoreVersionNotSkipped() {
alertType = setAlertType()
guard let previouslySkippedVersion = UserDefaults.standard.object(forKey: SirenDefaults.StoredSkippedVersion.rawValue) as? String else {
showAlert()
return
}
if let currentAppStoreVersion = currentAppStoreVersion, currentAppStoreVersion != previouslySkippedVersion {
showAlert()
}
}
func showAlert() {
let updateAvailableMessage = Bundle().localizedString(stringKey: "Update Available", forceLanguageLocalization: forceLanguageLocalization)
let newVersionMessage = localizedNewVersionMessage()
let alertController = UIAlertController(title: updateAvailableMessage, message: newVersionMessage, preferredStyle: .alert)
if let alertControllerTintColor = alertControllerTintColor {
alertController.view.tintColor = alertControllerTintColor
}
switch alertType {
case .force:
alertController.addAction(updateAlertAction())
case .option:
alertController.addAction(nextTimeAlertAction())
alertController.addAction(updateAlertAction())
case .skip:
alertController.addAction(nextTimeAlertAction())
alertController.addAction(updateAlertAction())
alertController.addAction(skipAlertAction())
case .none:
delegate?.sirenDidDetectNewVersionWithoutAlert(message: newVersionMessage)
}
if alertType != .none && !alertViewIsVisible {
alertController.show()
alertViewIsVisible = true
delegate?.sirenDidShowUpdateDialog(alertType: alertType)
}
}
func updateAlertAction() -> UIAlertAction {
let title = localizedUpdateButtonTitle()
let action = UIAlertAction(title: title, style: .default) { [unowned self] _ in
self.hideWindow()
self.launchAppStore()
self.delegate?.sirenUserDidLaunchAppStore()
self.alertViewIsVisible = false
return
}
return action
}
func nextTimeAlertAction() -> UIAlertAction {
let title = localizedNextTimeButtonTitle()
let action = UIAlertAction(title: title, style: .default) { [unowned self] _ in
self.hideWindow()
self.delegate?.sirenUserDidCancel()
self.alertViewIsVisible = false
return
}
return action
}
func skipAlertAction() -> UIAlertAction {
let title = localizedSkipButtonTitle()
let action = UIAlertAction(title: title, style: .default) { [unowned self] _ in
if let currentAppStoreVersion = self.currentAppStoreVersion {
UserDefaults.standard.set(currentAppStoreVersion, forKey: SirenDefaults.StoredSkippedVersion.rawValue)
UserDefaults.standard.synchronize()
}
self.hideWindow()
self.delegate?.sirenUserDidSkipVersion()
self.alertViewIsVisible = false
return
}
return action
}
func setAlertType() -> Siren.AlertType {
guard let currentInstalledVersion = currentInstalledVersion,
let currentAppStoreVersion = currentAppStoreVersion else {
return .option
}
let oldVersion = (currentInstalledVersion).characters.split {$0 == "."}.map { String($0) }.map {Int($0) ?? 0}
let newVersion = (currentAppStoreVersion).characters.split {$0 == "."}.map { String($0) }.map {Int($0) ?? 0}
guard let newVersionFirst = newVersion.first, let oldVersionFirst = oldVersion.first else {
return alertType // Default value is .Option
}
if newVersionFirst > oldVersionFirst { // A.b.c.d
alertType = majorUpdateAlertType
} else if newVersion.count > 1 && (oldVersion.count <= 1 || newVersion[1] > oldVersion[1]) { // a.B.c.d
alertType = minorUpdateAlertType
} else if newVersion.count > 2 && (oldVersion.count <= 2 || newVersion[2] > oldVersion[2]) { // a.b.C.d
alertType = patchUpdateAlertType
} else if newVersion.count > 3 && (oldVersion.count <= 3 || newVersion[3] > oldVersion[3]) { // a.b.c.D
alertType = revisionUpdateAlertType
}
return alertType
}
}
// MARK: - Helpers (Localization)
private extension Siren {
func localizedNewVersionMessage() -> String {
let newVersionMessageToLocalize = "A new version of %@ is available. Please update to version %@ now."
let newVersionMessage = Bundle().localizedString(stringKey: newVersionMessageToLocalize, forceLanguageLocalization: forceLanguageLocalization)
guard let currentAppStoreVersion = currentAppStoreVersion else {
return String(format: newVersionMessage, appName, "Unknown")
}
return String(format: newVersionMessage, appName, currentAppStoreVersion)
}
func localizedUpdateButtonTitle() -> String {
return Bundle().localizedString(stringKey: "Update", forceLanguageLocalization: forceLanguageLocalization)
}
func localizedNextTimeButtonTitle() -> String {
return Bundle().localizedString(stringKey: "Next time", forceLanguageLocalization: forceLanguageLocalization)
}
func localizedSkipButtonTitle() -> String {
return Bundle().localizedString(stringKey: "Skip this version", forceLanguageLocalization: forceLanguageLocalization)
}
}
// MARK: - Helpers (Version)
extension Siren {
func isAppStoreVersionNewer() -> Bool {
var newVersionExists = false
if let currentInstalledVersion = currentInstalledVersion,
let currentAppStoreVersion = currentAppStoreVersion,
(currentInstalledVersion.compare(currentAppStoreVersion, options: .numeric) == .orderedAscending) {
newVersionExists = true
}
return newVersionExists
}
fileprivate func storeVersionCheckDate() {
lastVersionCheckPerformedOnDate = Date()
if let lastVersionCheckPerformedOnDate = lastVersionCheckPerformedOnDate {
UserDefaults.standard.set(lastVersionCheckPerformedOnDate, forKey: SirenDefaults.StoredVersionCheckDate.rawValue)
UserDefaults.standard.synchronize()
}
}
}
// MARK: - Helpers (Misc.)
private extension Siren {
func isUpdateCompatibleWithDeviceOS(appData: [String: Any]) -> Bool {
guard let results = appData[JSONKeys.results] as? [[String: Any]],
let info = results.first,
let requiredOSVersion = info[JSONKeys.minimumOSVersion] as? String else {
postError(.appStoreOSVersionNumberFailure, underlyingError: nil)
return false
}
let systemVersion = UIDevice.current.systemVersion
guard systemVersion.compare(requiredOSVersion, options: .numeric) == .orderedDescending ||
systemVersion.compare(requiredOSVersion, options: .numeric) == .orderedSame else {
postError(.appStoreOSVersionUnsupported, underlyingError: nil)
return false
}
return true
}
func hideWindow() {
if let updaterWindow = updaterWindow {
updaterWindow.isHidden = true
self.updaterWindow = nil
}
}
func launchAppStore() {
guard let appID = appID,
let iTunesURL = URL(string: "https://itunes.apple.com/app/id\(appID)") else {
return
}
DispatchQueue.main.async {
UIApplication.shared.openURL(iTunesURL)
}
}
func printMessage(message: String) {
if debugEnabled {
print("[Siren] \(message)")
}
}
}
// MARK: - Enumerated Types (Public)
public extension Siren {
/// Determines the type of alert to present after a successful version check has been performed.
enum AlertType {
/// Forces user to update your app (1 button alert).
case force
/// (DEFAULT) Presents user with option to update app now or at next launch (2 button alert).
case option
/// Presents user with option to update the app now, at next launch, or to skip this version all together (3 button alert).
case skip
/// Doesn't show the alert, but instead returns a localized message
/// for use in a custom UI within the sirenDidDetectNewVersionWithoutAlert() delegate method.
case none
}
/// Determines the frequency in which the the version check is performed and the user is prompted to update the app.
///
enum VersionCheckType: Int {
/// Version check performed every time the app is launched.
case immediately = 0
/// Version check performed once a day.
case daily = 1
/// Version check performed once a week.
case weekly = 7
}
/// Determines the available languages in which the update message and alert button titles should appear.
///
/// By default, the operating system's default lanuage setting is used. However, you can force a specific language
/// by setting the forceLanguageLocalization property before calling checkVersion()
enum LanguageType: String {
case Arabic = "ar"
case Armenian = "hy"
case Basque = "eu"
case ChineseSimplified = "zh-Hans"
case ChineseTraditional = "zh-Hant"
case Croatian = "hr"
case Danish = "da"
case Dutch = "nl"
case English = "en"
case Estonian = "et"
case Finnish = "fi"
case French = "fr"
case German = "de"
case Greek = "el"
case Hebrew = "he"
case Hungarian = "hu"
case Indonesian = "id"
case Italian = "it"
case Japanese = "ja"
case Korean = "ko"
case Latvian = "lv"
case Lithuanian = "lt"
case Malay = "ms"
case Norwegian = "nb-NO"
case Polish = "pl"
case PortugueseBrazil = "pt"
case PortuguesePortugal = "pt-PT"
case Russian = "ru"
case SerbianCyrillic = "sr-Cyrl"
case SerbianLatin = "sr-Latn"
case Slovenian = "sl"
case Spanish = "es"
case Swedish = "sv"
case Thai = "th"
case Turkish = "tr"
case Vietnamese = "vi"
}
}
// MARK: - Enumerated Types (Private)
private extension Siren {
/// Siren-specific Error Codes
enum ErrorCode: Int {
case malformedURL = 1000
case recentlyCheckedAlready
case noUpdateAvailable
case appStoreDataRetrievalFailure
case appStoreJSONParsingFailure
case appStoreOSVersionNumberFailure
case appStoreOSVersionUnsupported
case appStoreVersionNumberFailure
case appStoreVersionArrayFailure
case appStoreAppIDFailure
case appStoreReleaseDateFailure
}
/// Siren-specific Throwable Errors
enum SirenError: Error {
case malformedURL
case missingBundleIdOrAppId
}
/// Siren-specific UserDefaults Keys
enum SirenDefaults: String {
/// Key that stores the timestamp of the last version check in UserDefaults
case StoredVersionCheckDate
/// Key that stores the version that a user decided to skip in UserDefaults.
case StoredSkippedVersion
}
struct JSONKeys {
static let appID = "trackId"
static let currentVersionReleaseDate = "currentVersionReleaseDate"
static let minimumOSVersion = "minimumOsVersion"
static let results = "results"
static let version = "version"
}
}
// MARK: - Error Handling
private extension Siren {
func postError(_ code: ErrorCode, underlyingError: Error?) {
let description: String
switch code {
case .malformedURL:
description = "The iTunes URL is malformed. Please leave an issue on http://github.com/ArtSabintsev/Siren with as many details as possible."
case .recentlyCheckedAlready:
description = "Not checking the version, because it already checked recently."
case .noUpdateAvailable:
description = "No new update available."
case .appStoreDataRetrievalFailure:
description = "Error retrieving App Store data as an error was returned."
case .appStoreJSONParsingFailure:
description = "Error parsing App Store JSON data."
case .appStoreOSVersionNumberFailure:
description = "Error retrieving iOS version number as there was no data returned."
case .appStoreOSVersionUnsupported:
description = "The version of iOS on the device is lower than that of the one required by the app verison update."
case .appStoreVersionNumberFailure:
description = "Error retrieving App Store version number as there was no data returned."
case .appStoreVersionArrayFailure:
description = "Error retrieving App Store verson number as the JSON does not contain a 'version' key."
case .appStoreAppIDFailure:
description = "Error retrieving trackId as the JSON does not contain a 'trackId' key."
case .appStoreReleaseDateFailure:
description = "Error retrieving trackId as the JSON does not contain a 'currentVersionReleaseDate' key."
}
var userInfo: [String: Any] = [NSLocalizedDescriptionKey: description]
if let underlyingError = underlyingError {
userInfo[NSUnderlyingErrorKey] = underlyingError
}
let error = NSError(domain: SirenErrorDomain, code: code.rawValue, userInfo: userInfo)
delegate?.sirenDidFailVersionCheck(error: error)
printMessage(message: error.localizedDescription)
}
}
| mit | 8bd3e53e72142d96f3268900bde29619 | 37.068858 | 195 | 0.653334 | 5.405778 | false | false | false | false |
hooman/swift | test/decl/typealias/fully_constrained.swift | 13 | 1809 | // RUN: %target-typecheck-verify-swift
struct OtherGeneric<U> {}
struct Generic<T> {
// FIXME: Should work with 'T' as well
typealias NonGeneric = Int where T == Int
typealias Unbound = OtherGeneric where T == Int
typealias Generic = OtherGeneric where T == Int
}
extension Generic where T == Int {
// FIXME: Should work with 'T' as well
typealias NonGenericInExtension = Int
typealias UnboundInExtension = OtherGeneric
typealias GenericInExtension = OtherGeneric
}
func use(_: Generic.NonGeneric,
_: Generic.Unbound<String>,
_: Generic.Generic<String>,
_: Generic.NonGenericInExtension,
_: Generic.UnboundInExtension<String>,
_: Generic.GenericInExtension<String>) {
// FIXME: Get these working too
#if false
let _ = Generic.NonGeneric.self
let _ = Generic.Unbound<String>.self
let _ = Generic.Generic<String>.self
let _ = Generic.NonGenericInExtension.self
let _ = Generic.UnboundInExtension<String>.self
let _ = Generic.GenericInExtension<String>.self
let _: Generic.NonGeneric = 123
let _: Generic.NonGenericInExtension = 123
#endif
let _: Generic.Unbound = OtherGeneric<String>()
let _: Generic.Generic = OtherGeneric<String>()
let _: Generic.UnboundInExtension = OtherGeneric<String>()
let _: Generic.GenericInExtension = OtherGeneric<String>()
}
struct Use {
let a1: Generic.NonGeneric
let b1: Generic.Unbound<String>
let c1: Generic.Generic<String>
let a2: Generic.NonGenericInExtension
let b2: Generic.UnboundInExtension<String>
let c2: Generic.GenericInExtension<String>
}
extension Generic.NonGeneric {}
extension Generic.Unbound {}
extension Generic.Generic {}
extension Generic.NonGenericInExtension {}
extension Generic.UnboundInExtension {}
extension Generic.GenericInExtension {}
| apache-2.0 | d19bb7f5c604d8d6b051c5ed5a4ca0d5 | 27.265625 | 60 | 0.726921 | 4.380145 | false | false | false | false |
andreacipriani/tableview-headerview | TestTableViewHeader/ViewController.swift | 1 | 2897 | import UIKit
class ViewController: UIViewController {
// MARK: - Outlets
@IBOutlet fileprivate weak var tableView: UITableView!
// MARK: - Private properties
fileprivate let customCellIdentifier = "CustomCell"
private let tableViewHeaderInitialFrame = CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 200))
private let tableViewHeaderUpdatedFrame = CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 500))
fileprivate let headerView: CustomTableViewHeader = UINib(nibName: "CustomTableViewHeader", bundle: nil).instantiate(withOwner: self, options: nil).first! as! CustomTableViewHeader
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupTableViewHeaderView()
tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
simulateLongOperation() {
DispatchQueue.main.sync {
self.headerView.activityIndicator.isHidden = true
self.headerView.label.text = "I'm the updated HeaderView"
self.updateTableViewHeaderFrame() //updateTableViewHeaderWithIOS9BugFix()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Private func
private func setupTableView() {
tableView.dataSource = self
tableView.register(UINib(nibName: customCellIdentifier, bundle: nil), forCellReuseIdentifier: customCellIdentifier)
}
private func setupTableViewHeaderView() {
headerView.frame = tableViewHeaderInitialFrame
tableView.tableHeaderView = headerView
}
private func simulateLongOperation(completion: @escaping(() -> Void)){
headerView.activityIndicator.startAnimating()
DispatchQueue.global(qos: .background).async {
sleep(3)
completion()
}
}
// Use this function to see the bug on iOS 9
private func updateTableViewHeaderFrame() {
tableView.tableHeaderView!.frame = tableViewHeaderUpdatedFrame
}
// Use this function to fix the bug
private func updateTableViewHeaderWithIOS9BugFix() {
headerView.frame = tableViewHeaderUpdatedFrame
tableView.tableHeaderView = headerView
}
}
extension ViewController: UITableViewDataSource {
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: customCellIdentifier, for: indexPath) as! CustomCell
cell.label.text = "Cell \(indexPath.row)"
return cell
}
}
| mit | 30322d20223e62ffaca984b133543376 | 33.082353 | 184 | 0.688989 | 5.435272 | false | false | false | false |
min/Lay | Example/Example/CollectionViewCell.swift | 1 | 972 | //
// CollectionViewCell.swift
// Example
//
// Created by Min Kim on 2/11/17.
// Copyright © 2017 Min Kim. All rights reserved.
//
import UIKit
final class CollectionViewCell: UICollectionViewCell {
class var reuseIdentifier: String {
return "\(type(of: self))ReuseIdentifier"
}
let titleLabel: UILabel = .init()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.textAlignment = .center
titleLabel.textColor = .white
titleLabel.font = UIFont(name: "Courier-Bold", size: 14)
contentView.addSubview(titleLabel)
contentView.layer.borderColor = UIColor.black.cgColor
contentView.layer.borderWidth = 1 / UIScreen.main.scale
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = contentView.bounds
}
}
| mit | b410b2e2cc23392651ba1df494876f71 | 23.275 | 64 | 0.657055 | 4.49537 | false | false | false | false |
Yoseob/Trevi | Lime/Lime/Layer.swift | 1 | 2972 | //
// Layer.swift
// Trevi
//
// Created by LeeYoseob on 2016. 3. 2..
// Copyright © 2016년 LeeYoseob. All rights reserved.
//
import Foundation
import Trevi
/*
Reuse for becoming more useful results Middleware and all the routes that object is wrapped with this class.
*/
public class Layer {
private var handle: HttpCallback?
public var path: String! = ""
public var regexp: RegExp!
public var name: String!
public var route: Route?
public var method: HTTPMethodType! = .UNDEFINED
public var keys: [String]? // params key ex path/:name , name is key
public var params: [String: String]?
public init(path: String ,name: String? = "function", options: Option? = nil, fn: HttpCallback){
setupAfterInit(path, opt: options, name: name, fn: fn)
}
public init(path: String, options: Option? = nil, module: Middleware){
setupAfterInit(path, opt: options, name: module.name.rawValue, fn: module.handle)
}
private func setupAfterInit(p: String, opt: Option? = nil, name: String?, fn: HttpCallback){
self.handle = fn
self.path = p
self.name = name
//create regexp
regexp = self.pathRegexp(path, option: opt)
if path == "/" && opt?.end == false {
regexp.fastSlash = true
}
}
private func pathRegexp(path: String, option: Option!) -> RegExp{
// create key, and append key when create regexp
keys = [String]()
if path.length() > 1 {
for param in searchWithRegularExpression(path, pattern: ":([^\\/]*)") {
keys!.append(param["$1"]!.text)
}
}
return RegExp(path: path)
}
//handle mathed route module
public func handleRequest(req: IncomingMessage , res: ServerResponse, next: NextCallback){
let function = self.handle
function!(req,res,next)
}
//Request url meching.
public func match(path: String?) -> Bool{
guard path != nil else {
self.params = nil
self.path = nil
return false
}
guard (self.regexp.fastSlash) == false else {
self.path = ""
self.params = [String: String]()
return true
}
var ret: [String]! = self.regexp.exec(path!)
guard ret != nil else{
self.params = nil
self.path = nil
return false
}
self.path = ret[0]
self.params = [String: String]()
ret.removeFirst()
var idx = 0
var key: String! = ""
for value in ret {
key = keys![idx]
idx += 1
if key == nil {
break
}
params![key] = value
key = nil
}
return true
}
}
| apache-2.0 | ca39fb53d044a528e5e42f97fdb2c97b | 25.508929 | 112 | 0.524756 | 4.431343 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/Vision/BarcodesVision/BarcodesVisionVC.swift | 1 | 9865 | /// Copyright (c) 2020 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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 Vision
import AVFoundation
import SafariServices
// https://www.raywenderlich.com/12663654-vision-framework-tutorial-for-ios-scanning-barcodes
class BarcodesVisionVC: UIViewController {
// MARK: - Private Variables
var captureSession = AVCaptureSession()
// TODO: Make VNDetectBarcodesRequest variable
lazy var detectBarcodeRequest = VNDetectBarcodesRequest { request, error in
guard error == nil else {
self.showAlert(withTitle: "Barcode error", message: error?.localizedDescription ?? "error")
return
}
self.processClassification(request)
}
// MARK: - Override Functions
override func viewDidLoad() {
super.viewDidLoad()
checkPermissions()
setupCameraLiveView()
view.addSubview(annotationOverlayView)
NSLayoutConstraint.activate([
annotationOverlayView.topAnchor.constraint(equalTo: view.topAnchor),
annotationOverlayView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
annotationOverlayView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
annotationOverlayView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
private lazy var annotationOverlayView: UIView = {
precondition(isViewLoaded)
let annotationOverlayView = UIView(frame: .zero)
annotationOverlayView.translatesAutoresizingMaskIntoConstraints = false
return annotationOverlayView
}()
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// TODO: Stop Session
captureSession.stopRunning()
}
var cameraPreviewLayer: AVCaptureVideoPreviewLayer!
}
extension BarcodesVisionVC {
// MARK: - Camera
private func checkPermissions() {
// TODO: Checking permissions
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { [self] granted in
if !granted {
self.showPermissionsAlert()
}
}
case .denied, .restricted:
showPermissionsAlert()
default:
return
}
}
private func setupCameraLiveView() {
// TODO: Setup captureSession
captureSession.sessionPreset = .hd1280x720
// TODO: Add input
let videoDevice = AVCaptureDevice
.default(.builtInWideAngleCamera, for: .video, position: .back)
guard
let device = videoDevice,
let videoDeviceInput = try? AVCaptureDeviceInput(device: device),
captureSession.canAddInput(videoDeviceInput) else {
showAlert(
withTitle: "Cannot Find Camera",
message: "There seems to be a problem with the camera on your device.")
return
}
captureSession.addInput(videoDeviceInput)
// TODO: Add output
let captureOutput = AVCaptureVideoDataOutput()
// TODO: Set video sample rate
captureOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
captureOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))
captureSession.addOutput(captureOutput)
configurePreviewLayer()
// TODO: Run session
captureSession.startRunning()
}
// MARK: - Vision
func processClassification(_ request: VNRequest) {
// TODO: Main logic
guard let barcodes = request.results else { return }
DispatchQueue.main.async { [self] in
if captureSession.isRunning {
view.layer.sublayers?.removeSubrange(1...)
let set: Set<VNBarcodeSymbology> = [.QR, .EAN13, .EAN8, .Code128]
for barcode in barcodes {
guard
// TODO: Check for QR Code symbology and confidence score
let potentialQRCode = barcode as? VNBarcodeObservation,
set.contains(potentialQRCode.symbology),
potentialQRCode.confidence > 0.9
else { return }
// https://github.com/jeffreybergier/Blog-Getting-Started-with-Vision/issues/2
let t = CGAffineTransform(translationX: 0.5, y: 0.5)
.rotated(by: CGFloat.pi / 2)
.translatedBy(x: -0.5, y: -0.5)
.translatedBy(x: 1.0, y: 0)
.scaledBy(x: -1, y: 1)
let box = potentialQRCode.boundingBox.applying(t)
let convertedRect = self.cameraPreviewLayer.layerRectConverted(
fromMetadataOutputRect: box
)
UIUtilities.addRectangle(
convertedRect,
to: view,
text: potentialQRCode.payloadStringValue
)
// observationHandler(payload: potentialQRCode.payloadStringValue)
}
}
}
}
// MARK: - Handler
func observationHandler(payload: String?) {
// TODO: Open it in Safari
guard
let payloadString = payload,
let url = URL(string: payloadString),
["http", "https"].contains(url.scheme?.lowercased())
else { return }
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = true
let safariVC = SFSafariViewController(url: url, configuration: config)
safariVC.delegate = self
present(safariVC, animated: true)
}
}
// MARK: - AVCaptureDelegation
extension BarcodesVisionVC: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// TODO: Live Vision
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
let imageRequestHandler = VNImageRequestHandler(
cvPixelBuffer: pixelBuffer,
orientation: .right)
do {
try imageRequestHandler.perform([detectBarcodeRequest])
} catch {
print(error)
}
}
}
// MARK: - Helper
extension BarcodesVisionVC {
private func configurePreviewLayer() {
let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.cameraPreviewLayer = cameraPreviewLayer
cameraPreviewLayer.videoGravity = .resizeAspectFill
cameraPreviewLayer.connection?.videoOrientation = .portrait
cameraPreviewLayer.frame = view.frame
view.layer.insertSublayer(cameraPreviewLayer, at: 0)
}
private func showAlert(withTitle title: String, message: String) {
DispatchQueue.main.async {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true)
}
}
private func showPermissionsAlert() {
showAlert(
withTitle: "Camera Permissions",
message: "Please open Settings and grant permission for this app to use your camera.")
}
}
// MARK: - SafariViewControllerDelegate
extension BarcodesVisionVC: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
captureSession.startRunning()
}
}
| mit | 8ca661deb65b2bb59ed36bb2073b26f0 | 38.618474 | 129 | 0.636087 | 5.598751 | false | false | false | false |
aotian16/SwiftGameDemo | Cat/Cat/GameViewController.swift | 1 | 1463 | //
// GameViewController.swift
// Cat
//
// Created by 童进 on 15/11/25.
// Copyright (c) 2015年 qefee. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .ResizeFill
// scene.size = UIScreen.mainScreen().bounds.size
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | f6f40419e1fbc144c15ec9dd7f77c59f | 25.981481 | 94 | 0.595745 | 5.416357 | false | false | false | false |
barteljan/VISPER | VISPER-Entity/Classes/FunctionalEntityStore.swift | 1 | 9164 | //
// FunctionalEntityStore.swift
// Pods-VISPER-Entity-Example
//
// Created by bartel on 09.04.18.
//
import Foundation
open class FunctionalEntityStore<EntityType: CanBeIdentified>: EntityStore {
public enum StoreError: Error {
case functionNotImplementedYet
}
let persistEntites: (_ entities: [EntityType]) throws -> Void
let deleteEntites: (_ entities: [EntityType]) throws -> Void
let getEntities: ()->[EntityType]
let getEntity: (_ identifier: String) -> EntityType?
let deleteEntity: (_ identifier: String) throws -> Void
public convenience init(persistEntites: @escaping (_ entities: [EntityType]) throws -> Void,
deleteEntites: @escaping (_ entities: [EntityType]) throws -> Void,
getEntities: @escaping ()->[EntityType]) {
let getEntity = { (aIdentifier) -> EntityType? in
return getEntities().filter({ return $0.identifier() == aIdentifier }).first
}
self.init(persistEntites: persistEntites,
deleteEntites: deleteEntites,
getEntities: getEntities,
getEntity: getEntity)
}
public convenience init(persistEntites: @escaping (_ entities: [EntityType]) throws -> Void,
deleteEntites: @escaping (_ entities: [EntityType]) throws -> Void,
getEntities: @escaping ()->[EntityType],
getEntity: @escaping (_ identifier: String) -> EntityType?){
let deleteEntity = { (identifier: String) throws -> Void in
if let entity = getEntity(identifier) {
try deleteEntites([entity])
}
}
self.init(persistEntites: persistEntites,
deleteEntites: deleteEntites,
getEntities: getEntities,
getEntity: getEntity,
deleteEntity: deleteEntity)
}
public convenience init(persistEntites: @escaping (_ entities: [EntityType]) throws -> Void,
getEntities: @escaping ()->[EntityType],
getEntity: @escaping (_ identifier: String) -> EntityType?,
deleteEntity: @escaping (_ identifier: String) throws -> Void ){
let deleteEntities = { (_ entities: [EntityType]) throws -> Void in
for entity in entities {
try deleteEntity(entity.identifier())
}
}
self.init(persistEntites: persistEntites,
deleteEntites: deleteEntities,
getEntities: getEntities,
getEntity: getEntity,
deleteEntity: deleteEntity)
}
public init(persistEntites: @escaping (_ entities: [EntityType]) throws -> Void,
deleteEntites: @escaping (_ entities: [EntityType]) throws -> Void,
getEntities: @escaping ()->[EntityType],
getEntity: @escaping (_ identifier: String) -> EntityType?,
deleteEntity: @escaping (_ identifier: String) throws -> Void ){
self.persistEntites = persistEntites
self.deleteEntites = deleteEntites
self.getEntities = getEntities
self.getEntity = getEntity
self.deleteEntity = deleteEntity
}
public func isResponsible<T>(for object: T) -> Bool {
return object is EntityType
}
public func isResponsible<T>(forType type: T.Type) -> Bool {
return type.self is EntityType.Type
}
public func delete<T>(_ item: T!) throws {
if let item = item as? EntityType {
try self.deleteEntites([item])
}
}
public func delete<T>(_ items: [T]) throws {
if T.self is EntityType.Type {
let convertedItems = items.map({ return $0 as! EntityType})
try self.deleteEntites(convertedItems)
}
}
public func delete<T>(_ item: T!,
completion: @escaping () -> ()) throws {
try self.delete(item)
completion()
}
public func delete<T>(_ identifier: String, type: T.Type) throws {
try self.deleteEntity(identifier)
}
public func get<T>(_ identifier: String) throws -> T? {
return self.getEntity(identifier) as? T
}
public func get<T>(_ identifier: String,
completion: @escaping (T?) -> Void) throws {
let item: T? = try self.get(identifier)
completion(item)
}
public func persist<T>(_ item: T!) throws {
if let item = item as? EntityType {
try self.persistEntites([item])
}
}
public func persist<T>(_ item: T!,
completion: @escaping () -> ()) throws {
try self.persist(item)
completion()
}
public func persist<T>(_ items: [T]) throws {
if T.self is EntityType.Type {
let convertedItems = items.map({ return $0 as! EntityType})
try self.persistEntites(convertedItems)
}
}
public func getAll<T>(_ type: T.Type) throws -> [T] {
if T.self is EntityType.Type {
return self.getEntities().map { (entity) -> T in
return entity as! T
}
} else {
return [T]()
}
}
public func getAll<T>(_ type: T.Type,
completion: @escaping ([T]) -> Void) throws {
let items = try self.getAll(type)
completion(items)
}
public func getAll<T>(_ viewName: String) throws -> [T] {
throw StoreError.functionNotImplementedYet
}
public func getAll<T>(_ viewName: String,
completion: @escaping ([T]) -> Void) throws {
throw StoreError.functionNotImplementedYet
}
public func getAll<T>(_ viewName: String,
groupName: String) throws -> [T] {
throw StoreError.functionNotImplementedYet
}
public func getAll<T>(_ viewName: String,
groupName: String,
completion: @escaping ([T]) -> Void) throws {
throw StoreError.functionNotImplementedYet
}
public func exists<T>(_ item: T!) throws -> Bool {
guard T.self is EntityType.Type else {
return false
}
if let item = item as? EntityType {
let identifier = item.identifier()
if let _ : T = try self.get(identifier) {
return true
}
}
return false
}
public func exists<T>(_ item: T!,
completion: @escaping (Bool) -> Void) throws {
let isExistent = try self.exists(item)
completion(isExistent)
}
public func exists<T>(_ identifier: String,
type: T.Type) throws -> Bool {
guard T.self is EntityType.Type else {
return false
}
if let _ : T = try self.get(identifier) {
return true
}
return false
}
public func exists<T>(_ identifier: String,
type: T.Type,
completion: @escaping (Bool) -> Void) throws {
let isExistent = try self.exists(identifier, type: type)
completion(isExistent)
}
public func filter<T>(_ type: T.Type,
includeElement: @escaping (T) -> Bool) throws -> [T] {
return try self.getAll(type).filter(includeElement)
}
public func filter<T>(_ type: T.Type,
includeElement: @escaping (T) -> Bool,
completion: @escaping ([T]) -> Void) throws {
let items: [T] = try self.filter(type, includeElement: includeElement)
completion(items)
}
public func addView<T>(_ viewName: String,
groupingBlock: @escaping ((String, String, T) -> String?),
sortingBlock: @escaping ((String, String, String, T, String, String, T) -> ComparisonResult)) throws {
throw StoreError.functionNotImplementedYet
}
public func transaction(transaction: @escaping (EntityStore) throws -> Void) throws {
let items = self.getEntities()
let transactionStore = try MemoryEntityStore([items])
try transaction(transactionStore)
for item in transactionStore.deletedEntities() {
if let item = item as? EntityType {
try self.delete(item)
}
}
for item in transactionStore.updatedEntities() {
if let item = item as? EntityType {
try self.persist(item)
}
}
}
public func toTypedEntityStore() throws -> TypedEntityStore<EntityType> {
return try TypedEntityStore(entityStore: self)
}
}
| mit | 2e8e1b1d891cf262c0743888138df2b4 | 32.323636 | 127 | 0.53481 | 5.195011 | false | false | false | false |
antelope-app/Antelope | Antelope-ios/Antelope/TutorialStepZero.swift | 1 | 4067 | //
// TutorialStepZero.swift
// AdShield
//
// Created by Jae Lee on 9/1/15.
// Copyright © 2015 AdShield. All rights reserved.
//
import UIKit
class TutorialStepZero: TutorialStep
{
@IBOutlet weak var logoImage: UIImageView!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var stepZeroHeader: UITextView!
@IBOutlet weak var stepZeroSubheader: UITextView!
@IBOutlet weak var stepZeroHeaderImage: UIImageView!
@IBOutlet weak var secondSubHeader: UITextView!
@IBOutlet weak var thirdSubHeader: UITextView!
var overlaySoft: UIView = UIView()
var overlayHard: UIView = UIView()
@IBOutlet weak var barTwo: UIView!
@IBOutlet weak var barOne: UIView!
override func viewDidLoad() {
super.viewDidLoad()
stepZeroSubheader = self.paragraphStyle(stepZeroSubheader)
stepZeroSubheader.userInteractionEnabled = false
secondSubHeader.hidden = true
secondSubHeader.text = "You'll use less data, see way fewer ads, have better battery life, and stop being tracked on the web."
secondSubHeader = self.paragraphStyle(secondSubHeader)
secondSubHeader.userInteractionEnabled = false
thirdSubHeader.hidden = true
thirdSubHeader.text = "Antelope receives none of your browsing data, and it's entirely open-source."
thirdSubHeader = self.paragraphStyle(thirdSubHeader)
thirdSubHeader.userInteractionEnabled = false
self.constrainButton(nextButton)
self.view.layoutSubviews()
}
override func viewDidAppear(animated: Bool) {
}
func initialize() {
let translationDistance: CGFloat = 140.0
let headerFrame = self.stepZeroHeader.frame
self.stepZeroSubheader.frame.origin.y = headerFrame.origin.y + headerFrame.size.height
self.secondSubHeader.frame = stepZeroSubheader.frame
self.secondSubHeader.frame.origin.x = self.view.frame.size.width
self.secondSubHeader.hidden = false
/*self.delay(7.0, closure: {
UIView.animateWithDuration(0.5, animations: {
let anchor = self.stepZeroSubheader.frame.origin.x
self.stepZeroSubheader.frame.origin.x = 0 - self.stepZeroSubheader.frame.size.width
self.secondSubHeader.frame.origin.x = anchor
})
})*/
self.thirdSubHeader.frame = self.secondSubHeader.frame
self.thirdSubHeader.frame.origin.x = self.view.frame.size.width
self.thirdSubHeader.hidden = false
/*self.delay(14.0, closure: {
UIView.animateWithDuration(0.5, animations: {
let anchor = self.secondSubHeader.frame.origin.x
self.secondSubHeader.frame.origin.x = 0 - self.secondSubHeader.frame.size.width
self.thirdSubHeader.frame.origin.x = anchor
})
})*/
UIView.animateWithDuration(0.7, delay: 0, options: .CurveEaseInOut, animations: {
// LOGO MOVING
let currentPosY = self.logoImage.frame.origin.y
self.logoImage.frame.origin.y = currentPosY - translationDistance
//self.stepZeroHeaderImage.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, distanceFromToBeLogoToTop + inset)
}, completion: {(Bool) in
// LOGO MOVED
UIView.animateWithDuration(0.7, animations: {
self.stepZeroHeader.alpha = 1.0
}, completion: {(Bool) in
})
// sub header, then bars
self.delay(1.0) {
UIView.animateWithDuration(0.7, animations: {
self.nextButton.alpha = 0.5
self.stepZeroSubheader.alpha = 1.0
})
}
})
}
}
| gpl-2.0 | dd3b1b69347e4a7aff564c637c17e968 | 35.630631 | 139 | 0.599606 | 5.0825 | false | false | false | false |
fgulan/letter-ml | project/LetterML/Frameworks/framework/Source/Operations/Dilation.swift | 9 | 1516 | public class Dilation: TwoStageOperation {
public var radius:UInt {
didSet {
switch radius {
case 0, 1:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation1VertexShader, fragmentShader:Dilation1FragmentShader)}
case 2:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation2VertexShader, fragmentShader:Dilation2FragmentShader)}
case 3:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation3VertexShader, fragmentShader:Dilation3FragmentShader)}
case 4:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation4VertexShader, fragmentShader:Dilation4FragmentShader)}
default:
shader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation4VertexShader, fragmentShader:Dilation4FragmentShader)}
}
}
}
public init() {
radius = 1
let initialShader = crashOnShaderCompileFailure("Dilation"){try sharedImageProcessingContext.programForVertexShader(ErosionDilation1VertexShader, fragmentShader:Dilation1FragmentShader)}
super.init(shader:initialShader, numberOfInputs:1)
}
} | mit | b2f6c3ff01bf191c343d7faabccc75db | 62.208333 | 194 | 0.742084 | 7.184834 | false | false | false | false |
silence0201/Swift-Study | Swifter/28Lazy.playground/Contents.swift | 1 | 780 | //: Playground - noun: a place where people can play
import Foundation
class ClassA {
lazy var str: String = {
let str = "Hello"
print("只在首次访问输出")
return str
}()
}
print("Creating object")
let obj = ClassA()
print("Accessing str")
obj.str
print("Accessing str again")
obj.str
let data1 = 1...3
let result1 = data1.map { (i) -> Int in
print("正在处理\(i)")
return i*2
}
print("准备访问结果")
for i in result1 {
print("操作后结果为 \(i)")
}
print("操作完毕")
let data2 = 1...3
let result2 = data2.lazy.map {
(i: Int) -> Int in
print("正在处理 \(i)")
return i * 2
}
print("准备访问结果")
for i in result2 {
print("操作后结果为 \(i)")
}
print("操作完毕")
| mit | 7ab7849fca653737702382673a8d31c1 | 12.959184 | 52 | 0.580409 | 2.87395 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/TabBarController/MainTabBarController.swift | 1 | 10166 | //
// MainTabBarController.swift
// Habitica
//
// Created by Phillip Thelen on 25.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import ReactiveSwift
import FirebaseAnalytics
#if DEBUG
import FLEX
#endif
class MainTabBarController: UITabBarController, Themeable {
private let userRepository = UserRepository()
private let taskRepository = TaskRepository()
private let disposable = ScopedDisposable(CompositeDisposable())
@objc public var selectedTags = [String]()
private var dueDailiesCount = 0
private var dueToDosCount = 0
private var tutorialDailyCount = 0
private var tutorialToDoCount = 0
private var badges: [Int: PaddedView]? {
set {
if let badges = newValue {
(tabBar as? MainTabBar)?.badges = badges
}
}
get { return (tabBar as? MainTabBar)?.badges }
}
private var showAdventureGuideBadge = false {
didSet {
let badge = badges?[4]
if showAdventureGuideBadge {
if badge == nil || badge?.containedView is UILabel {
badge?.removeFromSuperview()
let newBadge = PaddedView()
badges?[4] = newBadge
newBadge.verticalPadding = 4
newBadge.horizontalPadding = 4
newBadge.backgroundColor = .yellow10
newBadge.containedView = UIImageView(image: Asset.adventureGuideStar.image)
newBadge.isUserInteractionEnabled = false
tabBar.addSubview(newBadge)
(tabBar as? MainTabBar)?.layoutBadges()
} else {
return
}
} else {
if !(badge?.containedView is UILabel) {
badge?.removeFromSuperview()
badges?.removeValue(forKey: 4)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
#if DEBUG
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(showDebugMenu))
swipe.direction = .up
swipe.delaysTouchesBegan = true
swipe.numberOfTouchesRequired = 1
tabBar.addGestureRecognizer(swipe)
#endif
ThemeService.shared.addThemeable(themable: self)
}
func applyTheme(theme: Theme) {
tabBar.items?.forEach({
$0.badgeColor = theme.badgeColor
if theme.badgeColor.isLight() {
$0.setBadgeTextAttributes([.foregroundColor: UIColor.gray50], for: .normal)
} else {
$0.setBadgeTextAttributes([.foregroundColor: UIColor.gray700], for: .normal)
}
})
tabBar.tintColor = theme.fixedTintColor
tabBar.barTintColor = theme.contentBackgroundColor
tabBar.backgroundColor = theme.contentBackgroundColor
tabBar.backgroundImage = UIImage.from(color: theme.contentBackgroundColor)
tabBar.shadowImage = UIImage.from(color: theme.contentBackgroundColor)
tabBar.barStyle = .black
if #available(iOS 13.0, *) {
if ThemeService.shared.themeMode == "dark" {
self.overrideUserInterfaceStyle = .dark
} else if ThemeService.shared.themeMode == "light" {
self.overrideUserInterfaceStyle = .light
} else {
self.overrideUserInterfaceStyle = .unspecified
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
presentingViewController?.willMove(toParent: nil)
presentingViewController?.removeFromParent()
}
private func fetchData() {
disposable.inner.add(userRepository.getUser().on(value: {[weak self] user in
var badgeCount = 0
// swiftlint:disable:next empty_count
if let count = user.inbox?.numberNewMessages, count > 0 {
badgeCount += count
}
if user.flags?.hasNewStuff == true {
badgeCount += 1
}
if let partyID = user.party?.id {
if user.hasNewMessages.first(where: { (newMessages) -> Bool in
return newMessages.id == partyID
})?.hasNewMessages == true {
badgeCount += 1
}
}
self?.showAdventureGuideBadge = user.achievements?.hasCompletedOnboarding != true
self?.setBadgeCount(index: 4, count: badgeCount)
if let tutorials = user.flags?.tutorials {
self?.updateTutorialSteps(tutorials)
}
if user.flags?.welcomed != true {
self?.userRepository.updateUser(key: "flags.welcomed", value: true).observeCompleted {}
}
}).start())
disposable.inner.add(taskRepository.getDueTasks().on(value: {[weak self] tasks in
self?.dueDailiesCount = 0
self?.dueToDosCount = 0
let calendar = Calendar(identifier: .gregorian)
let today = Date()
for task in tasks.value where !task.completed {
if task.type == TaskType.daily {
self?.dueDailiesCount += 1
} else if task.type == TaskType.todo, let duedate = task.duedate {
if duedate < today || calendar.isDate(today, inSameDayAs: duedate) {
self?.dueToDosCount += 1
}
}
}
self?.updateDailyBadge()
self?.updateToDoBadge()
self?.updateAppBadge()
}).start())
}
private func updateTutorialSteps(_ tutorials: [TutorialStepProtocol]) {
for tutorial in tutorials {
if tutorial.key == "habits" {
setBadgeCount(index: 0, count: tutorial.wasSeen ? 0 : 1)
}
if tutorial.key == "dailies" {
tutorialDailyCount = tutorial.wasSeen ? 0 : 1
updateDailyBadge()
}
if tutorial.key == "todos" {
tutorialToDoCount = tutorial.wasSeen ? 0 : 1
updateToDoBadge()
}
if tutorial.key == "rewards" {
setBadgeCount(index: 3, count: tutorial.wasSeen ? 0 : 1)
}
}
}
private func updateDailyBadge() {
setBadgeCount(index: 1, count: dueDailiesCount + tutorialDailyCount)
}
private func updateToDoBadge() {
setBadgeCount(index: 2, count: dueToDosCount + tutorialToDoCount)
}
private func setBadgeCount(index: Int, count: Int) {
if index == 4 && showAdventureGuideBadge {
return
}
let badge = badges?[index] ?? PaddedView()
badges?[index] = badge
if !(badge.containedView is UILabel) {
badge.verticalPadding = 2
badge.horizontalPadding = 6
let label = UILabel()
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .center
badge.containedView = label
}
badge.backgroundColor = .gray50
if let label = badge.containedView as? UILabel {
label.text = "\(count)"
}
// swiftlint:disable:next empty_count
badge.isHidden = count == 0
badge.isUserInteractionEnabled = false
tabBar.addSubview(badge)
(tabBar as? MainTabBar)?.layoutBadges()
}
private func updateAppBadge() {
let defaults = UserDefaults.standard
if defaults.bool(forKey: "appBadgeActive") == true {
UIApplication.shared.applicationIconBadgeNumber = dueDailiesCount + dueToDosCount
} else {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if #available(iOS 13.0, *) {
ThemeService.shared.updateInterfaceStyle(newStyle: traitCollection.userInterfaceStyle)
}
}
#if DEBUG
@objc
private func showDebugMenu(_ recognizer: UISwipeGestureRecognizer) {
if recognizer.state = .recognizer {
FLEXManager.sharedManager.showExplorer()
}
}
#endif
}
class MainTabBar: UITabBar {
var badges = [Int: PaddedView]()
override open func sizeThatFits(_ size: CGSize) -> CGSize {
var sizeThatFits = super.sizeThatFits(size)
guard let window = UIApplication.shared.keyWindow else {
return sizeThatFits
}
if #available(iOS 11.0, *) {
if window.safeAreaInsets.bottom > 0 {
sizeThatFits.height = 42 + window.safeAreaInsets.bottom
}
}
return sizeThatFits
}
override func layoutSubviews() {
super.layoutSubviews()
layoutBadges()
}
func layoutBadges() {
for entry in badges {
let frame = frameForTab(atIndex: entry.key)
let size = entry.value.intrinsicContentSize
let width = max(size.height, size.width)
// Find the edge of the icon and then center the badge there
entry.value.frame = CGRect(x: frame.origin.x + (frame.size.width/2) + 15 - (width/2), y: frame.origin.y + 4, width: width, height: size.height)
entry.value.cornerRadius = size.height / 2
}
}
private func frameForTab(atIndex index: Int) -> CGRect {
var frames = subviews.compactMap { (view: UIView) -> CGRect? in
if let view = view as? UIControl {
return view.frame
}
return nil
}
frames.sort { $0.origin.x < $1.origin.x }
if frames.count > index {
return frames[index]
}
return frames.last ?? CGRect.zero
}
}
| gpl-3.0 | cbbdb8a860466478f6750df8d3d2c335 | 34.418118 | 155 | 0.56242 | 5.139029 | false | false | false | false |
jmgc/swift | test/decl/protocol/special/Actor.swift | 1 | 2227 | // RUN: %target-typecheck-verify-swift -enable-experimental-concurrency
// REQUIRES: concurrency
// Synthesis of for actor classes.
actor class A1 {
var x: Int = 17
}
actor class A2: Actor {
var x: Int = 17
}
actor class A3<T>: Actor {
var x: Int = 17
}
actor class A4: A1 {
}
actor class A5: A2 {
}
actor class A6: A1, Actor { // expected-error{{redundant conformance of 'A6' to protocol 'Actor'}}
// expected-note@-1{{'A6' inherits conformance to protocol 'Actor' from superclass here}}
}
// Explicitly satisfying the requirement.
actor class A7 {
// Okay: satisfy the requirement explicitly
@actorIndependent func enqueue(partialTask: PartialAsyncTask) { }
}
// A non-actor class can conform to the Actor protocol, if it does it properly.
class C1: Actor {
func enqueue(partialTask: PartialAsyncTask) { }
}
// Bad actors, that incorrectly try to satisfy the various requirements.
// Method that is not usable as a witness.
actor class BA1 {
func enqueue(partialTask: PartialAsyncTask) { } // expected-error{{actor-isolated instance method 'enqueue(partialTask:)' cannot be used to satisfy a protocol requirement}}
//expected-note@-1{{add '@asyncHandler' to function 'enqueue(partialTask:)' to create an implicit asynchronous context}}{{3-3=@asyncHandler }}
//expected-note@-2{{add '@actorIndependent' to 'enqueue(partialTask:)' to make this instance method independent of the actor}}{{3-3=@actorIndependent }}
}
// Method that isn't part of the main class definition cannot be used to
// satisfy the requirement, because then it would not have a vtable slot.
actor class BA2 { }
extension BA2 {
// expected-error@+1{{'enqueue(partialTask:)' can only be implemented in the definition of actor class 'BA2'}}
@actorIndependent func enqueue(partialTask: PartialAsyncTask) { }
}
// No synthesis for non-actor classes.
class C2: Actor { // expected-error{{type 'C2' does not conform to protocol 'Actor'}}
}
// Make sure the conformances actually happen.
func acceptActor<T: Actor>(_: T.Type) { }
func testConformance() {
acceptActor(A1.self)
acceptActor(A2.self)
acceptActor(A3<Int>.self)
acceptActor(A4.self)
acceptActor(A5.self)
acceptActor(A6.self)
acceptActor(A7.self)
}
| apache-2.0 | 01d03c83ec86afacdf6b8da8f5435492 | 29.506849 | 174 | 0.72564 | 3.736577 | false | false | false | false |
Liqiankun/DLSwift | Swift/Swift数据类型.playground/Contents.swift | 1 | 1663 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
/** 基础数据类型 */
var numberOne : Int = 30;
//int的最大值
Int.max
//int的最小值
Int.min
var numberTwo : UInt = 3000;
UInt.max
UInt.min
Int8.max
Int8.min
Int64.max
Int64.min
let numberThree = 100_100_000
let nbFloat : Float = 233333.33;
let nbDouble : Double = 23.3333;
//12.25乘以十的十次方
let nb = 12.25e10;
//12.25乘以十的负8次方
let nc = 12.25e-8
//类型装换
let x : Int64 = 100;
let y : Int8 = 100;
let m = x + Int64(y)
let i :Double = 2.33;
let z : Float = 2.3;
let j = i + Double(z);
let red : CGFloat = 0;
let green : CGFloat = 0;
let blue : CGFloat = 0.3;
UIColor(red: red, green: green, blue: blue, alpha: 1.0)
//布尔
let imTrue = true
let imFalse = false
if imFalse{
print("I'm True")
}else{
print("I'm False")
}
//元组
var point = (4 , 5)
var httpRep = (404 , "Not found")
var httpRe : (Int64 , String) = (202 , "OK")
//元组解包
let(pX , pY) = point;
print(pX)
print(pY)
print(httpRep.1)
let pointOne = (p:2 , q : 3)
pointOne.p
let pointTwo : (pointP:Int, pointQ:Int) = (2,4)
pointTwo.pointP
//使用下划线忽略一些值
let loginResult = (true , "Success")
let (login,_) = loginResult
if login{
print("登录成功")
}
/** String */
//变量名称可以是中文
var 名字 = "David Lee"
print(名字)
//变量名称可以是表情
var 😀 = "Smile"
print(名字 + 😀)
let One = 1,Two = 2, Three = 3,bool = true
//separator分隔符,terminator(默认为回车)
print(One,Two,Three,bool,separator:"__",terminator:":)")
print(One, "*",Two,"=",One * Two)
| mit | 35e60f716d81b21fd46500839dddbc44 | 12.026316 | 56 | 0.625589 | 2.430442 | false | false | false | false |
apple/swift-package-manager | Tests/WorkspaceTests/ManifestSourceGenerationTests.swift | 1 | 22833 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import PackageGraph
import PackageLoading
import PackageModel
import SPMTestSupport
import TSCBasic
import Workspace
import XCTest
extension String {
fileprivate func nativePathString(escaped: Bool) -> String {
#if _runtime(_ObjC)
return self
#else
let fsr = self.fileSystemRepresentation
defer { fsr.deallocate() }
if escaped {
return String(cString: fsr).replacingOccurrences(of: "\\", with: "\\\\")
}
return String(cString: fsr)
#endif
}
}
class ManifestSourceGenerationTests: XCTestCase {
/// Private function that writes the contents of a package manifest to a temporary package directory and then loads it, then serializes the loaded manifest back out again and loads it once again, after which it compares that no information was lost. Return the source of the newly generated manifest.
@discardableResult
private func testManifestWritingRoundTrip(
manifestContents: String,
toolsVersion: ToolsVersion,
toolsVersionHeaderComment: String? = .none,
additionalImportModuleNames: [String] = [],
fs: FileSystem = localFileSystem
) throws -> String {
try withTemporaryDirectory { packageDir in
let observability = ObservabilitySystem.makeForTesting()
// Write the original manifest file contents, and load it.
let manifestPath = packageDir.appending(component: Manifest.filename)
try fs.writeFileContents(manifestPath, string: manifestContents)
let manifestLoader = ManifestLoader(toolchain: try UserToolchain.default)
let identityResolver = DefaultIdentityResolver()
let manifest = try tsc_await {
manifestLoader.load(
manifestPath: manifestPath,
manifestToolsVersion: toolsVersion,
packageIdentity: .plain("Root"),
packageKind: .root(packageDir),
packageLocation: packageDir.pathString,
packageVersion: nil,
identityResolver: identityResolver,
fileSystem: fs,
observabilityScope: observability.topScope,
delegateQueue: .sharedConcurrent,
callbackQueue: .sharedConcurrent,
completion: $0
)
}
XCTAssertNoDiagnostics(observability.diagnostics)
// Generate source code for the loaded manifest,
let newContents = try manifest.generateManifestFileContents(
packageDirectory: packageDir,
toolsVersionHeaderComment: toolsVersionHeaderComment,
additionalImportModuleNames: additionalImportModuleNames)
// Check that the tools version was serialized properly.
let versionSpacing = (toolsVersion >= .v5_4) ? " " : ""
XCTAssertMatch(newContents, .prefix("// swift-tools-version:\(versionSpacing)\(toolsVersion.major).\(toolsVersion.minor)"))
// Write out the generated manifest to replace the old manifest file contents, and load it again.
try fs.writeFileContents(manifestPath, string: newContents)
let newManifest = try tsc_await {
manifestLoader.load(
manifestPath: manifestPath,
manifestToolsVersion: toolsVersion,
packageIdentity: .plain("Root"),
packageKind: .root(packageDir),
packageLocation: packageDir.pathString,
packageVersion: nil,
identityResolver: identityResolver,
fileSystem: fs,
observabilityScope: observability.topScope,
delegateQueue: .sharedConcurrent,
callbackQueue: .sharedConcurrent,
completion: $0
)
}
XCTAssertNoDiagnostics(observability.diagnostics)
// Check that all the relevant properties survived.
let failureDetails = "\n--- ORIGINAL MANIFEST CONTENTS ---\n" + manifestContents + "\n--- REWRITTEN MANIFEST CONTENTS ---\n" + newContents
XCTAssertEqual(newManifest.toolsVersion, manifest.toolsVersion, failureDetails)
XCTAssertEqual(newManifest.displayName, manifest.displayName, failureDetails)
XCTAssertEqual(newManifest.defaultLocalization, manifest.defaultLocalization, failureDetails)
XCTAssertEqual(newManifest.platforms, manifest.platforms, failureDetails)
XCTAssertEqual(newManifest.pkgConfig, manifest.pkgConfig, failureDetails)
XCTAssertEqual(newManifest.providers, manifest.providers, failureDetails)
XCTAssertEqual(newManifest.products, manifest.products, failureDetails)
XCTAssertEqual(newManifest.dependencies, manifest.dependencies, failureDetails)
XCTAssertEqual(newManifest.targets, manifest.targets, failureDetails)
XCTAssertEqual(newManifest.swiftLanguageVersions, manifest.swiftLanguageVersions, failureDetails)
XCTAssertEqual(newManifest.cLanguageStandard, manifest.cLanguageStandard, failureDetails)
XCTAssertEqual(newManifest.cxxLanguageStandard, manifest.cxxLanguageStandard, failureDetails)
// Return the generated manifest so that the caller can do further testing on it.
return newContents
}
}
func testBasics() throws {
let manifestContents = """
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MyPackage",
platforms: [
.macOS(.v10_14),
.iOS(.v13)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "MyPackage",
targets: ["MyPackage"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "MyPackage",
dependencies: []),
.testTarget(
name: "MyPackageTests",
dependencies: ["MyPackage"]),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
}
func testCustomPlatform() throws {
let manifestContents = """
// swift-tools-version:5.6
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MyPackage",
platforms: [
.custom("customOS", versionString: "1.0")
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "MyPackage",
targets: ["MyPackage"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "MyPackage",
dependencies: []),
.testTarget(
name: "MyPackageTests",
dependencies: ["MyPackage"]),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_6)
}
func testAdvancedFeatures() throws {
let manifestContents = """
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "MyPackage",
targets: ["MyPackage"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(path: "/a/b/c"),
.package(name: "abc", path: "/a/b/d"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.systemLibrary(
name: "SystemLibraryTarget",
pkgConfig: "libSystemModule",
providers: [
.brew(["SystemModule"]),
]),
.target(
name: "MyPackage",
dependencies: [
.target(name: "SystemLibraryTarget", condition: .when(platforms: [.macOS]))
],
linkerSettings: [
.unsafeFlags(["-Xlinker", "-rpath", "-Xlinker", "@executable_path/../../../lib/swift/macosx"], .when(platforms: [.iOS])),
]),
.testTarget(
name: "MyPackageTests",
dependencies: ["MyPackage"]),
],
swiftLanguageVersions: [.v5],
cLanguageStandard: .c11,
cxxLanguageStandard: .cxx11
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
}
func testPackageDependencyVariations() throws {
let manifestContents = """
// swift-tools-version:5.4
import PackageDescription
#if os(Windows)
let absolutePath = "file:///C:/Users/user/SourceCache/path/to/MyPkg16"
#else
let absolutePath = "file:///path/to/MyPkg16"
#endif
let package = Package(
name: "MyPackage",
dependencies: [
.package(url: "https://example.com/MyPkg1", from: "1.0.0"),
.package(url: "https://example.com/MyPkg2", .revision("58e9de4e7b79e67c72a46e164158e3542e570ab6")),
.package(url: "https://example.com/MyPkg5", .exact("1.2.3")),
.package(url: "https://example.com/MyPkg6", "1.2.3"..<"2.0.0"),
.package(url: "https://example.com/MyPkg7", .branch("main")),
.package(url: "https://example.com/MyPkg8", .upToNextMinor(from: "1.3.4")),
.package(url: "ssh://[email protected]/MyPkg9", .branch("my branch with spaces")),
.package(url: "../MyPkg10", from: "0.1.0"),
.package(path: "../MyPkg11"),
.package(path: "packages/path/to/MyPkg12"),
.package(path: "~/path/to/MyPkg13"),
.package(path: "~MyPkg14"),
.package(path: "~/path/to/~/MyPkg15"),
.package(path: "~"),
.package(path: absolutePath),
]
)
"""
let newContents = try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
// Check some things about the contents of the manifest.
XCTAssertTrue(newContents.contains("url: \"\("../MyPkg10".nativePathString(escaped: true))\""), newContents)
XCTAssertTrue(newContents.contains("path: \"\("../MyPkg11".nativePathString(escaped: true))\""), newContents)
XCTAssertTrue(newContents.contains("path: \"\("packages/path/to/MyPkg12".nativePathString(escaped: true))"), newContents)
}
func testResources() throws {
let manifestContents = """
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "Resources",
defaultLocalization: "is",
targets: [
.target(
name: "SwiftyResource",
resources: [
.copy("foo.txt"),
.process("a/b/c/"),
]
),
.target(
name: "SeaResource",
resources: [
.process("foo.txt", localization: .base),
]
),
.target(
name: "SieResource",
resources: [
.copy("bar.boo"),
]
),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
}
func testBuildSettings() throws {
let manifestContents = """
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "Localized",
targets: [
.target(name: "exe",
cxxSettings: [
.headerSearchPath("ProjectName"),
.headerSearchPath("../../.."),
.define("ABC=DEF"),
.define("GHI", to: "JKL")
]
),
.target(
name: "MyTool",
dependencies: ["Utility"],
cSettings: [
.headerSearchPath("path/relative/to/my/target"),
.define("DISABLE_SOMETHING", .when(platforms: [.iOS], configuration: .release)),
],
swiftSettings: [
.define("ENABLE_SOMETHING", .when(configuration: .release)),
],
linkerSettings: [
.linkedLibrary("openssl", .when(platforms: [.linux])),
]
),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)
}
func testPluginTargets() throws {
let manifestContents = """
// swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "Plugins",
targets: [
.plugin(
name: "MyPlugin",
capability: .buildTool(),
dependencies: ["MyTool"]
),
.executableTarget(
name: "MyTool"
),
]
)
"""
try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5)
}
func testCustomToolsVersionHeaderComment() throws {
let manifestContents = """
// swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "Plugins",
targets: [
.plugin(
name: "MyPlugin",
capability: .buildTool(),
dependencies: ["MyTool"]
),
.executableTarget(
name: "MyTool"
),
]
)
"""
let newContents = try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5, toolsVersionHeaderComment: "a comment")
XCTAssertTrue(newContents.hasPrefix("// swift-tools-version: 5.5; a comment\n"), "contents: \(newContents)")
}
func testAdditionalModuleImports() throws {
let manifestContents = """
// swift-tools-version:5.5
import PackageDescription
import Foundation
let package = Package(
name: "MyPkg",
targets: [
.executableTarget(
name: "MyExec"
),
]
)
"""
let newContents = try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5, additionalImportModuleNames: ["Foundation"])
XCTAssertTrue(newContents.contains("import Foundation\n"), "contents: \(newContents)")
}
func testCustomProductSourceGeneration() throws {
// Create a manifest containing a product for which we'd like to do custom source fragment generation.
let packageDir = AbsolutePath(path: "/tmp/MyLibrary")
let manifest = Manifest(
displayName: "MyLibrary",
path: packageDir.appending(component: "Package.swift"),
packageKind: .root(AbsolutePath(path: "/tmp/MyLibrary")),
packageLocation: packageDir.pathString,
platforms: [],
toolsVersion: .v5_5,
products: [
try .init(name: "Foo", type: .library(.static), targets: ["Bar"])
]
)
// Generate the manifest contents, using a custom source generator for the product type.
let contents = manifest.generateManifestFileContents(packageDirectory: packageDir, customProductTypeSourceGenerator: { product in
// This example handles library types in a custom way, for testing purposes.
var params: [SourceCodeFragment] = []
params.append(SourceCodeFragment(key: "name", string: product.name))
if !product.targets.isEmpty {
params.append(SourceCodeFragment(key: "targets", strings: product.targets))
}
// Handle .library specially (by not emitting as multiline), otherwise asking for default behavior.
if case .library(let type) = product.type {
if type != .automatic {
params.append(SourceCodeFragment(key: "type", enum: type.rawValue))
}
return SourceCodeFragment(enum: "library", subnodes: params, multiline: false)
}
else {
return nil
}
})
// Check that we generated what we expected.
XCTAssertTrue(contents.contains(".library(name: \"Foo\", targets: [\"Bar\"], type: .static)"), "contents: \(contents)")
}
func testModuleAliasGeneration() throws {
let manifest = Manifest.createRootManifest(
name: "thisPkg",
path: .init(path: "/thisPkg"),
toolsVersion: .v5_7,
dependencies: [
.localSourceControl(path: .init(path: "/fooPkg"), requirement: .upToNextMajor(from: "1.0.0")),
.localSourceControl(path: .init(path: "/barPkg"), requirement: .upToNextMajor(from: "2.0.0")),
],
targets: [
try TargetDescription(name: "exe",
dependencies: ["Logging",
.product(name: "Foo",
package: "fooPkg",
moduleAliases: ["Logging": "FooLogging"]
),
.product(name: "Bar",
package: "barPkg",
moduleAliases: ["Logging": "BarLogging"]
)
]),
try TargetDescription(name: "Logging", dependencies: []),
])
let contents = try manifest.generateManifestFileContents(packageDirectory: manifest.path.parentDirectory)
let parts =
"""
dependencies: [
"Logging",
.product(name: "Foo", package: "fooPkg", moduleAliases: [
"Logging": "FooLogging"
]),
.product(name: "Bar", package: "barPkg", moduleAliases: [
"Logging": "BarLogging"
])
]
"""
let trimmedContents = contents.components(separatedBy: CharacterSet.whitespacesAndNewlines)
let trimmedParts = parts.components(separatedBy: CharacterSet.whitespacesAndNewlines)
let isContained = trimmedParts.allSatisfy(trimmedContents.contains(_:))
XCTAssertTrue(isContained)
try testManifestWritingRoundTrip(manifestContents: contents, toolsVersion: .v5_8)
}
}
| apache-2.0 | 6a5722e1b011d2e97e9c577038ae1acd | 43.94685 | 304 | 0.518679 | 5.909161 | false | true | false | false |
overtake/TelegramSwift | Telegram-Mac/InstantPageImageItem.swift | 1 | 2666 | //
// InstantPageImageItem.swift
// Telegram
//
// Created by Mikhail Filimonov on 12/12/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import Postbox
import TelegramCore
protocol InstantPageImageAttribute {
}
struct InstantPageMapAttribute: InstantPageImageAttribute {
let zoom: Int32
let dimensions: CGSize
}
final class InstantPageImageItem: InstantPageItem {
let hasLinks: Bool = false
let isInteractive: Bool
let separatesTiles: Bool = false
func linkSelectionViews() -> [InstantPageLinkSelectionView] {
return []
}
var frame: CGRect
let webPage: TelegramMediaWebpage
let media: InstantPageMedia
let attributes: [InstantPageImageAttribute]
var medias: [InstantPageMedia] {
return [self.media]
}
let roundCorners: Bool
let fit: Bool
let wantsView: Bool = true
init(frame: CGRect, webPage: TelegramMediaWebpage, media: InstantPageMedia, attributes: [InstantPageImageAttribute] = [], interactive: Bool, roundCorners: Bool, fit: Bool) {
self.frame = frame
self.webPage = webPage
self.media = media
self.isInteractive = interactive
self.attributes = attributes
self.roundCorners = roundCorners
self.fit = fit
}
func view(arguments: InstantPageItemArguments, currentExpandedDetails: [Int : Bool]?) -> (InstantPageView & NSView)? {
let viewArguments: InstantPageMediaArguments
if let _ = media.media as? TelegramMediaMap, let attribute = attributes.first as? InstantPageMapAttribute {
viewArguments = .map(attribute)
} else {
viewArguments = .image(interactive: self.isInteractive, roundCorners: self.roundCorners, fit: self.fit)
}
return InstantPageMediaView(context: arguments.context, media: media, arguments: viewArguments)
}
func matchesAnchor(_ anchor: String) -> Bool {
return false
}
func matchesView(_ node: InstantPageView) -> Bool {
if let node = node as? InstantPageMediaView {
return node.media == self.media
} else {
return false
}
}
func distanceThresholdGroup() -> Int? {
return 1
}
func distanceThresholdWithGroupCount(_ count: Int) -> CGFloat {
if count > 3 {
return 400.0
} else {
return CGFloat.greatestFiniteMagnitude
}
}
func drawInTile(context: CGContext) {
}
func linkSelectionRects(at point: CGPoint) -> [CGRect] {
return []
}
}
| gpl-2.0 | 208d2bd01e33cc7d69583d9091506e0b | 24.873786 | 177 | 0.633771 | 4.810469 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatUnreadRowItem.swift | 1 | 2919 | //
// ChatUnreadRowItem.swift
// Telegram-Mac
//
// Created by keepcoder on 15/09/16.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import InAppSettings
import Postbox
class ChatUnreadRowItem: ChatRowItem {
override var height: CGFloat {
return 32
}
override var canBeAnchor: Bool {
return false
}
public var text:NSAttributedString;
override init(_ initialSize:NSSize, _ chatInteraction:ChatInteraction, _ context: AccountContext, _ entry:ChatHistoryEntry, _ downloadSettings: AutomaticMediaDownloadSettings, theme: TelegramPresentationTheme) {
let titleAttr:NSMutableAttributedString = NSMutableAttributedString()
let _ = titleAttr.append(string: strings().messagesUnreadMark, color: theme.colors.grayText, font: .normal(.text))
text = titleAttr.copy() as! NSAttributedString
super.init(initialSize,chatInteraction,entry, downloadSettings, theme: theme)
}
override var messageIndex:MessageIndex? {
switch entry {
case .UnreadEntry(let index, _, _):
return index
default:
break
}
return super.messageIndex
}
override var instantlyResize: Bool {
return true
}
override func viewClass() -> AnyClass {
return ChatUnreadRowView.self
}
}
private class ChatUnreadRowView: TableRowView {
private var text:TextNode = TextNode()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.layerContentsRedrawPolicy = .onSetNeedsDisplay
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ dirtyRect: NSRect) {
// Drawing code here.
}
override func updateColors() {
layer?.backgroundColor = .clear
}
override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
needsDisplay = true
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
ctx.setFillColor(theme.colors.grayBackground.cgColor)
ctx.fill(NSMakeRect(0, 6, frame.width, frame.height - 12))
if let item = self.item as? ChatUnreadRowItem {
let (layout, apply) = TextNode.layoutText(maybeNode: text, item.text, nil, 1, .end, NSMakeSize(NSWidth(self.frame), NSHeight(self.frame)), nil,false, .left)
apply.draw(NSMakeRect(round((NSWidth(layer.bounds) - layout.size.width)/2.0), round((NSHeight(layer.bounds) - layout.size.height)/2.0), layout.size.width, layout.size.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor)
}
}
deinit {
var bp:Int = 0
bp += 1
}
}
| gpl-2.0 | 8c9c202f6c18b6ff8ffd8fb2fd31464b | 27.057692 | 270 | 0.635709 | 4.691318 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/WordPressShareExtension/SharedCoreDataStack.swift | 2 | 13559 | import Foundation
import CoreData
import WordPressKit
/// NSPersistentContainer subclass that defaults to the shared container directory
///
final class SharedPersistentContainer: NSPersistentContainer {
internal override class func defaultDirectoryURL() -> URL {
var url = super.defaultDirectoryURL()
if let newURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: WPAppGroupName) {
url = newURL
}
return url
}
}
class SharedCoreDataStack {
// MARK: - Private Properties
fileprivate let modelName: String
fileprivate lazy var storeContainer: SharedPersistentContainer = {
let container = SharedPersistentContainer(name: self.modelName)
container.loadPersistentStores { (storeDescription, error) in
if let error = error as NSError? {
DDLogError("Error loading persistent stores: \(error), \(error.userInfo)")
}
}
return container
}()
// MARK: - Public Properties
/// Returns the managed context associated with the main queue
///
lazy var managedContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()
// MARK: - Initializers
/// Initialize the SharedPersistentContainer using the standard Extensions model.
///
convenience init() {
self.init(modelName: Constants.sharedModelName)
}
/// Initialize the core data stack with the given model name.
///
/// This initializer is meant for testing. You probably want to use the convenience `init()` that uses the standard Extensions model
///
/// - Parameters:
/// - modelName: Name of the model to initialize the SharedPersistentContainer with.
///
init(modelName: String) {
self.modelName = modelName
}
// MARK: - Public Funcntions
/// Commit unsaved changes (if any exist) using the main queue's managed context
///
func saveContext() {
guard managedContext.hasChanges else {
return
}
do {
try managedContext.save()
} catch let error as NSError {
DDLogError("Error saving context: \(error), \(error.userInfo)")
}
}
}
// MARK: - Persistence Helpers - Fetching
extension SharedCoreDataStack {
/// Fetches the group ID for the provided session ID.
///
/// - Parameter sessionID: the session ID
/// - Returns: group ID or nil if session does not have an associated group
///
func fetchGroupID(for sessionID: String) -> String? {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "UploadOperation")
request.predicate = NSPredicate(format: "(backgroundSessionIdentifier == %@)", sessionID)
request.fetchLimit = 1
guard let results = (try? managedContext.fetch(request)) as? [UploadOperation], let groupID = results.first?.groupID else {
return nil
}
return groupID
}
/// Fetch the post upload op for the provided managed object ID string
///
/// - Parameter objectID: Managed object ID string for a given post upload op
/// - Returns: PostUploadOperation or nil
///
func fetchPostUploadOp(withObjectID objectID: String) -> PostUploadOperation? {
guard let storeCoordinator = managedContext.persistentStoreCoordinator,
let url = URL(string: objectID),
let managedObjectID = storeCoordinator.managedObjectID(forURIRepresentation: url) else {
return nil
}
return fetchPostUploadOp(withObjectID: managedObjectID)
}
/// Fetch the post upload op for the provided managed object ID
///
/// - Parameter postUploadOpObjectID: Managed object ID for a given post upload op
/// - Returns: PostUploadOperation or nil
///
func fetchPostUploadOp(withObjectID postUploadOpObjectID: NSManagedObjectID) -> PostUploadOperation? {
var postUploadOp: PostUploadOperation?
do {
postUploadOp = try managedContext.existingObject(with: postUploadOpObjectID) as? PostUploadOperation
} catch {
DDLogError("Error loading PostUploadOperation Object with ID: \(postUploadOpObjectID)")
}
return postUploadOp
}
/// Fetch the upload op that represents a post for a given group ID.
///
/// NOTE: There will only ever be one post associated with a group of upload ops.
///
/// - Parameter groupID: group ID for a set of upload ops
/// - Returns: post PostUploadOperation or nil
///
func fetchPostUploadOp(for groupID: String) -> PostUploadOperation? {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PostUploadOperation")
request.predicate = NSPredicate(format: "(groupID == %@)", groupID)
request.fetchLimit = 1
guard let results = (try? managedContext.fetch(request)) as? [PostUploadOperation] else {
return nil
}
return results.first
}
/// Fetch the media upload ops for a given group ID.
///
/// - Parameter groupID: group ID for a set of upload ops
/// - Returns: An array of MediaUploadOperations or nil
///
func fetchMediaUploadOps(for groupID: String) -> [MediaUploadOperation]? {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MediaUploadOperation")
request.predicate = NSPredicate(format: "(groupID == %@)", groupID)
guard let results = (try? managedContext.fetch(request)) as? [MediaUploadOperation] else {
DDLogError("Failed to fetch MediaUploadOperation for group ID: \(groupID)")
return nil
}
return results
}
/// Fetch the media upload op that matches the provided filename and background session ID
///
/// - Parameters:
/// - fileName: the name of the local (and remote) file associated with a upload op
/// - sessionID: background session ID
/// - Returns: MediaUploadOperation or nil
///
func fetchMediaUploadOp(for fileName: String, with sessionID: String) -> MediaUploadOperation? {
guard let fileNameWithoutExtension = URL(string: fileName)?.deletingPathExtension().lastPathComponent else {
return nil
}
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MediaUploadOperation")
request.predicate = NSPredicate(format: "(fileName BEGINSWITH %@ AND backgroundSessionIdentifier == %@)", fileNameWithoutExtension.lowercased(), sessionID)
request.fetchLimit = 1
guard let results = (try? managedContext.fetch(request)) as? [MediaUploadOperation] else {
return nil
}
return results.first
}
/// Fetch the post and media upload ops for a given URLSession taskIdentifier.
///
/// NOTE: Because the WP API allows us to upload multiple media files in a single request, there
/// will most likely be multiple upload ops for a given task id.
///
/// - Parameters:
/// - taskIdentifier: the taskIdentifier from a URLSessionTask
/// - sessionID: background session ID
/// - Returns: An array of UploadOperations or nil
///
func fetchSessionUploadOps(for taskIdentifier: Int, with sessionID: String) -> [UploadOperation]? {
var uploadOps: [UploadOperation]?
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "UploadOperation")
request.predicate = NSPredicate(format: "(backgroundSessionTaskID == %d AND backgroundSessionIdentifier == %@)", taskIdentifier, sessionID)
do {
uploadOps = try managedContext.fetch(request) as! [MediaUploadOperation]
} catch {
DDLogError("Failed to fetch MediaUploadOperation: \(error)")
}
return uploadOps
}
}
// MARK: - Persistence Helpers - Saving and Updating
extension SharedCoreDataStack {
/// Updates the status using the given uploadOp's ObjectID.
///
/// - Parameters:
/// - status: New status
/// - uploadOpObjectID: Managed object ID for a given upload op
///
func updateStatus(_ status: UploadOperation.UploadStatus, forUploadOpWithObjectID uploadOpObjectID: NSManagedObjectID) {
var uploadOp: UploadOperation?
do {
uploadOp = try managedContext.existingObject(with: uploadOpObjectID) as? UploadOperation
} catch {
DDLogError("Error setting \(status.stringValue) status for UploadOperation Object with ID: \(uploadOpObjectID) — could not fetch object.")
return
}
uploadOp?.currentStatus = status
saveContext()
}
/// Saves a new media upload operation with the provided values
///
/// - Parameters:
/// - remoteMedia: RemoteMedia object containing the values to persist
/// - sessionID: background session ID
/// - groupIdentifier: group ID for a set of upload ops
/// - siteID: New site ID
/// - status: New status
/// - Returns: Managed object ID of newly saved media upload operation object
///
func saveMediaOperation(_ remoteMedia: RemoteMedia, sessionID: String, groupIdentifier: String, siteID: NSNumber, with status: UploadOperation.UploadStatus) -> NSManagedObjectID {
let mediaUploadOp = MediaUploadOperation(context: managedContext)
mediaUploadOp.updateWithMedia(remote: remoteMedia)
mediaUploadOp.backgroundSessionIdentifier = sessionID
mediaUploadOp.groupID = groupIdentifier
mediaUploadOp.created = NSDate()
mediaUploadOp.currentStatus = status
mediaUploadOp.siteID = siteID.int64Value
saveContext()
return mediaUploadOp.objectID
}
/// Updates the remote media URL and remote media ID on an upload op that corresponds with the provided
/// file name. If a parameter is nil, that specific param will not be updated.
///
/// Note: We are searching for the upload op using a filename because a given task ID can have
/// multiple files associated with it.
///
/// - Parameters:
/// - fileName: the fileName from a URLSessionTask
/// - sessionID: background session ID
/// - remoteMediaID: remote media ID
/// - remoteURL: remote media URL string
///
func updateMediaOperation(for fileName: String, with sessionID: String, remoteMediaID: Int64?, remoteURL: String?, width: Int32?, height: Int32?) {
guard let mediaUploadOp = fetchMediaUploadOp(for: fileName, with: sessionID) else {
DDLogError("Error loading UploadOperation Object with File Name: \(fileName)")
return
}
if let remoteMediaID = remoteMediaID {
mediaUploadOp.remoteMediaID = remoteMediaID
}
if let width = width {
mediaUploadOp.width = width
}
if let height = height {
mediaUploadOp.height = height
}
mediaUploadOp.remoteURL = remoteURL
saveContext()
}
/// Saves a new post upload operation with the provided values
///
/// - Parameters:
/// - remotePost: RemotePost object containing the values to persist.
/// - groupIdentifier: group ID for a set of upload ops
/// - status: New status
/// - Returns: Managed object ID of newly saved post upload operation object
///
func savePostOperation(_ remotePost: RemotePost, groupIdentifier: String, with status: UploadOperation.UploadStatus) -> NSManagedObjectID {
let postUploadOp = PostUploadOperation(context: managedContext)
postUploadOp.updateWithPost(remote: remotePost)
postUploadOp.groupID = groupIdentifier
postUploadOp.created = NSDate()
postUploadOp.currentStatus = status
saveContext()
return postUploadOp.objectID
}
/// Update an existing post upload operation with a new status and remote post ID
///
/// - Parameters:
/// - status: New status
/// - remotePostID: New remote post ID
/// - postUploadOpObjectID: Managed object ID for a given post upload op
///
func updatePostOperation(with status: UploadOperation.UploadStatus, remotePostID: Int64, forPostUploadOpWithObjectID postUploadOpObjectID: NSManagedObjectID) {
guard let postUploadOp = (try? managedContext.existingObject(with: postUploadOpObjectID)) as? PostUploadOperation else {
DDLogError("Error loading PostUploadOperation Object with ID: \(postUploadOpObjectID)")
return
}
postUploadOp.currentStatus = status
postUploadOp.remotePostID = remotePostID
saveContext()
}
/// Update an existing upload operations with a new background session task ID
///
/// - Parameters:
/// - taskID: New background session task ID
/// - uploadOpObjectID: Managed object ID for a given upload op
///
func updateTaskID(_ taskID: NSNumber, forUploadOpWithObjectID uploadOpObjectID: NSManagedObjectID) {
var uploadOp: UploadOperation?
do {
uploadOp = try managedContext.existingObject(with: uploadOpObjectID) as? UploadOperation
} catch {
DDLogError("Error loading UploadOperation Object with ID: \(uploadOpObjectID)")
return
}
uploadOp?.backgroundSessionTaskID = taskID.int32Value
saveContext()
}
}
// MARK: - Constants
extension SharedCoreDataStack {
struct Constants {
static let sharedModelName = "Extensions"
}
}
| gpl-2.0 | 5ef350329e35f7b7d258b38fbdcbf688 | 38.99115 | 183 | 0.665486 | 5.459928 | false | false | false | false |
shawnirvin/Terminal-iOS-Swift | Terminal/Models/DefaultsFunction.swift | 1 | 1935 | //
// DefaultsFunction.swift
// Terminal
//
// Created by Shawn Irvin on 12/4/15.
// Copyright © 2015 Shawn Irvin. All rights reserved.
//
import Foundation
class DefaultsFunction: Function, Helpful {
init() {
super.init(identifier: "^defaults (write \\S+.*|read \\S+.*|restore)", name: "defaults")
}
override func execute(command: Command, completion: (response: String?) -> Void) {
if command.rawValue.lowercaseString == "defaults restore" {
TerminalViewController.currentInstance.terminalTextView.getInput("Type 1 to confirm, 0 to cancel: ", inputType: .Normal) { input in
var output = ""
if input == "1" {
Setting.restoreDefaults()
output = "Defaults restored"
}
else {
output = "Restore cancelled"
}
completion(response: output)
}
return
}
else {
let action = command.elements[1]
let term = command.elements[2]
var output: String?
if action == "read" {
if let value = Setting.defaultForSettingType(SettingType(rawValue: term)) {
output = value.description
}
else {
output = "Invalid default"
}
}
else if action == "write" {
if term == "time" {
let stringValue = NSString(string: command.elements[3])
let value = stringValue.boolValue
Setting.setDefaultForSettingType(value, type: SettingType(rawValue: term))
}
}
completion(response: output)
}
}
func help() -> String {
return ""
}
}
| mit | 7d9fa47a47fb24e1d91fda2e28c7676c | 30.193548 | 143 | 0.481386 | 5.171123 | false | false | false | false |
pauljohanneskraft/Math | CoreMath/Classes/Functions/Zeros.swift | 1 | 4697 | //
// Zeros.swift
// Math
//
// Created by Paul Kraft on 18.12.17.
// Copyright © 2017 pauljohanneskraft. All rights reserved.
//
import Foundation
extension Double {
public static var floatLeastNonzeroMagnitude: Double {
return Double(Float.leastNonzeroMagnitude)
}
}
extension Function {
public func newtonsMethod(at x: Double, maxCount: Int = 1_000,
tolerance: Double = .floatLeastNonzeroMagnitude) -> Double? {
let derivative = self.derivative
var x = x
for _ in 0..<maxCount {
let y = call(x: x)
guard abs(y) > tolerance else { return x }
let dy = derivative.call(x: x)
x -= y / dy
}
return nil
}
/*
public func roots(in range: SamplingRange, alreadyFound: Set<Double> = [])
-> (roots: Set<Double>, result: Function) {
print("checking for roots", self)
guard !(self is Constant) else { return ([], self) }
var zeros = Set<Double>()
var function: Function = self
range.forEach { x in
guard let root = Double(guessZero(at: x).reducedDescription),
root.isReal, !alreadyFound.contains(root)
else { return }
zeros.insert(findZeroUsingFloatAccuracy(at: root))
function = function / PolynomialFunction(Polynomial([-root, 1]))
let functionZeros = function.roots(in: range, alreadyFound: alreadyFound)
zeros.formUnion(functionZeros.roots)
function = functionZeros.result
}
print("found", zeros)
return (zeros, function)
}
*/
public func secantMethod(x0: Double, x1: Double, maxIterations: Int = 1_000,
tolerance: Double = .floatLeastNonzeroMagnitude) -> Double {
var x0 = x0, x1 = x1, y0 = call(x: x0)
for _ in 0..<maxIterations {
let y1 = call(x: x1)
guard y1.isReal else { return x0 }
guard abs(y1) > tolerance else { return x1 }
let prevX1 = x1
x1 -= y1 * (x1 - x0) / (y1 - y0)
x0 = prevX1
y0 = y1
}
return x1
}
public func bisectionMethod(range: ClosedRange<Double>, maxIterations: Int = 10_000,
tolerance: Double = .floatLeastNonzeroMagnitude) -> ClosedRange<Double> {
guard maxIterations > 1, range.length > tolerance else { return range }
let midpoint = range.midpoint
let y = call(x: midpoint)
guard abs(y) != 0 else { return midpoint...midpoint }
let isEqual = (range.lowerBound.sign == y.sign)
return bisectionMethod(range: isEqual ? midpoint...range.upperBound : range.lowerBound...midpoint,
maxIterations: maxIterations - 1, tolerance: tolerance)
}
public func findZeroUsingFloatAccuracy(at doubleX: Double) -> Double {
let floatX = Double(Float(doubleX))
let floatY = abs(call(x: floatX))
let doubleY = abs(call(x: doubleX))
return doubleY < floatY ? doubleX : floatX
}
public func findZeroUsingFloatAccuracy(range: ClosedRange<Double>) -> Double {
let newRange = Float(range.lowerBound)...Float(range.upperBound)
guard !newRange.isPoint else {
return findZeroUsingFloatAccuracy(at: range.midpoint)
}
let a = Double(newRange.lowerBound), ay = abs(call(x: a))
let b = Double(newRange.midpoint ), by = abs(call(x: b))
let c = Double(newRange.upperBound), cy = abs(call(x: c))
if ay < by {
return ay < cy ? a : c
} else {
return by < cy ? b : c
}
}
}
extension ClosedRange where Bound: FixedWidthInteger {
public var midpoint: Bound {
let (value, overflow) = upperBound.addingReportingOverflow(lowerBound)
guard overflow else { return value }
let rest = (upperBound & 1) + (lowerBound & 1)
return (upperBound >> 1) + (lowerBound >> 1) + (rest >> 1)
}
public var length: Bound {
let sub = upperBound.subtractingReportingOverflow(lowerBound)
return sub.overflow ? Bound.max : sub.partialValue
}
public var isPoint: Bool {
return upperBound == lowerBound
}
}
extension ClosedRange where Bound: FloatingPoint {
public var midpoint: Bound {
return (upperBound + lowerBound) / 2
}
public var length: Bound {
return upperBound - lowerBound
}
public var isPoint: Bool {
return upperBound == lowerBound
}
}
| mit | daf2d278fd300391192ef9aee0d9f80b | 33.028986 | 106 | 0.574532 | 4.340111 | false | false | false | false |
forgot/FAAlertController | Source/FAAlertAction.swift | 1 | 1373 | //
// FAAlertAction.swift
// FAPlacemarkPicker
//
// Created by Jesse Cox on 8/20/16.
// Copyright © 2016 Apprhythmia LLC. All rights reserved.
//
import UIKit
protocol FAAlertActionDelegate {
func didPerformAction(_ action: FAAlertAction)
}
public enum FAAlertActionStyle : Int {
case `default`
case cancel
case destructive
}
public class FAAlertAction: NSObject {
public var title: String?
public let style: FAAlertActionStyle
public var handler: ((FAAlertAction) -> ())?
var isPreferredAction = false
var isEnabled = true
var delegate: FAAlertActionDelegate?
public init(title: String?, style: FAAlertActionStyle, handler: ((FAAlertAction) -> Void)? = nil) {
guard let _title = title else {
preconditionFailure("Actions added to FAAlertController must have a title")
}
self.title = _title
self.style = style
self.handler = handler
let button = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.text = title
button.addTarget(nil, action: #selector(self.performAction), for: .touchUpInside)
}
@objc func performAction() {
if let _handler = handler {
_handler(self)
}
delegate?.didPerformAction(self)
}
}
| mit | 23167cdee966544f2bf455cad1e36a5c | 25.384615 | 103 | 0.645044 | 4.666667 | false | false | false | false |
VikingDen/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Settings/SettingsPrivacyViewController.swift | 24 | 4971 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class SettingsPrivacyViewController: AATableViewController {
// MARK: -
// MARK: Private vars
private let CellIdentifier = "CellIdentifier"
private var authSessions: [ARApiAuthSession]?
// MARK: -
// MARK: Constructors
init() {
super.init(style: UITableViewStyle.Grouped)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("PrivacyTitle", comment: "Controller title")
tableView.registerClass(CommonCell.self, forCellReuseIdentifier: CellIdentifier)
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
execute(Actor.loadSessionsCommand(), successBlock: { (val) -> Void in
var list = val as! JavaUtilList
self.authSessions = []
for i in 0..<list.size() {
self.authSessions!.append(list.getWithInt(jint(i)) as! ARApiAuthSession)
}
self.tableView.reloadData()
}, failureBlock: nil)
}
// MARK: -
// MARK: Getters
private func terminateSessionsCell(indexPath: NSIndexPath) -> CommonCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell
cell.setContent(NSLocalizedString("PrivacyTerminate", comment: "Terminate action"))
cell.style = .Normal
// cell.showTopSeparator()
// cell.showBottomSeparator()
return cell
}
private func sessionsCell(indexPath: NSIndexPath) -> CommonCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell
var session = authSessions![indexPath.row]
cell.setContent(session.getDeviceTitle())
cell.style = .Normal
// if (indexPath.row == 0) {
// cell.showTopSeparator()
// } else {
// cell.hideTopSeparator()
// }
// cell.showBottomSeparator()
return cell
}
// MARK: -
// MARK: UITableView Data Source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if authSessions != nil {
if count(authSessions!) > 0 {
return 2
}
}
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 1 {
return count(authSessions!)
}
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 && indexPath.row == 0 {
return terminateSessionsCell(indexPath)
} else if (indexPath.section == 1) {
return sessionsCell(indexPath)
}
return UITableViewCell()
}
func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section > 0 { return nil }
return NSLocalizedString("PrivacyTerminateHint", comment: "Terminate hint")
}
// MARK: -
// MARK: UITableView Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.section == 0 {
execute(Actor.terminateAllSessionsCommand())
} else if (indexPath.section == 1) {
execute(Actor.terminateSessionCommandWithId(authSessions![indexPath.row].getId()), successBlock: { (val) -> Void in
self.execute(Actor.loadSessionsCommand(), successBlock: { (val) -> Void in
var list = val as! JavaUtilList
self.authSessions = []
for i in 0..<list.size() {
self.authSessions!.append(list.getWithInt(jint(i)) as! ARApiAuthSession)
}
self.tableView.reloadData()
}, failureBlock: nil)
}, failureBlock: nil)
}
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = MainAppTheme.list.sectionColor
}
func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = MainAppTheme.list.hintColor
}
}
| mit | 15514333e968ad384d74cc93d4e4f3fd | 34.507143 | 127 | 0.617381 | 5.333691 | false | false | false | false |
apple/swift | benchmark/single-source/Memset.swift | 10 | 947 | //===--- Memset.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let benchmarks =
BenchmarkInfo(
name: "Memset",
runFunction: run_Memset,
tags: [.validation, .unstable])
@inline(never)
func memset(_ a: inout [Int], _ c: Int) {
for i in 0..<a.count {
a[i] = c
}
}
@inline(never)
public func run_Memset(_ n: Int) {
var a = [Int](repeating: 0, count: 10_000)
for _ in 1...50*n {
memset(&a, 1)
memset(&a, 0)
}
check(a[87] == 0)
}
| apache-2.0 | 70fb1722c4d515b41efeff9aef2ce47f | 25.305556 | 80 | 0.551214 | 3.803213 | false | false | false | false |
lorentey/swift | test/attr/attr_originally_definedin_backward_compatibility.swift | 3 | 2960 | // REQUIRES: OS=macosx
//
// RUN: %empty-directory(%t)
//
// -----------------------------------------------------------------------------
// --- Prepare SDK (.swiftmodule).
// RUN: %empty-directory(%t/SDK)
//
// --- Build original high level framework.
// RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule
// RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \
// RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \
// RUN: %S/Inputs/SymbolMove/HighLevelOriginal.swift -Xlinker -install_name -Xlinker @rpath/HighLevel.framework/HighLevel -enable-library-evolution
// --- Build an executable using the original high level framework
// RUN: %target-build-swift -emit-executable %s -g -o %t/HighlevelRunner -F %t/SDK/Frameworks/ -framework HighLevel \
// RUN: -Xlinker -rpath -Xlinker %t/SDK/Frameworks
// --- Run the executable
// RUN: %t/HighlevelRunner | %FileCheck %s -check-prefix=BEFORE_MOVE
// --- Build low level framework.
// RUN: mkdir -p %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule
// RUN: %target-build-swift-dylib(%t/SDK/Frameworks/LowLevel.framework/LowLevel) -module-name LowLevel -emit-module \
// RUN: -emit-module-path %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule/%module-target-triple.swiftmodule \
// RUN: %S/Inputs/SymbolMove/LowLevel.swift -Xlinker -install_name -Xlinker @rpath/LowLevel.framework/LowLevel -enable-library-evolution
// --- Build high level framework.
// RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule
// RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \
// RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \
// RUN: %S/Inputs/SymbolMove/HighLevel.swift -F %t/SDK/Frameworks -Xlinker -reexport_framework -Xlinker LowLevel -enable-library-evolution
// --- Run the executable
// RUN: %t/HighlevelRunner | %FileCheck %s -check-prefix=AFTER_MOVE
import HighLevel
printMessage()
printMessageMoved()
// BEFORE_MOVE: Hello from HighLevel
// BEFORE_MOVE: Hello from HighLevel
// AFTER_MOVE: Hello from LowLevel
// AFTER_MOVE: Hello from LowLevel
let e = Entity()
print(e.location())
// BEFORE_MOVE: Entity from HighLevel
// AFTER_MOVE: Entity from LowLevel
print(CandyBox(Candy()).ItemKind)
// BEFORE_MOVE: candy
// AFTER_MOVE: candy
print(CandyBox(Candy()).shape())
// BEFORE_MOVE: square
// AFTER_MOVE: round
print(LanguageKind.Cpp.rawValue)
// BEFORE_MOVE: -1
// AFTER_MOVE: 1
print("\(Vehicle().currentSpeed)")
// BEFORE_MOVE: -40
// AFTER_MOVE: 40
class Bicycle: Vehicle {}
let bicycle = Bicycle()
bicycle.currentSpeed = 15.0
print("\(bicycle.currentSpeed)")
// BEFORE_MOVE: 15.0
// AFTER_MOVE: 15.0
| apache-2.0 | 31782b1bd95ea5d5b7465381857e8a7d | 38.466667 | 151 | 0.720608 | 3.579202 | false | false | false | false |
sebbean/ExSwift | ExSwiftTests/DoubleExtensionsTests.swift | 25 | 4054 | //
// DoubleExtensionsTests.swift
// ExSwift
//
// Created by pNre on 10/07/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Quick
import Nimble
class DoubleExtensionsSpec: QuickSpec {
override func spec() {
/**
* Double.abs
*/
it("abs") {
expect(Double(0).abs()) == Double(0)
expect(Double(-1).abs()).to(beCloseTo(1, within: 0.001))
expect(Double(1).abs()).to(beCloseTo(1, within: 0.001))
expect(Double(-111.2).abs()).to(beCloseTo(111.2, within: 0.001))
expect(Double(111.2).abs()).to(beCloseTo(111.2, within: 0.001))
}
/**
* Double.sqrt
*/
it("sqrt") {
expect(Double(0).sqrt()) == Double(0)
expect(Double(4).sqrt()).to(beCloseTo(2, within: 0.001))
expect(Double(111.2).sqrt()).to(beCloseTo(sqrt(111.2), within: 0.001))
expect(isnan(Double(-10).sqrt())).to(beTrue())
}
/**
* Double.floor
*/
it("floor") {
expect(Double(0).floor()) == Double(0)
expect(Double(4.99999999).floor()).to(beCloseTo(4, within: 0.001))
expect(Double(4.001).floor()).to(beCloseTo(4, within: 0.001))
expect(Double(4.5).floor()).to(beCloseTo(4, within: 0.001))
expect(Double(-4.99999999).floor()).to(beCloseTo(-5, within: 0.001))
expect(Double(-4.001).floor()).to(beCloseTo(-5, within: 0.001))
expect(Double(-4.5).floor()).to(beCloseTo(-5, within: 0.001))
}
/**
* Double.ceil
*/
it("ceil") {
expect(Double(0).ceil()) == Double(0)
expect(Double(4.99999999).ceil()).to(beCloseTo(5, within: 0.001))
expect(Double(4.001).ceil()).to(beCloseTo(5, within: 0.001))
expect(Double(4.5).ceil()).to(beCloseTo(5, within: 0.001))
expect(Double(-4.99999999).ceil()).to(beCloseTo(-4, within: 0.001))
expect(Double(-4.001).ceil()).to(beCloseTo(-4, within: 0.001))
expect(Double(-4.5).ceil()).to(beCloseTo(-4, within: 0.001))
}
/**
* Double.round
*/
it("round") {
expect(Double(0).round()) == Double(0)
expect(Double(4.99999999).round()).to(beCloseTo(5, within: 0.001))
expect(Double(4.001).round()).to(beCloseTo(4, within: 0.001))
expect(Double(4.5).round()).to(beCloseTo(5, within: 0.001))
expect(Double(4.3).round()).to(beCloseTo(4, within: 0.001))
expect(Double(4.7).round()).to(beCloseTo(5, within: 0.001))
expect(Double(-4.99999999).round()).to(beCloseTo(-5, within: 0.001))
expect(Double(-4.001).round()).to(beCloseTo(-4, within: 0.001))
expect(Double(-4.5).round()).to(beCloseTo(-5, within: 0.001))
}
/**
* Double.roundToNearest
*/
it("roundToNearest") {
expect(2.5.roundToNearest(0.3)).to(beCloseTo(2.4, within: 0.01))
expect(0.roundToNearest(0.3)).to(beCloseTo(0.0, within: 0.01))
expect(4.0.roundToNearest(2)).to(beCloseTo(4.0, within: 0.01))
expect(10.0.roundToNearest(3)).to(beCloseTo(9.0, within: 0.01))
expect(-2.0.roundToNearest(3)).to(beCloseTo(-3.0, within: 0.01))
}
/**
* Double.clamp
*/
it("clamp") {
expect(Double(0.25).clamp(0, 0.5)).to(beCloseTo(0.25, within: 0.01))
expect(Double(2).clamp(0, 0.5)).to(beCloseTo(0.5, within: 0.01))
expect(Double(-2).clamp(0, 0.5)).to(beCloseTo(0, within: 0.01))
}
}
}
| bsd-2-clause | 1570eea72c972fa3146078de2cdc4f44 | 31.432 | 82 | 0.47558 | 3.702283 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.