repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
solszl/Shrimp500px
refs/heads/master
Shrimp500px/ViewControllers/My/OAuth/WebViewController.swift
mit
1
// // OAuthWebViewController.swift // Shrimp500px // // Created by 振亮 孙 on 16/2/29. // Copyright © 2016年 papa.studio. All rights reserved. // import OAuthSwift import UIKit let oauthswift = OAuth1Swift( consumerKey: CustomKey, consumerSecret: CustomSecret, requestTokenUrl: "https://api.500px.com/v1/oauth/request_token", authorizeUrl:"https://api.500px.com/v1/oauth/authorize", accessTokenUrl:"https://api.500px.com/v1/oauth/access_token" ) /// 登陆界面,进行OAuth验证 <li/>网页.这样可以不跳转到safari class WebViewController: OAuthWebViewController { var targetURL : NSURL = NSURL() // web 容器 let webView = UIWebView() override func viewDidLoad() { super.viewDidLoad() // 根据web容器大小对网页是否进行缩放 self.webView.scalesPageToFit = true // 设置webview的代理 self.webView.delegate = self self.webView.frame = ScreenBounds self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(cancel)) let url = NSBundle.mainBundle().URLForResource("about", withExtension:"html") let myRequest = NSURLRequest(URL: url!); webView.loadRequest(myRequest); self.view.addSubview(self.webView) } override func handle(url: NSURL) { self.targetURL = url super.handle(url) loadAddress() } func loadAddress() { let req = NSURLRequest(URL: self.targetURL) // 请求登陆 self.webView.loadRequest(req) } func cancel() { dismissViewControllerAnimated(true, completion: nil) } } extension WebViewController: UIWebViewDelegate { func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let url = request.URL where (url.scheme == "shrimp500px"){ self.dismissWebViewController() } return true } }
da757a020cc1cea2aebff340b0e6e9da
27.366197
137
0.644489
false
false
false
false
heshamsalman/OctoViewer
refs/heads/master
OctoViewerTests/LoginCoordinatorSpec.swift
apache-2.0
1
// // LoginCoordinatorSpec.swift // OctoViewer // // Created by Hesham Salman on 5/26/17. // Copyright © 2017 Hesham Salman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import Quick import Nimble @testable import OctoViewer class LoginCoordinatorSpec: QuickSpec { override func spec() { var coordinator: LoginCoordinator! var app: MockUIApplication! var vc: MockUIViewController! beforeEach { vc = MockUIViewController() app = MockUIApplication() coordinator = LoginCoordinator(navigationController: nil) coordinator.application = app app.keyWindow?.rootViewController = vc app.keyWindow?.makeKeyAndVisible() } it("presents a view on the application") { coordinator.start() expect(vc.presentedController).toNot(beNil()) expect(vc.didPresent).to(beTruthy()) } it("presents a view on the application, alternate call") { coordinator.presentLoginViewController() expect(vc.presentedController).toNot(beNil()) expect(vc.didPresent).to(beTruthy()) } describe("Generic coordinator functionality") { it("can add and remove a child") { let secondaryCoordinator = AppCoordinator() coordinator.addChild(coordinator: secondaryCoordinator) expect(coordinator.childCoordinators.contains(where: { $0 === secondaryCoordinator })).to(beTruthy()) coordinator.removeChild(coordinator: secondaryCoordinator) expect(coordinator.childCoordinators.contains(where: { $0 === secondaryCoordinator })).to(beFalsy()) } it("doesn't blow up trying to remove something that doesn't exit") { let secondaryCoordinator = AppCoordinator() coordinator.removeChild(coordinator: secondaryCoordinator) } } } }
2b18258b07ce37d1ce350ea59c4f98d3
31.263889
109
0.705553
false
false
false
false
scotlandyard/expocity
refs/heads/master
expocity/Controller/Main/CController.swift
mit
1
import UIKit class CController:UIViewController { weak var layoutLeft:NSLayoutConstraint! weak var layoutRight:NSLayoutConstraint! weak var shadow:VMainShadow? override var title:String? { didSet { parentController.viewParent.bar.label.text = title } } override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge() extendedLayoutIncludesOpaqueBars = false automaticallyAdjustsScrollViewInsets = false } override var preferredStatusBarStyle:UIStatusBarStyle { return UIStatusBarStyle.lightContent } override var prefersStatusBarHidden:Bool { return false } //MARK: public func addShadow() { let shadow:VMainShadow = VMainShadow() self.shadow = shadow view.addSubview(shadow) let views:[String:UIView] = [ "shadow":shadow] let metrics:[String:CGFloat] = [:] view.addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[shadow]-0-|", options:[], metrics:metrics, views:views)) view.addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[shadow]-0-|", options:[], metrics:metrics, views:views)) view.layoutIfNeeded() } }
9ab556e3df093098e3651a79b634ef32
22.698413
62
0.575352
false
false
false
false
curiousurick/Rye
refs/heads/master
Login/LogViewController.swift
mit
1
// // LoginViewController.swift // Login // // Created by Jason Kwok on 2/7/15. // Copyright (c) 2015 Jason Kwok. All rights reserved. // import UIKit import Parse class LogViewController: UIViewController, UITextFieldDelegate { @IBOutlet var loginButton: UIButton! @IBOutlet var cancelButton: UIButton! @IBOutlet var facebookButton: UIButton! @IBOutlet var signupButton: UIButton! @IBOutlet weak var Email: UITextField! @IBOutlet weak var Password: UITextField! func checkInput() -> Bool{ var u = setUsername(Email.text) var p = setPassword(Password.text) var ErrorAlert: UIAlertView = UIAlertView() var isGood: Bool if u == "Good" && p == "Good" { isGood = true } else { if u == "Bad" { ErrorAlert.title = "Invalid Email! 😫" ErrorAlert.message = "Please enter a valid email address" isGood = false } else if p == "Short" { ErrorAlert.title = "Too Short! 😫" ErrorAlert.message = "Password requires 8 or more characters." isGood = false } else if p == "Letters" { ErrorAlert.title = "No Letters! 😫" ErrorAlert.message = "Password requires a letter." isGood = false } else if p == "Numbers" { ErrorAlert.title = "No Numbers! 😫" ErrorAlert.message = "Password requires a number." isGood = false } else { ErrorAlert.title = "I have no idea what happened" ErrorAlert.message = "I guess try again?" isGood = false } ErrorAlert.delegate = self ErrorAlert.addButtonWithTitle("OK") ErrorAlert.show() } return isGood } @IBAction func loginButtonClicked(sender: AnyObject) { PFUser.logInWithUsernameInBackground(Email.text, password:Password.text) { (user: PFUser!, error: NSError!) -> Void in if user != nil { let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) // NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") } else { // The login failed. Check error to see why. } } } @IBAction func facebookButtonClicked(sender: AnyObject) { var permissions = ["email"] PFFacebookUtils.logInWithPermissions(permissions, { (user: PFUser!, error: NSError!) -> Void in if user == nil { NSLog("Uh oh. The user cancelled the Facebook login.") } else if user.isNew { NSLog("User signed up and logged in through Facebook!") let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) // NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") } else { NSLog("User logged in through Facebook!") let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) //NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") } }) } @IBAction func signupButtonClicked(sender: AnyObject) { var user = PFUser() if(checkInput()) { user.username = Email.text user.password = Password.text user.email = Email.text // other fields can be set just like with PFObject var ErrorAlert: UIAlertView = UIAlertView() user.signUpInBackgroundWithBlock { (succeeded: Bool!, error: NSError!) -> Void in if error == nil { let viewContoler = self.storyboard?.instantiateViewControllerWithIdentifier("TabBar") as UITabBarController self.presentViewController(viewContoler, animated: true, completion: nil) // NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loggedIn") //self.performSegueWithIdentifier("main", sender: nil) // Hooray! Let them use the app now. } else { ErrorAlert.title = "You already have an account!" ErrorAlert.message = "Try signing in!" // Show the errorString somewhere and let the user try again. ErrorAlert.delegate = self ErrorAlert.addButtonWithTitle("OK") ErrorAlert.show() } } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } func setUsername(newValue: String) -> String { var hasAt: Bool = false var hasDot: Bool = false for letter in newValue { if letter == "@" { hasAt = true } if letter == "." { hasDot = true } } if hasAt && hasDot { return "Good" } else { return "Bad" } } func addDoneButtonOnKeyboard() { var doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50)) doneToolbar.barStyle = UIBarStyle.BlackTranslucent var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction")) var items = NSMutableArray() items.addObject(flexSpace) items.addObject(done) doneToolbar.items = items doneToolbar.sizeToFit() self.Email.inputAccessoryView = doneToolbar self.Password.inputAccessoryView = doneToolbar } func doneButtonAction() { self.view.endEditing(true) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.view.endEditing(true) } func setPassword(newValue: String) -> String { let letters = NSCharacterSet.letterCharacterSet() let digits = NSCharacterSet.decimalDigitCharacterSet() //Password Constraint Variables var hasLetters: Bool = false var hasNumb: Bool = false let length = countElements(newValue) //Check Password Constraints for letter in newValue.unicodeScalars { if letters.longCharacterIsMember(letter.value) { hasLetters = true } if digits.longCharacterIsMember(letter.value) { hasNumb = true } } if length >= 8 && hasLetters && hasNumb { return "Good" } else if length < 8 { return "Short" } else if !hasLetters { return "Letters" } else { return "Numbers" } } override func viewDidLoad() { super.viewDidLoad() Email.delegate = self Password.delegate = self loginButton.layer.masksToBounds = true loginButton.layer.cornerRadius = 10 cancelButton.layer.masksToBounds = true cancelButton.layer.cornerRadius = 10 facebookButton.layer.masksToBounds = true facebookButton.layer.cornerRadius = 10 signupButton.layer.masksToBounds = true signupButton.layer.cornerRadius = 10 addDoneButtonOnKeyboard() // Do any additional setup after loading the view. } func loginViewShowingLoggedInUser(loginView: FBLoginView!) { } func loginViewFetchedUserInfo(loginView: FBLoginView!, user: FBGraphUser!) { } func loginViewShowingLoggedOutUser(loginView: FBLoginView!) { } func loginView(loginView: FBLoginView!, handleError error: NSError!) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { if(textField == self.Email) { self.Password.becomeFirstResponder() } else if(textField == self.Password) { self.loginButtonClicked(loginButton) } return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
bde37128d0baf2be1e885fdfd65f43ed
31.979381
152
0.563509
false
false
false
false
embryoconcepts/TIY-Assignments
refs/heads/master
19 -- Forecaster/Forecaster/Forecaster/Weather.swift
cc0-1.0
1
// // Weather.swift // Forecaster // // Created by Jennifer Hamilton on 10/29/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation struct Weather { let location: [String: Double] let latitude: Double let longitude: Double let summary: String let icon: String let precipProbability: Double let precipIntensity: Double let temperature: Double let apparentTemperature: Double let dewpoint: Double let humidity: Double // let windSpeed: Double // let windBearing: Double // let visibility: Double // let cloudCover: Double let pressure: Double init(latitude: Double, longitude: Double, summary: String, icon: String, temperature: Double, precipProb: Double, precipIntensity: Double, apparentTemp: Double, dewpoint: Double, humidity: Double, pressure: Double) { self.latitude = latitude self.longitude = longitude self.location = ["lat": latitude, "lng": longitude] self.summary = summary self.icon = icon self.precipProbability = precipProb self.precipIntensity = precipIntensity self.temperature = temperature self.apparentTemperature = apparentTemp self.dewpoint = dewpoint self.humidity = humidity self.pressure = pressure } static func weatherWithJSON(weatherDictionaryResults: NSDictionary) -> Weather { var weather: Weather! let currentWeatherDictionary = weatherDictionaryResults.valueForKey("currently") if currentWeatherDictionary!.count > 0 { // let name = currentWeatherDictionary!.valueForKey("name") as? String ?? "" let latitude = weatherDictionaryResults.valueForKey("latitude") as! Double let longitude = weatherDictionaryResults.valueForKey("longitude") as! Double let summary = currentWeatherDictionary!.valueForKey("summary") as! String let icon = currentWeatherDictionary!.valueForKey("icon") as! String let precipProbability = currentWeatherDictionary!.valueForKey("precipProbability") as! Double let precipIntensity = currentWeatherDictionary!.valueForKey("precipIntensity") as! Double let temperature = currentWeatherDictionary!.valueForKey("temperature") as! Double let apparentTemperature = currentWeatherDictionary!.valueForKey("apparentTemperature") as! Double let dewpoint = currentWeatherDictionary!.valueForKey("dewPoint") as! Double let humidity = currentWeatherDictionary!.valueForKey("humidity") as! Double let pressure = currentWeatherDictionary!.valueForKey("pressure") as! Double weather = Weather(latitude: latitude, longitude: longitude, summary: summary, icon: icon, temperature: temperature, precipProb: precipProbability, precipIntensity: precipIntensity, apparentTemp: apparentTemperature, dewpoint: dewpoint, humidity: humidity, pressure: pressure) } return weather } }
d573decc2012194f066f48445943fbcb
40.053333
287
0.687561
false
false
false
false
lntotherain/huacaizhibo
refs/heads/master
huacaizhibo/huacaizhibo/Classes/Tools/UIBarButtonItem+Extention.swift
apache-2.0
1
// // UIBarButtonItem+Extention.swift // huacaizhibo // // Created by mac on 2016/10/29. // Copyright © 2016年 julia. All rights reserved. // import UIKit extension UIBarButtonItem { /* class func creatItem(imgname: String,highLightImgName: String, size:CGSize) -> UIBarButtonItem{ let img = UIImage(named: imgname) let imgHighLight = UIImage(named: highLightImgName) let btn = UIButton() btn.frame = CGRect(origin: CGPoint.zero, size: size) btn.setImage(img, for: .normal) btn.setImage(imgHighLight, for: .highlighted) let barButtonItem = UIBarButtonItem(customView: btn) return barButtonItem } */ //便利构造函数 convenience init(imgname: String,highLightImgName: String = "", size:CGSize = CGSize.zero) { let img = UIImage(named: imgname) let btn = UIButton() btn.setImage(img, for: .normal) if highLightImgName != "" { let imgHighLight = UIImage(named: highLightImgName) btn.setImage(imgHighLight, for: .highlighted) } if size != CGSize.zero { btn.frame = CGRect(origin: CGPoint.zero, size: size) } self.init(customView: btn) } }
d53008de81ab24bbe21a3579a53e5906
25.309091
101
0.530062
false
false
false
false
IAskWind/IAWExtensionTool
refs/heads/master
Pods/Easy/Easy/Classes/Core/EasyListView.swift
mit
1
// // EasyListView.swift // Easy // // Created by OctMon on 2018/11/8. // import UIKit public extension Easy { typealias ListView = EasyListView } open class EasyListView: UIView { deinit { EasyLog.debug(toDeinit) } /// 第一页 public lazy var firstPage: Int = EasyGlobal.listViewFirstPage /// 当前页 public lazy var currentPage: Int = EasyGlobal.listViewCurrentPage /// 分页数量 public lazy var pageSize: Int? = EasyGlobal.listViewPageSize /// 大于等于多少条数据提示没有更多的数据 public lazy var noMoreDataSize: Int = EasyGlobal.listViewNoMoreDataSize /// 下一页增量(跳过的页数) public lazy var incrementPage: Int = EasyGlobal.listViewIncrementPage /// 自动判断总页数 public lazy var autoTotalPage: Bool = EasyGlobal.listViewAutoTotalPage /// 忽略总页数判断 public lazy var ignoreTotalPage: Bool = EasyGlobal.listViewIgnoreTotalPage public var tableViewBackgroundColor: UIColor = EasyGlobal.tableViewBackgroundColor public var collectionViewBackgroundColor: UIColor = EasyGlobal.collectionViewBackgroundColor open lazy var model: Any? = nil open lazy var list: [Any] = [Any]() lazy var requestHandler: (() -> Void)? = { return nil }() open func configure() { } public func model<T>(_ class: T.Type) -> T? { return model as? T ?? nil } public func listTo<T>(_ class: T.Type) -> [T] { return list as? [T] ?? [] } public func list<T>(_ class: T.Type) -> [T]? { return list as? [T] } public var placeholders: [EasyPlaceholder]? public var placeholderBackgroundColor: UIColor = EasyGlobal.placeholderBackgroundColor, placeholderOffset: CGFloat = 0, placeholderBringSubviews: [UIView]? = nil public var placeholderIsUserInteractionEnabled: Bool = EasyGlobal.placeholderIsUserInteractionEnabled func getAny<T>(_ dataSource: [Any], indexPath: IndexPath, numberOfSections: Int, numberOfRowsInSectionHandler: ((T, Int) -> Int)?) -> Any? { if let model = model { return model } var rowsInSection = 0 if let `self` = self as? T, let rows = numberOfRowsInSectionHandler?(self, indexPath.section) { rowsInSection = rows } if numberOfSections == 1 && rowsInSection < 1 { if let row = dataSource[indexPath.section] as? [Any], indexPath.section < dataSource.count { return row[indexPath.row] } if indexPath.row < dataSource.count { return dataSource[indexPath.row] } } else if numberOfSections > 0 { if indexPath.section < dataSource.count { if let any = dataSource[indexPath.section] as? [Any] { if indexPath.row < any.count { return any[indexPath.row] } } else if rowsInSection > 0 && numberOfSections == dataSource.count { return dataSource[indexPath.section] } else if indexPath.row < dataSource.count { return dataSource[indexPath.row] } } } else if indexPath.row < dataSource.count { return dataSource[indexPath.row] } return nil } } public extension EasyListView { func requestFirst() { currentPage = firstPage requestHandler?() } func addPlaceholder(_ placeholder: EasyPlaceholder) { var existing = placeholders ?? [] existing.append(placeholder) placeholders = existing } func addPlaceholders(_ placeholder: [EasyPlaceholder]) { var existing = placeholders ?? [] existing.append(contentsOf: placeholder) placeholders = existing } }
433d4e0c1c8e68178935cd5c819dc85e
30.891667
165
0.609093
false
false
false
false
el-hoshino/NotAutoLayout
refs/heads/master
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/RightTopHeight.Individual.swift
apache-2.0
1
// // RightTopHeight.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct RightTopHeight { let right: LayoutElement.Horizontal let top: LayoutElement.Vertical let height: LayoutElement.Length } } // MARK: - Make Frame extension IndividualProperty.RightTopHeight { private func makeFrame(right: Float, top: Float, height: Float, width: Float) -> Rect { let x = right - width let y = top let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Width extension IndividualProperty.RightTopHeight: LayoutPropertyCanStoreWidthToEvaluateFrameType { public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let right = self.right.evaluated(from: parameters) let top = self.top.evaluated(from: parameters) let height = self.height.evaluated(from: parameters, withTheOtherAxis: .width(0)) let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height)) return self.makeFrame(right: right, top: top, height: height, width: width) } }
0415ff7d32c6bc5dc0f4aa6e48cdf776
21.963636
115
0.718923
false
false
false
false
rockgarden/swift_language
refs/heads/swift3
Playground/2015-10-MapFlatMapPlayground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play // // See original post at http://www.uraimo.com/2015/10/07/Swift2-map-flatmap-demystified import UIKit /////////////////////////////////////// // MAP // .map optionals var o1:Int? = nil var o1m = o1.map({$0 * 2}) o1m /* Int? with content nil */ o1 = 1 o1m = o1.map({$0 * 2}) o1m /* Int? with content 2 */ var os1m = o1.map({ (value) -> String in String(value * 2) }) os1m /* String? with content "2" */ os1m = o1.map({ (value) -> String in String(value * 2) }).map({"number "+$0}) os1m /* String? with content "number 2" */ // .map SequenceType: Array var a1 = [1,2,3,4,5,6] var a1m = a1.map({$0 * 2}) a1m /*[Int] with content [2, 4, 6, 8, 10, 12] */ var ao1:[Int?] = [1,2,3,4,5,6] var ao1m = ao1.map({$0! * 2}) ao1m /*[Int] with content [2, 4, 6, 8, 10, 12] */ var a1ms = a1.map({ (value) -> String in String(value * 2) }).map { (stringValue) -> Int? in Int(stringValue) } a1ms /*[Int?] with content [{Some 2}, {Some 4}, {Some 6}, {Some 8}, {Some 10}, {Some 12}] */ // .map Additional examples var s1:String? = "1" var i1 = s1.map { Int($0) } i1 /* Int?? with content 1 */ var ar1 = ["1","2","3","a"] var ar1m = ar1.map { Int($0) } ar1m /* [Int?] with content [{Some 1}, {Some 2}, {Some 3}, nil] */ ar1m = ar1.map { Int($0) } .filter({$0 != nil}) .map {$0! * 2} ar1m /* [Int?] with content [{Some 2}, {Some 4}, {Some 6}] */ /////////////////////////////////////// // FLATMAP // .flatMap optionals var fo1:Int? = nil var fo1m = fo1.flatMap({$0 * 2}) fo1m /* Int? with content nil */ fo1 = 1 fo1m = fo1.flatMap({$0 * 2}) fo1m /* Int? with content 2 */ var fos1m = fo1.flatMap({ (value) -> String? in String(value * 2) }) fos1m /* String? with content "2" */ var fs1:String? = "1" var fi1 = fs1.flatMap { Int($0) } fi1 /* Int? with content "1" */ var fi2 = fs1.flatMap { Int($0) }.map {$0*2} fi2 /* Int? with content "2" */ // .flatMap SequenceTypes var fa1 = [1,2,3,4,5,6] var fa1m = fa1.flatMap({$0 * 2}) fa1m /*[Int] with content [2, 4, 6, 8, 10, 12] */ var fao1:[Int?] = [1,2,3,4,nil,6] var fao1m = fao1.flatMap({$0}) fao1m /*[Int] with content [1, 2, 3, 4, 6] */ var fa2 = [[1,2],[3],[4,5,6]] var fa2m = fa2.flatMap({$0}) fa2m /*[Int] with content [1, 2, 3, 4, 6] */ // .map Additional examples Revisited var far1 = ["1","2","3","a"] var far1m = far1.flatMap { Int($0) } far1m /* [Int] with content [1, 2, 3] */ far1m = far1.flatMap { Int($0) } .map {$0 * 2} far1m /* [Int] with content [2, 4, 6] */
7e5efaeade6ebfa3edb6ab70fcb830c5
17.055944
92
0.530984
false
false
false
false
MoooveOn/Advanced-Frameworks
refs/heads/master
SideMenu/SideMenu/SideMenu/SideMenu.swift
mit
1
// // SideMenu.swift // SideMenu // // Created by Pavel Selivanov on 03.07.17. // Copyright © 2017 Pavel Selivanov. All rights reserved. // import UIKit protocol SideMenuDelegate { func didSelectMenuItem(withTitle title: String, index: Int) } class SideMenu: UIView, UITableViewDelegate, UITableViewDataSource { var backgroundView: UIView! var menuTable: UITableView! var animator: UIDynamicAnimator! var menuWidth: CGFloat = 0 var menuItemTitles = [String]() var menuDelegate: SideMenuDelegate? var parentViewController = UIViewController() //Universal view controller required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(menuWidth: CGFloat, menuItemTitles: [String], parentViewController: UIViewController) { super.init(frame: CGRect(x: -menuWidth, y: 20, width: menuWidth, height: parentViewController.view.frame.height)) print("init SideMenu...") self.menuWidth = menuWidth self.menuItemTitles = menuItemTitles self.parentViewController = parentViewController self.backgroundColor = UIColor.darkGray parentViewController.view.addSubview(self) setupMenuView() animator = UIDynamicAnimator(referenceView: parentViewController.view) let showMenuRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(SideMenu.handleGestures(recognizer:))) showMenuRecognizer.direction = .right parentViewController.view.addGestureRecognizer(showMenuRecognizer) //for closing let hideMenuRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(SideMenu.handleGestures(recognizer:))) hideMenuRecognizer.direction = .left parentViewController.view.addGestureRecognizer(hideMenuRecognizer) } func handleGestures(recognizer: UISwipeGestureRecognizer) { if recognizer.direction == .right { toggleMenu(open: true) } else { toggleMenu(open: false) } } func toggleMenu(open: Bool) { animator.removeAllBehaviors() //We need do it because we call this function many times let gravityX: CGFloat = open ? 2 : -1 let pushMagnitude: CGFloat = open ? 2 : -20 let boundaryX: CGFloat = open ? menuWidth : -menuWidth - 5 let gravity = UIGravityBehavior(items: [self]) gravity.gravityDirection = CGVector(dx: gravityX, dy: 0) //The direction and magnitude of the gravitational force, expressed as a vector animator.addBehavior(gravity) let collision = UICollisionBehavior(items: [self]) collision.addBoundary(withIdentifier: 1 as NSCopying, from: CGPoint(x: boundaryX, y: 20), to: CGPoint(x: boundaryX, y: parentViewController.view.bounds.height)) animator.addBehavior(collision) let push = UIPushBehavior(items: [self], mode: .continuous) push.magnitude = pushMagnitude animator.addBehavior(push) let menuBehaviour = UIDynamicItemBehavior(items: [self]) menuBehaviour.elasticity = 0.4 animator.addBehavior(menuBehaviour) UIView.animate(withDuration: 0.2) { self.backgroundView.alpha = open ? 0.5 : 0 } } func setupMenuView() { backgroundView = UIView(frame: parentViewController.view.bounds) backgroundView.backgroundColor = UIColor.lightGray backgroundView.alpha = 0 parentViewController.view.insertSubview(backgroundView, belowSubview: self) // backgroundView is below SideMenu menuTable = UITableView(frame: self.bounds, style: .plain) menuTable.backgroundColor = UIColor.clear menuTable.separatorStyle = .none //Our table will be without separators menuTable.isScrollEnabled = false menuTable.alpha = 1 menuTable.delegate = self menuTable.dataSource = self menuTable.reloadData() self.addSubview(menuTable) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItemTitles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell") if cell == nil { print("Cell \(indexPath.row) is nil...") cell = UITableViewCell(style: .default, reuseIdentifier: "Cell") } cell?.textLabel?.text = menuItemTitles[indexPath.row] cell?.textLabel?.textColor = UIColor.lightGray cell?.textLabel?.font = UIFont(name: "Cochin", size: 20) cell?.textLabel?.textAlignment = .center cell?.backgroundColor = UIColor.clear return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.cellForRow(at: indexPath)?.setSelected(false, animated: true) if let delegate = menuDelegate { delegate.didSelectMenuItem(withTitle: menuItemTitles[indexPath.row], index: indexPath.row) } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
321383c5c5b13cbe6fd8d6f2e0c47f6d
35.0625
168
0.653206
false
false
false
false
artursDerkintis/YouTube
refs/heads/master
YouTube/DataHelper.swift
mit
1
// // DataHelper.swift // YouTube // // Created by Arturs Derkintis on 1/4/16. // Copyright © 2016 Starfly. All rights reserved. // import UIKit import CoreData class DataHelper: NSObject { static let sharedInstance = DataHelper() private override init(){} lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.nealceffrey.Starfly" 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("Youtube", 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("Youtube.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true]) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } func favorited(id : String, completion:(Bool)-> Void){ let request = NSFetchRequest(entityName: "Favorites") request.predicate = NSPredicate(format: "id == %@", id) do{ let array = try self.managedObjectContext.executeFetchRequest(request) print("Favorited ?? \(array.count)") array.count > 0 ? completion(true) : completion(false) }catch _{ completion(false) } } func saveFavorite(videoDetails : VideoDetails){ let newEntity = NSEntityDescription.insertNewObjectForEntityForName("Favorites", inManagedObjectContext: self.managedObjectContext) as! Favorites newEntity.title = videoDetails.title newEntity.id = videoDetails.id newEntity.imageUrl = videoDetails.thumbnail newEntity.channelID = videoDetails.channelId newEntity.channelTitle = videoDetails.channelTitle newEntity.duration = videoDetails.duration self.saveContext() } }
5441b1335715696260435d5ef1f2aa64
51.272727
291
0.690435
false
false
false
false
toshi0383/TruncatingTextView
refs/heads/master
Sources/TruncatingTextView.swift
mit
1
// // TruncatingTextView.swift // TruncatingTextView // // Created by toshi0383 on 2017/01/27. // // import UIKit extension UITextView { /// Calculated text size is smaller than UITextView's size. /// Change margin size until you get "..." at correct position. /// /// This is what NSString.boundingRect's document says. /// > This method returns fractional sizes (in the size component of the returned CGRect); /// > to use a returned size to size views, you must raise its value to the nearest higher /// > integer using the ceil function. /// /// - parameter text: /// - parameter margin: public func setTextAfterTruncatingIfNeeded (text: String?, lineBreakMode: NSLineBreakMode, margin: CGFloat = 0.0) { guard let text = text else { self.text = nil return } guard let font = self.font else { self.text = text return } let size = getExpectedContainerSize(with: margin) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .byCharWrapping let attributes: [String: Any] = [ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle ] self.text = text.truncate(maxSize: size, attributes: attributes) } func getExpectedContainerSize(with margin: CGFloat) -> CGSize { let width = frame.width - margin let height = frame.height return CGSize( width: width, height: height ) } } extension String { func truncate(maxSize: CGSize, attributes: [String: Any]) -> String { if fits(in: maxSize, attributes: attributes) { return self } var result = "".characters for c in self.characters { let previous = String(result) result.append(c) let current = String(result) if !current.fits(in: maxSize, attributes: attributes) { return previous.replaceLastCharacter(with: ".", count: 3) } } #if DEBUG assertionFailure("Shouldn't reach here.") #endif return String(result) } func fits(in size: CGSize, attributes: [String: Any]) -> Bool { let height = self.getHeight(for: size.width, attributes: attributes) return height <= size.height } func getHeight(for width: CGFloat, attributes: [String: Any]) -> CGFloat { return getHeightUsingNSString(for: width, attributes: attributes) } func getHeightUsingNSString(for width: CGFloat, attributes: [String: Any]) -> CGFloat { let nsstring = self as NSString let calculated = nsstring.boundingRect( with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil ).size return calculated.height } // - Deprecated: Do not use this API for production use. func getHeightUsingNSLayoutManager(with width: CGFloat, attributes: [String: Any]) -> CGFloat { let textStorage = NSTextStorage(string: self) let textContainer = NSTextContainer( size: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) ) let layoutManager = NSLayoutManager() layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) textStorage.addAttributes(attributes, range: NSRange(location: 0, length: textStorage.length)) textContainer.lineFragmentPadding = 0.0 layoutManager.glyphRange(for: textContainer) let height = layoutManager.usedRect(for: textContainer).size.height return height } func replaceLastCharacter(with string: String, count: UInt) -> String { var s = self.characters for _ in (0..<count) { s = s.dropLast() } for _ in (0..<count) { if let c = string.characters.first { s.append(c) } } return String(s) } }
bd4f1add8c3bc24158f5b5b01c2626e0
33.254098
102
0.612826
false
false
false
false
jjatie/Charts
refs/heads/master
Source/Charts/Charts/BarLineChartViewBase.swift
apache-2.0
1
// // BarLineChartViewBase.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import CoreGraphics import Foundation #if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif /// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart. open class BarLineChartViewBase: ChartViewBase, BarLineScatterCandleBubbleChartDataProvider, NSUIGestureRecognizerDelegate { /// the number of maximum visible drawn values on the chart only active when `drawValuesEnabled` is enabled /// - Note: entry numbers greater than this value will cause value-labels to disappear public final var maxVisibleCount: Int { get { _maxVisibleCount } set { _maxVisibleCount = newValue } } private var _maxVisibleCount = 100 /// flag that indicates if auto scaling on the y axis is enabled. /// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes /// **default**: false /// `true` if auto scaling on the y axis is enabled. public var isAutoScaleMinMaxEnabled = false /// is dragging on the X axis enabled? public var isDragXEnabled = true /// is dragging on the Y axis enabled? public var isDragYEnabled = true /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). open var isDragEnabled: Bool { get { isDragXEnabled || isDragYEnabled } set { isDragYEnabled = newValue isDragXEnabled = newValue } } private var _scaleXEnabled = true private var _scaleYEnabled = true /// flag indicating if the grid background should be drawn or not /// **default**: true /// `true` if drawing the grid background is enabled, `false` ifnot. open var isDrawGridBackgroundEnabled = false /// the color for the background of the chart-drawing area (everything behind the grid lines). open var gridBackgroundColor = NSUIColor(red: 240 / 255.0, green: 240 / 255.0, blue: 240 / 255.0, alpha: 1.0) /// When enabled, the borders rectangle will be rendered. /// If this is enabled, there is no point drawing the axis-lines of x- and y-axis. /// **default**: false /// `true` if drawing the borders rectangle is enabled, `false` ifnot. open var isDrawBordersEnabled = false open var borderColor = NSUIColor.black open var borderLineWidth: CGFloat = 1.0 /// When enabled, the values will be clipped to contentRect, otherwise they can bleed outside the content rect. open var clipValuesToContentEnabled: Bool = false /// When disabled, the data and/or highlights will not be clipped to contentRect. Disabling this option can /// be useful, when the data lies fully within the content rect, but is drawn in such a way (such as thick lines) /// that there is unwanted clipping. open var clipDataToContentEnabled: Bool = true /// Sets the minimum offset (padding) around the chart, defaults to 10 open var minOffset = CGFloat(10.0) /// Sets whether the chart should keep its position (zoom / scroll) after a rotation (orientation change) /// **default**: false open var keepPositionOnRotation = false /// The left y-axis object. In the horizontal bar-chart, this is the /// top axis. open internal(set) var leftAxis = YAxis(position: .left) /// The right y-axis object. In the horizontal bar-chart, this is the /// bottom axis. open internal(set) var rightAxis = YAxis(position: .right) /// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of YAxisRenderer open lazy var leftYAxisRenderer = YAxisRenderer(viewPortHandler: viewPortHandler, axis: leftAxis, transformer: _leftAxisTransformer) /// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of YAxisRenderer open lazy var rightYAxisRenderer = YAxisRenderer(viewPortHandler: viewPortHandler, axis: rightAxis, transformer: _rightAxisTransformer) var _leftAxisTransformer: Transformer! var _rightAxisTransformer: Transformer! /// The X axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of XAxisRenderer open lazy var xAxisRenderer = XAxisRenderer(viewPortHandler: viewPortHandler, axis: xAxis, transformer: _leftAxisTransformer) var _tapGestureRecognizer: NSUITapGestureRecognizer! var _doubleTapGestureRecognizer: NSUITapGestureRecognizer! var _panGestureRecognizer: NSUIPanGestureRecognizer! #if !os(tvOS) var _pinchGestureRecognizer: NSUIPinchGestureRecognizer! #endif /// flag that indicates if a custom viewport offset has been set private var _customViewPortEnabled = false override public init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } override func initialize() { super.initialize() _leftAxisTransformer = Transformer(viewPortHandler: viewPortHandler) _rightAxisTransformer = Transformer(viewPortHandler: viewPortHandler) highlighter = ChartHighlighter(chart: self) _tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized(_:))) _doubleTapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(doubleTapGestureRecognized(_:))) _doubleTapGestureRecognizer.nsuiNumberOfTapsRequired = 2 _panGestureRecognizer = NSUIPanGestureRecognizer(target: self, action: #selector(panGestureRecognized(_:))) _panGestureRecognizer.delegate = self addGestureRecognizer(_tapGestureRecognizer) addGestureRecognizer(_doubleTapGestureRecognizer) addGestureRecognizer(_panGestureRecognizer) _panGestureRecognizer.isEnabled = isDragXEnabled || isDragYEnabled #if !os(tvOS) _pinchGestureRecognizer = NSUIPinchGestureRecognizer(target: self, action: #selector(BarLineChartViewBase.pinchGestureRecognized(_:))) _pinchGestureRecognizer.delegate = self addGestureRecognizer(_pinchGestureRecognizer) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } override public final func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { // Saving current position of chart. var oldPoint: CGPoint? if keepPositionOnRotation, keyPath == "frame" || keyPath == "bounds" { oldPoint = viewPortHandler.contentRect.origin getTransformer(forAxis: .left).pixelToValues(&oldPoint!) } // Superclass transforms chart. super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) // Restoring old position of chart if var newPoint = oldPoint, keepPositionOnRotation { getTransformer(forAxis: .left).pointValueToPixel(&newPoint) viewPortHandler.centerViewPort(pt: newPoint, chart: self) } else { viewPortHandler.refresh(newMatrix: viewPortHandler.touchMatrix, chart: self, invalidate: true) } } override public final func draw(_ rect: CGRect) { super.draw(rect) guard data != nil, let renderer = renderer else { return } let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } // execute all drawing commands drawGridBackground(context: context) if isAutoScaleMinMaxEnabled { autoScale() } if leftAxis.isEnabled { leftYAxisRenderer.computeAxis(min: leftAxis._axisMinimum, max: leftAxis._axisMaximum, inverted: leftAxis.isInverted) } if rightAxis.isEnabled { rightYAxisRenderer.computeAxis(min: rightAxis._axisMinimum, max: rightAxis._axisMaximum, inverted: rightAxis.isInverted) } if xAxis.isEnabled { xAxisRenderer.computeAxis(min: xAxis._axisMinimum, max: xAxis._axisMaximum, inverted: false) } xAxisRenderer.renderAxisLine(context: context) leftYAxisRenderer.renderAxisLine(context: context) rightYAxisRenderer.renderAxisLine(context: context) // The renderers are responsible for clipping, to account for line-width center etc. if xAxis.drawGridLinesBehindDataEnabled { xAxisRenderer.renderGridLines(context: context) leftYAxisRenderer.renderGridLines(context: context) rightYAxisRenderer.renderGridLines(context: context) } if xAxis.isEnabled, xAxis.isDrawLimitLinesBehindDataEnabled { xAxisRenderer.renderLimitLines(context: context) } if leftAxis.isEnabled, leftAxis.isDrawLimitLinesBehindDataEnabled { leftYAxisRenderer.renderLimitLines(context: context) } if rightAxis.isEnabled, rightAxis.isDrawLimitLinesBehindDataEnabled { rightYAxisRenderer.renderLimitLines(context: context) } context.saveGState() // make sure the data cannot be drawn outside the content-rect if clipDataToContentEnabled { context.clip(to: viewPortHandler.contentRect) } renderer.drawData(context: context) // The renderers are responsible for clipping, to account for line-width center etc. if !xAxis.drawGridLinesBehindDataEnabled { xAxisRenderer.renderGridLines(context: context) leftYAxisRenderer.renderGridLines(context: context) rightYAxisRenderer.renderGridLines(context: context) } // if highlighting is enabled if valuesToHighlight { renderer.drawHighlighted(context: context, indices: highlighted) } context.restoreGState() renderer.drawExtras(context: context) if xAxis.isEnabled, !xAxis.isDrawLimitLinesBehindDataEnabled { xAxisRenderer.renderLimitLines(context: context) } if leftAxis.isEnabled, !leftAxis.isDrawLimitLinesBehindDataEnabled { leftYAxisRenderer.renderLimitLines(context: context) } if rightAxis.isEnabled, !rightAxis.isDrawLimitLinesBehindDataEnabled { rightYAxisRenderer.renderLimitLines(context: context) } xAxisRenderer.renderAxisLabels(context: context) leftYAxisRenderer.renderAxisLabels(context: context) rightYAxisRenderer.renderAxisLabels(context: context) if clipValuesToContentEnabled { context.saveGState() context.clip(to: viewPortHandler.contentRect) renderer.drawValues(context: context) context.restoreGState() } else { renderer.drawValues(context: context) } legendRenderer.renderLegend(context: context) drawDescription(in: context) drawMarkers(context: context) } /// Performs auto scaling of the axis by recalculating the minimum and maximum y-values based on the entries currently in view. final func autoScale() { guard let data = data else { return } data.calcMinMaxY(fromX: lowestVisibleX, toX: highestVisibleX) xAxis.calculate(min: data.xRange.min, max: data.xRange.max) // calculate axis range (min / max) according to provided data if leftAxis.isEnabled { leftAxis.calculate(min: data.getYMin(axis: .left), max: data.getYMax(axis: .left)) } if rightAxis.isEnabled { rightAxis.calculate(min: data.getYMin(axis: .right), max: data.getYMax(axis: .right)) } calculateOffsets() } func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(rightAxis.axisRange), chartYMin: rightAxis._axisMinimum) _leftAxisTransformer.prepareMatrixValuePx(chartXMin: xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(leftAxis.axisRange), chartYMin: leftAxis._axisMinimum) } final func prepareOffsetMatrix() { _rightAxisTransformer.prepareMatrixOffset(inverted: rightAxis.isInverted) _leftAxisTransformer.prepareMatrixOffset(inverted: leftAxis.isInverted) } override public final func notifyDataSetChanged() { renderer?.initBuffers() calcMinMax() leftYAxisRenderer.computeAxis(min: leftAxis._axisMinimum, max: leftAxis._axisMaximum, inverted: leftAxis.isInverted) rightYAxisRenderer.computeAxis(min: rightAxis._axisMinimum, max: rightAxis._axisMaximum, inverted: rightAxis.isInverted) if let data = data { xAxisRenderer.computeAxis( min: xAxis._axisMinimum, max: xAxis._axisMaximum, inverted: false ) legendRenderer.computeLegend(data: data) } calculateOffsets() setNeedsDisplay() } func calcMinMax() { // calculate / set x-axis range xAxis.calculate(min: data?.xRange.min ?? 0.0, max: data?.xRange.max ?? 0.0) // calculate axis range (min / max) according to provided data leftAxis.calculate(min: data?.getYMin(axis: .left) ?? 0.0, max: data?.getYMax(axis: .left) ?? 0.0) rightAxis.calculate(min: data?.getYMin(axis: .right) ?? 0.0, max: data?.getYMax(axis: .right) ?? 0.0) } func calculateLegendOffsets(offsetLeft: inout CGFloat, offsetTop: inout CGFloat, offsetRight: inout CGFloat, offsetBottom: inout CGFloat) { // setup offsets for legend guard legend.isEnabled, !legend.drawInside else { return } switch legend.orientation { case .vertical: switch legend.horizontalAlignment { case .left: offsetLeft += min(legend.neededWidth, viewPortHandler.chartWidth * legend.maxSizePercent) + legend.xOffset case .right: offsetRight += min(legend.neededWidth, viewPortHandler.chartWidth * legend.maxSizePercent) + legend.xOffset case .center: switch legend.verticalAlignment { case .top: offsetTop += min(legend.neededHeight, viewPortHandler.chartHeight * legend.maxSizePercent) + legend.yOffset case .bottom: offsetBottom += min(legend.neededHeight, viewPortHandler.chartHeight * legend.maxSizePercent) + legend.yOffset default: break } } case .horizontal: switch legend.verticalAlignment { case .top: offsetTop += min(legend.neededHeight, viewPortHandler.chartHeight * legend.maxSizePercent) + legend.yOffset case .bottom: offsetBottom += min(legend.neededHeight, viewPortHandler.chartHeight * legend.maxSizePercent) + legend.yOffset default: break } } } override func calculateOffsets() { if !_customViewPortEnabled { var offsetLeft = CGFloat(0.0) var offsetRight = CGFloat(0.0) var offsetTop = CGFloat(0.0) var offsetBottom = CGFloat(0.0) calculateLegendOffsets(offsetLeft: &offsetLeft, offsetTop: &offsetTop, offsetRight: &offsetRight, offsetBottom: &offsetBottom) // offsets for y-labels if leftAxis.needsOffset { offsetLeft += leftAxis.requiredSize().width } if rightAxis.needsOffset { offsetRight += rightAxis.requiredSize().width } if xAxis.isEnabled, xAxis.isDrawLabelsEnabled { let xlabelheight = xAxis.labelRotatedHeight + xAxis.yOffset // offsets for x-labels if xAxis.labelPosition == .bottom { offsetBottom += xlabelheight } else if xAxis.labelPosition == .top { offsetTop += xlabelheight } else if xAxis.labelPosition == .bothSided { offsetBottom += xlabelheight offsetTop += xlabelheight } } offsetTop += extraTopOffset offsetRight += extraRightOffset offsetBottom += extraBottomOffset offsetLeft += extraLeftOffset viewPortHandler.restrainViewPort( offsetLeft: max(minOffset, offsetLeft), offsetTop: max(minOffset, offsetTop), offsetRight: max(minOffset, offsetRight), offsetBottom: max(minOffset, offsetBottom) ) } prepareOffsetMatrix() prepareValuePxMatrix() } /// draws the grid background final func drawGridBackground(context: CGContext) { if isDrawGridBackgroundEnabled || isDrawBordersEnabled { context.saveGState() } if isDrawGridBackgroundEnabled { // draw the grid background context.setFillColor(gridBackgroundColor.cgColor) context.fill(viewPortHandler.contentRect) } if isDrawBordersEnabled { context.setLineWidth(borderLineWidth) context.setStrokeColor(borderColor.cgColor) context.stroke(viewPortHandler.contentRect) } if isDrawGridBackgroundEnabled || isDrawBordersEnabled { context.restoreGState() } } // MARK: - Gestures private enum GestureScaleAxis { case both case x case y } private var _isDragging = false private var _isScaling = false private var _gestureScaleAxis = GestureScaleAxis.both private var _closestDataSetToTouch: ChartDataSet! private weak var _outerScrollView: NSUIScrollView? private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity private var _decelerationLastTime: TimeInterval = 0.0 private var _decelerationDisplayLink: NSUIDisplayLink! private var _decelerationVelocity = CGPoint() @objc private func tapGestureRecognized(_ recognizer: NSUITapGestureRecognizer) { if data === nil { return } if recognizer.state == NSUIGestureRecognizerState.ended { if !isHighLightPerTapEnabled { return } let h = getHighlightByTouchPoint(recognizer.location(in: self)) if h === nil || h == lastHighlighted { lastHighlighted = nil highlightValue(nil, callDelegate: true) } else { lastHighlighted = h highlightValue(h, callDelegate: true) } } } @objc private func doubleTapGestureRecognized(_ recognizer: NSUITapGestureRecognizer) { if data === nil { return } if recognizer.state == NSUIGestureRecognizerState.ended { if data !== nil, isDoubleTapToZoomEnabled, (data?.entryCount ?? 0) > 0 { var location = recognizer.location(in: self) location.x = location.x - viewPortHandler.offsetLeft if isTouchInverted { location.y = -(location.y - viewPortHandler.offsetTop) } else { location.y = -(bounds.size.height - location.y - viewPortHandler.offsetBottom) } zoom(scaleX: isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y) delegate?.chartScaled(self, scaleX: scaleX, scaleY: scaleY) } } } #if !os(tvOS) @objc private func pinchGestureRecognized(_ recognizer: NSUIPinchGestureRecognizer) { if recognizer.state == NSUIGestureRecognizerState.began { stopDeceleration() if data !== nil && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled) { _isScaling = true if _pinchZoomEnabled { _gestureScaleAxis = .both } else { let x = abs(recognizer.location(in: self).x - recognizer.nsuiLocationOfTouch(1, inView: self).x) let y = abs(recognizer.location(in: self).y - recognizer.nsuiLocationOfTouch(1, inView: self).y) if _scaleXEnabled != _scaleYEnabled { _gestureScaleAxis = _scaleXEnabled ? .x : .y } else { _gestureScaleAxis = x > y ? .x : .y } } } } else if recognizer.state == NSUIGestureRecognizerState.ended || recognizer.state == NSUIGestureRecognizerState.cancelled { if _isScaling { _isScaling = false // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } else if recognizer.state == NSUIGestureRecognizerState.changed { let isZoomingOut = (recognizer.nsuiScale < 1) var canZoomMoreX = isZoomingOut ? viewPortHandler.canZoomOutMoreX : viewPortHandler.canZoomInMoreX var canZoomMoreY = isZoomingOut ? viewPortHandler.canZoomOutMoreY : viewPortHandler.canZoomInMoreY if _isScaling { canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .x) canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .y) if canZoomMoreX || canZoomMoreY { var location = recognizer.location(in: self) location.x = location.x - viewPortHandler.offsetLeft if isTouchInverted { location.y = -(location.y - viewPortHandler.offsetTop) } else { location.y = -(viewPortHandler.chartHeight - location.y - viewPortHandler.offsetBottom) } let scaleX = canZoomMoreX ? recognizer.nsuiScale : 1.0 let scaleY = canZoomMoreY ? recognizer.nsuiScale : 1.0 var matrix = CGAffineTransform(translationX: location.x, y: location.y) matrix = matrix.scaledBy(x: scaleX, y: scaleY) matrix = matrix.translatedBy(x: -location.x, y: -location.y) matrix = viewPortHandler.touchMatrix.concatenating(matrix) viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if delegate !== nil { delegate?.chartScaled(self, scaleX: scaleX, scaleY: scaleY) } } recognizer.nsuiScale = 1.0 } } } #endif @objc private func panGestureRecognized(_ recognizer: NSUIPanGestureRecognizer) { if recognizer.state == .began && recognizer.nsuiNumberOfTouches > 0 { stopDeceleration() if data === nil || !isDragEnabled { // If we have no data, we have nothing to pan and no data to highlight return } // If drag is enabled and we are in a position where there's something to drag: // * If we're zoomed in, then obviously we have something to drag. // * If we have a drag offset - we always have something to drag if !hasNoDragOffset || !isFullyZoomedOut { _isDragging = true _closestDataSetToTouch = getDataSetByTouchPoint(point: recognizer.nsuiLocationOfTouch(0, inView: self)) var translation = recognizer.translation(in: self) if !isDragXEnabled { translation.x = 0.0 } else if !isDragYEnabled { translation.y = 0.0 } let didUserDrag = translation.x != 0.0 || translation.y != 0.0 // Check to see if user dragged at all and if so, can the chart be dragged by the given amount if didUserDrag, !performPanChange(translation: translation) { if _outerScrollView !== nil { // We can stop dragging right now, and let the scroll view take control _outerScrollView = nil _isDragging = false } } else { if _outerScrollView !== nil { // Prevent the parent scroll view from scrolling _outerScrollView?.nsuiIsScrollEnabled = false } } _lastPanPoint = recognizer.translation(in: self) } else if isHighlightPerDragEnabled { // We will only handle highlights on NSUIGestureRecognizerState.Changed _isDragging = false } } else if recognizer.state == .changed { if _isDragging { let originalTranslation = recognizer.translation(in: self) var translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y) if !isDragXEnabled { translation.x = 0.0 } else if !isDragYEnabled { translation.y = 0.0 } _ = performPanChange(translation: translation) _lastPanPoint = originalTranslation } else if isHighlightPerDragEnabled { let h = getHighlightByTouchPoint(recognizer.location(in: self)) let lastHighlighted = self.lastHighlighted if h != lastHighlighted { self.lastHighlighted = h highlightValue(h, callDelegate: true) } } } else if recognizer.state == .ended || recognizer.state == .cancelled { if _isDragging { if recognizer.state == .ended, isDragDecelerationEnabled { stopDeceleration() _decelerationLastTime = CACurrentMediaTime() _decelerationVelocity = recognizer.velocity(in: self) _decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(BarLineChartViewBase.decelerationLoop)) _decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.common) } _isDragging = false delegate?.chartViewDidEndPanning(self) } if _outerScrollView !== nil { _outerScrollView?.nsuiIsScrollEnabled = true _outerScrollView = nil } } } private func performPanChange(translation: CGPoint) -> Bool { var translation = translation if isTouchInverted { if self is HorizontalBarChartView { translation.x = -translation.x } else { translation.y = -translation.y } } let originalMatrix = viewPortHandler.touchMatrix var matrix = CGAffineTransform(translationX: translation.x, y: translation.y) matrix = originalMatrix.concatenating(matrix) matrix = viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if matrix != originalMatrix { delegate?.chartTranslated(self, dX: translation.x, dY: translation.y) } // Did we managed to actually drag or did we reach the edge? return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty } private var isTouchInverted: Bool { isAnyAxisInverted && _closestDataSetToTouch != nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted } public final func stopDeceleration() { if _decelerationDisplayLink !== nil { _decelerationDisplayLink.remove(from: RunLoop.main, forMode: RunLoop.Mode.common) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationVelocity.x *= dragDecelerationFrictionCoef _decelerationVelocity.y *= dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) let distance = CGPoint( x: _decelerationVelocity.x * timeInterval, y: _decelerationVelocity.y * timeInterval ) if !performPanChange(translation: distance) { // We reached the edge, stop _decelerationVelocity.x = 0.0 _decelerationVelocity.y = 0.0 } _decelerationLastTime = currentTime if abs(_decelerationVelocity.x) < 0.001, abs(_decelerationVelocity.y) < 0.001 { stopDeceleration() // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } private func nsuiGestureRecognizerShouldBegin(_ gestureRecognizer: NSUIGestureRecognizer) -> Bool { if gestureRecognizer == _panGestureRecognizer { let velocity = _panGestureRecognizer.velocity(in: self) if data === nil || !isDragEnabled || (hasNoDragOffset && isFullyZoomedOut && !isHighlightPerDragEnabled) || (!isDragYEnabled && abs(velocity.y) > abs(velocity.x)) || (!isDragXEnabled && abs(velocity.y) < abs(velocity.x)) { return false } } else { #if !os(tvOS) if gestureRecognizer == _pinchGestureRecognizer { if data === nil || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled) { return false } } #endif } return true } #if !os(OSX) override public final func gestureRecognizerShouldBegin(_ gestureRecognizer: NSUIGestureRecognizer) -> Bool { if !super.gestureRecognizerShouldBegin(gestureRecognizer) { return false } return nsuiGestureRecognizerShouldBegin(gestureRecognizer) } #endif #if os(OSX) public final func gestureRecognizerShouldBegin(gestureRecognizer: NSUIGestureRecognizer) -> Bool { nsuiGestureRecognizerShouldBegin(gestureRecognizer) } #endif public final func gestureRecognizer(_ gestureRecognizer: NSUIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: NSUIGestureRecognizer) -> Bool { #if !os(tvOS) if (gestureRecognizer is NSUIPinchGestureRecognizer && otherGestureRecognizer is NSUIPanGestureRecognizer) || (gestureRecognizer is NSUIPanGestureRecognizer && otherGestureRecognizer is NSUIPinchGestureRecognizer) { return true } #endif if gestureRecognizer is NSUIPanGestureRecognizer, otherGestureRecognizer is NSUIPanGestureRecognizer, gestureRecognizer == _panGestureRecognizer { var scrollView = superview while scrollView != nil, !(scrollView is NSUIScrollView) { scrollView = scrollView?.superview } // If there is two scrollview together, we pick the superview of the inner scrollview. // In the case of UITableViewWrepperView, the superview will be UITableView if let superViewOfScrollView = scrollView?.superview, superViewOfScrollView is NSUIScrollView { scrollView = superViewOfScrollView } var foundScrollView = scrollView as? NSUIScrollView if !(foundScrollView?.nsuiIsScrollEnabled ?? true) { foundScrollView = nil } let scrollViewPanGestureRecognizer = foundScrollView?.nsuiGestureRecognizers?.first { $0 is NSUIPanGestureRecognizer } if otherGestureRecognizer === scrollViewPanGestureRecognizer { _outerScrollView = foundScrollView return true } } return false } // MARK: Viewport modifiers /// Zooms in by 1.4, into the charts center. public final func zoomIn() { let center = viewPortHandler.contentCenter let matrix = viewPortHandler.zoomIn(x: center.x, y: -center.y) viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms out by 0.7, from the charts center. public final func zoomOut() { let center = viewPortHandler.contentCenter let matrix = viewPortHandler.zoomOut(x: center.x, y: -center.y) viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms out to original size. public final func resetZoom() { let matrix = viewPortHandler.resetZoom() viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. x and y are the coordinates /// (in pixels) of the zoom center. /// /// - Parameters: /// - scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - x: /// - y: public final func zoom( scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat ) { let matrix = viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y) viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. /// x and y are the values (**not pixels**) of the zoom center. /// /// - Parameters: /// - scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - xValue: /// - yValue: /// - axis: public final func zoom( scaleX: CGFloat, scaleY: CGFloat, xValue: Double, yValue: Double, axis: YAxis.AxisDependency ) { let job = ZoomViewJob( viewPortHandler: viewPortHandler, scaleX: scaleX, scaleY: scaleY, xValue: xValue, yValue: yValue, transformer: getTransformer(forAxis: axis), axis: axis, view: self ) addViewportJob(job) } /// Zooms to the center of the chart with the given scale factor. /// /// - Parameters: /// - scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - xValue: /// - yValue: /// - axis: public final func zoomToCenter( scaleX: CGFloat, scaleY: CGFloat ) { let center = centerOffsets let matrix = viewPortHandler.zoom( scaleX: scaleX, scaleY: scaleY, x: center.x, y: -center.y ) viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) } /// Zooms by the specified scale factor to the specified values on the specified axis. /// /// - Parameters: /// - scaleX: /// - scaleY: /// - xValue: /// - yValue: /// - axis: which axis should be used as a reference for the y-axis /// - duration: the duration of the animation in seconds /// - easing: public final func zoomAndCenterViewAnimated( scaleX: CGFloat, scaleY: CGFloat, xValue: Double, yValue: Double, axis: YAxis.AxisDependency, duration: TimeInterval, easing: ChartEasingFunctionBlock? ) { let origin = valueForTouchPoint( point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop), axis: axis ) let job = AnimatedZoomViewJob( viewPortHandler: viewPortHandler, transformer: getTransformer(forAxis: axis), view: self, yAxis: getAxis(axis), xAxisRange: xAxis.axisRange, scaleX: scaleX, scaleY: scaleY, xOrigin: viewPortHandler.scaleX, yOrigin: viewPortHandler.scaleY, zoomCenterX: CGFloat(xValue), zoomCenterY: CGFloat(yValue), zoomOriginX: origin.x, zoomOriginY: origin.y, duration: duration, easing: easing ) addViewportJob(job) } /// Zooms by the specified scale factor to the specified values on the specified axis. /// /// - Parameters: /// - scaleX: /// - scaleY: /// - xValue: /// - yValue: /// - axis: which axis should be used as a reference for the y-axis /// - duration: the duration of the animation in seconds /// - easing: public final func zoomAndCenterViewAnimated( scaleX: CGFloat, scaleY: CGFloat, xValue: Double, yValue: Double, axis: YAxis.AxisDependency, duration: TimeInterval, easingOption: ChartEasingOption = .easeInOutSine ) { zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption)) } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. public final func fitScreen() { let matrix = viewPortHandler.fitScreen() viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) calculateOffsets() setNeedsDisplay() } /// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen public final func setScaleMinima(_ scaleX: CGFloat, scaleY: CGFloat) { viewPortHandler.setMinimumScaleX(scaleX) viewPortHandler.setMinimumScaleY(scaleY) } public final var visibleXRange: Double { abs(highestVisibleX - lowestVisibleX) } /// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zooming out allowed). /// /// If this is e.g. set to 10, no more than a range of 10 values on the x-axis can be viewed at once without scrolling. /// /// If you call this method, chart must have data or it has no effect. public func setVisibleXRangeMaximum(_ maxXRange: Double) { let xScale = xAxis.axisRange / maxXRange viewPortHandler.setMinimumScaleX(CGFloat(xScale)) } /// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed). /// /// If this is e.g. set to 10, no less than a range of 10 values on the x-axis can be viewed at once without scrolling. /// /// If you call this method, chart must have data or it has no effect. public func setVisibleXRangeMinimum(_ minXRange: Double) { let xScale = xAxis.axisRange / minXRange viewPortHandler.setMaximumScaleX(CGFloat(xScale)) } /// Limits the maximum and minimum value count that can be visible by pinching and zooming. /// /// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed /// at once without scrolling. /// /// If you call this method, chart must have data or it has no effect. public func setVisibleXRange(minXRange: Double, maxXRange: Double) { let minScale = xAxis.axisRange / maxXRange let maxScale = xAxis.axisRange / minXRange viewPortHandler.setMinMaxScaleX( minScaleX: CGFloat(minScale), maxScaleX: CGFloat(maxScale) ) } /// Sets the size of the area (range on the y-axis) that should be maximum visible at once. /// /// - Parameters: /// - yRange: /// - axis: - the axis for which this limit should apply public func setVisibleYRangeMaximum(_ maxYRange: Double, axis: YAxis.AxisDependency) { let yScale = getAxis(axis).axisRange / maxYRange viewPortHandler.setMinimumScaleY(CGFloat(yScale)) } /// Sets the size of the area (range on the y-axis) that should be minimum visible at once, no further zooming in possible. /// /// - Parameters: /// - yRange: /// - axis: - the axis for which this limit should apply public func setVisibleYRangeMinimum(_ minYRange: Double, axis: YAxis.AxisDependency) { let yScale = getAxis(axis).axisRange / minYRange viewPortHandler.setMaximumScaleY(CGFloat(yScale)) } /// Limits the maximum and minimum y range that can be visible by pinching and zooming. /// /// - Parameters: /// - minYRange: /// - maxYRange: /// - axis: public func setVisibleYRange(minYRange: Double, maxYRange: Double, axis: YAxis.AxisDependency) { let minScale = getAxis(axis).axisRange / minYRange let maxScale = getAxis(axis).axisRange / maxYRange viewPortHandler.setMinMaxScaleY(minScaleY: CGFloat(minScale), maxScaleY: CGFloat(maxScale)) } /// Moves the left side of the current viewport to the specified x-value. /// This also refreshes the chart by calling setNeedsDisplay(). public final func moveViewToX(_ xValue: Double) { let job = MoveViewJob( viewPortHandler: viewPortHandler, xValue: xValue, yValue: 0.0, transformer: getTransformer(forAxis: .left), view: self ) addViewportJob(job) } /// Centers the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - Parameters: /// - yValue: /// - axis: - which axis should be used as a reference for the y-axis public final func moveViewToY(_ yValue: Double, axis: YAxis.AxisDependency) { let yInView = getAxis(axis).axisRange / Double(viewPortHandler.scaleY) let job = MoveViewJob( viewPortHandler: viewPortHandler, xValue: 0.0, yValue: yValue + yInView / 2.0, transformer: getTransformer(forAxis: axis), view: self ) addViewportJob(job) } /// This will move the left side of the current viewport to the specified x-value on the x-axis, and center the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - Parameters: /// - xValue: /// - yValue: /// - axis: - which axis should be used as a reference for the y-axis public final func moveViewTo(xValue: Double, yValue: Double, axis: YAxis.AxisDependency) { let yInView = getAxis(axis).axisRange / Double(viewPortHandler.scaleY) let job = MoveViewJob( viewPortHandler: viewPortHandler, xValue: xValue, yValue: yValue + yInView / 2.0, transformer: getTransformer(forAxis: axis), view: self ) addViewportJob(job) } /// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - Parameters: /// - xValue: /// - yValue: /// - axis: which axis should be used as a reference for the y-axis /// - duration: the duration of the animation in seconds /// - easing: public final func moveViewToAnimated( xValue: Double, yValue: Double, axis: YAxis.AxisDependency, duration: TimeInterval, easing: ChartEasingFunctionBlock? ) { let bounds = valueForTouchPoint( point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop), axis: axis ) let yInView = getAxis(axis).axisRange / Double(viewPortHandler.scaleY) let job = AnimatedMoveViewJob( viewPortHandler: viewPortHandler, xValue: xValue, yValue: yValue + yInView / 2.0, transformer: getTransformer(forAxis: axis), view: self, xOrigin: bounds.x, yOrigin: bounds.y, duration: duration, easing: easing ) addViewportJob(job) } /// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - Parameters: /// - xValue: /// - yValue: /// - axis: which axis should be used as a reference for the y-axis /// - duration: the duration of the animation in seconds /// - easing: public final func moveViewToAnimated( xValue: Double, yValue: Double, axis: YAxis.AxisDependency, duration: TimeInterval, easingOption: ChartEasingOption = .easeInOutSine ) { moveViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption)) } /// This will move the center of the current viewport to the specified x-value and y-value. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - Parameters: /// - xValue: /// - yValue: /// - axis: - which axis should be used as a reference for the y-axis public final func centerViewTo( xValue: Double, yValue: Double, axis: YAxis.AxisDependency ) { let yInView = getAxis(axis).axisRange / Double(viewPortHandler.scaleY) let xInView = xAxis.axisRange / Double(viewPortHandler.scaleX) let job = MoveViewJob( viewPortHandler: viewPortHandler, xValue: xValue - xInView / 2.0, yValue: yValue + yInView / 2.0, transformer: getTransformer(forAxis: axis), view: self ) addViewportJob(job) } /// This will move the center of the current viewport to the specified x-value and y-value animated. /// /// - Parameters: /// - xValue: /// - yValue: /// - axis: which axis should be used as a reference for the y-axis /// - duration: the duration of the animation in seconds /// - easing: public final func centerViewToAnimated( xValue: Double, yValue: Double, axis: YAxis.AxisDependency, duration: TimeInterval, easing: ChartEasingFunctionBlock? ) { let bounds = valueForTouchPoint( point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop), axis: axis ) let yInView = getAxis(axis).axisRange / Double(viewPortHandler.scaleY) let xInView = xAxis.axisRange / Double(viewPortHandler.scaleX) let job = AnimatedMoveViewJob( viewPortHandler: viewPortHandler, xValue: xValue - xInView / 2.0, yValue: yValue + yInView / 2.0, transformer: getTransformer(forAxis: axis), view: self, xOrigin: bounds.x, yOrigin: bounds.y, duration: duration, easing: easing ) addViewportJob(job) } /// This will move the center of the current viewport to the specified x-value and y-value animated. /// /// - Parameters: /// - xValue: /// - yValue: /// - axis: which axis should be used as a reference for the y-axis /// - duration: the duration of the animation in seconds /// - easing: public final func centerViewToAnimated( xValue: Double, yValue: Double, axis: YAxis.AxisDependency, duration: TimeInterval, easingOption: ChartEasingOption = .easeInOutSine ) { centerViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption)) } /// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this. /// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`. public final func setViewPortOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { _customViewPortEnabled = true if Thread.isMainThread { viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom) prepareOffsetMatrix() prepareValuePxMatrix() } else { DispatchQueue.main.async { self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom) } } } /// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically. public func resetViewPortOffsets() { _customViewPortEnabled = false calculateOffsets() } // MARK: - Accessors // /// - Returns: The range of the specified axis. // public final func getAxisRange(axis: YAxis.AxisDependency) -> Double { // getAxis(axis).axisRange // } /// - Returns: The position (in pixels) the provided Entry has inside the chart view public func getPosition(entry e: ChartDataEntry, axis: YAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y)) getTransformer(forAxis: axis).pointValueToPixel(&vals) return vals } /// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging). public final func setScaleEnabled(_ enabled: Bool) { if _scaleXEnabled != enabled || _scaleYEnabled != enabled { _scaleXEnabled = enabled _scaleYEnabled = enabled #if !os(tvOS) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } public var scaleXEnabled: Bool { get { _scaleXEnabled } set { if _scaleXEnabled != newValue { _scaleXEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var scaleYEnabled: Bool { get { _scaleYEnabled } set { if _scaleYEnabled != newValue { _scaleYEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var isScaleXEnabled: Bool { return scaleXEnabled } public var isScaleYEnabled: Bool { return scaleYEnabled } /// flag that indicates if double tap zoom is enabled or not /// **default**: true /// `true` if zooming via double-tap is enabled `false` ifnot. public var isDoubleTapToZoomEnabled: Bool { get { _doubleTapGestureRecognizer.isEnabled } set { _doubleTapGestureRecognizer.isEnabled = newValue } } /// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled /// If set to true, highlighting per dragging over a fully zoomed out chart is enabled /// You might want to disable this when using inside a `NSUIScrollView` /// /// **default**: true public var isHighlightPerDragEnabled = true /// - Returns: The x and y values in the chart at the given touch point /// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to /// coordinates / values in the chart. This is the opposite method to /// `getPixelsForValues(...)`. public final func valueForTouchPoint(point pt: CGPoint, axis: YAxis.AxisDependency) -> CGPoint { getTransformer(forAxis: axis).valueForTouchPoint(pt) } /// Transforms the given chart values into pixels. This is the opposite /// method to `valueForTouchPoint(...)`. public final func pixelForValues(x: Double, y: Double, axis: YAxis.AxisDependency) -> CGPoint { getTransformer(forAxis: axis).pixelForValues(x: x, y: y) } /// - Returns: The Entry object displayed at the touched position of the chart public final func getEntryByTouchPoint(point pt: CGPoint) -> ChartDataEntry! { if let h = getHighlightByTouchPoint(pt) { return data!.entry(for: h) } return nil } /// - Returns: The DataSet object displayed at the touched position of the chart public final func getDataSetByTouchPoint(point pt: CGPoint) -> BarLineScatterCandleBubbleChartDataSet? { guard let h = getHighlightByTouchPoint(pt) else { return nil } return data?[h.dataSetIndex] as? BarLineScatterCandleBubbleChartDataSet } /// The current x-scale factor public final var scaleX: CGFloat { viewPortHandler.scaleX } /// The current y-scale factor public final var scaleY: CGFloat { viewPortHandler.scaleY } /// if the chart is fully zoomed out, return true public final var isFullyZoomedOut: Bool { viewPortHandler.isFullyZoomedOut } /// - Returns: The y-axis object to the corresponding AxisDependency. In the /// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM public final func getAxis(_ axis: YAxis.AxisDependency) -> YAxis { switch axis { case .left: return leftAxis case .right: return rightAxis } } /// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled simultaneously with 2 fingers, if false, x and y axis can be scaled separately /// **default**: false /// `true` if pinch-zoom is enabled, `false` ifnot public final var isPinchZoomEnabled: Bool { get { _pinchZoomEnabled } set { if _pinchZoomEnabled != newValue { _pinchZoomEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } private var _pinchZoomEnabled = false /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the x-axis. public final func setDragOffsetX(_ offset: CGFloat) { viewPortHandler.setDragOffsetX(offset) } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the y-axis. public final func setDragOffsetY(_ offset: CGFloat) { viewPortHandler.setDragOffsetY(offset) } /// `true` if both drag offsets (x and y) are zero or smaller. public final var hasNoDragOffset: Bool { viewPortHandler.hasNoDragOffset } public final var chartYMax: Double { max(leftAxis._axisMaximum, rightAxis._axisMaximum) } public final var chartYMin: Double { min(leftAxis._axisMinimum, rightAxis._axisMinimum) } /// `true` if either the left or the right or both axes are inverted. private var isAnyAxisInverted: Bool { leftAxis.isInverted || rightAxis.isInverted } /// - Returns the width of the specified y axis. public final func getYAxisWidth(_ axis: YAxis.AxisDependency) -> CGFloat { getAxis(axis).requiredSize().width } // MARK: - BarLineScatterCandleBubbleChartDataProvider /// - Returns: The Transformer class that contains all matrices and is /// responsible for transforming values into pixels on the screen and /// backwards. public final func getTransformer(forAxis axis: YAxis.AxisDependency) -> Transformer { switch axis { case .left: return _leftAxisTransformer case .right: return _rightAxisTransformer } } public final func isInverted(axis: YAxis.AxisDependency) -> Bool { getAxis(axis).isInverted } /// The lowest x-index (value on the x-axis) that is still visible on he chart. open var lowestVisibleX: Double { var pt = CGPoint( x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom ) getTransformer(forAxis: .left).pixelToValues(&pt) return max(xAxis._axisMinimum, Double(pt.x)) } /// The highest x-index (value on the x-axis) that is still visible on the chart. open var highestVisibleX: Double { var pt = CGPoint( x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom ) getTransformer(forAxis: .left).pixelToValues(&pt) return min(xAxis._axisMaximum, Double(pt.x)) } }
30af9fc14604fc0bc90e24a3ce0b7d6d
36.830977
238
0.622832
false
false
false
false
radazzouz/firefox-ios
refs/heads/master
StorageTests/TestSQLiteHistoryRecommendations.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared @testable import Storage import Deferred import XCTest private let microsecondsPerMinute: UInt64 = 60_000_000 // 1000 * 1000 * 60 private let oneHourInMicroseconds: UInt64 = 60 * microsecondsPerMinute private let oneDayInMicroseconds: UInt64 = 24 * oneHourInMicroseconds class TestSQLiteHistoryRecommendations: XCTestCase { let files = MockFiles() /* * Verify that we return a non-recent history highlight if: * * 1. We haven't visited the site in the last 30 minutes * 2. We've only visited the site less than or equal to 3 times * 3. The site we visited has a non-empty title * */ func testHistoryHighlights() { let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let startTime = Date.nowMicroseconds() let oneHourAgo = startTime - oneHourInMicroseconds let fifteenMinutesAgo = startTime - 15 * microsecondsPerMinute /* * Site A: 1 visit, 1 hour ago = highlight * Site B: 1 visits, 15 minutes ago = non-highlight * Site C: 3 visits, 1 hour ago = highlight * Site D: 4 visits, 1 hour ago = non-highlight */ let siteA = Site(url: "http://siteA/", title: "A") let siteB = Site(url: "http://siteB/", title: "B") let siteC = Site(url: "http://siteC/", title: "C") let siteD = Site(url: "http://siteD/", title: "D") let siteVisitA1 = SiteVisit(site: siteA, date: oneHourAgo, type: .link) let siteVisitB1 = SiteVisit(site: siteB, date: fifteenMinutesAgo, type: .link) let siteVisitC1 = SiteVisit(site: siteC, date: oneHourAgo, type: .link) let siteVisitC2 = SiteVisit(site: siteC, date: oneHourAgo + 1000, type: .link) let siteVisitC3 = SiteVisit(site: siteC, date: oneHourAgo + 2000, type: .link) let siteVisitD1 = SiteVisit(site: siteD, date: oneHourAgo, type: .link) let siteVisitD2 = SiteVisit(site: siteD, date: oneHourAgo + 1000, type: .link) let siteVisitD3 = SiteVisit(site: siteD, date: oneHourAgo + 2000, type: .link) let siteVisitD4 = SiteVisit(site: siteD, date: oneHourAgo + 3000, type: .link) history.clearHistory().succeeded() history.addLocalVisit(siteVisitA1).succeeded() history.addLocalVisit(siteVisitB1).succeeded() history.addLocalVisit(siteVisitC1).succeeded() history.addLocalVisit(siteVisitC2).succeeded() history.addLocalVisit(siteVisitC3).succeeded() history.addLocalVisit(siteVisitD1).succeeded() history.addLocalVisit(siteVisitD2).succeeded() history.addLocalVisit(siteVisitD3).succeeded() history.addLocalVisit(siteVisitD4).succeeded() let highlights = history.getHighlights().value.successValue! XCTAssertEqual(highlights.count, 2) XCTAssertEqual(highlights[0]!.title, "A") XCTAssertEqual(highlights[1]!.title, "C") } /* * Verify that we return a bookmark highlight if: * * 1. Bookmark was last modified less than 3 days ago * 2. Bookmark has been visited at least 3 times * 3. Bookmark has a non-empty title * */ func testBookmarkHighlights() { let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let bookmarks = SQLiteBookmarkBufferStorage(db: db) let startTime = Date.nowMicroseconds() let oneHourAgo = startTime - oneHourInMicroseconds let fourDaysAgo = startTime - 4 * oneDayInMicroseconds let bookmarkA = BookmarkMirrorItem.bookmark("A", modified: oneHourAgo, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Menu Bookmarks", title: "A Bookmark", description: nil, URI: "http://bookmarkA/", tags: "", keyword: nil) let bookmarkB = BookmarkMirrorItem.bookmark("B", modified: fourDaysAgo, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Menu Bookmarks", title: "B Bookmark", description: nil, URI: "http://bookmarkB/", tags: "", keyword: nil) bookmarks.applyRecords([bookmarkA, bookmarkB]).succeeded() let bookmarkSiteA = Site(url: "http://bookmarkA/", title: "A Bookmark") let bookmarkVisitA1 = SiteVisit(site: bookmarkSiteA, date: oneHourAgo, type: .bookmark) let bookmarkVisitA2 = SiteVisit(site: bookmarkSiteA, date: oneHourAgo + 1000, type: .bookmark) let bookmarkVisitA3 = SiteVisit(site: bookmarkSiteA, date: oneHourAgo + 2000, type: .bookmark) let bookmarkSiteB = Site(url: "http://bookmarkB/", title: "B Bookmark") let bookmarkVisitB1 = SiteVisit(site: bookmarkSiteB, date: fourDaysAgo, type: .bookmark) let bookmarkVisitB2 = SiteVisit(site: bookmarkSiteB, date: fourDaysAgo + 1000, type: .bookmark) let bookmarkVisitB3 = SiteVisit(site: bookmarkSiteB, date: fourDaysAgo + 2000, type: .bookmark) let bookmarkVisitB4 = SiteVisit(site: bookmarkSiteB, date: fourDaysAgo + 3000, type: .bookmark) history.clearHistory().succeeded() history.addLocalVisit(bookmarkVisitA1).succeeded() history.addLocalVisit(bookmarkVisitA2).succeeded() history.addLocalVisit(bookmarkVisitA3).succeeded() history.addLocalVisit(bookmarkVisitB1).succeeded() history.addLocalVisit(bookmarkVisitB2).succeeded() history.addLocalVisit(bookmarkVisitB3).succeeded() history.addLocalVisit(bookmarkVisitB4).succeeded() let highlights = history.getHighlights().value.successValue! XCTAssertEqual(highlights.count, 1) XCTAssertEqual(highlights[0]!.title, "A Bookmark") } /* * Verify that we do not return a highlight if * its domain is in the blacklist * */ func testBlacklistHighlights() { let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let startTime = Date.nowMicroseconds() let oneHourAgo = startTime - oneHourInMicroseconds let fifteenMinutesAgo = startTime - 15 * microsecondsPerMinute /* * Site A: 1 visit, 1 hour ago = highlight that is on the blacklist * Site B: 1 visits, 15 minutes ago = non-highlight * Site C: 3 visits, 1 hour ago = highlight that is on the blacklist * Site D: 4 visits, 1 hour ago = non-highlight */ let siteA = Site(url: "http://www.google.com", title: "A") let siteB = Site(url: "http://siteB/", title: "B") let siteC = Site(url: "http://www.search.yahoo.com/", title: "C") let siteD = Site(url: "http://siteD/", title: "D") let siteVisitA1 = SiteVisit(site: siteA, date: oneHourAgo, type: .link) let siteVisitB1 = SiteVisit(site: siteB, date: fifteenMinutesAgo, type: .link) let siteVisitC1 = SiteVisit(site: siteC, date: oneHourAgo, type: .link) let siteVisitC2 = SiteVisit(site: siteC, date: oneHourAgo + 1000, type: .link) let siteVisitC3 = SiteVisit(site: siteC, date: oneHourAgo + 2000, type: .link) let siteVisitD1 = SiteVisit(site: siteD, date: oneHourAgo, type: .link) let siteVisitD2 = SiteVisit(site: siteD, date: oneHourAgo + 1000, type: .link) let siteVisitD3 = SiteVisit(site: siteD, date: oneHourAgo + 2000, type: .link) let siteVisitD4 = SiteVisit(site: siteD, date: oneHourAgo + 3000, type: .link) history.clearHistory().succeeded() history.addLocalVisit(siteVisitA1).succeeded() history.addLocalVisit(siteVisitB1).succeeded() history.addLocalVisit(siteVisitC1).succeeded() history.addLocalVisit(siteVisitC2).succeeded() history.addLocalVisit(siteVisitC3).succeeded() history.addLocalVisit(siteVisitD1).succeeded() history.addLocalVisit(siteVisitD2).succeeded() history.addLocalVisit(siteVisitD3).succeeded() history.addLocalVisit(siteVisitD4).succeeded() let highlights = history.getHighlights().value.successValue! XCTAssertEqual(highlights.count, 0) } /* * Verify that we return the most recent highlight per domain */ func testMostRecentUniqueDomainReturnedInHighlights() { let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let startTime = Date.nowMicroseconds() let oneHourAgo = startTime - oneHourInMicroseconds let twoHoursAgo = startTime - 2 * oneHourInMicroseconds /* * Site A: 1 visit, 1 hour ago = highlight * Site C: 2 visits, 2 hours ago = highlight with the same domain */ let siteA = Site(url: "http://www.foo.com/", title: "A") let siteC = Site(url: "http://m.foo.com/", title: "C") let siteVisitA1 = SiteVisit(site: siteA, date: oneHourAgo, type: .link) let siteVisitC1 = SiteVisit(site: siteC, date: twoHoursAgo, type: .link) let siteVisitC2 = SiteVisit(site: siteC, date: twoHoursAgo + 1000, type: .link) history.clearHistory().succeeded() history.addLocalVisit(siteVisitA1).succeeded() history.addLocalVisit(siteVisitC1).succeeded() history.addLocalVisit(siteVisitC2).succeeded() let highlights = history.getHighlights().value.successValue! XCTAssertEqual(highlights.count, 1) XCTAssertEqual(highlights[0]!.title, "A") } } class TestSQLiteHistoryRecommendationsPerf: XCTestCase { func testRecommendationPref() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let bookmarks = SQLiteBookmarkBufferStorage(db: db) let count = 500 history.clearHistory().value populateForRecommendationCalculations(history, bookmarks: bookmarks, historyCount: count, bookmarkCount: count) self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { history.getHighlights().value } self.stopMeasuring() } } } private func populateForRecommendationCalculations(_ history: SQLiteHistory, bookmarks: SQLiteBookmarkBufferStorage, historyCount: Int, bookmarkCount: Int) { let baseMillis: UInt64 = baseInstantInMillis - 20000 for i in 0..<historyCount { let site = Site(url: "http://s\(i)ite\(i)/foo", title: "A \(i)") site.guid = "abc\(i)def" history.insertOrUpdatePlace(site.asPlace(), modified: baseMillis).value for j in 0...20 { let visitTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i) + (1000 * j)) addVisitForSite(site, intoHistory: history, from: .local, atTime: visitTime) addVisitForSite(site, intoHistory: history, from: .remote, atTime: visitTime) } } let bookmarkItems: [BookmarkMirrorItem] = (0..<bookmarkCount).map { i in let modifiedTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i)) let bookmarkSite = Site(url: "http://bookmark-\(i)/", title: "\(i) Bookmark") bookmarkSite.guid = "bookmark-\(i)" addVisitForSite(bookmarkSite, intoHistory: history, from: .local, atTime: modifiedTime) addVisitForSite(bookmarkSite, intoHistory: history, from: .remote, atTime: modifiedTime) addVisitForSite(bookmarkSite, intoHistory: history, from: .local, atTime: modifiedTime) addVisitForSite(bookmarkSite, intoHistory: history, from: .remote, atTime: modifiedTime) return BookmarkMirrorItem.bookmark("http://bookmark-\(i)/", modified: modifiedTime, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Menu Bookmarks", title: "\(i) Bookmark", description: nil, URI: "http://bookmark-\(i)/", tags: "", keyword: nil) } bookmarks.applyRecords(bookmarkItems).succeeded() }
3624210e474dbb1e751ac1847a2afd67
45.109541
157
0.636754
false
false
false
false
lemberg/connfa-ios
refs/heads/master
Pods/SwiftDate/Sources/SwiftDate/Supports/Commons.swift
apache-2.0
1
// // DateFormatter.swift // SwiftDate // // Created by Daniele Margutti on 06/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation public extension DateFormatter { /// Return the local thread shared formatter initialized with the configuration of the region passed. /// /// - Parameters: /// - region: region used to pre-configure the cell. /// - format: optional format used to set the `dateFormat` property. /// - Returns: date formatter instance public static func sharedFormatter(forRegion region: Region?, format: String? = nil) -> DateFormatter { let name = "SwiftDate_\(NSStringFromClass(DateFormatter.self))" let formatter: DateFormatter = threadSharedObject(key: name, create: { return DateFormatter() }) if let region = region { formatter.timeZone = region.timeZone formatter.calendar = region.calendar formatter.locale = region.locale } formatter.dateFormat = (format ?? DateFormats.iso8601) return formatter } /// Returned number formatter instance shared along calling thread to format ordinal numbers. /// /// - Parameter locale: locale to set /// - Returns: number formatter instance @available(iOS 9.0, macOS 10.11, *) public static func sharedOrdinalNumberFormatter(locale: LocaleConvertible) -> NumberFormatter { var formatter: NumberFormatter? = nil let name = "SwiftDate_\(NSStringFromClass(NumberFormatter.self))" formatter = threadSharedObject(key: name, create: { return NumberFormatter() }) formatter!.numberStyle = .ordinal formatter!.locale = locale.toLocale() return formatter! } } /// This function create (if necessary) and return a thread singleton instance of the /// object you want. /// /// - Parameters: /// - key: identifier of the object. /// - create: create routine used the first time you are about to create the object in thread. /// - Returns: instance of the object for caller's thread. internal func threadSharedObject<T: AnyObject>(key: String, create: () -> T) -> T { if let cachedObj = Thread.current.threadDictionary[key] as? T { return cachedObj } else { let newObject = create() Thread.current .threadDictionary[key] = newObject return newObject } } /// Style used to format month, weekday, quarter symbols. /// Stand-alone properties are for use in places like calendar headers. /// Non-stand-alone properties are for use in context (for example, “Saturday, November 12th”). /// /// - `default`: Default formatter (ie. `4th quarter` for quarter, `April` for months and `Wednesday` for weekdays) /// - defaultStandalone: See `default`; See `short`; stand-alone properties are for use in places like calendar headers. /// - short: Short symbols (ie. `Jun` for months, `Fri` for weekdays, `Q1` for quarters). /// - veryShort: Very short symbols (ie. `J` for months, `F` for weekdays, for quarter it just return `short` variant). /// - standaloneShort: See `short`; stand-alone properties are for use in places like calendar headers. /// - standaloneVeryShort: See `veryShort`; stand-alone properties are for use in places like calendar headers. public enum SymbolFormatStyle { case `default` case defaultStandalone case short case veryShort case standaloneShort case standaloneVeryShort } /// Encapsulate the logic to use date format strings public struct DateFormats { /// This is the built-in list of all supported formats for auto-parsing of a string to a date. internal static let builtInAutoFormat: [String] = [ DateFormats.iso8601, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "h:mm:ss A", "h:mm A", "MM/dd/yyyy", "MMMM d, yyyy", "MMMM d, yyyy LT", "dddd, MMMM D, yyyy LT", "yyyyyy-MM-dd", "yyyy-MM-dd", "GGGG-[W]WW-E", "GGGG-[W]WW", "yyyy-ddd", "HH:mm:ss.SSSS", "HH:mm:ss", "HH:mm", "HH" ] /// This is the ordered list of all formats SwiftDate can use in order to attempt parsing a passaed /// date expressed as string. Evaluation is made in order; you can add or remove new formats as you wish. /// In order to reset the list call `resetAutoFormats()` function. public static var autoFormats: [String] = DateFormats.builtInAutoFormat /// Default ISO8601 format string public static let iso8601: String = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" /// Extended format public static let extended: String = "eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz" /// The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200" public static let altRSS: String = "d MMM yyyy HH:mm:ss ZZZ" /// The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200" public static let rss: String = "EEE, d MMM yyyy HH:mm:ss ZZZ" /// The http header formatted date "EEE, dd MM yyyy HH:mm:ss ZZZ" i.e. "Tue, 15 Nov 1994 12:45:26 GMT" public static let httpHeader: String = "EEE, dd MM yyyy HH:mm:ss ZZZ" /// A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy" public static let standard: String = "EEE MMM dd HH:mm:ss Z yyyy" /// SQL date format public static let sql: String = "yyyy-MM-dd'T'HH:mm:ss.SSSX" /// Reset the list of auto formats to the initial settings. public static func resetAutoFormats() { self.autoFormats = DateFormats.builtInAutoFormat } /// Parse a new string optionally passing the format in which is encoded. If no format is passed /// an attempt is made by cycling all the formats set in `autoFormats` property. /// /// - Parameters: /// - string: date expressed as string. /// - suggestedFormat: optional format of the date expressed by the string (set it if you can in order to optimize the parse task). /// - region: region in which the date is expressed. /// - Returns: parsed absolute `Date`, `nil` if parse fails. public static func parse(string: String, format: String?, region: Region) -> Date? { let formats = (format != nil ? [format!] : DateFormats.autoFormats) return DateFormats.parse(string: string, formats: formats, region: region) } public static func parse(string: String, formats: [String], region: Region) -> Date? { let formatter = DateFormatter.sharedFormatter(forRegion: region) var parsedDate: Date? = nil for format in formats { formatter.dateFormat = format formatter.locale = region.locale if let date = formatter.date(from: string) { parsedDate = date break } } return parsedDate } } // MARK: - Calendar Extension public extension Calendar.Component { internal static func toSet(_ src: [Calendar.Component]) -> Set<Calendar.Component> { var l: Set<Calendar.Component> = [] src.forEach { l.insert($0) } return l } internal var nsCalendarUnit: NSCalendar.Unit { switch self { case .era: return NSCalendar.Unit.era case .year: return NSCalendar.Unit.year case .month: return NSCalendar.Unit.month case .day: return NSCalendar.Unit.day case .hour: return NSCalendar.Unit.hour case .minute: return NSCalendar.Unit.minute case .second: return NSCalendar.Unit.second case .weekday: return NSCalendar.Unit.weekday case .weekdayOrdinal: return NSCalendar.Unit.weekdayOrdinal case .quarter: return NSCalendar.Unit.quarter case .weekOfMonth: return NSCalendar.Unit.weekOfMonth case .weekOfYear: return NSCalendar.Unit.weekOfYear case .yearForWeekOfYear: return NSCalendar.Unit.yearForWeekOfYear case .nanosecond: return NSCalendar.Unit.nanosecond case .calendar: return NSCalendar.Unit.calendar case .timeZone: return NSCalendar.Unit.timeZone } } } /// This define the weekdays for some functions. public enum WeekDay: Int { case sunday = 1 case monday = 2 case tuesday = 3 case wednesday = 4 case thursday = 5 case friday = 6 case saturday = 7 } /// Rounding mode for dates. /// Round off/up (ceil) or down (floor) target date. public enum RoundDateMode { case to5Mins case to10Mins case to30Mins case toMins(_: Int) case toCeil5Mins case toCeil10Mins case toCeil30Mins case toCeilMins(_: Int) case toFloor5Mins case toFloor10Mins case toFloor30Mins case toFloorMins(_: Int) } /// Related type enum to get derivated date from a receiver date. public enum DateRelatedType { case startOfDay case endOfDay case startOfWeek case endOfWeek case startOfMonth case endOfMonth case tomorrow case tomorrowAtStart case yesterday case yesterdayAtStart case nearestMinute(minute:Int) case nearestHour(hour:Int) case nextWeekday(_: WeekDay) case nextDSTDate case prevMonth case nextMonth case prevWeek case nextWeek case nextYear case prevYear case nextDSTTransition } public struct TimeCalculationOptions { /// Specifies the technique the search algorithm uses to find result public var matchingPolicy: Calendar.MatchingPolicy /// Specifies the behavior when multiple matches are found public var repeatedTimePolicy: Calendar.RepeatedTimePolicy /// Specifies the direction in time to search public var direction: Calendar.SearchDirection public init(matching: Calendar.MatchingPolicy = .nextTime, timePolicy: Calendar.RepeatedTimePolicy = .first, direction: Calendar.SearchDirection = .forward) { self.matchingPolicy = matching self.repeatedTimePolicy = timePolicy self.direction = direction } } //MARK: - compactMap for Swift 4.0 (not necessary > 4.0) #if swift(>=4.1) #else extension Collection { func compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { return try flatMap(transform) } } #endif
08c1d2d0793295e5581a69942a60a431
32.38676
134
0.723649
false
false
false
false
klwoon/TTGSnackbar
refs/heads/master
TTGSnackbar/TTGSnackbar.swift
mit
1
// // TTGSnackbar.swift // TTGSnackbar // // Created by zekunyan on 15/10/4. // Copyright © 2015年 tutuge. All rights reserved. // import UIKit import Darwin // MARK: - Enum /** Snackbar display duration types. - short: 1 second - middle: 3 seconds - long: 5 seconds - forever: Not dismiss automatically. Must be dismissed manually. */ @objc public enum TTGSnackbarDuration: Int { case short = 1 case middle = 3 case long = 5 case forever = 2147483647 // Must dismiss manually. } /** Snackbar animation types. - fadeInFadeOut: Fade in to show and fade out to dismiss. - slideFromBottomToTop: Slide from the bottom of screen to show and slide up to dismiss. - slideFromBottomBackToBottom: Slide from the bottom of screen to show and slide back to bottom to dismiss. - slideFromLeftToRight: Slide from the left to show and slide to rigth to dismiss. - slideFromRightToLeft: Slide from the right to show and slide to left to dismiss. - slideFromTopToBottom: Slide from the top of screen to show and slide down to dismiss. - slideFromTopBackToTop: Slide from the top of screen to show and slide back to top to dismiss. */ @objc public enum TTGSnackbarAnimationType: Int { case fadeInFadeOut case slideFromBottomToTop case slideFromBottomBackToBottom case slideFromLeftToRight case slideFromRightToLeft case slideFromTopToBottom case slideFromTopBackToTop } open class TTGSnackbar: UIView { // MARK: - Class property. /// Snackbar default frame fileprivate static let snackbarDefaultFrame: CGRect = CGRect(x: 0, y: 0, width: 320, height: 44) /// Snackbar min height fileprivate static var snackbarMinHeight: CGFloat = 44 @objc open dynamic var height: CGFloat = snackbarMinHeight { didSet { TTGSnackbar.snackbarMinHeight = height } } /// Snackbar icon imageView default width fileprivate static let snackbarIconImageViewWidth: CGFloat = 32 // MARK: - Typealias. /// Action callback closure definition. public typealias TTGActionBlock = (_ snackbar:TTGSnackbar) -> Void /// Dismiss callback closure definition. public typealias TTGDismissBlock = (_ snackbar:TTGSnackbar) -> Void /// Swipe gesture callback closure public typealias TTGSwipeBlock = (_ snackbar: TTGSnackbar, _ direction: UISwipeGestureRecognizerDirection) -> Void // MARK: - Public property. /// Tap callback @objc open dynamic var onTapBlock: TTGActionBlock? /// Swipe callback @objc open dynamic var onSwipeBlock: TTGSwipeBlock? /// A property to make the snackbar auto dismiss on Swipe Gesture @objc open dynamic var shouldDismissOnSwipe: Bool = false /// a property to enable left and right margin when using customContentView @objc open dynamic var shouldActivateLeftAndRightMarginOnCustomContentView: Bool = false /// Action callback. @objc open dynamic var actionBlock: TTGActionBlock? = nil /// Second action block @objc open dynamic var secondActionBlock: TTGActionBlock? = nil /// Dismiss callback. @objc open dynamic var dismissBlock: TTGDismissBlock? = nil /// Snackbar display duration. Default is Short - 1 second. @objc open dynamic var duration: TTGSnackbarDuration = TTGSnackbarDuration.short /// Snackbar animation type. Default is SlideFromBottomBackToBottom. @objc open dynamic var animationType: TTGSnackbarAnimationType = TTGSnackbarAnimationType.slideFromBottomBackToBottom /// Show and hide animation duration. Default is 0.3 @objc open dynamic var animationDuration: TimeInterval = 0.3 /// Corner radius: [0, height / 2]. Default is 4 @objc open dynamic var cornerRadius: CGFloat = 4 { didSet { if cornerRadius < 0 { cornerRadius = 0 } layer.cornerRadius = cornerRadius layer.masksToBounds = true } } /// Left margin. Default is 4 @objc open dynamic var leftMargin: CGFloat = 4 { didSet { leftMarginConstraint?.constant = leftMargin superview?.layoutIfNeeded() } } /// Right margin. Default is 4 @objc open dynamic var rightMargin: CGFloat = 4 { didSet { rightMarginConstraint?.constant = -rightMargin superview?.layoutIfNeeded() } } /// Bottom margin. Default is 4, only work when snackbar is at bottom @objc open dynamic var bottomMargin: CGFloat = 4 { didSet { bottomMarginConstraint?.constant = -bottomMargin superview?.layoutIfNeeded() } } /// Top margin. Default is 4, only work when snackbar is at top @objc open dynamic var topMargin: CGFloat = 4 { didSet { topMarginConstraint?.constant = topMargin superview?.layoutIfNeeded() } } /// Content inset. Default is (0, 4, 0, 4) @objc open dynamic var contentInset: UIEdgeInsets = UIEdgeInsets.init(top: 0, left: 4, bottom: 0, right: 4) { didSet { contentViewTopConstraint?.constant = contentInset.top contentViewBottomConstraint?.constant = -contentInset.bottom contentViewLeftConstraint?.constant = contentInset.left contentViewRightConstraint?.constant = -contentInset.right layoutIfNeeded() superview?.layoutIfNeeded() } } /// Main text shown on the snackbar. @objc open dynamic var message: String = "" { didSet { messageLabel.text = message } } /// Message text color. Default is white. @objc open dynamic var messageTextColor: UIColor = UIColor.white { didSet { messageLabel.textColor = messageTextColor } } /// Message text font. Default is Bold system font (14). @objc open dynamic var messageTextFont: UIFont = UIFont.boldSystemFont(ofSize: 14) { didSet { messageLabel.font = messageTextFont } } /// Message text alignment. Default is left @objc open dynamic var messageTextAlign: NSTextAlignment = .left { didSet { messageLabel.textAlignment = messageTextAlign } } /// Action button title. @objc open dynamic var actionText: String = "" { didSet { actionButton.setTitle(actionText, for: UIControlState()) } } /// Action button image. @objc open dynamic var actionIcon: UIImage? = nil { didSet { actionButton.setImage(actionIcon, for: UIControlState()) } } /// Second action button title. @objc open dynamic var secondActionText: String = "" { didSet { secondActionButton.setTitle(secondActionText, for: UIControlState()) } } /// Action button title color. Default is white. @objc open dynamic var actionTextColor: UIColor = UIColor.white { didSet { actionButton.setTitleColor(actionTextColor, for: UIControlState()) } } /// Second action button title color. Default is white. @objc open dynamic var secondActionTextColor: UIColor = UIColor.white { didSet { secondActionButton.setTitleColor(secondActionTextColor, for: UIControlState()) } } /// Action text font. Default is Bold system font (14). @objc open dynamic var actionTextFont: UIFont = UIFont.boldSystemFont(ofSize: 14) { didSet { actionButton.titleLabel?.font = actionTextFont } } /// Second action text font. Default is Bold system font (14). @objc open dynamic var secondActionTextFont: UIFont = UIFont.boldSystemFont(ofSize: 14) { didSet { secondActionButton.titleLabel?.font = secondActionTextFont } } /// Action button max width, min = 44 @objc open dynamic var actionMaxWidth: CGFloat = 64 { didSet { actionMaxWidth = actionMaxWidth < 44 ? 44 : actionMaxWidth actionButtonMaxWidthConstraint?.constant = actionButton.isHidden ? 0 : actionMaxWidth secondActionButtonMaxWidthConstraint?.constant = secondActionButton.isHidden ? 0 : actionMaxWidth layoutIfNeeded() } } /// Action button text number of lines. Default is 1 @objc open dynamic var actionTextNumberOfLines: Int = 1 { didSet { actionButton.titleLabel?.numberOfLines = actionTextNumberOfLines secondActionButton.titleLabel?.numberOfLines = actionTextNumberOfLines layoutIfNeeded() } } /// Icon image @objc open dynamic var icon: UIImage? = nil { didSet { iconImageView.image = icon } } /// Icon image content @objc open dynamic var iconContentMode: UIViewContentMode = .center { didSet { iconImageView.contentMode = iconContentMode } } /// Custom container view @objc open dynamic var containerView: UIView? /// Custom content view @objc open dynamic var customContentView: UIView? /// SeparateView background color @objc open dynamic var separateViewBackgroundColor: UIColor = UIColor.gray { didSet { separateView.backgroundColor = separateViewBackgroundColor } } /// ActivityIndicatorViewStyle @objc open dynamic var activityIndicatorViewStyle: UIActivityIndicatorViewStyle { get { return activityIndicatorView.activityIndicatorViewStyle } set { activityIndicatorView.activityIndicatorViewStyle = newValue } } /// ActivityIndicatorView color @objc open dynamic var activityIndicatorViewColor: UIColor { get { return activityIndicatorView.color ?? .white } set { activityIndicatorView.color = newValue } } /// Animation SpringWithDamping. Default is 0.7 @objc open dynamic var animationSpringWithDamping: CGFloat = 0.7 /// Animation initialSpringVelocity @objc open dynamic var animationInitialSpringVelocity: CGFloat = 5 // MARK: - Private property. fileprivate var contentView: UIView! fileprivate var iconImageView: UIImageView! fileprivate var messageLabel: UILabel! fileprivate var separateView: UIView! fileprivate var actionButton: UIButton! fileprivate var secondActionButton: UIButton! fileprivate var activityIndicatorView: UIActivityIndicatorView! /// Timer to dismiss the snackbar. fileprivate var dismissTimer: Timer? = nil // Constraints. fileprivate var leftMarginConstraint: NSLayoutConstraint? = nil fileprivate var rightMarginConstraint: NSLayoutConstraint? = nil fileprivate var bottomMarginConstraint: NSLayoutConstraint? = nil fileprivate var topMarginConstraint: NSLayoutConstraint? = nil // Only work when top animation type fileprivate var centerXConstraint: NSLayoutConstraint? = nil // Content constraints. fileprivate var iconImageViewWidthConstraint: NSLayoutConstraint? = nil fileprivate var actionButtonMaxWidthConstraint: NSLayoutConstraint? = nil fileprivate var secondActionButtonMaxWidthConstraint: NSLayoutConstraint? = nil fileprivate var contentViewLeftConstraint: NSLayoutConstraint? = nil fileprivate var contentViewRightConstraint: NSLayoutConstraint? = nil fileprivate var contentViewTopConstraint: NSLayoutConstraint? = nil fileprivate var contentViewBottomConstraint: NSLayoutConstraint? = nil // MARK: - Deinit deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Default init public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override init(frame: CGRect) { super.init(frame: TTGSnackbar.snackbarDefaultFrame) configure() } /** Default init - returns: TTGSnackbar instance */ public init() { super.init(frame: TTGSnackbar.snackbarDefaultFrame) configure() } /** Show a single message like a Toast. - parameter message: Message text. - parameter duration: Duration type. - returns: TTGSnackbar instance */ public init(message: String, duration: TTGSnackbarDuration) { super.init(frame: TTGSnackbar.snackbarDefaultFrame) self.duration = duration self.message = message configure() } /** Show a customContentView like a Toast - parameter customContentView: Custom View to be shown. - parameter duration: Duration type. - returns: TTGSnackbar instance */ public init(customContentView: UIView, duration: TTGSnackbarDuration) { super.init(frame: TTGSnackbar.snackbarDefaultFrame) self.duration = duration self.customContentView = customContentView configure() } /** Show a message with action button. - parameter message: Message text. - parameter duration: Duration type. - parameter actionText: Action button title. - parameter actionBlock: Action callback closure. - returns: TTGSnackbar instance */ public init(message: String, duration: TTGSnackbarDuration, actionText: String, actionBlock: @escaping TTGActionBlock) { super.init(frame: TTGSnackbar.snackbarDefaultFrame) self.duration = duration self.message = message self.actionText = actionText self.actionBlock = actionBlock configure() } /** Show a custom message with action button. - parameter message: Message text. - parameter duration: Duration type. - parameter actionText: Action button title. - parameter messageFont: Message label font. - parameter actionButtonFont: Action button font. - parameter actionBlock: Action callback closure. - returns: TTGSnackbar instance */ public init(message: String, duration: TTGSnackbarDuration, actionText: String, messageFont: UIFont, actionTextFont: UIFont, actionBlock: @escaping TTGActionBlock) { super.init(frame: TTGSnackbar.snackbarDefaultFrame) self.duration = duration self.message = message self.actionText = actionText self.actionBlock = actionBlock self.messageTextFont = messageFont self.actionTextFont = actionTextFont configure() } // Override open override func layoutSubviews() { super.layoutSubviews() if messageLabel.preferredMaxLayoutWidth != messageLabel.frame.size.width { messageLabel.preferredMaxLayoutWidth = messageLabel.frame.size.width setNeedsLayout() } super.layoutSubviews() } } // MARK: - Show methods. public extension TTGSnackbar { /** Show the snackbar. */ public func show() { // Only show once if superview != nil { return } // Create dismiss timer dismissTimer = Timer.init(timeInterval: (TimeInterval)(duration.rawValue), target: self, selector: #selector(dismiss), userInfo: nil, repeats: false) RunLoop.main.add(dismissTimer!, forMode: .commonModes) // Show or hide action button iconImageView.isHidden = icon == nil actionButton.isHidden = (actionIcon == nil || actionText.isEmpty) == false || actionBlock == nil secondActionButton.isHidden = secondActionText.isEmpty || secondActionBlock == nil separateView.isHidden = actionButton.isHidden iconImageViewWidthConstraint?.constant = iconImageView.isHidden ? 0 : TTGSnackbar.snackbarIconImageViewWidth actionButtonMaxWidthConstraint?.constant = actionButton.isHidden ? 0 : actionMaxWidth secondActionButtonMaxWidthConstraint?.constant = secondActionButton.isHidden ? 0 : actionMaxWidth // Content View let finalContentView = customContentView ?? contentView finalContentView?.translatesAutoresizingMaskIntoConstraints = false addSubview(finalContentView!) contentViewTopConstraint = NSLayoutConstraint.init(item: finalContentView!, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: contentInset.top) contentViewBottomConstraint = NSLayoutConstraint.init(item: finalContentView!, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: -contentInset.bottom) contentViewLeftConstraint = NSLayoutConstraint.init(item: finalContentView!, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: contentInset.left) contentViewRightConstraint = NSLayoutConstraint.init(item: finalContentView!, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -contentInset.right) addConstraints([contentViewTopConstraint!, contentViewBottomConstraint!, contentViewLeftConstraint!, contentViewRightConstraint!]) // Get super view to show if let superView = containerView ?? UIApplication.shared.delegate?.window ?? UIApplication.shared.keyWindow { superView.addSubview(self) // Left margin constraint if #available(iOS 11.0, *) { leftMarginConstraint = NSLayoutConstraint.init( item: self, attribute: .left, relatedBy: .equal, toItem: superView.safeAreaLayoutGuide, attribute: .left, multiplier: 1, constant: leftMargin) } else { leftMarginConstraint = NSLayoutConstraint.init( item: self, attribute: .left, relatedBy: .equal, toItem: superView, attribute: .left, multiplier: 1, constant: leftMargin) } // Right margin constraint if #available(iOS 11.0, *) { rightMarginConstraint = NSLayoutConstraint.init( item: self, attribute: .right, relatedBy: .equal, toItem: superView.safeAreaLayoutGuide, attribute: .right, multiplier: 1, constant: -rightMargin) } else { rightMarginConstraint = NSLayoutConstraint.init( item: self, attribute: .right, relatedBy: .equal, toItem: superView, attribute: .right, multiplier: 1, constant: -rightMargin) } // Bottom margin constraint if #available(iOS 11.0, *) { bottomMarginConstraint = NSLayoutConstraint.init( item: self, attribute: .bottom, relatedBy: .equal, toItem: superView.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1, constant: -bottomMargin) } else { bottomMarginConstraint = NSLayoutConstraint.init( item: self, attribute: .bottom, relatedBy: .equal, toItem: superView, attribute: .bottom, multiplier: 1, constant: -bottomMargin) } // Top margin constraint if #available(iOS 11.0, *) { topMarginConstraint = NSLayoutConstraint.init( item: self, attribute: .top, relatedBy: .equal, toItem: superView.safeAreaLayoutGuide, attribute: .top, multiplier: 1, constant: topMargin) } else { topMarginConstraint = NSLayoutConstraint.init( item: self, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1, constant: topMargin) } // Center X constraint centerXConstraint = NSLayoutConstraint.init( item: self, attribute: .centerX, relatedBy: .equal, toItem: superView, attribute: .centerX, multiplier: 1, constant: 0) // Min height constraint let minHeightConstraint = NSLayoutConstraint.init( item: self, attribute: .height, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: TTGSnackbar.snackbarMinHeight) // Avoid the "UIView-Encapsulated-Layout-Height" constraint conflicts // http://stackoverflow.com/questions/25059443/what-is-nslayoutconstraint-uiview-encapsulated-layout-height-and-how-should-i leftMarginConstraint?.priority = UILayoutPriority(999) rightMarginConstraint?.priority = UILayoutPriority(999) topMarginConstraint?.priority = UILayoutPriority(999) bottomMarginConstraint?.priority = UILayoutPriority(999) centerXConstraint?.priority = UILayoutPriority(999) // Add constraints superView.addConstraint(leftMarginConstraint!) superView.addConstraint(rightMarginConstraint!) superView.addConstraint(bottomMarginConstraint!) superView.addConstraint(topMarginConstraint!) superView.addConstraint(centerXConstraint!) superView.addConstraint(minHeightConstraint) // Active or deactive topMarginConstraint?.isActive = false // For top animation leftMarginConstraint?.isActive = self.shouldActivateLeftAndRightMarginOnCustomContentView ? true : customContentView == nil rightMarginConstraint?.isActive = self.shouldActivateLeftAndRightMarginOnCustomContentView ? true : customContentView == nil centerXConstraint?.isActive = customContentView != nil // Show showWithAnimation() } else { fatalError("TTGSnackbar needs a keyWindows to display.") } } /** Show. */ fileprivate func showWithAnimation() { var animationBlock: (() -> Void)? = nil let superViewWidth = (superview?.frame)!.width let snackbarHeight = systemLayoutSizeFitting(.init(width: superViewWidth - leftMargin - rightMargin, height: TTGSnackbar.snackbarMinHeight)).height switch animationType { case .fadeInFadeOut: alpha = 0.0 // Animation animationBlock = { self.alpha = 1.0 } case .slideFromBottomBackToBottom, .slideFromBottomToTop: bottomMarginConstraint?.constant = snackbarHeight case .slideFromLeftToRight: leftMarginConstraint?.constant = leftMargin - superViewWidth rightMarginConstraint?.constant = -rightMargin - superViewWidth bottomMarginConstraint?.constant = -bottomMargin centerXConstraint?.constant = -superViewWidth case .slideFromRightToLeft: leftMarginConstraint?.constant = leftMargin + superViewWidth rightMarginConstraint?.constant = -rightMargin + superViewWidth bottomMarginConstraint?.constant = -bottomMargin centerXConstraint?.constant = superViewWidth case .slideFromTopBackToTop, .slideFromTopToBottom: bottomMarginConstraint?.isActive = false topMarginConstraint?.isActive = true topMarginConstraint?.constant = -snackbarHeight } // Update init state superview?.layoutIfNeeded() // Final state bottomMarginConstraint?.constant = -bottomMargin topMarginConstraint?.constant = topMargin leftMarginConstraint?.constant = leftMargin rightMarginConstraint?.constant = -rightMargin centerXConstraint?.constant = 0 UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: animationSpringWithDamping, initialSpringVelocity: animationInitialSpringVelocity, options: .allowUserInteraction, animations: { () -> Void in animationBlock?() self.superview?.layoutIfNeeded() }, completion: nil) } } // MARK: - Dismiss methods. public extension TTGSnackbar { /** Dismiss the snackbar manually. */ @objc public func dismiss() { // On main thread DispatchQueue.main.async { () -> Void in self.dismissAnimated(true) } } /** Dismiss. - parameter animated: If dismiss with animation. */ fileprivate func dismissAnimated(_ animated: Bool) { // If the dismiss timer is nil, snackbar is dismissing or not ready to dismiss. if dismissTimer == nil { return } invalidDismissTimer() activityIndicatorView.stopAnimating() let superViewWidth = (superview?.frame)!.width let snackbarHeight = frame.size.height var safeAreaInsets = UIEdgeInsets.zero if #available(iOS 11.0, *) { safeAreaInsets = self.superview?.safeAreaInsets ?? UIEdgeInsets.zero; } if !animated { dismissBlock?(self) removeFromSuperview() return } var animationBlock: (() -> Void)? = nil switch animationType { case .fadeInFadeOut: animationBlock = { self.alpha = 0.0 } case .slideFromBottomBackToBottom: bottomMarginConstraint?.constant = snackbarHeight + safeAreaInsets.bottom case .slideFromBottomToTop: animationBlock = { self.alpha = 0.0 } bottomMarginConstraint?.constant = -snackbarHeight - bottomMargin case .slideFromLeftToRight: leftMarginConstraint?.constant = leftMargin + superViewWidth + safeAreaInsets.left rightMarginConstraint?.constant = -rightMargin + superViewWidth - safeAreaInsets.right centerXConstraint?.constant = superViewWidth case .slideFromRightToLeft: leftMarginConstraint?.constant = leftMargin - superViewWidth + safeAreaInsets.left rightMarginConstraint?.constant = -rightMargin - superViewWidth - safeAreaInsets.right centerXConstraint?.constant = -superViewWidth case .slideFromTopToBottom: topMarginConstraint?.isActive = false bottomMarginConstraint?.isActive = true bottomMarginConstraint?.constant = snackbarHeight + safeAreaInsets.bottom case .slideFromTopBackToTop: topMarginConstraint?.constant = -snackbarHeight - safeAreaInsets.top } setNeedsLayout() UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: animationSpringWithDamping, initialSpringVelocity: animationInitialSpringVelocity, options: .curveEaseIn, animations: { () -> Void in animationBlock?() self.superview?.layoutIfNeeded() }) { (finished) -> Void in self.dismissBlock?(self) self.removeFromSuperview() } } /** Invalid the dismiss timer. */ fileprivate func invalidDismissTimer() { dismissTimer?.invalidate() dismissTimer = nil } } // MARK: - Init configuration. private extension TTGSnackbar { func configure() { // Clear subViews for subView in subviews { subView.removeFromSuperview() } // Notification NotificationCenter.default.addObserver(self, selector: #selector(onScreenRotateNotification), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor.init(white: 0, alpha: 0.8) layer.cornerRadius = cornerRadius layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale layer.shadowOpacity = 0.4 layer.shadowRadius = 2 layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 2) contentView = UIView() contentView.translatesAutoresizingMaskIntoConstraints = false contentView.frame = TTGSnackbar.snackbarDefaultFrame contentView.backgroundColor = UIColor.clear iconImageView = UIImageView() iconImageView.translatesAutoresizingMaskIntoConstraints = false iconImageView.backgroundColor = UIColor.clear iconImageView.contentMode = iconContentMode contentView.addSubview(iconImageView) messageLabel = UILabel() messageLabel.translatesAutoresizingMaskIntoConstraints = false messageLabel.textColor = UIColor.white messageLabel.font = messageTextFont messageLabel.backgroundColor = UIColor.clear messageLabel.lineBreakMode = .byTruncatingTail messageLabel.numberOfLines = 0; messageLabel.textAlignment = .left messageLabel.text = message contentView.addSubview(messageLabel) actionButton = UIButton() actionButton.translatesAutoresizingMaskIntoConstraints = false actionButton.backgroundColor = UIColor.clear actionButton.contentEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 4) actionButton.titleLabel?.font = actionTextFont actionButton.titleLabel?.adjustsFontSizeToFitWidth = true actionButton.titleLabel?.numberOfLines = actionTextNumberOfLines actionButton.setTitle(actionText, for: UIControlState()) actionButton.setTitleColor(actionTextColor, for: UIControlState()) actionButton.addTarget(self, action: #selector(doAction(_:)), for: .touchUpInside) contentView.addSubview(actionButton) secondActionButton = UIButton() secondActionButton.translatesAutoresizingMaskIntoConstraints = false secondActionButton.backgroundColor = UIColor.clear secondActionButton.contentEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 4) secondActionButton.titleLabel?.font = secondActionTextFont secondActionButton.titleLabel?.adjustsFontSizeToFitWidth = true secondActionButton.titleLabel?.numberOfLines = actionTextNumberOfLines secondActionButton.setTitle(secondActionText, for: UIControlState()) secondActionButton.setTitleColor(secondActionTextColor, for: UIControlState()) secondActionButton.addTarget(self, action: #selector(doAction(_:)), for: .touchUpInside) contentView.addSubview(secondActionButton) separateView = UIView() separateView.translatesAutoresizingMaskIntoConstraints = false separateView.backgroundColor = separateViewBackgroundColor contentView.addSubview(separateView) activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white) activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false activityIndicatorView.stopAnimating() contentView.addSubview(activityIndicatorView) // Add constraints let hConstraints = NSLayoutConstraint.constraints( withVisualFormat: "H:|-0-[iconImageView]-2-[messageLabel]-2-[seperateView(0.5)]-2-[actionButton(>=44@999)]-0-[secondActionButton(>=44@999)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["iconImageView": iconImageView, "messageLabel": messageLabel, "seperateView": separateView, "actionButton": actionButton, "secondActionButton": secondActionButton]) let vConstraintsForIconImageView = NSLayoutConstraint.constraints( withVisualFormat: "V:|-2-[iconImageView]-2-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["iconImageView": iconImageView]) let vConstraintsForMessageLabel = NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[messageLabel]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["messageLabel": messageLabel]) let vConstraintsForSeperateView = NSLayoutConstraint.constraints( withVisualFormat: "V:|-4-[seperateView]-4-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["seperateView": separateView]) let vConstraintsForActionButton = NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[actionButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["actionButton": actionButton]) let vConstraintsForSecondActionButton = NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[secondActionButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["secondActionButton": secondActionButton]) iconImageViewWidthConstraint = NSLayoutConstraint.init( item: iconImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: TTGSnackbar.snackbarIconImageViewWidth) actionButtonMaxWidthConstraint = NSLayoutConstraint.init( item: actionButton, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: actionMaxWidth) secondActionButtonMaxWidthConstraint = NSLayoutConstraint.init( item: secondActionButton, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: actionMaxWidth) let vConstraintForActivityIndicatorView = NSLayoutConstraint.init( item: activityIndicatorView, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0) let hConstraintsForActivityIndicatorView = NSLayoutConstraint.constraints( withVisualFormat: "H:[activityIndicatorView]-2-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["activityIndicatorView": activityIndicatorView]) iconImageView.addConstraint(iconImageViewWidthConstraint!) actionButton.addConstraint(actionButtonMaxWidthConstraint!) secondActionButton.addConstraint(secondActionButtonMaxWidthConstraint!) contentView.addConstraints(hConstraints) contentView.addConstraints(vConstraintsForIconImageView) contentView.addConstraints(vConstraintsForMessageLabel) contentView.addConstraints(vConstraintsForSeperateView) contentView.addConstraints(vConstraintsForActionButton) contentView.addConstraints(vConstraintsForSecondActionButton) contentView.addConstraint(vConstraintForActivityIndicatorView) contentView.addConstraints(hConstraintsForActivityIndicatorView) messageLabel.setContentHuggingPriority(UILayoutPriority(1000), for: .vertical) messageLabel.setContentCompressionResistancePriority(UILayoutPriority(1000), for: .vertical) actionButton.setContentHuggingPriority(UILayoutPriority(998), for: .horizontal) actionButton.setContentCompressionResistancePriority(UILayoutPriority(999), for: .horizontal) secondActionButton.setContentHuggingPriority(UILayoutPriority(998), for: .horizontal) secondActionButton.setContentCompressionResistancePriority(UILayoutPriority(999), for: .horizontal) // add gesture recognizers // tap gesture self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.didTapSelf))) self.isUserInteractionEnabled = true // swipe gestures [UISwipeGestureRecognizerDirection.up, .down, .left, .right].forEach { (direction) in let gesture = UISwipeGestureRecognizer(target: self, action: #selector(self.didSwipeSelf(_:))) gesture.direction = direction self.addGestureRecognizer(gesture) } } } // MARK: - Actions private extension TTGSnackbar { /** Action button callback - parameter button: action button */ @objc func doAction(_ button: UIButton) { // Call action block first button == actionButton ? actionBlock?(self) : secondActionBlock?(self) // Show activity indicator if duration == .forever && actionButton.isHidden == false { actionButton.isHidden = true secondActionButton.isHidden = true separateView.isHidden = true activityIndicatorView.isHidden = false activityIndicatorView.startAnimating() } else { dismissAnimated(true) } } /// tap callback @objc func didTapSelf() { self.onTapBlock?(self) } /** Action button callback - parameter gesture: the gesture that is sent to the user */ @objc func didSwipeSelf(_ gesture: UISwipeGestureRecognizer) { self.onSwipeBlock?(self, gesture.direction) if self.shouldDismissOnSwipe { if gesture.direction == .right { self.animationType = .slideFromLeftToRight } else if gesture.direction == .left { self.animationType = .slideFromRightToLeft } else if gesture.direction == .up { self.animationType = .slideFromTopBackToTop } else if gesture.direction == .down { self.animationType = .slideFromTopBackToTop } self.dismiss() } } } // MARK: - Rotation notification private extension TTGSnackbar { @objc func onScreenRotateNotification() { messageLabel.preferredMaxLayoutWidth = messageLabel.frame.size.width layoutIfNeeded() } }
344040eae34532a6cba0a8703a687f83
38.103935
184
0.648999
false
false
false
false
AlwaysRightInstitute/SwiftSockets
refs/heads/master
Sources/SwiftyEchoDaemon/EchoServer.swift
mit
1
// // EchoServer.swift // SwiftSockets // // Created by Helge Hess on 6/13/14. // Copyright (c) 2014-2017 Always Right Institute. All rights reserved. // import SwiftSockets import Dispatch #if os(Linux) // for sockaddr_in import Glibc #else import Darwin #endif class EchoServer { let port : Int var listenSocket : PassiveSocketIPv4? let lockQueue = DispatchQueue(label: "com.ari.socklock") var openSockets = [FileDescriptor:ActiveSocket<sockaddr_in>](minimumCapacity: 8) var appLog : ((String) -> Void)? init(port: Int) { self.port = port } func log(string s: String) { if let lcb = appLog { lcb(s) } else { print(s) } } func start() { listenSocket = PassiveSocketIPv4(address: sockaddr_in(port: port)) if listenSocket == nil || !listenSocket!.isValid { // neat, eh? ;-) log(string: "ERROR: could not create socket ...") return } log(string: "Listen socket \(listenSocket as Optional)") let queue = DispatchQueue.global() // Note: capturing self here _ = listenSocket!.listen(queue: queue, backlog: 5) { newSock in self.log(string: "got new sock: \(newSock) nio=\(newSock.isNonBlocking)") newSock.isNonBlocking = true self.lockQueue.async { // Note: we need to keep the socket around!! self.openSockets[newSock.fd] = newSock } self.send(welcome: newSock) _ = newSock .onRead { self.handleIncomingData(socket: $0, expectedCount: $1) } .onClose { ( fd: FileDescriptor ) -> Void in // we need to consume the return value to give peace to the closure self.lockQueue.async { [unowned self] in _ = self.openSockets.removeValue(forKey: fd) } } } log(string: "Started running listen socket \(listenSocket as Optional)") } func stop() { listenSocket?.close() listenSocket = nil } let welcomeText = "\r\n" + " /----------------------------------------------------\\\r\n" + " | Welcome to the Always Right Institute! |\r\n" + " | I am an echo server with a zlight twist. |\r\n" + " | Just type something and I'll shout it back at you. |\r\n" + " \\----------------------------------------------------/\r\n" + "\r\nTalk to me Dave!\r\n" + "> " func send<T: TextOutputStream>(welcome sockI: T) { var sock = sockI // cannot use 'var' in parameters anymore? // Hm, how to use print(), this doesn't work for me: // print(s, target: sock) // (just writes the socket as a value, likely a tuple) sock.write(welcomeText) } func handleIncomingData<T>(socket s: ActiveSocket<T>, expectedCount: Int) { // remove from openSockets if all has been read repeat { // FIXME: This currently continues to read garbage if I just close the // Terminal which hosts telnet. Even with sigpipe off. let (count, block, errno) = s.read() if count < 0 && errno == EWOULDBLOCK { break } if count < 1 { log(string: "EOF \(socket) (err=\(errno))") s.close() return } logReceived(block: block, length: count) // maps the whole block. asyncWrite does not accept slices, // can we add this? // (should adopt sth like IndexedCollection<T>?) /* ptr has no map ;-) FIXME: add an extension 'mapWithCount'? let mblock = block.map({ $0 == 83 ? 90 : ($0 == 115 ? 122 : $0) }) */ var mblock = [CChar](repeating: 42, count: count + 1) for i in 0..<count { let c = block[i] mblock[i] = c == 83 ? 90 : (c == 115 ? 122 : c) } mblock[count] = 0 _ = s.asyncWrite(buffer: mblock, length: count) } while (true) s.write("> ") } func logReceived(block b: UnsafePointer<CChar>, length: Int) { let k = String(validatingUTF8: b) var s = k ?? "Could not process result block \(b) length \(length)" // Hu, now this is funny. In b5 \r\n is one Character (but 2 unicodeScalars) #if swift(>=3.2) let suffix = String(s.suffix(2)) #else let suffix = String(s.characters.suffix(2)) #endif if suffix == "\r\n" { let to = s.index(before: s.endIndex) #if swift(>=4.0) s = String(s[s.startIndex..<to]) #else s = s[s.startIndex..<to] #endif } log(string: "read string: \(s)") } final let alwaysRight = "Yes, indeed!" }
33fb237307853d71e7d04eb4257cf8d1
27.239264
80
0.556159
false
false
false
false
lpniuniu/bookmark
refs/heads/master
bookmark/bookmark/BookListViewController/BookListTableView.swift
mit
1
// // BookListTableView.swift // bookmark // // Created by FanFamily on 16/12/14. // Copyright © 2016年 niuniu. All rights reserved. // import UIKit import SnapKit import Bulb import SWTableViewCell import RealmSwift import Crashlytics // what she say class BookListDidSelectSignal: BulbBoolSignal { override class func description() -> String { return "BookList is selected"; } } class BookListDidDeselectSignal: BulbBoolSignal { override class func description() -> String { return "BookList is not selected"; } } class BookListTableView: UITableView, UITableViewDelegate, UITableViewDataSource, SWTableViewCellDelegate { let cellIdentifier:String = "book_list_cellIdentifier" var selectIndexPath:IndexPath? = nil override init(frame:CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) delegate = self dataSource = self separatorStyle = .none register(BookCell.self, forCellReuseIdentifier: cellIdentifier) showsVerticalScrollIndicator = false weak var weakSelf = self Bulb.bulbGlobal().register(BookSavedSignal.signalDefault()) { (data:Any?, identifier2Signal:[String : BulbSignal]?) -> Bool in weakSelf?.isHidden = false weakSelf?.reloadData() if weakSelf?.selectIndexPath != nil { weakSelf?.selectRow(at: weakSelf?.selectIndexPath, animated: true, scrollPosition: .none) } if let book = data as? BookData { Answers.logCustomEvent(withName: "addbook", customAttributes: ["name" : book.name]) } return true } Bulb.bulbGlobal().register(BookChangePageValue.signalDefault()) { (book:Any?, identifier2Signal:[String : BulbSignal]?) -> Bool in weakSelf?.reloadData() if weakSelf?.selectIndexPath != nil { weakSelf?.selectRow(at: weakSelf?.selectIndexPath, animated: true, scrollPosition: .none) } return true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let realm = try! Realm() return realm.objects(BookData.self).filter("done == false").count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:BookCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! BookCell cell.configureFlatCell(with: UIColor.white, selectedColor: UIColor.greenSea(), roundingCorners:.allCorners) cell.cornerRadius = 5.0 cell.separatorHeight = 20.0 cell.backgroundColor = backgroundColor cell.rightUtilityButtons = rightButton() as NSArray as? [Any] cell.delegate = self let realm = try! Realm() if let imageUrl = realm.objects(BookData.self).filter("done == false")[indexPath.row].photoUrl { let url = URL(string: imageUrl) if (url?.scheme == "http" || url?.scheme == "https") { cell.bookImageView.kf.setImage(with: url) } else { let doc = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first let photoPath = doc?.appendingPathComponent("photos") cell.bookImageView.image = UIImage(contentsOfFile: (photoPath?.appendingPathComponent((url?.path)!).path)!) } } cell.nameLabel.text = realm.objects(BookData.self).filter("done == false")[indexPath.row].name cell.pageLabel.text = "\(realm.objects(BookData.self).filter("done == false")[indexPath.row].pageCurrent)/\(realm.objects(BookData.self).filter("done == false")[indexPath.row].pageTotal)" return cell } func swipeableTableViewCell(_ cell: SWTableViewCell!, didTriggerRightUtilityButtonWith index: Int) { if index == 0 { let realm = try! Realm() let bookData = realm.objects(BookData.self).filter("done == false")[(indexPath(for: cell)?.row)!] try! realm.write({ bookData.done = true bookData.doneDate = Date() }) deleteRows(at:[indexPath(for: cell)!], with: .fade) Bulb.bulbGlobal().fire(BookListDidDeselectSignal.signalDefault(), data:nil) // 加入日历 let now = Date() let result = realm.objects(BookReadDateData.self).filter("date == %@", now.zeroOfDate) guard result.count == 0 else { return } let readDate = BookReadDateData() readDate.date = now.zeroOfDate try! realm.write({ realm.add(readDate) }) } else if index == 1 { let deleteConfirmAlert = UIAlertController(title: "即将删除这本书,是否确认", message: "", preferredStyle: .alert) deleteConfirmAlert.view.tintColor = UIColor.greenSea() let confirmAction = UIAlertAction(title: "确认", style: .default, handler: { (action:UIAlertAction) in let realm = try! Realm() let object = realm.objects(BookData.self)[(self.indexPath(for: cell)?.row)!] let doc = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first let photoPath = doc?.appendingPathComponent("photos") try! FileManager.default.removeItem(at: (photoPath?.appendingPathComponent(object.photoUrl!))!) try! realm.write({ realm.delete(object) }) self.deleteRows(at:[self.indexPath(for: cell)!], with: .fade) Bulb.bulbGlobal().fire(BookListDidDeselectSignal.signalDefault(), data:nil) }) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (action:UIAlertAction) in }) deleteConfirmAlert.addAction(confirmAction) deleteConfirmAlert.addAction(cancelAction) UIApplication.shared.keyWindow?.rootViewController?.present(deleteConfirmAlert, animated: true, completion: { }) } } func rightButton() -> NSMutableArray { let buttons:NSMutableArray = [] buttons.sw_addUtilityButton(with: UIColor.turquoise(), title: "阅完") buttons.sw_addUtilityButton(with: UIColor.red, title: "删除") return buttons } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectIndexPath = indexPath let realm = try! Realm() Bulb.bulbGlobal().fire(BookListDidSelectSignal.signalDefault(), data: realm.objects(BookData.self).filter("done == false")[indexPath.row]) } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { selectIndexPath = nil let realm = try! Realm() Bulb.bulbGlobal().fire(BookListDidDeselectSignal.signalDefault(), data: realm.objects(BookData.self).filter("done == false")[indexPath.row]) } }
7fceba932715dd7a6e8be0b6b8eae449
41.016667
195
0.614306
false
false
false
false
neonichu/emoji-search-keyboard
refs/heads/master
Keyboard/CatboardBanner.swift
bsd-3-clause
1
// // CatboardBanner.swift // TastyImitationKeyboard // // Created by Alexei Baboulevitch on 10/5/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit /* This is the demo banner. The banner is needed so that the top row popups have somewhere to go. Might as well fill it with something (or leave it blank if you like.) */ class CatboardBanner: ExtraView { var catSwitch: UISwitch = UISwitch() var catLabel: UILabel = UILabel() required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) { super.init(globalColors: globalColors, darkMode: darkMode, solidColorMode: solidColorMode) self.addSubview(self.catSwitch) self.addSubview(self.catLabel) self.catSwitch.on = NSUserDefaults.standardUserDefaults().boolForKey(kCatTypeEnabled) self.catSwitch.transform = CGAffineTransformMakeScale(0.75, 0.75) self.catSwitch.addTarget(self, action: Selector("respondToSwitch"), forControlEvents: UIControlEvents.ValueChanged) self.updateAppearance() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setNeedsLayout() { super.setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews() self.catSwitch.center = self.center self.catLabel.center = self.center self.catLabel.frame.origin = CGPointMake(self.catSwitch.frame.origin.x + self.catSwitch.frame.width + 8, self.catLabel.frame.origin.y) } func respondToSwitch() { NSUserDefaults.standardUserDefaults().setBool(self.catSwitch.on, forKey: kCatTypeEnabled) self.updateAppearance() } func updateAppearance() { if self.catSwitch.on { self.catLabel.text = "😺" self.catLabel.alpha = 1 } else { self.catLabel.text = "🐱" self.catLabel.alpha = 0.5 } self.catLabel.sizeToFit() } }
ba5d0c3a7fe5e303c92b6ef95d370d75
29.865672
142
0.652321
false
false
false
false
Darkkrye/DKDetailsParallax
refs/heads/master
DKDetailsParallax/Cells/FlatDarkTheme/FlatDarkSimpleDescriptionCell.swift
bsd-3-clause
1
// // FlatDarkSimpleDescriptionCell.swift // iOSeries // // Created by Pierre on 15/01/2017. // Copyright © 2017 Pierre Boudon. All rights reserved. // import UIKit /// FlatDarkSimpleDescriptionCell class open class FlatDarkSimpleDescriptionCell: UITableViewCell { /// MARK: - Private Constants /// Cell default height public static let defaultHeight: CGFloat = 50 /// MARK: - Private Variables /// Cell primary color public var primaryColor = UIColor.white /// Cell secondary color public var secondaryColor = UIColor.gray /// MARK: - IBOutlets /// Title Label @IBOutlet public weak var titleLabel: UILabel! /// Content Label @IBOutlet public weak var contentLabel: UILabel! /// MARK: - IBActions /// MARK: - "Default" Methods /// Override function awakeFromNib override open func awakeFromNib() { super.awakeFromNib() /* Initialization code */ self.titleLabel.text = self.titleLabel.text?.uppercased() self.titleLabel.textColor = self.secondaryColor self.contentLabel.textColor = self.primaryColor } /// Override function setSelected /// /// - Parameters: /// - selected: Bool - Selected value /// - animated: Bool - Animated value override open func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) /* Configure the view for the selected state */ } /* Use this function instead of property */ /// Set the title. Use this function instead of property /// /// - Parameter text: String - The text for the title open func setTitleText(text: String) { self.titleLabel.text = text.uppercased() } /// MARK: - Delegates /// MARK: - Personnal Delegates /// MARK: - Personnal Methods /// Default constructor for the cell /// /// - Parameters: /// - withPrimaryColor: UIColor? - The primary color /// - andSecondaryColor: UIColor? - The secondary color /// - Returns: FlatDarkSimpleDescriptionCell - The created cell open static func simpleDescriptionCell(withPrimaryColor: UIColor?, andSecondaryColor: UIColor?) -> FlatDarkSimpleDescriptionCell { /* Call other constructor with default value */ return simpleDescriptionCell(withPrimaryColor: withPrimaryColor, andSecondaryColor: andSecondaryColor, withoutTitle: false, withoutContent: false) } /// Complex constructor for the cell /// /// - Parameters: /// - withPrimaryColor: UIColor? - The primary color /// - andSecondaryColor: UIColor? - The secondary color /// - withoutTitle: Bool - If you don't want this item /// - withoutContent: Bool - If you don't want this item /// - Returns: FlatLightSimpleDescriptionCell open static func simpleDescriptionCell(withPrimaryColor: UIColor?, andSecondaryColor: UIColor?, withoutTitle: Bool, withoutContent: Bool) -> FlatDarkSimpleDescriptionCell { /* Retrieve cell */ let nibs = DKDetailsParallax.bundle()?.loadNibNamed("FlatDarkSimpleDescriptionCell", owner: self, options: nil) let cell: FlatDarkSimpleDescriptionCell = nibs![0] as! FlatDarkSimpleDescriptionCell cell.selectionStyle = .none /* Set colors */ if let p = withPrimaryColor { cell.primaryColor = p } if let s = andSecondaryColor { cell.secondaryColor = s } if withoutTitle { /* Hide title label */ cell.titleLabel.isHidden = true } if withoutContent { /* Hide content label */ cell.contentLabel.isHidden = true } return cell } }
5542ef98a0a5fe3d87e4138844d2b711
31.453782
176
0.630502
false
false
false
false
blstream/AugmentedSzczecin_iOS
refs/heads/master
AugmentedSzczecin/AugmentedSzczecin/ASSearchViewController.swift
apache-2.0
1
// // ASSearchViewController.swift // AugmentedSzczecin // // Created by Patronage on 16.04.2015. // Copyright (c) 2015 BLStream. All rights reserved. // import UIKit import CoreData class ASSearchViewController: UITableViewController, UISearchResultsUpdating, NSFetchedResultsControllerDelegate { var resultSearchController = UISearchController() lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "ASPOI") let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] let frc = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: ASData.sharedInstance.mainContext!, sectionNameKeyPath: "ASPOI.id", cacheName: nil) frc.delegate = self return frc }() override func viewDidLoad() { super.viewDidLoad() self.resultSearchController = ({ let controller = UISearchController(searchResultsController: nil) controller.searchResultsUpdater = self controller.dimsBackgroundDuringPresentation = false controller.searchBar.sizeToFit() self.tableView.tableHeaderView = controller.searchBar return controller })() self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: Selector("dismissViewController")) self.tableView.reloadData() } func dismissViewController() { self.dismissViewControllerAnimated(true, completion: nil) } override func viewDidAppear(animated: Bool) { } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if let sections = fetchedResultsController.sections { return sections.count } return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController.sections { let currentSection = sections[section] as! NSFetchedResultsSectionInfo return currentSection.numberOfObjects } return 0 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let sections = fetchedResultsController.sections { let currentSection = sections[section] as! NSFetchedResultsSectionInfo return currentSection.name } return nil } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ASSearchCell", forIndexPath: indexPath) as! UITableViewCell let poi = fetchedResultsController.objectAtIndexPath(indexPath) as! ASPOI cell.textLabel?.text = poi.name cell.detailTextLabel?.text = poi.tag return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("ShowDetailSegue", sender: fetchedResultsController.objectAtIndexPath(indexPath)) } func updateSearchResultsForSearchController(searchController: UISearchController) { if (searchController.searchBar.text != "") { var predicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text) fetchedResultsController.fetchRequest.predicate = predicate fetchedResultsController.fetchRequest.fetchLimit = 25 } else { fetchedResultsController.fetchRequest.predicate = nil } self.tableView.reloadData() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "ShowDetailSegue") { var destination = segue.destinationViewController as! ASPointDetailViewController destination.POI = sender as? ASPOI } } }
0a6bffa01b11506b8f4c6dd540db311e
34.825
171
0.662168
false
false
false
false
tanweirush/DGElasticPullToRefresh
refs/heads/master
DGElasticPullToRefresh/DGElasticPullToRefreshView.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015 Danil Gontovnik 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 // MARK: - // MARK: DGElasticPullToRefreshState public enum DGElasticPullToRefreshState: Int { case Stopped case Dragging case AnimatingBounce case Loading case AnimatingToStopped func isAnyOf(values: [DGElasticPullToRefreshState]) -> Bool { return values.contains({ $0 == self }) } } // MARK: - // MARK: DGElasticPullToRefreshView public class DGElasticPullToRefreshView: UIView { // MARK: - // MARK: Vars private var _state: DGElasticPullToRefreshState = .Stopped private(set) var state: DGElasticPullToRefreshState { get { return _state } set { let previousValue = state _state = newValue if previousValue == .Dragging && newValue == .AnimatingBounce { loadingView?.startAnimating() animateBounce() } else if previousValue == .Stopped && newValue == .AnimatingBounce { loadingView?.setPullProgress(1.0) loadingView?.startAnimating() animateBounce() } else if newValue == .Loading && actionHandler != nil { actionHandler() } else if newValue == .AnimatingToStopped { resetScrollViewContentInset(shouldAddObserverWhenFinished: true, animated: true, completion: { [weak self] () -> () in self?.state = .Stopped }) } else if newValue == .Stopped { loadingView?.stopLoading() } } } private var originalContentInsetTop: CGFloat = 0.0 { didSet { layoutSubviews() } } private let shapeLayer = CAShapeLayer() private var displayLink: CADisplayLink! var actionHandler: (() -> Void)! var loadingView: DGElasticPullToRefreshLoadingView? { willSet { loadingView?.removeFromSuperview() if let newValue = newValue { addSubview(newValue) } } } var observing: Bool = false { didSet { guard let scrollView = scrollView() else { return } if observing { scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentOffset) scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset) scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.Frame) scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.PanGestureRecognizerState) } else { scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentOffset) scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset) scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.Frame) scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.PanGestureRecognizerState) } } } var fillColor: UIColor = .clearColor() { didSet { shapeLayer.fillColor = fillColor.CGColor } } // MARK: Views private let bounceAnimationHelperView = UIView() private let cControlPointView = UIView() private let l1ControlPointView = UIView() private let l2ControlPointView = UIView() private let l3ControlPointView = UIView() private let r1ControlPointView = UIView() private let r2ControlPointView = UIView() private let r3ControlPointView = UIView() // MARK: - // MARK: Constructors init() { super.init(frame: CGRect.zero) displayLink = CADisplayLink(target: self, selector: Selector("displayLinkTick")) displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) displayLink.paused = true shapeLayer.backgroundColor = UIColor.clearColor().CGColor shapeLayer.fillColor = UIColor.blackColor().CGColor shapeLayer.actions = ["path" : NSNull(), "position" : NSNull(), "bounds" : NSNull()] layer.addSublayer(shapeLayer) addSubview(bounceAnimationHelperView) addSubview(cControlPointView) addSubview(l1ControlPointView) addSubview(l2ControlPointView) addSubview(l3ControlPointView) addSubview(r1ControlPointView) addSubview(r2ControlPointView) addSubview(r3ControlPointView) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("applicationWillEnterForeground"), name: UIApplicationWillEnterForegroundNotification, object: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - deinit { observing = false NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - // MARK: Observer override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == DGElasticPullToRefreshConstants.KeyPaths.ContentOffset { if let newContentOffsetY = change?[NSKeyValueChangeNewKey]?.CGPointValue.y, let scrollView = scrollView() { if state.isAnyOf([.Loading, .AnimatingToStopped]) && newContentOffsetY < -scrollView.contentInset.top { scrollView.dg_stopScrollingAnimation() scrollView.contentOffset.y = -scrollView.contentInset.top } else { scrollViewDidChangeContentOffset(dragging: scrollView.dragging) } layoutSubviews() } } else if keyPath == DGElasticPullToRefreshConstants.KeyPaths.ContentInset { if let newContentInsetTop = change?[NSKeyValueChangeNewKey]?.UIEdgeInsetsValue().top { originalContentInsetTop = newContentInsetTop } } else if keyPath == DGElasticPullToRefreshConstants.KeyPaths.Frame { layoutSubviews() } else if keyPath == DGElasticPullToRefreshConstants.KeyPaths.PanGestureRecognizerState { if let gestureState = scrollView()?.panGestureRecognizer.state where gestureState.dg_isAnyOf([.Ended, .Cancelled, .Failed]) { scrollViewDidChangeContentOffset(dragging: false) } } } // MARK: - // MARK: Notifications func applicationWillEnterForeground() { if state == .Loading { layoutSubviews() } } // MARK: - // MARK: Methods (Public) private func scrollView() -> UIScrollView? { return superview as? UIScrollView } func stopLoading() { // Prevent stop close animation if state == .AnimatingToStopped { return } state = .AnimatingToStopped } func startLoading() { //Only Stopped can StartLoading if state != .Stopped { return } state = .AnimatingBounce } // MARK: Methods (Private) private func isAnimating() -> Bool { return state.isAnyOf([.AnimatingBounce, .AnimatingToStopped]) } private func actualContentOffsetY() -> CGFloat { guard let scrollView = scrollView() else { return 0.0 } return max(-scrollView.contentInset.top - scrollView.contentOffset.y, 0) } private func currentHeight() -> CGFloat { guard let scrollView = scrollView() else { return 0.0 } return max(-originalContentInsetTop - scrollView.contentOffset.y, 0) } private func currentWaveHeight() -> CGFloat { return min(bounds.height / 3.0 * 1.6, DGElasticPullToRefreshConstants.WaveMaxHeight) } private func currentPath() -> CGPath { let width: CGFloat = scrollView()?.bounds.width ?? 0.0 let bezierPath = UIBezierPath() let animating = isAnimating() bezierPath.moveToPoint(CGPoint(x: 0.0, y: 0.0)) bezierPath.addLineToPoint(CGPoint(x: 0.0, y: l3ControlPointView.dg_center(animating).y)) bezierPath.addCurveToPoint(l1ControlPointView.dg_center(animating), controlPoint1: l3ControlPointView.dg_center(animating), controlPoint2: l2ControlPointView.dg_center(animating)) bezierPath.addCurveToPoint(r1ControlPointView.dg_center(animating), controlPoint1: cControlPointView.dg_center(animating), controlPoint2: r1ControlPointView.dg_center(animating)) bezierPath.addCurveToPoint(r3ControlPointView.dg_center(animating), controlPoint1: r1ControlPointView.dg_center(animating), controlPoint2: r2ControlPointView.dg_center(animating)) bezierPath.addLineToPoint(CGPoint(x: width, y: 0.0)) bezierPath.closePath() return bezierPath.CGPath } private func scrollViewDidChangeContentOffset(dragging dragging: Bool) { let offsetY = actualContentOffsetY() if state == .Stopped && dragging { state = .Dragging } else if state == .Dragging && dragging == false { if offsetY >= DGElasticPullToRefreshConstants.MinOffsetToPull { state = .AnimatingBounce scrollView()?.dg_stopScrollingAnimation() } else { state = .Stopped } } else if state.isAnyOf([.Dragging, .Stopped]) { let pullProgress: CGFloat = offsetY / DGElasticPullToRefreshConstants.MinOffsetToPull loadingView?.setPullProgress(pullProgress) } } private func resetScrollViewContentInset(shouldAddObserverWhenFinished shouldAddObserverWhenFinished: Bool, animated: Bool, completion: (() -> ())?) { guard let scrollView = scrollView() else { return } var contentInset = scrollView.contentInset contentInset.top = originalContentInsetTop if state == .AnimatingBounce { contentInset.top += currentHeight() } else if state == .Loading { contentInset.top += DGElasticPullToRefreshConstants.LoadingContentInset } scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset) let animationBlock = { scrollView.contentInset = contentInset } let completionBlock = { () -> Void in if shouldAddObserverWhenFinished { scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset) } completion?() } if animated { startDisplayLink() UIView.animateWithDuration(0.4, animations: animationBlock, completion: { _ in self.stopDisplayLink() completionBlock() }) } else { animationBlock() completionBlock() } } private func animateBounce() { guard let scrollView = scrollView() else { return } resetScrollViewContentInset(shouldAddObserverWhenFinished: false, animated: false, completion: nil) let centerY = DGElasticPullToRefreshConstants.LoadingContentInset let duration = 0.9 scrollView.scrollEnabled = false startDisplayLink() scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentOffset) scrollView.dg_removeObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentInset) UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.43, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in self.cControlPointView.center.y = centerY self.l1ControlPointView.center.y = centerY self.l2ControlPointView.center.y = centerY self.l3ControlPointView.center.y = centerY self.r1ControlPointView.center.y = centerY self.r2ControlPointView.center.y = centerY self.r3ControlPointView.center.y = centerY }, completion: { _ in self.stopDisplayLink() self.resetScrollViewContentInset(shouldAddObserverWhenFinished: true, animated: false, completion: nil) scrollView.dg_addObserver(self, forKeyPath: DGElasticPullToRefreshConstants.KeyPaths.ContentOffset) scrollView.scrollEnabled = true self.state = .Loading }) bounceAnimationHelperView.center = CGPoint(x: 0.0, y: originalContentInsetTop + currentHeight()) UIView.animateWithDuration(duration * 0.4, animations: { () -> Void in self.bounceAnimationHelperView.center = CGPoint(x: 0.0, y: self.originalContentInsetTop + DGElasticPullToRefreshConstants.LoadingContentInset) }, completion: nil) } // MARK: - // MARK: CADisplayLink private func startDisplayLink() { displayLink.paused = false } private func stopDisplayLink() { displayLink.paused = true } func displayLinkTick() { let width = bounds.width var height: CGFloat = 0.0 if state == .AnimatingBounce { guard let scrollView = scrollView() else { return } scrollView.contentInset.top = bounceAnimationHelperView.dg_center(isAnimating()).y scrollView.contentOffset.y = -scrollView.contentInset.top height = scrollView.contentInset.top - originalContentInsetTop frame = CGRect(x: 0.0, y: -height - 1.0, width: width, height: height) } else if state == .AnimatingToStopped { height = actualContentOffsetY() } shapeLayer.frame = CGRect(x: 0.0, y: 0.0, width: width, height: height) shapeLayer.path = currentPath() layoutLoadingView() } // MARK: - // MARK: Layout private func layoutLoadingView() { let width = bounds.width let height: CGFloat = bounds.height let loadingViewSize: CGFloat = DGElasticPullToRefreshConstants.LoadingViewSize let minOriginY = (DGElasticPullToRefreshConstants.LoadingContentInset - loadingViewSize) / 2.0 let originY: CGFloat = max(min((height - loadingViewSize) / 2.0, minOriginY), 0.0) loadingView?.frame = CGRect(x: (width - loadingViewSize) / 2.0, y: originY, width: loadingViewSize, height: loadingViewSize) loadingView?.maskLayer.frame = convertRect(shapeLayer.frame, toView: loadingView) loadingView?.maskLayer.path = shapeLayer.path } override public func layoutSubviews() { super.layoutSubviews() if let scrollView = scrollView() where state != .AnimatingBounce { let width = scrollView.bounds.width let height = currentHeight() frame = CGRect(x: 0.0, y: -height, width: width, height: height) if state.isAnyOf([.Loading, .AnimatingToStopped]) { cControlPointView.center = CGPoint(x: width / 2.0, y: height) l1ControlPointView.center = CGPoint(x: 0.0, y: height) l2ControlPointView.center = CGPoint(x: 0.0, y: height) l3ControlPointView.center = CGPoint(x: 0.0, y: height) r1ControlPointView.center = CGPoint(x: width, y: height) r2ControlPointView.center = CGPoint(x: width, y: height) r3ControlPointView.center = CGPoint(x: width, y: height) } else { let locationX = scrollView.panGestureRecognizer.locationInView(scrollView).x let waveHeight = currentWaveHeight() let baseHeight = bounds.height - waveHeight let minLeftX = min((locationX - width / 2.0) * 0.28, 0.0) let maxRightX = max(width + (locationX - width / 2.0) * 0.28, width) let leftPartWidth = locationX - minLeftX let rightPartWidth = maxRightX - locationX cControlPointView.center = CGPoint(x: locationX , y: baseHeight + waveHeight * 1.36) l1ControlPointView.center = CGPoint(x: minLeftX + leftPartWidth * 0.71, y: baseHeight + waveHeight * 0.64) l2ControlPointView.center = CGPoint(x: minLeftX + leftPartWidth * 0.44, y: baseHeight) l3ControlPointView.center = CGPoint(x: minLeftX, y: baseHeight) r1ControlPointView.center = CGPoint(x: maxRightX - rightPartWidth * 0.71, y: baseHeight + waveHeight * 0.64) r2ControlPointView.center = CGPoint(x: maxRightX - (rightPartWidth * 0.44), y: baseHeight) r3ControlPointView.center = CGPoint(x: maxRightX, y: baseHeight) } shapeLayer.frame = CGRect(x: 0.0, y: 0.0, width: width, height: height) shapeLayer.path = currentPath() layoutLoadingView() } } }
86ba074ab9c082245620a83d4a846308
40.671946
187
0.637114
false
false
false
false
crashoverride777/SwiftyAds
refs/heads/master
Sources/Public/SwiftyAds.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015-2022 Dominik Ringler // // 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 GoogleMobileAds import UserMessagingPlatform /** SwiftyAds A concret class implementation of SwiftAdsType to display ads from Google AdMob. */ public final class SwiftyAds: NSObject { // MARK: - Static Properties /// The shared SwiftyAds instance. public static let shared = SwiftyAds() // MARK: - Properties private let mobileAds: GADMobileAds private let interstitialAdIntervalTracker: SwiftyAdsIntervalTrackerType private let rewardedInterstitialAdIntervalTracker: SwiftyAdsIntervalTrackerType private var configuration: SwiftyAdsConfiguration? private var environment: SwiftyAdsEnvironment = .production private var requestBuilder: SwiftyAdsRequestBuilderType? private var mediationConfigurator: SwiftyAdsMediationConfiguratorType? private var interstitialAd: SwiftyAdsInterstitialType? private var rewardedAd: SwiftyAdsRewardedType? private var rewardedInterstitialAd: SwiftyAdsRewardedInterstitialType? private var nativeAd: SwiftyAdsNativeType? private var consentManager: SwiftyAdsConsentManagerType? private var disabled = false private var hasConsent: Bool { switch consentStatus { case .notRequired, .obtained: return true default: return false } } // MARK: - Initialization private override init() { mobileAds = .sharedInstance() interstitialAdIntervalTracker = SwiftyAdsIntervalTracker() rewardedInterstitialAdIntervalTracker = SwiftyAdsIntervalTracker() super.init() } } // MARK: - SwiftyAdsType extension SwiftyAds: SwiftyAdsType { /// The current consent status. /// /// - Warning: /// Returns .notRequired if consent has been disabled via SwiftyAds.plist isUMPDisabled entry. public var consentStatus: SwiftyAdsConsentStatus { consentManager?.consentStatus ?? .notRequired } /// Returns true if configured for child directed treatment or nil if ignored (COPPA). public var isTaggedForChildDirectedTreatment: Bool? { configuration?.isTaggedForChildDirectedTreatment } /// Returns true if configured for under age of consent (GDPR). public var isTaggedForUnderAgeOfConsent: Bool { configuration?.isTaggedForUnderAgeOfConsent ?? false } /// Check if interstitial ad is ready to be displayed. public var isInterstitialAdReady: Bool { interstitialAd?.isReady ?? false } /// Check if rewarded ad is ready to be displayed. public var isRewardedAdReady: Bool { rewardedAd?.isReady ?? false } /// Check if rewarded interstitial ad is ready to be displayed. public var isRewardedInterstitialAdReady: Bool { rewardedInterstitialAd?.isReady ?? false } /// Returns true if ads have been disabled. public var isDisabled: Bool { disabled } // MARK: Configure /// Configure SwiftyAds /// /// - parameter viewController: The view controller that will present the consent alert if needed. /// - parameter environment: The environment for ads to be displayed. /// - parameter requestBuilder: The GADRequest builder. /// - parameter mediationConfigurator: Optional configurator to update mediation networks COPPA/GDPR consent status. /// - parameter consentStatusDidChange: A handler that will be called everytime the consent status has changed. /// - parameter completion: A completion handler that will return the current consent status after the initial consent flow has finished. /// /// - Warning: /// Returns .notRequired in the completion handler if consent has been disabled via SwiftyAds.plist isUMPDisabled entry. public func configure(from viewController: UIViewController, for environment: SwiftyAdsEnvironment, requestBuilder: SwiftyAdsRequestBuilderType, mediationConfigurator: SwiftyAdsMediationConfiguratorType?, consentStatusDidChange: @escaping (SwiftyAdsConsentStatus) -> Void, completion: @escaping SwiftyAdsConsentResultHandler) { // Update configuration for selected environment let configuration: SwiftyAdsConfiguration switch environment { case .production: configuration = .production() case .development(let testDeviceIdentifiers, let consentConfiguration): configuration = .debug(isUMPDisabled: consentConfiguration.isDisabled) mobileAds.requestConfiguration.testDeviceIdentifiers = [GADSimulatorID].compactMap { $0 } + testDeviceIdentifiers } self.configuration = configuration self.environment = environment self.requestBuilder = requestBuilder self.mediationConfigurator = mediationConfigurator // Create ads if let interstitialAdUnitId = configuration.interstitialAdUnitId { interstitialAd = SwiftyAdsInterstitial( environment: environment, adUnitId: interstitialAdUnitId, request: requestBuilder.build ) } if let rewardedAdUnitId = configuration.rewardedAdUnitId { rewardedAd = SwiftyAdsRewarded( environment: environment, adUnitId: rewardedAdUnitId, request: requestBuilder.build ) } if let rewardedInterstitialAdUnitId = configuration.rewardedInterstitialAdUnitId { rewardedInterstitialAd = SwiftyAdsRewardedInterstitial( environment: environment, adUnitId: rewardedInterstitialAdUnitId, request: requestBuilder.build ) } if let nativeAdUnitId = configuration.nativeAdUnitId { nativeAd = SwiftyAdsNative( environment: environment, adUnitId: nativeAdUnitId, request: requestBuilder.build ) } // If UMP SDK is disabled skip consent flow completely if let isUMPDisabled = configuration.isUMPDisabled, isUMPDisabled { /// If consent flow was skipped we need to update COPPA settings. updateCOPPA(for: configuration, mediationConfigurator: mediationConfigurator) /// If consent flow was skipped we can start `GADMobileAds` and preload ads. startMobileAdsSDK { [weak self] in guard let self = self else { return } self.loadAds() completion(.success(.notRequired)) } return } // Create consent manager let consentManager = SwiftyAdsConsentManager( consentInformation: .sharedInstance, environment: environment, isTaggedForUnderAgeOfConsent: configuration.isTaggedForUnderAgeOfConsent ?? false, consentStatusDidChange: consentStatusDidChange ) self.consentManager = consentManager // Request initial consent requestInitialConsent(from: viewController, consentManager: consentManager) { [weak self] result in guard let self = self else { return } switch result { case .success(let consentStatus): /// Once initial consent flow has finished we need to update COPPA settings. self.updateCOPPA(for: configuration, mediationConfigurator: mediationConfigurator) /// Once initial consent flow has finished and consentStatus is not `.notRequired` /// we need to update GDPR settings. if consentStatus != .notRequired { self.updateGDPR( for: configuration, mediationConfigurator: mediationConfigurator, consentStatus: consentStatus ) } /// Once initial consent flow has finished we can start `GADMobileAds` and preload ads. self.startMobileAdsSDK { [weak self] in guard let self = self else { return } self.loadAds() completion(result) } case .failure: completion(result) } } } // MARK: Consent /// Under GDPR users must be able to change their consent at any time. /// /// - parameter viewController: The view controller that will present the consent form. /// - parameter completion: A completion handler that will return the updated consent status. public func askForConsent(from viewController: UIViewController, completion: @escaping SwiftyAdsConsentResultHandler) { guard let consentManager = consentManager else { completion(.failure(SwiftyAdsError.consentManagerNotAvailable)) return } DispatchQueue.main.async { consentManager.requestUpdate { result in switch result { case .success: DispatchQueue.main.async { consentManager.showForm(from: viewController) { [weak self] result in guard let self = self else { return } // If consent form was used to update consentStatus // we need to update GDPR settings if case .success(let newConsentStatus) = result, let configuration = self.configuration { self.updateGDPR( for: configuration, mediationConfigurator: self.mediationConfigurator, consentStatus: newConsentStatus ) } completion(result) } } case .failure: completion(result) } } } } // MARK: Banner Ads /// Make banner ad /// /// - parameter viewController: The view controller that will present the ad. /// - parameter adUnitIdType: The adUnitId type for the ad, either plist or custom. /// - parameter position: The position of the banner. /// - parameter animation: The animation of the banner. /// - parameter onOpen: An optional callback when the banner was presented. /// - parameter onClose: An optional callback when the banner was dismissed or removed. /// - parameter onError: An optional callback when an error has occurred. /// - parameter onWillPresentScreen: An optional callback when the banner was tapped and is about to present a screen. /// - parameter onWillDismissScreen: An optional callback when the banner is about dismiss a presented screen. /// - parameter onDidDismissScreen: An optional callback when the banner did dismiss a presented screen. /// - returns SwiftyAdsBannerType to show, hide or remove the prepared banner ad. public func makeBannerAd(in viewController: UIViewController, adUnitIdType: SwiftyAdsAdUnitIdType, position: SwiftyAdsBannerAdPosition, animation: SwiftyAdsBannerAdAnimation, onOpen: (() -> Void)?, onClose: (() -> Void)?, onError: ((Error) -> Void)?, onWillPresentScreen: (() -> Void)?, onWillDismissScreen: (() -> Void)?, onDidDismissScreen: (() -> Void)?) -> SwiftyAdsBannerType? { guard !isDisabled else { return nil } guard hasConsent else { return nil } var adUnitId: String? { switch adUnitIdType { case .plist: return configuration?.bannerAdUnitId case .custom(let id): if case .development = environment { return configuration?.bannerAdUnitId } return id } } guard let validAdUnitId = adUnitId else { onError?(SwiftyAdsError.bannerAdMissingAdUnitId) return nil } let bannerAd = SwiftyAdsBanner( environment: environment, isDisabled: { [weak self] in self?.isDisabled ?? false }, hasConsent: { [weak self] in self?.hasConsent ?? true }, request: { [weak self] in self?.requestBuilder?.build() ?? GADRequest() } ) bannerAd.prepare( withAdUnitId: validAdUnitId, in: viewController, position: position, animation: animation, onOpen: onOpen, onClose: onClose, onError: onError, onWillPresentScreen: onWillPresentScreen, onWillDismissScreen: onWillDismissScreen, onDidDismissScreen: onDidDismissScreen ) return bannerAd } // MARK: Interstitial Ads /// Show interstitial ad /// /// - parameter viewController: The view controller that will present the ad. /// - parameter interval: The interval of when to show the ad, e.g every 4th time the method is called. Set to nil to always show. /// - parameter onOpen: An optional callback when the ad was presented. /// - parameter onClose: An optional callback when the ad was dismissed. /// - parameter onError: An optional callback when an error has occurred. public func showInterstitialAd(from viewController: UIViewController, afterInterval interval: Int?, onOpen: (() -> Void)?, onClose: (() -> Void)?, onError: ((Error) -> Void)?) { guard !isDisabled else { return } guard hasConsent else { return } if let interval = interval { guard interstitialAdIntervalTracker.canShow(forInterval: interval) else { return } } interstitialAd?.show( from: viewController, onOpen: onOpen, onClose: onClose, onError: onError ) } // MARK: Rewarded Ads /// Show rewarded ad /// /// - parameter viewController: The view controller that will present the ad. /// - parameter onOpen: An optional callback when the ad was presented. /// - parameter onClose: An optional callback when the ad was dismissed. /// - parameter onError: An optional callback when an error has occurred. /// - parameter onNotReady: An optional callback when the ad was not ready. /// - parameter onReward: A callback when the reward has been granted. /// /// - Warning: /// Rewarded ads may be non-skippable and should only be displayed after pressing a dedicated button. public func showRewardedAd(from viewController: UIViewController, onOpen: (() -> Void)?, onClose: (() -> Void)?, onError: ((Error) -> Void)?, onNotReady: (() -> Void)?, onReward: @escaping (NSDecimalNumber) -> Void) { guard hasConsent else { return } rewardedAd?.show( from: viewController, onOpen: onOpen, onClose: onClose, onError: onError, onNotReady: onNotReady, onReward: onReward ) } /// Show rewarded interstitial ad /// /// - parameter viewController: The view controller that will present the ad. /// - parameter interval: The interval of when to show the ad, e.g every 4th time the method is called. Set to nil to always show. /// - parameter onOpen: An optional callback when the ad was presented. /// - parameter onClose: An optional callback when the ad was dismissed. /// - parameter onError: An optional callback when an error has occurred. /// - parameter onReward: A callback when the reward has been granted. /// /// - Warning: /// Before displaying a rewarded interstitial ad to users, you must present the user with an intro screen that provides clear reward messaging /// and an option to skip the ad before it starts. /// https://support.google.com/admob/answer/9884467 public func showRewardedInterstitialAd(from viewController: UIViewController, afterInterval interval: Int?, onOpen: (() -> Void)?, onClose: (() -> Void)?, onError: ((Error) -> Void)?, onReward: @escaping (NSDecimalNumber) -> Void) { guard !isDisabled else { return } guard hasConsent else { return } if let interval = interval { guard rewardedInterstitialAdIntervalTracker.canShow(forInterval: interval) else { return } } rewardedInterstitialAd?.show( from: viewController, onOpen: onOpen, onClose: onClose, onError: onError, onReward: onReward ) } // MARK: Native Ads /// Load native ad /// /// - parameter viewController: The view controller that will load the native ad. /// - parameter adUnitIdType: The adUnitId type for the ad, either plist or custom. /// - parameter loaderOptions: The loader options for GADMultipleAdsAdLoaderOptions, single or multiple. /// - parameter onFinishLoading: An optional callback when the load request has finished. /// - parameter onError: An optional callback when an error has occurred. /// - parameter onReceive: A callback when the GADNativeAd has been received. /// /// - Warning: /// Requests for multiple native ads don't currently work for AdMob ad unit IDs that have been configured for mediation. /// Publishers using mediation should avoid using the GADMultipleAdsAdLoaderOptions class when making requests i.e. set loaderOptions parameter to .single. public func loadNativeAd(from viewController: UIViewController, adUnitIdType: SwiftyAdsAdUnitIdType, loaderOptions: SwiftyAdsNativeAdLoaderOptions, onFinishLoading: (() -> Void)?, onError: ((Error) -> Void)?, onReceive: @escaping (GADNativeAd) -> Void) { guard !isDisabled else { return } guard hasConsent else { return } if nativeAd == nil, case .custom(let adUnitId) = adUnitIdType { nativeAd = SwiftyAdsNative( environment: environment, adUnitId: adUnitId, request: { [weak self] in self?.requestBuilder?.build() ?? GADRequest() } ) } nativeAd?.load( from: viewController, adUnitIdType: adUnitIdType, loaderOptions: loaderOptions, adTypes: [.native], onFinishLoading: onFinishLoading, onError: onError, onReceive: onReceive ) } // MARK: Enable/Disable /// Enable/Disable ads /// /// - parameter isDisabled: Set to true to disable ads or false to enable ads. public func setDisabled(_ isDisabled: Bool) { disabled = isDisabled if isDisabled { interstitialAd?.stopLoading() rewardedInterstitialAd?.stopLoading() nativeAd?.stopLoading() } else { loadAds() } } } // MARK: - Private Methods private extension SwiftyAds { func requestInitialConsent(from viewController: UIViewController, consentManager: SwiftyAdsConsentManagerType, completion: @escaping SwiftyAdsConsentResultHandler) { DispatchQueue.main.async { consentManager.requestUpdate { result in switch result { case .success(let status): switch status { case .required: DispatchQueue.main.async { consentManager.showForm(from: viewController, completion: completion) } default: completion(result) } case .failure: completion(result) } } } } func updateCOPPA(for configuration: SwiftyAdsConfiguration, mediationConfigurator: SwiftyAdsMediationConfiguratorType?) { guard let isCOPPAEnabled = configuration.isTaggedForChildDirectedTreatment else { return } // Update mediation networks mediationConfigurator?.updateCOPPA(isTaggedForChildDirectedTreatment: isCOPPAEnabled) // Update GADMobileAds mobileAds.requestConfiguration.tag(forChildDirectedTreatment: isCOPPAEnabled) } func updateGDPR(for configuration: SwiftyAdsConfiguration, mediationConfigurator: SwiftyAdsMediationConfiguratorType?, consentStatus: SwiftyAdsConsentStatus) { // Update mediation networks // // The GADMobileADs tagForUnderAgeOfConsent parameter is currently NOT forwarded to ad network // mediation adapters. // It is your responsibility to ensure that each third-party ad network in your application serves // ads that are appropriate for users under the age of consent per GDPR. mediationConfigurator?.updateGDPR( for: consentStatus, isTaggedForUnderAgeOfConsent: configuration.isTaggedForUnderAgeOfConsent ?? false ) // Update GADMobileAds // // The tags to enable the child-directed setting and tagForUnderAgeOfConsent // should not both simultaneously be set to true. // If they are, the child-directed setting takes precedence. // https://developers.google.com/admob/ios/targeting#child-directed_setting if let isCOPPAEnabled = configuration.isTaggedForChildDirectedTreatment, isCOPPAEnabled { return } if let isTaggedForUnderAgeOfConsent = configuration.isTaggedForUnderAgeOfConsent { mobileAds.requestConfiguration.tagForUnderAge(ofConsent: isTaggedForUnderAgeOfConsent) } } func startMobileAdsSDK(completion: @escaping () -> Void) { /* Warning: Ads may be preloaded by the Mobile Ads SDK or mediation partner SDKs upon calling startWithCompletionHandler:. If you need to obtain consent from users in the European Economic Area (EEA), set any request-specific flags (such as tagForChildDirectedTreatment or tag_for_under_age_of_consent), or otherwise take action before loading ads, ensure you do so before initializing the Mobile Ads SDK. */ mobileAds.start { [weak self] initializationStatus in guard let self = self else { return } if case .development = self.environment { print("SwiftyAds initialization status", initializationStatus.adapterStatusesByClassName) } completion() } } func loadAds() { rewardedAd?.load() guard !isDisabled else { return } interstitialAd?.load() rewardedInterstitialAd?.load() } } // MARK: - Deprecated public extension SwiftyAds { @available(*, deprecated, message: "Use `setDisabled` instead") func disable(_ isDisabled: Bool) { setDisabled(isDisabled) } }
ae6305a8ec57258c763e1076dafa8793
41.079208
159
0.606902
false
true
false
false
adrfer/swift
refs/heads/master
test/Constraints/lvalues.swift
apache-2.0
2
// RUN: %target-parse-verify-swift func f0(inout x: Int) {} func f1<T>(inout x: T) {} func f2(inout x: X) {} func f2(inout x: Double) {} class Reftype { var property: Double { get {} set {} } } struct X { subscript(i: Int) -> Float { get {} set {} } var property: Double { get {} set {} } func genuflect() {} } struct Y { subscript(i: Int) -> Float { get {} set {} } subscript(f: Float) -> Int { get {} set {} } } var i : Int var f : Float var x : X var y : Y func +=(inout lhs: X, rhs : X) {} func +=(inout lhs: Double, rhs : Double) {} prefix func ++(inout rhs: X) {} postfix func ++(inout lhs: X) {} f0(&i) f1(&i) f1(&x[i]) f1(&x.property) f1(&y[i]) // Missing '&' f0(i) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{4-4=&}} f1(y[i]) // expected-error{{passing value of type 'Float' to an inout parameter requires explicit '&'}} {{4-4=&}} // Assignment operators x += x ++x var yi = y[i] // Non-settable lvalues // FIXME: better diagnostic! var non_settable_x : X { return x } struct Z { var non_settable_x: X { get {} } var non_settable_reftype: Reftype { get {} } var settable_x : X subscript(i: Int) -> Double { get {} } subscript(_: (i: Int, j: Int)) -> X { get {} } } var z : Z func fz() -> Z {} func fref() -> Reftype {} // non-settable var is non-settable: // - assignment non_settable_x = x // expected-error{{cannot assign to value: 'non_settable_x' is a get-only property}} // - inout (mono) f2(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout (generic) f1(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout assignment non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++non_settable_x // expected-error{{cannot pass immutable value to mutating operator: 'non_settable_x' is a get-only property}} // non-settable property is non-settable: z.non_settable_x = x // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++z.non_settable_x // expected-error{{cannot pass immutable value to mutating operator: 'non_settable_x' is a get-only property}} // non-settable subscript is non-settable: z[0] = 0.0 // expected-error{{cannot assign through subscript: subscript is get-only}} f2(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} f1(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} z[0] += 0.0 // expected-error{{left side of mutating operator isn't mutable: subscript is get-only}} ++z[0] // expected-error{{cannot pass immutable value to mutating operator: subscript is get-only}} // settable property of an rvalue value type is non-settable: fz().settable_x = x // expected-error{{cannot assign to property: 'fz' returns immutable value}} f2(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} f1(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} fz().settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'fz' returns immutable value}} ++fz().settable_x // expected-error{{cannot pass immutable value to mutating operator: 'fz' returns immutable value}} // settable property of an rvalue reference type IS SETTABLE: fref().property = 0.0 f2(&fref().property) f1(&fref().property) fref().property += 0.0 fref().property += 1 // settable property of a non-settable value type is non-settable: z.non_settable_x.property = 1.0 // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x.property += 1.0 // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++z.non_settable_x.property // expected-error{{cannot pass immutable value to mutating operator: 'non_settable_x' is a get-only property}} // settable property of a non-settable reference type IS SETTABLE: z.non_settable_reftype.property = 1.0 f2(&z.non_settable_reftype.property) f1(&z.non_settable_reftype.property) z.non_settable_reftype.property += 1.0 z.non_settable_reftype.property += 1 // regressions with non-settable subscripts in value contexts _ = z[0] == 0 var d : Double d = z[0] // regressions with subscripts that return generic types var xs:[X] _ = xs[0].property struct A<T> { subscript(i: Int) -> T { get {} } } struct B { subscript(i: Int) -> Int { get {} } } var a:A<B> _ = a[0][0] // Instance members of struct metatypes. struct FooStruct { func instanceFunc0() {} } func testFooStruct() { FooStruct.instanceFunc0(FooStruct())() } // Don't load from explicit lvalues. func takesInt(x: Int) {} func testInOut(inout arg: Int) { var x : Int takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}} } // Don't infer inout types. var ir = &i // expected-error{{type 'inout Int' of variable is not materializable}} \ // expected-error{{'&' can only appear immediately in a call argument list}} var ir2 = ((&i)) // expected-error{{type 'inout Int' of variable is not materializable}} \ // expected-error{{'&' can only appear immediately in a call argument list}} // <rdar://problem/17133089> func takeArrayRef(inout x:Array<String>) { } // rdar://22308291 takeArrayRef(["asdf", "1234"]) // expected-error{{contextual type 'inout Array<String>' cannot be used with array literal}} // <rdar://problem/19835413> Reference to value from array changed func rdar19835413() { func f1(p: UnsafeMutablePointer<Void>) {} func f2(a: [Int], i: Int, pi: UnsafeMutablePointer<Int>) { var a = a f1(&a) f1(&a[i]) f1(&a[0]) f1(pi) f1(UnsafeMutablePointer(pi)) } } // <rdar://problem/21877598> Crash when accessing stored property without // setter from constructor protocol Radish { var root: Int { get } } public struct Kale : Radish { public let root : Int public init() { let _ = Kale().root self.root = 0 } } func testImmutableUnsafePointer(p: UnsafePointer<Int>) { p.memory = 1 // expected-error {{cannot assign to property: 'memory' is a get-only property}} p[0] = 1 // expected-error {{cannot assign through subscript: subscript is get-only}} } // <https://bugs.swift.org/browse/SR-7> Inferring closure param type to // inout crashes compiler let g = { x in f0(x) } // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{19-19=&}} // <rdar://problem/17245353> Crash with optional closure taking inout func rdar17245353() { typealias Fn = (inout Int) -> () func getFn() -> Fn? { return nil } let _: (inout UInt, UInt) -> Void = { $0 += $1 } } // <rdar://problem/23131768> Bugs related to closures with inout parameters func rdar23131768() { func f(g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f { $0 += 1 } // Crashes compiler func f2(g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f2 { $0 = $0 + 1 } // previously error: Cannot convert value of type '_ -> ()' to expected type '(inout Int) -> Void' func f3(g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f3 { (inout v: Int) -> Void in v += 1 } } // <rdar://problem/23331567> Swift: Compiler crash related to closures with inout parameter. func r23331567(fn: (inout x: Int) -> Void) { var a = 0 fn(x: &a) } r23331567 { $0 += 1 }
0104a2c64b39d7377485b1efe877e6b7
34.072034
139
0.673674
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Blog/Blog Dashboard/ViewModel/DashboardCardModel.swift
gpl-2.0
1
import Foundation /// Represents a card in the dashboard collection view struct DashboardCardModel: Hashable { let cardType: DashboardCard let dotComID: Int let apiResponse: BlogDashboardRemoteEntity? /** Initializes a new DashboardCardModel, used as a model for each dashboard card. - Parameters: - id: The `DashboardCard` id of this card - dotComID: The blog id for the blog associated with this card - entity: A `BlogDashboardRemoteEntity?` property - Returns: A `DashboardCardModel` that is used by the dashboard diffable collection view. The `id`, `dotComID` and the `entity` is used to differentiate one card from the other. */ init(cardType: DashboardCard, dotComID: Int, entity: BlogDashboardRemoteEntity? = nil) { self.cardType = cardType self.dotComID = dotComID self.apiResponse = entity } static func == (lhs: DashboardCardModel, rhs: DashboardCardModel) -> Bool { lhs.cardType == rhs.cardType && lhs.dotComID == rhs.dotComID && lhs.apiResponse == rhs.apiResponse } func hash(into hasher: inout Hasher) { hasher.combine(cardType) hasher.combine(dotComID) hasher.combine(apiResponse) } }
44de9c436aba0d26c387f8068bf182e3
32.763158
92
0.664848
false
false
false
false
Sweebi/tvProgress
refs/heads/master
tvProgress/Error/tvProgress+Error.swift
mit
1
// // tvProgress+Error.swift // tvProgress // // Created by Cédric Eugeni on 05/05/2016. // Copyright © 2016 tvProgress. All rights reserved. // import Foundation extension tvProgress { //MARK: - Methods /** If your loading fails, you can display a message that gives information about what happened to the user - Parameters: - status: specify a text to display - successImage: specify an image to be displayed instead of the default image - style: specify a style using tvProgressStyle enum - action: it's a tuple that contains a label and a closure. If you specify this parameter, the label will be use to generate a button while the closure will be executed when the user presses the button - menuButtonDidPress: specify a closure to be executed when the user press the Menu button while tvProgress is displayed - playButtonDidPress: specify a closure to be executed when the user press the Play/Pause button while tvProgress is displayed - marge: marging size for status label (right and left) */ public static func showErrorWithStatus(_ status: String? = .none, andErrorImage errorImage: UIImage? = .none, andStyle style: tvProgressStyle? = .none, andAction action: (label: String, closure: ((Void) -> Void))? = .none, menuButtonDidPress: (() -> Void)? = .none, playButtonDidPress: (() -> Void)? = .none, andWithMarginTextSize marge: CGFloat = 400, completion: (() -> Void)? = .none) -> Void { let instance: tvProgress = tvProgress.sharedInstance let f: () -> Void = { () -> Void in var views: [UIView] = [] let ei: UIImage = errorImage ?? instance.errorImage let errorImageView: UIImageView = UIImageView(frame: CGRect(x: instance.center.x - ei.size.width / 2, y: instance.center.y - ei.size.height / 2, width: ei.size.width, height: ei.size.height)) errorImageView.image = ei errorImageView.tintColor = (style ?? instance.style).mainColor views.insert(errorImageView, at: 0) if let s = status { let sLabel: UILabel = tvProgress.generateStatusLabelWithInstance(instance, andStatus: s, andStyle: style ?? instance.style, andWithMaxWidth: UIScreen.main.bounds.width - marge) let v: UIView = views[views.count - 1] sLabel.frame = CGRect(x: instance.center.x - (sLabel.frame.width / 2), y: v.frame.origin.y + v.frame.height + 30, width: sLabel.frame.width, height: sLabel.frame.height) sLabel.sizeToFit() views.insert(sLabel, at: views.count) } if let act = action { let button: UIButton = UIButton(type: .system) button.setTitle(act.label, for: UIControlState()) button.sizeToFit() button.actionHandleWithAction(act.closure) let v: UIView = views[views.count - 1] button.frame = CGRect(x: instance.center.x - (button.frame.width / 2), y: v.frame.origin.y + v.frame.height + 50, width: button.frame.width, height: button.frame.height) views.insert(button, at: views.count) } tvProgress.showWithInstance(instance, andVisibleType: visibleType.error(), andViews: views, andStyle: style, menuButtonDidPress: menuButtonDidPress, playButtonDidPress: playButtonDidPress, completion: completion) if let s = status , action == nil { Timer.scheduledTimer(timeInterval: tvProgress.displayDurationForString(s), target: self, selector: #selector(sdismiss), userInfo: nil, repeats: false) } } OperationQueue.main.addOperation() { () -> Void in if instance.isVisible { tvProgress.dismiss { () -> Void in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.25 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in f() } } } else { f() } } } }
8a155b7d240134b42e0cb513ed3a356c
55.891892
401
0.613539
false
false
false
false
marty-suzuki/QiitaWithFluxSample
refs/heads/master
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/APIWrappers/APIWrappersViewController.swift
mit
1
// // APIWrappersViewController.swift // RxExample // // Created by Carlos García on 8/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit import CoreLocation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif extension UILabel { open override var accessibilityValue: String! { get { return self.text } set { self.text = newValue self.accessibilityValue = newValue } } } class APIWrappersViewController: ViewController { @IBOutlet weak var debugLabel: UILabel! @IBOutlet weak var openActionSheet: UIButton! @IBOutlet weak var openAlertView: UIButton! @IBOutlet weak var bbitem: UIBarButtonItem! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var switcher: UISwitch! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var button: UIButton! @IBOutlet weak var slider: UISlider! @IBOutlet weak var textField: UITextField! @IBOutlet weak var textField2: UITextField! @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var mypan: UIPanGestureRecognizer! @IBOutlet weak var textView: UITextView! @IBOutlet weak var textView2: UITextView! let manager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() datePicker.date = Date(timeIntervalSince1970: 0) // MARK: UIBarButtonItem bbitem.rx.tap .subscribe(onNext: { [weak self] x in self?.debug("UIBarButtonItem Tapped") }) .disposed(by: disposeBag) // MARK: UISegmentedControl // also test two way binding let segmentedValue = Variable(0) _ = segmentedControl.rx.value <-> segmentedValue segmentedValue.asObservable() .subscribe(onNext: { [weak self] x in self?.debug("UISegmentedControl value \(x)") }) .disposed(by: disposeBag) // MARK: UISwitch // also test two way binding let switchValue = Variable(true) _ = switcher.rx.value <-> switchValue switchValue.asObservable() .subscribe(onNext: { [weak self] x in self?.debug("UISwitch value \(x)") }) .disposed(by: disposeBag) // MARK: UIActivityIndicatorView switcher.rx.value .bind(to: activityIndicator.rx.isAnimating) .disposed(by: disposeBag) // MARK: UIButton button.rx.tap .subscribe(onNext: { [weak self] x in self?.debug("UIButton Tapped") }) .disposed(by: disposeBag) // MARK: UISlider // also test two way binding let sliderValue = Variable<Float>(1.0) _ = slider.rx.value <-> sliderValue sliderValue.asObservable() .subscribe(onNext: { [weak self] x in self?.debug("UISlider value \(x)") }) .disposed(by: disposeBag) // MARK: UIDatePicker // also test two way binding let dateValue = Variable(Date(timeIntervalSince1970: 0)) _ = datePicker.rx.date <-> dateValue dateValue.asObservable() .subscribe(onNext: { [weak self] x in self?.debug("UIDatePicker date \(x)") }) .disposed(by: disposeBag) // MARK: UITextField // also test two way binding let textValue = Variable("") _ = textField.rx.textInput <-> textValue textValue.asObservable() .subscribe(onNext: { [weak self] x in self?.debug("UITextField text \(x)") }) .disposed(by: disposeBag) textValue.asObservable() .subscribe(onNext: { [weak self] x in self?.debug("UITextField text \(x)") }) .disposed(by: disposeBag) let attributedTextValue = Variable<NSAttributedString?>(NSAttributedString(string: "")) _ = textField2.rx.attributedText <-> attributedTextValue attributedTextValue.asObservable() .subscribe(onNext: { [weak self] x in self?.debug("UITextField attributedText \(x?.description ?? "")") }) .disposed(by: disposeBag) // MARK: UIGestureRecognizer mypan.rx.event .subscribe(onNext: { [weak self] x in self?.debug("UIGestureRecognizer event \(x.state.rawValue)") }) .disposed(by: disposeBag) // MARK: UITextView // also test two way binding let textViewValue = Variable("") _ = textView.rx.textInput <-> textViewValue textViewValue.asObservable() .subscribe(onNext: { [weak self] x in self?.debug("UITextView text \(x)") }) .disposed(by: disposeBag) let attributedTextViewValue = Variable<NSAttributedString?>(NSAttributedString(string: "")) _ = textView2.rx.attributedText <-> attributedTextViewValue attributedTextViewValue.asObservable() .subscribe(onNext: { [weak self] x in self?.debug("UITextView attributedText \(x?.description ?? "")") }) .disposed(by: disposeBag) // MARK: CLLocationManager #if !RX_NO_MODULE manager.requestWhenInUseAuthorization() #endif manager.rx.didUpdateLocations .subscribe(onNext: { x in print("rx.didUpdateLocations \(x)") }) .disposed(by: disposeBag) _ = manager.rx.didFailWithError .subscribe(onNext: { x in print("rx.didFailWithError \(x)") }) manager.rx.didChangeAuthorizationStatus .subscribe(onNext: { status in print("Authorization status \(status)") }) .disposed(by: disposeBag) manager.startUpdatingLocation() } func debug(_ string: String) { print(string) debugLabel.text = string } }
386d818c71415615ff9c7fa59b13ebe0
25.943478
99
0.574956
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/ModuleInterface/option-preservation.swift
apache-2.0
6
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -enable-library-evolution -emit-module-interface-path %t.swiftinterface -module-name t %s -emit-module -o /dev/null -Onone -enforce-exclusivity=unchecked -autolink-force-load // RUN: %FileCheck %s < %t.swiftinterface -check-prefix=CHECK-SWIFTINTERFACE // // CHECK-SWIFTINTERFACE: swift-module-flags: // CHECK-SWIFTINTERFACE-SAME: -enable-library-evolution // CHECK-SWIFTINTERFACE-SAME: -Onone // CHECK-SWIFTINTERFACE-SAME: -enforce-exclusivity=unchecked // CHECK-SWIFTINTERFACE-SAME: -autolink-force-load // Make sure flags show up when filelists are enabled // RUN: %target-build-swift %s -driver-filelist-threshold=0 -emit-module-interface -o %t/foo -module-name foo -module-link-name fooCore -force-single-frontend-invocation -Ounchecked -enforce-exclusivity=unchecked -autolink-force-load 2>&1 // RUN: %FileCheck %s < %t/foo.swiftinterface --check-prefix CHECK-FILELIST-INTERFACE // CHECK-FILELIST-INTERFACE: swift-module-flags: // CHECK-FILELIST-INTERFACE-SAME: -target // CHECK-FILELIST-INTERFACE-SAME: -autolink-force-load // CHECK-FILELIST-INTERFACE-SAME: -module-link-name fooCore // CHECK-FILELIST-INTERFACE-SAME: -enforce-exclusivity=unchecked // CHECK-FILELIST-INTERFACE-SAME: -Ounchecked // CHECK-FILELIST-INTERFACE-SAME: -module-name foo public func foo() { }
5043cf2601109cd0162fddd531cbc6b7
52.56
238
0.768484
false
false
false
false
EgzonArifi/Daliy-Gifs
refs/heads/master
AirDrummer/RAMAnimatedTabBarController/Animations/RotationAnimation/RAMRotationAnimation.swift
apache-2.0
7
// RAMRotationAnimation.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import QuartzCore /// The RAMRotationAnimation class provides rotation animation. open class RAMRotationAnimation : RAMItemAnimation { /** Animation direction - Left: left direction - Right: right direction */ public enum RAMRotationDirection { case left case right } /// Animation direction (left, right) open var direction : RAMRotationDirection! /** Start animation, method call when UITabBarItem is selected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ override open func playAnimation(_ icon : UIImageView, textLabel : UILabel) { playRoatationAnimation(icon) textLabel.textColor = textSelectedColor } /** Start animation, method call when UITabBarItem is unselected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel - parameter defaultTextColor: default UITabBarItem text color - parameter defaultIconColor: default UITabBarItem icon color */ override open func deselectAnimation(_ icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor, defaultIconColor : UIColor) { textLabel.textColor = defaultTextColor if let iconImage = icon.image { let renderMode = defaultIconColor.cgColor.alpha == 0 ? UIImageRenderingMode.alwaysOriginal : UIImageRenderingMode.alwaysTemplate let renderImage = iconImage.withRenderingMode(renderMode) icon.image = renderImage icon.tintColor = defaultIconColor } } /** Method call when TabBarController did load - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ override open func selectedState(_ icon : UIImageView, textLabel : UILabel) { textLabel.textColor = textSelectedColor if let iconImage = icon.image { let renderImage = iconImage.withRenderingMode(.alwaysTemplate) icon.image = renderImage icon.tintColor = textSelectedColor } } func playRoatationAnimation(_ icon : UIImageView) { let rotateAnimation = CABasicAnimation(keyPath: Constants.AnimationKeys.Rotation) rotateAnimation.fromValue = 0.0 var toValue = CGFloat(M_PI * 2.0) if direction != nil && direction == RAMRotationDirection.left { toValue = toValue * -1.0 } rotateAnimation.toValue = toValue rotateAnimation.duration = TimeInterval(duration) icon.layer.add(rotateAnimation, forKey: nil) if let iconImage = icon.image { let renderImage = iconImage.withRenderingMode(.alwaysTemplate) icon.image = renderImage icon.tintColor = iconSelectedColor } } } /// The RAMLeftRotationAnimation class provides letf rotation animation. class RAMLeftRotationAnimation : RAMRotationAnimation { override init() { super.init() direction = RAMRotationDirection.left } } /// The RAMRightRotationAnimation class provides rigth rotation animation. class RAMRightRotationAnimation : RAMRotationAnimation { override init() { super.init() direction = RAMRotationDirection.right } }
805371c05c7b925158ee89b1098fb85a
32.676923
139
0.729557
false
false
false
false
DanielFulton/ImageLibraryTests
refs/heads/master
DTMaster/Pods/HanekeSwift/Haneke/UIView+Haneke.swift
apache-2.0
25
// // UIView+Haneke.swift // Haneke // // Created by Joan Romano on 15/10/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit public extension HanekeGlobals { public struct UIKit { static func formatWithSize(size : CGSize, scaleMode : ImageResizer.ScaleMode, allowUpscaling: Bool = true) -> Format<UIImage> { let name = "auto-\(size.width)x\(size.height)-\(scaleMode.rawValue)" let cache = Shared.imageCache if let (format,_,_) = cache.formats[name] { return format } var format = Format<UIImage>(name: name, diskCapacity: HanekeGlobals.UIKit.DefaultFormat.DiskCapacity) { let resizer = ImageResizer(size:size, scaleMode: scaleMode, allowUpscaling: allowUpscaling, compressionQuality: HanekeGlobals.UIKit.DefaultFormat.CompressionQuality) return resizer.resizeImage($0) } format.convertToData = {(image : UIImage) -> NSData in image.hnk_data(compressionQuality: HanekeGlobals.UIKit.DefaultFormat.CompressionQuality) } return format } public struct DefaultFormat { public static let DiskCapacity : UInt64 = 50 * 1024 * 1024 public static let CompressionQuality : Float = 0.75 } static var SetImageAnimationDuration = 0.1 static var SetImageFetcherKey = 0 static var SetBackgroundImageFetcherKey = 1 } }
d42ec9ddef5f4608d27368df668ebdae
33.5625
135
0.570826
false
false
false
false
Hamuko/Nullpo
refs/heads/master
Nullpo/FileListData.swift
apache-2.0
1
import Cocoa class FileListData: NSViewController, NSTableViewDelegate, NSTableViewDataSource { @IBOutlet weak var fileTable: NSTableView! var fileList = [UploadFile]() /// Pushes a new URL onto the file list. /// - parameter file: File URL string. func addFile(file: UploadFile) { fileList.append(file) fileTable.reloadData() } /// Clear the entire file list. func clearFiles() { fileList = [UploadFile]() fileTable.reloadData() } var count: Int { return fileList.count } func numberOfRowsInTableView(tableView: NSTableView) -> Int { return fileList.count } func remove(index: Int) { fileList.removeAtIndex(index) fileTable.reloadData() } func sort(numberOfItems: Int) { let sortRange: Range<Int> = fileList.count - numberOfItems...fileList.count - 1 let sorted = fileList[sortRange].sort { $0.index < $1.index } fileList.replaceRange(sortRange, with: sorted) fileTable.reloadData() } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell: FileListCell = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! FileListCell cell.fileURL.stringValue = fileList[row].url! return cell } }
36e13aa1e95fb60586ee246a2c2fdfee
28.297872
120
0.655047
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/CoreData/Object/DVitaItemElementExport.swift
mit
1
import Foundation extension DVitaItemElement:DVitaItemExportProtocol { var hasheableItem:[String:Any] { get { let dateCreated:Date = Date( timeIntervalSince1970:self.dateCreated) let dateModified:Date = Date( timeIntervalSince1970:self.dateModified) let dateCreatedString:String = MVitaPtpDate.factoryString( date:dateCreated) let dateModifiedString:String = MVitaPtpDate.factoryString( date:dateModified) let name:String = self.name! let root:[String:Any] = [ "statusType":1, "name":name, "title":name, // "index":0, "ohfiParent":directory!.category.rawValue, "ohfi":directory!.category.rawValue, "size":size, "dateTimeCreated":dateCreatedString, "dateTimeUpdated":dateModifiedString] return root } } }
82f5f5f721ef30b0998bd42a8c6231ed
32.272727
71
0.51184
false
false
false
false
rtocd/NotificationObservers
refs/heads/master
NotificationObservers/Source/NotificationObservers/NotificationObserver.swift
mit
1
// // NotificationObserver.swift // Notification // // Created by rtocd on 7/4/17. // Copyright © 2017 RTOCD. All rights reserved. // import Foundation /// This handles most of the boilerplate code needed for creating a NotificationCenter observer. public class NotificationObserver<A: Adaptable>: NSObject { typealias callbackType = (A) -> () private let name: Notification.Name private var observer: NSObjectProtocol? private var callback: callbackType? = nil private var queue: OperationQueue? /// Call this when you want to start observer a notification. /// If you call the method multiple times it will stop and replace the previously created observer. public func start(queue: OperationQueue = .main, object: AnyObject? = nil, callback: @escaping (A) -> Void) { if self.callback != nil { self.stop() } self.callback = callback self.queue = queue self.observer = NotificationCenter.default.addObserver(key: self.name, object: object, queue: queue, callback: { (adaptor) in callback(adaptor) }) } public func stop() { if let observer = self.observer { NotificationCenter.default.removeObserver(observer) } self.callback = nil } public init(name: Notification.Name) { self.name = name super.init() } deinit { if let observer = self.observer { NotificationCenter.default.removeObserver(observer) } } }
50201cf19ab499ce291b3498c37a227e
28.037037
133
0.63074
false
false
false
false
LeoMobileDeveloper/PullToRefreshKit
refs/heads/master
Demo/Demo/QQVideoRefreshHeader.swift
mit
1
// // QQVideoRefreshHeader.swift // PullToRefreshKit // // Created by huangwenchen on 16/8/1. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import UIKit import PullToRefreshKit class QQVideoRefreshHeader:UIView,RefreshableHeader{ let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) imageView.frame = CGRect(x: 0, y: 0, width: 27, height: 10) imageView.center = CGPoint(x: self.bounds.width/2.0, y: self.bounds.height/2.0) imageView.image = UIImage(named: "loading15") addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - RefreshableHeader - func heightForHeader() -> CGFloat { return 50.0 } func stateDidChanged(_ oldState: RefreshHeaderState, newState: RefreshHeaderState) { if newState == .pulling{ UIView.animate(withDuration: 0.3, animations: { self.imageView.transform = CGAffineTransform.identity }) } if newState == .idle{ UIView.animate(withDuration: 0.3, animations: { self.imageView.transform = CGAffineTransform(translationX: 0, y: -50) }) } } //松手即将刷新的状态 func didBeginRefreshingState(){ imageView.image = nil let images = (0...29).map{return $0 < 10 ? "loading0\($0)" : "loading\($0)"} imageView.animationImages = images.map{return UIImage(named:$0)!} imageView.animationDuration = Double(images.count) * 0.04 imageView.startAnimating() } //刷新结束,将要隐藏header func didBeginHideAnimation(_ result:RefreshResult){} //刷新结束,完全隐藏header func didCompleteHideAnimation(_ result:RefreshResult){ imageView.animationImages = nil imageView.stopAnimating() imageView.image = UIImage(named: "loading15") } }
0807abe44cfada7691f60371ab558574
32.724138
88
0.633947
false
false
false
false
linhaosunny/smallGifts
refs/heads/master
小礼品/小礼品/Classes/Module/Me/Chat/ChatBar/KeyBoard/EmojiKeyboard.swift
mit
1
// // EmojiKeyboard.swift // 小礼品 // // Created by 李莎鑫 on 2017/5/6. // Copyright © 2017年 李莎鑫. All rights reserved. // 表情键盘 import UIKit import SnapKit import QorumLogs fileprivate let pageTintColor = UIColor(white: 0.5, alpha: 0.3) class EmojiKeyboard: BaseKeyboard { //MARK: 单例 static let shared = EmojiKeyboard() //MARK: 属性 weak var delegate:EmojiKeyboardDelegate? //MARK: 懒加载 //: 表情显示页面 lazy var emojiView:EmojiGroupView = { () -> EmojiGroupView in let view = EmojiGroupView() view.delegate = self return view }() //: 页控制器 lazy var pageControl:UIPageControl = { () -> UIPageControl in let control = UIPageControl() control.pageIndicatorTintColor = pageTintColor control.currentPageIndicatorTintColor = UIColor.gray control.numberOfPages = 0 control.addTarget(self, action: #selector(pageControlChanged), for: .valueChanged) return control }() //: 组控制器 lazy var groupControl:EmojiCroupControl = { () -> EmojiCroupControl in let control = EmojiCroupControl() control.delegate = self return control }() //MARK: 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupEmojiKeyboard() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setupEmojiKeyboardSubView() } //MARK: 私有方法 private func setupEmojiKeyboard() { backgroundColor = SystemGlobalBackgroundColor addSubview(pageControl) addSubview(groupControl) addSubview(emojiView) } private func setupEmojiKeyboardSubView() { emojiView.snp.remakeConstraints { (make) in make.top.left.right.equalToSuperview() make.bottom.equalTo(pageControl.snp.top) } pageControl.snp.remakeConstraints { (make) in make.left.right.equalToSuperview() make.bottom.equalTo(groupControl.snp.top) make.height.equalTo(margin*2.0) } groupControl.snp.remakeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(margin*3.8) } } //MARK: 内部响应 @objc private func pageControlChanged() { } } //MARK: 代理方法 -> EmojiGroupViewDelegate extension EmojiKeyboard:EmojiGroupViewDelegate { func emojiGroupViewGroupChanged(withGroupIndex index: Int, withGroupPages pages: Int) { pageControl.numberOfPages = pages } //: 发送表情 func emojiGroupViewDidSelectedEmoji(withItem item: Int, withEmojiName text: String?, isDelete delete: Bool) { QL1(text) delegate?.emojiKeyboardDidSelectdEmoji(withEmojiName: text, isDelete: delete) } func emojiGroupViewDidScrollToPage(withPage page: Int) { pageControl.currentPage = page } } //MARK: 代理方法 -> EmojiGroupControlDelegate extension EmojiKeyboard:EmojiGroupControlDelegate { func emojiGroupControlDidSelectGroupItem(GroupItem item: Int) { emojiView.groupIndex = item pageControl.currentPage = 0 emojiView.emojiGroupViewDidScrollTo(Pages: pageControl.currentPage) } func emojiGroupControlDidClickSendButton() { delegate?.emojiKeyboardDidClickSendButton() } } protocol EmojiKeyboardDelegate:NSObjectProtocol { func emojiKeyboardDidSelectdEmoji(withEmojiName text:String?,isDelete delete:Bool) func emojiKeyboardDidClickSendButton() }
b9bbcc31c0697fd4f2e8e6342075f16c
27.849206
113
0.661348
false
false
false
false
paulofaria/HTTP-Server
refs/heads/master
File Response/HTTPResponse+File.swift
mit
2
// HTTPResponse+File.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. extension HTTPResponse { init( status: HTTPStatus = .OK, headers: [String: String] = [:], baseDirectory: String, filePath: String, contentType: String? = .None) throws { guard let file = File(path: baseDirectory + filePath) else { throw HTTPError.NotFound(description: "Resource not found: \(filePath)") } if let contentType = contentType { self.init( status: status, headers: headers + ["content-type": contentType], body: file.data ) } else { self.init( status: status, headers: headers, body: file.data ) } } }
e26c23f4d65bcd06f69f50e464ec48b8
32.566667
88
0.620964
false
false
false
false
mobilabsolutions/jenkins-ios
refs/heads/master
JenkinsiOSTests/TestExtensions.swift
mit
1
// // TestExtensions.swift // JenkinsiOS // // Created by Robert on 18.10.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import Foundation import XCTest func AssertEmpty<T>(_ value: [T]) { XCTAssertTrue(value.isEmpty) } func AssertNotEmpty<T>(_ value: [T]) { XCTAssertFalse(value.isEmpty) } func assertArraysAreEqual(array1: [Any?], array2: [Any?]) { guard array1.count == array2.count else { XCTFail("Arrays do not have the same length: first: \(array1.count) second: \(array2.count)"); return } for (index, element) in array1.enumerated() { guard element != nil && array2[index] != nil else { if !(element == nil && array2[index] == nil) { XCTFail("\(String(describing: element)) is not the same as \(String(describing: array2[index]))") }; continue } if (element as? NSObject) != (array2[index] as? NSObject) { XCTFail("\(String(describing: element)) is not the same as \(String(describing: array2[index]))") } } }
b6be54a7e85bbea6a27cf5fb3d92de83
30.75
173
0.642717
false
true
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Blog/QuickStartChecklistCell.swift
gpl-2.0
1
import Gridicons class QuickStartChecklistCell: UITableViewCell { @IBOutlet private var titleLabel: UILabel! { didSet { WPStyleGuide.configureLabel(titleLabel, textStyle: .headline) } } @IBOutlet private var descriptionLabel: UILabel! { didSet { WPStyleGuide.configureLabel(descriptionLabel, textStyle: .subheadline) } } @IBOutlet private var iconView: UIImageView? @IBOutlet private var stroke: UIView? { didSet { stroke?.backgroundColor = .divider } } @IBOutlet private var topSeparator: UIView? { didSet { topSeparator?.backgroundColor = .divider } } private var bottomStrokeLeading: NSLayoutConstraint? private var contentViewLeadingAnchor: NSLayoutXAxisAnchor { return WPDeviceIdentification.isiPhone() ? contentView.leadingAnchor : contentView.readableContentGuide.leadingAnchor } private var contentViewTrailingAnchor: NSLayoutXAxisAnchor { return WPDeviceIdentification.isiPhone() ? contentView.trailingAnchor : contentView.readableContentGuide.trailingAnchor } public var completed = false { didSet { if completed { guard let titleText = tour?.title else { return } titleLabel.attributedText = NSAttributedString(string: titleText, attributes: [.strikethroughStyle: 1, .foregroundColor: UIColor.neutral(.shade30)]) // Overrides the existing accessibility hint in the tour property observer, // because users don't need the hint repeated to them after a task is completed. accessibilityHint = nil accessibilityLabel = tour?.titleMarkedCompleted descriptionLabel.textColor = .neutral(.shade30) iconView?.tintColor = .neutral(.shade30) } else { titleLabel.textColor = .text descriptionLabel.textColor = .textSubtle iconView?.tintColor = .listIcon } } } public var tour: QuickStartTour? { didSet { titleLabel.text = tour?.title descriptionLabel.text = tour?.description iconView?.image = tour?.icon.withRenderingMode(.alwaysTemplate) if let hint = tour?.accessibilityHintText, !hint.isEmpty { accessibilityHint = hint } } } public var lastRow: Bool = false { didSet { bottomStrokeLeading?.isActive = !lastRow } } public var topSeparatorIsHidden: Bool = false { didSet { topSeparator?.isHidden = topSeparatorIsHidden } } override func awakeFromNib() { super.awakeFromNib() contentView.backgroundColor = .listForeground setupConstraints() } static let reuseIdentifier = "QuickStartChecklistCell" } private extension QuickStartChecklistCell { func setupConstraints() { guard let stroke = stroke, let topSeparator = topSeparator else { return } bottomStrokeLeading = stroke.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor) bottomStrokeLeading?.isActive = true let strokeSuperviewLeading = stroke.leadingAnchor.constraint(equalTo: contentViewLeadingAnchor) strokeSuperviewLeading.priority = UILayoutPriority(999.0) strokeSuperviewLeading.isActive = true stroke.trailingAnchor.constraint(equalTo: contentViewTrailingAnchor).isActive = true topSeparator.leadingAnchor.constraint(equalTo: contentViewLeadingAnchor).isActive = true topSeparator.trailingAnchor.constraint(equalTo: contentViewTrailingAnchor).isActive = true } }
4edc60f77a3c45345811245274e36447
36.018692
127
0.623832
false
false
false
false
superman-coder/pakr
refs/heads/master
pakr/pakr/UserInterface/PostParking/AddressPicker/AddressPickerController.swift
apache-2.0
1
// // AddressPickerController.swift // pakr // // Created by Tien on 4/16/16. // Copyright © 2016 Pakr. All rights reserved. // import UIKit import MapKit import CoreLocation protocol AddressPickerDelegate { func addressPickerControllerDidCancel(addressPicker:AddressPickerController); func addressPickerController(addressPicker:AddressPickerController, didFinishPickingLocationWithLatlng latlng:CLLocationCoordinate2D!, address:String?, image:UIImage?) } let searchCellReuseId = "GMPlaceCell" class AddressPickerController: UIViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var searchTextField: UITextField! @IBOutlet weak var searchControllerView: UIView! @IBOutlet weak var searchResultContainerView: UIView! @IBOutlet weak var searchResultTableView: UITableView! @IBOutlet weak var searchIconButton: UIButton! @IBOutlet weak var bottomBarView: UIView! var delegate: AddressPickerDelegate? var isQuerying = false var currentSearchQuery:String? var latestSearchQuery:String? var selectedLocation:CLLocationCoordinate2D? var selectedAddress:String? private var reverseGeoCodeRequestTimer:NSTimer? private var placeSearchRequestTimer:NSTimer? private let centerPinLayer = CALayer() // Search functions var searchResult: [GMPlace]! = [] // A boolean indicates if we should perform a search when text changes. var shouldSearch = true // End of search functions override func viewDidLoad() { super.viewDidLoad() initMapView() initSearchController() } private func initMapView() { mapView.delegate = self if let initialLocation = selectedLocation { centerMapToCoordinate(initialLocation) } centerPinLayer.contents = UIImage(named: "pin-orange")?.CGImage centerPinLayer.bounds = CGRectMake(0, 0, 29, 42) let bounds = mapView.bounds centerPinLayer.position = CGPointMake(bounds.size.width / 2, bounds.size.height / 2) centerPinLayer.anchorPoint = CGPointMake(0.5, 1) centerPinLayer.hidden = true mapView.layer.addSublayer(centerPinLayer) } private func initSearchController() { LayoutUtils.dropShadowView(searchControllerView) searchTextField.delegate = self searchTextField.placeholder = "Search nearby address" searchResultTableView.registerNib(UINib(nibName: "GMPlaceCell", bundle: nil), forCellReuseIdentifier: searchCellReuseId) searchResultTableView.dataSource = self searchResultTableView.delegate = self bottomBarView.layer.masksToBounds = false bottomBarView.layer.shadowColor = UIColor.blackColor().CGColor bottomBarView.layer.shadowOffset = CGSize(width: 0, height: 2) bottomBarView.layer.shadowOpacity = 0.4 } override func viewDidLayoutSubviews() { let bounds = mapView.bounds centerPinLayer.position = CGPointMake(bounds.size.width / 2, bounds.size.height / 2) centerPinLayer.hidden = false } @IBAction func buttonCancelDidClick(sender: UIBarButtonItem) { delegate?.addressPickerControllerDidCancel(self) } @IBAction func buttonDoneDidClick(sender: UIBarButtonItem) { snapshotMapViewWithComplete { (snapshot, error) in self.delegate?.addressPickerController(self, didFinishPickingLocationWithLatlng: self.selectedLocation!, address: self.selectedAddress, image: snapshot) } } private func showSearchResultContainer(show:Bool) { if (show != self.searchResultContainerView.hidden) { return } // show true, hidden = false -> return // show false hidden = true -> return // show true, hidden = true -> do // show false, hidden = false -> do let initialAlpha:CGFloat = show ? 0 : 1 self.searchResultContainerView.alpha = initialAlpha self.searchResultContainerView.hidden = false if (show) { self.searchTextField.becomeFirstResponder() } else { self.searchTextField.resignFirstResponder() } // self.searchTextField.text = nil self.searchResult.removeAll() self.searchResultTableView.reloadData() UIView.animateWithDuration(0.3, animations: { self.searchResultContainerView.alpha = 1 - initialAlpha }) { (finished) in self.searchResultContainerView.hidden = !show } let targetImage = show ? UIImage(named: "back-gray") : UIImage(named: "search-gray") UIView.transitionWithView(self.searchIconButton, duration: 0.3, options: .TransitionCrossDissolve, animations: { self.searchIconButton .setImage(targetImage, forState: .Normal) }) { (finished) in } } @IBAction func searchTextFieldTextChanged(sender: UITextField) { latestSearchQuery = sender.text if sender.text == nil || sender.text!.characters.count == 0 { searchResult.removeAll() searchResultTableView.reloadData() return } let searchText = sender.text! if (!isQuerying) { requestSearchPlaces(searchText); } } @IBAction func searchControllerBackButtonDidClick(sender: UIButton) { self.showSearchResultContainer(false) } func requestSearchPlaces(searchText: String) { isQuerying = true currentSearchQuery = searchText UIApplication.sharedApplication().networkActivityIndicatorVisible = true GMServices.requestAddressSearchWithAddress(searchText) { (success, location) in self.isQuerying = false UIApplication.sharedApplication().networkActivityIndicatorVisible = false self.onQueryFinished() self.handleSearchResult(success, locations: location) } } private func handleSearchResult(success:Bool, locations:[GMPlace]?) { self.searchResult.removeAll() if success { self.searchResult.appendContentsOf(locations!) } else { // TODO: Handle search error } self.searchResultTableView.reloadData() } private func onQueryFinished() { if currentSearchQuery != nil && latestSearchQuery != nil && currentSearchQuery != latestSearchQuery { requestSearchPlaces(latestSearchQuery!) } } private func centerMapToCoordinate(latlng:CLLocationCoordinate2D) { let region = MKCoordinateRegionMakeWithDistance(latlng, MAP_DEFAULT_RADIUS, MAP_DEFAULT_RADIUS) mapView.setRegion(region, animated: true) } private func snapshotMapViewWithComplete(completion:(snapshot:UIImage?, error:NSError?)->()) { let snapshotOption = MKMapSnapshotOptions() snapshotOption.region = mapView.region snapshotOption.size = CGSizeMake(mapView.frame.size.width, mapView.frame.size.height / 2) snapshotOption.scale = UIScreen.mainScreen().scale let snapshoter = MKMapSnapshotter(options: snapshotOption) snapshoter.startWithQueue(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { (snapshot:MKMapSnapshot?, error:NSError?) in guard let snapshot = snapshot else { completion(snapshot: nil, error: error) return } let pin = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil) let mapImage = snapshot.image UIGraphicsBeginImageContextWithOptions(mapImage.size, true, mapImage.scale) mapImage.drawAtPoint(CGPoint.zero) var point = snapshot.pointForCoordinate(self.selectedLocation!) point.x = point.x + pin.centerOffset.x - (pin.bounds.size.width / 2) point.y = point.y + pin.centerOffset.y - (pin.bounds.size.height / 2) pin.image?.drawAtPoint(point) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() dispatch_async(dispatch_get_main_queue(), { completion(snapshot: image, error: nil) }) } } } extension AddressPickerController: MKMapViewDelegate { func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) { self.addressLabel.text = "Moving" } func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) { self.addressLabel.text = "Loading" selectedLocation = mapView.region.center reverseGeoCodeRequestTimer?.invalidate() reverseGeoCodeRequestTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(AddressPickerController.reverseGeoCodeRequest), userInfo: nil, repeats: false) } func reverseGeoCodeRequest() { guard let _ = selectedLocation else { return } GMServices.reverseGeocodeRequest(selectedLocation!.latitude, longitude: selectedLocation!.longitude) { (success, address) in if success { self.addressLabel.text = address self.selectedAddress = address } else { self.addressLabel.text = "Error" } } } } extension AddressPickerController: UITextFieldDelegate { func textFieldShouldBeginEditing(textField: UITextField) -> Bool { self.shouldSearch = true textField.text = "" self.showSearchResultContainer(true) return true } func textFieldDidEndEditing(textField: UITextField) { self.shouldSearch = false } } extension AddressPickerController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(searchCellReuseId) as! GMPlaceCell let gmPlace = searchResult[indexPath.row] cell.configWithName(gmPlace.name, address: gmPlace.address) return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResult.count } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.01 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let gmPlace = searchResult[indexPath.row] searchTextField.text = gmPlace.name centerMapToCoordinate(CLLocationCoordinate2D(latitude: gmPlace.geometry.latitude, longitude: gmPlace.geometry.longitude)) self.showSearchResultContainer(false) } }
bf83a96ad70837af595dee81a53f0d7c
36.397394
191
0.664663
false
false
false
false
InsectQY/HelloSVU_Swift
refs/heads/master
HelloSVU_Swift/Classes/Expand/Extension/UIBarButtonItem-Extension.swift
apache-2.0
1
// // UIBarButtonItem-Extension.swift // DouYuLive // // Created by Insect on 2017/4/8. // Copyright © 2017年 Insect. All rights reserved. // import UIKit extension UIBarButtonItem { convenience init(normalImg: String, highlightedImg: String? = "",title: String? = nil ,size: CGSize? = CGSize.zero,target: Any,action:Selector) { let btn = UIButton(type: .custom) btn.setImage(UIImage(named:normalImg ), for: .normal) btn.setTitleColor(.black, for: .normal) btn.titleLabel?.font = PFM16Font btn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, -10) btn.addTarget(target, action: action, for: .touchUpInside) if let highlightedImg = highlightedImg { btn.setImage(UIImage(named:highlightedImg), for: .highlighted) } if let title = title { btn.setTitle(title, for: .normal) } if let size = size { btn.frame = CGRect(origin:CGPoint.zero, size: size) }else { btn.sizeToFit() } self.init(customView: btn) } }
5bfed10d5b787564bf46f5e64b84c1cc
27.948718
149
0.58636
false
false
false
false
JGiola/swift
refs/heads/main
test/Constraints/casts_objc.swift
apache-2.0
6
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify %s // REQUIRES: objc_interop import Foundation struct NotClass {} class SomeClass {} func nsobject_as_class_cast<T>(_ x: NSObject, _: T) { let _ = x is AnyObject.Type let _ = x as! AnyObject.Type let _ = x as? AnyObject.Type let _ = x is Any.Type let _ = x as! Any.Type let _ = x as? Any.Type let _ = x is SomeClass.Type let _ = x as! SomeClass.Type let _ = x as? SomeClass.Type let _ = x is T.Type let _ = x as! T.Type let _ = x as? T.Type let _ = x is NotClass.Type // expected-warning{{cast from 'NSObject' to unrelated type 'NotClass.Type' always fails}} let _ = x as! NotClass.Type // expected-warning{{cast from 'NSObject' to unrelated type 'NotClass.Type' always fails}} let _ = x as? NotClass.Type // expected-warning{{cast from 'NSObject' to unrelated type 'NotClass.Type' always fails}} } // <rdar://problem/20294245> QoI: Error message mentions value rather than key for subscript func test(_ a : CFString!, b : CFString) { let dict = NSMutableDictionary() let object = NSObject() dict[a] = object dict[b] = object } // <rdar://problem/22507759> QoI: poor error message for invalid unsafeDowncast() let r22507759: NSObject! = "test" as NSString let _: NSString! = unsafeDowncast(r22507759) // expected-error {{missing argument for parameter 'to' in call}} // rdar://problem/29496775 / SR-3319 func sr3319(f: CGFloat, n: NSNumber) { let _ = [f].map { $0 as NSNumber } let _ = [n].map { $0 as! CGFloat } } func alwaysSucceedingConditionalCasts(f: CGFloat, n: NSNumber) { let _ = f as? NSNumber // expected-warning{{conditional cast from 'CGFloat' to 'NSNumber' always succeeds}} let _ = n as? CGFloat } func optionalityReducingCasts(f: CGFloat?, n: NSNumber?) { let _ = f as? NSNumber let _ = f as! NSNumber // expected-warning{{forced cast from 'CGFloat?' to 'NSNumber' only unwraps and bridges; did you mean to use '!' with 'as'?}} let _ = n as? CGFloat let _ = n as! CGFloat } func optionalityMatchingCasts(f: CGFloat?, n: NSNumber?) { let _ = f as NSNumber? let _ = f as? NSNumber? // expected-warning{{conditional cast from 'CGFloat?' to 'NSNumber?' always succeeds}} let _ = f as! NSNumber? // expected-warning{{forced cast from 'CGFloat?' to 'NSNumber?' always succeeds; did you mean to use 'as'?}}{{13-16=as}} let _ = n as? CGFloat? let _ = n as! CGFloat? } func optionalityMatchingCastsIUO(f: CGFloat?!, n: NSNumber?!) { let _ = f as NSNumber? let _ = f as? NSNumber? let _ = f as! NSNumber? // expected-warning{{forced cast from 'CGFloat??' to 'NSNumber?' only unwraps and bridges; did you mean to use '!' with 'as'?}} let _ = n as? CGFloat? let _ = n as! CGFloat? } func optionalityMismatchingCasts(f: CGFloat, n: NSNumber, fooo: CGFloat???, nooo: NSNumber???) { _ = f as NSNumber? _ = f as NSNumber?? let _ = fooo as NSNumber?? // expected-error{{'CGFloat???' is not convertible to 'NSNumber??'}} //expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{16-18=as!}} let _ = fooo as NSNumber???? // okay: injects extra optionals } func anyObjectCasts(xo: [Int]?, xooo: [Int]???, x: [Int]) { _ = x as AnyObject _ = x as AnyObject? _ = xo as AnyObject _ = xo as AnyObject? _ = xooo as AnyObject?? _ = xooo as AnyObject??? _ = xooo as AnyObject???? // okay: injects extra optionals }
507367532981bc2dece91b579f0085a0
34.56701
153
0.647246
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
refs/heads/master
Playground Collection/Part 4 - Alien Adventure 2/Dictionaries/Dictionaries.playground/Pages/Operations_insert, count, remove, update.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) //: ### Dictionary operations: insert, count, remove, update, retrieve var animalGroupsDict = ["whales":"pod", "geese":"flock", "lions": "pride"] // Adding items to a dictionary animalGroupsDict["crows"] = "murder" animalGroupsDict["monkeys"] = "troop" // The count method is available to all collections. animalGroupsDict.count print(animalGroupsDict) // Removing items from a dictionary animalGroupsDict["crows"] = nil animalGroupsDict // Updating a value animalGroupsDict["monkeys"] = "barrel" var group = animalGroupsDict.updateValue("gaggle", forKey: "geese") type(of: group) animalGroupsDict.updateValue("crash", forKey:"rhinoceroses") print(animalGroupsDict) //: [Next](@next)
fa531171b36ded4f8888370fdc1690ff
26.576923
74
0.739191
false
false
false
false
chicio/Exploring-SceneKit
refs/heads/master
ExploringSceneKit/Model/Scenes/BlinnPhong/BlinnPhongScene.swift
mit
1
// // BlinnPhongScene.swift // ExploringSceneKit // // Created by Fabrizio Duroni on 26.08.17. // import SceneKit @objc class BlinnPhongScene: SCNScene, Scene { private var camera: Camera! private var poolSphere: DynamicSphere! override init() { super.init() createCamera() createLight() createObjects() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: Camera private func createCamera() { camera = Camera( position: SCNVector3Make(0, 80.0, 100.0), rotation: SCNVector4Make(1.0, 0, 0, -1.0 * Float(CGFloat.pi / 4.0)) ) rootNode.addChildNode(camera.node) } //MARK: Light private func createLight() { rootNode.addChildNode(createOmniDirectionalLight().node) rootNode.addChildNode(createAmbientLight().node) } private func createOmniDirectionalLight() -> OmniDirectionalLight { let lightFeatures = LightFeatures( position: SCNVector3Make(0, 50, 10), orientation: SCNVector3Make(0, 0, 0), color: UIColor.white ) let light = OmniDirectionalLight(lightFeatures: lightFeatures) return light } private func createAmbientLight() -> AmbientLight { let lightFeatures = LightFeatures( position: SCNVector3Make(0, 0, 0), orientation: SCNVector3Make(0, 0, 0), color: UIColor.darkGray ) let light = AmbientLight(lightFeatures: lightFeatures) return light } //MARK: Objects private func createObjects() { addFloor() addWhiteMarbleBox() addBlueMarbleBox() addDarkBlueMarbleBox() addPoolSphere() } private func addFloor() { let floor = KinematicFloor( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "floor.jpg", textureWrapMode: .repeat), specular: 0.0 ), position: SCNVector3Make(0, 0, 0), rotation: SCNVector4Make(0, 0, 0, 0) ) rootNode.addChildNode(floor.node) } private func addWhiteMarbleBox() { let box = DynamicBox( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "marble1.jpg"), specular: 0.3 ), boxFeatures: BoxFeatures(width: 10.0, height: 10.0, length: 10.0, edgesRadius: 0.2), position: SCNVector3Make(0, 5, 0), rotation: SCNVector4Make(0, 1, 0, 0.5) ) rootNode.addChildNode(box.node) } private func addBlueMarbleBox() { let box = DynamicBox( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "marble2.jpg"), specular: 0.2 ), boxFeatures: BoxFeatures(width: 10.0, height: 10.0, length: 10.0, edgesRadius: 0.2), position: SCNVector3Make(-5, 5, 0), rotation: SCNVector4Make(0, 1, 0, 0.5) ) rootNode.addChildNode(box.node) } private func addDarkBlueMarbleBox() { let box = DynamicBox( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "marble3.jpg"), specular: 0.3 ), boxFeatures: BoxFeatures(width: 10.0, height: 10.0, length: 10.0, edgesRadius: 0.2), position: SCNVector3Make(-5, 10, 0), rotation: SCNVector4Make(0, 1, 0, 0.5) ) rootNode.addChildNode(box.node) } private func addPoolSphere() { self.poolSphere = DynamicSphere( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "pool.jpg"), specular: 0.9 ), physicsBodyFeature: PhysicsBodyFeatures(mass: 1.5, rollingFriction: 0.1), radius: 10.0, position: SCNVector3Make(20, 10, 20), rotation: SCNVector4Make(0, 0, 0, 0) ) rootNode.addChildNode(self.poolSphere.node) } func actionForOnefingerGesture(withLocation location: CGPoint, andHitResult hitResult: [Any]!) { if isThereAHitIn(hitResult: hitResult) { movePoolSphereUsing(hitResult: hitResult) } } private func isThereAHitIn(hitResult: [Any]!) -> Bool { return hitResult.count > 0 } private func movePoolSphereUsing(hitResult: [Any]!) { if let firstHit: SCNHitTestResult = hitResult[0] as? SCNHitTestResult { let force = SCNVector3Make( firstHit.worldCoordinates.x - self.poolSphere.node.position.x, 0, firstHit.worldCoordinates.z - self.poolSphere.node.position.z ) self.poolSphere.node.physicsBody?.applyForce(force, asImpulse: true) } } func actionForTwofingerGesture() { let randomX = CGFloat.randomIn(minRange: 0.0, maxRange: 50.0) let randomZ = CGFloat.randomIn(minRange: 0.0, maxRange: 50.0) let randomRadius = CGFloat.randomIn(minRange: 0.0, maxRange: 15.0) let randomTexture = String(format: "checked%d.jpg", Int.randomIn(minRange: 1, maxRange: 2)) let sphere = DynamicSphere( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: randomTexture), specular: CGFloat.randomIn(minRange: 0.0, maxRange: 2.0) ), physicsBodyFeature: PhysicsBodyFeatures(mass: randomRadius * 10.0, rollingFriction: 0.2), radius: randomRadius, position: SCNVector3(randomX, 120, randomZ), rotation: SCNVector4(0, 0, 0, 0) ) rootNode.addChildNode(sphere.node) } }
8f362584bbb5cd0307ab98370bf37e62
33.563536
106
0.586797
false
false
false
false
TryFetch/PutioKit
refs/heads/master
Sources/Router.swift
gpl-3.0
1
// // Router.swift // Fetch // // Created by Stephen Radford on 22/06/2016. // Copyright © 2016 Cocoon Development Ltd. All rights reserved. // import Foundation import Alamofire /// The router used for requests to the API. enum Router: URLRequestConvertible { static let base = "https://api.put.io/v2" /// MARK: - Cases case files(Int) case deleteFiles([Int]) case renameFile(Int, String) case file(Int) case moveFiles([Int], Int) case createFolder(String, Int) case convertToMp4(Int) case getMp4Status(Int) case shareFiles([Int], [String]) case getSharedWith(Int) case unshareFile(Int, [Int]) case getSubtitles(Int) case setVideoPosition(Int, Int) case deleteVideoPosition(Int) case getEvents case deleteEvents case transfers case cleanTransfers case addTransfer(String, Int, Bool) case retryTransfer(Int) case cancelTransfers([Int]) case getAccountInfo case getSettings var result: (method: HTTPMethod, path: String, parameters: Parameters) { switch self { case .files(let parent): return (.get, "/files/list", ["parent_id": parent, "start_from": 1]) case .file(let id): return (.get, "/files/\(id)", [:]) case .deleteFiles(let files): return (.post, "/files/delete", ["file_ids": files.map { String($0) }.joined(separator: ",")]) case .renameFile(let id, let name): return (.post, "/files/rename", ["file_id": id, "name": name]) case .moveFiles(let files, let parent): return (.post, "/files/move", ["file_ids": files.map { String($0) }.joined(separator: ","), "parent": parent]) case .createFolder(let name, let parent): return (.post, "/files/create-folder", ["name": name, "parent_id": parent]) case .convertToMp4(let id): return (.post, "/files/\(id)/mp4", [:]) case .getMp4Status(let id): return (.get, "/files/\(id)/mp4", [:]) case .shareFiles(let files, let friends): return (.post, "/files/share", ["file_ids": files.map { String($0) }.joined(separator: ","), "friends": friends.joined(separator: ",")]) case .getSharedWith(let id): return (.get, "/files/\(id)/shared-with", [:]) case .unshareFile(let id, let friends): return (.post, "/files/\(id)/unshare", ["shares": friends.map { String($0) }.joined(separator: ",")]) case .getSubtitles(let id): return (.get, "/files/\(id)/subtitles", [:]) case .setVideoPosition(let id, let position): return (.post, "/files/\(id)/start-from", ["time": position]) case .deleteVideoPosition(let id): return (.post, "/files/\(id)/start-from/delete", [:]) case .getEvents: return (.get, "/events/list", [:]) case .deleteEvents: return (.post, "/events/delete", [:]) case .transfers: return (.get, "/transfers/list", [:]) case .cleanTransfers: return (.post, "/transfers/clean", [:]) case .addTransfer(let url, let parent, let extract): return (.post, "/transfers/add", ["url": url, "parent": parent, "extract": extract]) case .retryTransfer(let id): return (.post, "/transfers/retry", ["id": id]) case .cancelTransfers(let transfers): return (.post, "/transfers/cancel", ["transfer_ids": transfers.map { String($0) }.joined(separator: ",")]) case .getAccountInfo: return (.get, "/account/info", [:]) case .getSettings: return (.get, "/account/settings", [:]) } } /// Returns a URL request or throws if an `Error` was encountered. /// /// - throws: An `Error` if the underlying `URLRequest` is `nil`. /// /// - returns: A URL request. public func asURLRequest() throws -> URLRequest { let url = try Router.base.asURL() var urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) urlRequest.httpMethod = result.method.rawValue var parameters = result.parameters if let token = Putio.accessToken { parameters["oauth_token"] = token } return try URLEncoding.default.encode(urlRequest, with: parameters) } }
36b6b86845ecd3214417fb5b806c881e
36.91453
148
0.574617
false
false
false
false
CodeJoyTeam/SwiftSimpleFramwork
refs/heads/master
Pods/EZSwiftExtensions/Sources/UIDeviceExtensions.swift
mit
4
// // UIDeviceExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit /// EZSwiftExtensions private let DeviceList = [ /* iPod 5 */ "iPod5,1": "iPod Touch 5", /* iPod 6 */ "iPod7,1": "iPod Touch 6", /* iPhone 4 */ "iPhone3,1": "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4", /* iPhone 4S */ "iPhone4,1": "iPhone 4S", /* iPhone 5 */ "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5", /* iPhone 5C */ "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C", /* iPhone 5S */ "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S", /* iPhone 6 */ "iPhone7,2": "iPhone 6", /* iPhone 6 Plus */ "iPhone7,1": "iPhone 6 Plus", /* iPhone 6S */ "iPhone8,1": "iPhone 6S", /* iPhone 6S Plus */ "iPhone8,2": "iPhone 6S Plus", /* iPad 2 */ "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2", /* iPad 3 */ "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3": "iPad 3", /* iPad 4 */ "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4", /* iPad Air */ "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air", /* iPad Air 2 */ "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2", /* iPad Mini */ "iPad2,5": "iPad Mini", "iPad2,6": "iPad Mini", "iPad2,7": "iPad Mini", /* iPad Mini 2 */ "iPad4,4": "iPad Mini 2", "iPad4,5": "iPad Mini 2", "iPad4,6": "iPad Mini 2", /* iPad Mini 3 */ "iPad4,7": "iPad Mini 3", "iPad4,8": "iPad Mini 3", "iPad4,9": "iPad Mini 3", /* iPad Mini 4 */ "iPad5,1": "iPad Mini 4", "iPad5,2": "iPad Mini 4", /* iPad Pro */ "iPad6,7": "iPad Pro", "iPad6,8": "iPad Pro", /* AppleTV */ "AppleTV5,3": "AppleTV", /* Simulator */ "x86_64": "Simulator", "i386": "Simulator" ] extension UIDevice { /// EZSwiftExtensions public class func idForVendor() -> String? { return UIDevice.current.identifierForVendor?.uuidString } /// EZSwiftExtensions - Operating system name public class func systemName() -> String { return UIDevice.current.systemName } /// EZSwiftExtensions - Operating system version public class func systemVersion() -> String { return UIDevice.current.systemVersion } /// EZSwiftExtensions - Operating system version public class func systemFloatVersion() -> Float { return (systemVersion() as NSString).floatValue } /// EZSwiftExtensions public class func deviceName() -> String { return UIDevice.current.name } /// EZSwiftExtensions public class func deviceLanguage() -> String { return Bundle.main.preferredLocalizations[0] } /// EZSwiftExtensions public class func deviceModelReadable() -> String { return DeviceList[deviceModel()] ?? deviceModel() } /// EZSE: Returns true if the device is iPhone //TODO: Add to readme public class func isPhone() -> Bool { return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone } /// EZSE: Returns true if the device is iPad //TODO: Add to readme public class func isPad() -> Bool { return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad } /// EZSwiftExtensions public class func deviceModel() -> String { var systemInfo = utsname() uname(&systemInfo) let machine = systemInfo.machine var identifier = "" let mirror = Mirror(reflecting: machine) for child in mirror.children { let value = child.value if let value = value as? Int8, value != 0 { identifier.append(String(UnicodeScalar(UInt8(value)))) } } return identifier } //TODO: Fix syntax, add docs and readme for these methods: //TODO: Delete isSystemVersionOver() // MARK: - Device Version Checks public enum Versions: Float { case five = 5.0 case six = 6.0 case seven = 7.0 case eight = 8.0 case nine = 9.0 } public class func isVersion(_ version: Versions) -> Bool { return systemFloatVersion() >= version.rawValue && systemFloatVersion() < (version.rawValue + 1.0) } public class func isVersionOrLater(_ version: Versions) -> Bool { return systemFloatVersion() >= version.rawValue } public class func isVersionOrEarlier(_ version: Versions) -> Bool { return systemFloatVersion() < (version.rawValue + 1.0) } public class var CURRENT_VERSION: String { return "\(systemFloatVersion())" } // MARK: iOS 5 Checks public class func IS_OS_5() -> Bool { return isVersion(.five) } public class func IS_OS_5_OR_LATER() -> Bool { return isVersionOrLater(.five) } public class func IS_OS_5_OR_EARLIER() -> Bool { return isVersionOrEarlier(.five) } // MARK: iOS 6 Checks public class func IS_OS_6() -> Bool { return isVersion(.six) } public class func IS_OS_6_OR_LATER() -> Bool { return isVersionOrLater(.six) } public class func IS_OS_6_OR_EARLIER() -> Bool { return isVersionOrEarlier(.six) } // MARK: iOS 7 Checks public class func IS_OS_7() -> Bool { return isVersion(.seven) } public class func IS_OS_7_OR_LATER() -> Bool { return isVersionOrLater(.seven) } public class func IS_OS_7_OR_EARLIER() -> Bool { return isVersionOrEarlier(.seven) } // MARK: iOS 8 Checks public class func IS_OS_8() -> Bool { return isVersion(.eight) } public class func IS_OS_8_OR_LATER() -> Bool { return isVersionOrLater(.eight) } public class func IS_OS_8_OR_EARLIER() -> Bool { return isVersionOrEarlier(.eight) } // MARK: iOS 9 Checks public class func IS_OS_9() -> Bool { return isVersion(.nine) } public class func IS_OS_9_OR_LATER() -> Bool { return isVersionOrLater(.nine) } public class func IS_OS_9_OR_EARLIER() -> Bool { return isVersionOrEarlier(.nine) } /// EZSwiftExtensions public class func isSystemVersionOver(_ requiredVersion: String) -> Bool { switch systemVersion().compare(requiredVersion, options: .numeric) { case .orderedSame, .orderedDescending: //println("iOS >= 8.0") return true case .orderedAscending: //println("iOS < 8.0") return false } } }
da4cb67f965b132f4848c22f6ddc8132
30.511737
109
0.578963
false
false
false
false
grandiere/box
refs/heads/master
box/Firebase/Database/Model/FDbAlgoHostileVirus.swift
mit
1
import Foundation class FDbAlgoHostileVirus:FDbProtocol { let items:[String:FDbAlgoHostileVirusItem] required init?(snapshot:Any) { var items:[String:FDbAlgoHostileVirusItem] = [:] if let snapshotDict:[String:Any] = snapshot as? [String:Any] { let snapshotKeys:[String] = Array(snapshotDict.keys) for virusId:String in snapshotKeys { guard let snapshotVirus:Any = snapshotDict[virusId], let virusItem:FDbAlgoHostileVirusItem = FDbAlgoHostileVirusItem( snapshot:snapshotVirus) else { continue } items[virusId] = virusItem } } self.items = items } func json() -> Any? { return nil } }
6f4fbe7e1c35b10fea152523dfec32bd
23.923077
84
0.467078
false
false
false
false
Miguel-Herrero/Swift
refs/heads/master
Rainy Shiny Cloudy/Rainy Shiny Cloudy/WeatherVC.swift
gpl-3.0
1
// // WeatherVC.swift // Rainy Shiny Cloudy // // Created by Miguel Herrero on 13/12/16. // Copyright © 2016 Miguel Herrero. All rights reserved. // import UIKit import Alamofire import CoreLocation class WeatherVC: UIViewController { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var currentTempLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var currentTempImage: UIImageView! @IBOutlet weak var currentTempTypeLabel: UILabel! @IBOutlet weak var tableView: UITableView! var currentWeather: CurrentWeather! var forecast: Forecast! var forecasts = [Forecast]() let locationManager = CLLocationManager() var currentLocation: CLLocation! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startMonitoringSignificantLocationChanges() locationManager.startUpdatingLocation() //Step-1 Requesting location updates currentWeather = CurrentWeather() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) locationAuthStatus() } func updateMainUI() { dateLabel.text = currentWeather.date currentTempLabel.text = "\(currentWeather.currentTemp) ºC" currentTempTypeLabel.text = currentWeather.weatherType locationLabel.text = currentWeather.cityName currentTempImage.image = UIImage(named: currentWeather.weatherType) tableView.reloadData() } func downloadForecastData(completed: @escaping DownloadComplete) { // DOwnload forecast weather data for TableView let forecastURL = URL(string: FORECAST_URL)! Alamofire.request(forecastURL).responseJSON { (response) in let result = response.result if let dict = result.value as? Dictionary<String, AnyObject> { if let list = dict["list"] as? [Dictionary<String, AnyObject>] { for obj in list { let forecast = Forecast(weatherDict: obj) self.forecasts.append(forecast) } self.forecasts.remove(at: 0) //Remove today from forecast! } } completed() } } } extension WeatherVC: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return forecasts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "weatherCell", for: indexPath) as? WeatherCell { let forecast = forecasts[indexPath.row] cell.configureCell(forecast: forecast) return cell } else { return WeatherCell() } } } extension WeatherVC: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { locationAuthStatus() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { currentLocation = locationManager.location if currentLocation != nil { locationManager.stopUpdatingLocation() } Location.sharedInstance.latitude = currentLocation.coordinate.latitude Location.sharedInstance.longitude = currentLocation.coordinate.longitude print(Location.sharedInstance.latitude ?? "nada", Location.sharedInstance.longitude ?? "nada") currentWeather.downloadWeatherDetails { //Setup UI to load downloaded data self.downloadForecastData { self.updateMainUI() } } } else { locationManager.requestWhenInUseAuthorization() } } /* * If CLLocation is not authorized, we cannot show any weather info */ func locationAuthStatus() { if CLLocationManager.authorizationStatus() != .authorizedWhenInUse { locationManager.requestWhenInUseAuthorization() } } }
9ea66e9f205b7dfa766373e1be540c60
32.076389
116
0.624606
false
false
false
false
zisko/swift
refs/heads/master
test/SILGen/class_bound_protocols.swift
apache-2.0
1
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -module-name Swift -emit-silgen %s | %FileCheck %s enum Optional<T> { case some(T) case none } precedencegroup AssignmentPrecedence {} typealias AnyObject = Builtin.AnyObject // -- Class-bound archetypes and existentials are *not* address-only and can // be manipulated using normal reference type value semantics. protocol NotClassBound { func notClassBoundMethod() } protocol ClassBound : class { func classBoundMethod() } protocol ClassBound2 : class { func classBound2Method() } class ConcreteClass : NotClassBound, ClassBound, ClassBound2 { func notClassBoundMethod() {} func classBoundMethod() {} func classBound2Method() {} } class ConcreteSubclass : ConcreteClass { } // CHECK-LABEL: sil hidden @$Ss19class_bound_generic{{[_0-9a-zA-Z]*}}F func class_bound_generic<T : ClassBound>(x: T) -> T { var x = x // CHECK: bb0([[X:%.*]] : $T): // CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: destroy_value [[X_ADDR]] // CHECK: destroy_value [[X]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @$Ss21class_bound_generic_2{{[_0-9a-zA-Z]*}}F func class_bound_generic_2<T : ClassBound & NotClassBound>(x: T) -> T { var x = x // CHECK: bb0([[X:%.*]] : $T): // CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound, τ_0_0 : NotClassBound> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] // CHECK: end_borrow [[BORROWED_X]] from [[X]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @$Ss20class_bound_protocol{{[_0-9a-zA-Z]*}}F func class_bound_protocol(x: ClassBound) -> ClassBound { var x = x // CHECK: bb0([[X:%.*]] : $ClassBound): // CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound } // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] // CHECK: end_borrow [[BORROWED_X]] from [[X]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @$Ss32class_bound_protocol_composition{{[_0-9a-zA-Z]*}}F func class_bound_protocol_composition(x: ClassBound & NotClassBound) -> ClassBound & NotClassBound { var x = x // CHECK: bb0([[X:%.*]] : $ClassBound & NotClassBound): // CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound & NotClassBound } // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] // CHECK: end_borrow [[BORROWED_X]] from [[X]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound & NotClassBound // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @$Ss19class_bound_erasure{{[_0-9a-zA-Z]*}}F func class_bound_erasure(x: ConcreteClass) -> ClassBound { return x // CHECK: [[PROTO:%.*]] = init_existential_ref {{%.*}} : $ConcreteClass, $ClassBound // CHECK: return [[PROTO]] } // CHECK-LABEL: sil hidden @$Ss30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF : func class_bound_existential_upcast(x: ClassBound & ClassBound2) -> ClassBound { return x // CHECK: bb0([[ARG:%.*]] : $ClassBound & ClassBound2): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPENED:%.*]] = open_existential_ref [[BORROWED_ARG]] : $ClassBound & ClassBound2 to [[OPENED_TYPE:\$@opened(.*) ClassBound & ClassBound2]] // CHECK: [[OPENED_COPY:%.*]] = copy_value [[OPENED]] // CHECK: [[PROTO:%.*]] = init_existential_ref [[OPENED_COPY]] : [[OPENED_TYPE]] : [[OPENED_TYPE]], $ClassBound // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[PROTO]] } // CHECK: } // end sil function '$Ss30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF' // CHECK-LABEL: sil hidden @$Ss41class_bound_to_unbound_existential_upcast1xs13NotClassBound_ps0hI0_sACp_tF : // CHECK: bb0([[ARG0:%.*]] : $*NotClassBound, [[ARG1:%.*]] : $ClassBound & NotClassBound): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[X_OPENED:%.*]] = open_existential_ref [[BORROWED_ARG1]] : $ClassBound & NotClassBound to [[OPENED_TYPE:\$@opened(.*) ClassBound & NotClassBound]] // CHECK: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[ARG0]] : $*NotClassBound, [[OPENED_TYPE]] // CHECK: [[X_OPENED_COPY:%.*]] = copy_value [[X_OPENED]] // CHECK: store [[X_OPENED_COPY]] to [init] [[PAYLOAD_ADDR]] // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] func class_bound_to_unbound_existential_upcast (x: ClassBound & NotClassBound) -> NotClassBound { return x } // CHECK-LABEL: sil hidden @$Ss18class_bound_method1xys10ClassBound_p_tF : // CHECK: bb0([[ARG:%.*]] : $ClassBound): func class_bound_method(x: ClassBound) { var x = x x.classBoundMethod() // CHECK: [[XBOX:%.*]] = alloc_box ${ var ClassBound }, var, name "x" // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[ARG_COPY]] to [init] [[XBOX_PB]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*ClassBound // CHECK: [[X:%.*]] = load [copy] [[READ]] : $*ClassBound // CHECK: [[PROJ:%.*]] = open_existential_ref [[X]] : $ClassBound to $[[OPENED:@opened(.*) ClassBound]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #ClassBound.classBoundMethod!1 // CHECK: apply [[METHOD]]<[[OPENED]]>([[PROJ]]) // CHECK: destroy_value [[PROJ]] // CHECK: destroy_value [[XBOX]] // CHECK: destroy_value [[ARG]] } // CHECK: } // end sil function '$Ss18class_bound_method1xys10ClassBound_p_tF' // rdar://problem/31858378 struct Value {} protocol HasMutatingMethod { mutating func mutateMe() var mutatingCounter: Value { get set } var nonMutatingCounter: Value { get nonmutating set } } protocol InheritsMutatingMethod : class, HasMutatingMethod {} func takesInOut<T>(_: inout T) {} // CHECK-LABEL: sil hidden @$Ss27takesInheritsMutatingMethod1x1yys0bcD0_pz_s5ValueVtF : $@convention(thin) (@inout InheritsMutatingMethod, Value) -> () { func takesInheritsMutatingMethod(x: inout InheritsMutatingMethod, y: Value) { // CHECK: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutateMe!1 : <Self where Self : HasMutatingMethod> (inout Self) -> () -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> () // CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>([[TEMPORARY]]) : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> () // CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod // CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod x.mutateMe() // CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $Value // CHECK-NEXT: [[RESULT:%.*]] = mark_uninitialized [var] [[RESULT_BOX]] : $*Value // CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD_RELOADED:%.*]] = load_borrow [[TEMPORARY]] // // ** *NOTE* This extra copy is here since RValue invariants enforce that all // ** loadable objects are actually loaded. So we form the RValue and // ** load... only to then need to store the value back in a stack location to // ** pass to an in_guaranteed method. PredictableMemOpts is able to handle this // ** type of temporary codegen successfully. // CHECK-NEXT: [[TEMPORARY_2:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store_borrow [[X_PAYLOAD_RELOADED:%.*]] to [[TEMPORARY_2]] // // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!getter.1 : <Self where Self : HasMutatingMethod> (Self) -> () -> Value, [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value // CHECK-NEXT: [[RESULT_VALUE:%.*]] = apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>([[TEMPORARY_2]]) : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value // CHECK-NEXT: dealloc_stack [[TEMPORARY_2]] // CHECK-NEXT: end_borrow [[X_PAYLOAD_RELOADED]] // CHECK-NEXT: assign [[RESULT_VALUE]] to [[RESULT]] : $*Value // CHECK-NEXT: destroy_addr [[TEMPORARY]] // CHECK-NEXT: end_access [[X_ADDR]] // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*Value _ = x.mutatingCounter // CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!setter.1 : <Self where Self : HasMutatingMethod> (inout Self) -> (Value) -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> () // CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>(%1, [[TEMPORARY]]) : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> () // CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod // CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod x.mutatingCounter = y takesInOut(&x.mutatingCounter) _ = x.nonMutatingCounter x.nonMutatingCounter = y takesInOut(&x.nonMutatingCounter) }
544efb34000c808ec8e7fdc40ed462d5
54.408511
382
0.624299
false
false
false
false
brokenseal/iOS-exercises
refs/heads/master
FaceSnap/FaceSnap/PhotoListController.swift
mit
1
// // ViewController.swift // FaceSnap // // Created by Davide Callegari on 25/06/17. // Copyright © 2017 Davide Callegari. All rights reserved. // import UIKit class PhotoListController: UIViewController { lazy var cameraButton: UIButton = { let button = UIButton(type: .system) // Camera Button Customization button.setTitle("Camera", for: []) button.tintColor = .white button.backgroundColor = UIColor(red: 254/255.0, green: 123/255.0, blue: 135/255.0, alpha: 1.0) button.addTarget(self, action: #selector(PhotoListController.presentImagePickerController), for: .touchUpInside) return button }() lazy var mediaPickerManager: MediaPickerManager = { let manager = MediaPickerManager(self) manager.delegate = self return manager }() override func viewDidLoad() { super.viewDidLoad() } override func viewWillLayoutSubviews(){ super.viewWillLayoutSubviews() // Camera Button Layout view.addSubview(cameraButton) cameraButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ cameraButton.leftAnchor.constraint(equalTo: view.leftAnchor), cameraButton.bottomAnchor.constraint(equalTo: view.bottomAnchor), cameraButton.rightAnchor.constraint(equalTo: view.rightAnchor), cameraButton.heightAnchor.constraint(equalToConstant: 56.0) ]) } @objc private func presentImagePickerController(){ mediaPickerManager.presentImagePickerController(true) } } extension PhotoListController: MediaPickerManagerDelegate { func mediaPickerManager(manager: MediaPickerManager, didFinishPickingImage image: UIImage) { // TODO } }
d40faf71ff0f5b672c17c8b7f80621aa
30.220339
120
0.67101
false
false
false
false
wesj/firefox-ios-1
refs/heads/master
Sync/Record.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared let ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60; /** * Immutable representation for Sync records. * * Envelopes consist of: * Required: "id", "collection", "payload". * Optional: "modified", "sortindex", "ttl". * * Deletedness is a property of the payload. */ public class Record<T: CleartextPayloadJSON> { public let id: String public let payload: T public let modified: UInt64 public let sortindex: Int public let ttl: Int // Seconds. // This is a hook for decryption. // Right now it only parses the string. In subclasses, it'll parse the // string, decrypt the contents, and return the data as a JSON object. // From the docs: // // payload none string 256k // A string containing a JSON structure encapsulating the data of the record. // This structure is defined separately for each WBO type. // Parts of the structure may be encrypted, in which case the structure // should also specify a record for decryption. // // @seealso EncryptedRecord. public class func payloadFromPayloadString(envelope: EnvelopeJSON, payload: String) -> T? { return T(payload) } // TODO: consider using error tuples. public class func fromEnvelope(envelope: EnvelopeJSON, payloadFactory: (String) -> T?) -> Record<T>? { if !(envelope.isValid()) { println("Invalid envelope.") return nil } let payload = payloadFactory(envelope.payload) if (payload == nil) { println("Unable to parse payload.") return nil } if payload!.isValid() { return Record<T>(envelope: envelope, payload: payload!) } println("Invalid payload \(payload!.toString(pretty: true)).") return nil } /** * Accepts an envelope and a decrypted payload. * Inputs are not validated. Use `fromEnvelope` above. */ convenience init(envelope: EnvelopeJSON, payload: T) { // TODO: modified, sortindex, ttl self.init(id: envelope.id, payload: payload, modified: envelope.modified, sortindex: envelope.sortindex) } init(id: String, payload: T, modified: UInt64 = UInt64(time(nil)), sortindex: Int = 0, ttl: Int = ONE_YEAR_IN_SECONDS) { self.id = id self.payload = payload; self.modified = modified self.sortindex = sortindex self.ttl = ttl } func equalIdentifiers(rec: Record) -> Bool { return rec.id == self.id } // Override me. func equalPayloads(rec: Record) -> Bool { return equalIdentifiers(rec) && rec.payload.deleted == self.payload.deleted } func equals(rec: Record) -> Bool { return rec.sortindex == self.sortindex && rec.modified == self.modified && equalPayloads(rec) } }
97d1e1653c6105c98d6e62efdc4a866f
31.051546
124
0.623874
false
false
false
false
Yummypets/YPImagePicker
refs/heads/master
Source/Pages/Video/YPVideoCaptureHelper.swift
mit
1
// // YPVideoHelper.swift // YPImagePicker // // Created by Sacha DSO on 27/01/2018. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit import AVFoundation import CoreMotion /// Abstracts Low Level AVFoudation details. class YPVideoCaptureHelper: NSObject { public var isRecording: Bool { return videoOutput.isRecording } public var didCaptureVideo: ((URL) -> Void)? public var videoRecordingProgress: ((Float, TimeInterval) -> Void)? private let session = AVCaptureSession() private var timer = Timer() private var dateVideoStarted = Date() private let sessionQueue = DispatchQueue(label: "YPVideoCaptureHelperQueue") private var videoInput: AVCaptureDeviceInput? private var videoOutput = AVCaptureMovieFileOutput() private var videoRecordingTimeLimit: TimeInterval = 0 private var isCaptureSessionSetup: Bool = false private var isPreviewSetup = false private var previewView: UIView! private var motionManager = CMMotionManager() private var initVideoZoomFactor: CGFloat = 1.0 // MARK: - Init public func start(previewView: UIView, withVideoRecordingLimit: TimeInterval, completion: @escaping () -> Void) { self.previewView = previewView self.videoRecordingTimeLimit = withVideoRecordingLimit sessionQueue.async { [weak self] in guard let strongSelf = self else { return } if !strongSelf.isCaptureSessionSetup { strongSelf.setupCaptureSession() } strongSelf.startCamera(completion: { completion() }) } } // MARK: - Start Camera public func startCamera(completion: @escaping (() -> Void)) { guard !session.isRunning else { print("Session is already running. Returning.") return } sessionQueue.async { [weak self] in // Re-apply session preset self?.session.sessionPreset = .photo let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) switch status { case .notDetermined, .restricted, .denied: self?.session.stopRunning() case .authorized: self?.session.startRunning() completion() self?.tryToSetupPreview() @unknown default: ypLog("unknown default reached. Check code.") } } } // MARK: - Flip Camera public func flipCamera(completion: @escaping () -> Void) { sessionQueue.async { [weak self] in guard let strongSelf = self else { return } strongSelf.session.beginConfiguration() strongSelf.session.resetInputs() if let videoInput = strongSelf.videoInput { strongSelf.videoInput = flippedDeviceInputForInput(videoInput) } if let videoInput = strongSelf.videoInput { if strongSelf.session.canAddInput(videoInput) { strongSelf.session.addInput(videoInput) } } // Re Add audio recording if let audioDevice = AVCaptureDevice.audioCaptureDevice, let audioInput = try? AVCaptureDeviceInput(device: audioDevice), strongSelf.session.canAddInput(audioInput) { strongSelf.session.addInput(audioInput) } strongSelf.session.commitConfiguration() DispatchQueue.main.async { completion() } } } // MARK: - Focus public func focus(onPoint point: CGPoint) { if let device = videoInput?.device { setFocusPointOnDevice(device: device, point: point) } } // MARK: - Zoom public func zoom(began: Bool, scale: CGFloat) { guard let device = videoInput?.device else { return } if began { initVideoZoomFactor = device.videoZoomFactor return } do { try device.lockForConfiguration() defer { device.unlockForConfiguration() } var minAvailableVideoZoomFactor: CGFloat = 1.0 if #available(iOS 11.0, *) { minAvailableVideoZoomFactor = device.minAvailableVideoZoomFactor } var maxAvailableVideoZoomFactor: CGFloat = device.activeFormat.videoMaxZoomFactor if #available(iOS 11.0, *) { maxAvailableVideoZoomFactor = device.maxAvailableVideoZoomFactor } maxAvailableVideoZoomFactor = min(maxAvailableVideoZoomFactor, YPConfig.maxCameraZoomFactor) let desiredZoomFactor = initVideoZoomFactor * scale device.videoZoomFactor = max(minAvailableVideoZoomFactor, min(desiredZoomFactor, maxAvailableVideoZoomFactor)) } catch let error { ypLog("Error: \(error)") } } // MARK: - Stop Camera public func stopCamera() { guard session.isRunning else { return } sessionQueue.async { [weak self] in self?.session.stopRunning() } } // MARK: - Torch public func hasTorch() -> Bool { return videoInput?.device.hasTorch ?? false } public func currentTorchMode() -> AVCaptureDevice.TorchMode { guard let device = videoInput?.device else { return .off } if !device.hasTorch { return .off } return device.torchMode } public func toggleTorch() { videoInput?.device.tryToggleTorch() } // MARK: - Recording public func startRecording() { let outputURL = YPVideoProcessor.makeVideoPathURL(temporaryFolder: true, fileName: "recordedVideoRAW") checkOrientation { [weak self] orientation in guard let strongSelf = self else { return } if let connection = strongSelf.videoOutput.connection(with: .video) { if let orientation = orientation, connection.isVideoOrientationSupported { connection.videoOrientation = orientation } strongSelf.videoOutput.startRecording(to: outputURL, recordingDelegate: strongSelf) } } } public func stopRecording() { videoOutput.stopRecording() } // Private private func setupCaptureSession() { session.beginConfiguration() let cameraPosition: AVCaptureDevice.Position = YPConfig.usesFrontCamera ? .front : .back let aDevice = AVCaptureDevice.deviceForPosition(cameraPosition) if let d = aDevice { videoInput = try? AVCaptureDeviceInput(device: d) } if let videoInput = videoInput { if session.canAddInput(videoInput) { session.addInput(videoInput) } // Add audio recording if let audioDevice = AVCaptureDevice.audioCaptureDevice, let audioInput = try? AVCaptureDeviceInput(device: audioDevice), session.canAddInput(audioInput) { session.addInput(audioInput) } let timeScale: Int32 = 30 // FPS let maxDuration = CMTimeMakeWithSeconds(self.videoRecordingTimeLimit, preferredTimescale: timeScale) videoOutput.maxRecordedDuration = maxDuration if let sizeLimit = YPConfig.video.recordingSizeLimit { videoOutput.maxRecordedFileSize = sizeLimit } videoOutput.minFreeDiskSpaceLimit = YPConfig.video.minFreeDiskSpaceLimit if YPConfig.video.fileType == .mp4, YPConfig.video.recordingSizeLimit != nil { videoOutput.movieFragmentInterval = .invalid // Allows audio for MP4s over 10 seconds. } if session.canAddOutput(videoOutput) { session.addOutput(videoOutput) } session.sessionPreset = .high } session.commitConfiguration() isCaptureSessionSetup = true } // MARK: - Recording Progress @objc func tick() { let timeElapsed = Date().timeIntervalSince(dateVideoStarted) var progress: Float if let recordingSizeLimit = YPConfig.video.recordingSizeLimit { progress = Float(videoOutput.recordedFileSize) / Float(recordingSizeLimit) } else { progress = Float(timeElapsed) / Float(videoRecordingTimeLimit) } // VideoOutput configuration is responsible for stopping the recording. Not here. DispatchQueue.main.async { self.videoRecordingProgress?(progress, timeElapsed) } } // MARK: - Orientation /// This enables to get the correct orientation even when the device is locked for orientation \o/ private func checkOrientation(completion: @escaping(_ orientation: AVCaptureVideoOrientation?) -> Void) { motionManager.accelerometerUpdateInterval = 5 motionManager.startAccelerometerUpdates( to: OperationQueue() ) { [weak self] data, _ in self?.motionManager.stopAccelerometerUpdates() guard let data = data else { completion(nil) return } let orientation: AVCaptureVideoOrientation = abs(data.acceleration.y) < abs(data.acceleration.x) ? data.acceleration.x > 0 ? .landscapeLeft : .landscapeRight : data.acceleration.y > 0 ? .portraitUpsideDown : .portrait DispatchQueue.main.async { completion(orientation) } } } // MARK: - Preview func tryToSetupPreview() { if !isPreviewSetup { setupPreview() isPreviewSetup = true } } func setupPreview() { let videoLayer = AVCaptureVideoPreviewLayer(session: session) DispatchQueue.main.async { videoLayer.frame = self.previewView.bounds videoLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill self.previewView.layer.addSublayer(videoLayer) } } } extension YPVideoCaptureHelper: AVCaptureFileOutputRecordingDelegate { public func fileOutput(_ captureOutput: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(tick), userInfo: nil, repeats: true) dateVideoStarted = Date() } public func fileOutput(_ captureOutput: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { if let error = error { ypLog("Error: \(error)") } if YPConfig.onlySquareImagesFromCamera { YPVideoProcessor.cropToSquare(filePath: outputFileURL) { [weak self] url in guard let _self = self, let u = url else { return } _self.didCaptureVideo?(u) } } else { self.didCaptureVideo?(outputFileURL) } timer.invalidate() } }
43ebd5cc779e18f34b7020e45872b8b8
33.766962
117
0.584846
false
false
false
false
vvusu/LogAnalysis
refs/heads/master
Log Analysis/DropView.swift
lgpl-3.0
1
// // DropView.swift // Log Analysis // // Created by vvusu on 10/26/15. // Copyright © 2015 vvusu. All rights reserved. // import Cocoa import AppKit class DropView: NSView { var image: NSImage! override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) if (image == nil) { NSColor.orangeColor().set() NSRectFill(dirtyRect) } else { image.drawInRect(dirtyRect, fromRect: NSZeroRect, operation: NSCompositingOperation.CompositeSourceOver, fraction: 1) } // Drawing code here. } convenience init() { self.init(frame: CGRectZero) } override init(frame frameRect: NSRect) { super.init(frame: frameRect) // let theArray = NSImage.imageTypes() self.registerForDraggedTypes([NSFilenamesPboardType]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { // let sourceDragMask = sender.draggingSourceOperationMask() // let pboard = sender.draggingPasteboard() // if pboard.availableTypeFromArray([NSFilenamesPboardType]) == NSFilenamesPboardType { // if sourceDragMask.rawValue & NSDragOperation.Generic.rawValue != 0 { // return NSDragOperation.Generic // } // } // return NSDragOperation.None //加载immage 能否加载上去 if NSImage.canInitWithPasteboard(sender.draggingPasteboard()) && sender.draggingSourceOperationMask().rawValue & NSDragOperation.Copy.rawValue != 0 { return NSDragOperation.Copy } else { return NSDragOperation.None } } override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation { self.print("UPDATED") return NSDragOperation.Copy } override func draggingExited(sender: NSDraggingInfo?) { self.print("ENDED") } override func prepareForDragOperation(sender: NSDraggingInfo) -> Bool { return true } override func performDragOperation(sender: NSDraggingInfo) -> Bool { // ... perform your magic // return true/false depending on success if NSImage.canInitWithPasteboard(sender.draggingPasteboard()) { self.image = NSImage.init(pasteboard: sender.draggingPasteboard()) } return true } override func concludeDragOperation(sender: NSDraggingInfo?) { self.needsDisplay = true } }
c9e18e3cce01b0282c0016ee85658fbe
28.931818
157
0.626424
false
false
false
false
ryan-boder/path-of-least-resistance
refs/heads/master
PathOfLeastResistance/Grid.swift
apache-2.0
1
import Foundation /** * Provides a navigateable grid. */ class Grid { var matrix: Array<Array<Int>>! init(_ matrix: Array<Array<Int>>) { self.matrix = matrix } var rows: Int { return matrix.count } var columns: Int { return matrix[0].count } /** * Returns the resistance at the given coordinates. */ func get(coords: (Int, Int)) -> Int! { let (r, c) = coords if r <= 0 || r > matrix.count || c <= 0 || c > matrix[0].count { return nil } return matrix[r - 1][c - 1] } /** * Navigates straight to the right and returns the new point. */ func right(coords: (Int, Int)) -> (Int, Int)! { let (r, c) = coords if c >= matrix[0].count { return nil } return (r, c + 1) } /** * Navigates up and to the right and returns the new point. */ func up(coords: (Int, Int)) -> (Int, Int)! { let (r, c) = coords if c >= matrix[0].count { return nil } return (r == 1 ? matrix.count : r - 1, c + 1) } /** * Navigates down and to the right and returns the new point. */ func down(coords: (Int, Int)) -> (Int, Int)! { let (r, c) = coords if c >= matrix[0].count { return nil } return (r == matrix.count ? 1 : r + 1, c + 1) } }
a5b3d35cb5f56ec80564e40f0dde6fc5
21.242424
72
0.46049
false
false
false
false
Gitliming/Demoes
refs/heads/master
Demoes/Demoes/QRScan/QRScanController.swift
apache-2.0
1
// // QRScanController.swift // Dispersive switch // // Created by xpming on 16/6/23. // Copyright © 2016年 xpming. All rights reserved. // import UIKit import AVFoundation class QRScanController: BaseViewController, AVCaptureMetadataOutputObjectsDelegate ,UIAlertViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate{ var scanView:ScanView? var guideLabel:UILabel? var openPhoto:UIButton? var openLight:UIButton? var imagePicker:UIImagePickerController? var session:AVCaptureSession? var input:AVCaptureDeviceInput? var output:AVCaptureMetadataOutput? var preLayer:AVCaptureVideoPreviewLayer? var avplayer:AVAudioPlayer? var isLightOn = false override func viewDidLoad() { super.viewDidLoad() setupUI() scanQR() } override func viewWillAppear(_ animated: Bool) { } override func viewWillDisappear(_ animated: Bool) { session?.stopRunning() } func setupUI(){ title = "扫描中。。。" view.layer.contents = UIImage(named: "i")?.cgImage let scanW:CGFloat = 200 let point = CGPoint(x: view.center.x - scanW/2, y: view.center.y - scanW/2) scanView = ScanView(frame: CGRect(origin: point, size: CGSize(width: scanW, height: scanW))) let y = scanView?.frame.maxY guideLabel = UILabel(frame: CGRect(x: (scanView?.frame.origin.x)!, y: y! + 20, width: scanView!.bounds.width, height: 60)) guideLabel?.text = "请将二维码置于窗口中,将会自动扫描" guideLabel?.textColor = UIColor.white guideLabel?.numberOfLines = 0 let yp = guideLabel?.frame.maxY let xp = guideLabel?.frame.minX let wp = guideLabel?.bounds.width openPhoto = UIButton(frame: CGRect(x: xp!, y: yp!, width: wp!/2 - 2, height: 30)) openPhoto?.setBackgroundImage(UIImage(named: "l"), for: UIControlState()) openPhoto?.setTitle("打开相册", for: UIControlState()) openPhoto?.addTarget(self, action: #selector(QRScanController.openPhotoAction), for: .touchUpInside) openLight = UIButton(frame: CGRect(x: xp! + wp!/2 + 2, y: yp!, width: wp!/2 - 2, height: 30)) openLight?.setTitle("打开灯光", for: UIControlState()) openLight?.setBackgroundImage(UIImage(named: "l"), for: UIControlState()) openLight?.addTarget(self, action: #selector(QRScanController.openLightAction), for: .touchUpInside) view.addSubview(scanView!) view.addSubview(guideLabel!) view.addSubview(openPhoto!) view.addSubview(openLight!) } //扫描成功声音提示 func scanedSound(){ let path = Bundle.main.path(forResource: "qrcode_found.wav", ofType: nil) let url = URL(fileURLWithPath: path!) do{ avplayer = try AVAudioPlayer(contentsOf: url) avplayer!.play() }catch{ print(error) } } func openPhotoAction(){ imagePicker = UIImagePickerController() imagePicker!.allowsEditing = true imagePicker?.delegate = self self.present(imagePicker!, animated: true, completion: nil) } ///mark:--UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { picker.dismiss(animated: true, completion: nil) let imageData = UIImageJPEGRepresentation(image, 1) //软件渲染消除警告修改Gpu渲染优先级提高渲染效率 let context = CIContext(options: [kCIContextUseSoftwareRenderer:true, kCIContextPriorityRequestLow:false]) let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: nil) let ciImage = CIImage(data: imageData!) let array = detector!.features(in: ciImage!) let feature = array.first as? CIQRCodeFeature var message = "" if feature != nil { print(feature!.messageString!) message = (feature?.messageString)! }else{ message = "没有扫描到内容" } scanedSound() let alertCtrl = UIAlertController(title: "扫描结果", message: message, preferredStyle: .actionSheet) let alertAction = UIAlertAction(title: "确定", style: .cancel) { (alertAction) in self.session?.startRunning() } alertCtrl.addAction(alertAction) self.present(alertCtrl, animated: true, completion: nil) } ///mark:--UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } func openLightAction(){ let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) if (device?.hasTorch)! { do{ try device?.lockForConfiguration() if isLightOn == false { device?.torchMode = AVCaptureTorchMode.on isLightOn = true }else{ device?.torchMode = AVCaptureTorchMode.off isLightOn = false } }catch{ print(error) } }else{ let alertCtrl = UIAlertController(title: "提示", message: "sorry!你的设备不支持!", preferredStyle: .actionSheet) let alertAction = UIAlertAction(title: "确定", style: .cancel, handler: nil) alertCtrl.addAction(alertAction) self.present(alertCtrl, animated: true, completion: nil) } } func scanQR(){ //创建设备对象 let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { input = try AVCaptureDeviceInput.init(device: device) }catch{ print(error) } output = AVCaptureMetadataOutput() session = AVCaptureSession() preLayer = AVCaptureVideoPreviewLayer(session: session) preLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill preLayer?.frame = (scanView?.frame)! view.layer.insertSublayer(preLayer!, at: 0) if session?.canAddInput(input) == true && input != nil { session?.addInput(input) }else{ let alertVc = UIAlertController(title: "提示", message: "对不起!您的设备无法启动相机", preferredStyle: .actionSheet) let alertAction = UIAlertAction(title: "确定", style: .default, handler: nil) let alertAction2 = UIAlertAction(title: "返回", style: .cancel, handler: nil) alertVc.addAction(alertAction) alertVc.addAction(alertAction2) self.present(alertVc, animated: true, completion: nil) return} if session?.canAddOutput(output) == true && output != nil{ session?.addOutput(output) }else{return} //设置数据源为二维码数据源 output?.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) output?.metadataObjectTypes = [AVMetadataObjectTypeQRCode] let screenHeight = UIScreen.main.bounds.height let screenWidth = UIScreen.main.bounds.width let bounds = scanView?.bounds let origin = scanView?.frame.origin output?.rectOfInterest = CGRect(x: (origin?.y)!/screenHeight, y: (origin?.x)!/screenWidth, width: 2*(bounds?.height)!/screenHeight , height: 2*(bounds?.width)!/screenWidth); //启动扫描 session?.sessionPreset = AVCaptureSessionPresetHigh session?.startRunning() } //--mark AVCaptureMetadataOutputObjectsDelegate func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { scanedSound() session?.stopRunning() scanView?.stopAnimating() if metadataObjects != nil { let obj = metadataObjects.first let str = (obj as AnyObject).absoluteString if (str??.hasPrefix("http"))! { let web = UIWebView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64)) let url = URL(string: str!!) web.loadHTMLString("您扫描到的内容是\(String(describing: str))", baseURL: url) view.addSubview(web) }else{ let alertCtrl = UIAlertController(title: "扫描结果", message: str!, preferredStyle: .actionSheet) let alertAction = UIAlertAction(title: "确定", style: .cancel, handler: { (alertAction) in self.session?.startRunning() self.scanView?.startAnimating() }) alertCtrl.addAction(alertAction) self.present(alertCtrl, animated: true, completion: nil) } } } override func didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
6cd0042be3e50eb880b044ccce64184b
40.119816
181
0.62535
false
false
false
false
tzef/BunbunuCustom
refs/heads/master
BunbunuCustom/BunbunuCustom/ImageView/ImageViewGroupViewController.swift
mit
1
// // ImageViewGroupViewController.swift // BunbunuCustom // // Created by LEE ZHE YU on 2016/7/7. // Copyright © 2016年 LEE ZHE YU. All rights reserved. // import UIKit private let reuseIdentifier = "customCell" class ImageViewGroupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! let items = ["CircleImageView", "CircleProgressImageView"] override func viewDidLoad() { super.viewDidLoad() } // MARK: - TableView func numberOfSectionsInTableView(tableView: UITableView) -> Int { return items.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return NSStringFromClass(CircleImageView) case 1: return NSStringFromClass(CircleProgressImageView) default: return "" } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let cellName = items[indexPath.section] if let view = NSBundle.mainBundle().loadNibNamed(cellName, owner: nil, options: nil)[0] as? UIView { return view.frame.height } else { return tableView.estimatedRowHeight } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as? ViewCell { let cellName = items[indexPath.section] if let view = NSBundle.mainBundle().loadNibNamed(cellName, owner: nil, options: nil)[0] as? UIView { cell.configureCell(view) } return cell } else { return UITableViewCell() } } }
e08669254795e49d6662d6c5093476eb
34.535714
122
0.657789
false
false
false
false
luiswdy/HowLoud
refs/heads/master
HowLoud/MainPresenter.swift
mit
1
// // MainPresenter.swift // HowLoud // // Created by Luis Wu on 6/2/16. // Copyright © 2016 Luis Wu. All rights reserved. // import UIKit class MainPresenter { private var _decibelMeterMinValue = DecibelMeter.MinValue private var _decibelMeterMaxValue = DecibelMeter.MaxValue private var decibelInfoClosure: ((CGFloat, String, String) -> Void)? = nil var decibelMeterMinValue: String? { get { return String(format: NSLocalizedString("gauge_range_format_string", comment: "format string"), _decibelMeterMinValue) } } var decibelMeterMaxValue: String? { get { return String(format: NSLocalizedString("gauge_range_format_string", comment: "format string"), _decibelMeterMaxValue) } } lazy var decibelMeter: DecibelMeter = DecibelMeter(dBHandler: { [weak self] (avgSpl, peakSpl) in let avgInfo = String(format: NSLocalizedString("avg_format_string",comment: "format string"), avgSpl) let peakInfo = String(format: NSLocalizedString("peak_format_string",comment: "format string"), peakSpl) self?.decibelInfoClosure?(CGFloat(avgSpl), avgInfo, peakInfo) }) func subscribeDecibelInfo(closure: (CGFloat, String, String) -> Void) { decibelInfoClosure = closure } func allowMic() -> Bool { return decibelMeter.isMicGranted } func toggleMeasuring() -> Bool { if decibelMeter.isMeasuring() { decibelMeter.stopMeasuring() } else { decibelMeter.startMeasuring() } return decibelMeter.isMeasuring() } }
f5deb0f91ea3a77a1514e3cff683f46b
31.8
130
0.64878
false
false
false
false
Ivacker/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00360-swift-parser-parseexprlist.swift
apache-2.0
12
// 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 import h } func e<l { enum e { func e j { } class l: j{ k() -> ()) } func j<o : BooleanType>(l: o) { } func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) { return { (p: (Any, Any) -> Any) -> Any in func n<n : l,) { } n(e()) struct d<f : e, g: e where g.h == f.h> {{ } struct B<T : A> { } protocol C { ty } } protocol a { } protocol h : a { } protocol k : a { } protocol g { } struct n : g { } func i<h : h, f : g m f.n == h> (g: f) { } func i<n : g m n.n = o) { } protoc { } protocol f { protocol c : b { func b class A { class func a() -> String { let d: String = { }() } class d<c>: NSObject { init(b: c) { } } protocol A { } class C<D> { init <A: A where A.B == D>(e: A.B) { } } class A { class func a { return static let d: String = { }() func x } ) T} protocol A { } struct B<T : A> { lett D : C { func g<T where T.E == F>(f: B<T>) { } } struct d<f : e, g: e where g.h == f.h> { col P { } } } i struct c { c a(b: Int0) { } class A { class func a() -> Self { return b(self.dy
36a57fe64b3138c032ca33e38b71f145
12.727273
87
0.540563
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/SLV_301_SellMainController.swift
mit
1
// // SLV_301_SellMainController.swift // selluv-ios // // Created by 조백근 on 2016. 11. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // /* 판매 메인 컨트롤러 */ import Foundation import UIKit import SnapKit import RealmSwift class SLV_301_SellMainController: SLVBaseStatusHiddenController { var tr_presentTransition: TRViewControllerTransitionDelegate? @IBOutlet weak var directButton: UIButton! @IBOutlet weak var balletButton: UIButton! @IBOutlet weak var sellGuideButton: UIButton! @IBOutlet weak var saveListButton: UIButton! @IBOutlet weak var callKakaoButton: UIButton! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var saveView: UIView! @IBOutlet weak var kakaoView: UIView! @IBOutlet weak var saveLabel: UILabel! @IBOutlet weak var kakaoLabel: UILabel! @IBOutlet weak var topForLogo: NSLayoutConstraint! @IBOutlet weak var topForTitle: NSLayoutConstraint! @IBOutlet weak var topForDirectButton: NSLayoutConstraint! @IBOutlet weak var topForGuide: NSLayoutConstraint! var aniObjects: [AnyObject]? override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } func settupLayout() { let height = UIScreen.main.bounds.size.height self.topForLogo.constant = height * 0.131 self.topForTitle.constant = height * 0.042 self.topForDirectButton.constant = height * 0.057 self.topForGuide.constant = height * 0.028 self.closeButton.translatesAutoresizingMaskIntoConstraints = false self.kakaoView.translatesAutoresizingMaskIntoConstraints = false self.saveView.translatesAutoresizingMaskIntoConstraints = false self.resetAppearLayout() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabController.animationTabBarHidden(false) tabController.hideFab() // self.setupAppearAnimation() self.resetSellerData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.isNavigationBarHidden = true self.navigationBar?.barHeight = 0 self.playAppearAnimation() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.resetAppearLayout() } override func viewDidLoad() { super.viewDidLoad() self.settupLayout() self.readyInfo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func resetSellerData() { TempInputInfoModel.shared.isGenderPass = false } func readyInfo() { let w = UIScreen.main.bounds.size.width/2 let h = UIScreen.main.bounds.size.height let closeHidePoint = CGPoint(x: w, y: h) //46, 16 //65, 85 let w_spacing = CGFloat(16 + 32) let h_spacing = CGFloat(46 + 42) let h_spacing_close = CGFloat(16 + 16) let v_height = h - h_spacing let v_height_close = h - h_spacing_close let tempPoint = CGPoint(x: w_spacing, y: v_height) let kakaoPoint = CGPoint(x: (w*2) - w_spacing, y: v_height) let closePoint = CGPoint(x: w, y: v_height_close) let views = [ [self.saveView, tempPoint, closeHidePoint], [self.kakaoView, kakaoPoint, closeHidePoint], [self.closeButton, closePoint, closeHidePoint]] self.aniObjects = views as [AnyObject]? } func resetAppearLayout() { //46, 16 //65, 85 self.kakaoLabel.isHidden = true self.saveLabel.isHidden = true self.kakaoView.isHidden = true self.saveView.isHidden = true self.closeButton.isHidden = true let w = UIScreen.main.bounds.size.width/2 let h = UIScreen.main.bounds.size.height let views = [self.saveView, self.kakaoView, self.closeButton] _ = views.map() { let view = $0! as UIView // view.cheetah.move(w, h).run() // RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) view.snp.remakeConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } } } func setupAppearAnimation() { let w = UIScreen.main.bounds.size.width/2 let h = UIScreen.main.bounds.size.height self.closeButton.snp.updateConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } self.kakaoView.snp.updateConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } self.saveView.snp.updateConstraints { (make) in make.centerX.equalTo(w) make.centerY.equalTo(h) } // _ = self.aniObjects!.map() { // let list = $0 as! [AnyObject] // let hide = list.last as! CGPoint // let view = list.first as! UIView // view.isHidden = true // let point = list[1] as! CGPoint // let x = hide.x - point.x // let y = hide.y - point.y //// view.cheetah.move(x, y).delay(0.01).wait(0.02).run().remove() //// RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) // } } func playAppearAnimation() { // RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1)) _ = self.aniObjects!.map() { let list = $0 as! [AnyObject] (list.first as! UIView).isHidden = false let point = list[1] as! CGPoint let hide = list.last as! CGPoint let x = point.x - hide.x let y = point.y - hide.y let view = list.first as! UIView view.cheetah.move(x, y).duration(0.2).delay(0.01).easeInBack.wait(0.02).run() RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) } self.kakaoLabel.isHidden = false self.saveLabel.isHidden = false } @IBAction func touchDirectSell(_ sender: Any) { TempInputInfoModel.shared.isDirectInput = true TempInputInfoModel.shared.isNewCase = true } @IBAction func touchBalletSell(_ sender: Any) { TempInputInfoModel.shared.isDirectInput = false TempInputInfoModel.shared.isNewCase = true } @IBAction func touchPopupGuide(_ sender: Any) { } @IBAction func touchTempList(_ sender: Any) { let board = UIStoryboard(name:"Sell", bundle: nil) let navigationController = board.instantiateViewController(withIdentifier: "saveListNavigationController") as! UINavigationController let controller = navigationController.viewControllers.first as! SLV_3a2_SellTempSaveListController controller.modalDelegate = self self.tr_presentViewController(navigationController, method: TRPresentTransitionMethod.twitter) { print("Present finished.") } } @IBAction func touchKakao(_ sender: Any) { // let board = UIStoryboard(name:"Sell", bundle: nil) // let controller = board.instantiateViewController(withIdentifier: "SLV_361_SellDirectFinalSNSShareController") as! SLV_361_SellDirectFinalSNSShareController // self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { // } let board = UIStoryboard(name:"Sell", bundle: nil) let navigationController = board.instantiateViewController(withIdentifier: "addrNavigationController") as! UINavigationController let controller = navigationController.viewControllers.first as! SLVAddressSearchController controller.modalDelegate = self self.tr_presentViewController(navigationController, method: TRPresentTransitionMethod.fade) { print("Present finished.") } } @IBAction func touchSellClose(_ sender: Any) { TempInputInfoModel.shared.saveCurrentModel() tabController.closePresent() { } } } extension SLV_301_SellMainController: ModalTransitionDelegate { func modalViewControllerDismiss(callbackData data:AnyObject?) { log.debug("SLV_301_SellMainController.modalViewControllerDismiss(callbackData:)") tr_dismissViewController(completion: { if let back = data { let cb = back as! [String: AnyObject] let key = cb["command"] as! String if key != nil { if key == "next" { let step = cb["step"] as! Int let board = UIStoryboard(name:"Sell", bundle: nil) switch step { case 1: self.delay(time: 0.2) { let controller = board.instantiateViewController(withIdentifier: "SLV_380_SellBallet1SellerInfoController") as! SLV_380_SellBallet1SellerInfoController self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 2: self.delay(time: 0.2) { let step2Controller = board.instantiateViewController(withIdentifier: "SLV_320_SellDirectStep2ItemInfoController") as! SLV_320_SellDirectStep2ItemInfoController self.navigationController?.tr_pushViewController(step2Controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 3: self.delay(time: 0.2) { let step2Controller = board.instantiateViewController(withIdentifier: "SLV_330_SellDirectStep3AdditionalInfoController") as! SLV_330_SellDirectStep3AdditionalInfoController self.navigationController?.tr_pushViewController(step2Controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 4: self.delay(time: 0.2) { let stepController = board.instantiateViewController(withIdentifier: "SLV_340_SellDirectStep4PriceController") as! SLV_340_SellDirectStep4PriceController self.navigationController?.tr_pushViewController(stepController, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break case 5: self.delay(time: 0.2) { let stepController = board.instantiateViewController(withIdentifier: "SLV_350_SellDirectStep5SellerInfoController") as! SLV_350_SellDirectStep5SellerInfoController self.navigationController?.tr_pushViewController(stepController, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } break default: break } } } } }) } }
0fb55202a12d02acce0e6ff032f14259
40.363636
204
0.592646
false
false
false
false
iOS-mamu/SS
refs/heads/master
P/Pods/PSOperations/PSOperations/OperationCondition.swift
mit
1
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the fundamental logic relating to Operation conditions. */ import Foundation public let OperationConditionKey = "OperationCondition" /** A protocol for defining conditions that must be satisfied in order for an operation to begin execution. */ public protocol OperationCondition { /** The name of the condition. This is used in userInfo dictionaries of `.ConditionFailed` errors as the value of the `OperationConditionKey` key. */ static var name: String { get } /** Specifies whether multiple instances of the conditionalized operation may be executing simultaneously. */ static var isMutuallyExclusive: Bool { get } /** Some conditions may have the ability to satisfy the condition if another operation is executed first. Use this method to return an operation that (for example) asks for permission to perform the operation - parameter operation: The `Operation` to which the Condition has been added. - returns: An `NSOperation`, if a dependency should be automatically added. Otherwise, `nil`. - note: Only a single operation may be returned as a dependency. If you find that you need to return multiple operations, then you should be expressing that as multiple conditions. Alternatively, you could return a single `GroupOperation` that executes multiple operations internally. */ func dependencyForOperation(_ operation: Operation) -> Foundation.Operation? /// Evaluate the condition, to see if it has been satisfied or not. func evaluateForOperation(_ operation: Operation, completion: @escaping (OperationConditionResult) -> Void) } /** An enum to indicate whether an `OperationCondition` was satisfied, or if it failed with an error. */ public enum OperationConditionResult { case satisfied case failed(NSError) var error: NSError? { switch self { case .failed(let error): return error default: return nil } } } func ==(lhs: OperationConditionResult, rhs: OperationConditionResult) -> Bool { switch (lhs, rhs) { case (.satisfied, .satisfied): return true case (.failed(let lError), .failed(let rError)) where lError == rError: return true default: return false } } // MARK: Evaluate Conditions struct OperationConditionEvaluator { static func evaluate(_ conditions: [OperationCondition], operation: Operation, completion: @escaping ([NSError]) -> Void) { // Check conditions. let conditionGroup = DispatchGroup() var results = [OperationConditionResult?](repeating: nil, count: conditions.count) // Ask each condition to evaluate and store its result in the "results" array. for (index, condition) in conditions.enumerated() { conditionGroup.enter() condition.evaluateForOperation(operation) { result in results[index] = result conditionGroup.leave() } } // After all the conditions have evaluated, this block will execute. conditionGroup.notify(queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default)) { // Aggregate the errors that occurred, in order. var failures = results.flatMap { $0?.error } /* If any of the conditions caused this operation to be cancelled, check for that. */ if operation.isCancelled { failures.append(NSError(code: .conditionFailed)) } completion(failures) } } }
0ffb6a8b5d998059eb32f1e699e91bfe
33.883929
127
0.648324
false
false
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/Model/LinearEquations/Solution/Strategy/MLinearEquationsSolutionStrategyRowAddition.swift
mit
1
import Foundation class MLinearEquationsSolutionStrategyRowAddition:MLinearEquationsSolutionStrategy { class func samePivot(step:MLinearEquationsSolutionStep) -> MLinearEquationsSolutionStrategyRowAddition? { var indexEquation:Int = 0 let countEquations:Int = step.equations.count let maxEquation:Int = countEquations - 1 for equation:MLinearEquationsSolutionEquation in step.equations { if indexEquation < maxEquation { let nextIndex:Int = indexEquation + 1 let equationBelow:MLinearEquationsSolutionEquation = step.equations[nextIndex] let pivotIndex:Int = equation.pivotIndex() let pivotIndexBelow:Int = equationBelow.pivotIndex() if pivotIndex == pivotIndexBelow { guard let topPolynomial:MLinearEquationsSolutionEquationItemPolynomial = equation.items[pivotIndex] as? MLinearEquationsSolutionEquationItemPolynomial, let bottomPolynomial:MLinearEquationsSolutionEquationItemPolynomial = equationBelow.items[pivotIndex] as? MLinearEquationsSolutionEquationItemPolynomial else { return nil } let topCoefficient:Double = topPolynomial.coefficient let bottomCoefficient:Double = bottomPolynomial.coefficient var scalar:Double = abs(bottomCoefficient / topCoefficient) if topCoefficient > 0 { if bottomCoefficient > 0 { scalar = -scalar } } else { if bottomCoefficient < 0 { scalar = -scalar } } let strategy:MLinearEquationsSolutionStrategyRowAddition = MLinearEquationsSolutionStrategyRowAddition( step:step, indexRow:nextIndex, scalar:scalar) return strategy } } indexEquation += 1 } return nil } private let indexRow:Int private let scalar:Double private init( step:MLinearEquationsSolutionStep, indexRow:Int, scalar:Double) { self.indexRow = indexRow self.scalar = scalar super.init(step:step) } override func process(delegate:MLinearEquationsSolutionStrategyDelegate) { super.process(delegate:delegate) addRows() } //MARK: private private func addRows() { var equations:[MLinearEquationsSolutionEquation] = [] let scalarString:String = MSession.sharedInstance.stringFrom(number:scalar) let descr:String = String( format:NSLocalizedString("MLinearEquationsSolutionStrategyRowAddition_descr", comment:""), "\(indexRow + 1)", "\(indexRow + 1)", "\((indexRow))", scalarString) var indexEquation:Int = 0 for equation:MLinearEquationsSolutionEquation in self.step.equations { let newEquation:MLinearEquationsSolutionEquation if indexEquation == indexRow { let previousEquation:MLinearEquationsSolutionEquation = self.step.equations[indexEquation - 1] let scaledPrevious:MLinearEquationsSolutionEquation = previousEquation.multiplyScalar( scalar:scalar) newEquation = equation.addEquation( equation:scaledPrevious) } else { newEquation = equation } equations.append(newEquation) indexEquation += 1 } let step:MLinearEquationsSolutionStepProcess = MLinearEquationsSolutionStepProcess( equations:equations, descr:descr) completed(step:step) } }
208fa653e07538bc1e656269eb6e85d7
33.829457
176
0.525929
false
false
false
false
rrunfa/StreamRun
refs/heads/master
StreamRun/AppDelegate.swift
mit
1
// // AppDelegate.swift // StreamRun // // Created by Nikita Nagajnik on 18/10/14. // Copyright (c) 2014 rrunfa. All rights reserved. // import Foundation import Cocoa import AppKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSTableViewDataSource, NSTableViewDelegate, NSUserNotificationCenterDelegate, NSMenuDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var addChannelWindow: NSPanel! @IBOutlet var channelsText: NSTextView! @IBOutlet weak var table: NSTableView! @IBOutlet weak var showOfflineCheckmark: NSButton! @IBOutlet weak var preferencesWindow: NSPanel! var streamConnector = StreamConnector() var streamers: [String: StreamerData]! var visibleStreams: [StreamData]! var settings: Settings! var refreshTime: Double! var refreshTimer: RefreshTimer! var linkLoader: StreamLinkLoader! var statusBar: NSStatusItem! var streamsOpened: Bool = false override func awakeFromNib() { statusBar = NSStatusBar.systemStatusBar().statusItemWithLength(-2) statusBar.highlightMode = true statusBar.title = "S" statusBar.menu = NSMenu() statusBar.menu?.autoenablesItems = false statusBar.menu?.delegate = self; } func menuWillOpen(menu: NSMenu) { menu.removeAllItems() if NSEvent.pressedMouseButtons() == 2 { menu.addItem(NSMenuItem(title: "Show from clipboard", action: "onPaste:", keyEquivalent: "")) } else { streamsOpened = true; updateMenuToStreams(menu); } } func menuDidClose(menu: NSMenu) { streamsOpened = false; } func updateMenuToStreams(menu: NSMenu) { menu.removeAllItems() if visibleStreams == nil || visibleStreams.count == 0 { let item = NSMenuItem(title: "All offline", action: nil, keyEquivalent: "") item.enabled = false menu.addItem(item) } else { for (index, stream) in enumerate(visibleStreams) { let item = NSMenuItem(title: getVisibleName(index), action: "menuItemClicked:", keyEquivalent: "") item.enabled = true item.tag = index menu.addItem(item); } } } func menuItemClicked(sender: NSMenuItem) { streamConnector.startTaskForUrl(visibleStreams[sender.tag].stremUrl(), quality: "best") } func applicationDidFinishLaunching(aNotification: NSNotification) { NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self table.doubleAction = "doubleClick" let reachability = Reachability.reachabilityForInternetConnection() reachability.whenReachable = { reachability in self.scanForOnlineWithNotification(false) } reachability.startNotifier() linkLoader = StreamLinkLoader(); linkLoader.loadStreams { (json) -> Void in self.loadStreams(json!) self.refreshTimer.start() } } @IBAction func onPaste(sender: AnyObject) { let pasteboard = NSPasteboard.generalPasteboard() let url = pasteboard.stringForType(NSPasteboardTypeString) if let url = url { streamConnector.startTaskForUrl(url, quality: "best") } } func loadStreams(json: JSON) { if let streamers = StoreService.parseStreams(json) { self.streamers = streamers } if let settings = StoreService.parseSettings() { self.settings = settings self.showOfflineCheckmark.state = self.settings.showOffline refreshTimer = RefreshTimer(refreshTime: settings.refreshTime) { self.scanForOnlineWithNotification(true) } } self.setupServiceClients() self.scanForOnlineWithNotification(false) } func sortByOnline() { refreshVisibleStreams() visibleStreams.sort { $0 > $1 } } func refreshVisibleStreams() { self.visibleStreams = [] for streamer in streamers { for stream in streamer.1.streams { if self.showOfflineCheckmark.state == 0 { if stream.status == .Online { visibleStreams.append(stream) } } else { visibleStreams.append(stream) } } } } func applicationShouldHandleReopen(theApplication: NSApplication, hasVisibleWindows flag: Bool) -> Bool { window.setIsVisible(true) return true } @IBAction func addChannelClick(sender: AnyObject) { self.populateChannelsText() window.beginSheet(addChannelWindow) { (let response) in } } @IBAction func preferencesClick(sender: AnyObject) { window.beginSheet(preferencesWindow) { (let response) in } } @IBAction func donePreferencesClick(sender: AnyObject) { window.endSheet(preferencesWindow) self.settings.showOffline = self.showOfflineCheckmark.state StoreService.storeSettings(self.settings) scanForOnlineWithNotification(true) } func populateChannelsText() { let streamsContent = StoreService.readFile("streams", fileType: "json") if let text = streamsContent { channelsText.string = text } } @IBAction func doneAddChannelsClick(sender: AnyObject) { window.endSheet(addChannelWindow) } @IBAction func saveChannelsClick(sender: AnyObject) { StoreService.saveFile("streams", fileType: "json", content: channelsText.string!) } func setupServiceClients() { for streamer in streamers { for streamData in streamer.1.streams { switch streamData.service { case "twitch.tv": streamData.serviceClient = TwitchClient() case "cybergame.tv": streamData.serviceClient = CybergameClient() case "goodgame.ru": streamData.serviceClient = GoodgameClient() streamData.streamUrlGen = { (service, channel) in return service + "/channel/" + channel + "/" } default: println("No service client for: \(streamData.service)") } } } } func scanForOnlineWithNotification(useNotification: Bool) { for streamer in streamers { for streamData in streamer.1.streams { if let client = streamData.serviceClient { client.checkOnlineChannel(streamData.channel, result: { online, ignore in if ignore { return } if useNotification && streamData.status == .Offline && online { self.showNotificationByTitle(streamData.name) } streamData.status = online ? .Online: .Offline self.sortByOnline() self.table.reloadData() if self.streamsOpened { self.updateMenuToStreams(self.statusBar.menu!) } }) } } } } func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true } func showNotificationByTitle(title: String) { let not = NSUserNotification() not.title = title; not.informativeText = String(format: "%@ %@", title, "stream is online"); not.soundName = nil; NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(not); } func doubleClick() { let row = table.selectedRow if row < visibleStreams.count { streamConnector.startTaskForUrl(visibleStreams[row].stremUrl(), quality: "best") } } //MARK: - TableDataSource func numberOfRowsInTableView(tableView: NSTableView) -> Int { if let count = visibleStreams?.count { return count } return 0 } func tableView( tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { return getVisibleName(row) } func getVisibleName(row: Int) -> String { let streamData = visibleStreams[row] let streamer = streamers[streamData.name] if streamer?.streams.filter({ $0.status == StreamStatus.Online }).count > 1 { return "\(streamData.name) (\(streamData.service))" } return streamData.name } func tableView(tableView: NSTableView, willDisplayCell cell: AnyObject, forTableColumn tableColumn: NSTableColumn?, row: Int) { let cell = cell as! NSTextFieldCell let service = visibleStreams[row].service let channel = visibleStreams[row].channel let status = visibleStreams[row].status if status == .Online { cell.textColor = NSColor.colorByHex("10A83F") } else if status == .Offline { cell.textColor = NSColor.colorByHex("C40E14") } else { cell.textColor = NSColor.darkGrayColor() } } }
e5a592649a5d537fc2f9e6cd6c2c9f2b
32.42268
131
0.586572
false
false
false
false
CoBug92/MyRestaurant
refs/heads/master
MyRestraunts/MyRestaurantTableViewController.swift
gpl-3.0
1
// // MyRestaurantTableViewController.swift // MyRestaurant // // Created by Богдан Костюченко on 03/10/16. // Copyright © 2016 Bogdan Kostyuchenko. All rights reserved. // import UIKit import CoreData class MyRestaurantTableViewController: UITableViewController, NSFetchedResultsControllerDelegate { @IBAction func unwindSegue(segue: UIStoryboardSegue) { } var restaurants: [Restaurant] = [] var searchController: UISearchController! //Объект который занимается поиском var filterResultArray: [Restaurant] = [] //массив в который будет помещаться все результаты которые удовлетворяют поиску var fetchResultsController: NSFetchedResultsController<Restaurant>! override func viewDidLoad() { super.viewDidLoad() //Work with searchBar searchController = UISearchController(searchResultsController: nil) //Nil because we want that point of entry blocked main list searchController.searchResultsUpdater = self //какой котроллер будет обновлять результаты searchController.searchBar.delegate = self searchController.dimsBackgroundDuringPresentation = false //if true the controller dims tableView.tableHeaderView = searchController.searchBar //SearchBar located in the header of table definesPresentationContext = true //SearchBar works only on the mainPage (doesn't save in detailView) //Create query let fetchRequest: NSFetchRequest<Restaurant> = Restaurant.fetchRequest() //Create descriptor let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) //For getting data fetchRequest.sortDescriptors = [sortDescriptor] //Create context if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext { fetchResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) fetchResultsController.delegate = self //try to take data do { try fetchResultsController.performFetch() //all data write in restaurants restaurants = fetchResultsController.fetchedObjects! } catch let error as NSError { print("Couldn't save data \(error.localizedDescription)") } //reload table tableView.reloadData() } //Clear unnecessary dividers self.tableView.tableFooterView = UIView(frame: CGRect.zero) //Change the interface of BACK button self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil) //Autosizing cell self.tableView.estimatedRowHeight = 85 //default height of cell (for increase capacity) self.tableView.rowHeight = UITableViewAutomaticDimension //Height is calculated automatically } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.searchController.hidesNavigationBarDuringPresentation = false //NavigationBar hides self.navigationController?.hidesBarsOnSwipe = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let userDefaults = UserDefaults.standard let wasInWatched = userDefaults.bool(forKey: "wasInWatched") guard !wasInWatched else { return } //Вызов PageViewController по его идентификатору if let PageViewController = storyboard?.instantiateViewController(withIdentifier: "pageViewController") as? PageViewController { //отображаем контроллер present(PageViewController, animated: true, completion: nil) } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 //Count of sections in TableView } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.isActive && searchController.searchBar.text != "" { return filterResultArray.count } else { return restaurants.count //Count of rows in Section } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyRestaurantTableViewCell let restaurant = restaurantToDisplayAt(indexPath: indexPath) //Configurate the cell: //Writes the value of MyRestaurant.name in nameLabel cell.nameLabel.text = restaurant.name //Writes the value of MyRestaurant.type in typeLabel cell.typeLabel.text = restaurant.type //Writes the value of MyRestaurant.location in locationLabel cell.locationLabel.text = restaurant.location cell.checkImageView.isHidden = !restaurant.wasVisited //Write the value of MyRestaurant.image in thumbnailImageView cell.thumbnailImageView.image = UIImage(data: restaurant .image as! Data) //Create the round pictures //The side of square is equal the diameter of circle, that why /2 cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.height/2 cell.thumbnailImageView.clipsToBounds = true //Give access to change the ImageView return cell } //Function creates swipe menu with additional buttons override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { //Create variable which will responsible for delete button let deleteAction = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in let context = (UIApplication.shared.delegate as! AppDelegate).coreDataStack.persistentContainer.viewContext let objectToDelete = self.fetchResultsController.object(at: indexPath) context.delete(objectToDelete) do { try context.save() } catch { print(error.localizedDescription) } tableView.reloadData() } //Create action menu when user clicks "Share" let shareAction = UITableViewRowAction(style: .default, title: "Share") { (action, indexPath) in // Share item by indexPath let defaultText = "I am in \(self.restaurants[indexPath.row].name) now" if let image = UIImage(data: self.restaurants[indexPath.row].image as! Data) { let activityController = UIActivityViewController(activityItems: [defaultText, image], applicationActivities: nil) self.present(activityController, animated: true, completion: nil) } } //Change the color of Share button shareAction.backgroundColor = UIColor(red: 63 / 255, green: 84 / 255, blue: 242 / 255, alpha: 1) //return 2 possible button in action menu return [deleteAction, shareAction] } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //Delete selecting of row tableView.deselectRow(at: indexPath, animated: true) } //MARK: - Fetch results controller delegate //вызывается перед тем как контроллер поменяет свой контент func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: guard let indexPath = newIndexPath else { break } tableView.insertRows(at: [indexPath], with: .fade) case .delete: guard let indexPath = indexPath else { break } tableView.deleteRows(at: [indexPath], with: .fade) case .update: guard let indexPath = indexPath else { break } tableView.reloadRows(at: [indexPath], with: .fade) default: tableView.reloadData() } restaurants = controller.fetchedObjects as! [Restaurant] } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } //MARK: - Functions //метод для отфильтровки результатов для filterResultArray func filterContentSearch(searchText text: String){ filterResultArray = restaurants.filter{ (restaurant) -> Bool in //в наш массив попадают элементы restaurant с маленькой буквы return (restaurant.name?.lowercased().contains(text.lowercased()))! } } func restaurantToDisplayAt(indexPath: IndexPath) -> Restaurant{ let restaurant: Restaurant if searchController.isActive && searchController.searchBar.text != "" { restaurant = filterResultArray[indexPath.row] } else { restaurant = restaurants[indexPath.row] } return restaurant } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "DetailsSegue" { if let indexPath = self.tableView.indexPathForSelectedRow{ let destinationVC = segue.destination as! DetailsViewController destinationVC.restaurant = restaurantToDisplayAt(indexPath: indexPath) } } } // //The massive responsible for Restaurant objects // var MyRestaurant: [Restaurant] = [ // Restaurant(name: "Barrafina", type: "Bar", image: "Barrafina", location: "10 Adelaide Street, Covent Garden, London", wasVisited: false), // Restaurant(name: "Bourkestreetbakery", type: "Bakery", image: "Bourkestreetbakery", location: "480 Bourke St, Melbourne VIC 3000, Australia", wasVisited: false), // Restaurant(name: "Cafe Deadend", type: "Cafe", image: "Cafedeadend", location: "72 Po Hing Fong, Hong Kong", wasVisited: false), // Restaurant(name: "Cafe Lore", type: "Cafe", image: "Cafelore", location: "4601 4th Ave, Brooklyn, NY 11220, United States", wasVisited: false), // Restaurant(name: "Confessional", type: "Restaurant", image: "Confessional", location: "308 E 6th St, New York, NY 10003, USA", wasVisited: false), // Restaurant(name: "Donostia", type: "Restaurant", image: "Donostia", location: " 10 Seymour Pl, London W1H 7ND, United Kingdom", wasVisited: false), // Restaurant(name: "Five Leaves", type: "Bar", image: "Fiveleaves", location: "18 Bedford Ave, Brooklyn, NY 11222, United States", wasVisited: false), // Restaurant(name: "For Kee", type: "Restaurant", image: "Forkeerestaurant", location: "200 Hollywood Rd, Sheung Wan, Hong Kong", wasVisited: false), // Restaurant(name: "Graham avenue meats", type: "Restaurant", image: "Grahamavenuemeats", location: "445 Graham Ave, Brooklyn, NY 11211, United States", wasVisited: false), // Restaurant(name: "Haigh's chocolate", type: "Chocolate shope", image: "Haighschocolate", location: "The Strand Arcade, 1/412-414 George St, Sydney NSW 2000, Australia", wasVisited: false), // Restaurant(name: "Homei", type: "Restaurant", image: "Homei", location: "Shop 8/38-52 Waterloo St, Surry Hills NSW 2010, Australia", wasVisited: false), // Restaurant(name: "Palomino Espresso", type: "Espresso Bar", image: "Palominoespresso", location: "1/61 York St, Sydney NSW 2000, Australia", wasVisited: false), // Restaurant(name: "Po's Atelier", type: "Bakery", image: "Posatelier", location: "70 Po Hing Fong, Hong Kong", wasVisited: false), // Restaurant(name: "Teakha", type: "Cafe", image: "Teakha", location: "18 Tai Ping Shan St, Hong Kong", wasVisited: false), // Restaurant(name: "Traif", type: "Restaurant", image: "Traif", location: "229 S 4th St, Brooklyn, NY 11211, United States", wasVisited: false), // Restaurant(name: "Upstate", type: "Seafood Restaurant", image: "Upstate", location: "95 1st Avenue, New York, NY 10003, United States", wasVisited: false), // Restaurant(name: "Waffle & Wolf", type: "Sandwich Shop", image: "Wafflewolf", location: "413 Graham Ave, Brooklyn, NY 11211, United States", wasVisited: false) // ] } extension MyRestaurantTableViewController: UISearchResultsUpdating { //метод автоматически срабатывает когда мы что либо меняем в поисковой строке func updateSearchResults(for searchController: UISearchController) { filterContentSearch(searchText: searchController.searchBar.text!) tableView.reloadData() //заново срабатывае cellForRowAtIndexPath } } extension MyRestaurantTableViewController: UISearchBarDelegate { //когда мы щелкнули на поисковую строку func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { if searchBar.text == "" { navigationController?.hidesBarsOnSwipe = false } } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { navigationController?.hidesBarsOnSwipe = true } }
88a791502b026bd451dfc1d72d5f516d
51.378378
202
0.674775
false
false
false
false
chernyog/CYWeibo
refs/heads/master
CYWeibo/CYWeibo/CYWeibo/Classes/UI/Message/MessageViewController.swift
mit
1
// // MessageViewController.swift // CYWeibo // // Created by 陈勇 on 15/3/5. // Copyright (c) 2015年 zhssit. All rights reserved. // import UIKit class MessageViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
a35c256bb76f531036ffeb2d4a562f3b
33.061856
157
0.683111
false
false
false
false
linhaosunny/smallGifts
refs/heads/master
小礼品/小礼品/Classes/Module/Me/Views/MeFooterView.swift
mit
1
// // MeFooterView.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/25. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit fileprivate let LabelColor = UIColor(red: 180.0/255.0, green: 180.0/255.0, blue: 180.0/255.0, alpha: 1.0) class MeFooterView: UIView { //MARK: 属性 var viewModel:MeFooterViewModel? { didSet{ tipLabel.text = viewModel?.tipLabelText if let image = viewModel?.iconImage { iconView.image = image iconView.isHidden = false } else{ iconView.isHidden = true } } } weak var delegate:MeFooterViewDelegate? //MARK 懒加载 lazy var iconView:UIImageView = UIImageView(image: #imageLiteral(resourceName: "me_blank")) lazy var tipLabel:UILabel = { () -> UILabel in let label = UILabel() label.textColor = LabelColor label.font = fontSize16 return label }() lazy var loginButton:UIButton = { let button = UIButton(type: .custom) button.backgroundColor = UIColor.clear return button }() //MARK: 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupMeFooterView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setupMeFooterViewSubView() } //MARK: 私有方法 private func setupMeFooterView() { backgroundColor = UIColor.white addSubview(iconView) addSubview(tipLabel) addSubview(loginButton) loginButton.addTarget(self, action: #selector(loginButtonClick), for: .touchUpInside) } private func setupMeFooterViewSubView() { iconView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(80) make.centerX.equalToSuperview() } tipLabel.snp.makeConstraints { (make) in make.top.equalTo(iconView.snp.bottom).offset(margin) make.centerX.equalToSuperview() } loginButton.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets.zero) } } //MARK: 内部响应 @objc private func loginButtonClick() { delegate?.meFooterViewLoginButtonClick() } } //MARK: 协议 protocol MeFooterViewDelegate:NSObjectProtocol { func meFooterViewLoginButtonClick() }
9a30310af9211115a5eca1b093618ae2
25.882979
105
0.603087
false
false
false
false
wordpress-mobile/AztecEditor-iOS
refs/heads/develop
Aztec/Classes/Converters/StringAttributesToAttributes/Implementations/SuperscriptStringAttributeConverter.swift
gpl-2.0
2
import Foundation import UIKit /// Converts the superscript style information from string attributes and aggregates it into an /// existing array of element nodes. /// open class SuperscriptStringAttributeConverter: StringAttributeConverter { private let toggler = HTMLStyleToggler(defaultElement: .sup, cssAttributeMatcher: NeverCSSAttributeMatcher()) public func convert( attributes: [NSAttributedString.Key: Any], andAggregateWith elementNodes: [ElementNode]) -> [ElementNode] { var elementNodes = elementNodes // We add the representation right away, if it exists... as it could contain attributes beyond just this // style. The enable and disable methods below can modify this as necessary. // if let representation = attributes[NSAttributedString.Key.supHtmlRepresentation] as? HTMLRepresentation, case let .element(representationElement) = representation.kind { elementNodes.append(representationElement.toElementNode()) } if shouldEnable(for: attributes) { return toggler.enable(in: elementNodes) } else { return toggler.disable(in: elementNodes) } } // MARK: - Style Detection func shouldEnable(for attributes: [NSAttributedString.Key : Any]) -> Bool { return hasTraits(for: attributes) } func hasTraits(for attributes: [NSAttributedString.Key : Any]) -> Bool { guard let baselineOffset = attributes[.baselineOffset] as? NSNumber else { return false } return baselineOffset.intValue > 0; } }
eab7776b813a6f7fc7ab2f2c237bfe05
34.166667
113
0.659953
false
false
false
false
bluesnap/bluesnap-ios
refs/heads/develop
BluesnapSDK/BluesnapSDK/BSStartViewController.swift
mit
1
// // StartViewController.swift // BluesnapSDK // // Created by Shevie Chen on 17/05/2017. // Copyright © 2017 Bluesnap. All rights reserved. // import UIKit import PassKit class BSStartViewController: UIViewController { // MARK: - private properties internal var supportedPaymentMethods: [String]? var paymentSummaryItems: [PKPaymentSummaryItem] = []; internal var activityIndicator: UIActivityIndicatorView? internal var payPalPurchaseDetails: BSPayPalSdkResult! internal var existingCardViews: [BSExistingCcUIView] = [] internal var showPayPal: Bool = false internal var showApplePay: Bool = false internal var bottomOfLastIcon: CGFloat = 0 // MARK: Outlets @IBOutlet weak var centeredView: UIView! @IBOutlet weak var ccnButton: BSPaymentTypeView! @IBOutlet weak var applePayButton: BSPaymentTypeView! @IBOutlet weak var payPalButton: BSPaymentTypeView! // MARK: init func initScreen() { self.supportedPaymentMethods = BSApiManager.supportedPaymentMethods } // MARK: UIViewController functions override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController!.isNavigationBarHidden = false // Hide/show the buttons and position them automatically showPayPal = BSApiManager.isSupportedPaymentMethod(paymentType: BSPaymentType.PayPal, supportedPaymentMethods: supportedPaymentMethods) && !(BlueSnapSDK.sdkRequestBase is BSSdkRequestSubscriptionCharge) showApplePay = BlueSnapSDK.applePaySupported(supportedPaymentMethods: supportedPaymentMethods, supportedNetworks: BlueSnapSDK.applePaySupportedNetworks).canMakePayments //self.hideShowElements() // Localize strings self.title = BSLocalizedStrings.getString(BSLocalizedString.Title_Payment_Type) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopActivityIndicator() } // MARK: button functions @IBAction func applePayClick(_ sender: Any) { let applePaySupported = BlueSnapSDK.applePaySupported(supportedPaymentMethods: supportedPaymentMethods, supportedNetworks: BlueSnapSDK.applePaySupportedNetworks) if (!applePaySupported.canMakePayments) { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: BSLocalizedString.Error_Not_available_on_this_device) present(alert, animated: true, completion: nil) return; } if (!applePaySupported.canSetupCards) { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: BSLocalizedString.Error_No_cards_set) present(alert, animated: true, completion: nil) return; } if BSApplePayConfiguration.getIdentifier() == nil { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: BSLocalizedString.Error_Setup_error) NSLog("Missing merchant identifier for apple pay") present(alert, animated: true, completion: nil) return; } if BlueSnapSDK.sdkRequestBase is BSSdkRequestShopperRequirements { BSApiManager.shopper?.chosenPaymentMethod = BSChosenPaymentMethod(chosenPaymentMethodType: BSPaymentType.ApplePay.rawValue) BlueSnapSDK.updateShopper(completion: { (isSuccess, message) in DispatchQueue.main.async { if (!isSuccess) { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: message!) self.present(alert, animated: true, completion: nil) return } else { _ = self.navigationController?.popViewController(animated: false) // execute callback let applePayPurchaseDetails = BSApplePaySdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!) BlueSnapSDK.sdkRequestBase?.purchaseFunc(applePayPurchaseDetails) } } }) } else { applePayPressed(sender, completion: { (error) in DispatchQueue.main.async { NSLog("Apple pay completion") if error == BSErrors.applePayCanceled { NSLog("Apple Pay operation canceled") return } else if error != nil { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_Apple_Pay, message: BSLocalizedString.Error_General_ApplePay_error) self.present(alert, animated: true, completion: nil) return } else { _ = self.navigationController?.popViewController(animated: false) // execute callback let applePayPurchaseDetails = BSApplePaySdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!) BlueSnapSDK.sdkRequestBase?.purchaseFunc(applePayPurchaseDetails) } } } ) } } @IBAction func ccDetailsClick(_ sender: Any) { let backItem = UIBarButtonItem() backItem.title = BSLocalizedStrings.getString(BSLocalizedString.Navigate_Back_to_payment_type_screen) navigationItem.backBarButtonItem = backItem // This will show in the next view controller being pushed animateToPaymentScreen(startY: bottomOfLastIcon, completion: { animate in _ = BSViewsManager.showCCDetailsScreen(existingCcPurchaseDetails: nil, inNavigationController: self.navigationController, animated: animate) }) } @IBAction func payPalClicked(_ sender: Any) { payPalPurchaseDetails = BSPayPalSdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!) if BlueSnapSDK.sdkRequestBase is BSSdkRequestShopperRequirements { BSApiManager.shopper?.chosenPaymentMethod = BSChosenPaymentMethod(chosenPaymentMethodType: BSPaymentType.PayPal.rawValue) BlueSnapSDK.updateShopper(completion: { (isSuccess, message) in DispatchQueue.main.async { if (!isSuccess) { let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_PayPal, message: message!) self.present(alert, animated: true, completion: nil) return } else { _ = self.navigationController?.popViewController(animated: false) // execute callback let payPalPurchaseDetails = BSPayPalSdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!) BlueSnapSDK.sdkRequestBase?.purchaseFunc(payPalPurchaseDetails) } } }) } else { DispatchQueue.main.async { self.startActivityIndicator() } DispatchQueue.main.async { BSApiManager.createPayPalToken(purchaseDetails: self.payPalPurchaseDetails, withShipping: BlueSnapSDK.sdkRequestBase!.shopperConfiguration.withShipping, completion: { resultToken, resultError in if let resultToken = resultToken { self.stopActivityIndicator() DispatchQueue.main.async { BSViewsManager.showBrowserScreen(inNavigationController: (nil != self.navigationController) ? self.navigationController : sender as! UINavigationController, url: resultToken, shouldGoToUrlFunc: self.paypalUrlListener) } } else { let errMsg = resultError == .paypalUnsupportedCurrency ? BSLocalizedString.Error_PayPal_Currency_Not_Supported : BSLocalizedString.Error_General_PayPal_error let alert = BSViewsManager.createErrorAlert(title: BSLocalizedString.Error_Title_PayPal, message: errMsg) self.stopActivityIndicator() self.present(alert, animated: true, completion: nil) } }) } } } // Mark: private functions private func isShowPayPal() -> Bool { var showPayPal = false showPayPal = !(BlueSnapSDK.sdkRequestBase is BSSdkRequestSubscriptionCharge) && BSApiManager.isSupportedPaymentMethod(paymentType: BSPaymentType.PayPal, supportedPaymentMethods: supportedPaymentMethods) return showPayPal } private func hideShowElements() { var existingCreditCards: [BSCreditCardInfo] = [] if let shopper = BSApiManager.shopper { existingCreditCards = shopper.existingCreditCards } let numSections = existingCreditCards.count + ((showPayPal && showApplePay) ? 3 : (!showPayPal && !showApplePay) ? 1 : 2) var sectionNum: CGFloat = 0 let sectionY: CGFloat = (centeredView.frame.height / CGFloat(numSections + 1)).rounded() if showApplePay { applePayButton.isHidden = false sectionNum = sectionNum + 1 applePayButton.center.y = sectionY * sectionNum bottomOfLastIcon = applePayButton.frame.maxY } else { applePayButton.isHidden = true } sectionNum = sectionNum + 1 ccnButton.center.y = sectionY * sectionNum bottomOfLastIcon = ccnButton.frame.maxY if showPayPal { sectionNum = sectionNum + 1 payPalButton.isHidden = false payPalButton.center.y = sectionY * sectionNum } else { payPalButton.isHidden = true } bottomOfLastIcon = payPalButton.frame.maxY let newCcRect = self.ccnButton.frame if existingCreditCards.count > 0 && existingCardViews.count == 0 { var tag: Int = 0 for existingCreditCard in existingCreditCards { let cardView = BSExistingCcUIView() self.centeredView.addSubview(cardView) cardView.frame = CGRect(x: newCcRect.minX, y: newCcRect.minY, width: newCcRect.width, height: newCcRect.height) sectionNum = sectionNum + 1 cardView.center.y = sectionY * sectionNum bottomOfLastIcon = cardView.frame.maxY cardView.setCc( ccType: existingCreditCard.creditCard.ccType ?? "", last4Digits: existingCreditCard.creditCard.last4Digits ?? "", expiration: existingCreditCard.creditCard.getExpiration()) cardView.resizeElements() cardView.addTarget(self, action: #selector(BSStartViewController.existingCCTouchUpInside(_:)), for: .touchUpInside) cardView.tag = tag // cardView.isAccessibilityElement = true let accessibilityIdentifier = "existingCc\(tag)" cardView.accessibilityIdentifier = accessibilityIdentifier cardView.isUserInteractionEnabled = true cardView.accessibilityTraits = UIAccessibilityTraits.button tag = tag + 1 } } } @objc func existingCCTouchUpInside(_ sender: Any) { if let existingCcUIView = sender as? BSExistingCcUIView, let existingCreditCards = BSApiManager.shopper?.existingCreditCards { let ccIdx = existingCcUIView.tag let cc = existingCreditCards[ccIdx] animateToPaymentScreen(startY: existingCcUIView.frame.minY, completion: { animate in let purchaseDetails = BSExistingCcSdkResult(sdkRequestBase: BlueSnapSDK.sdkRequestBase!, shopper: BSApiManager.shopper, existingCcDetails: cc) _ = BSViewsManager.showExistingCCDetailsScreen(purchaseDetails: purchaseDetails, inNavigationController: self.navigationController, animated: animate) }) } } private func animateToPaymentScreen(startY: CGFloat, completion: ((Bool) -> Void)!) { let moveUpBy = self.centeredView.frame.minY + startY - 48 UIView.animate(withDuration: 0.3, animations: { self.centeredView.center.y = self.centeredView.center.y - moveUpBy }, completion: { animate in completion(false) self.centeredView.center.y = self.centeredView.center.y + moveUpBy }) } func paypalUrlListener(url: String) -> Bool { if BSPaypalHandler.isPayPalProceedUrl(url: url) { // paypal success! BSPaypalHandler.parsePayPalResultDetails(url: url, purchaseDetails: self.payPalPurchaseDetails) // return to merchant screen if let viewControllers = navigationController?.viewControllers { let merchantControllerIndex = viewControllers.count - 3 _ = navigationController?.popToViewController(viewControllers[merchantControllerIndex], animated: false) } // execute callback BlueSnapSDK.sdkRequestBase?.purchaseFunc(self.payPalPurchaseDetails) return false } else if BSPaypalHandler.isPayPalCancelUrl(url: url) { // PayPal cancel URL detected - close web screen _ = navigationController?.popViewController(animated: false) return false } return true } // MARK: Prevent rotation, support only Portrait mode override var shouldAutorotate: Bool { return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return UIInterfaceOrientation.portrait } // Activity indicator func startActivityIndicator() { if self.activityIndicator == nil { activityIndicator = BSViewsManager.createActivityIndicator(view: self.view) } BSViewsManager.startActivityIndicator(activityIndicator: activityIndicator!, blockEvents: true) } func stopActivityIndicator() { if let activityIndicator = activityIndicator { BSViewsManager.stopActivityIndicator(activityIndicator: activityIndicator) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.hideShowElements() } }
5144d164a4909b7314c00733a21d084a
42.181818
245
0.644211
false
false
false
false
rnystrom/GitHawk
refs/heads/master
Classes/Issues/Preview/IssuePreviewSectionController.swift
mit
1
// // IssuePreviewViewController.swift // Freetime // // Created by Ryan Nystrom on 8/1/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit final class IssuePreviewSectionController: ListBindingSectionController<IssuePreviewModel>, ListBindingSectionControllerDataSource { private lazy var webviewCache: WebviewCellHeightCache = { return WebviewCellHeightCache(sectionController: self) }() private lazy var imageCache: ImageCellHeightCache = { return ImageCellHeightCache(sectionController: self) }() override init() { super.init() dataSource = self } // MARK: ListBindingSectionControllerDataSource func sectionController( _ sectionController: ListBindingSectionController<ListDiffable>, viewModelsFor object: Any ) -> [ListDiffable] { return self.object?.models ?? [] } func sectionController( _ sectionController: ListBindingSectionController<ListDiffable>, sizeForViewModel viewModel: Any, at index: Int ) -> CGSize { let height = BodyHeightForComment( viewModel: viewModel, width: collectionContext.safeContentWidth(), webviewCache: webviewCache, imageCache: imageCache ) return collectionContext.cellSize(with: height) } func sectionController( _ sectionController: ListBindingSectionController<ListDiffable>, cellForViewModel viewModel: Any, at index: Int ) -> UICollectionViewCell & ListBindable { guard let context = self.collectionContext else { fatalError("Missing context") } let cellClass: AnyClass = CellTypeForComment(viewModel: viewModel) guard let cell = context.dequeueReusableCell(of: cellClass, for: self, at: index) as? UICollectionViewCell & ListBindable else { fatalError("Cell not bindable") } ExtraCommentCellConfigure( cell: cell, imageDelegate: nil, htmlDelegate: webviewCache, htmlNavigationDelegate: nil, htmlImageDelegate: nil, markdownDelegate: nil, imageHeightDelegate: imageCache ) return cell } }
74987ce201880cbfc41449f574f89d7d
29.851351
129
0.663601
false
false
false
false
BabyShung/SplashWindow
refs/heads/master
SplashWindow/Views/SWShadowView.swift
mit
1
import UIKit public class SWShadowView: UIView { @IBInspectable var cornerRadius: CGFloat = 4.0 { didSet { updateProperties() } } @IBInspectable var shadowColor: UIColor = UIColor.black { didSet { updateProperties() } } @IBInspectable var shadowOffset: CGSize = CGSize(width: 0.0, height: 2) { didSet { updateProperties() } } @IBInspectable var shadowRadius: CGFloat = 2.5 { didSet { updateProperties() } } @IBInspectable var shadowOpacity: Float = 0.3 { didSet { updateProperties() } } public override func awakeFromNib() { super.awakeFromNib() layer.masksToBounds = false updateProperties() updateShadowPath() } public override func layoutSubviews() { super.layoutSubviews() updateShadowPath() } fileprivate func updateProperties() { layer.cornerRadius = cornerRadius layer.shadowColor = shadowColor.cgColor layer.shadowOffset = shadowOffset layer.shadowRadius = shadowRadius layer.shadowOpacity = shadowOpacity } fileprivate func updateShadowPath() { layer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: layer.cornerRadius).cgPath } }
5984e4d9e4afd808e6087f053b9fabbb
22.196721
107
0.584452
false
false
false
false
Antondomashnev/Sourcery
refs/heads/master
Kiosk/App/Models/BuyersPremium.swift
mit
4
import UIKit import SwiftyJSON final class BuyersPremium: NSObject, JSONAbleType { let id: String let name: String init(id: String, name: String) { self.id = id self.name = name } static func fromJSON(_ json: [String: Any]) -> BuyersPremium { let json = JSON(json) let id = json["id"].stringValue let name = json["name"].stringValue return BuyersPremium(id: id, name: name) } }
33d799c359d271989259c3459ba24e9b
21.7
66
0.603524
false
false
false
false
shajrawi/swift
refs/heads/master
test/attr/attr_escaping.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -swift-version 4 @escaping var fn : () -> Int = { 4 } // expected-error {{attribute can only be applied to types, not declarations}} func paramDeclEscaping(@escaping fn: (Int) -> Void) {} // expected-error {{attribute can only be applied to types, not declarations}} func wrongParamType(a: @escaping Int) {} // expected-error {{@escaping attribute only applies to function types}} func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{unknown attribute 'noescape'}} func takesEscaping(_ fn: @escaping () -> Int) {} // ok func callEscapingWithNoEscape(_ fn: () -> Int) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }} takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} // This is a non-escaping use: let _ = fn } typealias IntSugar = Int func callSugared(_ fn: () -> IntSugar) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }} takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } struct StoresClosure { var closure : () -> Int init(_ fn: () -> Int) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{14-14=@escaping }} closure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}} } func arrayPack(_ fn: () -> Int) -> [() -> Int] { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }} return [fn] // expected-error{{using non-escaping parameter 'fn' in a context expecting an @escaping closure}} } func dictPack(_ fn: () -> Int) -> [String: () -> Int] { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{23-23=@escaping }} return ["ultimate answer": fn] // expected-error{{using non-escaping parameter 'fn' in a context expecting an @escaping closure}} } func arrayPack(_ fn: @escaping () -> Int, _ fn2 : () -> Int) -> [() -> Int] { // expected-note@-1{{parameter 'fn2' is implicitly non-escaping}} {{53-53=@escaping }} return [fn, fn2] // expected-error{{using non-escaping parameter 'fn2' in a context expecting an @escaping closure}} } } func takesEscapingBlock(_ fn: @escaping @convention(block) () -> Void) { fn() } func callEscapingWithNoEscapeBlock(_ fn: () -> Void) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{42-42=@escaping }} takesEscapingBlock(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } func takesEscapingAutoclosure(_ fn: @autoclosure @escaping () -> Int) {} func callEscapingAutoclosureWithNoEscape(_ fn: () -> Int) { takesEscapingAutoclosure(1+1) } let foo: @escaping (Int) -> Int // expected-error{{@escaping attribute may only be used in function parameter position}} {{10-20=}} struct GenericStruct<T> {} func misuseEscaping(_ a: @escaping Int) {} // expected-error{{@escaping attribute only applies to function types}} {{26-38=}} func misuseEscaping(_ a: (@escaping Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{27-39=}} func misuseEscaping(opt a: @escaping ((Int) -> Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{28-38=}} // expected-note@-1{{closure is already escaping in optional type argument}} func misuseEscaping(_ a: (@escaping (Int) -> Int)?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}} // expected-note@-1{{closure is already escaping in optional type argument}} func misuseEscaping(nest a: (((@escaping (Int) -> Int))?)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}} // expected-note@-1{{closure is already escaping in optional type argument}} func misuseEscaping(iuo a: (@escaping (Int) -> Int)!) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{29-39=}} // expected-note@-1{{closure is already escaping in optional type argument}} func misuseEscaping(_ a: Optional<@escaping (Int) -> Int>, _ b: Int) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{35-45=}} func misuseEscaping(_ a: (@escaping (Int) -> Int, Int)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}} func misuseEscaping(_ a: [@escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}} func misuseEscaping(_ a: [@escaping (Int) -> Int]?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-37=}} func misuseEscaping(_ a: [Int : @escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{33-43=}} func misuseEscaping(_ a: GenericStruct<@escaping (Int) -> Int>) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{40-50=}} func takesEscapingGeneric<T>(_ fn: @escaping () -> T) {} func callEscapingGeneric<T>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{35-35=@escaping }} takesEscapingGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } class Super {} class Sub: Super {} func takesEscapingSuper(_ fn: @escaping () -> Super) {} func callEscapingSuper(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{30-30=@escaping }} takesEscapingSuper(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } func takesEscapingSuperGeneric<T: Super>(_ fn: @escaping () -> T) {} func callEscapingSuperGeneric(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }} takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } func callEscapingSuperGeneric<T: Sub>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{45-45=@escaping }} takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } func testModuloOptionalness() { var iuoClosure: (() -> Void)! = nil func setIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{28-28=@escaping }} iuoClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}} } var iuoClosureExplicit: (() -> Void)! func setExplicitIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{36-36=@escaping }} iuoClosureExplicit = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}} } var deepOptionalClosure: (() -> Void)??? func setDeepOptionalClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }} deepOptionalClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}} } } // Check that functions in vararg position are @escaping func takesEscapingFunction(fn: @escaping () -> ()) {} func takesArrayOfFunctions(array: [() -> ()]) {} func takesVarargsOfFunctions(fns: () -> ()...) { takesArrayOfFunctions(array: fns) for fn in fns { takesEscapingFunction(fn: fn) } } func takesVarargsOfFunctionsExplicitEscaping(fns: @escaping () -> ()...) {} // expected-error{{@escaping attribute may only be used in function parameter position}} func takesNoEscapeFunction(fn: () -> ()) { // expected-note {{parameter 'fn' is implicitly non-escaping}} takesVarargsOfFunctions(fns: fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } class FooClass { var stored : Optional<(()->Int)->Void> = nil var computed : (()->Int)->Void { get { return stored! } set(newValue) { stored = newValue } // ok } var computedEscaping : (@escaping ()->Int)->Void { get { return stored! } set(newValue) { stored = newValue } // expected-error{{assigning non-escaping parameter 'newValue' to an @escaping closure}} // expected-note@-1 {{parameter 'newValue' is implicitly non-escaping}} } } // A call of a closure literal should be non-escaping func takesInOut(y: inout Int) { _ = { y += 1 // no-error }() _ = ({ y += 1 // no-error })() _ = { () in y += 1 // no-error }() _ = ({ () in y += 1 // no-error })() _ = { () -> () in y += 1 // no-error }() _ = ({ () -> () in y += 1 // no-error })() } class HasIVarCaptures { var x: Int = 0 func method() { _ = { x += 1 // no-error }() _ = ({ x += 1 // no-error })() _ = { () in x += 1 // no-error }() _ = ({ () in x += 1 // no-error })() _ = { () -> () in x += 1 // no-error }() _ = ({ () -> () in x += 1 // no-error })() } } // https://bugs.swift.org/browse/SR-9760 protocol SR_9760 { typealias F = () -> Void typealias G<T> = (T) -> Void func foo<T>(_: T, _: @escaping F) // Ok func bar<T>(_: @escaping G<T>) // Ok } extension SR_9760 { func fiz<T>(_: T, _: @escaping F) {} // Ok func baz<T>(_: @escaping G<T>) {} // Ok }
52e74fd5d0f1367884e7b5a1d94d0c5b
40.789474
171
0.652813
false
false
false
false
igerard/Genesis
refs/heads/master
Genesis/Pages/BoardPageView.swift
mit
1
// // BoardPageView.swift // Genesis // // Created by Gerard Iglesias on 01/10/2017. // Copyright © 2017 Gerard Iglesias. All rights reserved. // import UIKit import Metal import MetalKit import simd /// The Vertex structure struct SimpleVertex { var position : float4 var color : float4 } struct Uniforms { var modelViewProjectionMatrix : matrix_float4x4 }; class BoardPageView: MTKView { var pageFormat = A4 { didSet { camera = BoardPageCamera(center: CGPoint(x: pageFormat.width/2.0, y: pageFormat.height/2.0), up: CGVector(dx: 0, dy: 1), extend: CGSize(width: pageFormat.width, height: pageFormat.height)) setNeedsDisplay() } } var showGrid = false { didSet { setNeedsDisplay() NotificationCenter.default.post(name: InfoEventGeneric, object: self, userInfo: ["message":showGrid ? "Show Grid" : "Hide Grid"]) } } // viewing of the world var camera = BoardPageCamera(); var mlLayer : CAMetalLayer { get { return self.layer as! CAMetalLayer } } var commandQueue: MTLCommandQueue? // MARK Data structure let pageGrid: GeoPageGrid! let axes: GeoAxes! var axePosition = float2(0,0) var viewingBuffer : MTLBuffer? var library : MTLLibrary? var vertexFunction : MTLFunction? var fragmentFunction : MTLFunction? var pipelineState : MTLRenderPipelineState? // the struc to pass transformation to the shader var uniforms = Uniforms(modelViewProjectionMatrix: matrix_identity_float4x4) // overrides // MARK: Init Phase override init(frame frameRect: CGRect, device: MTLDevice?) { camera = BoardPageCamera(center: CGPoint(x: pageFormat.width/2.0, y: pageFormat.height/2.0), up: CGVector(dx: 0, dy: 1), extend: CGSize(width: pageFormat.width, height: pageFormat.height)) axes = GeoAxes(size: float2(1,1), device: device) pageGrid = device.flatMap{GeoPageGrid(pageFormat: A4, device: $0)} super.init(frame: frameRect, device: device) isOpaque = false mlLayer.isOpaque = false preferredFramesPerSecond = 60 let value = 1.0 clearColor = MTLClearColor(red: value, green: value, blue: value, alpha: 1) clearDepth = 1.0 clearStencil = 0 colorPixelFormat = .bgra8Unorm sampleCount = 4 commandQueue = self.device?.makeCommandQueue() makeBuffers() makePipeline() } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func makeBuffers(){ // the viewing buffer let viewingBufferSize = MemoryLayout<Uniforms>.size viewingBuffer = self.device?.makeBuffer(length: viewingBufferSize, options: .cpuCacheModeWriteCombined) } func makePipeline(){ library = self.device?.makeDefaultLibrary() vertexFunction = library?.makeFunction(name : "vertex_main") fragmentFunction = library?.makeFunction(name : "fragment_main") let pipelineDescr = MTLRenderPipelineDescriptor() pipelineDescr.vertexFunction = vertexFunction pipelineDescr.fragmentFunction = fragmentFunction pipelineDescr.colorAttachments[0].pixelFormat = mlLayer.pixelFormat pipelineDescr.sampleCount = sampleCount do { pipelineState = try device!.makeRenderPipelineState(descriptor: pipelineDescr) } catch { board_log_error("%@", error.localizedDescription) } } // refresh the viewing transformation func updateViewBuffer(){ uniforms.modelViewProjectionMatrix = camera.metalProjectionToViewport(bounds.size) memcpy(viewingBuffer?.contents(), &uniforms, MemoryLayout<Uniforms>.size) } // MARK: Display override func draw(_ rect : CGRect) { guard self.device != nil else{ board_log_error("%@", "No Metal device") return } guard self.commandQueue != nil else{ board_log_error("%@", "No Command Queue") return } guard self.pipelineState != nil else{ board_log_error("%@", "No pipeline") return } if let drawable = self.currentDrawable, let commandBuffer = commandQueue!.makeCommandBuffer(), let passDescr = self.currentRenderPassDescriptor, let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescr){ commandEncoder.setRenderPipelineState(pipelineState!) let nativeScale = Double(UIScreen.main.nativeScale) let viewport = MTLViewport(originX: 0, originY: 0, width: nativeScale*Double(bounds.width), height: nativeScale*Double(bounds.height), znear: 0, zfar: 1) commandEncoder.setViewport(viewport) updateViewBuffer() drawGeometry(commandEncoder) commandEncoder.endEncoding() commandBuffer.present(drawable) commandBuffer.commit() } } fileprivate func drawGeometry(_ commandEncoder: MTLRenderCommandEncoder) { if let viewBuffer = viewingBuffer { axes.drawAt(position: axePosition, encoder: commandEncoder, viewingBuffer: viewBuffer) if showGrid { pageGrid?.draw(encoder: commandEncoder, viewingBuffer: viewBuffer) } } } // MARK: Events // MARK: Layouts // MARK: Archive override func awakeFromNib() { board_log_debug("%@", self.mlLayer.debugDescription) } }
1daf061c82ccc2989d2f710ae5697fd0
27.861878
194
0.69219
false
false
false
false
nthery/SwiftForth
refs/heads/master
SwiftForthKit/evaluator.swift
mit
1
// // Top-level class coordinating compiler and virtual machine. // import Foundation // A context for interpreting Forth code. // Main entry point for clients. public class ForthEvaluator { let compiler = Compiler() let vm = VM() public init() { // Compile builtins implemented in Forth. evalOrDie(": CR 13 EMIT ;") } // Evaluate Forth source code. // Passing incomplete code fragments is supported. For example eval(": foo") followed // by eval("42 ;"). // Return true on success. // Report an error through handler passed to setErrorHandler() and return false on failure. public func eval(input: String) -> Bool { if let phrase = compiler.compile(input) { debug(.Evaluator, "compiled: \(phrase)") return vm.execPhrase(phrase) } else { return false } } public func setErrorHandler(handler: ForthErrorHandler) { compiler.errorHandler = handler vm.errorHandler = handler } // Return accumulated content generated by '.', EMIT, CR and co and reset it afterward. public func getAndResetOutput() -> String { let o = vm.output vm.output = "" return o } // Allow clients to manipulate argument stack directly. public var argStack : ForthStack<Int> { return vm.argStack } func evalOrDie(input: String) { if !eval(input) { println("failed to evaluate '\(input)'") exit(1) } } }
05750424d381a31cc33e32849318d674
27.145455
95
0.601164
false
false
false
false
NorthernRealities/ColorSenseRainbow
refs/heads/master
ColorSenseRainbow/WhiteSeeker.swift
mit
1
// // WhiteSeeker.swift // ColorSenseRainbow // // Created by Reid Gravelle on 2015-08-05. // Copyright (c) 2015 Northern Realities Inc. All rights reserved. // import AppKit class WhiteSeeker: Seeker { override init () { super.init() var error : NSError? var regex: NSRegularExpression? // Swift let commonSwiftRegex = "hite:\\s*" + swiftFloatColourConst + "\\s*,\\s*alpha:\\s*" + swiftAlphaConst + "\\s*\\)" do { regex = try NSRegularExpression ( pattern: "(?:NS|UI)Color" + swiftInit + "\\s*\\(\\s*w" + commonSwiftRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Swift White float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } do { regex = try NSRegularExpression ( pattern: "NSColor" + swiftInit + "\\s*\\(\\s*(?:calibrated|device|genericGamma22)W" + commonSwiftRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Swift NSColor calibrated, device, genericGamma22 white float regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } // Objective-C - Only functions with alpha defined let commonObjCRegex = "White:\\s*" + objcFloatColourConst + "\\s*alpha:\\s*" + objcAlphaConst + "\\s*\\]" do { regex = try NSRegularExpression ( pattern: "\\[\\s*(?:NS|UI)Color\\s*colorWith" + commonObjCRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Objective-C White float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } do { // Don't care about saving the Calibrated, Device, or genericGamma22 since we assume that any function that // replace the values will do so selectively instead of overwriting the whole string. regex = try NSRegularExpression ( pattern: "\\[\\s*NSColor\\s*colorWith(?:Calibrated|Device|GenericGamma22)" + commonObjCRegex, options: []) } catch let error1 as NSError { error = error1 regex = nil } if regex == nil { print ( "Error creating Objective-C calibrated, device, genericGamma22 white float with alpha regex = \(error?.localizedDescription)" ) } else { regexes.append( regex! ) } } override func processMatch ( match : NSTextCheckingResult, line : String ) -> SearchResult? { // We'll always have two matches right now but if ever the alpha becomes optional // then it will be either one or two and this function will have to look like // the others. if ( match.numberOfRanges == 3 ) { let matchString = stringFromRange( match.range, line: line ) let whiteString = stringFromRange( match.rangeAtIndex( 1 ), line: line ) let alphaString = stringFromRange( match.rangeAtIndex( 2 ), line: line ) let capturedStrings = [ matchString, whiteString, alphaString ] let whiteValue = CGFloat ( ( whiteString as NSString).doubleValue ) let alphaValue = CGFloat ( ( alphaString as NSString).doubleValue ) let whiteColor = NSColor ( calibratedWhite: whiteValue, alpha: alphaValue ) if let color = whiteColor.colorUsingColorSpace( NSColorSpace.genericRGBColorSpace() ) { var searchResult = SearchResult ( color: color, textCheckingResult: match, capturedStrings: capturedStrings ) searchResult.creationType = .DefaultWhite return searchResult } } return nil } }
253fdbed778b59e469eb6e569098771b
35.466102
162
0.555891
false
false
false
false
gerardogrisolini/Webretail
refs/heads/master
Sources/Webretail/Models/MwsRequest.swift
apache-2.0
1
// // MwsRequest.swift // Webretail // // Created by Gerardo Grisolini on 22/04/18. // import Foundation import PerfectLogger import StORM class MwsRequest : PostgresSqlORM, Codable { public var id: Int = 0 public var requestSku : String = "" public var requestXml : String = "" public var requestId: Int = 0 public var requestParentId: Int = 0 public var requestSubmissionId: String = "" public var requestCreatedAt: Int = Int.now() public var requestSubmittedAt: Int = 0 public var requestCompletedAt: Int = 0 public var messagesProcessed: Int = 0 public var messagesSuccessful: Int = 0 public var messagesWithError: Int = 0 public var messagesWithWarning: Int = 0 public var errorDescription: String = "" open override func table() -> String { return "mwsrequests" } override init() { super.init() } open override func to(_ this: StORMRow) { id = this.data["id"] as? Int ?? 0 requestSku = this.data["requestsku"] as? String ?? "" requestXml = this.data["requestxml"] as? String ?? "" requestId = this.data["requestid"] as? Int ?? 0 requestParentId = this.data["requestparentid"] as? Int ?? 0 requestSubmissionId = this.data["requestsubmissionid"] as? String ?? "" requestCreatedAt = this.data["requestcreatedat"] as? Int ?? 0 requestSubmittedAt = this.data["requestsubmittedat"] as? Int ?? 0 requestCompletedAt = this.data["requestcompletedat"] as? Int ?? 0 messagesProcessed = this.data["messagesprocessed"] as? Int ?? 0 messagesSuccessful = this.data["messagessuccessful"] as? Int ?? 0 messagesWithError = this.data["messageswitherror"] as? Int ?? 0 messagesWithWarning = this.data["messageswithwarning"] as? Int ?? 0 errorDescription = this.data["errordescription"] as? String ?? "" } func rows() -> [MwsRequest] { var rows = [MwsRequest]() for i in 0..<self.results.rows.count { let row = MwsRequest() row.to(self.results.rows[i]) rows.append(row) } return rows } public func currentRequests() throws -> [MwsRequest] { // try self.query(whereclause: "requestcompletedat = $1", params: [0]) try self.query(orderby: ["requestcreatedat DESC", "requestid"]) return self.rows() } public func rangeRequests(startDate: Int, finishDate: Int) throws -> [MwsRequest] { try self.query( whereclause: "requestcreatedat >= $1 && requestcreatedat <= $2 ", params: [startDate, finishDate], orderby: ["requestcreatedat DESC", "requestid"] ) return self.rows() } public func lastRequest() throws -> Int { let sql = "SELECT MAX(requestcreatedat) AS counter FROM \(table())"; let getCount = try self.sqlRows(sql, params: []) return getCount.first?.data["counter"] as? Int ?? 0 } }
54a64377db487ffca15b6f12b707e318
34.348837
87
0.613158
false
false
false
false
stevehe-campray/BSBDJ
refs/heads/master
BSBDJ/BSBDJ/FriendTrends(关注)/Controllers/BSBFriendTrendsViewController.swift
mit
1
// // BSBFriendTrendsViewController.swift // BSBDJ // // Created by hejingjin on 16/3/15. // Copyright © 2016年 baisibudejie. All rights reserved. // import UIKit class BSBFriendTrendsViewController: UIViewController { @IBOutlet weak var loginregiterButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setUpNavgation() setupMainInterface() self.view.backgroundColor = UIColor.lightGrayColor() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupMainInterface(){ loginregiterButton.addTarget(self, action: #selector(BSBFriendTrendsViewController.login), forControlEvents: UIControlEvents.TouchUpInside) } @IBAction func LoginButtonPressed(sender: AnyObject) { let loginvc = BSBLoginRegisterViewController(nibName:"BSBLoginRegisterViewController", bundle:nil) self .presentViewController(loginvc, animated: true, completion: nil) } func setUpNavgation(){ self.navigationItem.title = "我的关注" let leftButton = UIButton() leftButton.setBackgroundImage(UIImage(named: "friendsRecommentIcon"), forState: UIControlState.Normal) leftButton.setBackgroundImage(UIImage(named: "cellFollowClickIcon"), forState: UIControlState.Highlighted) leftButton.bounds = CGRectMake(0, 0, (leftButton.currentBackgroundImage?.size.width)!, (leftButton.currentBackgroundImage?.size.height)!) leftButton.addTarget(self, action: #selector(BSBFriendTrendsViewController.myrecomment), forControlEvents: UIControlEvents.TouchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton) } func myrecomment(){ let recomendvc = BSBrecomendViewController(nibName:"BSBrecomendViewController" ,bundle:nil) self.navigationController?.pushViewController(recomendvc, animated: true) } func login(){ print("login") } }
9a42b0a9224b2f64e6df31c44713644b
34.483333
147
0.715359
false
false
false
false
EasonWQY/swiftweaher1
refs/heads/master
Swift Weather/ViewController.swift
mit
2
// // ViewController.swift // Swift Weather // // Created by Jake Lin on 4/06/2014. // Copyright (c) 2014 rushjet. All rights reserved. // import UIKit import CoreLocation import Alamofire import SwiftyJSON import SwiftWeatherService class ViewController: UIViewController, CLLocationManagerDelegate { let locationManager:CLLocationManager = CLLocationManager() @IBOutlet var loadingIndicator : UIActivityIndicatorView! = nil @IBOutlet var icon : UIImageView! @IBOutlet var temperature : UILabel! @IBOutlet var loading : UILabel! @IBOutlet var location : UILabel! @IBOutlet weak var time1: UILabel! @IBOutlet weak var time2: UILabel! @IBOutlet weak var time3: UILabel! @IBOutlet weak var time4: UILabel! @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! @IBOutlet weak var image4: UIImageView! @IBOutlet weak var temp1: UILabel! @IBOutlet weak var temp2: UILabel! @IBOutlet weak var temp3: UILabel! @IBOutlet weak var temp4: UILabel! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest self.loadingIndicator.startAnimating() let background = UIImage(named: "background.png") self.view.backgroundColor = UIColor(patternImage: background!) let singleFingerTap = UITapGestureRecognizer(target: self, action: "handleSingleTap:") self.view.addGestureRecognizer(singleFingerTap) locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } func handleSingleTap(recognizer: UITapGestureRecognizer) { locationManager.startUpdatingLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // It maybe a Xcode 6.2 beta Swift compiler's bug, it throws "command failed due to signal segmentation fault 11" error /* func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let service = SwiftWeatherService.WeatherService() service.retrieveForecast(latitude, longitude: longitude, success: { response in println(response) // self.updateUISuccess(response.object!) }, failure:{ response in println(response) println("Error: " + response.error!.localizedDescription) self.loading.text = "Internet appears down!" }) } */ func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let url = "http://api.openweathermap.org/data/2.5/forecast" let params = ["lat":latitude, "lon":longitude] println(params) Alamofire.request(.GET, url, parameters: params) .responseJSON { (request, response, json, error) in if(error != nil) { println("Error: \(error)") println(request) println(response) self.loading.text = "Internet appears down!" } else { println("Success: \(url)") println(request) var json = JSON(json!) self.updateUISuccess(json) } } } func updateUISuccess(json: JSON) { self.loading.text = nil self.loadingIndicator.hidden = true self.loadingIndicator.stopAnimating() let service = SwiftWeatherService.WeatherService() // If we can get the temperature from JSON correctly, we assume the rest of JSON is correct. if let tempResult = json["list"][0]["main"]["temp"].double { // Get country let country = json["city"]["country"].stringValue // Get and convert temperature var temperature = service.convertTemperature(country, temperature: tempResult) self.temperature.text = "\(temperature)°" // Get city name self.location.text = json["city"]["name"].stringValue // Get and set icon let weather = json["list"][0]["weather"][0] let condition = weather["id"].intValue var icon = weather["icon"].stringValue var nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: 0, callback: self.updatePictures) // Get forecast for index in 1...4 { println(json["list"][index]) if let tempResult = json["list"][index]["main"]["temp"].double { // Get and convert temperature var temperature = service.convertTemperature(country, temperature: tempResult) if (index==1) { self.temp1.text = "\(temperature)°" } else if (index==2) { self.temp2.text = "\(temperature)°" } else if (index==3) { self.temp3.text = "\(temperature)°" } else if (index==4) { self.temp4.text = "\(temperature)°" } // Get forecast time var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" let rawDate = json["list"][index]["dt"].doubleValue let date = NSDate(timeIntervalSince1970: rawDate) let forecastTime = dateFormatter.stringFromDate(date) if (index==1) { self.time1.text = forecastTime } else if (index==2) { self.time2.text = forecastTime } else if (index==3) { self.time3.text = forecastTime } else if (index==4) { self.time4.text = forecastTime } // Get and set icon let weather = json["list"][index]["weather"][0] let condition = weather["id"].intValue var icon = weather["icon"].stringValue var nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: index, callback: self.updatePictures) } else { continue } } } else { self.loading.text = "Weather info is not available!" } } func updatePictures(index: Int, name: String) { if (index==0) { self.icon.image = UIImage(named: name) } if (index==1) { self.image1.image = UIImage(named: name) } if (index==2) { self.image2.image = UIImage(named: name) } if (index==3) { self.image3.image = UIImage(named: name) } if (index==4) { self.image4.image = UIImage(named: name) } } //MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var location:CLLocation = locations[locations.count-1] as! CLLocation if (location.horizontalAccuracy > 0) { self.locationManager.stopUpdatingLocation() println(location.coordinate) updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude) } } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println(error) self.loading.text = "Can't get your location!" } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
fef3cd742101ef6f829b8118bcc996af
37.027397
123
0.555716
false
false
false
false
4taras4/totp-auth
refs/heads/master
TOTP/ViperModules/MainList/Module/Interactor/MainListInteractor.swift
mit
1
// // MainListMainListInteractor.swift // TOTP // // Created by Tarik on 10/10/2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import OneTimePassword import Base32 final class MainListInteractor: MainListInteractorInput { weak var output: MainListInteractorOutput? func converUserData(users: [User]) { var codes = [Code]() var favouritesArray = [Code]() for u in users { if let c = convertUser(user: u) { if u.isFavourite == true { favouritesArray.append(c) } codes.append(c) } } output?.listOfCodes(codes: codes, favourites: favouritesArray) } func convertUser(user: User) -> Code? { guard let secretData = MF_Base32Codec.data(fromBase32String: user.token), !secretData.isEmpty else { print("Invalid secret") return nil } guard let generator = Generator( factor: .timer(period: 30), secret: secretData, algorithm: .sha1, digits: 6) else { print("Invalid generator parameters") return nil } let token = Token(name: user.name ?? "", issuer: user.issuer ?? "", generator: generator) guard let currentCode = token.currentPassword else { print("Invalid generator parameters") return nil } return Code(name: user.name, issuer: user.issuer, code: currentCode, token: user.token) } func deleteRow(with token: String?) { let alertController = UIAlertController(title: Constants.text.removeBackupAlertTitle, message: Constants.text.removeBackupAlertDescription, preferredStyle: .alert) let cancelAction = UIAlertAction(title: Constants.text.cancelAlertButton, style: .cancel) let okAction = UIAlertAction(title: Constants.text.removeAlertButton, style: .destructive, handler: { _ in guard let item = RealmManager.shared.getUserBy(token: token) else { return } RealmManager.shared.removeObject(user: item, completionHandler: { success in if success { self.output?.dataBaseOperationFinished() } }) }) alertController.addAction(cancelAction) alertController.addAction(okAction) if let topController = UIApplication.topViewController() { topController.present(alertController, animated: true, completion: nil) } } func updateRow(with token: String?, isFavourite: Bool) { guard let item = RealmManager.shared.getUserBy(token: token) else { return } RealmManager.shared.saveNewUser(name: item.name, issuer: item.issuer, token: item.token ?? "", isFav: isFavourite, completionHandler: { completed in if completed { self.output?.dataBaseOperationFinished() } }) } func getFolders() { output?.listOfFolders(array: RealmManager.shared.fetchFolders() ?? []) } }
1c381c83dfd5850a0e37e0ef45d8b937
35.022989
171
0.60402
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOPosix/SelectorEpoll.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore #if !SWIFTNIO_USE_IO_URING #if os(Linux) || os(Android) /// Represents the `epoll` filters/events we might use: /// /// - `hangup` corresponds to `EPOLLHUP` /// - `readHangup` corresponds to `EPOLLRDHUP` /// - `input` corresponds to `EPOLLIN` /// - `output` corresponds to `EPOLLOUT` /// - `error` corresponds to `EPOLLERR` private struct EpollFilterSet: OptionSet, Equatable { typealias RawValue = UInt8 let rawValue: RawValue static let _none = EpollFilterSet([]) static let hangup = EpollFilterSet(rawValue: 1 << 0) static let readHangup = EpollFilterSet(rawValue: 1 << 1) static let input = EpollFilterSet(rawValue: 1 << 2) static let output = EpollFilterSet(rawValue: 1 << 3) static let error = EpollFilterSet(rawValue: 1 << 4) init(rawValue: RawValue) { self.rawValue = rawValue } } extension EpollFilterSet { /// Convert NIO's `SelectorEventSet` set to a `EpollFilterSet` init(selectorEventSet: SelectorEventSet) { var thing: EpollFilterSet = [.error, .hangup] if selectorEventSet.contains(.read) { thing.formUnion(.input) } if selectorEventSet.contains(.write) { thing.formUnion(.output) } if selectorEventSet.contains(.readEOF) { thing.formUnion(.readHangup) } self = thing } } extension SelectorEventSet { var epollEventSet: UInt32 { assert(self != ._none) // EPOLLERR | EPOLLHUP is always set unconditionally anyway but it's easier to understand if we explicitly ask. var filter: UInt32 = Epoll.EPOLLERR | Epoll.EPOLLHUP let epollFilters = EpollFilterSet(selectorEventSet: self) if epollFilters.contains(.input) { filter |= Epoll.EPOLLIN } if epollFilters.contains(.output) { filter |= Epoll.EPOLLOUT } if epollFilters.contains(.readHangup) { filter |= Epoll.EPOLLRDHUP } assert(filter & Epoll.EPOLLHUP != 0) // both of these are reported assert(filter & Epoll.EPOLLERR != 0) // always and can't be masked. return filter } fileprivate init(epollEvent: Epoll.epoll_event) { var selectorEventSet: SelectorEventSet = ._none if epollEvent.events & Epoll.EPOLLIN != 0 { selectorEventSet.formUnion(.read) } if epollEvent.events & Epoll.EPOLLOUT != 0 { selectorEventSet.formUnion(.write) } if epollEvent.events & Epoll.EPOLLRDHUP != 0 { selectorEventSet.formUnion(.readEOF) } if epollEvent.events & Epoll.EPOLLHUP != 0 || epollEvent.events & Epoll.EPOLLERR != 0 { selectorEventSet.formUnion(.reset) } self = selectorEventSet } } // EPollUserData supports (un)packing into an `UInt64` because epoll has a user info field that we can attach which is // up to 64 bits wide. We're using all of those 64 bits, 32 for a "registration ID" and 32 for the file descriptor. @usableFromInline struct EPollUserData { @usableFromInline var registrationID: SelectorRegistrationID @usableFromInline var fileDescriptor: CInt @inlinable init(registrationID: SelectorRegistrationID, fileDescriptor: CInt) { assert(MemoryLayout<UInt64>.size == MemoryLayout<EPollUserData>.size) self.registrationID = registrationID self.fileDescriptor = fileDescriptor } @inlinable init(rawValue: UInt64) { let unpacked = IntegerBitPacking.unpackUInt32CInt(rawValue) self = .init(registrationID: SelectorRegistrationID(rawValue: unpacked.0), fileDescriptor: unpacked.1) } } extension UInt64 { @inlinable init(_ epollUserData: EPollUserData) { let fd = epollUserData.fileDescriptor assert(fd >= 0, "\(fd) is not a valid file descriptor") self = IntegerBitPacking.packUInt32CInt(epollUserData.registrationID.rawValue, fd) } } extension Selector: _SelectorBackendProtocol { func initialiseState0() throws { self.selectorFD = try Epoll.epoll_create(size: 128) self.eventFD = try EventFd.eventfd(initval: 0, flags: Int32(EventFd.EFD_CLOEXEC | EventFd.EFD_NONBLOCK)) self.timerFD = try TimerFd.timerfd_create(clockId: CLOCK_MONOTONIC, flags: Int32(TimerFd.TFD_CLOEXEC | TimerFd.TFD_NONBLOCK)) self.lifecycleState = .open var ev = Epoll.epoll_event() ev.events = SelectorEventSet.read.epollEventSet ev.data.u64 = UInt64(EPollUserData(registrationID: .initialRegistrationID, fileDescriptor: self.eventFD)) try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_ADD, fd: self.eventFD, event: &ev) var timerev = Epoll.epoll_event() timerev.events = Epoll.EPOLLIN | Epoll.EPOLLERR | Epoll.EPOLLRDHUP timerev.data.u64 = UInt64(EPollUserData(registrationID: .initialRegistrationID, fileDescriptor: self.timerFD)) try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_ADD, fd: self.timerFD, event: &timerev) } func deinitAssertions0() { assert(self.eventFD == -1, "self.eventFD == \(self.eventFD) in deinitAssertions0, forgot close?") assert(self.timerFD == -1, "self.timerFD == \(self.timerFD) in deinitAssertions0, forgot close?") } func register0<S: Selectable>(selectable: S, fileDescriptor: CInt, interested: SelectorEventSet, registrationID: SelectorRegistrationID) throws { var ev = Epoll.epoll_event() ev.events = interested.epollEventSet ev.data.u64 = UInt64(EPollUserData(registrationID: registrationID, fileDescriptor: fileDescriptor)) try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_ADD, fd: fileDescriptor, event: &ev) } func reregister0<S: Selectable>(selectable: S, fileDescriptor: CInt, oldInterested: SelectorEventSet, newInterested: SelectorEventSet, registrationID: SelectorRegistrationID) throws { var ev = Epoll.epoll_event() ev.events = newInterested.epollEventSet ev.data.u64 = UInt64(EPollUserData(registrationID: registrationID, fileDescriptor: fileDescriptor)) _ = try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_MOD, fd: fileDescriptor, event: &ev) } func deregister0<S: Selectable>(selectable: S, fileDescriptor: CInt, oldInterested: SelectorEventSet, registrationID: SelectorRegistrationID) throws { var ev = Epoll.epoll_event() _ = try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_DEL, fd: fileDescriptor, event: &ev) } /// Apply the given `SelectorStrategy` and execute `body` once it's complete (which may produce `SelectorEvent`s to handle). /// /// - parameters: /// - strategy: The `SelectorStrategy` to apply /// - body: The function to execute for each `SelectorEvent` that was produced. func whenReady0(strategy: SelectorStrategy, onLoopBegin loopStart: () -> Void, _ body: (SelectorEvent<R>) throws -> Void) throws -> Void { assert(self.myThread == NIOThread.current) guard self.lifecycleState == .open else { throw IOError(errnoCode: EBADF, reason: "can't call whenReady for selector as it's \(self.lifecycleState).") } let ready: Int switch strategy { case .now: ready = Int(try Epoll.epoll_wait(epfd: self.selectorFD, events: events, maxevents: Int32(eventsCapacity), timeout: 0)) case .blockUntilTimeout(let timeAmount): // Only call timerfd_settime if we're not already scheduled one that will cover it. // This guards against calling timerfd_settime if not needed as this is generally speaking // expensive. let next = NIODeadline.now() + timeAmount if next < self.earliestTimer { self.earliestTimer = next var ts = itimerspec() ts.it_value = timespec(timeAmount: timeAmount) try TimerFd.timerfd_settime(fd: self.timerFD, flags: 0, newValue: &ts, oldValue: nil) } fallthrough case .block: ready = Int(try Epoll.epoll_wait(epfd: self.selectorFD, events: events, maxevents: Int32(eventsCapacity), timeout: -1)) } loopStart() for i in 0..<ready { let ev = events[i] let epollUserData = EPollUserData(rawValue: ev.data.u64) let fd = epollUserData.fileDescriptor let eventRegistrationID = epollUserData.registrationID switch fd { case self.eventFD: var val = EventFd.eventfd_t() // Consume event _ = try EventFd.eventfd_read(fd: self.eventFD, value: &val) case self.timerFD: // Consume event var val: UInt64 = 0 // We are not interested in the result _ = try! Posix.read(descriptor: self.timerFD, pointer: &val, size: MemoryLayout.size(ofValue: val)) // Processed the earliest set timer so reset it. self.earliestTimer = .distantFuture default: // If the registration is not in the Map anymore we deregistered it during the processing of whenReady(...). In this case just skip it. if let registration = registrations[Int(fd)] { guard eventRegistrationID == registration.registrationID else { continue } var selectorEvent = SelectorEventSet(epollEvent: ev) // we can only verify the events for i == 0 as for i > 0 the user might have changed the registrations since then. assert(i != 0 || selectorEvent.isSubset(of: registration.interested), "selectorEvent: \(selectorEvent), registration: \(registration)") // in any case we only want what the user is currently registered for & what we got selectorEvent = selectorEvent.intersection(registration.interested) guard selectorEvent != ._none else { continue } try body((SelectorEvent(io: selectorEvent, registration: registration))) } } } growEventArrayIfNeeded(ready: ready) } /// Close the `Selector`. /// /// After closing the `Selector` it's no longer possible to use it. public func close0() throws { self.externalSelectorFDLock.withLock { // We try! all of the closes because close can only fail in the following ways: // - EINTR, which we eat in Posix.close // - EIO, which can only happen for on-disk files // - EBADF, which can't happen here because we would crash as EBADF is marked unacceptable // Therefore, we assert here that close will always succeed and if not, that's a NIO bug we need to know // about. try! Posix.close(descriptor: self.timerFD) self.timerFD = -1 try! Posix.close(descriptor: self.eventFD) self.eventFD = -1 try! Posix.close(descriptor: self.selectorFD) self.selectorFD = -1 } } /* attention, this may (will!) be called from outside the event loop, ie. can't access mutable shared state (such as `self.open`) */ func wakeup0() throws { assert(NIOThread.current != self.myThread) try self.externalSelectorFDLock.withLock { guard self.eventFD >= 0 else { throw EventLoopError.shutdown } _ = try EventFd.eventfd_write(fd: self.eventFD, value: 1) } } } #endif #endif
ba5d3b99a69373d7235b6216ad3456b8
41.800676
155
0.611019
false
false
false
false
daehn/Counted-Set
refs/heads/develop
CountedSet/CountedSet.swift
mit
1
// // The MIT License (MIT) // Copyright 2016 Silvan Dähn // // 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. // public struct CountedSet<Element: Hashable>: ExpressibleByArrayLiteral { public typealias ElementWithCount = (element: Element, count: Int) public typealias Index = SetIndex<Element> fileprivate var backing = Set<Element>() fileprivate var countByElement = [Element: Int]() public mutating func insert(_ member: Element) { backing.insert(member) let count = countByElement[member] ?? 0 countByElement[member] = count + 1 } @discardableResult public mutating func remove(_ member: Element) -> Element? { guard var count = countByElement[member], count > 0 else { return nil } count -= 1 countByElement[member] = Swift.max(count, 0) if count <= 0 { backing.remove(member) } return member } public func count(for member: Element) -> Int { return countByElement[member] ?? 0 } public init(arrayLiteral elements: Element...) { elements.forEach { insert($0) } } public subscript(member: Element) -> Int { return count(for: member) } @discardableResult public mutating func setCount(_ count: Int, for element: Element) -> Bool { precondition(count >= 0, "Count has to be positive") guard count != countByElement[element] else { return false } if count > 0 && !contains(element) { backing.insert(element) } countByElement[element] = count if count <= 0 { backing.remove(element) } return true } public func mostFrequent() -> ElementWithCount? { guard !backing.isEmpty else { return nil } return reduce((backing[backing.startIndex], 0)) { max, current in let currentCount = count(for: current) guard currentCount > max.1 else { return max } return (current, currentCount) } } } // MARK: - Collection extension CountedSet: Collection { public var startIndex: SetIndex<Element> { return backing.startIndex } public var endIndex: SetIndex<Element> { return backing.endIndex } public func index(after i: SetIndex<Element>) -> SetIndex<Element> { return backing.index(after: i) } public subscript(position: SetIndex<Element>) -> Element { return backing[position] } public func makeIterator() -> SetIterator<Element> { return backing.makeIterator() } } // MARK: - Hashable extension CountedSet: Hashable { public var hashValue: Int { return backing.hashValue ^ Int(countByElement.values.reduce(0, ^)) } } // MARK: - Equatable Operator public func ==<Element>(lhs: CountedSet<Element>, rhs: CountedSet<Element>) -> Bool { return lhs.backing == rhs.backing && lhs.countByElement == rhs.countByElement } // MARK: - CustomStringConvertible extension CountedSet: CustomStringConvertible { public var description: String { return backing.reduce("<CountedSet>:\n") { sum, element in sum + "\t- \(element): \(count(for: element))\n" } } }
42459b3a96fc09093c59e1a81e9cf9a3
30.58209
98
0.663043
false
false
false
false
richardpiazza/SOSwift
refs/heads/master
Sources/SOSwift/MusicComposition.swift
mit
1
import Foundation /// A musical composition. public class MusicComposition: CreativeWork { /// The person or organization who wrote a composition, or who is the /// composer of a work performed at some event. public var composer: OrganizationOrPerson? /// The date and place the work was first performed. public var firstPerformance: Event? /// Smaller compositions included in this work (e.g. a movement in a symphony). public var includedComposition: MusicComposition? /// The International Standard Musical Work Code for the composition. public var iswcCode: String? /// The person who wrote the words. public var lyricist: Person? /// The words in the song. public var lyrics: CreativeWork? /// An arrangement derived from the composition. public var musicArrangement: MusicComposition? /// The type of composition (e.g. overture, sonata, symphony, etc.). public var musicCompositionForm: String? /// The key, mode, or scale this composition uses. public var musicalKey: String? /// An audio recording of the work. /// - Inverse property: recordingOf. public var recordedAs: MusicRecording? internal enum MusicCompositionCodingKeys: String, CodingKey { case composer case firstPerformance case includedComposition case iswcCode case lyricist case lyrics case musicArrangement case musicCompositionForm case musicalKey case recordedAs } public override init() { super.init() } public required init(from decoder: Decoder) throws { try super.init(from: decoder) let container = try decoder.container(keyedBy: MusicCompositionCodingKeys.self) composer = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .composer) firstPerformance = try container.decodeIfPresent(Event.self, forKey: .firstPerformance) includedComposition = try container.decodeIfPresent(MusicComposition.self, forKey: .includedComposition) iswcCode = try container.decodeIfPresent(String.self, forKey: .iswcCode) lyricist = try container.decodeIfPresent(Person.self, forKey: .lyricist) lyrics = try container.decodeIfPresent(CreativeWork.self, forKey: .lyrics) musicArrangement = try container.decodeIfPresent(MusicComposition.self, forKey: .musicArrangement) musicCompositionForm = try container.decodeIfPresent(String.self, forKey: .musicCompositionForm) musicalKey = try container.decodeIfPresent(String.self, forKey: .musicalKey) recordedAs = try container.decodeIfPresent(MusicRecording.self, forKey: .recordedAs) } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: MusicCompositionCodingKeys.self) try container.encodeIfPresent(composer, forKey: .composer) try container.encodeIfPresent(firstPerformance, forKey: .firstPerformance) try container.encodeIfPresent(includedComposition, forKey: .includedComposition) try container.encodeIfPresent(iswcCode, forKey: .iswcCode) try container.encodeIfPresent(lyricist, forKey: .lyricist) try container.encodeIfPresent(lyrics, forKey: .lyrics) try container.encodeIfPresent(musicArrangement, forKey: .musicArrangement) try container.encodeIfPresent(musicCompositionForm, forKey: .musicCompositionForm) try container.encodeIfPresent(musicalKey, forKey: .musicalKey) try container.encodeIfPresent(recordedAs, forKey: .recordedAs) try super.encode(to: encoder) } }
dd5d441aab44f7144da56a327676550b
41.625
112
0.705678
false
false
false
false
fancymax/12306ForMac
refs/heads/master
12306ForMac/Service/Service+Login.swift
mit
1
// // PcHTTPService+Login.swift // Train12306 // // Created by fancymax on 15/11/7. // Copyright © 2015年 fancy. All rights reserved. // import JavaScriptCore import Foundation import Alamofire import PromiseKit import SwiftyJSON extension Service { // MARK: - Request Flow func preLoginFlow(success:@escaping (NSImage)->Void,failure:@escaping (NSError)->Void){ let cookie1 = HTTPCookie(properties: [.name:"RAIL_DEVICEID",.domain:"kyfw.12306.cn",.value:"CyeQGv5X_Y9BsIIkxXGf8s_wPmVs2yH4idlQo3d4KxgeY10nAnXWcm72qwxLLd_xqQm-v8UaFAVL7elDx_KFZw1FN3MkwJcbQAGtPIFEWfWPsdsOr5_jgjV-HSn7t-2u2fZgGrTOSCpfoYMOF41I1qWmNkGkObIX",.path:"/"]) let cookie2 = HTTPCookie(properties: [.name:"RAIL_EXPIRATION",.domain:"kyfw.12306.cn",.value:"1516426090658",.path:"/"]) Service.Manager.session.configuration.httpCookieStorage?.setCookie(cookie1!) Service.Manager.session.configuration.httpCookieStorage?.setCookie(cookie2!) loginInit().then{(dynamicJs) -> Promise<Void> in return self.requestDynamicJs(dynamicJs, referHeader: ["refer": "https://kyfw.12306.cn/otn/login/init"]) }.then{_ -> Promise<NSImage> in return self.getPassCodeNewForLogin() }.then{ image in success(image) }.catch { error in failure(error as NSError) } } func loginFlow(user:String,passWord:String,randCodeStr:String,success:@escaping ()->Void,failure:@escaping (NSError)->Void){ after(interval: 2).then{ self.checkRandCodeForLogin(randCodeStr) }.then{() -> Promise<Void> in return self.loginUserWith(user, passWord: passWord, randCodeStr: randCodeStr) }.then{ () -> Promise<(Bool,String)> in return self.checkUAM() }.then{ (hasLogin,tk) -> Promise<Bool> in return self.uampassport(tk: tk) }.then{ (_) -> Promise<Void> in return self.initMy12306() }.then{ () -> Promise<Void> in return self.getPassengerDTOs(isSubmit: false) }.then{_ in success() }.catch { error in failure(error as NSError) } } // MARK: - Chainable Request func loginInit()->Promise<String>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/login/init" let headers = ["refer": "https://kyfw.12306.cn/otn/leftTicket/init"] Service.Manager.request(url, headers:headers).responseString(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let content): var dynamicJs = "" if let matches = Regex("src=\"/otn/dynamicJs/([^\"]+)\"").getMatches(content){ dynamicJs = matches[0][0] } else{ logger.error("fail to get dynamicJs:\(content)") } self.getConfigFromInitContent(content) fulfill(dynamicJs) }}) } } func loginOut() { let url = "https://kyfw.12306.cn/otn/login/loginOut" Service.Manager.request(url).responseString(completionHandler:{response in }) } func getPassCodeNewForLogin()->Promise<NSImage>{ return Promise{ fulfill, reject in let param = CaptchaImageParam().ToGetParams() let url = "\(passport_captcha)?\(param)" let headers = ["refer": "https://kyfw.12306.cn/otn/login/init"] Service.Manager.request(url, headers:headers).responseData{ response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let image = NSImage(data: data){ fulfill(image) } else{ let error = ServiceError.errorWithCode(.getRandCodeFailed) reject(error) } }} } } func checkUAM() ->Promise<(Bool,String)> { return Promise{ fulfill, reject in let url = passport_authuam //TODO //$.jc_getcookie("tk"); let params = ["appid":passport_appId] var headers:[String:String] = [:] headers[referKey] = referValueForLoginInit Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let result_code = JSON(data)["result_code"].int { var hasLogin = false var tk = "" if result_code == 0 { if let apptk = JSON(data)["apptk"].string { tk = apptk } if let newapptk = JSON(data)["newapptk"].string { tk = newapptk } hasLogin = true } else { hasLogin = false } fulfill((hasLogin,tk)) } else{ let error = ServiceError.errorWithCode(.loginFailed, failureReason: "checkUAM") reject(error) } }}) } } func uampassport(tk:String) ->Promise<Bool> { return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/" + passport_authclient //TODO //$.jc_getcookie("tk"); let params = ["tk":tk] var headers:[String:String] = [:] headers[referKey] = referValueForLoginInit Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let result_code = JSON(data)["result_code"].int { var hasLogin = false if result_code == 0 { hasLogin = true if let userName = JSON(data)["username"].string { MainModel.userName = userName } } else { hasLogin = false } fulfill(hasLogin) } else{ let error = ServiceError.errorWithCode(.loginFailed, failureReason: "uampassport") reject(error) } }}) } } func checkRandCodeForLogin(_ randCodeStr:String)->Promise<Void>{ return Promise{ fulfill, reject in let url = passport_captcha_check let params = ["answer":randCodeStr,"login_site":"E","rand":"sjrand"] let headers = ["Referer": "https://kyfw.12306.cn/otn/login/init", "X-Requested-With":"XMLHttpRequest"] Service.Manager.request(url, method:.post, parameters: params, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let msg = JSON(data)["result_code"].string , msg == "4"{ fulfill() } else{ let error = ServiceError.errorWithCode(.checkRandCodeFailed) reject(error) } }}) } } func loginUserWith(_ user:String, passWord:String, randCodeStr:String)->Promise<Void>{ return Promise{ fulfill, reject in let url = passport_login let params = ["username":user,"password":passWord,"appid":passport_appId] let headers = ["Referer": "https://kyfw.12306.cn/otn/login/init", "Origin":"https://kyfw.12306.cn", "X-Requested-With":"XMLHttpRequest"] Service.Manager.request(url, method:.post, parameters: params,encoding: URLEncoding.default, headers:headers).responseJSON(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let result_code = JSON(data)["result_code"].int ,result_code == 0{ fulfill() } else{ let error:NSError if let errorStr = JSON(data)["result_message"].string{ error = ServiceError.errorWithCode(.loginUserFailed, failureReason: errorStr) } else{ error = ServiceError.errorWithCode(.loginUserFailed) } reject(error) } }}) } } func initMy12306()->Promise<Void>{ return Promise{ fulfill, reject in let url = "https://kyfw.12306.cn/otn/index/initMy12306" let headers = ["refer": "https://kyfw.12306.cn/otn/login/init"] Service.Manager.request(url, headers:headers).responseString(completionHandler:{response in switch (response.result){ case .failure(let error): reject(error) case .success(let data): if let matches = Regex("(var user_name='[^']+')").getMatches(data){ //for javascript let context = JSContext()! context.evaluateScript(matches[0][0]) MainModel.realName = context.objectForKeyedSubscript("user_name").toString() } else{ logger.error("can't get user_name") } fulfill() }}) } } }
11914e9105bda21809afd2e57946507d
40.726236
273
0.487334
false
false
false
false
swift102016team5/mefocus
refs/heads/master
MeFocus/MeFocus/Session.swift
mit
1
// // Session.swift // MeFocus // // Created by Hao on 11/20/16. // Copyright © 2016 Group5. All rights reserved. // import Foundation import CoreData import AVFoundation import UIKit import SwiftWebSocket extension Session { func isExceedMaxiumPause() -> Bool { return SessionsManager.isExceedMaxiumPause(session:self) } func isOver() -> Bool { let now = Int64(NSDate().timeIntervalSince1970) if start_at + duration > now { return false } return true } func finish(){ end_at = Int64(NSDate().timeIntervalSince1970) is_success = isOver() && !isExceedMaxiumPause() SessionsManager.reset() Storage.shared.save() } } enum SessionsManagerError:Error { case Unfinished case MaximumPauseDurationMustGreaterThanZero } class SessionsManager:NSObject { // Start new session , doing implicit checking if there is any unfinished session // If satisfied , it will start new session and persisted to storage // Reset manager pauses count static func start( goal:String, duration:Int, maximPauseDuration:Int ) throws -> Session { if maximPauseDuration == 0 { throw SessionsManagerError.MaximumPauseDurationMustGreaterThanZero } if SessionsManager.unfinished == nil { SessionsManager.reset() let session = Session(data:[ "goal":goal, "duration":duration, "maximum_pause_duration":maximPauseDuration, "start_at":Int64(NSDate().timeIntervalSince1970) ]) Storage.shared.save() return session } throw SessionsManagerError.Unfinished } static var pauses:Int64 = 0 static func reset(){ SessionsManager.pauses = 0 } static func notify(){ } static func alert() -> AVAudioPlayer?{ if let asset = NSDataAsset(name:"cohangxom") { var player:AVAudioPlayer do { try player = AVAudioPlayer(data: asset.data, fileTypeHint:"mp3") player.volume = 1 return player } catch { print("Cannot play notification \(error)") } } return nil } static func isExceedMaxiumPause(session:Session) -> Bool { return SessionsManager.pauses > session.maximum_pause_duration } static func all() -> [Session]{ let request = Storage.shared.request(entityName: "Session") let sessions = Storage.shared.fetch(request: request) as! [Session] return sessions.reversed() } // Get unfinished session , usefull for navigation static var unfinished:Session? { get { let request = Storage.shared.request(entityName: "Session") request.fetchLimit = 1 request.predicate = NSPredicate(format: "end_at = 0") let sessions = Storage.shared.fetch(request: request) as! [Session] if sessions.count == 1 { if let unfinish = sessions.first { if unfinish.isExceedMaxiumPause() || unfinish.isOver() { unfinish.finish() return nil } return unfinish } } return nil } } }
17cef56894a5b4897489255ae0e3de01
25.304348
86
0.546832
false
false
false
false
kazedayo/GaldenApp
refs/heads/master
GaldenApp/View Controllers/PageSelectTableViewController.swift
mit
1
// // PageSelectTableViewController.swift // GaldenApp // // Created by Kin Wa Lam on 16/10/2017. // Copyright © 2017年 1080@galden. All rights reserved. // import UIKit class PageSelectTableViewController: UITableViewController { var pageCount: Double = 0.0 var pageSelected: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem self.tableView.tableFooterView = UIView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return Int(pageCount) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PageSelectTableViewCell", for: indexPath) as! PageSelectTableViewCell // Configure the cell... cell.pageNo.text = "第" + String(indexPath.row + 1) + "頁" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { pageSelected = (indexPath.row + 1) performSegue(withIdentifier: "unwindToPage", sender: self) } /* // 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. } */ }
fc96becf7b00780d9fb17eaa435f1782
33.247619
136
0.670467
false
false
false
false
mzp/OctoEye
refs/heads/master
Tests/Unit/GithubAPI/FetchBlobSpec.swift
mit
1
// // FetchTextSpec.swift // Tests // // Created by mzp on 2017/07/07. // Copyright © 2017 mzp. All rights reserved. // import JetToTheFuture import Nimble import Quick import Result internal class FetchBlobSpec: QuickSpec { override func spec() { let github = GithubClient( token: "-", httpRequest: MockHttpRequest(response: fixture(name: "content", ofType: "txt"))) let data = forcedFuture { _ in FetchBlob(github: github).call(owner: "octocat", name: "example", oid: "-") }.value // swiftlint:disable:next force_unwrapping let text = String(data: data!, encoding: String.Encoding.utf8) describe("text") { it("returns file content") { expect(text) == "Content of the blob\n" } } } }
e8dd0f14e7c091c751a5058dc99d3f21
25.83871
92
0.58774
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureOnboarding/Sources/FeatureOnboardingUI/OnboardingRouter.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainNamespace import Combine import CombineSchedulers import DIKit import Errors import SwiftUI import ToolKit import UIKit public protocol KYCRouterAPI { func presentEmailVerification(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> func presentKYCUpgradePrompt(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> } public protocol TransactionsRouterAPI { func presentBuyFlow(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> func navigateToBuyCryptoFlow(from presenter: UIViewController) func navigateToReceiveCryptoFlow(from presenter: UIViewController) } public final class OnboardingRouter: OnboardingRouterAPI { // MARK: - Properties let app: AppProtocol let kycRouter: KYCRouterAPI let transactionsRouter: TransactionsRouterAPI let featureFlagsService: FeatureFlagsServiceAPI let mainQueue: AnySchedulerOf<DispatchQueue> // MARK: - Init public init( app: AppProtocol = resolve(), kycRouter: KYCRouterAPI = resolve(), transactionsRouter: TransactionsRouterAPI = resolve(), featureFlagsService: FeatureFlagsServiceAPI = resolve(), mainQueue: AnySchedulerOf<DispatchQueue> = .main ) { self.app = app self.kycRouter = kycRouter self.transactionsRouter = transactionsRouter self.featureFlagsService = featureFlagsService self.mainQueue = mainQueue } // MARK: - Onboarding Routing public func presentPostSignUpOnboarding(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> { // Step 1: present email verification presentEmailVerification(from: presenter) .flatMap { [weak self] result -> AnyPublisher<OnboardingResult, Never> in guard let self = self else { return .just(.abandoned) } let app = self.app if app.remoteConfiguration.yes(if: blockchain.ux.onboarding.promotion.cowboys.is.enabled), app.state.yes(if: blockchain.user.is.cowboy.fan) { if result == .completed { return Task<OnboardingResult, Error>.Publisher(priority: .userInitiated) { try await self.presentCowboyPromotion(from: presenter) } .replaceError(with: .abandoned) .eraseToAnyPublisher() } else { return .just(.abandoned) } } return self.presentUITour(from: presenter) } .eraseToAnyPublisher() } public func presentPostSignInOnboarding(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> { kycRouter.presentKYCUpgradePrompt(from: presenter) } public func presentRequiredCryptoBalanceView( from presenter: UIViewController ) -> AnyPublisher<OnboardingResult, Never> { let subject = PassthroughSubject<OnboardingResult, Never>() let view = CryptoBalanceRequiredView( store: .init( initialState: (), reducer: CryptoBalanceRequired.reducer, environment: CryptoBalanceRequired.Environment( close: { presenter.dismiss(animated: true) { subject.send(.abandoned) subject.send(completion: .finished) } }, presentBuyFlow: { [transactionsRouter] in presenter.dismiss(animated: true) { transactionsRouter.navigateToBuyCryptoFlow(from: presenter) } }, presentRequestCryptoFlow: { [transactionsRouter] in presenter.dismiss(animated: true) { transactionsRouter.navigateToReceiveCryptoFlow(from: presenter) } } ) ) ) presenter.present(view) return subject.eraseToAnyPublisher() } // MARK: - Helper Methods private func presentUITour(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> { let subject = PassthroughSubject<OnboardingResult, Never>() let view = UITourView( close: { subject.send(.abandoned) subject.send(completion: .finished) }, completion: { subject.send(.completed) subject.send(completion: .finished) } ) let hostingController = UIHostingController(rootView: view) hostingController.modalTransitionStyle = .crossDissolve hostingController.modalPresentationStyle = .overFullScreen presenter.present(hostingController, animated: true, completion: nil) return subject .flatMap { [transactionsRouter] result -> AnyPublisher<OnboardingResult, Never> in guard case .completed = result else { return .just(.abandoned) } return Deferred { Future { completion in presenter.dismiss(animated: true) { completion(.success(())) } } } .flatMap { transactionsRouter.presentBuyFlow(from: presenter) } .eraseToAnyPublisher() } .eraseToAnyPublisher() } private func presentEmailVerification(from presenter: UIViewController) -> AnyPublisher<OnboardingResult, Never> { featureFlagsService.isEnabled(.showEmailVerificationInOnboarding) .receive(on: mainQueue) .flatMap { [kycRouter] shouldShowEmailVerification -> AnyPublisher<OnboardingResult, Never> in guard shouldShowEmailVerification else { return .just(.completed) } return kycRouter.presentEmailVerification(from: presenter) } .eraseToAnyPublisher() } private func presentCowboyPromotion(from presenter: UIViewController) async throws -> OnboardingResult { if try app.state.get(blockchain.user.account.tier) == blockchain.user.account.tier.none[] { guard case .completed = await present( promotion: blockchain.ux.onboarding.promotion.cowboys.welcome, from: presenter ) else { return .abandoned } let kyc = try await app .on(blockchain.ux.kyc.event.did.finish, blockchain.ux.kyc.event.did.stop, blockchain.ux.kyc.event.did.cancel) .stream() .next() guard kyc.origin ~= blockchain.ux.kyc.event.did.finish else { return .abandoned } try await Task.sleep(nanoseconds: NSEC_PER_SEC / 2) guard case .completed = await present( promotion: blockchain.ux.onboarding.promotion.cowboys.raffle, from: presenter ) else { return .abandoned } let transaction = try await app .on(blockchain.ux.transaction["buy"].event.did.finish, blockchain.ux.transaction["buy"].event.execution.status.completed) .stream() .next() guard transaction.origin ~= blockchain.ux.transaction.event.execution.status.completed else { return .abandoned } try await Task.sleep(nanoseconds: NSEC_PER_SEC / 2) } return await present( promotion: blockchain.ux.onboarding.promotion.cowboys.verify.identity, from: presenter ) } @MainActor private func present( promotion: L & I_blockchain_ux_onboarding_type_promotion, from presenter: UIViewController ) async -> OnboardingResult { do { let story = promotion.story let view = try await PromotionView(promotion, ux: app.get(story)) .app(app) await MainActor.run { presenter.present(UIHostingController(rootView: view), animated: true) } let event = try await app.on(story.action.then.launch.url, story.action.then.close).stream().next() switch event.tag { case story.action.then.launch.url: return .completed default: return .abandoned } } catch { return .abandoned } } }
ca192e8cc28f4a70d254423a13a61a40
38.19469
137
0.588959
false
false
false
false
antonio081014/LeetCode-CodeBase
refs/heads/main
Swift/min-cost-to-connect-all-points.swift
mit
1
// // Heap.swift // // Created by Yi Ding on 9/30/19. // Copyright © 2019 Yi Ding. All rights reserved. // import Foundation public struct Heap<T> { /** The array that stores the heap's nodes. */ private(set) var nodes: [T] /** * Determines how to compare two nodes in the heap. * Use '>' for a max-heap or '<' for a min-heap, * or provide a comparing method if the heap is made * of custom elements, for example tuples. */ fileprivate let sortingComparator: (T, T) -> Bool /** * Creates an empty heap. * The sort function determines whether this is a min-heap or max-heap. * For comparable data types, > makes a max-heap, < makes a min-heap. */ public init(sortingComparator: @escaping (T, T) -> Bool) { self.nodes = [] self.sortingComparator = sortingComparator } /** * Creates a heap from an array. The order of the array does not matter; * the elements are inserted into the heap in the order determined by the * sort function. For comparable data types, '>' makes a max-heap, * '<' makes a min-heap. */ public init(array: [T], sortingComparator: @escaping (T, T) -> Bool) { self.nodes = [] self.sortingComparator = sortingComparator self.buildHeap(from: array) } /** * Configures the max-heap or min-heap from an array, in a bottom-up manner. * Performance: This runs pretty much in O(n). */ private mutating func buildHeap(from array: [T]) { // self.insert(array) self.nodes = array for index in stride(from: array.count / 2 - 1, through: 0, by: -1) { self.shiftDown(from: index) } } } // MARK: - Peek, Insert, Remove, Replace extension Heap { public var isEmpty: Bool { return self.nodes.isEmpty } public var count: Int { return self.nodes.count } /** * Returns the maximum value in the heap (for a max-heap) or the minimum * value (for a min-heap). * Performance: O(1) */ public func peek() -> T? { return self.nodes.first } /** * Adds a new value to the heap. This reorders the heap so that the max-heap * or min-heap property still holds. * Performance: O(log n). */ public mutating func insert(element: T) { self.nodes.append(element) self.shiftUp(from: self.nodes.count - 1) } /** * Adds a sequence of values to the heap. This reorders the heap so that * the max-heap or min-heap property still holds. * Performance: O(log n). */ public mutating func insert<S: Sequence>(_ sequence: S) where S.Iterator.Element == T { for value in sequence { insert(element: value) } } /** * Allows you to change an element. This reorders the heap so that * the max-heap or min-heap property still holds. * Performance: O(log n) */ public mutating func replace(at index: Int, value: T) { guard index < nodes.count else { return } remove(at: index) insert(element: value) } /** * Removes the root node from the heap. For a max-heap, this is the maximum * value; for a min-heap it is the minimum value. * Performance: O(log n). */ @discardableResult public mutating func remove() -> T? { guard self.nodes.count > 0 else { return nil } if self.nodes.count == 1 { return self.nodes.removeLast() } else { let value = self.nodes.first self.nodes[0] = self.nodes.removeLast() self.shiftDown(from: 0) return value } } /** * Removes an arbitrary node from the heap. * Note that you need to know the node's index. * Performance: O(log n) */ @discardableResult public mutating func remove(at index: Int) -> T? { guard index < self.count else { return nil } self.nodes.swapAt(index, self.nodes.count - 1) let value = self.nodes.removeLast() self.shiftDown(from: index) self.shiftUp(from: index) return value } } // MARK: - Index extension Heap { /** * Returns the index of the parent of the element at index i. * The element at index 0 is the root of the tree and has no parent. * Performance: O(1) */ func parentIndex(ofIndex i: Int) -> Int { return (i - 1) / 2 } /** * Returns the index of the left child of the element at index i. * Note that this index can be greater than the heap size, in which case * there is no left child. * Performance: O(1) */ func leftChildIndex(ofIndex index: Int) -> Int { return index * 2 + 1 } /** * Returns the index of the right child of the element at index i. * Note that this index can be greater than the heap size, in which case * there is no right child. * Performance: O(1) */ func rightChildIndex(ofIndex index: Int) -> Int { return index * 2 + 2 } } // MARK: - Shift Up / Down extension Heap { /** * Takes a child node and looks at its parents; if a parent is not larger * (max-heap) or not smaller (min-heap) than the child, we exchange them. * Performance: O(log n) */ mutating func shiftUp(from index: Int) { var childIndex = index var parentIndex = self.parentIndex(ofIndex: childIndex) while parentIndex < childIndex, !self.sortingComparator(self.nodes[parentIndex], self.nodes[childIndex]) { self.nodes.swapAt(childIndex, parentIndex) childIndex = parentIndex parentIndex = self.parentIndex(ofIndex: childIndex) } } /** * Looks at a parent node and makes sure it is still larger (max-heap) or * smaller (min-heap) than its childeren. * Performance: O(log n) */ mutating func shiftDown(from index: Int) { let parentIndex = index let leftChildIndex = self.leftChildIndex(ofIndex: parentIndex) let rightChildIndex = self.rightChildIndex(ofIndex: parentIndex) var subIndex = parentIndex if leftChildIndex < self.nodes.count, self.sortingComparator(self.nodes[subIndex], self.nodes[leftChildIndex]) == false { subIndex = leftChildIndex } if rightChildIndex < self.nodes.count, self.sortingComparator(self.nodes[subIndex], self.nodes[rightChildIndex]) == false { subIndex = rightChildIndex } if parentIndex == subIndex { return } self.nodes.swapAt(subIndex, index) self.shiftDown(from: subIndex) } } extension Heap where T: Equatable { /** * Get the index of a node in the heap. * Performance: O(n). */ public func index(of node: T) -> Int? { return self.nodes.firstIndex(of: node) } /** * Removes the first occurrence of a node from the heap. * Performance: O(n + log n) => O(n). */ @discardableResult public mutating func remove(node: T) -> T? { if let index = self.index(of: node) { return self.remove(at: index) } return nil } } class Solution { struct Edge: Comparable { let from: Int let to: Int let distance: Int // init(from: Int, to: Int, distance: Int) { // self.from = min(from, to) // self.to = max(from, to) // self.distance = distance // } static func < (lhs: Solution.Edge, rhs: Solution.Edge) -> Bool { return lhs.distance < rhs.distance } } func minCostConnectPoints(_ points: [[Int]]) -> Int { let n = points.count var notVisited = Set(0 ..< n) var currentIndex = 0 var minHeap = Heap<Edge>(sortingComparator: { $0 < $1 }) var result = 0 while notVisited.isEmpty == false { // print(currentIndex) notVisited.remove(currentIndex) for p in 0 ..< n { if notVisited.contains(p) { minHeap.insert(element: Edge(from: currentIndex, to: p, distance: self.dist(points[currentIndex], points[p]))) } } while let node = minHeap.peek(), notVisited.contains(node.to) == false { minHeap.remove() } if let node = minHeap.remove() { result += node.distance currentIndex = node.to } else { return result } } return result } private func dist(_ a: [Int], _ b: [Int]) -> Int { return abs(a[0] - b[0]) + abs(a[1] - b[1]) } }
4b65e413fb36cc38ad3bf8c02f3cf2cf
29.387755
131
0.5666
false
false
false
false
lyimin/iOS-Animation-Demo
refs/heads/master
iOS-Animation学习笔记/iOS-Animation学习笔记/ViewController.swift
mit
1
// // ViewController.swift // iOS-Animation学习笔记 // // Created by 梁亦明 on 15/12/22. // Copyright © 2015年 xiaoming. All rights reserved. // import UIKit class ViewController: UITableViewController { var titleArray : Array<String> = ["雪花粒子Demo","弹簧效果Demo","Twitter启动Demo","登陆动画Demo","引导页卡片Demo","扩大背景转场","SlidingPanels", "简书转场动画","进度条动画","音符加载动画"] var nameArray : Array<String> = Array() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.tableView.reloadData() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.titleArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cellId") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cellId") } cell?.textLabel?.text = titleArray[indexPath.row] return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var nextController : UIViewController! switch indexPath.row { case 0 : // 雪花demo nextController = EmitterViewController() case 1: // 弹簧Demo nextController = SpringAnimationViewController() case 2: // Twitter启动Demo nextController = SplashAnimiationController() case 3: // 登陆动画Demo nextController = LoginViewController() case 4: // 引导页卡片Demo nextController = TipFirstViewController() case 5: // 扩大背景转场 nextController = PingFirstController() case 6: // SlidingPanels nextController = RoomsViewController() nextController.view.backgroundColor = UIColor.orange nextController.title = titleArray[indexPath.row] self.present(nextController, animated: true, completion: nil) return case 7: // 简书转场动画 nextController = JSFirstViewController() case 8: // 进度条动画 nextController = ProgressAnimationController() case 9: // 音符加载 nextController = MusicIndicatorViewController() default: break; } nextController.view.backgroundColor = UIColor.orange nextController.title = titleArray[indexPath.row] self.navigationController?.pushViewController(nextController, animated: true) } }
e7f52bf192502459f5b87d0c24890dbe
34.308642
151
0.584965
false
false
false
false
evgenyneu/walk-to-circle-ios
refs/heads/master
walk to circle/Utils/iiDate.swift
mit
1
import Foundation public class iiDate { public class func toStringAsYearMonthDay(date: NSDate) -> String { let components = NSCalendar.currentCalendar().components( [NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: date) return "\(components.year).\(components.month).\(components.day)" } public class func fromYearMonthDay(year: Int, month: Int, day: Int) -> NSDate? { let dateComponents = NSDateComponents() dateComponents.year = year dateComponents.month = month dateComponents.day = day return NSCalendar.currentCalendar().dateFromComponents(dateComponents) } }
c3aaf7b7131e7c55e355ac00820fd6bb
29.666667
82
0.726708
false
false
false
false
toshiapp/toshi-ios-client
refs/heads/master
Toshi/Models/SofaWrappers/SofaPaymentRequest.swift
gpl-3.0
1
// Copyright (c) 2018 Token Browser, Inc // // 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 final class SofaPaymentRequest: SofaWrapper { override var type: SofaType { return .paymentRequest } lazy var body: String = { self.json["body"] as? String ?? "" }() var fiatValueString: String { guard let string = self.json["fiatValueString"] as? String else { return "" } return string } var value: NSDecimalNumber { guard let hexValue = self.json["value"] as? String else { return NSDecimalNumber.zero } return NSDecimalNumber(hexadecimalString: hexValue) } var destinationAddress: String { return json["destinationAddress"] as? String ?? "" } convenience init(valueInWei: NSDecimalNumber) { let request: [String: Any] = [ "value": valueInWei.toHexString, "destinationAddress": Cereal.shared.paymentAddress ] self.init(content: request) } override init(content: String) { guard let sofaContent = SofaWrapper.addFiatStringIfNecessary(to: content, for: SofaType.paymentRequest) else { fatalError("Could not add fiat string if necessary") } super.init(content: sofaContent) } override init(content: [String: Any]) { guard let sofaContent = SofaWrapper.addFiatStringIfNecessary(to: content, for: SofaType.paymentRequest) else { fatalError("Could not add fiat string if necessary") } super.init(content: sofaContent) } }
7ef2963cf6f42da4d7edb41c171d2902
32.46875
173
0.68394
false
false
false
false
zoeyzhong520/InformationTechnology
refs/heads/master
InformationTechnology/InformationTechnology/Classes/GuideViewController.swift
mit
1
// // GuideViewController.swift // InformationTechnology // // Created by qianfeng on 16/11/14. // Copyright © 2016年 zzj. All rights reserved. // import UIKit class GuideViewController: UIViewController { //创建分页控件 var pageCtrl:UIPageControl? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() //创建界面 configView() } //创建界面 func configView() { //添加滚动视图 let scrollView = UIScrollView(frame: self.view.bounds) scrollView.delegate = self scrollView.pagingEnabled = true view.addSubview(scrollView) //循环添加图片 let imgArray = ["IMG_0169_New.jpg","IMG_0172_New.jpg","IMG_0170.jpg"] for i in 0..<imgArray.count { //背景图片 let frame:CGRect = CGRectMake(kScreenWidth*CGFloat(i), 0, kScreenWidth, kScreenHeight) let imageView = UIImageView(frame: frame) imageView.image = UIImage(named: "guideView_bg@2x") scrollView.addSubview(imageView) //图片 let tmpImgView = UIImageView(frame: imageView.bounds) tmpImgView.image = UIImage(named: imgArray[i]) imageView.addSubview(tmpImgView) if i == imgArray.count-1 { imageView.userInteractionEnabled = true //按钮 let btn = UIButton(frame: CGRect(x: 110, y: kScreenHeight-120, width: kScreenWidth-2*110, height: 40)) btn.setTitle("进入应用", forState: .Normal) btn.setTitleColor(UIColor.blackColor(), forState: .Normal) btn.layer.masksToBounds = true btn.layer.cornerRadius = 20 btn.backgroundColor = UIColor.whiteColor() btn.addTarget(self, action: #selector(clickBtn), forControlEvents: .TouchUpInside) imageView.addSubview(btn) } //分页控件 pageCtrl = UIPageControl(frame: CGRect(x: 50, y: kScreenHeight-60, width: kScreenWidth-2*50, height: 30)) pageCtrl?.numberOfPages = imgArray.count pageCtrl?.currentPageIndicatorTintColor = UIColor.whiteColor() pageCtrl?.pageIndicatorTintColor = UIColor.lightGrayColor() view.addSubview(pageCtrl!) } scrollView.contentSize = CGSizeMake(kScreenWidth*CGFloat(imgArray.count), 0) } func clickBtn() { self.view.window?.rootViewController = CreateTabBarController() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } //MARK: UIScrollView代理方法 extension GuideViewController:UIScrollViewDelegate { func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = scrollView.contentOffset.x/scrollView.bounds.size.width pageCtrl?.currentPage = Int(index) } }
50b43de711fa5aab8a93d5d2ed0a693a
28.016949
118
0.611565
false
false
false
false
troystribling/BlueCap
refs/heads/master
BlueCapKit/Injectables.swift
mit
1
// // Injectables.swift // BlueCapKit // // Created by Troy Stribling on 4/20/16. // Copyright © 2016 Troy Stribling. All rights reserved. // import Foundation import CoreBluetooth // MARK: - ManagerState - public enum ManagerState: CustomStringConvertible { case unauthorized, unknown, unsupported, resetting, poweredOff, poweredOn public var description: String { switch self { case .unauthorized: return "unauthorized" case .unknown: return "unknown" case .unsupported: return "unsupported" case .resetting: return "resetting" case .poweredOff: return "poweredOff" case .poweredOn: return "poweredOn" } } } // MARK: - CBCentralManagerInjectable - protocol CBCentralManagerInjectable: class { var managerState : ManagerState { get } var delegate: CBCentralManagerDelegate? { get set } func scanForPeripherals(withServices serviceUUIDs: [CBUUID]?, options: [String : Any]?) func stopScan() func connect(_ peripheral: CBPeripheralInjectable, options: [String : Any]?) func cancelPeripheralConnection(_ peripheral: CBPeripheralInjectable) func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> [CBPeripheralInjectable] func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> [CBPeripheralInjectable] } extension CBCentralManager : CBCentralManagerInjectable { var managerState: ManagerState { switch state { case .unauthorized: return .unauthorized case .unknown: return .unknown case .unsupported: return .unsupported case .resetting: return .resetting case .poweredOff: return .poweredOff case .poweredOn: return .poweredOn @unknown default: fatalError() } } func connect(_ peripheral: CBPeripheralInjectable, options: [String : Any]?) { self.connect(peripheral as! CBPeripheral, options: options) } func cancelPeripheralConnection(_ peripheral: CBPeripheralInjectable) { self.cancelPeripheralConnection(peripheral as! CBPeripheral) } func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> [CBPeripheralInjectable] { let peripherals = self.retrieveConnectedPeripherals(withServices: serviceUUIDs) as [CBPeripheral] return peripherals.map { $0 as CBPeripheralInjectable } } func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> [CBPeripheralInjectable] { let peripherals = self.retrievePeripherals(withIdentifiers: identifiers) as [CBPeripheral] return peripherals.map { $0 as CBPeripheralInjectable } } } // MARK: - CBPeripheralInjectable - protocol CBPeripheralInjectable: class { var name: String? { get } var state: CBPeripheralState { get } var identifier: UUID { get } var delegate: CBPeripheralDelegate? { get set } func readRSSI() func discoverServices(_ services: [CBUUID]?) func discoverCharacteristics(_ characteristics: [CBUUID]?, forService service: CBServiceInjectable) func setNotifyValue(_ enabled:Bool, forCharacteristic characteristic: CBCharacteristicInjectable) func readValueForCharacteristic(_ characteristic: CBCharacteristicInjectable) func writeValue(_ data:Data, forCharacteristic characteristic: CBCharacteristicInjectable, type: CBCharacteristicWriteType) func getServices() -> [CBServiceInjectable]? } extension CBPeripheral: CBPeripheralInjectable { func discoverCharacteristics(_ characteristics:[CBUUID]?, forService service: CBServiceInjectable) { self.discoverCharacteristics(characteristics, for: service as! CBService) } func setNotifyValue(_ enabled: Bool, forCharacteristic characteristic: CBCharacteristicInjectable) { self.setNotifyValue(enabled, for: characteristic as! CBCharacteristic) } func readValueForCharacteristic(_ characteristic: CBCharacteristicInjectable) { self.readValue(for: characteristic as! CBCharacteristic) } func writeValue(_ data: Data, forCharacteristic characteristic: CBCharacteristicInjectable, type: CBCharacteristicWriteType) { self.writeValue(data, for: characteristic as! CBCharacteristic, type: type) } func getServices() -> [CBServiceInjectable]? { guard let services = services else { return nil } return services.map{ $0 as CBServiceInjectable } } } // MARK: - CBServiceInjectable - protocol CBServiceInjectable: class { var uuid: CBUUID { get } func getCharacteristics() -> [CBCharacteristicInjectable]? } extension CBService : CBServiceInjectable { func getCharacteristics() -> [CBCharacteristicInjectable]? { guard let characteristics = self.characteristics else { return nil } return characteristics.map{ $0 as CBCharacteristicInjectable } } } // MARK: - CBCharacteristicInjectable - public protocol CBCharacteristicInjectable: class { var uuid: CBUUID { get } var value: Data? { get } var properties: CBCharacteristicProperties { get } var isNotifying: Bool { get } } extension CBCharacteristic : CBCharacteristicInjectable {} // MARK: - CBPeripheralManagerInjectable - protocol CBPeripheralManagerInjectable { var delegate: CBPeripheralManagerDelegate? { get set } var isAdvertising: Bool { get } var managerState: ManagerState { get } func startAdvertising(_ advertisementData : [String : Any]?) func stopAdvertising() func add(_ service: CBMutableServiceInjectable) func remove(_ service: CBMutableServiceInjectable) func removeAllServices() func respondToRequest(_ request: CBATTRequestInjectable, withResult result: CBATTError.Code) func updateValue(_ value: Data, forCharacteristic characteristic: CBMutableCharacteristicInjectable, onSubscribedCentrals centrals: [CBCentralInjectable]?) -> Bool } extension CBPeripheralManager: CBPeripheralManagerInjectable { var managerState: ManagerState { switch state { case .unauthorized: return .unauthorized case .unknown: return .unknown case .unsupported: return .unsupported case .resetting: return .resetting case .poweredOff: return .poweredOff case .poweredOn: return .poweredOn @unknown default: fatalError() } } func add(_ service: CBMutableServiceInjectable) { self.add(service as! CBMutableService) } func remove(_ service: CBMutableServiceInjectable) { self.remove(service as! CBMutableService) } func respondToRequest(_ request: CBATTRequestInjectable, withResult result: CBATTError.Code) { self.respond(to: request as! CBATTRequest, withResult: result) } func updateValue(_ value: Data, forCharacteristic characteristic: CBMutableCharacteristicInjectable, onSubscribedCentrals centrals: [CBCentralInjectable]?) -> Bool { return self.updateValue(value, for: characteristic as! CBMutableCharacteristic, onSubscribedCentrals: centrals as! [CBCentral]?) } } // MARK: - CBMutableServiceInjectable - protocol CBMutableServiceInjectable: CBServiceInjectable { func setCharacteristics(_ characteristics: [CBCharacteristicInjectable]?) } extension CBMutableService: CBMutableServiceInjectable { func setCharacteristics(_ characteristics: [CBCharacteristicInjectable]?) { self.characteristics = characteristics?.map { $0 as! CBCharacteristic } } } // MARK: - CBMutableCharacteristicInjectable - protocol CBMutableCharacteristicInjectable: CBCharacteristicInjectable { var permissions: CBAttributePermissions { get } } extension CBMutableCharacteristic : CBMutableCharacteristicInjectable {} // MARK: - CBATTRequestInjectable - public protocol CBATTRequestInjectable { var offset: Int { get } var value: Data? { get set } func getCharacteristic() -> CBCharacteristicInjectable } extension CBATTRequest: CBATTRequestInjectable { public func getCharacteristic() -> CBCharacteristicInjectable { return self.characteristic } } // MARK: - CBCentralInjectable - public protocol CBCentralInjectable { var identifier: UUID { get } var maximumUpdateValueLength: Int { get } } extension CBCentral: CBCentralInjectable {}
c34fbe89797f055a191dc8571debdb34
33.909465
169
0.713427
false
false
false
false
ioscreator/ioscreator
refs/heads/master
SwiftUIJSONListTutorial/SwiftUIJSONListTutorial/SceneDelegate.swift
mit
1
// // SceneDelegate.swift // SwiftUIJSONListTutorial // // Created by Arthur Knopper on 18/02/2020. // Copyright © 2020 Arthur Knopper. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
b853845d00745877a8718b2879e0a53e
42.453125
147
0.705861
false
false
false
false
a412657308/kkvapor
refs/heads/master
Sources/App/Models/SQFriend.swift
apache-2.0
2
import Foundation import Vapor struct SQFriend: Model { var exists: Bool = false var id: Node? var username: String let sex: String var headimgurl: String let rcuserid: String let deviceno: String let way: String let account: String let pwd: String var aboutme:String var zannum: Int var photos: String var tags: String var activities: String // var sqrctoken_id: Int init(username: String,sex: String, headimgurl: String, rcuserid: String, deviceno: String, way: String, account: String, pwd: String, aboutme:String, zannum:Int ,photos:String, tags:String, activities: String) { self.id = nil self.username = username self.sex = sex self.headimgurl = headimgurl self.rcuserid = rcuserid self.deviceno = deviceno self.way = way self.account = account self.pwd = pwd self.aboutme = aboutme self.zannum = zannum; self.photos = photos; self.tags = tags; self.activities = activities; // self.sqrctoken_id = sqrctoken_id } // Node Initializable init(node: Node, in context: Context) throws { id = try node.extract("id") username = try node.extract("username") sex = try node.extract("sex") headimgurl = try node.extract("headimgurl") rcuserid = try node.extract("rcuserid") deviceno = try node.extract("deviceno") way = try node.extract("way") account = try node.extract("account") pwd = try node.extract("pwd") aboutme = try node.extract("aboutme") zannum = try node.extract("zannum") photos = try node.extract("photos") tags = try node.extract("tags") activities = try node.extract("activities") // sqrctoken_id = try node.extract("id") } // Node Represen table func makeNode(context: Context) throws -> Node { return try Node(node: ["id": id, "username": username, "sex": sex, "headimgurl": headimgurl, "rcuserid": rcuserid, "deviceno": deviceno, "way": way, "account": account, "pwd": pwd, "aboutme":aboutme, "zannum":zannum, "photos":photos, "tags":tags, "activities":activities, // "sqrctoken_id":sqrctoken_id ]) } // Preparation static func prepare(_ database: Database) throws { try database.create("SQFriends") { friends in friends.id() friends.string("username") friends.string("sex") friends.string("headimgurl") friends.string("rcuserid") friends.string("deviceno") friends.string("way") friends.string("account") friends.string("pwd") friends.string("aboutme") friends.int("zannum") friends.string("photos") friends.string("tags") friends.string("activities") // friends.int("sqrctoken_id") } } static func revert(_ database: Database) throws { try database.delete("SQFriends") } } import Auth extension SQFriend: Auth.User { static func authenticate(credentials: Credentials) throws -> Auth.User { let user: SQFriend? switch credentials { case let id as Identifier: user = try SQFriend.find(id.id) case let accessToken as AccessToken: user = try SQFriend.query().filter("access_token", accessToken.string).first() case let apiKey as APIKey: user = try SQFriend.query().filter("email", apiKey.id).filter("password", apiKey.secret).first() default: throw Abort.custom(status: .badRequest, message: "Invalid credentials.") } guard let u = user else { throw Abort.custom(status: .badRequest, message: "User not found") } return u } static func register(credentials: Credentials) throws -> Auth.User { throw Abort.custom(status: .badRequest, message: "Register not supported.") } } import HTTP extension Request { func user() throws -> SQFriend { guard let user = try auth.user() as? SQFriend else { throw Abort.custom(status: .badRequest, message: "Invalid user type.") } return user } }
98134a4f822983559d0fec1c001b910b
30.741935
215
0.525813
false
false
false
false
zimcherDev/ios
refs/heads/master
Zimcher/UIKit Objects/UI Helpers/Cell/TextPromptCell.swift
apache-2.0
1
import UIKit class TextPromptEntryFieldCell: BaseEntryCell { let promptTextLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func setup() { contentView.addSubview(promptTextLabel) setupPrompt(promptTextLabel) promptTextLabel.translatesAutoresizingMaskIntoConstraints = false promptTextLabel.leadingAnchor.constraintEqualToAnchor(contentView.leadingAnchor, constant: UI.ENTRY_FIELD.CELL_INDENT).active = true promptTextLabel.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true promptTextLabel.bottomAnchor.constraintEqualToAnchor(separator.topAnchor).active = true //default promptTextLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) promptTextLabel.setContentHuggingPriority(1000, forAxis: .Horizontal) } private func setupPrompt(prompt: UILabel) { prompt.textColor = COLORSCHEME.ENTRY_FIELD.PROMPT_TEXT_FG prompt.font = FONTS.SF_SEMIBOLD.fontWithSize(18) } }
3828c06c23ffc070660b35e74446b3a0
33.289474
140
0.704528
false
false
false
false
PiXeL16/BudgetShare
refs/heads/master
BudgetShareTests/Services/Mocks/Firebase/MockFirebaseBudgetService.swift
mit
1
// // Created by Chris Jimenez on 8/26/18. // Copyright (c) 2018 Chris Jimenez. All rights reserved. // import Foundation import FirebaseDatabase import RxSwift @testable import BudgetShare internal class MockFirebaseBudgetService: FirebaseBudgetService { var invokedObserveBudget = false var invokedObserveBudgetCount = 0 var invokedObserveBudgetParameters: (budgetId: String, Void)? var invokedObserveBudgetParametersList = [(budgetId: String, Void)]() var stubbedObserveBudgetResult: Observable<DataSnapshot>! func observeBudget(budgetId: String) -> Observable<DataSnapshot> { invokedObserveBudget = true invokedObserveBudgetCount += 1 invokedObserveBudgetParameters = (budgetId, ()) invokedObserveBudgetParametersList.append((budgetId, ())) return stubbedObserveBudgetResult } var invokedCreateBudget = false var invokedCreateBudgetCount = 0 var invokedCreateBudgetParameters: (data: BudgetServiceCreateData, Void)? var invokedCreateBudgetParametersList = [(data: BudgetServiceCreateData, Void)]() var stubbedCreateBudgetCallbackResult: BudgetServiceResult? func createBudget(data: BudgetServiceCreateData, callback: ((BudgetServiceResult) -> Void)?) { invokedCreateBudget = true invokedCreateBudgetCount += 1 invokedCreateBudgetParameters = (data, ()) invokedCreateBudgetParametersList.append((data, ())) if let result = stubbedCreateBudgetCallbackResult { callback?(result) } } var invokedFetchBudgetInfo = false var invokedFetchBudgetInfoCount = 0 var invokedFetchBudgetInfoParameters: (budgetId: String, Void)? var invokedFetchBudgetInfoParametersList = [(budgetId: String, Void)]() var stubbedFetchBudgetInfoCallbackResult: BudgetServiceResult? func fetchBudgetInfo(budgetId: String, callback: ((BudgetServiceResult) -> Void)?) { invokedFetchBudgetInfo = true invokedFetchBudgetInfoCount += 1 invokedFetchBudgetInfoParameters = (budgetId, ()) invokedFetchBudgetInfoParametersList.append((budgetId, ())) if let result = stubbedFetchBudgetInfoCallbackResult { callback?(result) } } }
4e97d14fc2d1b6b7729e69797dd05b00
37.672414
98
0.728934
false
false
false
false
wasm3/wasm3
refs/heads/main
platforms/ios/wasm3/ViewController.swift
mit
1
// // ViewController.swift // wasm3 // // Created by Volodymyr Shymanskyy on 1/10/20. // Copyright © 2020 wasm3. All rights reserved. // import UIKit var gLog: UITextView! class ViewController: UIViewController { // MARK: Properties @IBOutlet var log: UITextView! override func viewDidLoad() { super.viewDidLoad() gLog = log redirect_output({ if let ptr = $0 { let data = Data(bytes: ptr, count: Int($1)) if let str = String(data: data, encoding: String.Encoding.utf8) { DispatchQueue.main.async { gLog.text += str } } } }) run_app() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
f76acd06d6788c608d99d4f90a48610c
19.390244
81
0.528708
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Neocom/Neocom/Utility/UserActivities/NSUserActivity+Extensions.swift
lgpl-2.1
2
// // NSUserActivity+Extensions.swift // Neocom // // Created by Artem Shimanski on 4/23/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import UIKit import CoreData enum NSUserActivityType { static let fitting = "\(bundleID).fitting.activity" } extension NSUserActivity { static let isMainWindowKey = "isMainWindow" static let loadoutKey = "loadout" } // // // extension NSUserActivity { convenience init(fitting: FittingProject) throws { self.init(activityType: NSUserActivityType.fitting) // let data = try JSONEncoder().encode(fitting) // addUserInfoEntries(from: ["fitting": data]) } func fitting(from managedObjectContext: NSManagedObjectContext) throws -> FittingProject { let project = FittingProject(fileURL: FittingProject.documentsDirectoryURL.appendingPathComponent(UUID().uuidString).appendingPathExtension(Config.current.loadoutPathExtension), managedObjectContext: AppDelegate.sharedDelegate.storage.persistentContainer.viewContext) project.restoreUserActivityState(self) guard project.gang != nil || project.structure != nil else {throw RuntimeError.invalidLoadoutFormat} return project // guard let data = userInfo?["fitting"] as? Data else {throw RuntimeError.invalidActivityType} // let decoder = JSONDecoder() // decoder.userInfo[FittingProject.managedObjectContextKey] = managedObjectContext // return try decoder.decode(FittingProject.self, from: data) } }
c887f1a5d449fedaa6dd16c01a3b55ba
36.926829
185
0.716399
false
false
false
false
zdima/ZDComboBox
refs/heads/master
ZDComboBox/ZDPopupWindowManager.swift
mit
1
// // ZDPopupWindowManager.swift // MyFina // // Created by Dmitriy Zakharkin on 3/7/15. // Copyright (c) 2015 ZDima. All rights reserved. // import Cocoa extension NSView { func flippedRect( rect: NSRect ) -> NSRect { var rectRet: NSRect = rect if self.superview != nil { if !self.superview!.flipped { rectRet.origin.y = self.superview!.frame.size.height - rectRet.origin.y - rectRet.size.height } } return rectRet } } class ZDPopupWindowManager: NSObject { private var control: NSControl? = nil private var popupWindow: ZDPopupWindow? = nil private var dropDownButtonObject: NSButton? private var originalHeight: CGFloat = 0 static var popupManager = ZDPopupWindowManager() override init() { super.init() var contentRect: NSRect = NSZeroRect contentRect.size.height = 200 popupWindow = ZDPopupWindow(contentRect: contentRect, styleMask: NSBorderlessWindowMask, backing: NSBackingStoreType.Buffered, defer: false, screen: nil) popupWindow!.movableByWindowBackground = false popupWindow!.excludedFromWindowsMenu = true popupWindow!.hasShadow = true popupWindow!.titleVisibility = NSWindowTitleVisibility.Hidden } func showPopupForControl(userControl: NSControl?, withContent content: NSView?) -> Bool { if control == userControl { return true } if control != nil { hidePopup() } control = userControl if let ctrl = control as? ZDComboBox, let pWindow = popupWindow, let window = ctrl.window { originalHeight = content!.bounds.size.height pWindow.contentView = content! layoutPopupWindow() window.addChildWindow(pWindow, ordered: NSWindowOrderingMode.Above) NSNotificationCenter.defaultCenter().addObserver(self, selector: "windowDidResize:", name: NSApplicationDidResignActiveNotification, object: ctrl.window ) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidResignActive:", name: NSWindowDidResizeNotification, object: NSApplication.sharedApplication() ) ctrl.buttonState = NSOnState return true } return false } func hidePopup() { if let ctrl = control as? ZDComboBox, let window = ctrl.window, let pWindow = popupWindow { if popupWindow!.visible { popupWindow!.orderOut(self) ctrl.window!.removeChildWindow(popupWindow!) NSNotificationCenter.defaultCenter().removeObserver(self) } ctrl.buttonState = NSOffState } control = nil } func applicationDidResignActive(node: NSNotification?) { hidePopup() } func layoutPopupWindow() { if let ctrl = control, let pWindow = popupWindow { var screenFrame: NSRect if let screen = pWindow.screen { screenFrame = screen.visibleFrame } else if let screen = NSScreen.mainScreen() { screenFrame = screen.visibleFrame } else { NSException(name: "runtime", reason: "no screen", userInfo: nil) return } let contentRect: NSRect = ctrl.bounds let controlRect: NSRect = ctrl.flippedRect(ctrl.frame) var frame = NSRect( x: controlRect.origin.x, y: controlRect.origin.y + controlRect.size.height-2, width: contentRect.size.width, height: originalHeight) var parentView: NSView? = ctrl.superview while parentView != nil { let parentFrame: NSRect = parentView!.flippedRect(parentView!.frame) frame = NSOffsetRect(frame, parentFrame.origin.x - parentView!.bounds.origin.x, parentFrame.origin.y - parentView!.bounds.origin.y) parentView = parentView!.superview } frame = adjustToScreen(frame,screenFrame,ctrl) pWindow.setFrame(frame, display: false) } } func adjustToScreen(srcFrame: NSRect, _ screenFrame: NSRect, _ ctrl: NSControl) -> NSRect { let screenRect = ctrl.window!.frame let contentRect: NSRect = ctrl.bounds var frame = srcFrame frame.origin.x = frame.origin.x + screenRect.origin.x frame.origin.y = screenRect.origin.y+screenRect.size.height-frame.origin.y - originalHeight let x2: CGFloat = frame.origin.x + frame.size.width if frame.origin.x < screenFrame.origin.x { frame.origin.x = screenFrame.origin.x } if frame.origin.y < screenFrame.origin.y { frame.origin.y = frame.origin.y + frame.size.height + contentRect.size.height } if x2 > screenFrame.size.width { frame.origin.x -= (x2 - screenFrame.size.width) } return frame } func windowDidResignKey(note: NSNotification?) { hidePopup() } func windowDidResize(note: NSNotification?) { layoutPopupWindow() } } @objc(ZDPopupWindow) class ZDPopupWindow: NSWindow { override var canBecomeKeyWindow: Bool { get { return false } } } @objc protocol ZDPopupContentDelegate { func selectionDidChange( selector: AnyObject?, fromUpDown updown: Bool ); func updateBindingProperty(); func showPopupForControl(control: NSControl?) -> Bool; var combo: ZDComboBox? { get set } } class ZDPopupContent: NSViewController { var delegate: ZDPopupContentDelegate? var rootNodes: [AnyObject]? { didSet { convertUserObjectToItems() } } var items: [ZDComboBoxItem] = [] var filter: String = "" { didSet { if oldValue != filter { invalidateFilter() } } } /// filter items again func invalidateFilter() {} func moveSelectionUp(up: Bool) {} func moveSelectionTo(string: String?, filtered: Bool ) -> NSString? { return nil } func convertUserObjectToItems() { items = [] if let nodes = rootNodes as? [NSObject], let comboBox = delegate!.combo { for child in nodes { if let treeNode = child as? NSTreeNode, let obj = treeNode.representedObject as? NSObject, let item = ZDComboBoxItem.itemWith( obj, hierarchical: comboBox.isHierarchical, displayKey: comboBox.displayKey, childsKey: comboBox.childsKey) { items.append(item) } else { if let item = ZDComboBoxItem.itemWith( child, hierarchical: false, displayKey: comboBox.displayKey, childsKey: comboBox.childsKey) { items.append(item) } } } } } }
0886957e259acfa513e02716be9e3b86
27.382883
97
0.674337
false
false
false
false
OneBusAway/onebusaway-iphone
refs/heads/develop
Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/WidthSelectionTableViewCell.swift
apache-2.0
3
// // WidthSelectionTableViewCell.swift // SwiftEntryKit_Example // // Created by Daniel Huri on 4/25/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit class WidthSelectionTableViewCell: SelectionTableViewCell { override func configure(attributesWrapper: EntryAttributeWrapper) { super.configure(attributesWrapper: attributesWrapper) titleValue = "Width" descriptionValue = "Describes the entry's width inside the screen. It can be stretched to the margins, it can have an offset, can a constant or have a ratio to the screen" insertSegments(by: ["Stretch", "20pts Offset", "90% Screen"]) selectSegment() } private func selectSegment() { switch attributesWrapper.attributes.positionConstraints.size.width { case .offset(value: let value): if value == 0 { segmentedControl.selectedSegmentIndex = 0 } else { segmentedControl.selectedSegmentIndex = 1 } case .ratio(value: _): segmentedControl.selectedSegmentIndex = 2 default: break } } @objc override func segmentChanged() { switch segmentedControl.selectedSegmentIndex { case 0: attributesWrapper.attributes.positionConstraints.size.width = .offset(value: 0) case 1: attributesWrapper.attributes.positionConstraints.size.width = .offset(value: 20) case 2: attributesWrapper.attributes.positionConstraints.size.width = .ratio(value: 0.9) default: break } } }
fa256a432bc79b4192f7183ef2405c09
34.042553
179
0.64238
false
false
false
false
AllisonWangJiaoJiao/KnowledgeAccumulation
refs/heads/master
03-YFPageViewExtensionDemo(IM)/YFPageViewExtensionDemo/YFPageView/YFPageStyle.swift
mit
2
// // YFPageStyle.swift // YFPageViewDemo // // Created by Allison on 2017/4/27. // Copyright © 2017年 Allison. All rights reserved. // import UIKit class YFPageStyle { var titleViewHeight : CGFloat = 44 var normalColor : UIColor = UIColor(r: 0, g: 0, b: 0) var selectColor : UIColor = UIColor(r: 255, g: 127, b: 0) var fontSize : CGFloat = 15 var titleFont : UIFont = UIFont.systemFont(ofSize: 15.0) //是否是滚动的title var isScrollEnable : Bool = false //间距 var itemMargin : CGFloat = 20 var isShowBottomLine : Bool = true var bottomLineColor : UIColor = UIColor.orange var bottomLineHeight : CGFloat = 2 //YFPageCollectionView ///title的高度 var titleHeight : CGFloat = 44 }
2a5ab76696cadaa1964a5a8f7d998893
19.153846
61
0.618321
false
false
false
false