repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
nab0y4enko/PrettyFloatingMenuView
Example/AppDelegate.swift
1
2187
// // AppDelegate.swift // Example // // Created by Oleksii Naboichenko on 5/11/17. // Copyright © 2017 Oleksii Naboichenko. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
OscarSwanros/swift
test/refactoring/ConvertForceTryToTryCatch/for_loop.swift
4
315
func throwingFunc() throws -> [Int] { return [] } for num in try! throwingFunc() { let _ = num } // RUN: rm -rf %t.result && mkdir -p %t.result // RUN: %refactor -convert-to-do-catch -source-filename %s -pos=4:14 > %t.result/L5.swift // RUN: diff -u %S/Outputs/for_loop/L5.swift.expected %t.result/L5.swift
apache-2.0
natecook1000/swift-compiler-crashes
crashes-duplicates/13059-swift-sourcemanager-getmessage.swift
11
241
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for { case var { if true { protocol A { struct d { var b { class case ,
mit
qlongming/shppingCat
shoppingCart-master/shoppingCart/Classes/ShopCart/Controller/MSShoppingCartViewController.swift
1
9140
// // JFShoppingCartViewController.swift // shoppingCart // // Created by jianfeng on 15/11/17. // Copyright © 2015年 六阿哥. All rights reserved. // import UIKit class MSShoppingCartViewController: UIViewController { // MARK: - 属性 /// 已经添加进购物车的商品模型数组,初始化 var addGoodArray: [MSGoodModel]? { didSet { } } /// 总金额,默认0.00 var price: CFloat = 0.00 /// 商品列表cell的重用标识符 private let shoppingCarCellIdentifier = "shoppingCarCell" // MARK: - view生命周期 override func viewDidLoad() { super.viewDidLoad() // 准备UI prepareUI() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // 布局UI layoutUI() // 重新计算价格 reCalculateGoodCount() } /** 准备UI */ private func prepareUI() { // 标题 navigationItem.title = "购物车列表" // 导航栏左边返回 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "didTappedBackButton") // view背景颜色 view.backgroundColor = UIColor.whiteColor() // cell行高 tableView.rowHeight = 80 // 注册cell tableView.registerClass(MSShoppingCartCell.self, forCellReuseIdentifier: shoppingCarCellIdentifier) // 添加子控件 view.addSubview(tableView) view.addSubview(bottomView) bottomView.addSubview(selectButton) bottomView.addSubview(totalPriceLabel) bottomView.addSubview(buyButton) // 判断是否需要全选 for model in addGoodArray! { if model.selected != true { // 只要有一个不等于就不全选 selectButton.selected = false break } } } /** 布局UI */ private func layoutUI() { // 约束子控件 tableView.snp_makeConstraints { (make) -> Void in make.left.top.right.equalTo(0) make.bottom.equalTo(-49) } bottomView.snp_makeConstraints { (make) -> Void in make.left.bottom.right.equalTo(0) make.height.equalTo(49) } selectButton.snp_makeConstraints { (make) -> Void in make.left.equalTo(12) make.centerY.equalTo(bottomView.snp_centerY) } totalPriceLabel.snp_makeConstraints { (make) -> Void in make.center.equalTo(bottomView.snp_center) } buyButton.snp_makeConstraints { (make) -> Void in make.right.equalTo(-12) make.top.equalTo(9) make.width.equalTo(88) make.height.equalTo(30) } } // MARK: - 懒加载 /// tableView lazy var tableView: UITableView = { let tableView = UITableView() // 指定数据源和代理 tableView.dataSource = self tableView.delegate = self return tableView }() /// 底部视图 lazy var bottomView: UIView = { let bottomView = UIView() bottomView.backgroundColor = UIColor.whiteColor() return bottomView }() /// 底部多选、反选按钮 lazy var selectButton: UIButton = { let selectButton = UIButton(type: UIButtonType.Custom) selectButton.setImage(UIImage(named: "check_n"), forState: UIControlState.Normal) selectButton.setImage(UIImage(named: "check_y"), forState: UIControlState.Selected) selectButton.setTitle("多选\\反选", forState: UIControlState.Normal) selectButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal) selectButton.titleLabel?.font = UIFont.systemFontOfSize(12) selectButton.addTarget(self, action: "didTappedSelectButton:", forControlEvents: UIControlEvents.TouchUpInside) selectButton.selected = true selectButton.sizeToFit() return selectButton }() /// 底部总价Label lazy var totalPriceLabel: UILabel = { let totalPriceLabel = UILabel() let attributeText = NSMutableAttributedString(string: "总共价格:\(self.price)0") attributeText.setAttributes([NSForegroundColorAttributeName : UIColor.redColor()], range: NSMakeRange(5, attributeText.length - 5)) totalPriceLabel.attributedText = attributeText totalPriceLabel.sizeToFit() return totalPriceLabel }() /// 底部付款按钮 lazy var buyButton: UIButton = { let buyButton = UIButton(type: UIButtonType.Custom) buyButton.setTitle("付款", forState: UIControlState.Normal) buyButton.setBackgroundImage(UIImage(named: "button_cart_add"), forState: UIControlState.Normal) buyButton.layer.cornerRadius = 15 buyButton.layer.masksToBounds = true return buyButton }() } // MARK: - UITableViewDataSource, UITableViewDelegate数据、代理 extension MSShoppingCartViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return addGoodArray?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // 从缓存池创建cell,不成功就根据重用标识符和注册的cell新创建一个 let cell = tableView.dequeueReusableCellWithIdentifier(shoppingCarCellIdentifier, forIndexPath: indexPath) as! MSShoppingCartCell // cell取消选中效果 cell.selectionStyle = UITableViewCellSelectionStyle.None // 指定代理对象 cell.delegate = self // 传递模型 cell.goodModel = addGoodArray?[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { reCalculateGoodCount() } } // MARK: - view上的一些事件处理 extension MSShoppingCartViewController { /** 返回按钮 */ @objc private func didTappedBackButton() { dismissViewControllerAnimated(true, completion: nil) } /** 重新计算商品数量 */ private func reCalculateGoodCount() { // 遍历模型 for model in addGoodArray! { // 只计算选中的商品 if model.selected == true { price += Float(model.count) * (model.newPrice! as NSString).floatValue } } // 赋值价格 let attributeText = NSMutableAttributedString(string: "总共价格:\(self.price)0") attributeText.setAttributes([NSForegroundColorAttributeName : UIColor.redColor()], range: NSMakeRange(5, attributeText.length - 5)) totalPriceLabel.attributedText = attributeText // 清空price price = 0 // 刷新表格 tableView.reloadData() } /** 点击了多选按钮后的事件处理 - parameter button: 多选按钮 */ @objc private func didTappedSelectButton(button: UIButton) { selectButton.selected = !selectButton.selected for model in addGoodArray! { model.selected = selectButton.selected } // 重新计算总价 reCalculateGoodCount() // 刷新表格 tableView.reloadData() } } // MARK: - JFShoppingCartCellDelegate代理方法 extension MSShoppingCartViewController: MSShoppingCartCellDelegate { /** 当点击了cell中加、减按钮 - parameter cell: 被点击的cell - parameter button: 被点击的按钮 - parameter countLabel: 显示数量的label */ func shoppingCartCell(cell: MSShoppingCartCell, button: UIButton, countLabel: UILabel) { // 根据cell获取当前模型 guard let indexPath = tableView.indexPathForCell(cell) else { return } // 获取当前模型,添加到购物车模型数组 let model = addGoodArray![indexPath.row] if button.tag == 10 { if model.count < 1 { print("数量不能低于0") return } // 减 model.count-- countLabel.text = "\(model.count)" } else { // 加 model.count++ countLabel.text = "\(model.count)" } // 重新计算商品数量 reCalculateGoodCount() } /** 重新计算总价 */ func reCalculateTotalPrice() { reCalculateGoodCount() } }
apache-2.0
natecook1000/swift-compiler-crashes
crashes-duplicates/20510-swift-sourcemanager-getmessage.swift
11
217
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [ { init( ) { struct c { class A { class case ,
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/24304-swift-boundgenerictype-get.swift
9
207
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum S<T{class B<T where S=x.r{var:{l
mit
franciscocgoncalves/ToDoList
ToDoListAppTests/ToDoListAppTests.swift
1
916
// // ToDoListAppTests.swift // ToDoListAppTests // // Created by Francisco Gonçalves on 10/11/14. // Copyright (c) 2014 SINFO. All rights reserved. // import UIKit import XCTest class ToDoListAppTests: XCTestCase { 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
aatalyk/swift-algorithm-club
Topological Sort/Topological Sort.playground/Contents.swift
5
936
//: Playground - noun: a place where people can play import UIKit let graph = Graph() let node5 = graph.addNode("5") let node7 = graph.addNode("7") let node3 = graph.addNode("3") let node11 = graph.addNode("11") let node8 = graph.addNode("8") let node2 = graph.addNode("2") let node9 = graph.addNode("9") let node10 = graph.addNode("10") graph.addEdge(fromNode: node5, toNode: node11) graph.addEdge(fromNode: node7, toNode: node11) graph.addEdge(fromNode: node7, toNode: node8) graph.addEdge(fromNode: node3, toNode: node8) graph.addEdge(fromNode: node3, toNode: node10) graph.addEdge(fromNode: node11, toNode: node2) graph.addEdge(fromNode: node11, toNode: node9) graph.addEdge(fromNode: node11, toNode: node10) graph.addEdge(fromNode: node8, toNode: node9) // using depth-first search graph.topologicalSort() // also using depth-first search graph.topologicalSortAlternative() // Kahn's algorithm graph.topologicalSortKahn()
mit
Fenrikur/ef-app_ios
Eurofurence/Modules/News/Interactor/NewsViewModel.swift
1
1822
import EurofurenceModel import Foundation.NSIndexPath import UIKit.UIImage protocol NewsViewModel { var numberOfComponents: Int { get } func numberOfItemsInComponent(at index: Int) -> Int func titleForComponent(at index: Int) -> String func describeComponent(at indexPath: IndexPath, to visitor: NewsViewModelVisitor) func fetchModelValue(at indexPath: IndexPath, completionHandler: @escaping (NewsViewModelValue) -> Void) } enum NewsViewModelValue { case messages case announcement(AnnouncementIdentifier) case allAnnouncements case event(Event) } protocol NewsViewModelVisitor { func visit(_ userWidget: UserWidgetComponentViewModel) func visit(_ countdown: ConventionCountdownComponentViewModel) func visit(_ announcement: AnnouncementComponentViewModel) func visit(_ viewAllAnnouncements: ViewAllAnnouncementsComponentViewModel) func visit(_ event: EventComponentViewModel) } struct ConventionCountdownComponentViewModel: Hashable { var timeUntilConvention: String } struct AnnouncementComponentViewModel: Hashable { var title: String var detail: NSAttributedString var receivedDateTime: String var isRead: Bool } struct ViewAllAnnouncementsComponentViewModel: Hashable { var caption: String } struct EventComponentViewModel: Hashable { var startTime: String var endTime: String var eventName: String var location: String var isSponsorEvent: Bool var isSuperSponsorEvent: Bool var isFavourite: Bool var isArtShowEvent: Bool var isKageEvent: Bool var isDealersDenEvent: Bool var isMainStageEvent: Bool var isPhotoshootEvent: Bool } struct UserWidgetComponentViewModel: Hashable { var prompt: String var detailedPrompt: String var hasUnreadMessages: Bool }
mit
audiokit/AudioKitArchive
Examples/OSX/Swift/AudioKitDemo/AudioKitDemo/AnalysisViewController.swift
2
2807
// // AnalysisViewController.swift // AudioKitDemo // // Created by Nicholas Arner on 3/1/15. // Copyright (c) 2015 AudioKit. All rights reserved. // class AnalysisViewController: NSViewController { @IBOutlet var frequencyLabel: NSTextField! @IBOutlet var amplitudeLabel: NSTextField! @IBOutlet var noteNameWithSharpsLabel: NSTextField! @IBOutlet var noteNameWithFlatsLabel: NSTextField! var analyzer: AKAudioAnalyzer! let microphone = AKMicrophone() let noteFrequencies = [16.35,17.32,18.35,19.45,20.6,21.83,23.12,24.5,25.96,27.5,29.14,30.87] let noteNamesWithSharps = ["C", "C♯","D","D♯","E","F","F♯","G","G♯","A","A♯","B"] let noteNamesWithFlats = ["C", "D♭","D","E♭","E","F","G♭","G","A♭","A","B♭","B"] let analysisSequence = AKSequence() var updateAnalysis: AKEvent? override func viewDidLoad() { super.viewDidLoad() AKSettings.shared().audioInputEnabled = true analyzer = AKAudioAnalyzer(input: microphone.output) AKOrchestra.addInstrument(microphone) AKOrchestra.addInstrument(analyzer) analyzer.play() microphone.play() let analysisSequence = AKSequence() updateAnalysis = AKEvent { self.updateUI() analysisSequence.addEvent(self.updateAnalysis, afterDuration: 0.1) } analysisSequence.addEvent(updateAnalysis) analysisSequence.play() } func updateUI() { if (analyzer.trackedAmplitude.floatValue > 0.1) { frequencyLabel.stringValue = String(format: "%0.1f", analyzer.trackedFrequency.floatValue) var frequency = analyzer.trackedFrequency.floatValue while (frequency > Float(noteFrequencies[noteFrequencies.count-1])) { frequency = frequency / 2.0 } while (frequency < Float(noteFrequencies[0])) { frequency = frequency * 2.0 } var minDistance: Float = 10000.0 var index = 0 for (var i = 0; i < noteFrequencies.count; i++) { let distance = fabsf(Float(noteFrequencies[i]) - frequency) if (distance < minDistance){ index = i minDistance = distance } } let octave = Int(log2f(analyzer.trackedFrequency.floatValue / frequency)) var noteName = String(format: "%@%d", noteNamesWithSharps[index], octave) noteNameWithSharpsLabel.stringValue = noteName noteName = String(format: "%@%d", noteNamesWithFlats[index], octave) noteNameWithFlatsLabel.stringValue = noteName } amplitudeLabel.stringValue = String(format: "%0.2f", analyzer.trackedAmplitude.floatValue) } }
mit
bgerstle/wikipedia-ios
Wikipedia/Code/WMFTableOfContentsItem.swift
2
1647
// // WMFTableOfContentsItem.swift // Wikipedia // // Created by Brian Gerstle on 10/20/15. // Copyright © 2015 Wikimedia Foundation. All rights reserved. // import Foundation // MARK: - TOC Item Types public enum TableOfContentsItemType { case Primary case Secondary var titleFont: UIFont { get { switch (self) { case .Primary: return UIFont.wmf_tableOfContentsSectionFont() case .Secondary: return UIFont.wmf_tableOfContentsSubsectionFont() } } } var titleColor: UIColor { get { switch (self) { case .Primary: return UIColor.wmf_tableOfContentsSectionTextColor() case .Secondary: return UIColor.wmf_tableOfContentsSubsectionTextColor() } } } } public enum TableOfContentsBorderType { case Default case FullWidth case None } // MARK: - TOC Item public protocol TableOfContentsItem : NSObjectProtocol { var titleText: String { get } var itemType: TableOfContentsItemType { get } var borderType: TableOfContentsBorderType { get } var indentationLevel: UInt { get } func shouldBeHighlightedAlongWithItem(item: TableOfContentsItem) -> Bool } // MARK: - TOC Item Defaults extension TableOfContentsItem { public func shouldBeHighlightedAlongWithItem(item: TableOfContentsItem) -> Bool { return false } public var borderType: TableOfContentsBorderType { get { return TableOfContentsBorderType.Default } } public var indentationLevel: UInt { get { return 0 } } }
mit
chenyun122/StepIndicator
Package.swift
1
558
// swift-tools-version:5.3 // // Created by ChenYun on 2019/8/28. // Copyright © 2019 ChenYun. All rights reserved. // import PackageDescription let package = Package(name: "StepIndicator", platforms: [.iOS(.v8)], products: [.library(name: "StepIndicator", targets: ["StepIndicator"])], targets: [.target(name: "StepIndicator", path: "StepIndicator")], swiftLanguageVersions: [.v5])
mit
socialbanks/ios-wallet
SocialWallet/BaseVC.swift
1
3102
// // BaseVC.swift // SocialWallet // // Created by Mauricio de Oliveira on 5/4/15. // Copyright (c) 2015 SocialBanks. All rights reserved. // import UIKit class BaseVC: UIViewController { lazy var HUD:MBProgressHUD = { let tmpHUD:MBProgressHUD = MBProgressHUD(view: self.view) self.view.addSubview(tmpHUD) //tmpHUD.delegate = self tmpHUD.labelText = "Aguarde" tmpHUD.detailsLabelText = "Carregando dados..." //tmpHUD.square = true return tmpHUD }() //MARK: UI Functions func showLoading() { self.showNetWorkActivity() self.HUD.show(true) } func hideLoading() { self.hideNetWorkActivity() self.HUD.hide(true) } func showNetWorkActivity() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func hideNetWorkActivity() { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } override func viewDidLoad() { super.viewDidLoad() //self.removeLeftBarButtonTitle() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationItem.backBarButtonItem?.tintColor = UIColor.whiteColor() //self.removeLeftBarButtonTitle() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Navigation bar functions func setDefaultTitleLogo() { let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) logo.contentMode = .ScaleAspectFit logo.image = UIImage(named: "logo_socialbanks") self.navigationItem.titleView = logo } func setupLeftMenuButton() { let leftDrawerButton:MMDrawerBarButtonItem = MMDrawerBarButtonItem(target:self, action:"leftDrawerButtonPress") leftDrawerButton.tintColor = UIColor.whiteColor() self.navigationItem.leftBarButtonItem = leftDrawerButton } func leftDrawerButtonPress() { self.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) } func removeLeftBarButtonTitle() { self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: UIBarButtonItemStyle.Plain, target: self, action: nil) } func removeLeftBarButton() { self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: nil) } func instantiateViewControlerFromStoryboard(vcId: String, sbId: String) -> UIViewController { let mainStoryboard:UIStoryboard = UIStoryboard(name: sbId, bundle: nil) let vc:UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier(vcId) as! UIViewController return vc } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
mit
anlaital/Swan
Swan/Swan/CGSizeExtensions.swift
1
1147
// // CGSizeExtensions.swift // Swan // // Created by Antti Laitala on 19/11/15. // // import Foundation public func +(lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height) } public func +=(lhs: inout CGSize, rhs: CGSize) { lhs.width += rhs.width lhs.height += rhs.height } public func -(lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width - rhs.width, height: lhs.height - rhs.height) } public func -=(lhs: inout CGSize, rhs: CGSize) { lhs.width -= rhs.width lhs.height -= rhs.height } public func *(lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width * rhs.width, height: lhs.height * rhs.height) } public func *(lhs: CGSize, rhs: Double) -> CGSize { return CGSize(width: Double(lhs.width) * rhs, height: Double(lhs.height) * rhs) } public func /(lhs: CGSize, rhs: CGSize) -> CGSize { return CGSize(width: lhs.width / rhs.width, height: lhs.height / rhs.height) } public func /(lhs: CGSize, rhs: Double) -> CGSize { return CGSize(width: Double(lhs.width) / rhs, height: Double(lhs.height) / rhs) }
mit
shinobicontrols/iOS8-LevellingUp
LevellingUpTests/LevellingUpTests.swift
1
918
// // LevellingUpTests.swift // LevellingUpTests // // Created by Sam Davies on 17/03/2015. // Copyright (c) 2015 shinobicontrols. All rights reserved. // import UIKit import XCTest class LevellingUpTests: XCTestCase { 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
apache-2.0
Inquisitor0/LSB2
LSB2/Extensions/Character+Extensions.swift
1
310
// // Character+Extensions.swift // LSB2 // // Created by Alexander Kravchenko on 26.05.17. // Copyright © 2017 Askrav's Inc. All rights reserved. // import Foundation extension Character { var asciiValue: UInt32? { return String(self).unicodeScalars.filter{$0.isASCII}.first?.value } }
mit
CodeMath/iOS8_Swift_App_LeeDH
Example App/Example App/AppDelegate.swift
1
2150
// // AppDelegate.swift // Example App // // Created by 이동혁 on 2015. 4. 24.. // Copyright (c) 2015년 CodeMath. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
AnirudhDas/AniruddhaDas.github.io
RedBus/RedBus/Controller/FilterViewController.swift
1
6983
// // FilterViewController.swift // RedBus // // Created by Anirudh Das on 8/22/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import UIKit class FilterViewController: BaseViewController { @IBOutlet weak var bgView: UIView! @IBOutlet weak var ratingImg: UIImageView! @IBOutlet weak var ratingArrow: UIImageView! @IBOutlet weak var departureImg: UIImageView! @IBOutlet weak var departureArrowIng: UIImageView! @IBOutlet weak var fareImg: UIImageView! @IBOutlet weak var fareArrowImg: UIImageView! @IBOutlet weak var acImg: UIImageView! @IBOutlet weak var nonAcImg: UIImageView! @IBOutlet weak var seaterImg: UIImageView! @IBOutlet weak var sleeperImg: UIImageView! @IBOutlet weak var resetBtn: UIButton! @IBOutlet weak var cancelBtn: UIButton! @IBOutlet weak var ratingBtn: UIButton! @IBOutlet weak var departureTimeBtn: UIButton! @IBOutlet weak var fareBtn: UIButton! @IBOutlet weak var acBtn: UIButton! @IBOutlet weak var nonAcBtn: UIButton! @IBOutlet weak var seaterBtn: UIButton! @IBOutlet weak var sleeperBtn: UIButton! @IBOutlet weak var applyBtn: UIButton! var sortBy: SortBusesBy = .none var busFilterType = BusType(isAc: false, isNonAc: false, isSeater: false, isSleeper: false) var applyCompletionHandler: ((SortBusesBy, BusType) -> ())? override func viewDidLoad() { super.viewDidLoad() setupView() configureSortRadioButtonImage(isReset: false) configureFilterCheckBoxImage(isReset: false) } func setupView() { bgView.addShadow() resetBtn.addShadow() cancelBtn.addShadow() ratingBtn.addShadow() departureTimeBtn.addShadow() fareBtn.addShadow() acBtn.addShadow() nonAcBtn.addShadow() seaterBtn.addShadow() sleeperBtn.addShadow() applyBtn.addShadow() self.view.backgroundColor = UIColor.black.withAlphaComponent(0.7) } @IBAction func resetBtnClicked(_ sender: UIButton) { sortBy = .none busFilterType = BusType(isAc: false, isNonAc: false, isSeater: false, isSleeper: false) configureSortRadioButtonImage(isReset: true) configureFilterCheckBoxImage(isReset: true) } @IBAction func applyBtnClicked(_ sender: UIButton) { self.dismiss(animated: true, completion: { self.applyCompletionHandler?(self.sortBy, self.busFilterType) }) } @IBAction func cancelBtnClicked(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } @IBAction func ratingBtnClicked(_ sender: UIButton) { if sortBy == .ratingDescending { sortBy = .ratingAscending } else if sortBy == .ratingAscending { sortBy = .none } else { sortBy = .ratingDescending } configureSortRadioButtonImage(isReset: false) } @IBAction func departureTimeBtnClicked(_ sender: UIButton) { if sortBy == .departureTimeAscending { sortBy = .departureTimeDescending } else if sortBy == .departureTimeDescending { sortBy = .none } else { sortBy = .departureTimeAscending } configureSortRadioButtonImage(isReset: false) } @IBAction func fareBtnClicked(_ sender: UIButton) { if sortBy == .fareAscending { sortBy = .fareDescending } else if sortBy == .fareDescending { sortBy = .none } else { sortBy = .fareAscending } configureSortRadioButtonImage(isReset: false) } @IBAction func acBtnClicked(_ sender: UIButton) { busFilterType.isAc = busFilterType.isAc ? false : true configureFilterCheckBoxImage(isReset: false) } @IBAction func nonAcBtnClicked(_ sender: UIButton) { busFilterType.isNonAc = busFilterType.isNonAc ? false : true configureFilterCheckBoxImage(isReset: false) } @IBAction func seaterBtnClicked(_ sender: UIButton) { busFilterType.isSeater = busFilterType.isSeater ? false : true configureFilterCheckBoxImage(isReset: false) } @IBAction func sleeperBtnClicked(_ sender: UIButton) { busFilterType.isSleeper = busFilterType.isSleeper ? false : true configureFilterCheckBoxImage(isReset: false) } func configureSortRadioButtonImage(isReset: Bool) { func resetSortRadioButtonImage() { ratingImg.image = Constants.ratingDeselected ratingArrow.isHidden = true departureImg.image = Constants.depatureDeselected departureArrowIng.isHidden = true fareImg.image = Constants.fareDeselected fareArrowImg.isHidden = true } resetSortRadioButtonImage() if !isReset { switch sortBy { case .ratingAscending: ratingImg.image = Constants.ratingSelected ratingArrow.image = Constants.arrowUp ratingArrow.isHidden = false case .ratingDescending: ratingImg.image = Constants.ratingSelected ratingArrow.image = Constants.arrowDown ratingArrow.isHidden = false case .departureTimeAscending: departureImg.image = Constants.depatureSelected departureArrowIng.image = Constants.arrowUp departureArrowIng.isHidden = false case .departureTimeDescending: departureImg.image = Constants.depatureSelected departureArrowIng.image = Constants.arrowDown departureArrowIng.isHidden = false case .fareAscending: fareImg.image = Constants.fareSelected fareArrowImg.image = Constants.arrowUp fareArrowImg.isHidden = false case .fareDescending: fareImg.image = Constants.fareSelected fareArrowImg.image = Constants.arrowDown fareArrowImg.isHidden = false case .none: break } } } func configureFilterCheckBoxImage(isReset: Bool) { if isReset { acImg.image = Constants.acDeselected nonAcImg.image = Constants.nonACDeselected seaterImg.image = Constants.seaterDeselected sleeperImg.image = Constants.sleeperDeselected } else { acImg.image = busFilterType.isAc ? Constants.acSelected : Constants.acDeselected nonAcImg.image = busFilterType.isNonAc ? Constants.nonACSelected : Constants.nonACDeselected seaterImg.image = busFilterType.isSeater ? Constants.seaterSelected : Constants.seaterDeselected sleeperImg.image = busFilterType.isSleeper ? Constants.sleeperSelected : Constants.sleeperDeselected } } }
apache-2.0
lady12/firefox-ios
Client/Frontend/Browser/BrowserViewController.swift
7
91722
/* 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 Photos import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire import Account private let log = Logger.browserLogger private let OKString = NSLocalizedString("OK", comment: "OK button") private let CancelString = NSLocalizedString("Cancel", comment: "Cancel button") private let KVOLoading = "loading" private let KVOEstimatedProgress = "estimatedProgress" private let KVOURL = "URL" private let KVOCanGoBack = "canGoBack" private let KVOCanGoForward = "canGoForward" private let KVOContentSize = "contentSize" private let ActionSheetTitleMaxLength = 120 private struct BrowserViewControllerUX { private static let BackgroundColor = UIConstants.AppBackgroundColor private static let ShowHeaderTapAreaHeight: CGFloat = 32 private static let BookmarkStarAnimationDuration: Double = 0.5 private static let BookmarkStarAnimationOffset: CGFloat = 80 } class BrowserViewController: UIViewController { var homePanelController: HomePanelViewController? var webViewContainer: UIView! var urlBar: URLBarView! var readerModeBar: ReaderModeBarView? private var statusBarOverlay: UIView! private var toolbar: BrowserToolbar? private var searchController: SearchViewController? private let uriFixup = URIFixup() private var screenshotHelper: ScreenshotHelper! private var homePanelIsInline = false private var searchLoader: SearchLoader! private let snackBars = UIView() private let auralProgress = AuralProgressBar() // location label actions private var pasteGoAction: AccessibleAction! private var pasteAction: AccessibleAction! private var copyAddressAction: AccessibleAction! private weak var tabTrayController: TabTrayController! private let profile: Profile let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them var header: UIView! var headerBackdrop: UIView! var footer: UIView! var footerBackdrop: UIView! private var footerBackground: UIView! private var topTouchArea: UIButton! private var scrollController = BrowserScrollingController() private var keyboardState: KeyboardState? let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"] // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: BrowserToolbarProtocol { return toolbar ?? urlBar } init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager super.init(nibName: nil, bundle: nil) didInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return UIInterfaceOrientationMask.AllButUpsideDown } else { return UIInterfaceOrientationMask.All } } override func didReceiveMemoryWarning() { print("THIS IS BROWSERVIEWCONTROLLER.DIDRECEIVEMEMORYWARNING - WE ARE GOING TO TABMANAGER.RESETPROCESSPOOL()") log.debug("THIS IS BROWSERVIEWCONTROLLER.DIDRECEIVEMEMORYWARNING - WE ARE GOING TO TABMANAGER.RESETPROCESSPOOL()") NSLog("THIS IS BROWSERVIEWCONTROLLER.DIDRECEIVEMEMORYWARNING - WE ARE GOING TO TABMANAGER.RESETPROCESSPOOL()") super.didReceiveMemoryWarning() tabManager.resetProcessPool() } private func didInit() { screenshotHelper = BrowserScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } func shouldShowFooterForTraitCollection(previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .Compact && previousTraitCollection.horizontalSizeClass != .Regular } func toggleSnackBarVisibility(show show: Bool) { if show { UIView.animateWithDuration(0.1, animations: { self.snackBars.hidden = false }) } else { snackBars.hidden = true } } private func updateToolbarStateForTraitCollection(newCollection: UITraitCollection) { let showToolbar = shouldShowFooterForTraitCollection(newCollection) urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.browserToolbarDelegate = nil footerBackground?.removeFromSuperview() footerBackground = nil toolbar = nil if showToolbar { toolbar = BrowserToolbar() toolbar?.browserToolbarDelegate = self footerBackground = wrapInEffect(toolbar!, parent: footer) } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab, webView = tab.webView { updateURLBarDisplayURL(tab) navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) navigationToolbar.updateReloadStatus(tab.loading ?? false) } } override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator) updateToolbarStateForTraitCollection(newCollection) // WKWebView looks like it has a bug where it doesn't invalidate it's visible area when the user // performs a device rotation. Since scrolling calls // _updateVisibleContentRects (https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKWebView.mm#L1430) // this method nudges the web view's scroll view by a single pixel to force it to invalidate. if let scrollView = self.tabManager.selectedTab?.webView?.scrollView { let contentOffset = scrollView.contentOffset coordinator.animateAlongsideTransition({ context in scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y + 1), animated: true) self.scrollController.showToolbars(animated: false) // Update overlay that sits behind the status bar to reflect the new topLayoutGuide length. It seems that // when updateViewConstraints is invoked during rotation, the UILayoutSupport instance hasn't updated // to reflect the new orientation which is why we do it here instead of in updateViewConstraints. self.statusBarOverlay.snp_remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(self.topLayoutGuide.length) } }, completion: { context in scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y), animated: false) }) } } func SELtappedTopArea() { scrollController.showToolbars(animated: true) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: BookmarkStatusChangedNotification, object: nil) } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELBookmarkStatusDidChange:", name: BookmarkStatusChangedNotification, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) footerBackdrop = UIView() footerBackdrop.backgroundColor = UIColor.whiteColor() view.addSubview(footerBackdrop) headerBackdrop = UIView() headerBackdrop.backgroundColor = UIColor.whiteColor() view.addSubview(headerBackdrop) webViewContainer = UIView() view.addSubview(webViewContainer) // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() statusBarOverlay.backgroundColor = BrowserViewControllerUX.BackgroundColor view.addSubview(statusBarOverlay) topTouchArea = UIButton() topTouchArea.isAccessibilityElement = false topTouchArea.addTarget(self, action: "SELtappedTopArea", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(topTouchArea) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.translatesAutoresizingMaskIntoConstraints = false urlBar.delegate = self urlBar.browserToolbarDelegate = self header = wrapInEffect(urlBar, parent: view, backgroundColor: nil) // UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.generalPasteboard().string { self.urlBar(self.urlBar, didSubmitText: pasteboardContents) return true } return false }) pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.generalPasteboard().string { // Enter overlay mode and fire the text entered callback to make the search controller appear. self.urlBar.enterOverlayMode(pasteboardContents, pasted: true) self.urlBar(self.urlBar, didEnterText: pasteboardContents) return true } return false }) copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in if let urlString = self.urlBar.currentURL?.absoluteString { UIPasteboard.generalPasteboard().string = urlString } return true }) searchLoader = SearchLoader(history: profile.history, urlBar: urlBar) footer = UIView() self.view.addSubview(footer) self.view.addSubview(snackBars) snackBars.backgroundColor = UIColor.clearColor() scrollController.urlBar = urlBar scrollController.header = header scrollController.footer = footer scrollController.snackBars = snackBars self.updateToolbarStateForTraitCollection(self.traitCollection) setupConstraints() } private func setupConstraints() { urlBar.snp_makeConstraints { make in make.edges.equalTo(self.header) } let viewBindings: [String: AnyObject] = [ "header": header, "topLayoutGuide": topLayoutGuide ] let topConstraint = NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide][header]", options: [], metrics: nil, views: viewBindings) view.addConstraints(topConstraint) scrollController.headerTopConstraint = topConstraint.first header.snp_makeConstraints { make in make.height.equalTo(UIConstants.ToolbarHeight) make.left.right.equalTo(self.view) } headerBackdrop.snp_makeConstraints { make in make.edges.equalTo(self.header) } } func loadQueuedTabs() { log.debug("Loading queued tabs in the background.") // Chain off of a trivial deferred in order to run on the background queue. succeed().upon() { res in self.dequeueQueuedTabs() } } private func dequeueQueuedTabs() { assert(!NSThread.currentThread().isMainThread, "This must be called in the background.") self.profile.queue.getQueuedTabs() >>== { cursor in // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. log.debug("Queue. Count: \(cursor.count).") if cursor.count > 0 { var urls = [NSURL]() for row in cursor { if let url = row?.url.asURL { log.debug("Queuing \(url).") urls.append(url) } } if !urls.isEmpty { dispatch_async(dispatch_get_main_queue()) { self.tabManager.addTabsForURLs(urls, zombie: false) } } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } } func startTrackingAccessibilityStatus() { NSNotificationCenter.defaultCenter().addObserverForName(UIAccessibilityVoiceOverStatusChanged, object: nil, queue: nil) { (notification) -> Void in self.auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning() } auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning() } func stopTrackingAccessibilityStatus() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIAccessibilityVoiceOverStatusChanged, object: nil) auralProgress.hidden = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // On iPhone, if we are about to show the On-Boarding, blank out the browser so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.currentDevice().userInterfaceIdiom == .Phone { self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0 } if tabManager.count == 0 && !AppConstants.IsRunningTest { tabManager.restoreTabs() } if tabManager.count == 0 { let tab = tabManager.addTab() tabManager.selectTab(tab) } } override func viewDidAppear(animated: Bool) { startTrackingAccessibilityStatus() // We want to load queued tabs here in case we need to execute any commands that were received while using a share extension, // but no point even trying if this is the first time. if !presentIntroViewController() { loadQueuedTabs() } super.viewDidAppear(animated) } override func viewDidDisappear(animated: Bool) { stopTrackingAccessibilityStatus() } override func updateViewConstraints() { super.updateViewConstraints() topTouchArea.snp_remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } readerModeBar?.snp_remakeConstraints { make in make.top.equalTo(self.header.snp_bottom).constraint make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } webViewContainer.snp_remakeConstraints { make in make.left.right.equalTo(self.view) if let readerModeBarBottom = readerModeBar?.snp_bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp_bottom) } if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp_top) } else { make.bottom.equalTo(self.view) } } // Setup the bottom toolbar toolbar?.snp_remakeConstraints { make in make.edges.equalTo(self.footerBackground!) make.height.equalTo(UIConstants.ToolbarHeight) } footer.snp_remakeConstraints { make in scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp_bottom).constraint make.top.equalTo(self.snackBars.snp_top) make.leading.trailing.equalTo(self.view) } footerBackdrop.snp_remakeConstraints { make in make.edges.equalTo(self.footer) } adjustFooterSize(nil) footerBackground?.snp_remakeConstraints { make in make.bottom.left.right.equalTo(self.footer) make.height.equalTo(UIConstants.ToolbarHeight) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp_remakeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } else { make.bottom.equalTo(self.view.snp_bottom) } } } private func wrapInEffect(view: UIView, parent: UIView) -> UIView { return self.wrapInEffect(view, parent: parent, backgroundColor: UIColor.clearColor()) } private func wrapInEffect(view: UIView, parent: UIView, backgroundColor: UIColor?) -> UIView { let effect = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) effect.clipsToBounds = false effect.translatesAutoresizingMaskIntoConstraints = false if let _ = backgroundColor { view.backgroundColor = backgroundColor } effect.addSubview(view) parent.addSubview(effect) return effect } private func showHomePanelController(inline inline: Bool) { homePanelIsInline = inline if homePanelController == nil { homePanelController = HomePanelViewController() homePanelController!.profile = profile homePanelController!.delegate = self homePanelController!.url = tabManager.selectedTab?.displayURL homePanelController!.view.alpha = 0 addChildViewController(homePanelController!) view.addSubview(homePanelController!.view) homePanelController!.didMoveToParentViewController(self) } let panelNumber = tabManager.selectedTab?.url?.fragment // splitting this out to see if we can get better crash reports when this has a problem var newSelectedButtonIndex = 0 if let numberArray = panelNumber?.componentsSeparatedByString("=") { if let last = numberArray.last, lastInt = Int(last) { newSelectedButtonIndex = lastInt } } homePanelController?.selectedButtonIndex = newSelectedButtonIndex // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animateWithDuration(0.2, animations: { () -> Void in self.homePanelController!.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true self.stopTrackingAccessibilityStatus() UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) view.setNeedsUpdateConstraints() } private func hideHomePanelController() { if let controller = homePanelController { UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { finished in if finished { controller.willMoveToParentViewController(nil) controller.view.removeFromSuperview() controller.removeFromParentViewController() self.homePanelController = nil self.webViewContainer.accessibilityElementsHidden = false self.startTrackingAccessibilityStatus() UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode where readerMode.state == .Active { self.showReaderModeBar(animated: false) } } }) } } private func updateInContentHomePanel(url: NSURL?) { if !urlBar.inOverlayMode { if AboutUtils.isAboutHomeURL(url){ showHomePanelController(inline: (tabManager.selectedTab?.canGoForward ?? false || tabManager.selectedTab?.canGoBack ?? false)) } else { hideHomePanelController() } } } private func showSearchController() { if searchController != nil { return } searchController = SearchViewController() searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchController!.profile = self.profile searchLoader.addListener(searchController!) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp_makeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.hidden = true searchController!.didMoveToParentViewController(self) } private func hideSearchController() { if let searchController = searchController { searchController.willMoveToParentViewController(nil) searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.hidden = false } } private func finishEditingAndSubmit(url: NSURL, visitType: VisitType) { urlBar.currentURL = url urlBar.leaveOverlayMode() if let tab = tabManager.selectedTab, let nav = tab.loadRequest(NSURLRequest(URL: url)) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(url: String, title: String?) { let shareItem = ShareItem(url: url, title: title, favicon: nil) profile.bookmarks.shareItem(shareItem) animateBookmarkStar() // Dispatch to the main thread to update the UI dispatch_async(dispatch_get_main_queue()) { _ in self.toolbar?.updateBookmarkStatus(true) self.urlBar.updateBookmarkStatus(true) } } private func animateBookmarkStar() { let offset: CGFloat let button: UIButton! if let toolbar: BrowserToolbar = self.toolbar { offset = BrowserViewControllerUX.BookmarkStarAnimationOffset * -1 button = toolbar.bookmarkButton } else { offset = BrowserViewControllerUX.BookmarkStarAnimationOffset button = self.urlBar.bookmarkButton } let offToolbar = CGAffineTransformMakeTranslation(0, offset) UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 2.0, options: [], animations: { () -> Void in button.transform = offToolbar let rotation = CABasicAnimation(keyPath: "transform.rotation") rotation.toValue = CGFloat(M_PI * 2.0) rotation.cumulative = true rotation.duration = BrowserViewControllerUX.BookmarkStarAnimationDuration + 0.075 rotation.repeatCount = 1.0 rotation.timingFunction = CAMediaTimingFunction(controlPoints: 0.32, 0.70 ,0.18 ,1.00) button.imageView?.layer.addAnimation(rotation, forKey: "rotateStar") }, completion: { finished in UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.15, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in button.transform = CGAffineTransformIdentity }, completion: nil) }) } private func removeBookmark(url: String) { profile.bookmarks.removeByURL(url).uponQueue(dispatch_get_main_queue()) { res in if res.isSuccess { self.toolbar?.updateBookmarkStatus(false) self.urlBar.updateBookmarkStatus(false) } } } func SELBookmarkStatusDidChange(notification: NSNotification) { if let bookmark = notification.object as? BookmarkItem { if bookmark.url == urlBar.currentURL?.absoluteString { if let userInfo = notification.userInfo as? Dictionary<String, Bool>{ if let added = userInfo["added"]{ self.toolbar?.updateBookmarkStatus(added) self.urlBar.updateBookmarkStatus(added) } } } } } override func accessibilityPerformEscape() -> Bool { if urlBar.inOverlayMode { urlBar.SELdidClickCancel() return true } else if let selectedTab = tabManager.selectedTab where selectedTab.canGoBack { selectedTab.goBack() return true } return false } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) { let webView = object as! WKWebView if webView !== tabManager.selectedTab?.webView { return } guard let path = keyPath else { assertionFailure("Unhandled KVO key: \(keyPath)"); return } switch path { case KVOEstimatedProgress: guard let progress = change?[NSKeyValueChangeNewKey] as? Float else { break } urlBar.updateProgressBar(progress) // when loading is stopped, KVOLoading is fired first, and only then KVOEstimatedProgress with progress 1.0 which would leave the progress bar running if progress != 1.0 || tabManager.selectedTab?.loading ?? false { auralProgress.progress = Double(progress) } case KVOLoading: guard let loading = change?[NSKeyValueChangeNewKey] as? Bool else { break } toolbar?.updateReloadStatus(loading) urlBar.updateReloadStatus(loading) auralProgress.progress = loading ? 0 : nil case KVOURL: if let tab = tabManager.selectedTab where tab.webView?.URL == nil { log.debug("URL IS NIL! WE ARE RESETTING PROCESS POOL") NSLog("URL IS NIL! WE ARE RESETTING PROCESS POOL") print("URL IS NIL! WE ARE RESETTING PROCESS POOL") tabManager.resetProcessPool() } if let tab = tabManager.selectedTab where tab.webView === webView && !tab.restoring { updateUIForReaderHomeStateForTab(tab) } case KVOCanGoBack: guard let canGoBack = change?[NSKeyValueChangeNewKey] as? Bool else { break } navigationToolbar.updateBackStatus(canGoBack) case KVOCanGoForward: guard let canGoForward = change?[NSKeyValueChangeNewKey] as? Bool else { break } navigationToolbar.updateForwardStatus(canGoForward) default: assertionFailure("Unhandled KVO key: \(keyPath)") } } private func updateUIForReaderHomeStateForTab(tab: Browser) { updateURLBarDisplayURL(tab) scrollController.showToolbars(animated: false) if let url = tab.url { if ReaderModeUtils.isReaderModeURL(url) { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } updateInContentHomePanel(url) } } private func isWhitelistedUrl(url: NSURL) -> Bool { for entry in WhiteListedUrls { if let _ = url.absoluteString.rangeOfString(entry, options: .RegularExpressionSearch) { return UIApplication.sharedApplication().canOpenURL(url) } } return false } /// Updates the URL bar text and button states. /// Call this whenever the page URL changes. private func updateURLBarDisplayURL(tab: Browser) { urlBar.currentURL = tab.displayURL let isPage = (tab.displayURL != nil) ? isWebPage(tab.displayURL!) : false navigationToolbar.updatePageStatus(isWebPage: isPage) if let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.navigationToolbar.updateBookmarkStatus(bookmarked) }, failure: { err in log.error("Error getting bookmark status: \(err).") }) } } func openURLInNewTab(url: NSURL) { let tab = tabManager.addTab(NSURLRequest(URL: url)) tabManager.selectTab(tab) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(tab: Browser, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(tab: Browser, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(tab: Browser, navigation: WKNavigation?) -> VisitType? { guard let navigation = navigation else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.Link } if let _ = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValueForKey(navigation) ?? VisitType.Link } } extension BrowserViewController: URLBarDelegate { func urlBarDidPressReload(urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressStop(urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(urlBar: URLBarView) { let tabTrayController = TabTrayController() tabTrayController.profile = profile tabTrayController.tabManager = tabManager if let tab = tabManager.selectedTab { tab.setScreenshot(screenshotHelper.takeScreenshot(tab, aspectRatio: 0, quality: 1)) } self.navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController } func urlBarDidPressReaderMode(urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .Available: enableReaderMode() case .Active: disableReaderMode() case .Unavailable: break } } } } func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool { guard let tab = tabManager.selectedTab, url = tab.displayURL, result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) else { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed.")) return false } switch result { case .Success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action.")) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .Failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it's already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures.")) log.error("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)") } return true } func locationActionsForURLBar(urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.generalPasteboard().string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDidLongPressLocation(urlBar: URLBarView) { let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) for action in locationActionsForURLBar(urlBar) { longPressAlertController.addAction(action.alertAction(style: .Default)) } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel alert view"), style: .Cancel, handler: { (alert: UIAlertAction) -> Void in }) longPressAlertController.addAction(cancelAction) if let popoverPresentationController = longPressAlertController.popoverPresentationController { popoverPresentationController.sourceView = urlBar popoverPresentationController.sourceRect = urlBar.frame popoverPresentationController.permittedArrowDirections = .Any } self.presentViewController(longPressAlertController, animated: true, completion: nil) } func urlBarDidPressScrollToTop(urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab { // Only scroll to top if we are not showing the home view controller if homePanelController == nil { selectedTab.webView?.scrollView.setContentOffset(CGPointZero, animated: true) } } } func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(urlBar: URLBarView, didEnterText text: String) { searchLoader.query = text if text.isEmpty { hideSearchController() } else { showSearchController() searchController!.searchQuery = text } } func urlBar(urlBar: URLBarView, didSubmitText text: String) { var url = uriFixup.getURL(text) // If we can't make a valid URL, do a search query. if url == nil { url = profile.searchEngines.defaultEngine.searchURLForQuery(text) } // If we still don't have a valid URL, something is broken. Give up. if url == nil { log.error("Error handling URL entry: \"\(text)\".") return } finishEditingAndSubmit(url!, visitType: VisitType.Typed) } func urlBarDidEnterOverlayMode(urlBar: URLBarView) { showHomePanelController(inline: false) } func urlBarDidLeaveOverlayMode(urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url) } } extension BrowserViewController: BrowserToolbarDelegate { func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { // See 1159373 - Disable long press back/forward for backforward list // let controller = BackForwardListViewController() // controller.listData = tabManager.selectedTab?.backList // controller.tabManager = tabManager // presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { // See 1159373 - Disable long press back/forward for backforward list // let controller = BackForwardListViewController() // controller.listData = tabManager.selectedTab?.forwardList // controller.tabManager = tabManager // presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let tab = tabManager.selectedTab, let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { isBookmarked in if isBookmarked { self.removeBookmark(url) } else { self.addBookmark(url, title: tab.title) } }, failure: { err in log.error("Bookmark error: \(err).") } ) } else { log.error("Bookmark error: No tab is selected, or no URL in tab.") } } func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { } func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let selected = tabManager.selectedTab { if let url = selected.displayURL { let printInfo = UIPrintInfo(dictionary: nil) printInfo.jobName = url.absoluteString printInfo.outputType = .General let renderer = BrowserPrintPageRenderer(browser: selected) let activityItems = [printInfo, renderer, selected.title ?? url.absoluteString, url] let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) // Hide 'Add to Reading List' which currently uses Safari. // Also hide our own View Later… after all, you're in the browser! let viewLater = NSBundle.mainBundle().bundleIdentifier! + ".ViewLater" activityViewController.excludedActivityTypes = [ UIActivityTypeAddToReadingList, viewLater, // Doesn't work: rdar://19430419 ] activityViewController.completionWithItemsHandler = { activityType, completed, _, _ in log.debug("Selected activity type: \(activityType).") if completed { if let selectedTab = self.tabManager.selectedTab { // We don't know what share action the user has chosen so we simply always // update the toolbar and reader mode bar to refelect the latest status. self.updateURLBarDisplayURL(selectedTab) self.updateReaderModeBar() } } } if let popoverPresentationController = activityViewController.popoverPresentationController { // Using the button for the sourceView here results in this not showing on iPads. popoverPresentationController.sourceView = toolbar ?? urlBar popoverPresentationController.sourceRect = button.frame ?? button.frame popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Up popoverPresentationController.delegate = self } presentViewController(activityViewController, animated: true, completion: nil) } } } } extension BrowserViewController: WindowCloseHelperDelegate { func windowCloseHelper(helper: WindowCloseHelper, didRequestToCloseBrowser browser: Browser) { tabManager.removeTab(browser) } } extension BrowserViewController: BrowserDelegate { func browser(browser: Browser, didCreateWebView webView: WKWebView) { webViewContainer.insertSubview(webView, atIndex: 0) webView.snp_makeConstraints { make in make.edges.equalTo(self.webViewContainer) } // Observers that live as long as the tab. Make sure these are all cleared // in willDeleteWebView below! webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOLoading, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .New, context: nil) browser.webView?.addObserver(self, forKeyPath: KVOURL, options: .New, context: nil) webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOContentSize, options: .New, context: nil) webView.UIDelegate = self let readerMode = ReaderMode(browser: browser) readerMode.delegate = self browser.addHelper(readerMode, name: ReaderMode.name()) let favicons = FaviconManager(browser: browser, profile: profile) browser.addHelper(favicons, name: FaviconManager.name()) // Temporarily disable password support until the new code lands let logins = LoginsHelper(browser: browser, profile: profile) browser.addHelper(logins, name: LoginsHelper.name()) let contextMenuHelper = ContextMenuHelper(browser: browser) contextMenuHelper.delegate = self browser.addHelper(contextMenuHelper, name: ContextMenuHelper.name()) let errorHelper = ErrorPageHelper() browser.addHelper(errorHelper, name: ErrorPageHelper.name()) let windowCloseHelper = WindowCloseHelper(browser: browser) windowCloseHelper.delegate = self browser.addHelper(windowCloseHelper, name: WindowCloseHelper.name()) let sessionRestoreHelper = SessionRestoreHelper(browser: browser) sessionRestoreHelper.delegate = self browser.addHelper(sessionRestoreHelper, name: SessionRestoreHelper.name()) } func browser(browser: Browser, willDeleteWebView webView: WKWebView) { webView.removeObserver(self, forKeyPath: KVOEstimatedProgress) webView.removeObserver(self, forKeyPath: KVOLoading) webView.removeObserver(self, forKeyPath: KVOCanGoBack) webView.removeObserver(self, forKeyPath: KVOCanGoForward) webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOContentSize) webView.removeObserver(self, forKeyPath: KVOURL) webView.UIDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } private func findSnackbar(barToFind: SnackBar) -> Int? { let bars = snackBars.subviews for (index, bar) in bars.enumerate() { if bar === barToFind { return index } } return nil } private func adjustFooterSize(top: UIView? = nil) { snackBars.snp_remakeConstraints { make in let bars = self.snackBars.subviews // if the keyboard is showing then ensure that the snackbars are positioned above it, otherwise position them above the toolbar/view bottom if bars.count > 0 { let view = bars[bars.count-1] make.top.equalTo(view.snp_top) if let state = keyboardState { make.bottom.equalTo(-(state.intersectionHeightForView(self.view))) } else { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } } else { make.top.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } if traitCollection.horizontalSizeClass != .Regular { make.leading.trailing.equalTo(self.footer) self.snackBars.layer.borderWidth = 0 } else { make.centerX.equalTo(self.footer) make.width.equalTo(SnackBarUX.MaxWidth) self.snackBars.layer.borderColor = UIConstants.BorderColor.CGColor self.snackBars.layer.borderWidth = 1 } } } // This removes the bar from its superview and updates constraints appropriately private func finishRemovingBar(bar: SnackBar) { // If there was a bar above this one, we need to remake its constraints. if let index = findSnackbar(bar) { // If the bar being removed isn't on the top of the list let bars = snackBars.subviews if index < bars.count-1 { // Move the bar above this one let nextbar = bars[index+1] as! SnackBar nextbar.snp_updateConstraints { make in // If this wasn't the bottom bar, attach to the bar below it if index > 0 { let bar = bars[index-1] as! SnackBar nextbar.bottom = make.bottom.equalTo(bar.snp_top).constraint } else { // Otherwise, we attach it to the bottom of the snackbars nextbar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).constraint } } } } // Really remove the bar bar.removeFromSuperview() } private func finishAddingBar(bar: SnackBar) { snackBars.addSubview(bar) bar.snp_remakeConstraints { make in // If there are already bars showing, add this on top of them let bars = self.snackBars.subviews // Add the bar on top of the stack // We're the new top bar in the stack, so make sure we ignore ourself if bars.count > 1 { let view = bars[bars.count - 2] bar.bottom = make.bottom.equalTo(view.snp_top).offset(0).constraint } else { bar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).offset(0).constraint } make.leading.trailing.equalTo(self.snackBars) } } func showBar(bar: SnackBar, animated: Bool) { finishAddingBar(bar) adjustFooterSize(bar) bar.hide() view.layoutIfNeeded() UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.show() self.view.layoutIfNeeded() }) } func removeBar(bar: SnackBar, animated: Bool) { if let _ = findSnackbar(bar) { UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.hide() self.view.layoutIfNeeded() }) { success in // Really remove the bar self.finishRemovingBar(bar) // Adjust the footer size to only contain the bars self.adjustFooterSize() } } } func removeAllBars() { let bars = snackBars.subviews for bar in bars { if let bar = bar as? SnackBar { bar.removeFromSuperview() } } self.adjustFooterSize() } func browser(browser: Browser, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } } extension BrowserViewController: HomePanelViewControllerDelegate { func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectURL url: NSURL, visitType: VisitType) { finishEditingAndSubmit(url, visitType: visitType) } func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) { if AboutUtils.isAboutHomeURL(tabManager.selectedTab?.url) { tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil) } } func homePanelViewControllerDidRequestToCreateAccount(homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToSignIn(homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL) { finishEditingAndSubmit(url, visitType: VisitType.Typed) } func presentSearchSettingsController() { let settingsNavigationController = SearchSettingsTableViewController() settingsNavigationController.model = self.profile.searchEngines let navController = UINavigationController(rootViewController: settingsNavigationController) self.presentViewController(navController, animated: true, completion: nil) } } extension BrowserViewController: TabManagerDelegate { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { wv.endEditing(true) wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil // due to screwy handling within iOS, the scrollToTop handling does not work if there are // more than one scroll view in the view hierarchy // we therefore have to hide all the scrollViews that we are no actually interesting in interacting with // to ensure that scrollsToTop actually works wv.scrollView.hidden = true } if let tab = selected, webView = tab.webView { // if we have previously hidden this scrollview in order to make scrollsToTop work then // we should ensure that it is not hidden now that it is our foreground scrollView if webView.scrollView.hidden { webView.scrollView.hidden = false } updateURLBarDisplayURL(tab) scrollController.browser = selected webViewContainer.addSubview(webView) webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false if let url = webView.URL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.toolbar?.updateBookmarkStatus(bookmarked) self.urlBar.updateBookmarkStatus(bookmarked) }, failure: { err in log.error("Error getting bookmark status: \(err).") }) } else { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. tab.reload() } } removeAllBars() if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } navigationToolbar.updateReloadStatus(selected?.loading ?? false) navigationToolbar.updateBackStatus(selected?.canGoBack ?? false) navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false) self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .Active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.Unavailable) } updateInContentHomePanel(selected?.url) } func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) { } func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex: Int, restoring: Bool) { // If we are restoring tabs then we update the count once at the end if !restoring { urlBar.updateTabCount(tabManager.count) } tab.browserDelegate = self } func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex: Int) { urlBar.updateTabCount(max(tabManager.count, 1)) // browserDelegate is a weak ref (and the tab's webView may not be destroyed yet) // so we don't expcitly unset it. } func tabManagerDidAddTabs(tabManager: TabManager) { urlBar.updateTabCount(tabManager.count) } func tabManagerDidRestoreTabs(tabManager: TabManager) { urlBar.updateTabCount(tabManager.count) } private func isWebPage(url: NSURL) -> Bool { let httpSchemes = ["http", "https"] if let _ = httpSchemes.indexOf(url.scheme) { return true } return false } } extension BrowserViewController: WKNavigationDelegate { func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { if tabManager.selectedTab?.webView !== webView { return } // If we are going to navigate to a new page, hide the reader mode button. Unless we // are going to a about:reader page. Then we keep it on screen: it will change status // (orange color) as soon as the page has loaded. if let url = webView.URL { if !ReaderModeUtils.isReaderModeURL(url) { urlBar.updateReaderModeState(ReaderModeState.Unavailable) hideReaderModeBar(animated: false) } } } private func openExternal(url: NSURL, prompt: Bool = true) { if prompt { // Ask the user if it's okay to open the url with UIApplication. let alert = UIAlertController( title: String(format: NSLocalizedString("Opening %@", comment:"Opening an external URL"), url), message: NSLocalizedString("This will open in another application", comment: "Opening an external app"), preferredStyle: UIAlertControllerStyle.Alert ) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: { (action: UIAlertAction) in })) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"Alert OK Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(url) })) presentViewController(alert, animated: true, completion: nil) } else { UIApplication.sharedApplication().openURL(url) } } private func callExternal(url: NSURL) { if let phoneNumber = url.resourceSpecifier.stringByRemovingPercentEncoding { let alert = UIAlertController(title: phoneNumber, message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: NSLocalizedString("Call", comment:"Alert Call Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(url) })) presentViewController(alert, animated: true, completion: nil) } } func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.URL else { decisionHandler(WKNavigationActionPolicy.Cancel) return } switch url.scheme { case "about", "http", "https": if isWhitelistedUrl(url) { // If the url is whitelisted, we open it without prompting… // … unless the NavigationType is Other, which means it is JavaScript- or Redirect-initiated. openExternal(url, prompt: navigationAction.navigationType == WKNavigationType.Other) decisionHandler(WKNavigationActionPolicy.Cancel) } else { decisionHandler(WKNavigationActionPolicy.Allow) } case "tel": callExternal(url) decisionHandler(WKNavigationActionPolicy.Cancel) default: if UIApplication.sharedApplication().canOpenURL(url) { openExternal(url) } decisionHandler(WKNavigationActionPolicy.Cancel) } } func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest { if let tab = tabManager[webView] { let helper = tab.getHelper(name: LoginsHelper.name()) as! LoginsHelper helper.handleAuthRequest(self, challenge: challenge).uponQueue(dispatch_get_main_queue()) { res in if let credentials = res.successValue { completionHandler(.UseCredential, credentials.credentials) } else { completionHandler(NSURLSessionAuthChallengeDisposition.RejectProtectionSpace, nil) } } } } else { completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling, nil) } } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { let tab: Browser! = tabManager[webView] tabManager.expireSnackbars() if let url = webView.URL where !ErrorPageHelper.isErrorPageURL(url) && !AboutUtils.isAboutHomeURL(url) { let notificationCenter = NSNotificationCenter.defaultCenter() var info = [NSObject: AnyObject]() info["url"] = tab.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } tab.lastExecutedTime = NSDate.now() notificationCenter.postNotificationName("LocationChange", object: self, userInfo: info) // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("_firefox_ReaderMode.checkReadability()", completionHandler: nil) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } } } extension BrowserViewController: WKUIDelegate { func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if let currentTab = tabManager.selectedTab { currentTab.setScreenshot(screenshotHelper.takeScreenshot(currentTab, aspectRatio: 0, quality: 1)) } // If the page uses window.open() or target="_blank", open the page in a new tab. // TODO: This doesn't work for window.open() without user action (bug 1124942). let tab = tabManager.addTab(navigationAction.request, configuration: configuration) tabManager.selectTab(tab) return tab.webView } func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript alerts. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler() })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript confirm dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(true) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(false) })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript input dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: prompt, preferredStyle: UIAlertControllerStyle.Alert) var input: UITextField! alertController.addTextFieldWithConfigurationHandler({ (textField: UITextField) in textField.text = defaultText input = textField }) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(input.text) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(nil) })) presentViewController(alertController, animated: true, completion: nil) } /// Invoked when an error occurs during a committed main frame navigation. func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) { return } // Ignore the "Plug-in handled load" error. Which is more like a notification than an error. // Note that there are no constants in the SDK for the WebKit domain or error codes. if error.domain == "WebKitErrorDomain" && error.code == 204 { return } if checkIfWebContentProcessHasCrashed(webView, error: error) { return } if let url = error.userInfo["NSErrorFailingURLKey"] as? NSURL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) } } /// Invoked when an error occurs while starting to load data for the main frame. func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { // Ignore the "Frame load interrupted" error that is triggered when we cancel a request // to open an external application and hand it over to UIApplication.openURL(). The result // will be that we switch to the external app, for example the app store, while keeping the // original web page in the tab instead of replacing it with an error page. if error.domain == "WebKitErrorDomain" && error.code == 102 { return } if checkIfWebContentProcessHasCrashed(webView, error: error) { return } if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) { if let browser = tabManager[webView] where browser === tabManager.selectedTab { urlBar.currentURL = browser.displayURL } return } if let url = error.userInfo["NSErrorFailingURLKey"] as? NSURL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) } } private func checkIfWebContentProcessHasCrashed(webView: WKWebView, error: NSError) -> Bool { if error.code == WKErrorCode.WebContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" { log.debug("WebContent process has crashed. Trying to reloadFromOrigin to restart it.") webView.reloadFromOrigin() return true } return false } func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) { if navigationResponse.canShowMIMEType { decisionHandler(WKNavigationResponsePolicy.Allow) return } let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: "Downloads aren't supported in Firefox yet (but we're working on it)."]) ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.URL!, inWebView: webView) decisionHandler(WKNavigationResponsePolicy.Allow) } } extension BrowserViewController: ReaderModeDelegate, UIPopoverPresentationControllerDelegate { func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser) { // If this reader mode availability state change is for the tab that we currently show, then update // the button. Otherwise do nothing and the button will be updated when the tab is made active. if tabManager.selectedTab === browser { urlBar.updateReaderModeState(state) } } func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser) { self.showReaderModeBar(animated: true) browser.showContent(true) } // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } } extension BrowserViewController: ReaderModeStyleViewControllerDelegate { func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) { // Persist the new style to the profile let encodedStyle: [String:AnyObject] = style.encode() profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle) // Change the reader mode style on all tabs that have reader mode active for tabIndex in 0..<tabManager.count { if let tab = tabManager[tabIndex] { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { if readerMode.state == ReaderModeState.Active { readerMode.style = style } } } } } } extension BrowserViewController { func updateReaderModeBar() { if let readerModeBar = readerModeBar { if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { readerModeBar.unread = record.unread readerModeBar.added = true } else { readerModeBar.unread = true readerModeBar.added = false } } else { readerModeBar.unread = true readerModeBar.added = false } } } func showReaderModeBar(animated animated: Bool) { if self.readerModeBar == nil { let readerModeBar = ReaderModeBarView(frame: CGRectZero) readerModeBar.delegate = self view.insertSubview(readerModeBar, belowSubview: header) self.readerModeBar = readerModeBar } updateReaderModeBar() self.updateViewConstraints() } func hideReaderModeBar(animated animated: Bool) { if let readerModeBar = self.readerModeBar { readerModeBar.removeFromSuperview() self.readerModeBar = nil self.updateViewConstraints() } } /// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode /// and be done with it. In the more complicated case, reader mode was already open for this page and we simply /// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version /// of the current page is there. And if so, we go there. func enableReaderMode() { guard let tab = tabManager.selectedTab, webView = tab.webView else { return } let backList = webView.backForwardList.backList let forwardList = webView.backForwardList.forwardList guard let currentURL = webView.backForwardList.currentItem?.URL, let readerModeURL = ReaderModeUtils.encodeURL(currentURL) else { return } if backList.count > 1 && backList.last?.URL == readerModeURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == readerModeURL { webView.goToBackForwardListItem(forwardList.first!) } else { // Store the readability result in the cache and load it. This will later move to the ReadabilityHelper. webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in if let readabilityResult = ReadabilityResult(object: object) { do { try ReaderModeCache.sharedInstance.put(currentURL, readabilityResult) } catch _ { } if let nav = webView.loadRequest(NSURLRequest(URL: readerModeURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } }) } } /// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which /// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that /// case we simply open a new page with the original url. In the more complicated page, the non-readerized version /// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there. func disableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView { let backList = webView.backForwardList.backList let forwardList = webView.backForwardList.forwardList if let currentURL = webView.backForwardList.currentItem?.URL { if let originalURL = ReaderModeUtils.decodeURL(currentURL) { if backList.count > 1 && backList.last?.URL == originalURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == originalURL { webView.goToBackForwardListItem(forwardList.first!) } else { if let nav = webView.loadRequest(NSURLRequest(URL: originalURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } } } } } } extension BrowserViewController: ReaderModeBarViewDelegate { func readerModeBar(readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) { switch buttonType { case .Settings: if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode where readerMode.state == ReaderModeState.Active { var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict) { readerModeStyle = style } } let readerModeStyleViewController = ReaderModeStyleViewController() readerModeStyleViewController.delegate = self readerModeStyleViewController.readerModeStyle = readerModeStyle readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.Popover let popoverPresentationController = readerModeStyleViewController.popoverPresentationController popoverPresentationController?.backgroundColor = UIColor.whiteColor() popoverPresentationController?.delegate = self popoverPresentationController?.sourceView = readerModeBar popoverPresentationController?.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1) popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up self.presentViewController(readerModeStyleViewController, animated: true, completion: nil) } case .MarkAsRead: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail? readerModeBar.unread = false } } case .MarkAsUnread: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail? readerModeBar.unread = true } } case .AddToReadingList: if let tab = tabManager.selectedTab, let url = tab.url where ReaderModeUtils.isReaderModeURL(url) { if let url = ReaderModeUtils.decodeURL(url) { profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail? readerModeBar.added = true } } case .RemoveFromReadingList: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.deleteRecord(record) // TODO Check result, can this fail? readerModeBar.added = false } } } } } private class BrowserScreenshotHelper: ScreenshotHelper { private weak var controller: BrowserViewController? init(controller: BrowserViewController) { self.controller = controller } func takeScreenshot(tab: Browser, aspectRatio: CGFloat, quality: CGFloat) -> UIImage? { if let url = tab.url { if url == UIConstants.AboutHomeURL { if let homePanel = controller?.homePanelController { return homePanel.view.screenshot(aspectRatio, quality: quality) } } else { let offset = CGPointMake(0, -(tab.webView?.scrollView.contentInset.top ?? 0)) return tab.webView?.screenshot(aspectRatio, offset: offset, quality: quality) } } return nil } } extension BrowserViewController: IntroViewControllerDelegate { func presentIntroViewController(force: Bool = false) -> Bool{ if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if UIDevice.currentDevice().userInterfaceIdiom == .Pad { introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height) introViewController.modalPresentationStyle = UIModalPresentationStyle.FormSheet } presentViewController(introViewController, animated: true) { self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey) } return true } return false } func introViewControllerDidFinish(introViewController: IntroViewController) { introViewController.dismissViewControllerAnimated(true) { finished in if self.navigationController?.viewControllers.count > 1 { self.navigationController?.popToRootViewControllerAnimated(true) } } } func presentSignInViewController() { // Show the settings page if we have already signed in. If we haven't then show the signin page let vcToPresent: UIViewController if profile.hasAccount() { let settingsTableViewController = SettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager vcToPresent = settingsTableViewController } else { let signInVC = FxAContentViewController() signInVC.delegate = self signInVC.url = profile.accountConfiguration.signInURL signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "dismissSignInViewController") vcToPresent = signInVC } let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent) settingsNavigationController.modalPresentationStyle = .FormSheet self.presentViewController(settingsNavigationController, animated: true, completion: nil) } func dismissSignInViewController() { self.dismissViewControllerAnimated(true, completion: nil) } func introViewControllerDidRequestToLogin(introViewController: IntroViewController) { introViewController.dismissViewControllerAnimated(true, completion: { () -> Void in self.presentSignInViewController() }) } } extension BrowserViewController: FxAContentViewControllerDelegate { func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void { if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil { // The /settings endpoint sends a partial "login"; ignore it entirely. log.debug("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.") return } // TODO: Error handling. let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)! profile.setAccount(account) if let account = self.profile.getAccount() { account.advance() } self.dismissViewControllerAnimated(true, completion: nil) } func contentViewControllerDidCancel(viewController: FxAContentViewController) { log.info("Did cancel out of FxA signin") self.dismissViewControllerAnimated(true, completion: nil) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) { let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) var dialogTitle: String? if let url = elements.link { dialogTitle = url.absoluteString let newTabTitle = NSLocalizedString("Open In New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) in self.scrollController.showToolbars(animated: !self.scrollController.toolbarsShowing, completion: { _ in self.tabManager.addTab(NSURLRequest(URL: url)) }) } actionSheetController.addAction(openNewTabAction) let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in let pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = url.absoluteString } actionSheetController.addAction(copyAction) } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in if photoAuthorizeStatus == PHAuthorizationStatus.Authorized || photoAuthorizeStatus == PHAuthorizationStatus.NotDetermined { self.getImage(url) { UIImageWriteToSavedPhotosAlbum($0, nil, nil, nil) } } else { let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: UIAlertControllerStyle.Alert) let dismissAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Default, handler: nil) accessDenied.addAction(dismissAction) let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.Default ) { (action: UIAlertAction!) -> Void in UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) } accessDenied.addAction(settingsAction) self.presentViewController(accessDenied, animated: true, completion: nil) } } actionSheetController.addAction(saveImageAction) let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in let pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = url.absoluteString // TODO: put the actual image on the clipboard } actionSheetController.addAction(copyAction) } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: gestureRecognizer.locationInView(view), size: CGSizeMake(0, 16)) popoverPresentationController.permittedArrowDirections = .Any } actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength) let cancelAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: nil) actionSheetController.addAction(cancelAction) self.presentViewController(actionSheetController, animated: true, completion: nil) } private func getImage(url: NSURL, success: UIImage -> ()) { Alamofire.request(.GET, url) .validate(statusCode: 200..<300) .response { _, _, data, _ in if let data = data, let image = UIImage(data: data) { success(image) } } } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state // if we are already showing snack bars, adjust them so they sit above the keyboard if snackBars.subviews.count > 0 { adjustFooterSize(nil) } } func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil // if we are showing snack bars, adjust them so they are no longer sitting above the keyboard if snackBars.subviews.count > 0 { adjustFooterSize(nil) } } } extension BrowserViewController: SessionRestoreHelperDelegate { func sessionRestoreHelper(helper: SessionRestoreHelper, didRestoreSessionForBrowser browser: Browser) { browser.restoring = false if let tab = tabManager.selectedTab where tab.webView === browser.webView { updateUIForReaderHomeStateForTab(tab) } } } private struct CrashPromptMessaging { static let CrashPromptTitle = NSLocalizedString("Well, this is embarrassing.", comment: "Restore Tabs Prompt Title") static let CrashPromptDescription = NSLocalizedString("Looks like Firefox crashed previously. Would you like to restore your tabs?", comment: "Restore Tabs Prompt Description") static let CrashPromptAffirmative = NSLocalizedString("Okay", comment: "Restore Tabs Affirmative Action") static let CrashPromptNegative = NSLocalizedString("No", comment: "Restore Tabs Negative Action") } extension BrowserViewController: UIAlertViewDelegate { private enum CrashPromptIndex: Int { case Cancel = 0 case Restore = 1 } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == CrashPromptIndex.Restore.rawValue { tabManager.restoreTabs() } // In case restore fails, launch at least one tab if tabManager.count == 0 { let tab = tabManager.addTab() tabManager.selectTab(tab) } } }
mpl-2.0
ahoppen/swift
test/SourceKit/SyntaxMapData/syntaxmap-partial-delete.swift
45
1419
// RUN: %sourcekitd-test -req=open -print-raw-response %S/Inputs/syntaxmap-partial-delete.swift == -req=edit -print-raw-response -pos=2:10 -length=2 -replace='' %S/Inputs/syntaxmap-partial-delete.swift | %sed_clean > %t.response // RUN: %FileCheck -input-file=%t.response %s // CHECK: {{^}}{ // CHECK-NEXT: key.offset: 0, // CHECK-NEXT: key.length: 13, // CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse, // CHECK-NEXT: key.syntaxmap: [ // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.keyword, // CHECK-NEXT: key.offset: 1, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.identifier, // CHECK-NEXT: key.offset: 5, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number, // CHECK-NEXT: key.offset: 9, // CHECK-NEXT: key.length: 3 // CHECK-NEXT: } // CHECK-NEXT: ], // After removing 2 chars from number literal // CHECK: {{^}}{ // CHECK-NEXT: key.offset: 9, // CHECK-NEXT: key.length: 1, // CHECK-NEXT: key.diagnostic_stage: source.diagnostic.stage.swift.parse, // CHECK-NEXT: key.syntaxmap: [ // CHECK-NEXT: { // CHECK-NEXT: key.kind: source.lang.swift.syntaxtype.number, // CHECK-NEXT: key.offset: 9, // CHECK-NEXT: key.length: 1 // CHECK-NEXT: } // CHECK-NEXT: ],
apache-2.0
wangjianquan/wjq-weibo
weibo_wjq/Tool/PhotoBrowse/PhotoBrowserAnimator.swift
1
4454
// // PhotoBrowserAnimator.swift // weibo_wjq // // Created by landixing on 2017/6/13. // Copyright © 2017年 WJQ. All rights reserved. // import UIKit protocol AnimatorPresentDelegate: NSObjectProtocol { //开始位置 func startAnimatorRect(indexpath: IndexPath) -> CGRect //结束位置 func endAnimatorRect(indexpath: IndexPath) -> CGRect //临时 func imageView(indexpath: IndexPath) -> UIImageView } protocol AnimatorDismissDelegate: NSObjectProtocol { func imageViewForDismissView() -> UIImageView func indexPathForDismissView() -> IndexPath } class PhotoBrowserAnimator: NSObject { var isPresented : Bool = false var presentDelegate : AnimatorPresentDelegate? var dismissDelegate : AnimatorDismissDelegate? var indexPath: IndexPath? func setIndexPath(_ indexPath : IndexPath, presentedDelegate : AnimatorPresentDelegate, dismissDelegate : AnimatorDismissDelegate) { self.indexPath = indexPath self.presentDelegate = presentedDelegate self.dismissDelegate = dismissDelegate } } extension PhotoBrowserAnimator : UIViewControllerTransitioningDelegate{ func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = true return self } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = false return self } } extension PhotoBrowserAnimator : UIViewControllerAnimatedTransitioning{ func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning){ isPresented ? animationForPresentedView(transitionContext) : animationForDismissView(transitionContext) } } extension PhotoBrowserAnimator { //present动画 fileprivate func animationForPresentedView(_ transitionContext: UIViewControllerContextTransitioning?) { guard let presentDelegate = presentDelegate, let indexpath = indexPath else { return } guard let presentView = transitionContext?.view(forKey: UITransitionContextViewKey.to) else { return } transitionContext?.containerView.addSubview(presentView) //临时iamgeview let imageview = presentDelegate.imageView(indexpath: indexpath) transitionContext?.containerView.addSubview(imageview) //开始位置 imageview.frame = presentDelegate.startAnimatorRect(indexpath: indexpath) presentView.alpha = 0.0 transitionContext?.containerView.backgroundColor = UIColor.black UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { //结束位置 imageview.frame = presentDelegate.endAnimatorRect(indexpath: indexpath) }) { (_) in transitionContext?.containerView.backgroundColor = UIColor.clear imageview.removeFromSuperview() presentView.alpha = 1.0 transitionContext?.completeTransition(true) } } //dismiss动画 fileprivate func animationForDismissView(_ transitionContext: UIViewControllerContextTransitioning){ guard let dismissDele = dismissDelegate, let presentDele = presentDelegate else { return } guard let dismissView = transitionContext.view(forKey: UITransitionContextViewKey.from) else { return } dismissView.removeFromSuperview() let imageview = dismissDele.imageViewForDismissView() transitionContext.containerView.addSubview(imageview) let indexpath = dismissDele.indexPathForDismissView() UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { imageview.frame = presentDele.startAnimatorRect(indexpath: indexpath) }) { (_) in imageview.removeFromSuperview() transitionContext.completeTransition(true) } } }
apache-2.0
ipraba/EPShapes
Pod/Classes/Views/Arrow/ArrowImageView.swift
1
348
// // ArrowImageView.swift // Pods // // Created by Prabaharan Elangovan on 08/02/16. // // import Foundation @IBDesignable open class ArrowImageView: ShapeImageView, ArrowDesignable { @IBInspectable open var arrowDirection: String = ArrowDirection.Default.rawValue override open func config() { drawArrow() } }
mit
turekj/ReactiveTODO
ReactiveTODOFramework/Classes/ViewControllers/TODONoteListViewControllerProtocol.swift
1
175
import Foundation public protocol TODONoteListViewControllerProtocol { var onAddTODO: (Void -> Void)? { get set } var onSelectTODO: (String -> Void)? { get set } }
mit
nsagora/validation-kit
ValidationToolkit.playground/Pages/BlockPredicate.xcplaygroundpage/Contents.swift
1
441
import Foundation import ValidationToolkit /*: ## `BlockPredicate` In the following example we use a `BlockPredicate` to evaluate if the length of the user input is equal to 5 characters. */ let input = "Hel!O" let predicate = BlockPredicate<String> { $0.count == 5 } let isValid = predicate.evaluate(with: input) if isValid { print("High ✋!") } else { print("We're expecting exactlly 5 characters.") } //: [Next](@next)
apache-2.0
daniel-barros/TV-Calendar
TV Calendar/ShowDetailDataSource.swift
1
23788
// // ShowDetailDataSource.swift // TV Calendar // // Created by Daniel Barros López on 1/18/17. // Copyright © 2017 Daniel Barros. All rights reserved. // import ExtendedUIKit /// Data source for table view that displays a show's detailed info. /// It provides, at most, 4 table sections: /// 0 - A DetailShowTableViewCell and a ShowActionsTableViewCell /// 1 - Multiple ShowInfoTableViewCell /// 2 - Multiple CalendarSettingTableViewCell and a CalendarActionTableViewCell (default-only settings) /// 3 - Multiple CalendarSettingTableViewCell and CalendarActionTableViewCell (show-specific settings) /// /// It also provides some `indexPaths(...)` funcs for retrieving index paths and sections. `indexPaths(forCellsAffectedBy:)` returns detailed info about rows and sections that need to be updated after a calendar settings change, which permits fine-grained table view updates with animations. class ShowDetailDataSource: NSObject { typealias AlteredIndexPaths = (added: [IndexPath], deleted: [IndexPath], updated: [IndexPath]) typealias AlteredSections = (added: IndexSet, deleted: IndexSet) var show: Show? { didSet { updateShowInfo() } } var calendarSettingsManager: CalendarSettingsManager? /// The content displayed by the table view cells of type ShowInfoTableViewCell. fileprivate var showInfo: [(title: String, body: String, maxNumberOfLines: Int)] = [] // MARK: IndexPaths and Sections Info /// The index path for the DetailShowTableViewCell or nil if it doesn't exist. func indexPathForDetailShowCell() -> IndexPath? { return show == nil ? nil : IndexPath(row: 0, section: 0) } /// The index path for the ShowActionsTableViewCell or nil if it doesn't exist. func indexPathForActionsCell() -> IndexPath? { return hasActionsCell ? IndexPath(row: 1, section: 0) : nil } var showInfoSection: Int? { return hasInfoSection ? 1 : nil } var calendarDefaultSettingsSection: Int? { if !hasDefaultCalendarSettingsSection { return nil } return hasInfoSection ? 2 : 1 } var calendarShowSpecificSettingsSection: Int? { if !hasShowSpecificCalendarSettingsSection { return nil } return hasInfoSection ? 3 : 2 } /// The index paths corresponding to cells which will be added/removed/updated and section numbers which will be added/removed as consequence of a calendar settings change. /// The `updated` index paths correspond to the cells that need to be updated AFTER the table view inserts and removes the `added` and `deleted` index paths. /// - warning: Call only after the calendar setting update has completed successfuly func indexPaths(forCellsAffectedBy setting: CalendarSettings, in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) { switch setting { case .createCalendarEvents: return indexPathsForCellsAffectedByCreateCalendarEvents() case .eventsName: return indexPathsForCellsAffectedByEventsName() case .createEventsForAllSeasons: return indexPathsForCellsAffectedByCreateEventsForAllSeasons(in: tableView) case .createAllDayEvents: return indexPathsForCellsAffectedByCreateAllDayEvents(in: tableView) case .useOriginalTimeZone: return indexPathsForCellsAffectedByUseOriginalTimeZone(in: tableView) case .useNetworkAsLocation: return indexPathsForCellsAffectedByUseNetworkAsLocation(in: tableView) case .setAlarms: return indexPathsForCellsAffectedBySetAlarms(in: tableView) } } /// The index paths corresponding to cells which will be added/removed/updated as consequence of a calendar settings action. /// The `updated` index paths correspond to the cells that need to be updated AFTER the table view inserts and removes the `added` and `deleted` index paths. /// - warning: Call only after the calendar action has completed successfuly func indexPaths(forCellsAffectedBy actionType: CalendarActionTableViewCell.ActionType, in tableView: UITableView) -> AlteredIndexPaths { switch actionType { case .disableCalendarEventsForAll: // Remove "disable events" return ([], [indexPathCalendarActionCellWouldHave(withType: actionType)], []) case .setDefaultSettings: // Remove "set" and update "reset default settings" return ([], [indexPathCalendarActionCellWouldHave(withType: .setDefaultSettings)], [indexPathCalendarActionCellWouldHave(withType: .setDefaultSettings)]) case .resetToDefaultSettings: let setDefaultsIndex = indexPathCalendarActionCellWouldHave(withType: .setDefaultSettings) // Remove "set" and update "reset default settings" and show-specific settings if tableView.numberOfRows(inSection: calendarShowSpecificSettingsSection!) == CalendarSettings.numberOfShowSpecificSettings + 2 { return ([], [indexPathCalendarActionCellWouldHave(withType: .setDefaultSettings)], [setDefaultsIndex] + indexPathsForSettingCellsInShowSpecificSection()) } // Or update "set default settings" and show-specific settings return ([], [], [setDefaultsIndex] + indexPathsForSettingCellsInShowSpecificSection()) case .enableCalendarEventsForAll: // Update "enable events" return ([],[],[indexPathCalendarActionCellWouldHave(withType: actionType)]) } } } // MARK: - UITableViewDataSource extension ShowDetailDataSource: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { if show == nil { return 0 } return 1 + (hasInfoSection ? 1 : 0) + (hasDefaultCalendarSettingsSection ? 1 : 0) + (hasShowSpecificCalendarSettingsSection ? 1 : 0) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard show != nil else { return 0 } switch section { case 0: return 1 + (hasActionsCell ? 1 : 0) case 1: if hasInfoSection { return showInfo.count } else { return numberOfCellsInDefaultCalendarSettingsSection } case 2: if hasInfoSection { return numberOfCellsInDefaultCalendarSettingsSection } else { return numberOfCellsInShowSpecificCalendarSettingsSection } case 3: return numberOfCellsInShowSpecificCalendarSettingsSection default: assertionFailure(); return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let show = show else { assertionFailure(); return UITableViewCell() } // Cell making func detailShowCell() -> DetailShowTableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath) as DetailShowTableViewCell cell.configure(with: show, animated: false) return cell } func showActionsCell() -> ShowActionsTableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath) as ShowActionsTableViewCell cell.configure(with: show) return cell } func infoCell() -> ShowInfoTableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath) as ShowInfoTableViewCell let info = showInfo[indexPath.row] cell.configure(title: info.title, body: info.body, maxNumberOfBodyLinesInCompactMode: info.maxNumberOfLines) return cell } func calendarSettingCell(with setting: CalendarSettings) -> CalendarSettingTableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath) as CalendarSettingTableViewCell cell.configure(with: show, setting: setting) return cell } func calendarActionCell(with type: CalendarActionTableViewCell.ActionType, isLastOfSection: Bool = false, isLastOfTable: Bool = false) -> CalendarActionTableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath) as CalendarActionTableViewCell cell.configure(with: show, type: type, bottomMarginSize: isLastOfTable ? .medium : (isLastOfSection ? .large : .regular), showsSeparator: (isLastOfSection || !isLastOfTable) ? true : false, settingsManager: calendarSettingsManager) return cell } // Cell selection switch indexPath.section { // SHOW DETAIL + ACTIONS SECTION case 0: if indexPath.row == 0 { return detailShowCell() } else { return showActionsCell() } // SHOW INFO SECTION case 1 where hasInfoSection: return infoCell() // DEFAULT CALENDAR SETTINGS SECTION case 1 where !hasInfoSection, 2: switch indexPath.row { // Calendar section title cell case 0: return tableView.dequeueReusableCell(withIdentifier: "CalendarSettingsTitleCell", for: indexPath) // "Creates calendar events" cell case 1: return calendarSettingCell(with: .createCalendarEvents) // "Disable calendar events for all" defaults cell case 2 where numberOfCellsInDefaultCalendarSettingsSection == 3: return calendarActionCell(with: .disableCalendarEventsForAll, isLastOfTable: true) // "Events name" cell case 2...CalendarSettings.numberOfDefaultOnlySettings: return calendarSettingCell(with: CalendarSettings(rawValue: indexPath.row + defaultsOnlySettingsRawValueOffset)!) // "Enable calendar for all shows" defaults cell case CalendarSettings.numberOfDefaultOnlySettings + 1: return calendarActionCell(with: .enableCalendarEventsForAll, isLastOfSection: true) default: assertionFailure() } // SHOW-SPECIFIC CALENDAR SETTINGS SECTION case 2 where !hasInfoSection, 3: switch indexPath.row { // Remaining calendar settings cells case 0..<CalendarSettings.numberOfShowSpecificSettings: return calendarSettingCell(with: CalendarSettings(rawValue: indexPath.row + showSpecificSettingsRawValueOffset)!) // "Set default settings for all shows" cell case CalendarSettings.numberOfShowSpecificSettings where numberOfCellsInShowSpecificCalendarSettingsSection > CalendarSettings.numberOfShowSpecificSettings + 1: return calendarActionCell(with: .setDefaultSettings) // "Reset to default settings" cell case CalendarSettings.numberOfShowSpecificSettings where numberOfCellsInShowSpecificCalendarSettingsSection == CalendarSettings.numberOfShowSpecificSettings + 1, CalendarSettings.numberOfShowSpecificSettings + 1: return calendarActionCell(with: .resetToDefaultSettings, isLastOfTable: true) default: assertionFailure() } default: assertionFailure() } assertionFailure() return UITableViewCell() } } // MARK: - Number of cells and section existence fileprivate extension ShowDetailDataSource { var hasActionsCell: Bool { return show?.trailerUrl != nil || show?.imdbUrl != nil || show?.isPersistent == true } var hasInfoSection: Bool { return !showInfo.isEmpty } var hasDefaultCalendarSettingsSection: Bool { return numberOfCellsInDefaultCalendarSettingsSection > 0 } var hasShowSpecificCalendarSettingsSection: Bool { return numberOfCellsInShowSpecificCalendarSettingsSection > 0 } var numberOfCellsInDefaultCalendarSettingsSection: Int { guard let show = show else { return 0 } // No calendar settings for untracked shows if !show.isPersistent { return 0 } // Calendar access not authorized: title + createCalendarEvents if CalendarEventsManager.authorizationStatus != .authorized { return 2 } // Creates calendar events setting disabled if !CalendarSettingsManager.boolValue(of: .createCalendarEvents, for: show) { // If not disabled for all shows: title + createCalendarEvents + disableForAllShows if CalendarSettingsManager.DefaultSettings.createsCalendarEvents { return 3 } // If already disabled for all shows: title + createCalendarEvents else { return 2 } } // Creates calendar events setting enabled else { return 2 + CalendarSettings.numberOfDefaultOnlySettings // title + createCalendarEvents + eventsName + enableForAllShows } } var numberOfCellsInShowSpecificCalendarSettingsSection: Int { guard let show = show else { return 0 } // Not persistent, not creating events or not authorized to if !hasDefaultCalendarSettingsSection || CalendarEventsManager.authorizationStatus != .authorized || !CalendarSettingsManager.boolValue(of: .createCalendarEvents, for: show) { return 0 } // Remaining settings + reset and set default settings if show's settings are different, or just reset default settings otherwise (even if it is using the default settings that cell shows a message) return CalendarSettings.numberOfShowSpecificSettings + (CalendarSettingsManager.showHasSameSettingsAsDefault(show) ? 1 : 2) } /// The number you have to add to a row in the show-specific settings section to get the raw value of the corresponding CalendarSettings (or add to it to get the row from the raw value). var showSpecificSettingsRawValueOffset: Int { return CalendarSettings.numberOfDefaultOnlySettings } /// The number you have to add to a row in the defaults-only settings section to get the raw value of the corresponding CalendarSettings (or add to it to get the row from the raw value). var defaultsOnlySettingsRawValueOffset: Int { return -1 } } // MARK: - Data generation fileprivate extension ShowDetailDataSource { func updateShowInfo() { showInfo = [] guard let show = show else { return } let formatter = ShowFormatter(source: show) if let summary = show.summary { showInfo.append(("Summary", summary, 4)) } if let genres = show.genres { showInfo.append(("Genre", genres, 1)) } if let runtimeString = formatter.string(for: .runtime) { showInfo.append(("Duration", runtimeString, 1)) } if Global.Other.showDatesInOriginalTimeZoneInDetailInfo { if show.status == .airing, show.timeZone != show.originalTimeZone, let country = show.country, let airDateString = formatter.string(for: .originalAirDayAndTime) { showInfo.append(("Air Date in Original Time Zone", airDateString + " (\(country))", 1)) } else if show.status == .waitingForNewSeason, let country = show.country, let nextSeason = show.currentSeason.value, let premiereDateString = formatter.string(for: .originalNextSeasonPremiereDate(appendingPremieresOnString: false)), let localPremiereDateString = formatter.string(for: .nextSeasonPremiereDate(appendingPremieresOnString: false)), premiereDateString != localPremiereDateString { showInfo.append(("Season \(nextSeason) Premiere in Original Time Zone", premiereDateString + " (\(country))", 1)) } } if let actors = show.actors { showInfo.append(("Actors", actors, 1)) } } } // MARK: - Place for cells fileprivate extension ShowDetailDataSource { func indexPathsForSettingCellsInShowSpecificSection() -> [IndexPath] { return (0..<CalendarSettings.numberOfShowSpecificSettings).map { IndexPath(row: $0, section: calendarShowSpecificSettingsSection!) } } /// The index path the CalendarActionTableViewCell would have if it existed. /// - warning: Use carefully. This assumes the section where the cell would be exists. func indexPathCalendarActionCellWouldHave(withType type: CalendarActionTableViewCell.ActionType) -> IndexPath { switch type { case .disableCalendarEventsForAll: return IndexPath(row: 2, section: calendarDefaultSettingsSection!) case .enableCalendarEventsForAll: return IndexPath(row: CalendarSettings.numberOfDefaultOnlySettings + 1, section: calendarDefaultSettingsSection!) case .setDefaultSettings: return IndexPath(row: CalendarSettings.numberOfShowSpecificSettings, section: calendarShowSpecificSettingsSection!) case .resetToDefaultSettings: return IndexPath(row: CalendarSettings.numberOfShowSpecificSettings + 1, section: calendarShowSpecificSettingsSection!) } } func indexPathsForCellsAffectedByCreateCalendarEvents() -> (AlteredIndexPaths, AlteredSections) { guard let show = show else { return (([],[],[]), ([],[])) } let section = calendarDefaultSettingsSection! // all default-only settings except "create events" plus one action button let numberOfTemporaryCells = CalendarSettings.numberOfDefaultOnlySettings - 1 + 1 // They all go right after cell 1 (the "create events" cell) let temporaryCellsIndexPaths = (2..<(2 + numberOfTemporaryCells)).map { IndexPath(row: $0, section: section) } // The action button at the end of section when "create events" is off, if defaults is not off too. let disableEventsActionCellIndexPathOrEmpty = CalendarSettingsManager.DefaultSettings.createsCalendarEvents ? [IndexPath(row: 2, section: section)] : [] // The "creates events" cell let updatedCellIndexPath = [IndexPath(row: 1, section: section)] let showSpecificSectionIndex = IndexSet(integer: section + 1) // Turning on "creates events" if CalendarSettingsManager.boolValue(of: .createCalendarEvents, for: show) { return ((temporaryCellsIndexPaths, // add disableEventsActionCellIndexPathOrEmpty, // delete updatedCellIndexPath // update ), (showSpecificSectionIndex, IndexSet())) // add, delete } // Turning off "creates events" else { return ((disableEventsActionCellIndexPathOrEmpty, // add temporaryCellsIndexPaths, // delete updatedCellIndexPath // update ), (IndexSet(), showSpecificSectionIndex)) // add, delete } } func indexPathsForCellsAffectedByEventsName() -> (AlteredIndexPaths, AlteredSections) { return (([],[],[indexPathOfInitatingCell(for: .eventsName, section: .defaultsOnly)]),([],[])) } func indexPathsForCellsAffectedByCreateEventsForAllSeasons(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) { var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView) indexPaths.updated.append(indexPathOfInitatingCell(for: .createEventsForAllSeasons, section: .showSpecific)) return (indexPaths, ([],[])) } func indexPathsForCellsAffectedByCreateAllDayEvents(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) { var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView) indexPaths.updated.append(indexPathOfInitatingCell(for: .createAllDayEvents, section: .showSpecific)) // original time zone is disabled if all day events is true indexPaths.updated.append(indexPathOfInitatingCell(for: .useOriginalTimeZone, section: .showSpecific)) return (indexPaths, ([],[])) } func indexPathsForCellsAffectedByUseOriginalTimeZone(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) { var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView) indexPaths.updated.append(indexPathOfInitatingCell(for: .useOriginalTimeZone, section: .showSpecific)) return (indexPaths, ([],[])) } func indexPathsForCellsAffectedByUseNetworkAsLocation(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) { var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView) indexPaths.updated.append(indexPathOfInitatingCell(for: .useNetworkAsLocation, section: .showSpecific)) return (indexPaths, ([],[])) } func indexPathsForCellsAffectedBySetAlarms(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) { var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView) indexPaths.updated.append(indexPathOfInitatingCell(for: .setAlarms, section: .showSpecific)) return (indexPaths, ([],[])) } enum SettingsSection { case defaultsOnly, showSpecific } /// The index path of the cell corresponding to the specified setting. private func indexPathOfInitatingCell(for setting: CalendarSettings, section: SettingsSection) -> IndexPath { let row = setting.rawValue + (section == .defaultsOnly ? -defaultsOnlySettingsRawValueOffset : -showSpecificSettingsRawValueOffset) let section = section == .defaultsOnly ? calendarDefaultSettingsSection! : calendarShowSpecificSettingsSection! return IndexPath(row: row, section: section) } /// The `AlteredIndexPaths` for the "set default settings" and "reset to default settings" action cells in the show-specific calendar settings table section. private func indexPathOfAffectedShowSpecificSectionActionCells(in tableView: UITableView) -> AlteredIndexPaths { let numberOfRowsBefore = tableView.numberOfRows(inSection: calendarShowSpecificSettingsSection!) let numberOfRowAfter = numberOfCellsInShowSpecificCalendarSettingsSection let section = calendarShowSpecificSettingsSection! let setDefaultsIndexPath = IndexPath(row: CalendarSettings.numberOfShowSpecificSettings, section: section) let resetDefaultsIndexPath = IndexPath(row: CalendarSettings.numberOfShowSpecificSettings + 1, section: section) // Need to delete the "set defaults" cell and update "reset defaults" if numberOfRowsBefore > numberOfRowAfter { return ([], [setDefaultsIndexPath], [resetDefaultsIndexPath]) } // Need to add the "set defaults" cell and update "reset defaults" else if numberOfRowsBefore < numberOfRowAfter { return ([setDefaultsIndexPath], [], [resetDefaultsIndexPath]) } // If same number of actions, no updates else { return ([],[],[]) } } }
gpl-3.0
chaselatta/Channels
Channels/Channel.swift
1
765
// // Channel.swift // Channels // // Created by Chase Latta on 11/23/15. // Copyright © 2015 Chase Latta. All rights reserved. // public struct Channel<Data> { private let sink: ChannelSink public init(sink: ChannelSink) { self.sink = sink } public func registerListener<T: AnyObject>(listener: T, handler: (T, Data) -> ()) { sink.registerListener(listener) { target, data in if let typedData = data as? Data, let typedTarget = target as? T { handler(typedTarget, typedData) } } } public func unregisterListener(listener: AnyObject?) { guard let listener = listener else { return } sink.unregisterListener(listener) } }
mit
DAloG/BlueCap
BlueCapKit/Service Profile Definitions/GnosusProfiles.swift
1
7811
// // GnosusProfiles.swift // BlueCap // // Created by Troy Stribling on 7/25/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation import CoreBluetooth public struct Gnosus { //*************************************************************************************************** // Hello World Service public struct HelloWorldService : ServiceConfigurable { // ServiceConfigurable public static let uuid = "2f0a0000-69aa-f316-3e78-4194989a6c1a" public static let name = "Hello World" public static let tag = "gnos.us" public struct Greeting : CharacteristicConfigurable { // BLEConfigurable public static let uuid = "2f0a0001-69aa-f316-3e78-4194989a6c1a" public static let name = "Hello World Greeting" public static let permissions : CBAttributePermissions = [.Readable, .Writeable] public static let properties : CBCharacteristicProperties = [.Read, .Notify] public static let initialValue = Serde.serialize("Hello") } public struct UpdatePeriod : RawDeserializable, CharacteristicConfigurable, StringDeserializable { public let period : UInt16 // CharacteristicConfigurable public static let uuid = "2f0a0002-69aa-f316-3e78-4194989a6c1a" public static let name = "Update Period" public static let permissions : CBAttributePermissions = [.Readable, .Writeable] public static let properties : CBCharacteristicProperties = [.Read, .Write] public static let initialValue : NSData? = Serde.serialize(UInt16(5000)) // RawDeserializable public var rawValue : UInt16 { return self.period } public init?(rawValue:UInt16) { self.period = rawValue } // StringDeserializable public static var stringValues : [String] { return [] } public var stringValue : [String:String] { return [UpdatePeriod.name:"\(self.period)"] } public init?(stringValue:[String:String]) { if let value = uint16ValueFromStringValue(UpdatePeriod.name, values:stringValue) { self.period = value } else { return nil } } } } //*************************************************************************************************** // Location Service public struct LocationService : ServiceConfigurable { // ServiceConfigurable public static let uuid = "2f0a0001-69aa-f316-3e78-4194989a6c1a" public static let name = "Location" public static let tag = "gnos.us" public struct LatitudeAndLongitude : RawArrayDeserializable, CharacteristicConfigurable, StringDeserializable { private let latitudeRaw : Int16 private let longitudeRaw : Int16 public let latitude : Double public let longitude : Double public init?(latitude:Double, longitude:Double) { self.latitude = latitude self.longitude = longitude if let rawValues = LatitudeAndLongitude.rawFromValues([latitude, longitude]) { (self.latitudeRaw, self.longitudeRaw) = rawValues } else { return nil } } private static func valuesFromRaw(rawValues:[Int16]) -> (Double, Double) { return (100.0*Double(rawValues[0]), 100.0*Double(rawValues[1])) } private static func rawFromValues(values:[Double]) -> (Int16, Int16)? { let latitudeRaw = Int16(doubleValue:values[0]/100.0) let longitudeRaw = Int16(doubleValue:values[1]/100.0) if latitudeRaw != nil && longitudeRaw != nil { return (latitudeRaw!, longitudeRaw!) } else { return nil } } // CharacteristicConfigurable public static let uuid = "2f0a0017-69aa-f316-3e78-4194989a6c1a" public static let name = "Lattitude and Longitude" public static let permissions : CBAttributePermissions = [.Readable, .Writeable] public static let properties : CBCharacteristicProperties = [.Read, .Write] public static let initialValue : NSData? = Serde.serialize(Gnosus.LocationService.LatitudeAndLongitude(latitude:37.752760, longitude:-122.413234)!) // RawArrayDeserializable public static let size = 4 public var rawValue : [Int16] { return [self.latitudeRaw, self.longitudeRaw] } public init?(rawValue:[Int16]) { if rawValue.count == 2 { self.latitudeRaw = rawValue[0] self.longitudeRaw = rawValue[1] (self.latitude, self.longitude) = LatitudeAndLongitude.valuesFromRaw(rawValue) } else { return nil } } // StringDeserializable public static var stringValues : [String] { return [] } public var stringValue : [String:String] { return ["latitudeRaw":"\(self.latitudeRaw)", "longitudeRaw":"\(self.longitudeRaw)", "latitude":"\(self.latitude)", "longitude":"\(self.longitude)"] } public init?(stringValue:[String:String]) { let lat = int16ValueFromStringValue("latitudeRaw", values:stringValue) let lon = int16ValueFromStringValue("longitudeRaw", values:stringValue) if lat != nil && lon != nil { self.latitudeRaw = lat! self.longitudeRaw = lon! (self.latitude, self.longitude) = LatitudeAndLongitude.valuesFromRaw([self.latitudeRaw, self.longitudeRaw]) } else { return nil } } } } } public struct GnosusProfiles { public static func create() { let profileManager = ProfileManager.sharedInstance // Hello World Service let helloWorldService = ConfiguredServiceProfile<Gnosus.HelloWorldService>() let greetingCharacteristic = StringCharacteristicProfile<Gnosus.HelloWorldService.Greeting>() let updateCharacteristic = RawCharacteristicProfile<Gnosus.HelloWorldService.UpdatePeriod>() helloWorldService.addCharacteristic(greetingCharacteristic) helloWorldService.addCharacteristic(updateCharacteristic) profileManager.addService(helloWorldService) // Location Service let locationService = ConfiguredServiceProfile<Gnosus.LocationService>() let latlonCharacteristic = RawArrayCharacteristicProfile<Gnosus.LocationService.LatitudeAndLongitude>() locationService.addCharacteristic(latlonCharacteristic) profileManager.addService(locationService) } }
mit
emilstahl/swift
stdlib/public/SDK/Foundation/NSValue.swift
10
1135
//===--- NSValue.swift - Bridging things in NSValue -------------*-swift-*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// extension NSRange : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public static func _getObjectiveCType() -> Any.Type { return NSValue.self } public func _bridgeToObjectiveC() -> NSValue { return NSValue(range: self) } public static func _forceBridgeFromObjectiveC( x: NSValue, inout result: NSRange? ) { result = x.rangeValue } public static func _conditionallyBridgeFromObjectiveC( x: NSValue, inout result: NSRange? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } }
apache-2.0
yanagiba/swift-ast
Tests/ParserTests/Declaration/ParserConstantDeclarationTests.swift
2
8905
/* Copyright 2017-2018 Ryuichi Intellectual Property and the Yanagiba project 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 XCTest @testable import AST @testable import Parser class ParserConstantDeclarationTests: XCTestCase { func testDefineConstant() { parseDeclarationAndTest("let foo", "let foo", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[0].initializerExpression) }) } func testDefineConstantWithTypeAnnotation() { parseDeclarationAndTest("let foo: Foo", "let foo: Foo", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo: Foo") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[0].initializerExpression) }) } func testDefineConstantWithInitializer() { parseDeclarationAndTest("let foo: Foo = bar", "let foo: Foo = bar", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo: Foo = bar") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNotNil(constDecl.initializerList[0].initializerExpression) }) } func testMultipleDecls() { parseDeclarationAndTest("let foo = bar, a, x = y", "let foo = bar, a, x = y", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 3) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo = bar") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNotNil(constDecl.initializerList[0].initializerExpression) XCTAssertEqual(constDecl.initializerList[1].textDescription, "a") XCTAssertTrue(constDecl.initializerList[1].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[1].initializerExpression) XCTAssertEqual(constDecl.initializerList[2].textDescription, "x = y") XCTAssertTrue(constDecl.initializerList[2].pattern is IdentifierPattern) XCTAssertNotNil(constDecl.initializerList[2].initializerExpression) }) } func testAttributes() { parseDeclarationAndTest("@a let foo", "@a let foo", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertEqual(constDecl.attributes.count, 1) ASTTextEqual(constDecl.attributes[0].name, "a") XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[0].initializerExpression) }) } func testModifiers() { parseDeclarationAndTest( "private nonmutating static final let foo = bar", "private nonmutating static final let foo = bar", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertEqual(constDecl.modifiers.count, 4) XCTAssertEqual(constDecl.modifiers[0], .accessLevel(.private)) XCTAssertEqual(constDecl.modifiers[1], .mutation(.nonmutating)) XCTAssertEqual(constDecl.modifiers[2], .static) XCTAssertEqual(constDecl.modifiers[3], .final) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo = bar") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNotNil(constDecl.initializerList[0].initializerExpression) }) } func testAttributeAndModifiers() { parseDeclarationAndTest("@a fileprivate let foo", "@a fileprivate let foo", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertEqual(constDecl.attributes.count, 1) ASTTextEqual(constDecl.attributes[0].name, "a") XCTAssertEqual(constDecl.modifiers.count, 1) XCTAssertEqual(constDecl.modifiers[0], .accessLevel(.fileprivate)) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[0].initializerExpression) }) } func testFollowedByTrailingClosure() { parseDeclarationAndTest( "let foo = bar { $0 == 0 }", "let foo = bar { $0 == 0 }", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo = bar { $0 == 0 }") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertTrue(constDecl.initializerList[0].initializerExpression is FunctionCallExpression) }) parseDeclarationAndTest( "let foo = bar { $0 = 0 }, a = b { _ in true }, x = y { t -> Int in t^2 }", "let foo = bar { $0 = 0 }, a = b { _ in\ntrue\n}, x = y { t -> Int in\nt ^ 2\n}") parseDeclarationAndTest( "let foo = bar { $0 == 0 }.joined()", "let foo = bar { $0 == 0 }.joined()") } func testFollowedBySemicolon() { parseDeclarationAndTest("let issue = 61;", "let issue = 61") } func testSourceRange() { parseDeclarationAndTest("let foo", "let foo", testClosure: { decl in XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 8)) }) parseDeclarationAndTest("@a let foo = bar, a, x = y", "@a let foo = bar, a, x = y", testClosure: { decl in XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 27)) }) parseDeclarationAndTest("private let foo, bar", "private let foo, bar", testClosure: { decl in XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 21)) }) parseDeclarationAndTest("let foo = bar { $0 == 0 }", "let foo = bar { $0 == 0 }", testClosure: { decl in XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 26)) }) } static var allTests = [ ("testDefineConstant", testDefineConstant), ("testDefineConstantWithTypeAnnotation", testDefineConstantWithTypeAnnotation), ("testDefineConstantWithInitializer", testDefineConstantWithInitializer), ("testMultipleDecls", testMultipleDecls), ("testAttributes", testAttributes), ("testModifiers", testModifiers), ("testAttributeAndModifiers", testAttributeAndModifiers), ("testFollowedByTrailingClosure", testFollowedByTrailingClosure), ("testFollowedBySemicolon", testFollowedBySemicolon), ("testSourceRange", testSourceRange), ] }
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/01251-getcallerdefaultarg.swift
1
580
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 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 // RUN: not %target-swift-frontend %s -typecheck class func a() -> String { re> d) { } protocol A { } init <A: A where A.B == D>(e: A.B) { } var e: Int -> Int = { return $0 = { c, b in }(f, e) func a(b: Int = 0) { } let c = a c()
apache-2.0
Fri3ndlyGerman/OpenWeatherSwift
Sources/HPOpenWeather/DataTypes/Sun.swift
1
323
import Foundation /// Type that holds information about sunrise and sunset times in UTC time public struct Sun: Codable, Equatable, Hashable { /// Sunset time public let sunset: Date /// Sunrise timeWind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour. public let sunrise: Date }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/02194-swift-nominaltypedecl-getdeclaredtypeincontext.swift
1
590
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 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 // RUN: not %target-swift-frontend %s -typecheck protocol A { protocol C { protocol a { class c : Int { } } class A<h : A : X<T.A<T, q:Any) -> T> : a { func a () -> S) -> T.init() { struct c: String { } public var b: d { } } } } func c: C {
apache-2.0
knutnyg/picnic
picnicTests/ConvertionRateManagerTests.swift
1
3278
import Foundation import XCTest class ConvertionRateManagerTests : XCTestCase { var userModel:UserModel! // var conversionRateManagerSub:ConversionRateManagerSub! // var conversionRateManagerIntegration:ConversionRateManager! override func setUp() { super.setUp() userModel = UserModel() } func testMissingConfigFileThrowsException(){ let cvr = ConversionRateManager(userModel: userModel) cvr.configPath = "wrong" XCTAssertNil(cvr.loadConfig(), "loading config should fail: 404") } func testGetAllCurrenciesIllegalResponse(){ let crm = ConversionRateManager(userModel: userModel) setBundleToTest(crm) crm.config = crm.loadConfig() let URL = crm.getAllCurrenciesURL()! let expected = "http://example.com/api/currencies" XCTAssertEqual(URL.description,expected,"should be equal") } func testGetAllCurrenciesURL(){ let crm = ConversionRateManager(userModel: userModel) setBundleToTest(crm) crm.config = crm.loadConfig() let URL = crm.getAllCurrenciesURL()! let expected = "http://example.com/api/currencies" XCTAssertEqual(URL.description,expected,"should be equal") } func testOfflineConversionRate(){ let userModel = UserModel() var dict:[String:OfflineEntry] = [:] dict["NOK"] = OfflineEntry(timeStamp: Date(), unit_from: "USD", unit_to: "NOK", value: 8) dict["USD"] = OfflineEntry(timeStamp: Date(), unit_from: "USD", unit_to: "USD", value: 1) dict["SEK"] = OfflineEntry(timeStamp: Date(), unit_from: "USD", unit_to: "SEK", value: 10) let norLocale = Locale(identifier: "nb_NO") let usdLocale = Locale(identifier: "en_US") let seLocale = Locale(identifier: "se_SE") userModel.offlineData = dict let conversionRateUSDNOK = userModel.getConversionrate(norLocale, toLocale: usdLocale) XCTAssert(conversionRateUSDNOK! == 0.125, "Conversionrate should be 0.125") let conversionRateUSDSEK = userModel.getConversionrate(seLocale, toLocale: usdLocale) XCTAssert(conversionRateUSDSEK! == 0.1, "Conversionrate should be 0.1") let conversionRateSEKNOK = userModel.getConversionrate(seLocale, toLocale: norLocale) XCTAssert(conversionRateSEKNOK! == 0.8, "Conversionrate should be 0.8") } func testSavingAndLoadingOfflineDataFile(){ var dict:[String:OfflineEntry] = [:] dict["NOK"] = OfflineEntry(timeStamp: Date(), unit_from: "USD", unit_to: "NOK", value: 2) saveDictionaryToDisk("test.dat", dict: dict) let loadedDict = readOfflineDateFromDisk("test.dat") XCTAssertNotNil(loadedDict, "shouldNotBeNil") } func testLoadingNilShouldNotCrashApp(){ let result = readOfflineDateFromDisk("doesNotExist.dat") XCTAssertNil(result, "should be nil!") } func setBundleToTest(_ crm:ConversionRateManager){ let bundle = Bundle(for: ConvertionRateManagerTests.self) crm.configPath = bundle.path(forResource: "config_test", ofType: "plist") } }
bsd-2-clause
julienbodet/wikipedia-ios
Wikipedia/Code/WMFAuthAccountCreationInfoFetcher.swift
1
2376
public enum WMFAuthAccountCreationError: LocalizedError { case cannotExtractInfo case cannotCreateAccountsNow public var errorDescription: String? { switch self { case .cannotExtractInfo: return "Could not extract account creation info" case .cannotCreateAccountsNow: return "Unable to create accounts at this time" } } } public typealias WMFAuthAccountCreationInfoBlock = (WMFAuthAccountCreationInfo) -> Void public struct WMFAuthAccountCreationInfo { let canCreateAccounts:Bool let captcha: WMFCaptcha? init(canCreateAccounts:Bool, captcha:WMFCaptcha?) { self.canCreateAccounts = canCreateAccounts self.captcha = captcha } } public class WMFAuthAccountCreationInfoFetcher { private let manager = AFHTTPSessionManager.wmf_createDefault() public func isFetching() -> Bool { return manager.operationQueue.operationCount > 0 } public func fetchAccountCreationInfoForSiteURL(_ siteURL: URL, success: @escaping WMFAuthAccountCreationInfoBlock, failure: @escaping WMFErrorHandler){ let manager = AFHTTPSessionManager(baseURL: siteURL) manager.responseSerializer = WMFApiJsonResponseSerializer.init(); let parameters = [ "action": "query", "meta": "authmanagerinfo", "amirequestsfor": "create", "format": "json" ] _ = manager.wmf_apiPOSTWithParameters(parameters, success: { (_, response) in guard let response = response as? [String : AnyObject], let query = response["query"] as? [String : AnyObject], let authmanagerinfo = query["authmanagerinfo"] as? [String : AnyObject], let requests = authmanagerinfo["requests"] as? [[String : AnyObject]] else { failure(WMFAuthAccountCreationError.cannotExtractInfo) return } guard authmanagerinfo["cancreateaccounts"] != nil else { failure(WMFAuthAccountCreationError.cannotCreateAccountsNow) return } success(WMFAuthAccountCreationInfo.init(canCreateAccounts: true, captcha: WMFCaptcha.captcha(from: requests))) }, failure: { (_, error) in failure(error) }) } }
mit
josve05a/wikipedia-ios
Wikipedia/Code/OnThisDayViewControllerHeader.swift
2
2731
import UIKit class OnThisDayViewControllerHeader: UICollectionReusableView { @IBOutlet weak var eventsLabel: UILabel! @IBOutlet weak var onLabel: UILabel! @IBOutlet weak var fromLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() updateFonts() apply(theme: Theme.standard) wmf_configureSubviewsForDynamicType() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } private func updateFonts() { onLabel.font = UIFont.wmf_font(.heavyTitle1, compatibleWithTraitCollection: traitCollection) } func configureFor(eventCount: Int, firstEvent: WMFFeedOnThisDayEvent?, lastEvent: WMFFeedOnThisDayEvent?, midnightUTCDate: Date) { let language = firstEvent?.language let locale = NSLocale.wmf_locale(for: language) semanticContentAttribute = MWLanguageInfo.semanticContentAttribute(forWMFLanguage: language) eventsLabel.semanticContentAttribute = semanticContentAttribute onLabel.semanticContentAttribute = semanticContentAttribute fromLabel.semanticContentAttribute = semanticContentAttribute eventsLabel.text = String(format: WMFLocalizedString("on-this-day-detail-header-title", language: language, value:"{{PLURAL:%1$d|%1$d historical event|%1$d historical events}}", comment:"Title for 'On this day' detail view - %1$d is replaced with the number of historical events which occurred on the given day"), locale: locale, eventCount).uppercased(with: locale) onLabel.text = DateFormatter.wmf_monthNameDayNumberGMTFormatter(for: language).string(from: midnightUTCDate) if let firstEventEraString = firstEvent?.yearString, let lastEventEraString = lastEvent?.yearString { fromLabel.text = String(format: WMFLocalizedString("on-this-day-detail-header-date-range", language: language, value:"from %1$@ - %2$@", comment:"Text for 'On this day' detail view events 'year range' label - %1$@ is replaced with string version of the oldest event year - i.e. '300 BC', %2$@ is replaced with string version of the most recent event year - i.e. '2006', "), locale: locale, lastEventEraString, firstEventEraString) } else { fromLabel.text = nil } } } extension OnThisDayViewControllerHeader: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground eventsLabel.textColor = theme.colors.secondaryText onLabel.textColor = theme.colors.primaryText fromLabel.textColor = theme.colors.secondaryText } }
mit
julienbodet/wikipedia-ios
WMF Framework/EventLoggingService.swift
1
20882
import Foundation enum EventLoggingError { case generic } @objc(WMFEventLoggingService) public class EventLoggingService : NSObject, URLSessionDelegate { private struct Key { static let isEnabled = "SendUsageReports" static let appInstallID = "WMFAppInstallID" static let lastLoggedSnapshot = "WMFLastLoggedSnapshot" static let appInstallDate = "AppInstallDate" static let loggedDaysInstalled = "DailyLoggingStatsDaysInstalled" } public var pruningAge: TimeInterval = 60*60*24*30 // 30 days public var sendImmediatelyOnWWANThreshhold: TimeInterval = 30 public var postBatchSize = 10 public var postTimeout: TimeInterval = 60*2 // 2 minutes public var postInterval: TimeInterval = 60*10 // 10 minutes public var debugDisableImmediateSend = false private static let scheme = "https" // testing is http private static let host = "meta.wikimedia.org" // testing is deployment.wikimedia.beta.wmflabs.org private static let path = "/beacon/event" private let reachabilityManager: AFNetworkReachabilityManager private let urlSessionConfiguration: URLSessionConfiguration private var urlSession: URLSession? private let postLock = NSLock() private var posting = false private var started = false private var timer: Timer? private var lastNetworkRequestTimestamp: TimeInterval? private let persistentStoreCoordinator: NSPersistentStoreCoordinator private let managedObjectContext: NSManagedObjectContext @objc(sharedInstance) public static let shared: EventLoggingService = { let fileManager = FileManager.default var permanentStorageDirectory = fileManager.wmf_containerURL().appendingPathComponent("Event Logging", isDirectory: true) var didGetDirectoryExistsError = false do { try fileManager.createDirectory(at: permanentStorageDirectory, withIntermediateDirectories: true, attributes: nil) } catch let error { DDLogError("EventLoggingService: Error creating permanent cache: \(error)") } do { var values = URLResourceValues() values.isExcludedFromBackup = true try permanentStorageDirectory.setResourceValues(values) } catch let error { DDLogError("EventLoggingService: Error excluding from backup: \(error)") } let permanentStorageURL = permanentStorageDirectory.appendingPathComponent("Events.sqlite") DDLogDebug("EventLoggingService: Events persistent store: \(permanentStorageURL)") return EventLoggingService(permanentStorageURL: permanentStorageURL) }() @objc public func log(event: Dictionary<String, Any>, schema: String, revision: Int, wiki: String) { let event: NSDictionary = ["event": event, "schema": schema, "revision": revision, "wiki": wiki] logEvent(event) } private var shouldSendImmediately: Bool { if !started { return false } if (debugDisableImmediateSend) { return false } if self.reachabilityManager.isReachableViaWiFi { return true } if self.reachabilityManager.isReachableViaWWAN, let lastNetworkRequestTimestamp = self.lastNetworkRequestTimestamp, Date.timeIntervalSinceReferenceDate < (lastNetworkRequestTimestamp + sendImmediatelyOnWWANThreshhold) { return true } return false } public init(urlSesssionConfiguration: URLSessionConfiguration, reachabilityManager: AFNetworkReachabilityManager, permanentStorageURL: URL? = nil) { self.reachabilityManager = reachabilityManager self.urlSessionConfiguration = urlSesssionConfiguration let bundle = Bundle.wmf let modelURL = bundle.url(forResource: "EventLogging", withExtension: "momd")! let model = NSManagedObjectModel(contentsOf: modelURL)! let psc = NSPersistentStoreCoordinator(managedObjectModel: model) let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(booleanLiteral: true), NSInferMappingModelAutomaticallyOption: NSNumber(booleanLiteral: true)] if let storeURL = permanentStorageURL { do { try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) } catch { do { try FileManager.default.removeItem(at: storeURL) } catch { } do { try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) } catch { abort() } } } else { do { try psc.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: options) } catch { abort() } } self.persistentStoreCoordinator = psc self.managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) self.managedObjectContext.persistentStoreCoordinator = psc } public convenience init(permanentStorageURL: URL) { let reachabilityManager = AFNetworkReachabilityManager.init(forDomain: EventLoggingService.host) let urlSessionConfig = URLSessionConfiguration.default urlSessionConfig.httpShouldUsePipelining = true urlSessionConfig.allowsCellularAccess = true urlSessionConfig.httpMaximumConnectionsPerHost = 2 urlSessionConfig.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData self.init(urlSesssionConfiguration: urlSessionConfig, reachabilityManager: reachabilityManager, permanentStorageURL: permanentStorageURL) } deinit { stop() } @objc public func start() { assert(Thread.isMainThread, "must be started on main thread") guard !self.started else { return } self.started = true self.urlSession = URLSession(configuration: self.urlSessionConfiguration, delegate: self, delegateQueue: nil) NotificationCenter.default.addObserver(forName: NSNotification.Name.WMFNetworkRequestBegan, object: nil, queue: .main) { (note) in self.lastNetworkRequestTimestamp = Date.timeIntervalSinceReferenceDate //DDLogDebug("last network request: \(String(describing: self.lastNetworkRequestTimestamp))") } self.reachabilityManager.setReachabilityStatusChange { (status) in switch status { case .reachableViaWiFi: self.tryPostEvents() default: break } } self.reachabilityManager.startMonitoring() self.timer = Timer.scheduledTimer(timeInterval: self.postInterval, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true) prune() #if DEBUG self.managedObjectContext.perform { do { let countFetch: NSFetchRequest<EventRecord> = EventRecord.fetchRequest() countFetch.includesSubentities = false let count = try self.managedObjectContext.count(for: countFetch) DDLogInfo("EventLoggingService: There are \(count) queued events") } catch let error { DDLogError(error.localizedDescription) } } #endif } @objc private func timerFired() { tryPostEvents() asyncSave() } @objc public func stop() { assert(Thread.isMainThread, "must be stopped on main thread") guard self.started else { return } self.started = false self.reachabilityManager.stopMonitoring() self.urlSession?.finishTasksAndInvalidate() self.urlSession = nil NotificationCenter.default.removeObserver(self) self.timer?.invalidate() self.timer = nil self.managedObjectContext.performAndWait { self.save() } } @objc public func reset() { self.resetSession() self.resetInstall() } private func prune() { self.managedObjectContext.perform { let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "WMFEventRecord") fetch.returnsObjectsAsFaults = false let pruneDate = Date().addingTimeInterval(-(self.pruningAge)) as NSDate fetch.predicate = NSPredicate(format: "(recorded < %@) OR (posted != nil) OR (failed == TRUE)", pruneDate) let delete = NSBatchDeleteRequest(fetchRequest: fetch) delete.resultType = .resultTypeCount do { let result = try self.managedObjectContext.execute(delete) guard let deleteResult = result as? NSBatchDeleteResult else { DDLogError("EventLoggingService: Could not read NSBatchDeleteResult") return } guard let count = deleteResult.result as? Int else { DDLogError("EventLoggingService: Could not read NSBatchDeleteResult count") return } DDLogInfo("EventLoggingService: Pruned \(count) events") } catch let error { DDLogError("EventLoggingService: Error pruning events: \(error.localizedDescription)") } } } @objc public func logEvent(_ event: NSDictionary) { let now = NSDate() let moc = self.managedObjectContext moc.perform { let record = NSEntityDescription.insertNewObject(forEntityName: "WMFEventRecord", into: self.managedObjectContext) as! EventRecord record.event = event record.recorded = now record.userAgent = WikipediaAppUtils.versionedUserAgent() DDLogDebug("EventLoggingService: \(record.objectID) recorded!") self.save() if self.shouldSendImmediately { self.tryPostEvents() } } } @objc private func tryPostEvents() { self.postLock.lock() guard started, !posting else { self.postLock.unlock() return } posting = true self.postLock.unlock() let moc = self.managedObjectContext moc.perform { let fetch: NSFetchRequest<EventRecord> = EventRecord.fetchRequest() fetch.sortDescriptors = [NSSortDescriptor(keyPath: \EventRecord.recorded, ascending: true)] fetch.predicate = NSPredicate(format: "(posted == nil) AND (failed != TRUE)") fetch.fetchLimit = self.postBatchSize do { var eventRecords: [EventRecord] = [] defer { if eventRecords.count > 0 { self.postEvents(eventRecords) } else { self.postLock.lock() self.posting = false self.postLock.unlock() } } eventRecords = try moc.fetch(fetch) } catch let error { DDLogError(error.localizedDescription) } } } private func asyncSave() { self.managedObjectContext.perform { self.save() } } private func postEvents(_ eventRecords: [EventRecord]) { assert(posting, "method expects posting to be set when called") DDLogDebug("EventLoggingService: Posting \(eventRecords.count) events!") let taskGroup = WMFTaskGroup() var completedRecordIDs = Set<NSManagedObjectID>() var failedRecordIDs = Set<NSManagedObjectID>() for record in eventRecords { let moid = record.objectID guard let payload = record.event else { failedRecordIDs.insert(moid) continue } taskGroup.enter() let userAgent = record.userAgent ?? WikipediaAppUtils.versionedUserAgent() submit(payload: payload, userAgent: userAgent) { (error) in if error != nil { failedRecordIDs.insert(moid) } else { completedRecordIDs.insert(moid) } taskGroup.leave() } } taskGroup.waitInBackground { self.managedObjectContext.perform { let postDate = NSDate() for moid in completedRecordIDs { let mo = try? self.managedObjectContext.existingObject(with: moid) guard let record = mo as? EventRecord else { continue } record.posted = postDate } for moid in failedRecordIDs { let mo = try? self.managedObjectContext.existingObject(with: moid) guard let record = mo as? EventRecord else { continue } record.failed = true } self.save() self.postLock.lock() self.posting = false self.postLock.unlock() if (completedRecordIDs.count == eventRecords.count) { DDLogDebug("EventLoggingService: All records succeeded, attempting to post more") self.tryPostEvents() } else { DDLogDebug("EventLoggingService: Some records failed, waiting to post more") } } } } private func submit(payload: NSObject, userAgent: String, completion: @escaping (EventLoggingError?) -> Void) { guard let urlSession = self.urlSession else { assertionFailure("urlSession was nil") completion(EventLoggingError.generic) return } do { let payloadJsonData = try JSONSerialization.data(withJSONObject:payload, options: []) guard let payloadString = String(data: payloadJsonData, encoding: .utf8) else { DDLogError("EventLoggingService: Could not convert JSON data to string") completion(EventLoggingError.generic) return } let encodedPayloadJsonString = payloadString.wmf_UTF8StringWithPercentEscapes() var components = URLComponents() components.scheme = EventLoggingService.scheme components.host = EventLoggingService.host components.path = EventLoggingService.path components.percentEncodedQuery = encodedPayloadJsonString guard let url = components.url else { DDLogError("EventLoggingService: Could not creatre URL") completion(EventLoggingError.generic) return } var request = URLRequest(url: url) request.setValue(userAgent, forHTTPHeaderField: "User-Agent") let task = urlSession.dataTask(with: request, completionHandler: { (_, response, error) in guard error == nil, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode / 100 == 2 else { completion(EventLoggingError.generic) return } completion(nil) // DDLogDebug("EventLoggingService: event \(eventRecord.objectID) posted!") }) task.resume() } catch let error { DDLogError(error.localizedDescription) completion(EventLoggingError.generic) return } } // mark stored values private func save() { guard managedObjectContext.hasChanges else { return } do { try managedObjectContext.save() } catch let error { DDLogError("Error saving EventLoggingService managedObjectContext: \(error)") } } private var semaphore = DispatchSemaphore(value: 1) private var libraryValueCache: [String: NSCoding] = [:] private func libraryValue(for key: String) -> NSCoding? { semaphore.wait() defer { semaphore.signal() } var value = libraryValueCache[key] if value != nil { return value } managedObjectContext.performAndWait { value = managedObjectContext.wmf_keyValue(forKey: key)?.value if value != nil { libraryValueCache[key] = value return } if let legacyValue = UserDefaults.wmf_userDefaults().object(forKey: key) as? NSCoding { value = legacyValue libraryValueCache[key] = legacyValue managedObjectContext.wmf_setValue(legacyValue, forKey: key) UserDefaults.wmf_userDefaults().removeObject(forKey: key) save() } } return value } private func setLibraryValue(_ value: NSCoding?, for key: String) { semaphore.wait() defer { semaphore.signal() } libraryValueCache[key] = value managedObjectContext.perform { self.managedObjectContext.wmf_setValue(value, forKey: key) self.save() } } @objc public var isEnabled: Bool { get { var isEnabled = false if let enabledNumber = libraryValue(for: Key.isEnabled) as? NSNumber { isEnabled = enabledNumber.boolValue } return isEnabled } set { setLibraryValue(NSNumber(booleanLiteral: newValue), for: Key.isEnabled) } } @objc public var appInstallID: String? { get { var installID = libraryValue(for: Key.appInstallID) as? String if installID == nil || installID == "" { installID = UUID().uuidString setLibraryValue(installID as NSString?, for: Key.appInstallID) } return installID } set { setLibraryValue(newValue as NSString?, for: Key.appInstallID) } } @objc public var lastLoggedSnapshot: NSCoding? { get { return libraryValue(for: Key.lastLoggedSnapshot) } set { setLibraryValue(newValue, for: Key.lastLoggedSnapshot) } } @objc public var appInstallDate: Date? { get { var value = libraryValue(for: Key.appInstallDate) as? Date if value == nil { value = Date() setLibraryValue(value as NSDate?, for: Key.appInstallDate) } return value } set { setLibraryValue(newValue as NSDate?, for: Key.appInstallDate) } } @objc public var loggedDaysInstalled: NSNumber? { get { return libraryValue(for: Key.loggedDaysInstalled) as? NSNumber } set { setLibraryValue(newValue, for: Key.loggedDaysInstalled) } } private var _sessionID: String? @objc public var sessionID: String? { semaphore.wait() defer { semaphore.signal() } if _sessionID == nil { _sessionID = UUID().uuidString } return _sessionID } private var _sessionStartDate: Date? @objc public var sessionStartDate: Date? { semaphore.wait() defer { semaphore.signal() } if _sessionStartDate == nil { _sessionStartDate = Date() } return _sessionStartDate } @objc public func resetSession() { semaphore.wait() defer { semaphore.signal() } _sessionID = nil _sessionStartDate = Date() } private func resetInstall() { appInstallID = nil lastLoggedSnapshot = nil loggedDaysInstalled = nil appInstallDate = nil } }
mit
FXSolutions/FXDemoXCodeInjectionPlugin
testinjection/Stevia+Operators.swift
2
3645
// // Stevia+Operators.swift // Stevia // // Created by Sacha Durand Saint Omer on 10/02/16. // Copyright © 2016 Sacha Durand Saint Omer. All rights reserved. // import UIKit prefix operator | {} public prefix func | (p:UIView) -> UIView { return p.left(0) } postfix operator | {} public postfix func | (p:UIView) -> UIView { return p.right(0) } infix operator ~ {} public func ~ (left: CGFloat, right: UIView) -> UIView { return right.height(left) } public func ~ (left: UIView, right: CGFloat) -> UIView { return left.height(right) } prefix operator |- {} public prefix func |- (p: CGFloat) -> SideConstraint { var s = SideConstraint() s.constant = p return s } public prefix func |- (v: UIView) -> UIView { v.left(8) return v } postfix operator -| {} public postfix func -| (p: CGFloat) -> SideConstraint { var s = SideConstraint() s.constant = p return s } public postfix func -| (v: UIView) -> UIView { v.right(8) return v } public struct SideConstraint { var constant:CGFloat! } public struct PartialConstraint { var view1:UIView! var constant:CGFloat! var views:[UIView]? } public func - (left: UIView, right: CGFloat) -> PartialConstraint { var p = PartialConstraint() p.view1 = left p.constant = right return p } // Side Constraints public func - (left: SideConstraint, right: UIView) -> UIView { if let spv = right.superview { let c = constraint(item: right, attribute: .Left, toItem: spv, attribute: .Left, constant: left.constant) spv.addConstraint(c) } return right } public func - (left: [UIView], right: SideConstraint) -> [UIView] { let lastView = left[left.count-1] if let spv = lastView.superview { let c = constraint(item: lastView, attribute: .Right, toItem: spv, attribute: .Right, constant: -right.constant) spv.addConstraint(c) } return left } public func - (left:UIView, right: SideConstraint) -> UIView { if let spv = left.superview { let c = constraint(item: left, attribute: .Right, toItem: spv, attribute: .Right, constant: -right.constant) spv.addConstraint(c) } return left } public func - (left: PartialConstraint, right: UIView) -> [UIView] { if let views = left.views { if let spv = right.superview { let lastView = views[views.count-1] let c = constraint(item: lastView, attribute: .Right, toItem: right, attribute: .Left, constant: -left.constant) spv.addConstraint(c) } return views + [right] } else { // were at the end?? nooope?/? if let spv = right.superview { let c = constraint(item: left.view1, attribute: .Right, toItem: right, attribute: .Left, constant: -left.constant) spv.addConstraint(c) } return [left.view1, right] } } public func - (left: UIView, right: UIView) -> [UIView] { if let spv = left.superview { let c = constraint(item: right, attribute: .Left, toItem: left, attribute: .Right, constant: 8) spv.addConstraint(c) } return [left,right] } public func - (left: [UIView], right: CGFloat) -> PartialConstraint { var p = PartialConstraint() p.constant = right p.views = left return p } public func - (left: [UIView], right: UIView) -> [UIView] { let lastView = left[left.count-1] if let spv = lastView.superview { let c = constraint(item: lastView, attribute: .Right, toItem: right, attribute: .Left, constant: -8) spv.addConstraint(c) } return left + [right] }
mit
adrfer/swift
validation-test/compiler_crashers_fixed/26534-swift-modulefile-getdecl.swift
13
242
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {func a{class A{class case,
apache-2.0
rockwotj/FirebaseMovieQuotesiOS
MovieQuotesCoreData/MovieQuoteDetailViewController.swift
1
2162
// // MovieQuoteDetailViewController.swift // MovieQuotesCoreData // // Created by CSSE Department on 3/24/15. // Copyright (c) 2015 CSSE Department. All rights reserved. // import UIKit class MovieQuoteDetailViewController: UIViewController { @IBOutlet weak var quoteLabel: UILabel! @IBOutlet weak var movieLabel: UILabel! var quoteTextField: UITextField? var movieTextField: UITextField? var movieQuote : MovieQuote? override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //TODO: Listen for changes to the quote updateView() } func quoteChanged() { //TODO: Push change to Firebase } func updateView() { quoteLabel.text = movieQuote?.quote movieLabel.text = movieQuote?.movie } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "showEditQuoteDialog") } func showEditQuoteDialog() { let alertController = UIAlertController(title: "Edit new movie quote", message: "", preferredStyle: .Alert) alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in textField.placeholder = "Quote" textField.text = self.movieQuote?.quote self.quoteTextField = textField textField.addTarget(self, action: "quoteChanged", forControlEvents: .EditingChanged) } alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in textField.placeholder = "Movie Title" textField.text = self.movieQuote?.movie self.movieTextField = textField textField.addTarget(self, action: "quoteChanged", forControlEvents: .EditingChanged) } let cancelAction = UIAlertAction(title: "Done", style: .Cancel) { (_) -> Void in println("Done") } alertController.addAction(cancelAction) presentViewController(alertController, animated: true, completion: nil) } }
mit
KrishMunot/swift
test/SILGen/dynamic_self.swift
5
8437
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s protocol P { func f() -> Self } protocol CP : class { func f() -> Self } class X : P, CP { required init(int i: Int) { } // CHECK-LABEL: sil hidden @_TFC12dynamic_self1X1f{{.*}} : $@convention(method) (@guaranteed X) -> @owned func f() -> Self { return self } // CHECK-LABEL: sil hidden @_TZFC12dynamic_self1X7factory{{.*}} : $@convention(method) (Int, @thick X.Type) -> @owned X // CHECK: bb0([[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $@thick X.Type): // CHECK: [[CTOR:%[0-9]+]] = class_method [[SELF]] : $@thick X.Type, #X.init!allocator.1 : X.Type -> (int: Int) -> X , $@convention(method) (Int, @thick X.Type) -> @owned X // CHECK: apply [[CTOR]]([[I]], [[SELF]]) : $@convention(method) (Int, @thick X.Type) -> @owned X class func factory(i: Int) -> Self { return self.init(int: i) } } class Y : X { required init(int i: Int) { } } class GX<T> { func f() -> Self { return self } } class GY<T> : GX<[T]> { } // CHECK-LABEL: sil hidden @_TF12dynamic_self23testDynamicSelfDispatch{{.*}} : $@convention(thin) (@owned Y) -> () func testDynamicSelfDispatch(y: Y) { // CHECK: bb0([[Y:%[0-9]+]] : $Y): // CHECK: strong_retain [[Y]] // CHECK: [[Y_AS_X:%[0-9]+]] = upcast [[Y]] : $Y to $X // CHECK: [[X_F:%[0-9]+]] = class_method [[Y_AS_X]] : $X, #X.f!1 : X -> () -> Self , $@convention(method) (@guaranteed X) -> @owned X // CHECK: [[X_RESULT:%[0-9]+]] = apply [[X_F]]([[Y_AS_X]]) : $@convention(method) (@guaranteed X) -> @owned X // CHECK: strong_release [[Y_AS_X]] // CHECK: [[Y_RESULT:%[0-9]+]] = unchecked_ref_cast [[X_RESULT]] : $X to $Y // CHECK: strong_release [[Y_RESULT]] : $Y // CHECK: strong_release [[Y]] : $Y y.f() } // CHECK-LABEL: sil hidden @_TF12dynamic_self30testDynamicSelfDispatchGeneric{{.*}} : $@convention(thin) (@owned GY<Int>) -> () func testDynamicSelfDispatchGeneric(gy: GY<Int>) { // CHECK: bb0([[GY:%[0-9]+]] : $GY<Int>): // CHECK: strong_retain [[GY]] // CHECK: [[GY_AS_GX:%[0-9]+]] = upcast [[GY]] : $GY<Int> to $GX<Array<Int>> // CHECK: [[GX_F:%[0-9]+]] = class_method [[GY_AS_GX]] : $GX<Array<Int>>, #GX.f!1 : <T> GX<T> -> () -> Self , $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0> // CHECK: [[GX_RESULT:%[0-9]+]] = apply [[GX_F]]<[Int]>([[GY_AS_GX]]) : $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0> // CHECK: strong_release [[GY_AS_GX]] // CHECK: [[GY_RESULT:%[0-9]+]] = unchecked_ref_cast [[GX_RESULT]] : $GX<Array<Int>> to $GY<Int> // CHECK: strong_release [[GY_RESULT]] : $GY<Int> // CHECK: strong_release [[GY]] gy.f() } // CHECK-LABEL: sil hidden @_TF12dynamic_self21testArchetypeDispatch{{.*}} : $@convention(thin) <T where T : P> (@in T) -> () func testArchetypeDispatch<T: P>(t: T) { // CHECK: bb0([[T:%[0-9]+]] : $*T): // CHECK: [[ARCHETYPE_F:%[0-9]+]] = witness_method $T, #P.f!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T // CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[ARCHETYPE_F]]<T>([[T_RESULT]], [[T]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 t.f() } // CHECK-LABEL: sil hidden @_TF12dynamic_self23testExistentialDispatch{{.*}} func testExistentialDispatch(p: P) { // CHECK: bb0([[P:%[0-9]+]] : $*P): // CHECK: [[PCOPY_ADDR:%[0-9]+]] = open_existential_addr [[P]] : $*P to $*@opened([[N:".*"]]) P // CHECK: [[P_RESULT:%[0-9]+]] = alloc_stack $P // CHECK: [[P_RESULT_ADDR:%[0-9]+]] = init_existential_addr [[P_RESULT]] : $*P, $@opened([[N]]) P // CHECK: [[P_F_METHOD:%[0-9]+]] = witness_method $@opened([[N]]) P, #P.f!1, [[PCOPY_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: apply [[P_F_METHOD]]<@opened([[N]]) P>([[P_RESULT_ADDR]], [[PCOPY_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: destroy_addr [[P_RESULT]] : $*P // CHECK: dealloc_stack [[P_RESULT]] : $*P // CHECK: destroy_addr [[P]] : $*P p.f() } // CHECK-LABEL: sil hidden @_TF12dynamic_self28testExistentialDispatchClass{{.*}} : $@convention(thin) (@owned CP) -> () func testExistentialDispatchClass(cp: CP) { // CHECK: bb0([[CP:%[0-9]+]] : $CP): // CHECK: [[CP_ADDR:%[0-9]+]] = open_existential_ref [[CP]] : $CP to $@opened([[N:".*"]]) CP // CHECK: [[CP_F:%[0-9]+]] = witness_method $@opened([[N]]) CP, #CP.f!1, [[CP_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0 // CHECK: [[CP_F_RESULT:%[0-9]+]] = apply [[CP_F]]<@opened([[N]]) CP>([[CP_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0 // CHECK: [[RESULT_EXISTENTIAL:%[0-9]+]] = init_existential_ref [[CP_F_RESULT]] : $@opened([[N]]) CP : $@opened([[N]]) CP, $CP // CHECK: strong_release [[CP_F_RESULT]] : $@opened([[N]]) CP cp.f() } @objc class ObjC { @objc func method() -> Self { return self } } // CHECK-LABEL: sil hidden @_TF12dynamic_self21testAnyObjectDispatch{{.*}} : $@convention(thin) (@owned AnyObject) -> () func testAnyObjectDispatch(o: AnyObject) { // CHECK: dynamic_method_br [[O_OBJ:%[0-9]+]] : $@opened({{.*}}) AnyObject, #ObjC.method!1.foreign, bb1, bb2 // CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject): // CHECK: [[VAR_9:%[0-9]+]] = partial_apply [[METHOD]]([[O_OBJ]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject var x = o.method } // <rdar://problem/16270889> Dispatch through ObjC metatypes. class ObjCInit { dynamic required init() { } } // CHECK: sil hidden @_TF12dynamic_self12testObjCInit{{.*}} : $@convention(thin) (@thick ObjCInit.Type) -> () func testObjCInit(meta: ObjCInit.Type) { // CHECK: bb0([[THICK_META:%[0-9]+]] : $@thick ObjCInit.Type): // CHECK: [[O:%[0-9]+]] = alloc_box $ObjCInit // CHECK: [[PB:%.*]] = project_box [[O]] // CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[THICK_META]] : $@thick ObjCInit.Type to $@objc_metatype ObjCInit.Type // CHECK: [[OBJ:%[0-9]+]] = alloc_ref_dynamic [objc] [[OBJC_META]] : $@objc_metatype ObjCInit.Type, $ObjCInit // CHECK: [[INIT:%[0-9]+]] = class_method [volatile] [[OBJ]] : $ObjCInit, #ObjCInit.init!initializer.1.foreign : ObjCInit.Type -> () -> ObjCInit , $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit // CHECK: [[RESULT_OBJ:%[0-9]+]] = apply [[INIT]]([[OBJ]]) : $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit // CHECK: store [[RESULT_OBJ]] to [[PB]] : $*ObjCInit // CHECK: strong_release [[O]] : $@box ObjCInit // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() var o = meta.init() } class OptionalResult { func foo() -> Self? { return self } } // CHECK-LABEL: sil hidden @_TFC12dynamic_self14OptionalResult3foo // CHECK: bb0( // CHECK-NEXT: debug_value %0 : $OptionalResult // CHECK-NEXT: strong_retain [[VALUE:%[0-9]+]] // CHECK-NEXT: [[T0:%.*]] = enum $Optional<OptionalResult>, #Optional.some!enumelt.1, %0 : $OptionalResult // CHECK-NEXT: return [[T0]] : $Optional<OptionalResult> class OptionalResultInheritor : OptionalResult { func bar() {} } func testOptionalResult(v : OptionalResultInheritor) { v.foo()?.bar() } // CHECK-LABEL: sil hidden @_TF12dynamic_self18testOptionalResult{{.*}} : $@convention(thin) (@owned OptionalResultInheritor) -> () // CHECK: [[T0:%.*]] = class_method [[V:%.*]] : $OptionalResult, #OptionalResult.foo!1 : OptionalResult -> () -> Self? , $@convention(method) (@guaranteed OptionalResult) -> @owned Optional<OptionalResult> // CHECK-NEXT: [[RES:%.*]] = apply [[T0]]([[V]]) // CHECK: select_enum [[RES]] // CHECK: [[T1:%.*]] = unchecked_enum_data [[RES]] // CHECK-NEXT: [[T4:%.*]] = unchecked_ref_cast [[T1]] : $OptionalResult to $OptionalResultInheritor // CHECK-NEXT: enum $Optional<OptionalResultInheritor>, #Optional.some!enumelt.1, [[T4]] // CHECK-LABEL: sil_witness_table hidden X: P module dynamic_self { // CHECK: method #P.f!1: @_TTWC12dynamic_self1XS_1PS_FS1_1f // CHECK-LABEL: sil_witness_table hidden X: CP module dynamic_self { // CHECK: method #CP.f!1: @_TTWC12dynamic_self1XS_2CPS_FS1_1f
apache-2.0
texuf/outandabout
outandabout/outandabout/RSBarcodes/RSCodeGenerator.swift
1
6048
// // RSCodeGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/10/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import Foundation import UIKit import AVFoundation import CoreImage let DIGITS_STRING = "0123456789" // Code generators are required to provide these two functions. public protocol RSCodeGenerator { func generateCode(machineReadableCodeObject:AVMetadataMachineReadableCodeObject) -> UIImage? func generateCode(contents:String, machineReadableCodeObjectType:String) -> UIImage? } // Check digit are not required for all code generators. // UPC-E is using check digit to valid the contents to be encoded. // Code39Mod43, Code93 and Code128 is using check digit to encode barcode. public protocol RSCheckDigitGenerator { func checkDigit(contents:String) -> String } // Abstract code generator, provides default functions for validations and generations. public class RSAbstractCodeGenerator : RSCodeGenerator { // Check whether the given contents are valid. public func isValid(contents:String) -> Bool { let length = contents.length() if length > 0 { for i in 0..<length { let character = contents[i] if !DIGITS_STRING.contains(character!) { return false } } return true } return false } // Barcode initiator, subclass should return its own value. public func initiator() -> String { return "" } // Barcode terminator, subclass should return its own value. public func terminator() -> String { return "" } // Barcode content, subclass should return its own value. public func barcode(contents:String) -> String { return "" } // Composer for combining barcode initiator, contents, terminator together. func completeBarcode(barcode:String) -> String { return self.initiator() + barcode + self.terminator() } // Drawer for completed barcode. func drawCompleteBarcode(completeBarcode:String) -> UIImage? { let length:Int = completeBarcode.length() if length <= 0 { return nil } // Values taken from CIImage generated AVMetadataObjectTypePDF417Code type image // Top spacing = 1.5 // Bottom spacing = 2 // Left & right spacing = 2 // Height = 28 let width = length + 4 let size = CGSizeMake(CGFloat(width), 28) UIGraphicsBeginImageContextWithOptions(size, true, 0) let context = UIGraphicsGetCurrentContext() CGContextSetShouldAntialias(context, false) UIColor.whiteColor().setFill() UIColor.blackColor().setStroke() CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)) CGContextSetLineWidth(context, 1) for i in 0..<length { let character = completeBarcode[i] if character == "1" { let x = i + (2 + 1) CGContextMoveToPoint(context, CGFloat(x), 1.5) CGContextAddLineToPoint(context, CGFloat(x), size.height - 2) } } CGContextDrawPath(context, kCGPathFillStroke) let barcode = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return barcode } // RSCodeGenerator public func generateCode(machineReadableCodeObject:AVMetadataMachineReadableCodeObject) -> UIImage? { return self.generateCode(machineReadableCodeObject.stringValue, machineReadableCodeObjectType: machineReadableCodeObject.type) } public func generateCode(contents:String, machineReadableCodeObjectType:String) -> UIImage? { if self.isValid(contents) { return self.drawCompleteBarcode(self.completeBarcode(self.barcode(contents))) } return nil } // Class funcs // Get CIFilter name by machine readable code object type public class func filterName(machineReadableCodeObjectType:String) -> String! { if machineReadableCodeObjectType == AVMetadataObjectTypeQRCode { return "CIQRCodeGenerator" } else if machineReadableCodeObjectType == AVMetadataObjectTypePDF417Code { return "CIPDF417BarcodeGenerator" } else if machineReadableCodeObjectType == AVMetadataObjectTypeAztecCode { return "CIAztecCodeGenerator" } else if machineReadableCodeObjectType == AVMetadataObjectTypeCode128Code { return "CICode128BarcodeGenerator" } else { return "" } } // Generate CI related code image public class func generateCode(contents:String, filterName:String) -> UIImage { if filterName == "" { return UIImage() } let filter = CIFilter(name: filterName) filter.setDefaults() let inputMessage = contents.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) filter.setValue(inputMessage, forKey: "inputMessage") let outputImage = filter.outputImage let context = CIContext(options: nil) let cgImage = context.createCGImage(outputImage, fromRect: outputImage.extent()) return UIImage(CGImage: cgImage, scale: 1, orientation: UIImageOrientation.Up)! } // Resize image public class func resizeImage(source:UIImage, scale:CGFloat) -> UIImage { let width = source.size.width * scale let height = source.size.height * scale UIGraphicsBeginImageContext(CGSizeMake(width, height)) let context = UIGraphicsGetCurrentContext() CGContextSetInterpolationQuality(context, kCGInterpolationNone) source.drawInRect(CGRectMake(0, 0, width, height)) let target = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return target } }
mit
ti-gars/BugTracker
macOS/BugTracker_macOS/BugTracker_macOS/LoginViewController.swift
1
1457
// // LoginViewController.swift // BugTracker_macOS // // Created by Charles-Olivier Demers on 2015-09-20. // Copyright (c) 2015 Charles-Olivier Demers. All rights reserved. // import Cocoa import Parse class LoginViewController: NSViewController { @IBOutlet weak var usernameTextField: NSTextField! @IBOutlet weak var passwordTextField: NSTextField! override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } @IBAction func login(sender: AnyObject) { PFUser.logInWithUsernameInBackground(usernameTextField.stringValue, password: passwordTextField.stringValue) { (user: PFUser?, error: NSError?) -> Void in if user != nil { println("L'utilisateur s'est correctement connecté") gblAfterLogin() let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)! let sourceViewController = mainStoryboard.instantiateControllerWithIdentifier("issueTrackerView") as! NSViewController self.insertChildViewController(sourceViewController, atIndex: 0) self.view.addSubview(sourceViewController.view) self.view.frame = sourceViewController.view.frame } else { gblError(error!) } } } @IBAction func signup(sender: AnyObject) { } }
mit
khizkhiz/swift
stdlib/public/core/Misc.swift
2
5158
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 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 // //===----------------------------------------------------------------------===// // Extern C functions //===----------------------------------------------------------------------===// // FIXME: Once we have an FFI interface, make these have proper function bodies @_transparent @warn_unused_result public // @testable func _countLeadingZeros(value: Int64) -> Int64 { return Int64(Builtin.int_ctlz_Int64(value._value, false._value)) } /// Returns if `x` is a power of 2. @_transparent @warn_unused_result public // @testable func _isPowerOf2(x: UInt) -> Bool { if x == 0 { return false } // Note: use unchecked subtraction because we have checked that `x` is not // zero. return x & (x &- 1) == 0 } /// Returns if `x` is a power of 2. @_transparent @warn_unused_result public // @testable func _isPowerOf2(x: Int) -> Bool { if x <= 0 { return false } // Note: use unchecked subtraction because we have checked that `x` is not // `Int.min`. return x & (x &- 1) == 0 } #if _runtime(_ObjC) @_transparent public func _autorelease(x: AnyObject) { Builtin.retain(x) Builtin.autorelease(x) } #endif /// Invoke `body` with an allocated, but uninitialized memory suitable for a /// `String` value. /// /// This function is primarily useful to call various runtime functions /// written in C++. func _withUninitializedString<R>( body: (UnsafeMutablePointer<String>) -> R ) -> (R, String) { let stringPtr = UnsafeMutablePointer<String>(allocatingCapacity: 1) let bodyResult = body(stringPtr) let stringResult = stringPtr.move() stringPtr.deallocateCapacity(1) return (bodyResult, stringResult) } @_silgen_name("swift_getTypeName") public func _getTypeName(type: Any.Type, qualified: Bool) -> (UnsafePointer<UInt8>, Int) /// Returns the demangled qualified name of a metatype. @warn_unused_result public // @testable func _typeName(type: Any.Type, qualified: Bool = true) -> String { let (stringPtr, count) = _getTypeName(type, qualified: qualified) return ._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: stringPtr, count: count)) } @_silgen_name("swift_getTypeByMangledName") func _getTypeByMangledName( name: UnsafePointer<UInt8>, _ nameLength: UInt) -> Any.Type? /// Lookup a class given a name. Until the demangled encoding of type /// names is stabilized, this is limited to top-level class names (Foo.bar). @warn_unused_result public // SPI(Foundation) func _typeByName(name: String) -> Any.Type? { let components = name.characters.split{$0 == "."}.map(String.init) guard components.count == 2 else { return nil } // Note: explicitly build a class name to match on, rather than matching // on the result of _typeName(), to ensure the type we are resolving is // actually a class. var name = "C" if components[0] == "Swift" { name += "s" } else { name += String(components[0].characters.count) + components[0] } name += String(components[1].characters.count) + components[1] let nameUTF8 = Array(name.utf8) return nameUTF8.withUnsafeBufferPointer { (nameUTF8) in let type = _getTypeByMangledName(nameUTF8.baseAddress, UInt(nameUTF8.endIndex)) return type } } @warn_unused_result @_silgen_name("swift_stdlib_demangleName") func _stdlib_demangleNameImpl( mangledName: UnsafePointer<UInt8>, _ mangledNameLength: UInt, _ demangledName: UnsafeMutablePointer<String>) // NB: This function is not used directly in the Swift codebase, but is // exported for Xcode support. Please coordinate before changing. @warn_unused_result public // @testable func _stdlib_demangleName(mangledName: String) -> String { let mangledNameUTF8 = Array(mangledName.utf8) return mangledNameUTF8.withUnsafeBufferPointer { (mangledNameUTF8) in let (_, demangledName) = _withUninitializedString { _stdlib_demangleNameImpl( mangledNameUTF8.baseAddress, UInt(mangledNameUTF8.endIndex), $0) } return demangledName } } /// Returns `floor(log(x))`. This equals to the position of the most /// significant non-zero bit, or 63 - number-of-zeros before it. /// /// The function is only defined for positive values of `x`. /// /// Examples: /// /// floorLog2(1) == 0 /// floorLog2(2) == floorLog2(3) == 1 /// floorLog2(9) == floorLog2(15) == 3 /// /// TODO: Implement version working on Int instead of Int64. @warn_unused_result @_transparent public // @testable func _floorLog2(x: Int64) -> Int { _sanityCheck(x > 0, "_floorLog2 operates only on non-negative integers") // Note: use unchecked subtraction because we this expression cannot // overflow. return 63 &- Int(_countLeadingZeros(x)) }
apache-2.0
alecananian/osx-coin-ticker
CoinTicker/Source/Exchanges/HuobiExchange.swift
1
2999
// // HuobiExchange.swift // CoinTicker // // Created by Alec Ananian on 1/10/18. // Copyright © 2018 Alec Ananian. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import SwiftyJSON import PromiseKit class HuobiExchange: Exchange { private struct Constants { static let ProductListAPIPath = "https://api.huobi.pro/v1/common/symbols" static let TickerAPIPathFormat = "https://api.huobi.pro/market/detail/merged?symbol=%@" } init(delegate: ExchangeDelegate? = nil) { super.init(site: .huobi, delegate: delegate) } override func load() { super.load(from: Constants.ProductListAPIPath) { $0.json["data"].arrayValue.compactMap { result in let baseCurrency = result["base-currency"].stringValue let quoteCurrency = result["quote-currency"].stringValue return CurrencyPair( baseCurrency: baseCurrency, quoteCurrency: quoteCurrency, customCode: "\(baseCurrency)\(quoteCurrency)" ) } } } override internal func fetch() { _ = when(resolved: selectedCurrencyPairs.map({ currencyPair -> Promise<ExchangeAPIResponse> in let apiRequestPath = String(format: Constants.TickerAPIPathFormat, currencyPair.customCode) return requestAPI(apiRequestPath, for: currencyPair) })).map { [weak self] results in results.forEach({ result in switch result { case .fulfilled(let value): if let currencyPair = value.representedObject as? CurrencyPair { let price = value.json["tick"]["close"].doubleValue self?.setPrice(price, for: currencyPair) } default: break } }) self?.onFetchComplete() } } }
mit
ringly/IOS-Pods-DFU-Library
iOSDFULibrary/Classes/Implementation/DFUSelector/DFUStarterPeripheral.swift
2
2372
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder 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 CoreBluetooth internal class DFUStarterPeripheral : BaseDFUPeripheral<DFUServiceSelector> { /** Method called when a DFU service has been found. */ override func peripheralDidDiscoverDfuService(_ service: CBService) { if SecureDFUService.matches(service) { delegate?.peripheralDidSelectedExecutor(SecureDFUExecutor.self) } else if LegacyDFUService.matches(service) { delegate?.peripheralDidSelectedExecutor(LegacyDFUExecutor.self) } else if SecureDFUService.matches(experimental: service) { delegate?.peripheralDidSelectedExecutor(SecureDFUExecutor.self) } else { // This will never go in here delegate?.error(.deviceNotSupported, didOccurWithMessage: "Device not supported") } } }
bsd-3-clause
radex/swift-compiler-crashes
crashes-fuzzing/01926-swift-constraints-constraintgraph-addconstraint.swift
11
200
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A<T where T:A}print ((A.c
mit
devandsev/theTVDB-iOS
tvShows/Source/Screens/WF.swift
1
1260
// // BaseWireframe.swift // tvShows // // Created by Andrey Sevrikov on 17/09/2017. // Copyright © 2017 devandsev. All rights reserved. // import UIKit class BaseWireframe: Wireframe { let navigationController: UINavigationController required init(with navigationController: UINavigationController) { self.navigationController = navigationController } func show(viewController: UIViewController, modally: Bool = false) { if modally { self.navigationController.present(viewController, animated: true) {} } else { self.navigationController.pushViewController(viewController, animated: true) } } func hide(viewController: UIViewController) { guard let lastVC = self.navigationController.viewControllers.last, lastVC == viewController else { self.navigationController.dismiss(animated: true) {} return } self.navigationController.popViewController(animated: true) } } protocol Wireframe { var navigationController: UINavigationController {get} init(with navigationController: UINavigationController) } protocol ModuleConstructable { func module() -> UIViewController }
mit
radex/swift-compiler-crashes
crashes-fuzzing/23336-llvm-foldingset-swift-enumtype-nodeequals.swift
11
225
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing 1 (<u class A{ protocol e:A.t protocol A{ typealias e:e
mit
radex/swift-compiler-crashes
fixed/00236-swift-typechecker-typecheckforeachbinding.swift
12
628
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol p { class func g() } class h: p { class func g() { } } (h() as p).dynamicType.g() protocol p { } protocol h : p { } protocol g : p { } protocol n { o t = p } struct h : n { t : n q m.t == m> (h: m) { } func q<t : n q t.t == g> (h: t) { } q(h()) func r(g: m) -> <s>(() -> s) -> n func m<u>() -> (u, u -> u) -> u { p o p.s = { } { u) eturn s(c, u) } } func n(r:-> t { r}) func p<p>() -> (p, p -> p) -> p { ) { (e: o,
mit
radex/swift-compiler-crashes
crashes-duplicates/21908-no-stacktrace.swift
11
214
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let f = 0 as a func a { { class case c, case
mit
royratcliffe/Snippets
Sources/Bundle+Snippets.swift
1
3750
// Snippets NSBundle+Snippets.swift // // Copyright © 2008–2015, Roy Ratcliffe, Pioneering Software, United Kingdom // // 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, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO // EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES // OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //------------------------------------------------------------------------------ import Foundation extension Bundle { /// Loads an immutable property list from a named resource within a named /// sub-directory. Fails by answering `nil` if the resource does not exist, or /// it fails to load. Throws an error if the data loads but fails to decode as /// a properly-formatted property list. /// /// For some reason, `URLForResource` has an optional name parameter. Apple /// documentation does not make it clear what happens if the name is /// `nil`. This method does not follow the same pattern. The name string is /// *not* optional. public func propertyList(forResource name: String, subdirectory: String?) throws -> Any? { guard let URL = url(forResource: name, withExtension: "plist", subdirectory: subdirectory) else { return nil } guard let data = try? Data(contentsOf: URL) else { return nil } return try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.MutabilityOptions(), format: nil) } /// - returns: Bundle's display name; returns the application's display name /// if applied to the application's main bundle, /// i.e. `NSBundle.mainBundle().displayName` gives you the application /// display name. /// /// See Technical Q&A QA1544 for more details. /// /// Note that some users enable "Show all filename extensions" in Finder. With /// that option enabled, the application display name becomes /// AppDisplayName.app rather than just AppDisplayName. The displayName /// implementation removes the `app` extension so that when creating an /// Application Support folder by this name, for example, the new support /// folder does not also carry the `app` extension. public var displayName: String { let manager = FileManager.default let displayName = manager.displayName(atPath: bundlePath) as NSString return displayName.deletingPathExtension } /// - parameter subpath: sub-folder within this bundle. /// - returns: an array of storyboard names found in this bundle. /// /// Compiled storyboards have the `storyboardc` extension; `c` standing for /// compiled, presumably. public func storyboardNames(inDirectory subpath: String?) -> [String] { return paths(forResourcesOfType: "storyboardc", inDirectory: subpath).map { path in let component = (path as NSString).lastPathComponent return (component as NSString).deletingPathExtension } } }
mit
suifengqjn/swiftDemo
基本语法/10属性/属性/属性/AppDelegate.swift
1
2140
// // AppDelegate.swift // 属性 // // Created by qianjn on 16/7/24. // Copyright © 2016年 SF. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
LarsStegman/helios-for-reddit
Sources/Model/Listing.swift
1
1543
// // Listing.swift // Helios // // Created by Lars Stegman on 30-12-16. // Copyright © 2016 Stegman. All rights reserved. // import Foundation public struct Listing: Kindable, Decodable { let before: String? let after: String? let modhash: String? var source: URL? public let children: [KindWrapper] public static let kind = Kind.listing init(before: String?, after: String?, modhash: String?, source: URL?, children: [KindWrapper]) { self.before = before self.after = after self.modhash = modhash self.source = source self.children = children } /// Whether there are pages before this one. public var hasPrevious: Bool { return before != nil } /// Whether there are more pages. public var hasNext: Bool { return after != nil } public init(from decoder: Decoder) throws { let dataContainer = try decoder.container(keyedBy: CodingKeys.self) source = try dataContainer.decodeIfPresent(URL.self, forKey: .source) after = try dataContainer.decodeIfPresent(String.self, forKey: .after) before = try dataContainer.decodeIfPresent(String.self, forKey: .before) modhash = try dataContainer.decodeIfPresent(String.self, forKey: .modhash) children = try dataContainer.decode([KindWrapper].self, forKey: .children) } enum CodingKeys: String, CodingKey { case before case after case children case modhash case source } }
mit
jpsim/SourceKitten
Tests/SourceKittenFrameworkTests/OffsetMapTests.swift
1
1626
import Foundation import SourceKittenFramework import XCTest class OffsetMapTests: XCTestCase { func testOffsetMapContainsDeclarationOffsetWithDocCommentButNotAlreadyDocumented() throws { // Subscripts aren't parsed by SourceKit, so OffsetMap should contain its offset. let file = File(contents: "struct VoidStruct {\n/// Returns or sets Void.\nsubscript(key: String) -> () {\n" + "get { return () }\nset {}\n}\n}" ) let documentedTokenOffsets = file.stringView.documentedTokenOffsets(syntaxMap: try SyntaxMap(file: file)) let response = file.process(dictionary: try Request.editorOpen(file: file).send(), cursorInfoRequest: nil) let offsetMap = file.makeOffsetMap(documentedTokenOffsets: documentedTokenOffsets, dictionary: response) XCTAssertEqual(offsetMap, [:], "should generate correct offset map of [(declaration offset): (parent offset)]") } func testOffsetMapDoesntContainAlreadyDocumentedDeclarationOffset() throws { // Struct declarations are parsed by SourceKit, so OffsetMap shouldn't contain its offset. let file = File(contents: "/// Doc Comment\nstruct DocumentedStruct {}") let documentedTokenOffsets = file.stringView.documentedTokenOffsets(syntaxMap: try SyntaxMap(file: file)) let response = file.process(dictionary: try Request.editorOpen(file: file).send(), cursorInfoRequest: nil) let offsetMap = file.makeOffsetMap(documentedTokenOffsets: documentedTokenOffsets, dictionary: response) XCTAssertEqual(offsetMap, [:], "should generate empty offset map") } }
mit
jtbandes/swift-compiler-crashes
crashes-fuzzing/28153-swift-normalprotocolconformance-setwitness.swift
2
250
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import a enum S<f{class B<I{ let i{struct A:OptionSetType{struct B<a where I.e:a
mit
Cleverlance/Pyramid
Sources/Common/Command Pattern/Application/Command.swift
1
762
// // Copyright © 2015 Cleverlance. All rights reserved. // internal class Command<Request, Response, Tag>: CommandType { typealias Receiver = TaggedOperation<Request, Response, Tag> private let receiver: Receiver let request: Request private let completion: (OperationResult<Response>) -> Void required init( receiver: Receiver, request: Request, completion: @escaping (OperationResult<Response>) -> Void ) { self.receiver = receiver self.request = request self.completion = completion } func execute() throws -> Response { return try receiver.execute(with: request) } func complete(_ result: OperationResult<Response>) { completion(result) } }
mit
gbarcena/ImageCaptureSession
ImageCaptureSession/ViewController.swift
1
2538
// // ViewController.swift // ImageCaptureSession // // Created by Gustavo Barcena on 5/27/15. // Copyright (c) 2015 Gustavo Barcena. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var previewView : PreviewView! var captureSession : ImageCaptureSession? override func viewDidLoad() { super.viewDidLoad() setupCameraView() } deinit { captureSession?.stop() } func setupCameraView() { let cameraPosition : AVCaptureDevicePosition if (ImageCaptureSession.hasFrontCamera()) { cameraPosition = .front } else if (ImageCaptureSession.hasBackCamera()) { cameraPosition = .back } else { cameraPosition = .unspecified assertionFailure("Device needs to have a camera for this demo") } captureSession = ImageCaptureSession(position: cameraPosition, previewView: previewView) captureSession?.start() } @IBAction func takePhotoPressed(_ sender:AnyObject) { captureSession?.captureImage({ (image, error) -> Void in if (error == nil) { if let imageVC = self.storyboard?.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController { imageVC.image = image self.present(imageVC, animated: true, completion: nil) } return } let alertController = UIAlertController(title: "Oh no!", message: "Failed to take a photo.", preferredStyle: .alert) self.present(alertController, animated: true, completion: nil) }) } @IBAction func switchCamerasPressed(_ sender:AnyObject) { let stillFrame = previewView.snapshotView(afterScreenUpdates: false) stillFrame?.frame = previewView.frame view.insertSubview(stillFrame!, aboveSubview: previewView) UIView.animate(withDuration: 0.05, animations: { self.captureSession?.previewLayer.opacity = 0 }, completion: { (finished) in self.captureSession?.switchCameras() UIView.animate(withDuration: 0.05, animations: { self.captureSession?.previewLayer.opacity = 1 }, completion: { (finished) in stillFrame?.removeFromSuperview() }) }) } }
mit
vi4m/Sideburns
Sources/Sideburns.swift
1
1926
// Sideburns.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. @_exported import File @_exported import HTTP @_exported import Mustache public typealias TemplateData = MustacheBoxable public enum SideburnsError: ErrorProtocol { case unsupportedTemplateEncoding } extension Response { public init(status: Status = .ok, headers: Headers = [:], templateName: String, repository: TemplateRepository, templateData: TemplateData) throws { let template = try repository.template(named: templateName) let rendering = try template.render(box: Box(boxable: templateData)) self.init(status: status, headers: headers, body: rendering) // if let fileExtension = templateFile.fileExtension, mediaType = mediaType(forFileExtension: fileExtension) { // self.contentType = mediaType // } } }
mit
amuramoto/realm-objc
Realm/Tests/Swift/SwiftRealmTests.swift
1
5285
//////////////////////////////////////////////////////////////////////////// // // 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 XCTest import TestFramework class SwiftRealmTests: RLMTestCase { func testRealmExists() { var realm = realmWithTestPath() XCTAssertNotNil(realm, "realm should not be nil"); XCTAssertTrue((realm as AnyObject) is RLMRealm, "realm should be of class RLMRealm") } func testEmptyWriteTransaction() { var realm = realmWithTestPath() realm.beginWriteTransaction() realm.commitWriteTransaction() } func testRealmAddAndRemoveObjects() { var realm = realmWithTestPath() realm.beginWriteTransaction() StringObject.createInRealm(realm, withObject: ["a"]) StringObject.createInRealm(realm, withObject: ["b"]) StringObject.createInRealm(realm, withObject: ["c"]) XCTAssertEqual(StringObject.allObjectsInRealm(realm).count, 3, "Expecting 3 objects") realm.commitWriteTransaction() // test again after write transaction var objects = StringObject.allObjectsInRealm(realm) XCTAssertEqual(objects.count, 3, "Expecting 3 objects") XCTAssertEqualObjects(objects.firstObject().stringCol, "a", "Expecting column to be 'a'") realm.beginWriteTransaction() realm.deleteObject(objects[2] as StringObject) realm.deleteObject(objects[0] as StringObject) XCTAssertEqual(StringObject.allObjectsInRealm(realm).count, 1, "Expecting 1 object") realm.commitWriteTransaction() objects = StringObject.allObjectsInRealm(realm) XCTAssertEqual(objects.count, 1, "Expecting 1 object") XCTAssertEqualObjects(objects.firstObject().stringCol, "b", "Expecting column to be 'b'") } func testRealmIsUpdatedAfterBackgroundUpdate() { let realm = realmWithTestPath() // we have two notifications, one for opening the realm, and a second when performing our transaction var noteCount = 0 let notificationFired = expectationWithDescription("notification fired") let token = realm.addNotificationBlock { note, realm in XCTAssertNotNil(realm, "Realm should not be nil") if ++noteCount == 2 { notificationFired.fulfill() } } dispatch_async(dispatch_queue_create("background", nil)) { let realm = self.realmWithTestPath() realm.beginWriteTransaction() StringObject.createInRealm(realm, withObject: ["string"]) realm.commitWriteTransaction() } waitForExpectationsWithTimeout(2.0, handler: nil) realm.removeNotification(token) // get object let objects = StringObject.allObjectsInRealm(realm) XCTAssertEqual(objects.count, 1, "There should be 1 object of type StringObject") XCTAssertEqualObjects((objects[0] as StringObject).stringCol, "string", "Value of first column should be 'string'") } func testRealmIsUpdatedImmediatelyAfterBackgroundUpdate() { let realm = realmWithTestPath() // we have two notifications, one for opening the realm, and a second when performing our transaction var noteCount = 0 let notificationFired = expectationWithDescription("notification fired") let token = realm.addNotificationBlock { note, realm in XCTAssertNotNil(realm, "Realm should not be nil") if ++noteCount == 2 { notificationFired.fulfill() } } dispatch_async(dispatch_queue_create("background", nil)) { let realm = self.realmWithTestPath() let obj = StringObject(object: ["string"]) realm.beginWriteTransaction() realm.addObject(obj) realm.commitWriteTransaction() let objects = StringObject.allObjectsInRealm(realm) XCTAssertEqual(objects.count, 1, "There should be 1 object of type StringObject") XCTAssertEqualObjects((objects[0] as StringObject).stringCol, "string", "Value of first column should be 'string'") } // this should complete very fast before the timer waitForExpectationsWithTimeout(0.01, handler: nil) realm.removeNotification(token) // get object let objects = StringObject.allObjectsInRealm(realm) XCTAssertEqual(objects.count, 1, "There should be 1 object of type RLMTestObject") XCTAssertEqualObjects((objects[0] as StringObject).stringCol, "string", "Value of first column should be 'string'") } }
apache-2.0
hadashiA/RippleLayer
WaveLayerTests/WaveLayerTests.swift
1
757
import UIKit import XCTest class WaveLayerTests: XCTestCase { 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
wireapp/wire-ios-data-model
Tests/Source/Model/Conversation/ZMConversationTests+Transport.swift
1
10579
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation @testable import WireDataModel class ZMConversationTests_Transport: ZMConversationTestsBase { // MARK: Access Mode func testThatItUpdateAccessStatus() { syncMOC.performGroupedBlockAndWait { let conversation = ZMConversation.insertNewObject(in: self.syncMOC) let accessRoles: Set<ConversationAccessRoleV2> = [.teamMember, .guest, .service] let accessMode = ConversationAccessMode.allowGuests // when conversation.updateAccessStatus(accessModes: accessMode.stringValue, accessRoles: accessRoles.map({$0.rawValue})) // then XCTAssertEqual(conversation.accessMode, accessMode) XCTAssertEqual(conversation.accessRoles, accessRoles) } } // MARK: Receipt Mode func testThatItUpdateReadReceiptStatusAndInsertsSystemMessage_ForNonEmptyConversations() { syncMOC.performGroupedBlockAndWait { // given let conversation = ZMConversation.insertNewObject(in: self.syncMOC) conversation.appendNewConversationSystemMessage(at: Date(), users: Set()) conversation.hasReadReceiptsEnabled = false // when conversation.updateReceiptMode(1) // then XCTAssertEqual(conversation.lastMessage?.systemMessageData?.systemMessageType, .readReceiptsOn) } } func testThatItDoesntInsertsSystemMessage_WhenReadReceiptStatusDoesntChange() { syncMOC.performGroupedBlockAndWait { // given let conversation = ZMConversation.insertNewObject(in: self.syncMOC) conversation.hasReadReceiptsEnabled = true // when conversation.updateReceiptMode(1) // then XCTAssertNil(conversation.lastMessage) } } // MARK: Archiving func testThatItUpdateArchiveStatus() { syncMOC.performGroupedBlockAndWait { let timestamp = Date() let conversation = ZMConversation.insertNewObject(in: self.syncMOC) // when conversation.updateArchivedStatus(archived: true, referenceDate: timestamp) // then XCTAssertEqual(conversation.isArchived, true) XCTAssertEqual(conversation.archivedChangedTimestamp, timestamp) } } // MARK: Muting func testThatItUpdateMutedStatus() { syncMOC.performGroupedBlockAndWait { let timestamp = Date() let conversation = ZMConversation.insertNewObject(in: self.syncMOC) let mutedMessages: MutedMessageTypes = .all // when conversation.updateMutedStatus(status: mutedMessages.rawValue, referenceDate: timestamp) // then XCTAssertEqual(conversation.mutedMessageTypes, .all) XCTAssertEqual(conversation.silencedChangedTimestamp, timestamp) } } // MARK: Roles func testThatItAssignsRoles_WhenNotInTeam() { syncMOC.performGroupedAndWait { _ -> Void in // given ZMUser.selfUser(in: self.syncMOC).teamIdentifier = UUID() let conversation = ZMConversation.insertNewObject(in: self.syncMOC) conversation.remoteIdentifier = UUID.create() let user1 = self.createUser(in: self.syncMOC) let user2 = self.createUser(in: self.syncMOC) let role = Role.create(managedObjectContext: self.syncMOC, name: "test_role", conversation: conversation) // when conversation.updateMembers([(user1, nil), (user2, role)], selfUserRole: nil) // then XCTAssertTrue(conversation.localParticipants.contains(user1)) XCTAssertTrue(conversation.localParticipants.contains(user2)) guard let participant1 = conversation.participantForUser(user1), let participant2 = conversation.participantForUser(user2) else { return XCTFail() } XCTAssertNil(participant1.role) XCTAssertEqual(participant2.role?.name, "test_role") XCTAssertEqual(conversation.nonTeamRoles.count, 1) XCTAssertEqual(conversation.nonTeamRoles.first, participant2.role) } } func testThatItAssignsRoles_WhenInTeam() { syncMOC.performGroupedAndWait { _ -> Void in // given ZMUser.selfUser(in: self.syncMOC).teamIdentifier = UUID() let team = Team.insertNewObject(in: self.syncMOC) team.remoteIdentifier = UUID.create() let conversation = ZMConversation.insertNewObject(in: self.syncMOC) conversation.remoteIdentifier = UUID.create() conversation.team = team let user1 = self.createUser(in: self.syncMOC) let user2 = self.createUser(in: self.syncMOC) let role1 = Role.create(managedObjectContext: self.syncMOC, name: "test_role1", team: team) let role2 = Role.create(managedObjectContext: self.syncMOC, name: "test_role2", team: team) // when conversation.updateMembers([(user1, role1), (user2, role2)], selfUserRole: nil) // then XCTAssertTrue(conversation.localParticipants.contains(user1)) XCTAssertTrue(conversation.localParticipants.contains(user2)) guard let participant1 = conversation.participantForUser(user1), let participant2 = conversation.participantForUser(user2) else { return XCTFail() } XCTAssertEqual(participant1.role?.team, team) XCTAssertEqual(participant2.role?.team, team) XCTAssertEqual(participant1.role?.name, "test_role1") XCTAssertEqual(participant2.role?.name, "test_role2") XCTAssertEqual(team.roles, Set([participant1.role, participant2.role].compactMap {$0})) } } func testThatItUpdatesRoles_WhenInTeam() { syncMOC.performGroupedAndWait { _ -> Void in // given ZMUser.selfUser(in: self.syncMOC).teamIdentifier = UUID() let team = Team.insertNewObject(in: self.syncMOC) team.remoteIdentifier = UUID.create() let conversation = ZMConversation.insertNewObject(in: self.syncMOC) conversation.remoteIdentifier = UUID.create() conversation.team = team let user1 = ZMUser.insertNewObject(in: self.syncMOC) user1.name = "U1" user1.remoteIdentifier = UUID.create() let oldRole = Role.create(managedObjectContext: self.syncMOC, name: "ROLE1", team: team) conversation.addParticipantAndUpdateConversationState(user: user1, role: oldRole) let newRole = Role.create(managedObjectContext: self.syncMOC, name: "new_role", team: team) // when conversation.updateMembers([(user1, newRole)], selfUserRole: nil) // then XCTAssertEqual(conversation.participantForUser(user1)?.role, newRole) } } func testThatItAssignsSelfRole_WhenInTeam() { syncMOC.performGroupedAndWait { _ -> Void in // given ZMUser.selfUser(in: self.syncMOC).teamIdentifier = UUID() let selfUser = ZMUser.selfUser(in: self.syncMOC) let team = Team.insertNewObject(in: self.syncMOC) team.remoteIdentifier = UUID.create() let conversation = ZMConversation.insertNewObject(in: self.syncMOC) conversation.remoteIdentifier = UUID.create() conversation.team = team let selfRole = Role.create(managedObjectContext: self.syncMOC, name: "test_role", team: team) // when conversation.updateMembers([], selfUserRole: selfRole) // then XCTAssertEqual(conversation.participantForUser(selfUser)?.role, selfRole) } } func testThatItAssignsSelfRole_WhenNotInTeam() { syncMOC.performGroupedAndWait { _ -> Void in // given ZMUser.selfUser(in: self.syncMOC).teamIdentifier = UUID() let conversation = ZMConversation.insertNewObject(in: self.syncMOC) let selfUser = ZMUser.selfUser(in: self.syncMOC) conversation.remoteIdentifier = UUID.create() let selfRole = Role.create(managedObjectContext: self.syncMOC, name: "test_role", conversation: conversation) // when conversation.updateMembers([], selfUserRole: selfRole) // then XCTAssertEqual(conversation.participantForUser(selfUser)?.role, selfRole) } } func testThatItRefetchesRoles_WhenSelfUserIsAssignedARole() { syncMOC.performGroupedAndWait { _ -> Void in // given ZMUser.selfUser(in: self.syncMOC).teamIdentifier = UUID() let selfUser = ZMUser.selfUser(in: self.syncMOC) let conversation = ZMConversation.insertNewObject(in: self.syncMOC) conversation.conversationType = .group conversation.remoteIdentifier = UUID.create() conversation.addParticipantAndUpdateConversationState(user: selfUser, role: nil) let selfRole = Role.create(managedObjectContext: self.syncMOC, name: "test_role", conversation: conversation) // when conversation.updateMembers([], selfUserRole: selfRole) // then XCTAssertTrue(conversation.needsToDownloadRoles) } } } extension ZMConversation { fileprivate func participantForUser(_ user: ZMUser) -> ParticipantRole? { return self.participantForUser(id: user.remoteIdentifier!) } fileprivate func participantForUser(id: UUID) -> ParticipantRole? { return self.participantRoles.first(where: { $0.user?.remoteIdentifier == id }) } }
gpl-3.0
paleksandrs/APScheduledLocationManager
ScheduledLocationExample/ViewController.swift
1
1944
// // Created by Aleksandrs Proskurins // // License // Copyright © 2016 Aleksandrs Proskurins // Released under an MIT license: http://opensource.org/licenses/MIT // import UIKit import APScheduledLocationManager import CoreLocation class ViewController: UIViewController, APScheduledLocationManagerDelegate { private var manager: APScheduledLocationManager! @IBOutlet weak var startStopButton: UIButton! @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() manager = APScheduledLocationManager(delegate: self) } @IBAction func startStop(_ sender: AnyObject) { if manager.isRunning { startStopButton.setTitle("start", for: .normal) manager.stopUpdatingLocation() }else{ if CLLocationManager.authorizationStatus() == .authorizedAlways { startStopButton.setTitle("stop", for: .normal) manager.startUpdatingLocation(interval: 60, acceptableLocationAccuracy: 100) }else{ manager.requestAlwaysAuthorization() } } } func scheduledLocationManager(_ manager: APScheduledLocationManager, didUpdateLocations locations: [CLLocation]) { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .medium let l = locations.first! textView.text = "\(textView.text!)\r \(formatter.string(from: Date())) loc: \(l.coordinate.latitude), \(l.coordinate.longitude)" } func scheduledLocationManager(_ manager: APScheduledLocationManager, didFailWithError error: Error) { } func scheduledLocationManager(_ manager: APScheduledLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { } }
mit
Chaosspeeder/YourGoals
YourGoalsTests/Business/TaskStateManagerTests.swift
1
870
// // TaskStateManagerTests.swift // YourGoalsTests // // Created by André Claaßen on 27.10.17. // Copyright © 2017 André Claaßen. All rights reserved. // import XCTest @testable import YourGoals class TaskStateManagerTests: StorageTestCase { func testStateDone() { // setup let task = TaskFactory(manager: self.manager).create(name: "Active Task", state: .active, prio: 1) try! self.manager.saveContext() let id = task.objectID let stateManager = TaskStateManager(manager: self.manager) // act try! stateManager.setTaskState(task: task, state: .done, atDate: Date.dateWithYear(2017, month: 10, day: 25)) // test let taskReloaded = self.manager.tasksStore.retrieveExistingObject(objectId: id) XCTAssertEqual(.done, taskReloaded.getTaskState()) } }
lgpl-3.0
glessard/swift-channels
ChannelsTestApp/ViewController.swift
1
503
// // ViewController.swift // ChannelsTestApp // // Created by Guillaume Lessard on 2015-06-26. // Copyright © 2015 Guillaume Lessard. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
germc/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/ReadyAppRetail/Controllers/ListViewController.swift
2
1097
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit class ListViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() UserAuthHelper.checkIfLoggedIn(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { self.navigationItem.title = NSLocalizedString("MY LISTS", comment:"") self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Oswald-Regular", size: 22)!, NSForegroundColorAttributeName: UIColor.whiteColor()] } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "listTableViewSegue") { } } }
epl-1.0
wattson12/Moya-Argo
Example/Moya-Argo/ArgoUser.swift
1
567
// // ArgoUser.swift // Moya-Argo // // Created by Sam Watts on 23/01/2016. // Copyright © 2016 Sam Watts. All rights reserved. // import Foundation struct ArgoUser { let id: Int let name: String let birthdate: String? } extension ArgoUser: UserType { } import Argo import Curry import Runes extension ArgoUser: Argo.Decodable { static func decode(_ json: JSON) -> Decoded<ArgoUser> { return curry(ArgoUser.init) <^> json <| "id" <*> json <| "name" <*> json <|? "birthdate" } }
mit
Kiandr/CrackingCodingInterview
Swift/Ch 2. Linked Lists/Ch 2. Linked Lists.playground/Pages/2.8 Loop Detection.xcplaygroundpage/Contents.swift
1
1664
import Foundation /*: 2.8 Given a singly linked, circular list, return the node at the beginning of the loop. A circular list is a (corrupt) linked list in which a node's next pointer points to an earlier node in the list. Input: `a -> b -> c -> d -> e -> c` (The same c as before) \ Output: `c` */ extension MutableList { func nodeBeginningLoop() -> MutableList? { return nodeBeginningLoop(advanceBy: 1) } private func nodeBeginningLoop(advanceBy: Int) -> MutableList? { guard !isEmpty else { return nil } guard self !== node(at: advanceBy) else { return self } return tail?.nodeBeginningLoop(advanceBy: advanceBy + 1) } } let list = MutableList(arrayLiteral: "a", "b", "c", "d", "e") list.description let listToAppend = MutableList(arrayLiteral: "a", "b", "c", "d", "e") list.append(list: listToAppend) list.description assert(list.nodeBeginningLoop() == nil) let circularList = MutableList(arrayLiteral: "a", "b", "c", "d", "e") circularList.description assert(circularList.nodeBeginningLoop() == nil) let subList = circularList.tail?.tail circularList.append(list: subList!) assert(circularList.nodeBeginningLoop() === subList) // customizing MutableList's debugDescription prevents the playground from recursing infintely // when it prints a circular list extension MutableList: CustomDebugStringConvertible { public var debugDescription: String { guard let head = head else { return "nil" } let description = "\(head)" if let tailHead = tail?.head { return description + " -> \(tailHead) ..." } return description } }
mit
Sethmr/FantasticView
FantasticView/FantasticView.swift
1
839
// // FantasticView.swift // FantasticView // // Created by Seth Rininger on 5/22/17. // Copyright © 2017 Seth Rininger. All rights reserved. // import UIKit class FantasticView: UIView { let colors : [UIColor] = [.red, .orange, .yellow, .green, .blue, .purple] var colorCounter = 0 override init(frame: CGRect) { super.init(frame: frame) let scheduledColorChanged = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { timer in UIView.animate(withDuration: 2.0) { self.layer.backgroundColor = self.colors[self.colorCounter % 6].cgColor self.colorCounter += 1 } } scheduledColorChanged.fire() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
larryhou/swift
CoredataExample/CoredataExample/AppDelegate.swift
1
6181
// // AppDelegate.swift // CoredataExample // // Created by larryhou on 19/7/2015. // Copyright © 2015 larryhou. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let rootViewController = window!.rootViewController as! ViewController rootViewController.managedObjectContext = managedObjectContext return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.larryhou.samples.CoredataExample" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count - 1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("CoredataExample", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("data.sqlite") do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { var failureReason = "There was an error creating or loading the application's saved data." // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
duycao2506/SASCoffeeIOS
Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView/Presenter/NVActivityIndicatorPresenter.swift
2
10575
// // NVActivityIndicatorPresenter.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit /// Class packages information used to display UI blocker. public final class ActivityData { /// Size of activity indicator view. let size: CGSize /// Message displayed under activity indicator view. let message: String? /// Font of message displayed under activity indicator view. let messageFont: UIFont /// Animation type. let type: NVActivityIndicatorType /// Color of activity indicator view. let color: UIColor /// Color of text. let textColor: UIColor /// Padding of activity indicator view. let padding: CGFloat /// Display time threshold to actually display UI blocker. let displayTimeThreshold: Int /// Minimum display time of UI blocker. let minimumDisplayTime: Int /// Background color of the UI blocker let backgroundColor: UIColor /** Create information package used to display UI blocker. Appropriate NVActivityIndicatorView.DEFAULT_* values are used for omitted params. - parameter size: size of activity indicator view. - parameter message: message displayed under activity indicator view. - parameter messageFont: font of message displayed under activity indicator view. - parameter type: animation type. - parameter color: color of activity indicator view. - parameter padding: padding of activity indicator view. - parameter displayTimeThreshold: display time threshold to actually display UI blocker. - parameter minimumDisplayTime: minimum display time of UI blocker. - parameter textColor: color of the text below the activity indicator view. Will match color parameter if not set, otherwise DEFAULT_TEXT_COLOR if color is not set. - returns: The information package used to display UI blocker. */ public init(size: CGSize? = nil, message: String? = nil, messageFont: UIFont? = nil, type: NVActivityIndicatorType? = nil, color: UIColor? = nil, padding: CGFloat? = nil, displayTimeThreshold: Int? = nil, minimumDisplayTime: Int? = nil, backgroundColor: UIColor? = nil, textColor: UIColor? = nil) { self.size = size ?? NVActivityIndicatorView.DEFAULT_BLOCKER_SIZE self.message = message ?? NVActivityIndicatorView.DEFAULT_BLOCKER_MESSAGE self.messageFont = messageFont ?? NVActivityIndicatorView.DEFAULT_BLOCKER_MESSAGE_FONT self.type = type ?? NVActivityIndicatorView.DEFAULT_TYPE self.color = color ?? NVActivityIndicatorView.DEFAULT_COLOR self.padding = padding ?? NVActivityIndicatorView.DEFAULT_PADDING self.displayTimeThreshold = displayTimeThreshold ?? NVActivityIndicatorView.DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD self.minimumDisplayTime = minimumDisplayTime ?? NVActivityIndicatorView.DEFAULT_BLOCKER_MINIMUM_DISPLAY_TIME self.backgroundColor = backgroundColor ?? NVActivityIndicatorView.DEFAULT_BLOCKER_BACKGROUND_COLOR self.textColor = textColor ?? color ?? NVActivityIndicatorView.DEFAULT_TEXT_COLOR } } /// Presenter that displays NVActivityIndicatorView as UI blocker. public final class NVActivityIndicatorPresenter { private enum State { case waitingToShow case showed case waitingToHide case hidden } private let restorationIdentifier = "NVActivityIndicatorViewContainer" private let messageLabel: UILabel = { let label = UILabel() label.textAlignment = .center label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() private var state: State = .hidden private let startAnimatingGroup = DispatchGroup() /// Shared instance of `NVActivityIndicatorPresenter`. public static let sharedInstance = NVActivityIndicatorPresenter() private init() {} // MARK: - Public interface /** Display UI blocker. - parameter data: Information package used to display UI blocker. */ public final func startAnimating(_ data: ActivityData) { guard state == .hidden else { return } state = .waitingToShow startAnimatingGroup.enter() DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(data.displayTimeThreshold)) { guard self.state == .waitingToShow else { self.startAnimatingGroup.leave() return } self.show(with: data) self.startAnimatingGroup.leave() } } /** Remove UI blocker. */ public final func stopAnimating() { _hide() } /// Set message displayed under activity indicator view. /// /// - Parameter message: message displayed under activity indicator view. public final func setMessage(_ message: String?) { guard state == .showed else { startAnimatingGroup.notify(queue: DispatchQueue.main) { self.messageLabel.text = message } return } messageLabel.text = message } // MARK: - Helpers private func show(with activityData: ActivityData) { let containerView = UIView(frame: UIScreen.main.bounds) containerView.backgroundColor = activityData.backgroundColor containerView.restorationIdentifier = restorationIdentifier containerView.translatesAutoresizingMaskIntoConstraints = false let activityIndicatorView = NVActivityIndicatorView( frame: CGRect(x: 0, y: 0, width: activityData.size.width, height: activityData.size.height), type: activityData.type, color: activityData.color, padding: activityData.padding) activityIndicatorView.startAnimating() activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(activityIndicatorView) // Add constraints for `activityIndicatorView`. ({ let xConstraint = NSLayoutConstraint(item: containerView, attribute: .centerX, relatedBy: .equal, toItem: activityIndicatorView, attribute: .centerX, multiplier: 1, constant: 0) let yConstraint = NSLayoutConstraint(item: containerView, attribute: .centerY, relatedBy: .equal, toItem: activityIndicatorView, attribute: .centerY, multiplier: 1, constant: 0) containerView.addConstraints([xConstraint, yConstraint]) }()) messageLabel.font = activityData.messageFont messageLabel.textColor = activityData.textColor messageLabel.text = activityData.message containerView.addSubview(messageLabel) // Add constraints for `messageLabel`. ({ let leadingConstraint = NSLayoutConstraint(item: containerView, attribute: .leading, relatedBy: .equal, toItem: messageLabel, attribute: .leading, multiplier: 1, constant: -8) let trailingConstraint = NSLayoutConstraint(item: containerView, attribute: .trailing, relatedBy: .equal, toItem: messageLabel, attribute: .trailing, multiplier: 1, constant: 8) containerView.addConstraints([leadingConstraint, trailingConstraint]) }()) ({ let spacingConstraint = NSLayoutConstraint(item: messageLabel, attribute: .top, relatedBy: .equal, toItem: activityIndicatorView, attribute: .bottom, multiplier: 1, constant: 8) containerView.addConstraint(spacingConstraint) }()) guard let keyWindow = UIApplication.shared.keyWindow else { return } keyWindow.addSubview(containerView) state = .showed // Add constraints for `containerView`. ({ let leadingConstraint = NSLayoutConstraint(item: keyWindow, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1, constant: 0) let trailingConstraint = NSLayoutConstraint(item: keyWindow, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1, constant: 0) let topConstraint = NSLayoutConstraint(item: keyWindow, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: keyWindow, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: 0) keyWindow.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint]) }()) DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(activityData.minimumDisplayTime)) { self._hide() } } private func _hide() { if state == .waitingToHide { hide() } else if state == .waitingToShow { state = .hidden } else if state != .hidden { state = .waitingToHide } } private func hide() { guard let keyWindow = UIApplication.shared.keyWindow else { return } for item in keyWindow.subviews where item.restorationIdentifier == restorationIdentifier { item.removeFromSuperview() } state = .hidden } }
gpl-3.0
akosma/Swift-Presentation
PresentationKit/Demos/MathDemo.swift
1
2131
import Cocoa typealias ScalarFunction = Double -> Double typealias Trapezoidal = (Double, Double) -> Double prefix operator ∑ {} prefix func ∑ (array: [Double]) -> Double { var result = 0.0 for value in array { result += value } return result } func ~= (left: Double, right: Double) -> Bool { let ε : Double = 0.001 var δ = left - right return abs(δ) <= ε } // Trapezoidal rule adapted from // http://www.numericmethod.com/About-numerical-methods/numerical-integration/trapezoidal-rule prefix operator ∫ {} prefix func ∫ (𝑓: ScalarFunction) -> Trapezoidal { return { (min : Double, max : Double) -> (Double) in let steps = 100 let h = abs(min - max) / Double(steps) var surfaces : [Double] = [] for position in 0..<steps { let x1 = min + Double(position) * h let x2 = x1 + h let y1 = 𝑓(x1) let y2 = 𝑓(x2) let s = (y1 + y2) * h / 2 surfaces.append(s) } return ∑surfaces } } public class MathDemo: BaseDemo { override public var description : String { return "This demo shows how to use custom operations to represent complex mathematical operations." } public override var URL : NSURL { return NSURL(string: "https://github.com/mattt/Euler") } public override func show() { let π = M_PI let sum = ∑[1, 2, 3, 5, 8, 13] // Function taken from the "fast numeric integral" example from // http://www.codeproject.com/Articles/31550/Fast-Numerical-Integration func 𝑓 (x: Double) -> Double { return exp(-x / 5.0) * (2.0 + sin(2.0 * x)) } let integral = (∫𝑓) (0, 100) let sinIntegral = ∫sin let curve1 = sinIntegral(0, π/2) let curve2 = sinIntegral(0, π) assert(curve1 ~= 1, "Almost 1") assert(curve2 ~= 2, "Almost 2") println("sum: \(sum) – integral: \(integral) – curve1: \(curve1) – curve2: \(curve2)") } }
bsd-2-clause
jboullianne/EndlessTunes
EndlessSoundFeed/PlaylistSelectionController.swift
1
5763
// // PlaylistSelectionController.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 5/17/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import UIKit class PlaylistSelectionController: UIViewController, UITableViewDelegate, UITableViewDataSource { var manager:AccountManager! var potentialTrack:Track! @IBOutlet var albumView: UIImageView! @IBOutlet var titleLabel: UILabel! @IBOutlet var subtitleLabel: UILabel! @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.manager = AccountManager.sharedInstance // 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() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.tableFooterView = UIView() albumView.image = potentialTrack.thumbnailImage albumView.layer.cornerRadius = 3 titleLabel.text = potentialTrack.title subtitleLabel.text = potentialTrack.author } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return manager.playlists.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlaylistSelectionCell", for: indexPath) let index = indexPath.row cell.textLabel?.text = manager.playlists[index].name cell.textLabel?.textColor = UIColor.white cell.detailTextLabel?.text = "\(manager.playlists[index].tracks.count)" cell.detailTextLabel?.textColor = UIColor.white return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let index = indexPath.row //add track to playlist self.manager.addTrack(toPlaylist: potentialTrack, index: index) self.dismiss(animated: true, completion: nil) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } @IBAction func cancelPressed(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func createNewPressed(_ sender: Any) { print("Create Playlist") let ac = UIAlertController(title: "Create Playlist", message: "Enter a name for this new playlist", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in print("Canceled Playlist Creation") } let confirmAction = UIAlertAction(title: "Create", style: .default) { (action) in if let field = ac.textFields?[0]{ //print("NEW PLAYLIST NAME:", field.text) let manager = AccountManager.sharedInstance //manager.createNewPlaylist(name: field.text!) manager.create(newPlaylist: field.text!, withTrack: self.potentialTrack) self.dismiss(animated: true, completion: nil) } } ac.addTextField { (textfield) in textfield.placeholder = "Playlist Name" } ac.addAction(cancelAction) ac.addAction(confirmAction) self.present(ac, animated: true, completion: nil) } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
mathewsheets/SwiftLearning
SwiftLearning.playground/Pages/Classes | Structures.xcplaygroundpage/Contents.swift
1
16771
/*: [Table of Contents](@first) | [Previous](@previous) | [Next](@next) - - - # Classes & Structures * callout(Session Overview): The Swift language features that we learned in the previous sessions dealt with simple data types. We learned about 'Int's, 'String's, 'Bool's that allowed us to store values with the correct data type. We can group a small number of data type values together as an atomic unit using tuples and we can store data type values in containers that will enabled us to collect data throughout our programs. Swift also provides us the ability to extend Swift itself by creating custom data types in the form of Classes and Structures. These custom data types in their simplest form are really composite data types, data types that contain other data types. - - - */ import Foundation /*: ## Creating Creating a class or a structure is done with the keywords `class` and `struct`. */ class President { } struct Term { } /*: Above we created a class `President` and a structure `Term`. Right now they don't store data or have behavior. Throughout this session we will build out what a `President` and `Term` can store the behavior it provides. */ /*: ## Types vs. Instances `President` and `Term` are types. There is only 1 in existence throughout your program. We can create many instances of a `President` or `Term`. Remember the simple data types such as `Int` and `String`? There is only 1 `Int` and 1 `String` data type in Swift, but we can create as many instances as `Int` or `String` that we like. */ let president = President() let term = Term() /*: Above we have created instances of type `President` and `Term` into constants. We create `President` and `Term` instance using an initializer `()`. */ /*: ## Value Types vs. Reference Types Value types are data types like `Int` and `String`, their values are copied when either assigned to constancts or variables or passed to functions. Reference types are data type like closures, you are assigning or passing a location pointing to a memory space. Structures are *value types*. Classes are *reference types*. The difference is very important. */ /*: ## Properties Properties enable you to store data within a class or structure. Properties are constants or variables tied to the class/structure (data type) or to an instance of the class/structure. */ class President1 { static var address = "" // stored type property let country = "United States of America" // stored instance constant property var name = "" // stored instance variable propery } struct Term1 { static let length = 4 // stored type property var start: Date? // stored instance variable propery var end: Date? // stored instance variable propery } /*: Above we created a class `President1` and structure `Term1`, each with a type property and instance properties of a constant and variables. Some properties are initialized and some are optional. */ /*: ### Instance Stored Properties `President1` and `Term1` both have instance stored properties. You can change instance stored properties through out your program for that particular instance. */ let president1 = President1() president1.name = "George Washington" var term1 = Term1() term1.start = DateUtils.createDate(year: 1789, month: 4, day: 30) term1.end = DateUtils.createDate(year: 1797, month: 3, day: 4) /*: Above we assign the `president1.name`, `term1.start` and `term1.end` instance stored property. */ /*: ### Type Stored Properties Stored properties that only exist for the class/structure and *not* the instance of a class/structure are type stored properties. You create a type property with the keyword `static`. */ President1.address = "1600 Pennsylvania Ave NW, Washington, DC 20500" let presidentAddress = President1.address let presidentialLength = Term1.length /*: Above we assign the `President1.address` type store property. We are able to do this because it's a variable. The `Term.length` is a constant, therefore we can not assign a new value to it. */ //: > **Experiment**: Uncomment below to see what happens. //president1.country = "South" //Term1.length = 8 //let term2 = Term1(); //term2.start = nil /*: #### Computed Properties Swift provides properties that look and act like stored properties, but they don't store anything; they derive values or accept values to be stored in a different way. These types of properties are called *computed properties*. */ class President3 { var birthDate: Date? var deathDate: Date? var yearsAlive: Int { // computed property with "get", and "set" with custom parameter get { guard birthDate != nil && deathDate != nil else { return 0 } return DateUtils.yearSpan(from: birthDate!, to: deathDate!) } set(years) { guard birthDate != nil else { return } let dateComps = Calendar.current.dateComponents([.year, .month, .day], from: birthDate!) deathDate = DateUtils.createDate(year: dateComps.year! + years, month: dateComps.month!, day: dateComps.day!) } } var diedHowLongAgo: Int { // shorthand setter declaration, allowed to omit the (parenthesis and custom parameter name) get { guard deathDate != nil else { return 0 } return DateUtils.yearSpan(from: deathDate!, to: Date()) } set { // no custom parameter, 'newValue' is the implicit constant storing the value let nowComps = Calendar.current.dateComponents([.year, .month, .day], from: Date()) deathDate = DateUtils.createDate(year: nowComps.year! - newValue, month: nowComps.month!, day: nowComps.day! - 1) // subtract 1 so we don't end on same date } } var age: Int { // read-only computed property, allowed to omit the "get" guard birthDate != nil else { return 0 } return DateUtils.yearSpan(from: birthDate!, to: Date()) } } let ronald = President3() ronald.birthDate = DateUtils.createDate(year: 1911, month: 2, day: 6) ronald.diedHowLongAgo = 11 print("died \(ronald.diedHowLongAgo) years ago") print("had \(ronald.yearsAlive) years on earth") print("if alive he would be \(ronald.age) years old") /*: Above we created a `President3` class with stored properties of `birthDate` and `deathDate` and computed properties of `yearsAlive`, `diedHowLongAgo`, and `age`. Notice how the computed properteis act like proxies for the stored properties. Also notice how a computed property can be read-only as well as the shorhand version of the `set` for the `diedHowLongAgo` computed property. */ /*: ### Property Observers Swift provides the abiliy to observe changes to properties when values change. The `willSet` method is called just before the property value is set and the `didSet` is called just after the property value is set. */ class ElectoralVote { static let houseVotes = 435 static let senateVotes = 100 static let dictrictOfColumbiaVotes = 3 static let maxElectoralVotes = houseVotes + senateVotes + dictrictOfColumbiaVotes static let electoralVotesNeedToWin = maxElectoralVotes / 2 var count: Int = 0 { willSet { print("About to set vote count to \(newValue)") // 'newValue' is the implicit constant storing the value } didSet { print("You had \(oldValue) votes, now you have \(count)") // 'oldValue' is the implicit constant storing the value if ElectoralVote.electoralVotesNeedToWin < count { print("You just won the presidency") } } } } print("There are a total of \(ElectoralVote.maxElectoralVotes) electoral votes.") print("You need more than \(ElectoralVote.electoralVotesNeedToWin) electoral votes to win the presidency.") let electoralVote = ElectoralVote() electoralVote.count = 100 electoralVote.count = 270 /*: Above we have a stored property `count` that is using the property observers of `willSet` and `didSet`. `willSet` provides the special `newValue` constant of *what* the property will change to. `didSet` provides the constant `oldValue` after the property as been changed. */ /*: ## Initializing Initializers on classes and structures are specials methods that initialize the class or structure. */ class President4 { var name = "James Madison" var state = "Virginia" var party = "Democratic-Republican" } struct Term4 { var start: Date var end: Date } /*: ### Default Initializer Both classes and structures data types have default initializers. The default initializer is simply `()`, an empty pair of parentheses. */ let president4 = President4() print(president4.name) print(president4.state) print(president4.party) /*: Above we create a new instance of class `President4` by using the default initializer of `()`. */ /*: ### Structures: Memberwise Initializer Swift automatically provides structures an initializer with parameters for every variable stored property. */ let startTerm4 = DateUtils.createDate(year: 2004, month: 11, day: 2) let endTerm4 = DateUtils.createDate(year: 2008, month: 11, day: 2) let term4 = Term4(start: startTerm4!, end: endTerm4!) /*: Above we create a new instance of structure `Term4` by using the initializer memberwise initializer. */ /*: ## The `self` property and Custom Initializers Custom initializers are initializers created by you for the purpose of supplying values to a class/structure. You use the argument values of the initializer to set properties. If the argument names are the same as the property names, you can use the implicit `self` property to distinguish between the class/structure and the argument. One important note on custom initializers is that all non-optional stored properties must be initialized. */ class President5 { var name: String var state: String var party: String init(name: String, state: String, party: String) { // initializer to set values using "self" self.name = name self.state = state self.party = party } } struct Term5 { var start: Date var end: Date init(start: Date, end: Date) { // you can have multiple initializers self.start = start self.end = end } init(start: Date, years: Int) { let startComps = Calendar.current.dateComponents([.year, .month, .day], from: start) let end = DateUtils.createDate(year: startComps.year! + years, month: startComps.month!, day: startComps.day!)! self.init(start: start, end: end) // allowed to call another initialize and need to initialize all non-optional stored properties } } let president5 = President5(name: "James Monroe", state: "Virginia", party: "Democratic-Republican") let term5_1 = Term5(start: DateUtils.createDate(year: 1817, month: 3, day: 4)!, end: DateUtils.createDate(year: 1825, month: 3, day: 4)!) let term5_2 = Term5(start: DateUtils.createDate(year: 1817, month: 3, day: 4)!, years: 8) print(term5_1.start) print(term5_1.end) print(term5_2.start) print(term5_2.end) /*: Above we have class `President5` and structure `Term5`, both with custom initializer using `self` inside the initializer. */ /*: ## Methods Methods give you the abiliy to provide behavior to your class/structure. Methods are just like functions, but are tied the class/structure and are able to access properties within the class/structure. */ class President6 { var firstname: String! var lastname: String! var street: String! var city: String! var state: String! var zip: String! // custom initializer init(firstname: String, lastname: String) { self.firstname = firstname self.lastname = lastname } // instance method func getFullname() -> String { return firstname + " " + lastname } // type method static func buildFullname(firstname: String, lastname: String) -> String { var fullname = "" if(!firstname.isEmpty) { fullname += firstname } if(!lastname.isEmpty) { fullname += " " fullname += lastname } return fullname } // type method that can be overridden by a subclass... inheritance not cover yet class func buildAddress(street: String, city: String, state: String, zip: String) -> String { var address = "" if(!street.isEmpty) { address += street address += "," } if(!city.isEmpty) { address += "\n" address += city address += "," } if(!state.isEmpty) { address += " " address += state } if(!zip.isEmpty) { address += " " address += zip } return address } } /*: ### Instance Methods `President6` has 1 instance method. It has access to instance properties. */ let president6 = President6(firstname: "John", lastname: "Adams") print(president6.getFullname()) /*: Above we assign an instance of `President6` to a constant and print the return of the instance method `getFullname()`. */ /*: ### Type Methods `President6` has 2 type methods. Type methods do not have access to instance properties. You use the name of the class/structure then the method name to call a type method. */ president6.street = "1600 Pennsylvania Ave NW" president6.city = "Washington" president6.state = "DC" president6.zip = "20500" let address = President6.buildAddress(street: president6.street, city: president6.city, state: president6.state, zip: president6.zip) print("The address of the president is\n\(address)") let fullname = President6.buildFullname(firstname: president6.firstname, lastname: president6.lastname) print("The name of the president is \(fullname)") /*: Above we call `buildAddress` and `buildFullname` type methods of class `President6` passing in arguments from instance properties. */ /*: ### Working with Parameters Remember that methods are really functions but tied to either a class/structure or an instance of a class/structure and therefore have access to properties. One important note, type properties don't have access to instance properties, but instance properties can access type properties. */ class President7 { var name: String! var vpName: String! func setFullname(first firstname: String, last lastname: String) { // shortened argument names name = firstname + " " + lastname } func setVpName(_ firstname: String, _ lastname: String) { // no argument names vpName = firstname + " " + lastname } } let president7 = President7() president7.setFullname(first: "Andrew", last: "Jackson") president7.setVpName("Martin", "Van Buren") /*: Above are two methods, each mutating a name, either the president's name or vice president's name. All the rules we learned about functions in the [Functions](Functions) session apply to methods. */ /*: ## Deinitialization Every class/structure has an `init`ializer and also an `deinit`ializer. The only purpose for the deinitializer is to do any cleanup tasks just before the memory of the class/structure becomes unreferencable. */ class President10 { var name: String init(name: String) { print("initializing with \(name)") self.name = name } deinit { print("de-initializing president \(name)") } } var president10: President10? president10 = President10(name: "John Tyler") president10 = nil /*: Above we have a print statement in the `init` and the `deinit` to show that the `deinit` will get called when the instance is no longer accessible. */ /*: - - - * callout(Checkpoint): At this point, you should be able to extend the Swift language by providing your own classes or structures and create instances of your class/structure using properties and methods. - - - [Table of Contents](@first) | [Previous](@previous) | [Next](@next) */
mit
skedgo/tripkit-ios
Tests/TripKitTests/parsing/TKTripSegmentModeTitleTest.swift
1
803
// // TKTripSegmentModeTitleTest.swift // TripKitTests // // Created by Brian Huang on 27/8/21. // Copyright © 2021 SkedGo Pty Ltd. All rights reserved. // import XCTest @testable import TripKit class TKTripSegmentModeTitleTest: XCTestCase { func testSegmentModeTitle() throws { let json = """ { "alt": "Shuttle", "color": { "blue": 26, "green": 34, "red": 226 }, "description": "SMARTBus", "identifier": "ps_drt_smartbus", "localIcon": "shuttlebus", "remoteIconIsBranding": true } """ let model = try JSONDecoder().decode(TKModeInfo.self, from: Data(json.utf8)) XCTAssertNotNil(model) XCTAssertEqual(model.descriptor, "SMARTBus") } }
apache-2.0
lieven/fietsknelpunten-ios
FietsknelpuntenAPI/Tag.swift
1
414
// // Tag.swift // Fietsknelpunten // // Created by Lieven Dekeyser on 12/11/16. // Copyright © 2016 Fietsknelpunten. All rights reserved. // import UIKit public class Tag: NSObject { public let identifier: String public let name: String public let info: String? public init(identifier: String, name: String, info: String?) { self.identifier = identifier self.name = name self.info = info } }
mit
Quick/QuickOnLinuxExample
Tests/SampleLibraryTests/SampleLibrarySpec.swift
2
281
import Quick import Nimble import SampleLibrary class SampleLibrarySpec: QuickSpec { override func spec() { describe("foo") { it("returns a nice greeting") { expect(Foo().greeting()).to(equal("Hello World")) } } } }
mit
Shashi717/ImmiGuide
ImmiGuide/ImmiGuide/TeamViewController.swift
1
2908
// // TeamViewController.swift // ImmiGuide // // Created by Annie Tung on 2/19/17. // Copyright © 2017 Madushani Lekam Wasam Liyanage. All rights reserved. // import UIKit class TeamViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var teamCollectionView: UICollectionView! let teamArray = ["Annie Tung","Christopher Chavez", "Eashir Arafat", "Madushani Lekam Wasam Liyanage"] let titleArray = ["Design Lead", "Project Manager", "Demo Lead", "Technical Lead"] let teamDict = ["Annie Tung":"https://www.linkedin.com/in/tungannie/", "Christopher Chavez": "https://www.linkedin.com/in/cristopher-chavez-6693b965/", "Eashir Arafat":"https://www.linkedin.com/in/eashirarafat/", "Madushani Lekam Wasam Liyanage":"https://www.linkedin.com/in/madushani-lekam-wasam-liyanage-74319bb5/"] var selectedTeamMember = "" override func viewDidLoad() { super.viewDidLoad() teamCollectionView.delegate = self teamCollectionView.dataSource = self self.navigationItem.titleView = UIImageView(image: UIImage(named: "TeamIcon")) teamCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "teamCellIdentifier") let nib = UINib(nibName: "TeamDetailCollectionViewCell", bundle:nil) teamCollectionView.register(nib, forCellWithReuseIdentifier: "teamCellIdentifier") } // MARK: - Collection View Data Source func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return teamArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "teamCellIdentifier", for: indexPath) as! TeamDetailCollectionViewCell cell.nameLabel.text = teamArray[indexPath.row] cell.titleLabel.text = titleArray[indexPath.row] cell.imageView.image = UIImage(named: teamArray[indexPath.row]) cell.setNeedsLayout() return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedTeamMember = teamArray[indexPath.row] performSegue(withIdentifier: "LinkedInSegue", sender: self) } // 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?) { if segue.identifier == "LinkedInSegue" { if let cuvc = segue.destination as? ContactUsViewController { cuvc.url = teamDict[selectedTeamMember] } } } }
mit
wangyun-hero/sinaweibo-with-swift
sinaweibo/Classes/ViewModel/WYStatusViewModel.swift
1
3216
// // WYStatusViewModel.swift // sinaweibo // // Created by 王云 on 16/9/3. // Copyright © 2016年 王云. All rights reserved. // import UIKit class WYStatusViewModel: NSObject { // 当前微博作者的会员图标 var memberImage: UIImage? // 认证的图标 var avatarImage: UIImage? // 转发数 var reposts_count: String? // 评论数量的字符串 var comments_count: String? // 静态数量的字符串 var attitudes_count: String? // 转发微博的内容 var retweetStautsText: String? var status: WYStatus? { didSet { // 会员图标计算出来 if let mbrank = status?.user?.mbrank, mbrank > 0 { // 会员图标名字 let imageName = "common_icon_membership_level\(mbrank)" memberImage = UIImage(named: imageName) } // // 认证图标计算 认证类型 -1:没有认证,1:认证用户,2,3,5: 企业认证,220: 达人 if let type = status?.user?.verified_type { switch type { case 1: // 大v avatarImage = #imageLiteral(resourceName: "avatar_vip") case 2, 3, 5: // 企业 avatarImage = #imageLiteral(resourceName: "avatar_enterprise_vip") case 220: // 达人 avatarImage = #imageLiteral(resourceName: "avatar_grassroot") default: break } } // 计算转发,评论,赞数 reposts_count = caclCount(count: status?.reposts_count ?? 0, defaultTitle: "转发") comments_count = caclCount(count: status?.comments_count ?? 0, defaultTitle: "评论") attitudes_count = caclCount(count: status?.attitudes_count ?? 0, defaultTitle: "赞") // 计算转发微博的内容 if let text = status?.retweeted_status?.text, let name = status?.retweeted_status?.user?.name{ retweetStautsText = "@\(name):\(text)" } } } /// 计算转发评论赞的文字显示内容 /// /// - parameter count: 数量 /// - parameter defaultTitle: 如果数量为0,就返回默认的标题 /// /// - returns: <#return value description#> private func caclCount(count: Int, defaultTitle: String) -> String { if count == 0 { return defaultTitle }else{ // 0 - 10000 --> 显示具体的数值 // 10000-11000 --> 1万 // 13000 --> 1.3万 // 20800 2万 if count < 10000 { return "\(count)" }else{ // 取到十位数 let result = count / 1000 // 取到小数点后的一位 let str = "\(Float(result) / 10)" let string = "\(str)万" // 如果有.0就替换成空字符串 return string.replacingOccurrences(of: ".0", with: "") } } } }
mit
SwiftGen/SwiftGen
Sources/TestUtils/Fixtures/Generated/IB-macOS/scenes-swift4/all-customName.swift
1
5663
// swiftlint:disable all // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen // swiftlint:disable sorted_imports import Foundation import AppKit import ExtraModule import PrefsWindowController // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length implicit_return // MARK: - Storyboard Scenes // swiftlint:disable explicit_type_interface identifier_name line_length prefer_self_in_static_references // swiftlint:disable type_body_length type_name internal enum XCTStoryboardCustom { internal enum AdditionalImport: StoryboardType { internal static let storyboardName = "AdditionalImport" internal static let `private` = SceneType<PrefsWindowController.DBPrefsWindowController>(storyboard: AdditionalImport.self, identifier: "private") } internal enum Anonymous: StoryboardType { internal static let storyboardName = "Anonymous" } internal enum Dependency: StoryboardType { internal static let storyboardName = "Dependency" internal static let dependent = SceneType<ExtraModule.LoginViewController>(storyboard: Dependency.self, identifier: "Dependent") } internal enum KnownTypes: StoryboardType { internal static let storyboardName = "Known Types" internal static let item1 = SceneType<AppKit.NSWindowController>(storyboard: KnownTypes.self, identifier: "item 1") internal static let item2 = SceneType<AppKit.NSSplitViewController>(storyboard: KnownTypes.self, identifier: "item 2") internal static let item3 = SceneType<AppKit.NSViewController>(storyboard: KnownTypes.self, identifier: "item 3") internal static let item4 = SceneType<AppKit.NSPageController>(storyboard: KnownTypes.self, identifier: "item 4") internal static let item5 = SceneType<AppKit.NSTabViewController>(storyboard: KnownTypes.self, identifier: "item 5") } internal enum Message: StoryboardType { internal static let storyboardName = "Message" internal static let messageDetails = SceneType<SwiftGen.DetailsViewController>(storyboard: Message.self, identifier: "MessageDetails") internal static let messageList = SceneType<AppKit.NSViewController>(storyboard: Message.self, identifier: "MessageList") internal static let messageListFooter = SceneType<AppKit.NSViewController>(storyboard: Message.self, identifier: "MessageListFooter") internal static let messagesTab = SceneType<SwiftGen.CustomTabViewController>(storyboard: Message.self, identifier: "MessagesTab") internal static let splitMessages = SceneType<AppKit.NSSplitViewController>(storyboard: Message.self, identifier: "SplitMessages") internal static let windowCtrl = SceneType<AppKit.NSWindowController>(storyboard: Message.self, identifier: "WindowCtrl") } internal enum Placeholder: StoryboardType { internal static let storyboardName = "Placeholder" internal static let window = SceneType<AppKit.NSWindowController>(storyboard: Placeholder.self, identifier: "Window") } } // swiftlint:enable explicit_type_interface identifier_name line_length prefer_self_in_static_references // swiftlint:enable type_body_length type_name // MARK: - Implementation Details internal protocol StoryboardType { static var storyboardName: String { get } } internal extension StoryboardType { static var storyboard: NSStoryboard { let name = NSStoryboard.Name(self.storyboardName) return NSStoryboard(name: name, bundle: BundleToken.bundle) } } internal struct SceneType<T> { internal let storyboard: StoryboardType.Type internal let identifier: String internal func instantiate() -> T { let identifier = NSStoryboard.SceneIdentifier(self.identifier) guard let controller = storyboard.storyboard.instantiateController(withIdentifier: identifier) as? T else { fatalError("Controller '\(identifier)' is not of the expected class \(T.self).") } return controller } @available(macOS 10.15, *) internal func instantiate(creator block: @escaping (NSCoder) -> T?) -> T where T: NSViewController { return storyboard.storyboard.instantiateController(identifier: identifier, creator: block) } @available(macOS 10.15, *) internal func instantiate(creator block: @escaping (NSCoder) -> T?) -> T where T: NSWindowController { return storyboard.storyboard.instantiateController(identifier: identifier, creator: block) } } internal struct InitialSceneType<T> { internal let storyboard: StoryboardType.Type internal func instantiate() -> T { guard let controller = storyboard.storyboard.instantiateInitialController() as? T else { fatalError("Controller is not of the expected class \(T.self).") } return controller } @available(macOS 10.15, *) internal func instantiate(creator block: @escaping (NSCoder) -> T?) -> T where T: NSViewController { guard let controller = storyboard.storyboard.instantiateInitialController(creator: block) else { fatalError("Storyboard \(storyboard.storyboardName) does not have an initial scene.") } return controller } @available(macOS 10.15, *) internal func instantiate(creator block: @escaping (NSCoder) -> T?) -> T where T: NSWindowController { guard let controller = storyboard.storyboard.instantiateInitialController(creator: block) else { fatalError("Storyboard \(storyboard.storyboardName) does not have an initial scene.") } return controller } } // swiftlint:disable convenience_type private final class BundleToken { static let bundle: Bundle = { #if SWIFT_PACKAGE return Bundle.module #else return Bundle(for: BundleToken.self) #endif }() } // swiftlint:enable convenience_type
mit
hipposan/Oslo
Oslo/PublishedPhotoCollectionViewCell.swift
1
541
// // PublishedPhotoCollectionViewCell.swift // Oslo // // Created by Ziyi Zhang on 01/12/2016. // Copyright © 2016 Ziyideas. All rights reserved. // import UIKit class PublishedPhotoCollectionViewCell: UICollectionViewCell { @IBOutlet var publishedPhotoImageView: UIImageView! override func layoutSubviews() { super.layoutSubviews() self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.1 self.layer.shadowRadius = 3.0 self.layer.shadowOffset = CGSize(width: 2, height: 4) } }
mit
SwiftGen/SwiftGen
Sources/SwiftGen/Commands/Template/Template Cat.swift
1
508
// // SwiftGen // Copyright © 2022 SwiftGen // MIT Licence // import ArgumentParser extension Commands.Template { struct Cat: ParsableCommand { static let configuration = CommandConfiguration(abstract: "Print path of a given named template.") @OptionGroup var template: TemplateOptions @OptionGroup var output: Commands.OutputDestination func run() throws { let content: String = try template.path.read() try output.destination.write(content: content) } } }
mit
onekiloparsec/SwiftAA
Package.swift
1
1832
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SwiftAA", platforms: [ .macOS(.v10_13), .iOS(.v12), ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "AAplus", type: .dynamic, targets: ["AAplus"] ), .library( name: "ObjCAA", targets: ["ObjCAA"] ), .library( name: "SwiftAA", type: .dynamic, targets: ["SwiftAA"] ) ], 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 which this package depends on. .target( name: "AAplus", dependencies: [], path: "Sources/AA+", exclude: ["naughter.css", "CMakeLists.txt", "AA+.htm", "include/AAVSOP2013.h", "include/AA+.h", "AAVSOP2013.cpp", "AATest.cpp"] ), .target( name: "ObjCAA", dependencies: ["AAplus"], exclude: [] ), .target( name: "SwiftAA", dependencies: ["ObjCAA"], exclude: [] ), .testTarget( name: "ObjCAATests", dependencies: ["ObjCAA"]), .testTarget( name: "SwiftAATests", dependencies: ["SwiftAA"]), ], cxxLanguageStandard: .gnucxx17 )
mit
shopgun/shopgun-ios-sdk
Sources/TjekPublicationViewer/IncitoPublication/IncitoLoaderViewController+v4APILoader.swift
1
6571
/// /// Copyright (c) 2020 Tjek. All rights reserved. /// import Foundation import Future @_exported import Incito #if !COCOAPODS // Cocoapods merges these modules import TjekAPI import TjekEventsTracker import enum TjekUtils.JSONValue #endif import UIKit enum IncitoAPIQueryError: Error { case invalidData case notAnIncitoPublication } struct IncitoAPIQuery: Encodable { enum DeviceCategory: String, Encodable { case mobile case tablet case desktop } enum Orientation: String, Encodable { case horizontal case vertical } enum PointerType: String, Encodable { case fine case coarse } var id: PublicationId var deviceCategory: DeviceCategory var orientation: Orientation var pointer: PointerType var pixelRatio: Double var maxWidth: Int var versionsSupported: [String] var localeCode: String? var time: Date? var featureLabels: [String: Double] var apiRequest: APIRequest<IncitoDocument, API_v4> { APIRequest<IncitoDocument, API_v4>( endpoint: "generate_incito_from_publication", body: .encodable(self), decoder: APIRequestDecoder { data, _ in guard let jsonDict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let jsonStr = String(data: data, encoding: .utf8) else { throw IncitoAPIQueryError.invalidData } return try IncitoDocument(jsonDict: jsonDict, jsonStr: jsonStr) } ) } enum CodingKeys: String, CodingKey { case id, deviceCategory = "device_category", orientation, pointer, pixelRatio = "pixel_ratio", maxWidth = "max_width", versionsSupported = "versions_supported", localeCode = "locale_code", time, featureLabels = "feature_labels" } func encode(to encoder: Encoder) throws { var c = encoder.container(keyedBy: CodingKeys.self) try c.encode(self.id, forKey: .id) try c.encode(self.deviceCategory, forKey: .deviceCategory) try c.encode(self.orientation, forKey: .orientation) try c.encode(self.pointer, forKey: .pointer) try c.encode(self.pixelRatio, forKey: .pixelRatio) try c.encode(self.maxWidth, forKey: .maxWidth) try c.encode(self.versionsSupported, forKey: .versionsSupported) try c.encode(self.localeCode, forKey: .localeCode) try c.encode(self.time, forKey: .time) let features: [[String: JSONValue]] = self.featureLabels.map({ ["key": $0.jsonValue, "value": $1.jsonValue] }) try c.encode(features, forKey: .featureLabels) } } extension IncitoAPIQuery.DeviceCategory { init(device: UIDevice) { switch device.userInterfaceIdiom { case .pad: self = .tablet default: self = .mobile } } } extension IncitoLoaderViewController { public func load( publicationId: PublicationId, featureLabelWeights: [String: Double] = [:], apiClient: TjekAPI = .shared, publicationLoaded: ((Result<Publication_v2, Error>) -> Void)? = nil, completion: ((Result<(viewController: IncitoViewController, firstSuccessfulLoad: Bool), Error>) -> Void)? = nil ) { var hasLoadedIncito: Bool = false if TjekEventsTracker.isInitialized { TjekEventsTracker.shared.trackEvent( .incitoPublicationOpened(publicationId) ) } if let publicationLoadedCallback = publicationLoaded { apiClient.send(.getPublication(withId: publicationId)) .eraseToAnyError() .run(publicationLoadedCallback) } let loader = IncitoLoader { [weak self] callback in Future<IncitoAPIQuery>(work: { [weak self] in let viewWidth = Int(self?.view.frame.size.width ?? 0) let windowWidth = Int(self?.view.window?.frame.size.width ?? 0) let screenWidth = Int(UIScreen.main.bounds.size.width) let minWidth = 100 // build the query on the main queue. return IncitoAPIQuery( id: publicationId, deviceCategory: .init(device: .current), orientation: .vertical, pointer: .coarse, pixelRatio: Double(UIScreen.main.scale), maxWidth: max(viewWidth >= minWidth ? viewWidth : windowWidth >= minWidth ? windowWidth : screenWidth, minWidth), versionsSupported: IncitoEnvironment.supportedVersions, localeCode: Locale.autoupdatingCurrent.identifier, time: Date(), featureLabels: featureLabelWeights ) }) .performing(on: .main) .flatMap({ query in apiClient.send(query.apiRequest) }) .eraseToAnyError() // .measure(print: " 🌈 Incito Fully Loaded") .run(callback) } self.load(loader) { vcResult in switch vcResult { case let .success(viewController): let firstLoad = !hasLoadedIncito hasLoadedIncito = true completion?(.success((viewController, firstLoad))) case let .failure(error): completion?(.failure(error)) } } } public func load( publication: Publication_v2, featureLabelWeights: [String: Double] = [:], apiClient: TjekAPI = .shared, completion: ((Result<(viewController: IncitoViewController, firstSuccessfulLoad: Bool), Error>) -> Void)? = nil ) { // if the publication doesnt have a graphId, then just eject with an error guard publication.hasIncitoPublication else { self.load(IncitoLoader(load: { cb in cb(.failure(IncitoAPIQueryError.notAnIncitoPublication)) })) { vcResult in completion?(vcResult.map({ ($0, false) })) } return } self.load( publicationId: publication.id, featureLabelWeights: featureLabelWeights, apiClient: apiClient, completion: completion ) } }
mit
marty-suzuki/QiitaWithFluxSample
QiitaWithFluxSample/Source/Search/Model/SearchTopViewModel.swift
1
5727
// // SearchTopViewModel.swift // QiitaWithFluxSample // // Created by marty-suzuki on 2017/04/16. // Copyright © 2017年 marty-suzuki. All rights reserved. // import RxSwift import RxCocoa import Action import QiitaSession final class SearchTopViewModel { private let session: QiitaSessionType private let routeAction: RouteAction private let applicationAction: ApplicationAction let lastItemsRequest: Property<ItemsRequest?> private let _lastItemsRequest = Variable<ItemsRequest?>(nil) let items: Property<[Item]> private let _items = Variable<[Item]>([]) let totalCount: Property<Int> private let _totalCount = Variable<Int>(0) let error: Property<Error?> private let _error = Variable<Error?>(nil) let hasNext: Property<Bool> private let _hasNext = Variable<Bool>(true) let searchAction: Action<ItemsRequest, ElementsResponse<Item>> private let perPage: Int = 20 private let disposeBag = DisposeBag() let noResult: Observable<Bool> let reloadData: Observable<Void> let isFirstLoading: Observable<Bool> let keyboardWillShow: Observable<UIKeyboardInfo> let keyboardWillHide: Observable<UIKeyboardInfo> init(session: QiitaSessionType = QiitaSession.shared, routeAction: RouteAction = .shared, applicationAction: ApplicationAction = .shared, selectedIndexPath: Observable<IndexPath>, searchText: ControlProperty<String>, deleteButtonTap: ControlEvent<Void>, reachedBottom: Observable<Void>) { self.session = session self.routeAction = routeAction self.applicationAction = applicationAction self.lastItemsRequest = Property(_lastItemsRequest) self.items = Property(_items) self.error = Property(_error) self.totalCount = Property(_totalCount) self.hasNext = Property(_hasNext) self.searchAction = Action { [weak session] request -> Observable<ElementsResponse<Item>> in session.map { $0.send(request) } ?? .empty() } let itemsObservable = items.changed self.noResult = Observable.combineLatest(itemsObservable, searchAction.executing) .map { !$0.isEmpty || $1 } let hasNextObservable = hasNext.changed self.reloadData = Observable.combineLatest(itemsObservable, hasNextObservable) .map { _ in } self.isFirstLoading = Observable.combineLatest(itemsObservable, hasNextObservable, lastItemsRequest.changed) .map { $0.0.isEmpty && $0.1 && $0.2 != nil } self.keyboardWillShow = NotificationCenter.default.rx.notification(.UIKeyboardWillShow) .map { $0.userInfo } .filterNil() .map { UIKeyboardInfo(info: $0) } .filterNil() self.keyboardWillHide = NotificationCenter.default.rx.notification(.UIKeyboardWillHide) .map { $0.userInfo } .filterNil() .map { UIKeyboardInfo(info: $0) } .filterNil() selectedIndexPath .withLatestFrom(_items.asObservable()) { $1[$0.row] } .map { $0.url } .subscribe(onNext: { [weak routeAction] in routeAction?.show(searchDisplayType: .webView($0)) }) .disposed(by: disposeBag) searchAction.elements .subscribe(onNext: { [weak self] response in guard let me = self else { return } me._items.value.append(contentsOf: response.elements) me._totalCount.value = response.totalCount me._hasNext.value = (me._items.value.count < me._totalCount.value) && !response.elements.isEmpty }) .disposed(by: disposeBag) searchAction.errors .map { Optional($0) } .bind(to: _error) .disposed(by: disposeBag) deleteButtonTap .subscribe(onNext: { [weak applicationAction] in applicationAction?.removeAccessToken() }) .disposed(by: disposeBag) let firstLoad = searchText .debounce(0.3, scheduler: MainScheduler.instance) .distinctUntilChanged() .do(onNext: { [weak self] _ in self?._lastItemsRequest.value = nil self?._items.value.removeAll() self?._hasNext.value = true }) .filter { !$0.isEmpty } .map { ($0, 1) } let loadMore = reachedBottom .withLatestFrom(hasNext.asObservable()) .filter { $0 } .withLatestFrom(lastItemsRequest.asObservable()) .filterNil() .map { ($0.query, $0.page + 1) } Observable.merge(firstLoad, loadMore) .flatMap { [weak self] query, page -> Observable<ItemsRequest> in self.map { .just(ItemsRequest(page: page, perPage: $0.perPage, query: query)) } ?? .empty() } .bind(to: _lastItemsRequest) .disposed(by: disposeBag) _lastItemsRequest.asObservable() .filterNil() .distinctUntilChanged { $0.page == $1.page && $0.query == $1.query } .subscribe(onNext: { [weak self] request in self?.searchAction.execute(request) }) .disposed(by: disposeBag) } }
mit
CrazyKids/ADSideMenu
ADSideMenuSample/ADSideMenuSample/Controllers/ADRightMenuViewController.swift
1
1346
// // ADRightMenuViewController.swift // ADSideMenuSample // // Created by duanhongjin on 16/6/17. // Copyright © 2016年 CrazyKids. All rights reserved. // import UIKit class ADRightMenuViewController: UIViewController, UITableViewDataSource { var tableView: UITableView? let tableData = ["小明", "小红", "小兰", "小邓"] override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: view.bounds) tableView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView?.dataSource = self // tableView?.backgroundColor = UIColor.clearColor() tableView?.tableFooterView = UIView(frame: CGRect.zero) tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cell") view.addSubview(tableView!) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! cell.selectionStyle = .none cell.textLabel?.text = tableData[indexPath.row] cell.textLabel?.textAlignment = .right return cell } }
mit
shaps80/Stack
Pod/Classes/Transaction.swift
1
4650
/* Copyright © 2015 Shaps Mohsenin. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY SHAPS MOHSENIN `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 APP BUSINESS 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 CoreData /// A transaction provides a type-safe implementation for performing any write action to CoreData public class Transaction: Readable, Writable { /// Returns the stack associated with this transaction private(set) var stack: Stack /// Returns the context associated with this transaction private(set) var context: NSManagedObjectContext /** Internal: Initializes a new transaction for the specified Stack - parameter stack: The stack this transaction will be applied to - parameter context: The context this transaction will be applied to - returns: A new Transaction */ init(stack: Stack, context: NSManagedObjectContext) { self.stack = stack self.context = context } /** Inserts a new entity of the specified class. Usage: `insert() as EntityName` */ public func insert<T: NSManagedObject>() throws -> T { guard let entityName = stack.entityNameForManagedObjectClass(T) where entityName != NSStringFromClass(NSManagedObject) else { throw StackError.EntityNameNotFoundForClass(T) } guard let object = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as? T else { throw StackError.EntityNotFoundInStack(stack, entityName) } return object as T } /** Fetches (or inserts if not found) an entity with the specified identifier */ public func fetchOrInsert<T: NSManagedObject, U: StackManagedKey>(key: String, identifier: U) throws -> T { let results = try fetchOrInsert(key, identifiers: [identifier]) as [T] return results.first! } /** Fetches (or inserts if not found) entities with the specified identifiers */ public func fetchOrInsert<T : NSManagedObject, U : StackManagedKey>(key: String, identifiers: [U]) throws -> [T] { let query = Query<T>(key: key, identifiers: identifiers) let request = try fetchRequest(query) guard let results = try context.executeFetchRequest(request) as? [T] else { throw StackError.FetchError(nil) } if results.count == identifiers.count { return results } var objects = [T]() if let existingIds = (results as NSArray).valueForKey(key) as? [U] { for id in identifiers { if !existingIds.contains(id) { let result = try insert() as T result.setValue(id, forKeyPath: key) objects.append(result) } } } return objects as [T] } /** Performs a fetch using the specified NSManagedObjectID - parameter objectID: The objectID to use for this fetch - throws: An error will be thrown if the query cannot be performed - returns: The resulting object or nil */ public func fetch<T: NSManagedObject>(objectWithID objectID: NSManagedObjectID) throws -> T? { let stack = _stack() let context = stack.currentThreadContext() return try context.existingObjectWithID(objectID) as? T } /** Deletes the specified objects */ public func delete<T: NSManagedObject>(objects: T...) throws { try delete(objects: objects) } /** Deletes the specified objects */ public func delete<T: NSManagedObject>(objects objects: [T]) throws { for object in objects { context.deleteObject(object) } } }
mit
AndreyPanov/ApplicationCoordinator
ApplicationCoordinator/Protocols/BaseView.swift
1
53
protocol BaseView: NSObjectProtocol, Presentable { }
mit
icecoffin/GlossLite
GlossLite/Views/AddEditWord/AddEditWordViewController.swift
1
3909
// // AddEditWordViewController.swift // GlossLite // // Created by Daniel on 01/10/16. // Copyright © 2016 icecoffin. All rights reserved. // import UIKit import SnapKit import IQKeyboardManagerSwift class AddEditWordViewController: UIViewController { fileprivate let viewModel: AddEditWordViewModel private let scrollView = UIScrollView() private let containerView = IQPreviousNextView() private let wordInputView = WordInputView() private let definitionInputView = DefinitionInputView() private let lookUpButton = UIButton(type: .system) // MARK: Initialization init(viewModel: AddEditWordViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View lifecycle & configuration override func viewDidLoad() { super.viewDidLoad() configureView() bindToViewModel() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) _ = wordInputView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) view.endEditing(true) } private func configureView() { view.backgroundColor = .white title = viewModel.title addScrollView() addContainerView() addWordInputView() addDefinitionInputView() addLookUpButton() } private func addScrollView() { view.addSubview(scrollView) scrollView.snp.makeConstraints { make in make.edges.equalToSuperview() } } private func addContainerView() { scrollView.addSubview(containerView) containerView.snp.makeConstraints { make in make.width.edges.equalToSuperview() } } private func addWordInputView() { containerView.addSubview(wordInputView) wordInputView.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview() } wordInputView.text = viewModel.wordText } private func addDefinitionInputView() { containerView.addSubview(definitionInputView) definitionInputView.snp.makeConstraints { make in make.top.equalTo(wordInputView.snp.bottom).offset(8) make.leading.trailing.equalToSuperview() } definitionInputView.text = viewModel.definition } private func addLookUpButton() { containerView.addSubview(lookUpButton) lookUpButton.snp.makeConstraints { make in make.centerX.equalToSuperview() make.top.equalTo(definitionInputView.snp.bottom).offset(16) make.bottom.equalToSuperview().offset(-16) } lookUpButton.setTitle(NSLocalizedString("Look up in the dictionary", comment: ""), for: .normal) lookUpButton.titleLabel?.font = Fonts.openSans(size: 14) lookUpButton.addTarget(self, action: #selector(lookUpButtonTapped(_:)), for: .touchUpInside) } // MARK: View model private func bindToViewModel() { viewModel.onWordDefinitionNotFound = { [unowned self] text in Alert.show(onViewController: self, withTitle: "", message: NSLocalizedString("Definition for '\(text)' couldn't be found", comment: "")) } } // MARK: Actions func lookUpButtonTapped(_ sender: UIButton) { let wordText = wordInputView.text viewModel.lookUpWord(withText: wordText) } func saveWord() { let wordText = wordInputView.text let definition = definitionInputView.text let result = viewModel.validateAndSave(wordText: wordText, definition: definition) switch result { case .emptyWord: handleEmptyWordIssue() default: break } } private func handleEmptyWordIssue() { Alert.show(onViewController: self, withTitle: NSLocalizedString("Validation Error", comment: ""), message: NSLocalizedString("Word text can't be empty.", comment: "")) } }
mit
fellipecaetano/Democracy-iOS
Sources/Support/RxSwift+Unwrap.swift
1
568
import RxSwift protocol Maybe { associatedtype Value static func isEmpty(_ maybe: Self) -> Bool static func dematerialize(_ maybe: Self) -> Value } extension Optional: Maybe { typealias Value = Wrapped static func isEmpty(_ maybe: Optional<Wrapped>) -> Bool { return maybe == nil } static func dematerialize(_ maybe: Optional<Wrapped>) -> Wrapped { return maybe! } } extension Observable where E: Maybe { func unwrap() -> Observable<E.Value> { return filter(not(E.isEmpty)).map(E.dematerialize) } }
mit
linkedin/LayoutKit
LayoutKitTests/CGFloatExtensionTests.swift
6
4502
// Copyright 2016 LinkedIn Corp. // 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. import XCTest @testable import LayoutKit class CGFloatExtensionTests: XCTestCase { struct TestCase { let rawValue: CGFloat /// Map of screen density to rounded value. let roundedValue: [CGFloat: CGFloat] } func testRoundedUpToFractionalPoint() { let scale = UIScreen.main.scale let testCases: [TestCase] = [ TestCase(rawValue: -1.1, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -1.0, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -0.9, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -2.0/3.0]), TestCase(rawValue: -0.5, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -1.0/3.0]), TestCase(rawValue: -1.0/3.0, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: -1.0/3.0]), TestCase(rawValue: -0.3, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 0.0]), TestCase(rawValue: 0.0, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 0.0]), TestCase(rawValue: 0.3, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 1.0/3.0]), TestCase(rawValue: 1.0/3.0, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 1.0/3.0]), TestCase(rawValue: 0.5, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 2.0/3.0]), TestCase(rawValue: 0.9, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), TestCase(rawValue: 1.0, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), TestCase(rawValue: 1.1, roundedValue: [1.0: 2.0, 2.0: 1.5, 3.0: 1.0 + 1.0/3.0]) ] for testCase in testCases { let expected = testCase.roundedValue[scale] XCTAssertEqual(testCase.rawValue.roundedUpToFractionalPoint, expected) } } func testRoundedToFractionalPoint() { let scale = UIScreen.main.scale let testCases: [TestCase] = [ TestCase(rawValue: -1.1, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -1.0, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -0.9, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -0.8, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -2.0/3.0]), TestCase(rawValue: -0.7, roundedValue: [1.0: -1.0, 2.0: -0.5, 3.0: -2.0/3.0]), TestCase(rawValue: -0.6, roundedValue: [1.0: -1.0, 2.0: -0.5, 3.0: -2.0/3.0]), TestCase(rawValue: -0.5, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -2.0/3.0]), TestCase(rawValue: -0.4, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -1.0/3.0]), TestCase(rawValue: -0.3, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -1.0/3.0]), TestCase(rawValue: -0.2, roundedValue: [1.0: 0.0, 2.0: -0.0, 3.0: -1.0/3.0]), TestCase(rawValue: -0.1, roundedValue: [1.0: 0.0, 2.0: -0.0, 3.0: 0.0]), TestCase(rawValue: 0.0, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 0.0]), TestCase(rawValue: 0.1, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 0.0]), TestCase(rawValue: 0.2, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 1.0/3.0]), TestCase(rawValue: 0.3, roundedValue: [1.0: 0.0, 2.0: 0.5, 3.0: 1.0/3.0]), TestCase(rawValue: 0.4, roundedValue: [1.0: 0.0, 2.0: 0.5, 3.0: 1.0/3.0]), TestCase(rawValue: 0.5, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 2.0/3.0]), TestCase(rawValue: 0.6, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 2.0/3.0]), TestCase(rawValue: 0.7, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 2.0/3.0]), TestCase(rawValue: 0.8, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 2.0/3.0]), TestCase(rawValue: 0.9, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), TestCase(rawValue: 1.0, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), TestCase(rawValue: 1.1, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), ] for testCase in testCases { let expected = testCase.roundedValue[scale] XCTAssertEqual(testCase.rawValue.roundedToFractionalPoint, expected) } } }
apache-2.0
carabina/DDMathParser
MathParser/FunctionSet.swift
2
2481
// // FunctionSet.swift // DDMathParser // // Created by Dave DeLong on 9/18/15. // // import Foundation internal class FunctionSet { private var functionsByName = Dictionary<String, FunctionRegistration>() private let caseSensitive: Bool internal init(caseSensitive: Bool) { self.caseSensitive = caseSensitive Function.standardFunctions.forEach { do { try registerFunction($0) } catch _ { fatalError("Conflicting name/alias in built-in functions") } } } internal func normalize(name: String) -> String { return caseSensitive ? name : name.lowercaseString } private func registeredFunctionForName(name: String) -> FunctionRegistration? { let casedName = normalize(name) return functionsByName[casedName] } internal func evaluatorForName(name: String) -> FunctionEvaluator? { return registeredFunctionForName(name)?.function } internal func addAlias(alias: String, forFunctionName name: String) throws { guard registeredFunctionForName(alias) == nil else { throw FunctionRegistrationError.FunctionAlreadyExists(alias) } guard let registration = registeredFunctionForName(name) else { throw FunctionRegistrationError.FunctionDoesNotExist(name) } let casedAlias = normalize(alias) registration.addAlias(casedAlias) functionsByName[casedAlias] = registration } internal func registerFunction(function: Function) throws { let registration = FunctionRegistration(function: function, caseSensitive: caseSensitive) // we need to make sure that every name is accounted for for name in registration.names { guard registeredFunctionForName(name) == nil else { throw FunctionRegistrationError.FunctionAlreadyExists(name) } } registration.names.forEach { self.functionsByName[$0] = registration } } } private class FunctionRegistration { var names: Set<String> let function: FunctionEvaluator init(function: Function, caseSensitive: Bool) { self.function = function.evaluator self.names = Set(function.names.map { caseSensitive ? $0.lowercaseString : $0 }) } func addAlias(name: String) { names.insert(name) } }
mit
PerrchicK/swift-app
SomeApp/SomeApp/UI/XibViewContainer.swift
1
1223
// // XibViewContainer.swift // SomeApp // // Created by Perry on 16/01/2018. // Copyright © 2018 PerrchicK. All rights reserved. // import UIKit /// Reference: https://medium.com/zenchef-tech-and-product/how-to-visualize-reusable-xibs-in-storyboards-using-ibdesignable-c0488c7f525d class XibViewContainer: UIView { private(set) var contentView:UIView? @IBInspectable var nibName:String? override func awakeFromNib() { super.awakeFromNib() xibSetup() } func xibSetup() { guard let view = loadViewFromNib() else { return } view.frame = bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(view) contentView = view } func loadViewFromNib() -> UIView? { guard let nibName = nibName else { return nil } let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: nibName, bundle: bundle) return nib.instantiate( withOwner: self, options: nil).first as? UIView } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() xibSetup() contentView?.prepareForInterfaceBuilder() } }
apache-2.0
wangzhizhou/JokerBlog
docs/iOS/swift-on-server/code/todo/Sources/Model.swift
1
618
// // Model.swift // LoggerAPI // // Created by JokerAtBaoFeng on 2017/9/13. // import Foundation import SwiftyJSON enum ItemError: String, Error { case malformatJSON } struct Item{ let id: UUID let title: String init(json:JSON) throws { guard let d = json.dictionary, let title = d["title"]?.string else { throw ItemError.malformatJSON } self.id = UUID() self.title = title } var json: JSON { return JSON(["id": self.id.uuidString as Any, "title": self.title as Any]) } }
apache-2.0
nderkach/FlightKit
Pod/Classes/AutoCompleteTextField/AirportTextField.swift
1
16672
// // AutoCompleteTextField.swift // AutocompleteTextfieldSwift // // Created by Mylene Bayan on 6/13/15. // Copyright (c) 2015 MaiLin. All rights reserved. // import Foundation import UIKit public class AirportTextField: UITextField, UITableViewDataSource, UITableViewDelegate { let placeholderLabel = UILabel() var tintedClearImage: UIImage? /// Manages the instance of tableview private var autoCompleteTableView:UITableView? /// Holds the collection of attributed strings private var attributedAutoCompleteStrings:[NSAttributedString]? /// Handles user selection action on autocomplete table view public var onSelect:(String, NSIndexPath)->() = {_,_ in} /// Handles textfield's textchanged public var onTextChange:(String)->() = {_ in} /// Font for the text suggestions public var autoCompleteTextFont = UIFont(name: "HelveticaNeue-Light", size: 12) /// Color of the text suggestions public var autoCompleteTextColor = UIColor.blackColor() /// Used to set the height of cell for each suggestions public var autoCompleteCellHeight:CGFloat = 44.0 /// The maximum visible suggestion public var maximumAutoCompleteCount = 3 /// Used to set your own preferred separator inset public var autoCompleteSeparatorInset = UIEdgeInsetsZero /// Shows autocomplete text with formatting public var enableAttributedText = false /// User Defined Attributes public var autoCompleteAttributes:[String:AnyObject]? // Hides autocomplete tableview after selecting a suggestion public var hidesWhenSelected = true /// Hides autocomplete tableview when the textfield is empty public var hidesWhenEmpty:Bool? { didSet{ assert(hidesWhenEmpty != nil, "hideWhenEmpty cannot be set to nil") autoCompleteTableView?.hidden = hidesWhenEmpty! } } /// The table view height public var autoCompleteTableHeight:CGFloat?{ didSet{ redrawTable() } } /// The strings to be shown on as suggestions, setting the value of this automatically reload the tableview public var autoCompleteStrings:[String]?{ didSet{ reload() } } //MARK: - Init override init(frame: CGRect) { super.init(frame: frame) commonInit() setupAutocompleteTable(superview!) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } public override func awakeFromNib() { super.awakeFromNib() commonInit() setupAutocompleteTable(superview!) } override public func layoutSubviews() { super.layoutSubviews() for view in subviews { if view is UIButton { let button = view as! UIButton if let uiImage = button.imageForState(.Highlighted) { if tintedClearImage == nil { tintedClearImage = tintImage(uiImage, color: tintColor) } button.setImage(tintedClearImage, forState: .Normal) button.setImage(tintedClearImage, forState: .Highlighted) } } } } private func tintImage(image: UIImage, color: UIColor) -> UIImage { let size = image.size UIGraphicsBeginImageContextWithOptions(size, false, 2) let context = UIGraphicsGetCurrentContext() image.drawAtPoint(CGPointZero, blendMode: .Normal, alpha: 1.0) CGContextSetFillColorWithColor(context, color.CGColor) CGContextSetBlendMode(context, .SourceIn) CGContextSetAlpha(context, 1.0) let rect = CGRectMake( CGPointZero.x, CGPointZero.y, image.size.width, image.size.height) CGContextFillRect(UIGraphicsGetCurrentContext(), rect) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage } public override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) commonInit() setupAutocompleteTable(newSuperview!) if newSuperview != nil { NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldDidEndEditing", name:UITextFieldTextDidEndEditingNotification, object: self) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldDidBeginEditing", name:UITextFieldTextDidBeginEditingNotification, object: self) } else { NSNotificationCenter.defaultCenter().removeObserver(self) } } private func commonInit(){ hidesWhenEmpty = true autoCompleteAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()] autoCompleteAttributes![NSFontAttributeName] = UIFont(name: "HelveticaNeue-Bold", size: 12) self.addTarget(self, action: "textFieldDidChange", forControlEvents: .EditingChanged) textColor = tintColor } private func setupAutocompleteTable(view:UIView){ let screenSize = UIScreen.mainScreen().bounds.size let tableView = UITableView(frame: CGRectMake(self.frame.origin.x, self.frame.origin.y + CGRectGetHeight(self.frame), screenSize.width - (self.frame.origin.x * 2), 30.0)) tableView.dataSource = self tableView.delegate = self tableView.rowHeight = autoCompleteCellHeight tableView.hidden = hidesWhenEmpty ?? true tableView.backgroundColor = FlightColors.presqueWhite.colorWithAlphaComponent(0.1) tableView.scrollEnabled = false tableView.tableFooterView = UIView(frame: CGRectZero) view.addSubview(tableView) autoCompleteTableView = tableView autoCompleteTableHeight = CGFloat(maximumAutoCompleteCount) * autoCompleteCellHeight } private func redrawTable(){ if autoCompleteTableView != nil{ var newFrame = autoCompleteTableView!.frame newFrame.size.height = autoCompleteTableHeight! autoCompleteTableView!.frame = newFrame } } public func hideAutoCompleteTableView() { autoCompleteTableView?.hidden = true } //MARK: - UITableViewDataSource public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return autoCompleteStrings != nil ? (autoCompleteStrings!.count > maximumAutoCompleteCount ? maximumAutoCompleteCount : autoCompleteStrings!.count) : 0 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "autocompleteCellIdentifier" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) if cell == nil{ cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier) } cell?.backgroundColor = UIColor.clearColor() cell?.selectionStyle = .None if enableAttributedText{ cell?.textLabel?.attributedText = attributedAutoCompleteStrings![indexPath.row] } else{ cell?.textLabel?.font = autoCompleteTextFont cell?.textLabel?.textColor = autoCompleteTextColor cell?.textLabel?.text = autoCompleteStrings![indexPath.row] } return cell! } //MARK: - UITableViewDelegate public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) onSelect(cell!.textLabel!.text!, indexPath) dispatch_async(dispatch_get_main_queue(), { () -> Void in tableView.hidden = self.hidesWhenSelected }) } public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell.respondsToSelector("setSeparatorInset:"){ cell.separatorInset = autoCompleteSeparatorInset} if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:"){ cell.preservesSuperviewLayoutMargins = false} if cell.respondsToSelector("setLayoutMargins:"){ cell.layoutMargins = autoCompleteSeparatorInset} } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return autoCompleteCellHeight } //MARK: - Private Interface private func reload(){ if enableAttributedText{ let attrs = [NSForegroundColorAttributeName:autoCompleteTextColor, NSFontAttributeName:UIFont.systemFontOfSize(12.0)] if attributedAutoCompleteStrings == nil{ attributedAutoCompleteStrings = [NSAttributedString]() } else{ if attributedAutoCompleteStrings?.count > 0 { attributedAutoCompleteStrings?.removeAll(keepCapacity: false) } } if autoCompleteStrings != nil{ for i in 0..<autoCompleteStrings!.count{ let str = autoCompleteStrings![i] as NSString let range = str.rangeOfString(text!, options: .CaseInsensitiveSearch) let attString = NSMutableAttributedString(string: autoCompleteStrings![i], attributes: attrs) attString.addAttributes(autoCompleteAttributes!, range: range) attributedAutoCompleteStrings?.append(attString) } } } if let ac = autoCompleteStrings { if (ac.count < 3) { autoCompleteTableHeight = CGFloat(ac.count) * autoCompleteCellHeight } else { autoCompleteTableHeight = CGFloat(maximumAutoCompleteCount) * autoCompleteCellHeight } } else { autoCompleteTableHeight = 0 } autoCompleteTableView?.reloadData() } //MARK: - Internal func textFieldDidChange(){ if let _ = text { onTextChange(text!) } if text!.isEmpty{ autoCompleteStrings = nil } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.autoCompleteTableView?.hidden = self.hidesWhenEmpty! ? self.text!.isEmpty : false }) } public var borderInactiveColor: UIColor? { didSet { updateBorder() } } public var borderActiveColor: UIColor? { didSet { updateBorder() } } public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: (active: CGFloat, inactive: CGFloat) = (active: 2, inactive: 2) private let placeholderInsets = CGPoint(x: 0, y: 6) private let textFieldInsets = CGPoint(x: 0, y: 12) private let inactiveBorderLayer = CALayer() private let activeBorderLayer = CALayer() private var inactivePlaceholderPoint: CGPoint = CGPointZero private var activePlaceholderPoint: CGPoint = CGPointZero // MARK: - TextFieldsEffectsProtocol func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(self.font!) updateBorder() updatePlaceholder() layer.addSublayer(inactiveBorderLayer) layer.addSublayer(activeBorderLayer) addSubview(placeholderLabel) inactivePlaceholderPoint = placeholderLabel.frame.origin activePlaceholderPoint = CGPoint(x: placeholderLabel.frame.origin.x, y: placeholderLabel.frame.origin.y - placeholderLabel.frame.size.height - placeholderInsets.y) } private func updateBorder() { inactiveBorderLayer.frame = rectForBorder(borderThickness.inactive, isFill: true) inactiveBorderLayer.backgroundColor = borderInactiveColor?.CGColor activeBorderLayer.frame = rectForBorder(borderThickness.active, isFill: false) activeBorderLayer.backgroundColor = borderActiveColor?.CGColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() || !text!.isEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.65) return smallerFont } private func rectForBorder(thickness: CGFloat, isFill: Bool) -> CGRect { if isFill { return CGRect(origin: CGPoint(x: 0, y: CGRectGetHeight(frame)-thickness), size: CGSize(width: CGRectGetWidth(frame), height: thickness)) } else { return CGRect(origin: CGPoint(x: 0, y: CGRectGetHeight(frame)-thickness), size: CGSize(width: 0, height: thickness)) } } private func layoutPlaceholderInTextRect() { let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch self.textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: textRect.height/2, width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height) } func animateViewsForTextEntry() { UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ [unowned self] in if self.text!.isEmpty { self.placeholderLabel.frame.origin = CGPoint(x: 10, y: self.placeholderLabel.frame.origin.y) self.placeholderLabel.alpha = 0 } }), completion: { [unowned self] (completed) in self.layoutPlaceholderInTextRect() self.placeholderLabel.frame.origin = self.activePlaceholderPoint UIView.animateWithDuration(0.2, animations: { () -> Void in self.placeholderLabel.alpha = 0.5 }) }) self.activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFill: true) } func animateViewsForTextDisplay() { if text!.isEmpty { UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ [unowned self] in self.layoutPlaceholderInTextRect() self.placeholderLabel.alpha = 1 }), completion: nil) self.activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFill: false) } } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y) } override public func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y) } override public func prepareForInterfaceBuilder() { drawViewsForRect(frame) } // MARK: - Overrides override public func drawRect(rect: CGRect) { drawViewsForRect(rect) } override public func drawPlaceholderInRect(rect: CGRect) { // Don't draw any placeholders } public func textFieldDidBeginEditing() { animateViewsForTextEntry() } public func textFieldDidEndEditing() { animateViewsForTextDisplay() } }
mit
iampikuda/iOS-Scribbles
autolayout/autolayout/UIColor+extension.swift
1
373
// // File.swift // autolayout // // Created by Oluwadamisi Pikuda on 14/11/2017. // Copyright © 2017 Oluwadamisi Pikuda. All rights reserved. // import UIKit extension UIColor { static var activePink = UIColor(red: 232/255, green: 68/255, blue: 133/255, alpha: 1) static var inactivePink = UIColor(red: 249/255, green: 207/255, blue: 224/255, alpha: 1) }
mit
cam-hop/APIUtility
RxSwiftFluxDemo/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/WikipediaImageSearch/ViewModels/SearchResultViewModel.swift
8
1992
// // SearchResultViewModel.swift // RxExample // // Created by Krunoslav Zaher on 4/3/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class SearchResultViewModel { let searchResult: WikipediaSearchResult var title: Driver<String> var imageURLs: Driver<[URL]> let API = DefaultWikipediaAPI.sharedAPI let $: Dependencies = Dependencies.sharedDependencies init(searchResult: WikipediaSearchResult) { self.searchResult = searchResult self.title = Driver.never() self.imageURLs = Driver.never() let URLs = configureImageURLs() self.imageURLs = URLs.asDriver(onErrorJustReturn: []) self.title = configureTitle(URLs).asDriver(onErrorJustReturn: "Error during fetching") } // private methods func configureTitle(_ imageURLs: Observable<[URL]>) -> Observable<String> { let searchResult = self.searchResult let loadingValue: [URL]? = nil return imageURLs .map(Optional.init) .startWith(loadingValue) .map { URLs in if let URLs = URLs { return "\(searchResult.title) (\(URLs.count) pictures)" } else { return "\(searchResult.title) (loading…)" } } .retryOnBecomesReachable("⚠️ Service offline ⚠️", reachabilityService: $.reachabilityService) } func configureImageURLs() -> Observable<[URL]> { let searchResult = self.searchResult return API.articleContent(searchResult) .observeOn($.backgroundWorkScheduler) .map { page in do { return try parseImageURLsfromHTMLSuitableForDisplay(page.text as NSString) } catch { return [] } } .shareReplayLatestWhileConnected() } }
mit
letsspeak/Stock
Package.swift
1
1699
// swift-tools-version:4.0 import PackageDescription var packageDependencies: [Package.Dependency] = [ .package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.3.0")), .package(url: "https://github.com/vapor/leaf-provider.git", from: "1.0.0"), .package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.2.0")), .package(url: "https://github.com/vapor/mysql-provider.git", .upToNextMajor(from: "2.0.0")), .package(url: "https://github.com/DanToml/Jay.git", from: "1.0.1"), .package(url: "https://github.com/remko/swift-duktape.git", .upToNextMinor(from: "0.2.0")), .package(url: "https://github.com/kamcma/vapor-xfp-middleware", from: "1.0.0"), ] var appDependencies: [Target.Dependency] = [ "Vapor", "LeafProvider", "FluentProvider", "MySQLProvider", "Jay", "VaporXFPMiddleware", ] #if os(Linux) packageDependencies.append( Package.Dependency.package( url: "https://github.com/remko/swift-duktape.git", .upToNextMinor(from: "0.2.0"))) appDependencies.append(Target.Dependency.byName(name: "swift-duktape")) #endif let package = Package( name: "Stock", products: [ .library(name: "App", targets: ["App"]), .executable(name: "stock", targets: ["Run"]) ], dependencies: packageDependencies, targets: [ .target(name: "App", dependencies: appDependencies, exclude: [ "Config", "Public", "Resources", ]), .target(name: "Run", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App", "Testing"]) ] )
mit
PatrickSCLin/PLTimeSlider
PLTimeSliderDemo/AppDelegate.swift
1
2183
// // AppDelegate.swift // PLTimeSliderDemo // // Created by Patrick Lin on 09/12/2016. // Copyright © 2016 Patrick Lin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
stripe/stripe-ios
Stripe/STPShippingAddressViewController.swift
1
26710
// // STPShippingAddressViewController.swift // StripeiOS // // Created by Ben Guo on 8/29/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import PassKit @_spi(STP) import StripeCore @_spi(STP) import StripePaymentsUI @_spi(STP) import StripeUICore import UIKit /// This view controller contains a shipping address collection form. It renders a right bar button item that submits the form, so it must be shown inside a `UINavigationController`. Depending on your configuration's shippingType, the view controller may present a shipping method selection form after the user enters an address. public class STPShippingAddressViewController: STPCoreTableViewController { /// A convenience initializer; equivalent to calling `init(configuration: STPPaymentConfiguration.shared theme: STPTheme.defaultTheme currency:"" shippingAddress:nil selectedShippingMethod:nil prefilledInformation:nil)`. @objc public convenience init() { self.init( configuration: STPPaymentConfiguration.shared, theme: STPTheme.defaultTheme, currency: "", shippingAddress: nil, selectedShippingMethod: nil, prefilledInformation: nil ) } /// Initializes a new `STPShippingAddressViewController` with the given payment context and sets the payment context as its delegate. /// - Parameter paymentContext: The payment context to use. @objc(initWithPaymentContext:) public convenience init( paymentContext: STPPaymentContext ) { STPAnalyticsClient.sharedClient.addClass( toProductUsageIfNecessary: STPShippingAddressViewController.self ) var billingAddress: STPAddress? weak var paymentOption = paymentContext.selectedPaymentOption if paymentOption is STPCard { let card = paymentOption as? STPCard billingAddress = card?.address } else if paymentOption is STPPaymentMethod { let paymentMethod = paymentOption as? STPPaymentMethod if let billingDetails1 = paymentMethod?.billingDetails { billingAddress = STPAddress(paymentMethodBillingDetails: billingDetails1) } } var prefilledInformation: STPUserInformation? if paymentContext.prefilledInformation != nil { prefilledInformation = paymentContext.prefilledInformation } else { prefilledInformation = STPUserInformation() } prefilledInformation?.billingAddress = billingAddress self.init( configuration: paymentContext.configuration, theme: paymentContext.theme, currency: paymentContext.paymentCurrency, shippingAddress: paymentContext.shippingAddress, selectedShippingMethod: paymentContext.selectedShippingMethod, prefilledInformation: prefilledInformation ) self.delegate = paymentContext } /// Initializes a new `STPShippingAddressCardViewController` with the provided parameters. /// - Parameters: /// - configuration: The configuration to use (this determines the required shipping address fields and shipping type). - seealso: STPPaymentConfiguration /// - theme: The theme to use to inform the view controller's visual appearance. - seealso: STPTheme /// - currency: The currency to use when displaying amounts for shipping methods. The default is USD. /// - shippingAddress: If set, the shipping address view controller will be pre-filled with this address. - seealso: STPAddress /// - selectedShippingMethod: If set, the shipping methods view controller will use this method as the selected shipping method. If `selectedShippingMethod` is nil, the first shipping method in the array of methods returned by your delegate will be selected. /// - prefilledInformation: If set, the shipping address view controller will be pre-filled with this information. - seealso: STPUserInformation @objc( initWithConfiguration: theme: currency: shippingAddress: selectedShippingMethod: prefilledInformation: ) public init( configuration: STPPaymentConfiguration, theme: STPTheme, currency: String?, shippingAddress: STPAddress?, selectedShippingMethod: PKShippingMethod?, prefilledInformation: STPUserInformation? ) { STPAnalyticsClient.sharedClient.addClass( toProductUsageIfNecessary: STPShippingAddressViewController.self ) addressViewModel = STPAddressViewModel( requiredBillingFields: configuration.requiredBillingAddressFields, availableCountries: configuration.availableCountries ) super.init(theme: theme) assert( (configuration.requiredShippingAddressFields?.count ?? 0) > 0, "`requiredShippingAddressFields` must not be empty when initializing an STPShippingAddressViewController." ) self.configuration = configuration self.currency = currency self.selectedShippingMethod = selectedShippingMethod billingAddress = prefilledInformation?.billingAddress hasUsedBillingAddress = false addressViewModel = STPAddressViewModel( requiredShippingFields: configuration.requiredShippingAddressFields ?? [], availableCountries: configuration.availableCountries ) addressViewModel.delegate = self if let shippingAddress = shippingAddress { addressViewModel.address = shippingAddress } else if prefilledInformation?.shippingAddress != nil { addressViewModel.address = prefilledInformation?.shippingAddress ?? STPAddress() } title = title(for: self.configuration?.shippingType ?? .shipping) } /// The view controller's delegate. This must be set before showing the view controller in order for it to work properly. - seealso: STPShippingAddressViewControllerDelegate @objc public weak var delegate: STPShippingAddressViewControllerDelegate? /// If you're pushing `STPShippingAddressViewController` onto an existing `UINavigationController`'s stack, you should use this method to dismiss it, since it may have pushed an additional shipping method view controller onto the navigation controller's stack. /// - Parameter completion: The callback to run after the view controller is dismissed. You may specify nil for this parameter. @objc(dismissWithCompletion:) public func dismiss(withCompletion completion: STPVoidBlock?) { if stp_isAtRootOfNavigationController() { presentingViewController?.dismiss(animated: true, completion: completion ?? {}) } else { var previous = navigationController?.viewControllers.first for viewController in navigationController?.viewControllers ?? [] { if viewController == self { break } previous = viewController } navigationController?.stp_pop( to: previous, animated: true, completion: completion ?? {} ) } } /// Use one of the initializers declared in this interface. @available( *, unavailable, message: "Use one of the initializers declared in this interface instead." ) @objc public required init( theme: STPTheme? ) { let configuration = STPPaymentConfiguration.shared addressViewModel = STPAddressViewModel( requiredBillingFields: configuration.requiredBillingAddressFields, availableCountries: configuration.availableCountries ) super.init(theme: theme) } /// Use one of the initializers declared in this interface. @available( *, unavailable, message: "Use one of the initializers declared in this interface instead." ) @objc public required init( nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle? ) { let configuration = STPPaymentConfiguration.shared addressViewModel = STPAddressViewModel( requiredBillingFields: configuration.requiredBillingAddressFields, availableCountries: configuration.availableCountries ) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } /// Use one of the initializers declared in this interface. @available( *, unavailable, message: "Use one of the initializers declared in this interface instead." ) required init?( coder aDecoder: NSCoder ) { let configuration = STPPaymentConfiguration.shared addressViewModel = STPAddressViewModel( requiredBillingFields: configuration.requiredBillingAddressFields, availableCountries: configuration.availableCountries ) super.init(coder: aDecoder) } private var configuration: STPPaymentConfiguration? private var currency: String? private var selectedShippingMethod: PKShippingMethod? private weak var imageView: UIImageView? private var nextItem: UIBarButtonItem? private var _loading = false private var loading: Bool { get { _loading } set(loading) { if loading == _loading { return } _loading = loading stp_navigationItemProxy?.setHidesBackButton(loading, animated: true) stp_navigationItemProxy?.leftBarButtonItem?.isEnabled = !loading activityIndicator?.animating = loading if loading { tableView?.endEditing(true) var loadingItem: UIBarButtonItem? if let activityIndicator = activityIndicator { loadingItem = UIBarButtonItem(customView: activityIndicator) } stp_navigationItemProxy?.setRightBarButton(loadingItem, animated: true) } else { stp_navigationItemProxy?.setRightBarButton(nextItem, animated: true) } for cell in addressViewModel.addressCells { cell.isUserInteractionEnabled = !loading UIView.animate( withDuration: 0.1, animations: { cell.alpha = loading ? 0.7 : 1.0 } ) } } } private var activityIndicator: STPPaymentActivityIndicatorView? internal var addressViewModel: STPAddressViewModel private var billingAddress: STPAddress? private var hasUsedBillingAddress = false private var addressHeaderView: STPSectionHeaderView? override func createAndSetupViews() { super.createAndSetupViews() var nextItem: UIBarButtonItem? switch configuration?.shippingType { case .shipping: nextItem = UIBarButtonItem( title: STPLocalizedString("Next", "Button to move to the next text entry field"), style: .done, target: self, action: #selector(next(_:)) ) case .delivery, .none, .some: nextItem = UIBarButtonItem( barButtonSystemItem: .done, target: self, action: #selector(next(_:)) ) } self.nextItem = nextItem stp_navigationItemProxy?.rightBarButtonItem = nextItem stp_navigationItemProxy?.rightBarButtonItem?.isEnabled = false stp_navigationItemProxy?.rightBarButtonItem?.accessibilityIdentifier = "ShippingViewControllerNextButtonIdentifier" let imageView = UIImageView(image: STPLegacyImageLibrary.largeShippingImage()) imageView.contentMode = .center imageView.frame = CGRect( x: 0, y: 0, width: view.bounds.size.width, height: imageView.bounds.size.height + (57 * 2) ) self.imageView = imageView tableView?.tableHeaderView = imageView activityIndicator = STPPaymentActivityIndicatorView( frame: CGRect(x: 0, y: 0, width: 20.0, height: 20.0) ) tableView?.dataSource = self tableView?.delegate = self tableView?.reloadData() view.addGestureRecognizer( UITapGestureRecognizer( target: self, action: #selector(NSMutableAttributedString.endEditing) ) ) let headerView = STPSectionHeaderView() headerView.theme = theme if let shippingType1 = configuration?.shippingType { headerView.title = headerTitle(for: shippingType1) } headerView.button?.setTitle( STPLocalizedString( "Use Billing", "Button to fill shipping address from billing address." ), for: .normal ) headerView.button?.addTarget( self, action: #selector(useBillingAddress(_:)), for: .touchUpInside ) headerView.button?.accessibilityIdentifier = "ShippingAddressViewControllerUseBillingButton" var buttonVisible = false if let requiredFields = configuration?.requiredShippingAddressFields { let needsAddress = requiredFields.contains(.postalAddress) && !(addressViewModel.isValid) buttonVisible = needsAddress && billingAddress?.containsContent(forShippingAddressFields: requiredFields) ?? false && !hasUsedBillingAddress } headerView.button?.alpha = buttonVisible ? 1 : 0 headerView.setNeedsLayout() addressHeaderView = headerView updateDoneButton() } @objc func endEditing() { view.endEditing(false) } @objc override func updateAppearance() { super.updateAppearance() let navBarTheme = navigationController?.navigationBar.stp_theme ?? theme nextItem?.stp_setTheme(navBarTheme) tableView?.allowsSelection = false imageView?.tintColor = theme.accentColor activityIndicator?.tintColor = theme.accentColor for cell in addressViewModel.addressCells { cell.theme = theme } addressHeaderView?.theme = theme } /// :nodoc: @objc public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) stp_beginObservingKeyboardAndInsettingScrollView( tableView, onChange: nil ) firstEmptyField()?.becomeFirstResponder() } func firstEmptyField() -> UIResponder? { for cell in addressViewModel.addressCells { if (cell.contents?.count ?? 0) == 0 { return cell } } return nil } @objc override func handleCancelTapped(_ sender: Any?) { delegate?.shippingAddressViewControllerDidCancel(self) } @objc func next(_ sender: Any?) { let address = addressViewModel.address switch configuration?.shippingType { case .shipping: loading = true delegate?.shippingAddressViewController(self, didEnter: address) { status, shippingValidationError, shippingMethods, selectedShippingMethod in self.loading = false if status == .valid { if (shippingMethods?.count ?? 0) > 0 { var nextViewController: STPShippingMethodsViewController? if let shippingMethods = shippingMethods, let selectedShippingMethod = selectedShippingMethod { nextViewController = STPShippingMethodsViewController( shippingMethods: shippingMethods, selectedShippingMethod: selectedShippingMethod, currency: self.currency ?? "", theme: self.theme ) } nextViewController?.delegate = self if let nextViewController = nextViewController { self.navigationController?.pushViewController( nextViewController, animated: true ) } } else { self.delegate?.shippingAddressViewController( self, didFinishWith: address, shippingMethod: nil ) } } else { self.handleShippingValidationError(shippingValidationError) } } case .delivery, .none, .some: delegate?.shippingAddressViewController( self, didFinishWith: address, shippingMethod: nil ) } } func updateDoneButton() { stp_navigationItemProxy?.rightBarButtonItem?.isEnabled = addressViewModel.isValid } func handleShippingValidationError(_ error: Error?) { firstEmptyField()?.becomeFirstResponder() var title = STPLocalizedString("Invalid Shipping Address", "Shipping form error message") var message: String? if let error = error { title = error.localizedDescription message = (error as NSError).localizedFailureReason } let alertController = UIAlertController( title: title, message: message, preferredStyle: .alert ) alertController.addAction( UIAlertAction( title: String.Localized.ok, style: .cancel, handler: nil ) ) present(alertController, animated: true) } /// :nodoc: @objc public override func tableView( _ tableView: UITableView, heightForHeaderInSection section: Int ) -> CGFloat { let size = addressHeaderView?.sizeThatFits( CGSize(width: view.bounds.size.width, height: CGFloat.greatestFiniteMagnitude) ) return size?.height ?? 0.0 } @objc func useBillingAddress(_ sender: UIButton) { guard let billingAddress = billingAddress else { return } tableView?.beginUpdates() addressViewModel.address = billingAddress hasUsedBillingAddress = true firstEmptyField()?.becomeFirstResponder() UIView.animate( withDuration: 0.2, animations: { self.addressHeaderView?.buttonHidden = true } ) tableView?.endUpdates() } func title(for type: STPShippingType) -> String { if let shippingAddressFields = configuration?.requiredShippingAddressFields, shippingAddressFields.contains(.postalAddress) { switch type { case .shipping: return STPLocalizedString("Shipping", "Title for shipping info form") case .delivery: return STPLocalizedString("Delivery", "Title for delivery info form") } } else { return STPLocalizedString("Contact", "Title for contact info form") } } func headerTitle(for type: STPShippingType) -> String { if let shippingAddressFields = configuration?.requiredShippingAddressFields, shippingAddressFields.contains(.postalAddress) { switch type { case .shipping: return String.Localized.shipping_address case .delivery: return STPLocalizedString( "Delivery Address", "Title for delivery address entry section" ) } } else { return STPLocalizedString("Contact", "Title for contact info form") } } } /// An `STPShippingAddressViewControllerDelegate` is notified when an `STPShippingAddressViewController` receives an address, completes with an address, or is cancelled. @objc public protocol STPShippingAddressViewControllerDelegate: NSObjectProtocol { /// Called when the user cancels entering a shipping address. You should dismiss (or pop) the view controller at this point. /// - Parameter addressViewController: the view controller that has been cancelled func shippingAddressViewControllerDidCancel( _ addressViewController: STPShippingAddressViewController ) /// This is called when the user enters a shipping address and taps next. You /// should validate the address and determine what shipping methods are available, /// and call the `completion` block when finished. If an error occurrs, call /// the `completion` block with the error. Otherwise, call the `completion` /// block with a nil error and an array of available shipping methods. If you don't /// need to collect a shipping method, you may pass an empty array or nil. /// - Parameters: /// - addressViewController: the view controller where the address was entered /// - address: the address that was entered. - seealso: STPAddress /// - completion: call this callback when you're done validating the address and determining available shipping methods. @objc(shippingAddressViewController:didEnterAddress:completion:) func shippingAddressViewController( _ addressViewController: STPShippingAddressViewController, didEnter address: STPAddress, completion: @escaping STPShippingMethodsCompletionBlock ) /// This is called when the user selects a shipping method. If no shipping methods are given, or if the shipping type doesn't require a shipping method, this will be called after the user has a shipping address and your validation has succeeded. After updating your app with the user's shipping info, you should dismiss (or pop) the view controller. Note that if `shippingMethod` is non-nil, there will be an additional shipping methods view controller on the navigation controller's stack. /// - Parameters: /// - addressViewController: the view controller where the address was entered /// - address: the address that was entered. - seealso: STPAddress /// - method: the shipping method that was selected. @objc(shippingAddressViewController:didFinishWithAddress:shippingMethod:) func shippingAddressViewController( _ addressViewController: STPShippingAddressViewController, didFinishWith address: STPAddress, shippingMethod method: PKShippingMethod? ) } extension STPShippingAddressViewController: STPAddressViewModelDelegate, UITableViewDelegate, UITableViewDataSource, STPShippingMethodsViewControllerDelegate { // MARK: - UITableView /// :nodoc: @objc public func numberOfSections(in tableView: UITableView) -> Int { return 1 } /// :nodoc: @objc public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return addressViewModel.addressCells.count } /// :nodoc: @objc public func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell { let cell = addressViewModel.addressCells.stp_boundSafeObject(at: indexPath.row) cell?.backgroundColor = theme.secondaryBackgroundColor cell?.contentView.backgroundColor = UIColor.clear return cell! } /// :nodoc: @objc public func tableView( _ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath ) { let topRow = indexPath.row == 0 let bottomRow = tableView.numberOfRows(inSection: indexPath.section) - 1 == indexPath.row cell.stp_setBorderColor(theme.tertiaryBackgroundColor) cell.stp_setTopBorderHidden(!topRow) cell.stp_setBottomBorderHidden(!bottomRow) cell.stp_setFakeSeparatorColor(theme.quaternaryBackgroundColor) cell.stp_setFakeSeparatorLeftInset(15.0) } /// :nodoc: @objc public func tableView( _ tableView: UITableView, heightForFooterInSection section: Int ) -> CGFloat { return 0.01 } /// :nodoc: @objc public func tableView( _ tableView: UITableView, viewForFooterInSection section: Int ) -> UIView? { return UIView() } /// :nodoc: @objc public func tableView( _ tableView: UITableView, viewForHeaderInSection section: Int ) -> UIView? { return addressHeaderView } // MARK: - STPShippingMethodsViewControllerDelegate func shippingMethodsViewController( _ methodsViewController: STPShippingMethodsViewController, didFinishWith method: PKShippingMethod ) { delegate?.shippingAddressViewController( self, didFinishWith: addressViewModel.address, shippingMethod: method ) } // MARK: - STPAddressViewModelDelegate func addressViewModel(_ addressViewModel: STPAddressViewModel, addedCellAt index: Int) { let indexPath = IndexPath(row: index, section: 0) tableView?.insertRows(at: [indexPath], with: .automatic) } func addressViewModel(_ addressViewModel: STPAddressViewModel, removedCellAt index: Int) { let indexPath = IndexPath(row: index, section: 0) tableView?.deleteRows(at: [indexPath], with: .automatic) } func addressViewModelDidChange(_ addressViewModel: STPAddressViewModel) { updateDoneButton() } func addressViewModelWillUpdate(_ addressViewModel: STPAddressViewModel) { tableView?.beginUpdates() } func addressViewModelDidUpdate(_ addressViewModel: STPAddressViewModel) { tableView?.endUpdates() } } /// :nodoc: @_spi(STP) extension STPShippingAddressViewController: STPAnalyticsProtocol { @_spi(STP) public static var stp_analyticsIdentifier = "STPShippingAddressViewController" }
mit
q231950/road-to-bishkek
Bish/Cities/CitySelectionViewController.swift
1
4585
// // CitySelectionViewController.swift // Bish // // Created by Martin Kim Dung-Pham on 02.07.17. // Copyright © 2017 elbedev.com. All rights reserved. // import UIKit import CoreData import CloudKit class CitySelectionViewController: UITableViewController { public var selectedCity: City? private var filteredCities = [City]() private let cloud = CityCloud() private var searchTermChanged = false private var searchTerm: String? private var updateTimer: Timer! private var cursor: CKQueryCursor? override func viewDidLoad() { super.viewDidLoad() setupTitle() setupSearchController() } private func setupTitle() { navigationController?.navigationBar.prefersLargeTitles = true title = "City Selection" } private func setupSearchController() { navigationItem.searchController = UISearchController(searchResultsController: nil) navigationItem.searchController?.searchResultsUpdater = self navigationItem.searchController?.dimsBackgroundDuringPresentation = false navigationItem.hidesSearchBarWhenScrolling = false navigationItem.searchController?.searchBar.delegate = self definesPresentationContext = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupTimer() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) updateTimer.invalidate() } private func setupTimer() { updateTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true, block: { [weak self] (_) in self?.updateResults(cursor: self?.cursor) }) } } extension CitySelectionViewController: UISearchResultsUpdating { func loadMore() { searchTermChanged = true updateResults(cursor: cursor) } func updateSearchResults(for searchController: UISearchController) { guard let name = searchController.searchBar.text, name.count > 0 else { return } searchTerm = name searchTermChanged = true } private func updateResults(cursor: CKQueryCursor?) { guard let name = searchTerm, searchTermChanged == true else { return } searchTermChanged = false var newCursor: CKQueryCursor? if cursor == nil { filteredCities.removeAll() DispatchQueue.main.async { self.tableView.reloadData() } } else { newCursor = cursor self.cursor = nil } self.cloud.citiesNamed(name, cursor: newCursor, completion: { (city, error) in if let city = city { self.filteredCities.append(city) } DispatchQueue.main.async { self.tableView.reloadData() } }, next: { (cursor) in self.cursor = cursor }) } } extension CitySelectionViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cityCell", for: indexPath) let city = filteredCities[indexPath.row] cell.textLabel?.text = city.name cell.detailTextLabel?.text = city.countryCode if let selectedCity = selectedCity { cell.accessoryType = selectedCity == city ? .checkmark : .none } if indexPath.row == filteredCities.count - 1 && cursor != nil { loadMore() } return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredCities.count } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let city = filteredCities[indexPath.row] selectedCity = city do { try DataStore.shared.deselectAllCities() try DataStore.shared.select(city) DataStore.shared.saveContext() } catch { } DispatchQueue.main.async { self.navigationItem.searchController?.isActive = false self.tableView.reloadData() } } } extension CitySelectionViewController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { self.cursor = nil } }
mit