repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
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
wordpress-mobile/AztecEditor-iOS
refs/heads/develop
Aztec/Classes/Formatters/Base/StandardAttributeFormatter.swift
gpl-2.0
2
import Foundation import UIKit /// Formatter to apply simple value (NSNumber, UIColor) attributes to an attributed string. class StandardAttributeFormatter: AttributeFormatter { var placeholderAttributes: [NSAttributedString.Key: Any]? { return nil } let attributeKey: NSAttributedString.Key var attributeValue: Any let htmlRepresentationKey: NSAttributedString.Key let needsToMatchValue: Bool // MARK: - Init init(attributeKey: NSAttributedString.Key, attributeValue: Any, htmlRepresentationKey: NSAttributedString.Key, needsToMatchValue: Bool = false) { self.attributeKey = attributeKey self.attributeValue = attributeValue self.htmlRepresentationKey = htmlRepresentationKey self.needsToMatchValue = needsToMatchValue } func applicationRange(for range: NSRange, in text: NSAttributedString) -> NSRange { return range } func apply(to attributes: [NSAttributedString.Key: Any], andStore representation: HTMLRepresentation?) -> [NSAttributedString.Key: Any] { var resultingAttributes = attributes resultingAttributes[attributeKey] = attributeValue resultingAttributes[htmlRepresentationKey] = representation return resultingAttributes } func remove(from attributes: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] { var resultingAttributes = attributes resultingAttributes.removeValue(forKey: attributeKey) resultingAttributes.removeValue(forKey: htmlRepresentationKey) return resultingAttributes } func present(in attributes: [NSAttributedString.Key: Any]) -> Bool { let enabled = attributes[attributeKey] != nil if (!needsToMatchValue) { return enabled } if let value = attributes[attributeKey] as? NSObject, let attributeValue = attributeValue as? NSObject { return value.isEqual(attributeValue) } return false } }
ee91ef19c0c05f27123bca317b919413
31.983607
149
0.707753
false
false
false
false
festrs/DotaComp
refs/heads/master
DotaComp/LiveGamesTableViewCell.swift
mit
1
// // EventSoonTableViewCell.swift // DotaComp // // Created by Felipe Dias Pereira on 2016-10-27. // Copyright © 2016 Felipe Dias Pereira. All rights reserved. // import UIKit class LiveGamesTableViewCell: UITableViewCell { @IBOutlet weak var team1Label: UILabel! @IBOutlet weak var team2Label: UILabel! @IBOutlet weak var bestOfLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var backView: UIView! override func awakeFromNib() { super.awakeFromNib() backView.layer.cornerRadius = 8 backView.layer.masksToBounds = true } func setUpCell(liveGame: Game) { let direTeam = liveGame.direTeam?.teamName.map { $0 } ?? "" let radiantTeam = liveGame.radiantTeam?.teamName.map { $0 } ?? "" team1Label.text = radiantTeam team2Label.text = direTeam timeLabel.text = "LIVE" bestOfLabel.text = getSeriesType(seriesType: liveGame.seriesType!) } func getSeriesType(seriesType: Int) -> String { switch seriesType { case 0: return "Best of 1" case 1: return "Best of 3" case 2: return "Best of 5" default: return "" } } }
1fa2ab45495accbf876a62525a293aed
25.122449
74
0.603906
false
false
false
false
adamahrens/noisily
refs/heads/master
Noisily/Noisily/ViewControllers/NoiseLayeringViewController.swift
mit
1
// // NoiseLayeringViewController.swift // Noisily // // Created by Adam Ahrens on 3/19/15. // Copyright (c) 2015 Appsbyahrens. All rights reserved. // import UIKit class NoiseLayeringViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var multiSectorControl: SAMultisectorControl! private let dataSource = NoiseDataSource() private let selectedPaths = Set<NSIndexPath>() // Currently displayed sectors private var currentSectors = Array<Dictionary<String,SAMultisectorSector>>() override func viewDidLoad() { super.viewDidLoad() // Blur the background let blurEffect = UIBlurEffect(style: .Light) let blurView = UIVisualEffectView(effect: blurEffect) blurView.translatesAutoresizingMaskIntoConstraints = false self.view.insertSubview(blurView, atIndex: 0) // Have equal width and height let equalHeight = NSLayoutConstraint(item: blurView, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 1.0, constant: 0.0) let equalWidth = NSLayoutConstraint(item: blurView, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 1.0, constant: 0.0) self.view.addConstraints([equalHeight, equalWidth]) // Want white checkmarks for UItableViewCells UITableViewCell.appearance().tintColor = UIColor.whiteColor() } @IBAction func dismiss(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { self.multiSectorControl.setNeedsDisplay() coordinator.animateAlongsideTransition({ (coordinator) -> Void in self.multiSectorControl.layer.layoutIfNeeded() }, completion: nil) } //MARK: UITableView func numberOfSectionsInTableView(tableView: UITableView) -> Int { return dataSource.numberOfSections() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.numberOfNoises() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("NoiseCell", forIndexPath: indexPath) cell.textLabel!.text = dataSource.noiseAtIndexPath(indexPath).name cell.textLabel!.textColor = UIColor.whiteColor() if selectedPaths.contains(indexPath) { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if selectedPaths.contains(indexPath) { let noiseName = dataSource.noiseAtIndexPath(indexPath).name selectedPaths.remove(indexPath) let found = currentSectors.filter { $0.keys.first! == noiseName } if let dictionary = found.first { let sectorToRemove = dictionary.values.first! multiSectorControl.removeSector(sectorToRemove) currentSectors = currentSectors.filter{ $0.keys.first! != noiseName } } } else { // Add a sector selectedPaths.add(indexPath) let color = selectedPaths.size() % 2 == 0 ? UIColor.whiteColor() : UIColor.brightPink() let sector = SAMultisectorSector(color: color, minValue: 1.0, maxValue: 20.0) let noiseName = dataSource.noiseAtIndexPath(indexPath).name sector.tag = selectedPaths.size() multiSectorControl.addSector(sector) multiSectorControl.setNeedsDisplay() currentSectors.append([noiseName: sector]) } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } }
c1ce876096f1ffd952a00a0eb30ad277
40.958763
170
0.674447
false
false
false
false
Holmusk/HMRequestFramework-iOS
refs/heads/master
HMRequestFramework-FullDemo/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // HMRequestFramework-FullDemo // // Created by Hai Pham on 17/1/18. // Copyright © 2018 Holmusk. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let provider = Singleton.instance let topVC = (window?.rootViewController as? NavigationVC)! let navigator = NavigationService(topVC) let vm = NavigationViewModel(provider, navigator) topVC.viewModel = vm return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive // state. This can occur for certain types of temporary interruptions // (such as an incoming phone call or SMS message) or when the user // quits the application and it begins the transition to the background // state. // Use this method to pause ongoing tasks, disable timers, and invalidate // graphics rendering callbacks. Games should use this method to pause // the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate // timers, and store enough application state information to restore // your application to its current state in case it is terminated later. // // If your application supports background execution, this method is // called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active // state; here you can undo many of the changes made on entering the // background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the // application was inactive. If the application was previously in the // background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if // appropriate. See also applicationDidEnterBackground:. // // Saves changes in the application's managed object context before the // application terminates. } }
977cfea0f0e7b8a550c614a92d5afd8e
40.19403
114
0.689493
false
false
false
false
tgu/HAP
refs/heads/master
Sources/HAP/Accessories/ContactSensor.swift
mit
1
extension Accessory { open class ContactSensor: Accessory { public let contactSensor = Service.ContactSensor() public init(info: Service.Info, additionalServices: [Service] = []) { super.init(info: info, type: .sensor, services: [contactSensor] + additionalServices) } } } public enum ContactSensorState: Int, CharacteristicValueType { case detected = 0 case notDetected = 1 } extension Service { open class ContactSensor: Service { public let contactSensorState = GenericCharacteristic<ContactSensorState>( type: .contactSensorState, value: .notDetected, permissions: [.read, .events]) public init() { super.init(type: .contactSensor, characteristics: [contactSensorState]) } } }
b400315b0cc3da9fe4415ecc9fd5bac6
29.259259
97
0.647491
false
false
false
false
WLChopSticks/weiboCopy
refs/heads/master
weiboCopy/weiboCopy/Classes/Module/oAuth/CHSLogInViewController.swift
mit
2
// // CHSLogInViewController.swift // weiboCopy // // Created by 王 on 15/12/14. // Copyright © 2015年 王. All rights reserved. // import UIKit import AFNetworking class CHSLogInViewController: UIViewController, UIWebViewDelegate { let webView = UIWebView() override func viewDidLoad() { super.viewDidLoad() //change the view to the webView to show the oAhtu information view = webView //add a reurn button navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "returnToTheMainView") //add an autofill button navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填写", style: .Plain, target: self, action: "autoFillButton") //webView delegate webView.delegate = self //load the autho view loadAuthoView() } private func loadAuthoView() { let url = NSURL(string: "https://api.weibo.com/oauth2/authorize" + "?client_id=" + "235072683" + "&redirect_uri=" + callBackURL) let urlRequest = NSURLRequest(URL: url!) webView.loadRequest(urlRequest) } //return and autofill button method @objc private func autoFillButton() { let autofill = "document.getElementById('userId').value = '18602602808' ,document.getElementById('passwd').value = '1357924680'" webView.stringByEvaluatingJavaScriptFromString(autofill) } @objc private func returnToTheMainView() { dismissViewControllerAnimated(true, completion: nil) } //realize delegate method func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { // print(request.URL?.absoluteString) //shield some unuseful web, eg.regist button and change account choice guard let urlString = request.URL?.absoluteString else { return false } if urlString.hasPrefix("http://weibo.cn/dpool/ttt/h5/reg.php") { return false } if urlString.hasPrefix("http://passport.sina.cn/sso/crossdomain") { return false } if urlString.hasPrefix("https://api.weibo.com/oauth2/") { return true } if urlString.hasPrefix("https://m.baidu.com/") { return false } //http://www.weibo.com/yes603020460?code=972944fad66aee898b8bfc296355e804&is_all=1 //get the code from the call back url let query = request.URL?.query if let q = query { let pre = "code=" let code = q.substringFromIndex(pre.endIndex) CHSUserAccountViewModel().getAccessTocken(code, finish: { (userLogIn) -> () in if userLogIn { print("success") self.returnToTheMainView() }else { print("fail to load") } }) } return true } }
82236e91238eb9442662f0b4d67888ae
28.87619
137
0.589735
false
false
false
false
shlyren/ONE-Swift
refs/heads/master
ONE_Swift/Classes/Reading-阅读/Model/JENReadCarouselItem.swift
mit
1
// // JENReadCarouselItem.swift // ONE_Swift // // Created by 任玉祥 on 16/5/2. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit // MARK: - 轮播列表模型 class JENReadCarouselListItem: NSObject { /// id var carousel_id: String? /// 标题 var title: String? /// 图片 var cover: String? /// 背景颜色 var bgcolor: String? /// 底部文字 var bottom_text: String? //var pv_url: String? } // MARK: - 轮播主题模型 class JENReadCarouselItem: NSObject { /// item id var item_id: String? /// 标题 var title: String? /// 内容 var introduction: String? /// 作者 var author: String? /// var number = "" /// 类型 var type = 0 var readType: JENReadType { get { var readType = JENReadType.Unknow switch type { case 1: readType = .Essay case 2: readType = .Serial case 3: readType = .Question default: readType = .Unknow } return readType } } }
2ff3dd9d2bb32c922749986892d795bb
18.637931
47
0.47891
false
false
false
false
superman-coder/pakr
refs/heads/master
pakr/pakr/Model/GoogleServices/GMPlace.swift
apache-2.0
1
// // GMPlace.swift // pakr // // Created by Tien on 4/18/16. // Copyright © 2016 Pakr. All rights reserved. // import UIKit class GMPlace: NSObject { let geometry:Coordinate! let name:String! let address:String! init(json:NSDictionary) { let geometryJson = json["geometry"] as! NSDictionary let location = geometryJson["location"] as! NSDictionary let lat = location["lat"] as! Double let lng = location["lng"] as! Double geometry = Coordinate(latitude: lat, longitude: lng) name = json["name"] as! String address = json["formatted_address"] as! String } }
10a6a29d287a16a2fead0794eb56652d
24.153846
64
0.616208
false
false
false
false
MenloHacks/ios-app
refs/heads/master
Menlo Hacks/Pods/Parchment/Parchment/Structs/PagingItems.swift
mit
1
import Foundation /// A data structure used to hold an array of `PagingItem`'s, with /// methods for getting the index path for a given `PagingItem` and /// vice versa. public struct PagingItems<T: PagingItem> where T: Hashable & Comparable { /// A sorted array of the currently visible `PagingItem`'s. public let items: [T] let hasItemsBefore: Bool let hasItemsAfter: Bool let itemsCache: Set<T> init(items: [T], hasItemsBefore: Bool = false, hasItemsAfter: Bool = false) { self.items = items self.hasItemsBefore = hasItemsBefore self.hasItemsAfter = hasItemsAfter self.itemsCache = Set(items) } /// The `IndexPath` for a given `PagingItem`. Returns nil if the /// `PagingItem` is not in the `items` array. /// /// - Parameter pagingItem: A `PagingItem` instance /// - Returns: The `IndexPath` for the given `PagingItem` public func indexPath(for pagingItem: T) -> IndexPath? { guard let index = items.index(of: pagingItem) else { return nil } return IndexPath(item: index, section: 0) } /// The `PagingItem` for a given `IndexPath`. This method will crash /// if you pass in an `IndexPath` that is currently not visible in /// the collection view. /// /// - Parameter indexPath: An `IndexPath` that is currently visible /// - Returns: The `PagingItem` for the given `IndexPath` public func pagingItem(for indexPath: IndexPath) -> T { return items[indexPath.item] } /// The direction from a given `PagingItem` to another `PagingItem`. /// If the `PagingItem`'s are equal the direction will be .none. /// /// - Parameter from: The current `PagingItem` /// - Parameter to: The `PagingItem` being scrolled towards /// - Returns: The `PagingDirection` for a given `PagingItem` public func direction(from: T, to: T) -> PagingDirection { if itemsCache.contains(from) == false { return .none } else if to > from { return .forward } else if to < from { return .reverse } return .none } }
3cd2d5095b9f82189c41ef1caa184b7c
33.931034
79
0.671273
false
false
false
false
popwarsweet/StreamingProgressBar
refs/heads/master
Example/StreamingProgressBar/ViewController.swift
mit
1
// // ViewController.swift // StreamingProgressBar // // Created by Kyle Zaragoza on 08/23/2016. // Copyright (c) 2016 Kyle Zaragoza. All rights reserved. // import UIKit import StreamingProgressBar class ViewController: UIViewController { @IBOutlet weak var progressBar: StreamingProgressBar! var playTimer: Timer? var bufferTimer: Timer? override func viewDidLoad() { super.viewDidLoad() playTimer = Timer.scheduledTimer( timeInterval: 1/30, target: self, selector: #selector(incrementPlayTimer), userInfo: nil, repeats: true) bufferTimer = Timer.scheduledTimer( timeInterval: 0.5, target: self, selector: #selector(incrementBufferProgress), userInfo: nil, repeats: true) } func incrementPlayTimer() { let updatedProgress = progressBar.progress + 0.002 if updatedProgress > 1 { progressBar.progress = 0 progressBar.secondaryProgress = 0 } else { progressBar.progress = updatedProgress } } func incrementBufferProgress() { progressBar.secondaryProgress += 0.1 } }
a345cc49a8562c7e650741e14cb12a4e
24.916667
58
0.606913
false
false
false
false
suragch/MongolAppDevelopment-iOS
refs/heads/master
Mongol App Componants/QwertyKeyboard.swift
mit
1
import UIKit class QwertyKeyboard: UIView, KeyboardKeyDelegate { weak var delegate: KeyboardDelegate? // probably the view controller fileprivate let renderer = MongolUnicodeRenderer.sharedInstance fileprivate var punctuationOn = false fileprivate let nirugu = "\u{180a}" fileprivate let fvs1 = "\u{180b}" fileprivate let fvs2 = "\u{180c}" fileprivate let fvs3 = "\u{180d}" // Keyboard Keys // Row 1 fileprivate let keyQ = KeyboardTextKey() fileprivate let keyW = KeyboardTextKey() fileprivate let keyE = KeyboardTextKey() fileprivate let keyR = KeyboardTextKey() fileprivate let keyT = KeyboardTextKey() fileprivate let keyY = KeyboardTextKey() fileprivate let keyU = KeyboardTextKey() fileprivate let keyI = KeyboardTextKey() fileprivate let keyO = KeyboardTextKey() fileprivate let keyP = KeyboardTextKey() // Row 2 fileprivate let keyA = KeyboardTextKey() fileprivate let keyS = KeyboardTextKey() fileprivate let keyD = KeyboardTextKey() fileprivate let keyF = KeyboardTextKey() fileprivate let keyG = KeyboardTextKey() fileprivate let keyH = KeyboardTextKey() fileprivate let keyJ = KeyboardTextKey() fileprivate let keyK = KeyboardTextKey() fileprivate let keyL = KeyboardTextKey() fileprivate let keyNg = KeyboardTextKey() // Row 3 fileprivate let keyFVS = KeyboardFvsKey() fileprivate let keyZ = KeyboardTextKey() fileprivate let keyX = KeyboardTextKey() fileprivate let keyC = KeyboardTextKey() fileprivate let keyV = KeyboardTextKey() fileprivate let keyB = KeyboardTextKey() fileprivate let keyN = KeyboardTextKey() fileprivate let keyM = KeyboardTextKey() fileprivate let keyBackspace = KeyboardImageKey() // Row 4 fileprivate let keyKeyboard = KeyboardChooserKey() fileprivate let keyMVS = KeyboardTextKey() fileprivate let keyComma = KeyboardTextKey() fileprivate let keySpace = KeyboardImageKey() fileprivate let keyQuestion = KeyboardTextKey() fileprivate let keySuffix = KeyboardTextKey() fileprivate let keyReturn = KeyboardImageKey() // MARK:- keyboard initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { addSubviews() initializeNonChangingKeys() setMongolKeyStrings() assignDelegates() //print(renderer.unicodeToGlyphs("ᠠᠨ\u{180E}ᠠ ᠠᠮ\u{180E}ᠠ ᠠᠭ\u{180E}ᠠ")) //print(renderer.unicodeToGlyphs("\u{202F}ᠶᠢ\u{202F}ᠳᠦ\u{202F}ᠦᠨ")) } func addSubviews() { // Row 1 self.addSubview(keyQ) self.addSubview(keyW) self.addSubview(keyE) self.addSubview(keyR) self.addSubview(keyT) self.addSubview(keyY) self.addSubview(keyU) self.addSubview(keyI) self.addSubview(keyO) self.addSubview(keyP) // Row 2 self.addSubview(keyA) self.addSubview(keyS) self.addSubview(keyD) self.addSubview(keyF) self.addSubview(keyG) self.addSubview(keyH) self.addSubview(keyJ) self.addSubview(keyK) self.addSubview(keyL) self.addSubview(keyNg) // Row 3 self.addSubview(keyFVS) self.addSubview(keyZ) self.addSubview(keyX) self.addSubview(keyC) self.addSubview(keyV) self.addSubview(keyB) self.addSubview(keyN) self.addSubview(keyM) self.addSubview(keyBackspace) // Row 4 self.addSubview(keyKeyboard) self.addSubview(keyMVS) self.addSubview(keyComma) self.addSubview(keySpace) self.addSubview(keyQuestion) self.addSubview(keySuffix) self.addSubview(keyReturn) } func initializeNonChangingKeys() { // Row 3 keyFVS.setStrings("", fvs2Top: "", fvs3Top: "", fvs1Bottom: "", fvs2Bottom: "", fvs3Bottom: "") keyBackspace.image = UIImage(named: "backspace_dark") keyBackspace.keyType = KeyboardImageKey.KeyType.backspace keyBackspace.repeatOnLongPress = true // Row 4 keyKeyboard.image = UIImage(named: "keyboard_dark") keyMVS.primaryString = "\u{180E}" // MVS keyMVS.primaryStringDisplayOverride = "  " // na ma ga keyMVS.primaryStringFontSize = 14.0 keyMVS.secondaryString = "\u{200D}" // ZWJ keyMVS.secondaryStringDisplayOverride = "-" // TODO: keyComma.primaryString = "\u{1802}" // mongol comma keyComma.secondaryString = "\u{1803}" // mongol period keySpace.primaryString = " " keySpace.image = UIImage(named: "space_dark") keySpace.repeatOnLongPress = true keyQuestion.primaryString = "?" keyQuestion.secondaryString = "!" keySuffix.primaryString = "\u{202F}" // NNBS keySuffix.primaryStringDisplayOverride = "  " // yi du un keySuffix.primaryStringFontSize = 14.0 keyReturn.image = UIImage(named: "return_dark") } func setMongolKeyStrings() { // Row 1 keyQ.primaryString = "ᠴ" keyQ.secondaryString = "ᡂ" keyW.primaryString = "ᠸ" keyW.secondaryString = "" keyE.primaryString = "ᠡ" keyE.secondaryString = "ᠧ" keyR.primaryString = "ᠷ" keyR.secondaryString = "ᠿ" keyT.primaryString = "ᠲ" keyT.secondaryString = "" keyY.primaryString = "ᠶ" keyY.secondaryString = "" keyU.primaryString = "ᠦ" keyU.primaryStringDisplayOverride = "" keyU.secondaryString = "" keyI.primaryString = "ᠢ" keyI.secondaryString = "" keyO.primaryString = "ᠥ" keyO.secondaryString = "" keyP.primaryString = "ᠫ" keyP.secondaryString = "" // Row 2 keyA.primaryString = "ᠠ" keyS.primaryString = "ᠰ" keyD.primaryString = "ᠳ" keyF.primaryString = "ᠹ" keyG.primaryString = "ᠭ" keyH.primaryString = "ᠬ" keyH.secondaryString = "ᠾ" keyJ.primaryString = "ᠵ" keyJ.secondaryString = "ᡁ" keyK.primaryString = "ᠺ" keyL.primaryString = "ᠯ" keyL.secondaryString = "ᡀ" keyNg.primaryString = "ᠩ" // Row 3 keyZ.primaryString = "ᠽ" keyZ.secondaryString = "ᠼ" keyX.primaryString = "ᠱ" keyC.primaryString = "ᠣ" keyV.primaryString = "ᠤ" keyV.primaryStringDisplayOverride = "" keyB.primaryString = "ᠪ" keyN.primaryString = "ᠨ" keyM.primaryString = "ᠮ" } func setPunctuationKeyStrings() { // Row 1 keyQ.primaryString = "1" keyQ.secondaryString = "᠑" keyW.primaryString = "2" keyW.secondaryString = "᠒" keyE.primaryString = "3" keyE.secondaryString = "᠓" keyR.primaryString = "4" keyR.secondaryString = "᠔" keyT.primaryString = "5" keyT.secondaryString = "᠕" keyY.primaryString = "6" keyY.secondaryString = "᠖" keyU.primaryString = "7" keyU.secondaryString = "᠗" keyI.primaryString = "8" keyI.secondaryString = "᠘" keyO.primaryString = "9" keyO.secondaryString = "᠙" keyP.primaryString = "0" keyP.secondaryString = "᠐" // Row 2 keyA.primaryString = "(" keyS.primaryString = ")" keyD.primaryString = "<" keyF.primaryString = ">" keyG.primaryString = "«" keyH.primaryString = "»" keyH.secondaryString = "" keyJ.primaryString = "⁈" keyJ.secondaryString = "" keyK.primaryString = "⁉" keyL.primaryString = "‼" keyL.secondaryString = "" keyNg.primaryString = "᠄" // Row 3 keyZ.primaryString = "᠁" keyZ.secondaryString = "" keyX.primaryString = "᠅" keyC.primaryString = "·" keyV.primaryString = "." keyB.primaryString = "᠊" keyN.primaryString = "︱" keyM.primaryString = ";" } func assignDelegates() { // Row 1 keyQ.delegate = self keyW.delegate = self keyE.delegate = self keyR.delegate = self keyT.delegate = self keyY.delegate = self keyU.delegate = self keyI.delegate = self keyO.delegate = self keyP.delegate = self // Row 2 keyA.delegate = self keyS.delegate = self keyD.delegate = self keyF.delegate = self keyG.delegate = self keyH.delegate = self keyJ.delegate = self keyK.delegate = self keyL.delegate = self keyNg.delegate = self // Row 3 keyFVS.delegate = self keyZ.delegate = self keyX.delegate = self keyC.delegate = self keyV.delegate = self keyB.delegate = self keyN.delegate = self keyM.delegate = self keyBackspace.delegate = self // Row 4 //keyKeyboard.addTarget(self, action: "keyKeyboardTapped", forControlEvents: UIControlEvents.TouchUpInside) keyKeyboard.delegate = self keyMVS.delegate = self keyComma.delegate = self keySpace.delegate = self keyQuestion.delegate = self keySuffix.delegate = self keyReturn.addTarget(self, action: #selector(keyReturnTapped), for: UIControlEvents.touchUpInside) } override func layoutSubviews() { // TODO: - should add autolayout constraints instead // | Q | W | E | R | T | Y | U | I | O | P | Row 1 // | A | S | D | F | G | H | J | K | L | NG| Row 2 // | fvs | Z | X | C | V | B | N | M | del | Row 3 // | 123 |mvs| , | space | ? |nbs| ret | Row 4 //let suggestionBarWidth: CGFloat = 30 let numberOfRows: CGFloat = 4 let keyUnitsInRow1: CGFloat = 10 let rowHeight = self.bounds.height / numberOfRows let keyUnitWidth = self.bounds.width / keyUnitsInRow1 let wideKeyWidth = 1.5 * keyUnitWidth let spaceKeyWidth = 3 * keyUnitWidth // Row 1 keyQ.frame = CGRect(x: keyUnitWidth*0, y: 0, width: keyUnitWidth, height: rowHeight) keyW.frame = CGRect(x: keyUnitWidth*1, y: 0, width: keyUnitWidth, height: rowHeight) keyE.frame = CGRect(x: keyUnitWidth*2, y: 0, width: keyUnitWidth, height: rowHeight) keyR.frame = CGRect(x: keyUnitWidth*3, y: 0, width: keyUnitWidth, height: rowHeight) keyT.frame = CGRect(x: keyUnitWidth*4, y: 0, width: keyUnitWidth, height: rowHeight) keyY.frame = CGRect(x: keyUnitWidth*5, y: 0, width: keyUnitWidth, height: rowHeight) keyU.frame = CGRect(x: keyUnitWidth*6, y: 0, width: keyUnitWidth, height: rowHeight) keyI.frame = CGRect(x: keyUnitWidth*7, y: 0, width: keyUnitWidth, height: rowHeight) keyO.frame = CGRect(x: keyUnitWidth*8, y: 0, width: keyUnitWidth, height: rowHeight) keyP.frame = CGRect(x: keyUnitWidth*9, y: 0, width: keyUnitWidth, height: rowHeight) // Row 2 keyA.frame = CGRect(x: keyUnitWidth*0, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyS.frame = CGRect(x: keyUnitWidth*1, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyD.frame = CGRect(x: keyUnitWidth*2, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyF.frame = CGRect(x: keyUnitWidth*3, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyG.frame = CGRect(x: keyUnitWidth*4, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyH.frame = CGRect(x: keyUnitWidth*5, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyJ.frame = CGRect(x: keyUnitWidth*6, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyK.frame = CGRect(x: keyUnitWidth*7, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyL.frame = CGRect(x: keyUnitWidth*8, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyNg.frame = CGRect(x: keyUnitWidth*9, y: rowHeight, width: keyUnitWidth, height: rowHeight) // Row 3 keyFVS.frame = CGRect(x: 0, y: rowHeight*2, width: wideKeyWidth, height: rowHeight) keyZ.frame = CGRect(x: wideKeyWidth, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyX.frame = CGRect(x: wideKeyWidth + keyUnitWidth*1, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyC.frame = CGRect(x: wideKeyWidth + keyUnitWidth*2, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyV.frame = CGRect(x: wideKeyWidth + keyUnitWidth*3, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyB.frame = CGRect(x: wideKeyWidth + keyUnitWidth*4, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyN.frame = CGRect(x: wideKeyWidth + keyUnitWidth*5, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyM.frame = CGRect(x: wideKeyWidth + keyUnitWidth*6, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyBackspace.frame = CGRect(x: wideKeyWidth + keyUnitWidth*7, y: rowHeight*2, width: wideKeyWidth, height: rowHeight) // Row 4 keyKeyboard.frame = CGRect(x: 0, y: rowHeight*3, width: wideKeyWidth, height: rowHeight) keyMVS.frame = CGRect(x: wideKeyWidth, y: rowHeight*3, width: keyUnitWidth, height: rowHeight) keyComma.frame = CGRect(x: wideKeyWidth + keyUnitWidth*1, y: rowHeight*3, width: keyUnitWidth, height: rowHeight) keySpace.frame = CGRect(x: wideKeyWidth + keyUnitWidth*2, y: rowHeight*3, width: spaceKeyWidth, height: rowHeight) keyQuestion.frame = CGRect(x: wideKeyWidth + keyUnitWidth*5, y: rowHeight*3, width: keyUnitWidth, height: rowHeight) keySuffix.frame = CGRect(x: wideKeyWidth + keyUnitWidth*6, y: rowHeight*3, width: keyUnitWidth, height: rowHeight) keyReturn.frame = CGRect(x: wideKeyWidth + keyUnitWidth*7, y: rowHeight*3, width: wideKeyWidth, height: rowHeight) } // MARK: - Other func otherAvailableKeyboards(_ displayNames: [String]) { keyKeyboard.menuItems = displayNames } func updateFvsKey(_ previousChar: String?, currentChar: String) { // get the last character (previousChar is not necessarily a single char) var lastChar: UInt32 = 0 if let previous = previousChar { for c in previous.unicodeScalars { lastChar = c.value } } // lookup the strings and update the key if renderer.isMongolian(lastChar) { // Medial or Final // Medial on top var fvs1Top = "" if let search = renderer.medialGlyphForUnicode(currentChar + fvs1) { fvs1Top = search } var fvs2Top = "" if let search = renderer.medialGlyphForUnicode(currentChar + fvs2) { fvs2Top = search } var fvs3Top = "" if let search = renderer.medialGlyphForUnicode(currentChar + fvs3) { fvs3Top = search } // Final on bottom var fvs1Bottom = "" if let search = renderer.finalGlyphForUnicode(currentChar + fvs1) { fvs1Bottom = search } var fvs2Bottom = "" if let search = renderer.finalGlyphForUnicode(currentChar + fvs2) { fvs2Bottom = search } var fvs3Bottom = "" if let search = renderer.finalGlyphForUnicode(currentChar + fvs3) { fvs3Bottom = search } keyFVS.setStrings(fvs1Top, fvs2Top: fvs2Top, fvs3Top: fvs3Top, fvs1Bottom: fvs1Bottom, fvs2Bottom: fvs2Bottom, fvs3Bottom: fvs3Bottom) } else { // Initial or Isolate // Initial on top var fvs1Top = "" if let search = renderer.initialGlyphForUnicode(currentChar + fvs1) { fvs1Top = search } var fvs2Top = "" if let search = renderer.initialGlyphForUnicode(currentChar + fvs2) { fvs2Top = search } var fvs3Top = "" if let search = renderer.initialGlyphForUnicode(currentChar + fvs3) { fvs3Top = search } // Isolate on bottom var fvs1Bottom = "" if let search = renderer.isolateGlyphForUnicode(currentChar + fvs1) { fvs1Bottom = search } var fvs2Bottom = "" if let search = renderer.isolateGlyphForUnicode(currentChar + fvs2) { fvs2Bottom = search } var fvs3Bottom = "" if let search = renderer.isolateGlyphForUnicode(currentChar + fvs3) { fvs3Bottom = search } keyFVS.setStrings(fvs1Top, fvs2Top: fvs2Top, fvs3Top: fvs3Top, fvs1Bottom: fvs1Bottom, fvs2Bottom: fvs2Bottom, fvs3Bottom: fvs3Bottom) } } // MARK: - KeyboardKeyDelegate protocol func keyTextEntered(_ keyText: String) { print("key text: \(keyText)") // pass the input up to the Keyboard delegate let previousChar = self.delegate?.charBeforeCursor() updateFvsKey(previousChar, currentChar: keyText) self.delegate?.keyWasTapped(keyText) } func keyBackspaceTapped() { self.delegate?.keyBackspace() print("key text: backspace") updateFvsKey("", currentChar: "") } func keyReturnTapped() { self.delegate?.keyWasTapped("\n") print("key text: return") updateFvsKey("", currentChar: "") } func keyFvsTapped(_ fvs: String) { print("key text: fvs") self.delegate?.keyWasTapped(fvs) } func keyKeyboardTapped() { print("key text: keyboard") // switch punctuation punctuationOn = !punctuationOn if punctuationOn { setPunctuationKeyStrings() } else { setMongolKeyStrings() } updateFvsKey("", currentChar: "") } // tell the view controller to switch keyboards func keyNewKeyboardChosen(_ keyboardName: String) { delegate?.keyNewKeyboardChosen(keyboardName) updateFvsKey("", currentChar: "") } }
10bcd4768cd6ba101f865cc82e40a22e
35.456979
146
0.590864
false
false
false
false
coderZsq/coderZsq.target.swift
refs/heads/master
StudyNotes/iOS Collection/Business/Business/Bluetooth/BluetoothViewController.swift
mit
1
// // BluetoothViewController.swift // Business // // Created by 朱双泉 on 2018/12/6. // Copyright © 2018 Castie!. All rights reserved. // import UIKit import MultipeerConnectivity let serviceType = "castiel" class BluetoothViewController: UIViewController { @IBOutlet weak var inputTextField: UITextField! @IBOutlet weak var tableView: UITableView! lazy var assistant: MCAdvertiserAssistant = { let assistant = MCAdvertiserAssistant(serviceType: serviceType, discoveryInfo: ["advinfo" : "castiel"], session: session) return assistant }() lazy var session: MCSession = { let displayName = UIDevice.current.name let peer = MCPeerID(displayName: displayName) let session = MCSession(peer: peer) session.delegate = self return session }() lazy var browser: MCBrowserViewController = { let browser = MCBrowserViewController(serviceType: serviceType, session: session) browser.delegate = self return browser }() @IBAction func mcButtonClick(_ sender: UIButton) { present(browser, animated: true, completion: nil) } @IBAction func changeAdv(_ sender: UISwitch) { sender.isOn ? assistant.start() : assistant.stop() } var msgs: [String] = [] override func viewDidLoad() { super.viewDidLoad() title = "Multipeer" NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: OperationQueue.main) { (note) in if let beginFrame = note.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect, let endFrame = note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect { let changeY = endFrame.minY - beginFrame.minY self.view.frame = CGRect(origin: CGPoint(x: 0, y: changeY), size: self.view.bounds.size) } } } } extension BluetoothViewController: MCBrowserViewControllerDelegate { func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) { print(#function, #line) browserViewController.dismiss(animated: true, completion: nil) } func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) { print(#function, #line) browserViewController.dismiss(animated: true, completion: nil) } // func browserViewController(_ browserViewController: MCBrowserViewController, shouldPresentNearbyPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) -> Bool { // return true // } } extension BluetoothViewController: MCSessionDelegate { func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { print(session, peerID, state) switch state { case .notConnected: print("notConnected") case .connecting: print("connecting") case .connected: print("connected") browser.dismiss(animated: true, completion: nil) } } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { print(data, peerID) let receive = "T: " + (String(data: data, encoding: .utf8) ?? "") msgs.append(receive) DispatchQueue.main.async { self.tableView.reloadData() self.assistant.stop() } } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { } } extension BluetoothViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return msgs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) cell.textLabel?.text = msgs[indexPath.row]; return cell } } extension BluetoothViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { let text = textField.text guard session.connectedPeers.count > 0 else { print("error: there is no peers for textSend") return true } guard let data = text?.data(using: String.Encoding.utf8) else { return true } do { try session.send(data, toPeers: session.connectedPeers, with: .reliable) // session.sendResource(at: <#T##URL#>, withName: <#T##String#>, toPeer: <#T##MCPeerID#>, withCompletionHandler: <#T##((Error?) -> Void)?##((Error?) -> Void)?##(Error?) -> Void#>) // session.startStream(withName: <#T##String#>, toPeer: <#T##MCPeerID#>) } catch { print(error) return true } textField.text = nil textField.resignFirstResponder() msgs.append("Me: " + (text ?? "")); DispatchQueue.main.async { self.tableView.reloadData() } // perform(<#T##aSelector: Selector##Selector#>, on: <#T##Thread#>, with: <#T##Any?#>, waitUntilDone: <#T##Bool#>) return true } }
d092ebc95d07ce8bff505ed6269f0cf3
35.346154
190
0.644092
false
false
false
false
glennposadas/gpkit-ios
refs/heads/master
GPKit/GPNotification.swift
mit
1
// // GPNotification.swift // GPKit // // Created by Glenn Posadas on 6/17/17. // Copyright © 2017 Citus Labs. All rights reserved. // import UIKit import UserNotifications public class GPNotification { /** Public class function for presenting a local notification immediately. * @params - message. */ public class func presentLocalNotification(message: String) { let localNotification = UILocalNotification() localNotification.alertBody = message localNotification.soundName = UILocalNotificationDefaultSoundName; UIApplication.shared.presentLocalNotificationNow(localNotification) } /** A public class function for cancelling all scheduled local notifications */ public class func cancelScheduledLocalNotifications() { UIApplication.shared.cancelAllLocalNotifications() } /** A public class function used for scheduling local notification. * @params * - hour: Int (ex. 1 for 1 o'clock) * - minute: Int (ex. 30 for 30 minutes) */ public class func scheduleLocalNotification(hour: Int, minute: Int, notificationMessage: String, category: String? = nil) { // have to use NSCalendar for the components let calendar = NSCalendar(identifier: .gregorian)!; var dateFire = Date() var fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire) // if today's date is passed, use tomorrow if (fireComponents.hour! > hour || (fireComponents.hour == hour && fireComponents.minute! >= minute) ) { dateFire = dateFire.addingTimeInterval(86400) // Use tomorrow's date fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire); } // set up the time fireComponents.hour = hour fireComponents.minute = minute // schedule local notification dateFire = calendar.date(from: fireComponents)! let localNotification = UILocalNotification() localNotification.fireDate = dateFire localNotification.alertBody = notificationMessage localNotification.repeatInterval = NSCalendar.Unit.day localNotification.soundName = UILocalNotificationDefaultSoundName localNotification.category = category UIApplication.shared.scheduleLocalNotification(localNotification) } }
96ddf33d42ff64bf202b07274541cc60
33.337349
127
0.630877
false
false
false
false
bnickel/StackedDrafts
refs/heads/master
StackedDrafts/StackedDrafts/AllDraftsCollectionViewLayout.swift
mit
1
// // AllDraftsCollectionViewLayout.swift // StackedDrafts // // Created by Brian Nickel on 4/26/16. // Copyright © 2016 Stack Exchange. All rights reserved. // import UIKit func * (a: CATransform3D, b: CATransform3D) -> CATransform3D { return CATransform3DConcat(a, b) } struct PannedItem { let indexPath: IndexPath var translation: CGPoint } class AllDraftsCollectionViewLayout : UICollectionViewLayout { private var allAttributes: [UICollectionViewLayoutAttributes] = [] private var contentSize: CGSize = .zero private var changingBounds = false var pannedItem: PannedItem? { didSet { invalidateLayout() } } @NSCopying var lastPannedItemAttributes: UICollectionViewLayoutAttributes? var deletingPannedItem = false override func prepare() { guard let collectionView = collectionView else { return } precondition(collectionView.numberOfSections == 1) let count = collectionView.numberOfItems(inSection: 0) let size = collectionView.frame.size var topCenter = CGPoint(x: size.width / 2, y: 40) let scale = 1 - 12 / size.height let clampedCount = max(2, min(count, 5)) let verticalGap = (size.height - 80) / CGFloat(clampedCount) let angleInDegrees: CGFloat switch clampedCount { case 2: angleInDegrees = 30 case 3: angleInDegrees = 45 default: angleInDegrees = 61 } var allAttributes: [UICollectionViewLayoutAttributes] = [] for i in 0 ..< count { let indexPath = IndexPath(item: i, section: 0) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) let size = i == 0 ? size : UIEdgeInsetsInsetRect(CGRect(origin: .zero, size: size), DraftPresentationController.presentedInsets).size attributes.bounds = CGRect(origin: .zero, size: size) attributes.zIndex = i attributes.transform3D = rotateDown(degrees: angleInDegrees, itemHeight: size.height, scale: scale) attributes.center = topCenter let gapMultiplier: CGFloat if let pannedItem = pannedItem, pannedItem.indexPath.item == i { let delta = pannedItem.translation.x if delta > 0 { attributes.center.x += sqrt(delta) gapMultiplier = 1 } else { attributes.center.x += delta gapMultiplier = 1 - abs(delta) / size.width } lastPannedItemAttributes = attributes } else { gapMultiplier = 1 } allAttributes.append(attributes) topCenter.y += verticalGap * gapMultiplier } self.allAttributes = allAttributes if let lastAttribute = allAttributes.last { contentSize = CGSize(width: size.width, height: lastAttribute.frame.maxY - 40) } } private func rotateDown(degrees angleInDegrees: CGFloat, itemHeight: CGFloat, scale: CGFloat) -> CATransform3D { let angleOfRotation: CGFloat = (-angleInDegrees / 180) * .pi let rotation = CATransform3DMakeRotation(angleOfRotation, 1, 0, 0) let translateDown = CATransform3DMakeTranslation(0, itemHeight / 2, 0) let scale = CATransform3DMakeScale(scale, scale, scale) var perspective = CATransform3DIdentity perspective.m34 = -1/1500 return translateDown * rotation * scale * perspective } override var collectionViewContentSize : CGSize { return contentSize } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return allAttributes.filter({ $0.frame.intersects(rect) }) } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return allAttributes.indices.contains(indexPath.item) ? allAttributes[indexPath.item] : nil } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func prepare(forAnimatedBoundsChange oldBounds: CGRect) { changingBounds = true super.prepare(forAnimatedBoundsChange: oldBounds) } override func finalizeAnimatedBoundsChange() { changingBounds = false super.finalizeAnimatedBoundsChange() } override func initialLayoutAttributesForAppearingItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return allAttributes.indices.contains(indexPath.item) && !changingBounds ? allAttributes[indexPath.item] : nil } override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let lastPannedItemAttributes = lastPannedItemAttributes , deletingPannedItem && lastPannedItemAttributes.indexPath == itemIndexPath, let collectionView = collectionView { lastPannedItemAttributes.center.x = -collectionView.frame.width / 2 return lastPannedItemAttributes } else { return super.finalLayoutAttributesForDisappearingItem(at: itemIndexPath) } } }
ae5b2c959f9679ca80ba1e44d98e74a1
37.404255
181
0.644875
false
false
false
false
jphacks/TK_08
refs/heads/master
iOS/Demo/PushCatchDemo/iBeaconDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // iBeaconDemo // // Created by Go Sato on 2015/11/21. // Copyright © 2015年 go. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var test: UIApplication? var notification = UILocalNotification() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Sound, UIUserNotificationType.Alert], categories: nil)) // アプリに登録されている全ての通知を削除 UIApplication.sharedApplication().cancelAllLocalNotifications() //pushControll(application) return true } func pushControll(){ print(ViewController().isChange) // push設定 // 登録済みのスケジュールをすべてリセット print("push") //application!.cancelAllLocalNotifications() notification.alertAction = "AirMeet" notification.alertBody = "iBeacon範囲に入りました" notification.soundName = UILocalNotificationDefaultSoundName // あとのためにIdを割り振っておく notification.userInfo = ["notifyId": "AirMeet"] UIApplication.sharedApplication().scheduleLocalNotification(notification) } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { print("in") var alert = UIAlertView() alert.title = "Message" alert.message = notification.alertBody alert.addButtonWithTitle(notification.alertAction) alert.show() } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
a22980adb2b6dcd0e73b31c853326d8f
39.447059
285
0.709133
false
false
false
false
idomizrachi/Regen
refs/heads/master
regen/ArgumentsParser.swift
mit
1
// // ArgumentsParser.swift // Regen // // Created by Ido Mizrachi on 7/15/16. // import Foundation protocol CanBeInitializedWithString { init?(_ description: String) } extension Int: CanBeInitializedWithString {} extension String: CanBeInitializedWithString {} class ArgumentsParser { let arguments : [String] let operationType: OperationType init(arguments : [String]) { self.arguments = arguments self.operationType = ArgumentsParser.parseOperationType(arguments: arguments) } private static func parseOperationType(arguments: [String]) -> OperationType { let operationTypeKey = parseOperationTypeKey(arguments) switch operationTypeKey { case .localization: guard let parameters = parseLocalizationParameters(arguments) else { return .usage } return .localization(parameters: parameters) case .images: guard let parameters = parseImagesParameters(arguments) else { return .usage } return .images(parameters: parameters) case .version: return .version case .usage: return .usage } } private static func parseOperationTypeKey(_ arguments: [String]) -> OperationType.Keys { guard let firstArgument = arguments.first else { return .usage } return OperationType.Keys(rawValue: firstArgument) ?? .usage } private static func parseLocalizationParameters(_ arguments: [String]) -> Localization.Parameters? { let parser = LocalizationParametersParser(arguments: arguments) return parser.parse() } private static func parseImagesParameters(_ arguments: [String]) -> Images.Parameters? { let parser = ImagesParametersParser(arguments: arguments) return parser.parse() } // private static func parseAssetsFile(arguments: [String]) -> String? { // let assetsFile: String? = tryParse("--assets-file", from: arguments) // return assetsFile // } private static func isVersionOperation(_ arguments: [String]) -> Bool { guard let firstArgument = arguments.first else { return false } return firstArgument.lowercased() == OperationType.Keys.version.rawValue } }
13ab93d588782f10604db2425fd6f53f
29.881579
104
0.649766
false
false
false
false
johndpope/Cerberus
refs/heads/master
Cerberus/Classes/Extensions/String+MD5.swift
mit
1
import Foundation extension String { func md5() -> String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) var hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.destroy() return String(format: hash as String) } }
df1ad81f2e73950b433b69e5aaab8cc3
27.666667
88
0.63228
false
false
false
false
karstengresch/rw_studies
refs/heads/master
swift_playgrounds/EnumPlayground.playground/Contents.swift
unlicense
1
//: Playground - noun: a place where people can play import UIKit enum MicrosoftCEOs: Int { case BillGates = 1 case SteveBallmer case SatyaNadella init() { self = .SatyaNadella } func description() -> String { switch (self) { case .BillGates: return "Bill Gates" case .SteveBallmer: return "Steve Ballmer" case .SatyaNadella: return "Satya Nadella" } } } let currentCEO = MicrosoftCEOs() println(currentCEO.description()) let oFirstCEO = MicrosoftCEOs(rawValue: 1) if let firstCEO = oFirstCEO { println(firstCEO.description()) } else { println("No such value") }
0bc1b152c5267b28e925567941835e23
17
52
0.666667
false
false
false
false
belkevich/DTModelStorage
refs/heads/master
DTModelStorage/Memory/MemoryStorage.swift
mit
1
// // MemoryStorage.swift // DTModelStorageTests // // Created by Denys Telezhkin on 10.07.15. // Copyright (c) 2015 Denys Telezhkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /// This struct contains error types that can be thrown for various MemoryStorage errors public struct MemoryStorageErrors { /// Errors that can happen when inserting items into memory storage public enum Insertion: ErrorType { case IndexPathTooBig } /// Errors that can happen when replacing item in memory storage public enum Replacement: ErrorType { case ItemNotFound } /// Errors that can happen when removing item from memory storage public enum Removal : ErrorType { case ItemNotFound } } /// This class represents model storage in memory. /// /// `MemoryStorage` stores data models like array of `SectionModel` instances. It has various methods for changing storage contents - add, remove, insert, replace e.t.c. /// - Note: It also notifies it's delegate about underlying changes so that delegate can update interface accordingly /// - SeeAlso: `SectionModel` public class MemoryStorage: BaseStorage, StorageProtocol { /// sections of MemoryStorage public var sections: [Section] = [SectionModel]() /// Retrieve object at index path from `MemoryStorage` /// - Parameter path: NSIndexPath for object /// - Returns: model at indexPath or nil, if item not found public func objectAtIndexPath(path: NSIndexPath) -> Any? { let sectionModel : SectionModel if path.section >= self.sections.count { return nil } else { sectionModel = self.sections[path.section] as! SectionModel if path.item >= sectionModel.numberOfObjects { return nil } } return sectionModel.objects[path.item] } /// Set section header model for MemoryStorage /// - Note: This does not update UI /// - Parameter model: model for section header at index /// - Parameter sectionIndex: index of section for setting header public func setSectionHeaderModel<T>(model: T?, forSectionIndex sectionIndex: Int) { assert(self.supplementaryHeaderKind != nil, "supplementaryHeaderKind property was not set before calling setSectionHeaderModel: forSectionIndex: method") self.sectionAtIndex(sectionIndex).setSupplementaryModel(model, forKind: self.supplementaryHeaderKind!) } /// Set section footer model for MemoryStorage /// - Note: This does not update UI /// - Parameter model: model for section footer at index /// - Parameter sectionIndex: index of section for setting footer public func setSectionFooterModel<T>(model: T?, forSectionIndex sectionIndex: Int) { assert(self.supplementaryFooterKind != nil, "supplementaryFooterKind property was not set before calling setSectionFooterModel: forSectionIndex: method") self.sectionAtIndex(sectionIndex).setSupplementaryModel(model, forKind: self.supplementaryFooterKind!) } /// Set supplementaries for specific kind. Usually it's header or footer kinds. /// - Parameter models: supplementary models for sections /// - Parameter kind: supplementary kind public func setSupplementaries<T>(models : [T], forKind kind: String) { self.startUpdate() if models.count == 0 { for index in 0..<self.sections.count { let section = self.sections[index] as! SectionModel section.setSupplementaryModel(nil, forKind: kind) } return } self.getValidSection(models.count - 1) for index in 0..<models.count { let section = self.sections[index] as! SectionModel section.setSupplementaryModel(models[index], forKind: kind) } self.finishUpdate() } /// Set section header models. /// - Note: `supplementaryHeaderKind` property should be set before calling this method. /// - Parameter models: section header models public func setSectionHeaderModels<T>(models : [T]) { assert(self.supplementaryHeaderKind != nil, "Please set supplementaryHeaderKind property before setting section header models") self.setSupplementaries(models, forKind: self.supplementaryHeaderKind!) } /// Set section footer models. /// - Note: `supplementaryFooterKind` property should be set before calling this method. /// - Parameter models: section footer models public func setSectionFooterModels<T>(models : [T]) { assert(self.supplementaryFooterKind != nil, "Please set supplementaryFooterKind property before setting section header models") self.setSupplementaries(models, forKind: self.supplementaryFooterKind!) } /// Set items for specific section. This will reload UI after updating. /// - Parameter items: items to set for section /// - Parameter forSectionIndex: index of section to update public func setItems<T>(items: [T], forSectionIndex index: Int) { let section = self.sectionAtIndex(index) section.objects.removeAll(keepCapacity: false) for item in items { section.objects.append(item) } self.delegate?.storageNeedsReloading() } /// Add items to section with `toSection` number. /// - Parameter items: items to add /// - Parameter toSection: index of section to add items public func addItems<T>(items: [T], toSection index: Int = 0) { self.startUpdate() let section = self.getValidSection(index) for item in items { let numberOfItems = section.numberOfObjects section.objects.append(item) self.currentUpdate?.insertedRowIndexPaths.append(NSIndexPath(forItem: numberOfItems, inSection: index)) } self.finishUpdate() } /// Add item to section with `toSection` number. /// - Parameter item: item to add /// - Parameter toSection: index of section to add item public func addItem<T>(item: T, toSection index: Int = 0) { self.startUpdate() let section = self.getValidSection(index) let numberOfItems = section.numberOfObjects section.objects.append(item) self.currentUpdate?.insertedRowIndexPaths.append(NSIndexPath(forItem: numberOfItems, inSection: index)) self.finishUpdate() } /// Insert item to indexPath /// - Parameter item: item to insert /// - Parameter toIndexPath: indexPath to insert /// - Throws: if indexPath is too big, will throw MemoryStorageErrors.Insertion.IndexPathTooBig public func insertItem<T>(item: T, toIndexPath indexPath: NSIndexPath) throws { self.startUpdate() let section = self.getValidSection(indexPath.section) guard section.objects.count > indexPath.item else { throw MemoryStorageErrors.Insertion.IndexPathTooBig } section.objects.insert(item, atIndex: indexPath.item) self.currentUpdate?.insertedRowIndexPaths.append(indexPath) self.finishUpdate() } /// Reload item /// - Parameter item: item to reload. public func reloadItem<T:Equatable>(item: T) { self.startUpdate() if let indexPath = self.indexPathForItem(item) { self.currentUpdate?.updatedRowIndexPaths.append(indexPath) } self.finishUpdate() } /// Replace item `itemToReplace` with `replacingItem`. /// - Parameter itemToReplace: item to replace /// - Parameter replacingItem: replacing item /// - Throws: if `itemToReplace` is not found, will throw MemoryStorageErrors.Replacement.ItemNotFound public func replaceItem<T: Equatable, U:Equatable>(itemToReplace: T, replacingItem: U) throws { self.startUpdate() defer { self.finishUpdate() } guard let originalIndexPath = self.indexPathForItem(itemToReplace) else { throw MemoryStorageErrors.Replacement.ItemNotFound } let section = self.getValidSection(originalIndexPath.section) section.objects[originalIndexPath.item] = replacingItem self.currentUpdate?.updatedRowIndexPaths.append(originalIndexPath) } /// Remove item `item`. /// - Parameter item: item to remove /// - Throws: if item is not found, will throw MemoryStorageErrors.Removal.ItemNotFound public func removeItem<T:Equatable>(item: T) throws { self.startUpdate() defer { self.finishUpdate() } guard let indexPath = self.indexPathForItem(item) else { throw MemoryStorageErrors.Removal.ItemNotFound } self.getValidSection(indexPath.section).objects.removeAtIndex(indexPath.item) self.currentUpdate?.deletedRowIndexPaths.append(indexPath) } /// Remove items /// - Parameter items: items to remove /// - Note: Any items that were not found, will be skipped public func removeItems<T:Equatable>(items: [T]) { self.startUpdate() let indexPaths = self.indexPathArrayForItems(items) for item in items { if let indexPath = self.indexPathForItem(item) { self.getValidSection(indexPath.section).objects.removeAtIndex(indexPath.item) } } self.currentUpdate?.deletedRowIndexPaths.appendContentsOf(indexPaths) self.finishUpdate() } /// Remove items at index paths. /// - Parameter indexPaths: indexPaths to remove item from. Any indexPaths that will not be found, will be skipped public func removeItemsAtIndexPaths(indexPaths : [NSIndexPath]) { self.startUpdate() let reverseSortedIndexPaths = self.dynamicType.sortedArrayOfIndexPaths(indexPaths, ascending: false) for indexPath in reverseSortedIndexPaths { if let _ = self.objectAtIndexPath(indexPath) { self.getValidSection(indexPath.section).objects.removeAtIndex(indexPath.item) self.currentUpdate?.deletedRowIndexPaths.append(indexPath) } } self.finishUpdate() } /// Delete sections in indexSet /// - Parameter sections: sections to delete public func deleteSections(sections : NSIndexSet) { self.startUpdate() for var i = sections.lastIndex; i != NSNotFound; i = sections.indexLessThanIndex(i) { self.sections.removeAtIndex(i) } self.currentUpdate?.deletedSectionIndexes.addIndexes(sections) self.finishUpdate() } } // MARK: - Searching in storage extension MemoryStorage { /// Retrieve items in section /// - Parameter section: index of section /// - Returns array of items in section or nil, if section does not exist public func itemsInSection(section: Int) -> [Any]? { if self.sections.count > section { return self.sections[section].objects } return nil } /// Retrieve object at index path from `MemoryStorage` /// - Parameter path: NSIndexPath for object /// - Returns: model at indexPath or nil, if item not found public func itemAtIndexPath(indexPath: NSIndexPath) -> Any? { return self.objectAtIndexPath(indexPath) } /// Find index path of specific item in MemoryStorage /// - Parameter searchableItem: item to find /// - Returns: index path for found item, nil if not found public func indexPathForItem<T: Equatable>(searchableItem : T) -> NSIndexPath? { for sectionIndex in 0..<self.sections.count { let rows = self.sections[sectionIndex].objects for rowIndex in 0..<rows.count { if let item = rows[rowIndex] as? T { if item == searchableItem { return NSIndexPath(forItem: rowIndex, inSection: sectionIndex) } } } } return nil } /// Retrieve section model for specific section. /// - Parameter sectionIndex: index of section /// - Note: if section did not exist prior to calling this, it will be created, and UI updated. public func sectionAtIndex(sectionIndex : Int) -> SectionModel { self.startUpdate() let section = self.getValidSection(sectionIndex) self.finishUpdate() return section } /// Find-or-create section func getValidSection(sectionIndex : Int) -> SectionModel { if sectionIndex < self.sections.count { return self.sections[sectionIndex] as! SectionModel } else { for i in self.sections.count...sectionIndex { self.sections.append(SectionModel()) self.currentUpdate?.insertedSectionIndexes.addIndex(i) } } return self.sections.last as! SectionModel } /// Index path array for items func indexPathArrayForItems<T:Equatable>(items:[T]) -> [NSIndexPath] { var indexPaths = [NSIndexPath]() for index in 0..<items.count { if let indexPath = self.indexPathForItem(items[index]) { indexPaths.append(indexPath) } } return indexPaths } /// Sorted array of index paths - useful for deletion. class func sortedArrayOfIndexPaths(indexPaths: [NSIndexPath], ascending: Bool) -> [NSIndexPath] { let unsorted = NSMutableArray(array: indexPaths) let descriptor = NSSortDescriptor(key: "self", ascending: ascending) return unsorted.sortedArrayUsingDescriptors([descriptor]) as! [NSIndexPath] } } // MARK: - HeaderFooterStorageProtocol extension MemoryStorage :HeaderFooterStorageProtocol { /// Header model for section. /// - Requires: supplementaryHeaderKind to be set prior to calling this method /// - Parameter index: index of section /// - Returns: header model for section, or nil if there are no model public func headerModelForSectionIndex(index: Int) -> Any? { assert(self.supplementaryHeaderKind != nil, "supplementaryHeaderKind property was not set before calling headerModelForSectionIndex: method") return self.supplementaryModelOfKind(self.supplementaryHeaderKind!, sectionIndex: index) } /// Footer model for section. /// - Requires: supplementaryFooterKind to be set prior to calling this method /// - Parameter index: index of section /// - Returns: footer model for section, or nil if there are no model public func footerModelForSectionIndex(index: Int) -> Any? { assert(self.supplementaryFooterKind != nil, "supplementaryFooterKind property was not set before calling footerModelForSectionIndex: method") return self.supplementaryModelOfKind(self.supplementaryFooterKind!, sectionIndex: index) } } // MARK: - SupplementaryStorageProtocol extension MemoryStorage : SupplementaryStorageProtocol { /// Retrieve supplementary model of specific kind for section. /// - Parameter kind: kind of supplementary model /// - Parameter sectionIndex: index of section /// - SeeAlso: `headerModelForSectionIndex` /// - SeeAlso: `footerModelForSectionIndex` public func supplementaryModelOfKind(kind: String, sectionIndex: Int) -> Any? { let sectionModel : SectionModel if sectionIndex >= self.sections.count { return nil } else { sectionModel = self.sections[sectionIndex] as! SectionModel } return sectionModel.supplementaryModelOfKind(kind) } }
368f26d017b72705b845929bfcb8ea56
38.919811
170
0.664165
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
Widget/Shared Views/SizeCategories.swift
mit
1
// // SizeCategories.swift // NetNewsWire iOS Widget Extension // // Created by Stuart Breckenridge on 24/12/2020. // Copyright © 2020 Ranchero Software. All rights reserved. // import SwiftUI struct SizeCategories { let largeSizeCategories: [ContentSizeCategory] = [.extraExtraLarge, .extraExtraExtraLarge, .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge] func isSizeCategoryLarge(category: ContentSizeCategory) -> Bool { largeSizeCategories.filter{ $0 == category }.count == 1 } }
24a46e91cc395a0a63411e3fcabb4014
25.115385
68
0.670103
false
false
false
false
woshishui1243/QRCodeInSwift
refs/heads/master
QRCodeInSwift/Source/QRCode.swift
mit
1
// // QRCode.swift // QRCodeInSwift // // Created by 李禹 on 15/9/13. // Copyright (c) 2015年 dayu. All rights reserved. // import Foundation import AVFoundation public class QRCode: NSObject { public override init() {} // var completion: ((stringValue: String)->())? public func sayHello () { NSLog("hello"); } // // //摄像头输入 // lazy var videoInput: AVCaptureDeviceInput? = { // if let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) { // // return AVCaptureDeviceInput.deviceInputWithDevice(device, error: nil) as? AVCaptureDeviceInput; // } // return nil; // }() // // //输出数据 // lazy var output: AVCaptureMetadataOutput = { // return AVCaptureMetadataOutput(); // }(); // // //会话 // lazy var session: AVCaptureSession = { // let session = AVCaptureSession(); // // return session; // // }(); // // //预览图层 // lazy var previewLayer: AVCaptureVideoPreviewLayer? = { // let previewLayer = AVCaptureVideoPreviewLayer.layerWithSession(self.session) as? AVCaptureVideoPreviewLayer; // return previewLayer; // }() // // //二维码边框 // lazy var boundsView: UIView = { // let view = UIView(); // return view; // }() // // // public func startScan(fromView: UIView, previewFrame: CGRect, boarderColor: UIColor, boarderWidth: CGFloat, completion:(qrcode:String)->()) { // if (session.canAddInput(videoInput)) { // session.addInput(videoInput); // } // if (session.canAddOutput(output)) { // session.addOutput(output); // } // //设置扫描数据类型(全部支持) // output.metadataObjectTypes = output.availableMetadataObjectTypes; // println(output.availableMetadataObjectTypes); // // previewLayer?.frame = previewFrame; // fromView.layer.insertSublayer(previewLayer, atIndex: 0); // // fromView.frame = CGRectZero; // fromView.layer.borderWidth = boarderWidth; // fromView.layer.borderColor = boarderColor.CGColor; // fromView.addSubview(boundsView); // // output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()); // // session.startRunning(); // // } } extension QRCode: AVCaptureMetadataOutputObjectsDelegate { // public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { // if (metadataObjects == nil || metadataObjects.count == 0) { // return; // } // // let readableCodeObj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject; // if (readableCodeObj == nil) { // return // } // if readableCodeObj!.type == AVMetadataObjectTypeQRCode { // let codeObject = previewLayer?.transformedMetadataObjectForMetadataObject(readableCodeObj!); // if codeObject != nil { // boundsView.frame = codeObject!.bounds; // let str = readableCodeObj!.stringValue; // if str == nil { return; } // self.completion?(stringValue: str); // // } // } // } }
d3563ae3b750e08c13c85d0122fd1653
31.970874
171
0.580094
false
false
false
false
orta/Tinker
refs/heads/master
Tinker/Library/TinkerObject.swift
mit
1
// // TinkerObject.swift // Relate // // Created by Orta on 8/23/14. // Copyright (c) 2014 Orta. All rights reserved. // public typealias voidClosure = () -> Void public class TinkerObject: Equatable { public let name: String public var id: String public var heldObjects: [TinkerObject] = [] private var inlineResponses: Dictionary <String, voidClosure> = [String: voidClosure]() public init(name: String) { self.name = name; self.id = name.lowercaseString } public func respondToCommand(command: String) -> Bool { for object in heldObjects { if object.respondsToCommand(command) { return true } } return false } private func respondsToCommand(command: String) -> Bool { for key in inlineResponses.keys { if key == command { inlineResponses[key]!() return true } } return false } public func addResponseToCommand(to: String, with: voidClosure) { inlineResponses[to] = with } } public func ==(lhs: TinkerObject, rhs: TinkerObject) -> Bool { return lhs.id == rhs.id }
9fc02756cdf3a7146d35a282d0ce1c9d
23.857143
91
0.582102
false
false
false
false
shiwwgis/MyDiaryForEvernote
refs/heads/master
MyDiraryForEvernote/SetBkgroundViewCtrller.swift
mit
1
// // SetBkgroundViewCtrller.swift // DrawingBoard // // Created by shiweiwei on 16/2/22. // Copyright © 2016年 shiww. All rights reserved. // import UIKit class SetBkgroundViewCtrller: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{ @IBAction func doSelimageFromAlbum(sender: UIButton) { let pickerController = UIImagePickerController(); pickerController.delegate = self; self.presentViewController(pickerController, animated: true, completion: nil); } var mainViewController:ViewController?; private let strImageName=["background1","background2","background3","background4","background5","background6","background7","background8","background9"]; var imageIndex:Int=0; @IBAction func doSetbkCancel(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil);//关闭窗口 } @IBAction func doSetbkOK(sender: AnyObject) { //设置背景 let tempImage=imgBkground.image; if imageIndex<self.strImageName.count { mainViewController!.board.bkImgName=strImageName[imageIndex]; } mainViewController!.setBackgroundColor(tempImage!); self.dismissViewControllerAnimated(true, completion: nil); } @IBAction func doPrevImage(sender: UIButton) { if imageIndex<=0//已是第一个 { imageIndex=strImageName.count-1; } else { imageIndex=imageIndex-1; } let tempImage=UIImage(named: strImageName[imageIndex]); imgBkground.image=tempImage; } @IBAction func doNextImage(sender: UIButton) { if imageIndex>=strImageName.count-1//已是最后一个 { imageIndex=0 } else { imageIndex=imageIndex+1; } let tempImage=UIImage(named: strImageName[imageIndex]); imgBkground.image=tempImage; } @IBOutlet weak var imgBkground: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. imageIndex=strImageName.indexOf((mainViewController?.board.bkImgName)!)!; assert(imageIndex<strImageName.count); let tempImage=UIImage(named: strImageName[imageIndex]); imgBkground.image=tempImage; } 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: UIImagePickerControllerDelegate Methods func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage self.imgBkground.image=image self.dismissViewControllerAnimated(true, completion: nil) } }
909cc779d548b7ef1ae6216f3586f2c5
30.495327
157
0.650445
false
false
false
false
cuzv/TinyCoordinator
refs/heads/master
Sources/TCDataSource.swift
mit
1
// // TCDataSource.swift // Copyright (c) 2016 Red Rain (https://github.com/cuzv). // // 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 /// Swift does not support generic protocol, so follow code can not compile: /// if self is TCDataSourceable { ..} // See: http://www.captechconsulting.com/blogs/ios-9-tutorial-series-protocol-oriented-programming-with-uikit /// > UIKit is still compiled from Objective-C, and Objective-C has no concept of protocol extendability. /// What this means in practice is that despite our ability to declare extensions on UIKit protocols, /// UIKit objects can't see the methods inside our extensions. /// So we can not extension `TCDataSourceable` implement `UITableViewDataSource`. /// The only thing we can do is provide helper func for `UITableViewDataSource` implement instance. open class TCDataSource: NSObject, UITableViewDataSource, UICollectionViewDataSource { open let tableView: UITableView! open let collectionView: UICollectionView! open var globalDataMetric: TCGlobalDataMetric #if DEBUG deinit { debugPrint("\(#file):\(#line):\(type(of: self)):\(#function)") } #endif fileprivate override init() { fatalError("Use init(tableView:) or init(collectionView:) instead.") } public init(tableView: UITableView) { self.tableView = tableView collectionView = nil globalDataMetric = TCGlobalDataMetric.empty() super.init() checkConforms() registereusableView() } public init(collectionView: UICollectionView) { self.collectionView = collectionView tableView = nil globalDataMetric = TCGlobalDataMetric.empty() super.init() checkConforms() registereusableView() } fileprivate func checkConforms() { guard self is TCDataSourceable else { fatalError("Must conforms protocol `TCDataSourceable`.") } } fileprivate func registereusableView() { guard let subclass = self as? TCDataSourceable else { fatalError("Must conforms protocol `TCDataSourceable`.") } subclass.registerReusableCell() if let subclass = self as? TCTableViewHeaderFooterViewibility { subclass.registerReusableHeaderFooterView() } else if let subclass = self as? TCCollectionSupplementaryViewibility { subclass.registerReusableSupplementaryView() collectionView.tc_registerReusableSupplementaryView(class: TCDefaultSupplementaryView.self, kind: .sectionHeader) collectionView.tc_registerReusableSupplementaryView(class: TCDefaultSupplementaryView.self, kind: .sectionFooter) } } open var delegate: TCDelegate? { if let tableView = tableView { return tableView.delegate as? TCDelegate } return collectionView.delegate as? TCDelegate } open var scrollingToTop: Bool? { return delegate?.scrollingToTop } open var isEmpty: Bool { return globalDataMetric.allData.count == 0 } }
1efd28cf8497bea35270988005b46186
38.698113
125
0.694629
false
false
false
false
mintrocket/MRKit
refs/heads/master
MRKit/Classes/Backend/Core/Response/ResponseData.swift
mit
1
// // ResponseData.swift // RedArmy // // Created by Kirill Kunst on 24/01/2017. // Copyright © 2017 MintRocket LLC. All rights reserved. // import Foundation public class ResponseData: CustomDebugStringConvertible, Equatable { public let statusCode: Int public let data: AnyObject public let request: URLRequest? public let response: URLResponse? /// ResponseData initialisation /// - parameter statusCode: code of response /// - parameter data: processed response data /// - parameter request: URLRequest /// - parameter response: URLResponse public init(statusCode: Int, data: AnyObject, request: URLRequest? = nil, response: URLResponse? = nil) { self.statusCode = statusCode self.data = data self.request = request self.response = response } /// ResponseData initialisation /// - parameter networkResponse: NetworkService response /// - parameter data: processed response data public init(from networkResponse: NetworkService.NetworkResponse, data: AnyObject) { self.statusCode = networkResponse.1 self.data = data self.request = networkResponse.3 self.response = networkResponse.2 } /// A text description of the `Response`. public var description: String { return "Status Code: \(statusCode), Data Length: \(data.count)" } /// A text description of the `Response`. Suitable for debugging. public var debugDescription: String { return description } public static func == (lhs: ResponseData, rhs: ResponseData) -> Bool { return lhs.statusCode == rhs.statusCode && lhs.response == rhs.response } }
e00274ac023461c6534db1fd0e58413f
30.071429
109
0.658046
false
false
false
false
Brightify/ReactantUI
refs/heads/master
Sources/Tokenizer/Util/Parsing/Lexer.swift
mit
1
// // Lexer.swift // ReactantUI // // Created by Tadeas Kriz on 4/29/17. // Copyright © 2017 Brightify. All rights reserved. // import Foundation struct Lexer { enum Token { case identifier(String) case number(value: Float, original: String) case parensOpen case parensClose case assignment case equals(value: Bool, original: String) case colon case semicolon case period case at case other(String) case whitespace(String) case comma case bracketsOpen case bracketsClose case exclamation case argument(String) } } extension Lexer.Token: Equatable { static func ==(lhs: Lexer.Token, rhs: Lexer.Token) -> Bool { switch (lhs, rhs) { case (.identifier(let lhsIdentifier), .identifier(let rhsIdentifier)): return lhsIdentifier == rhsIdentifier case (.number(let lhsNumber, let lhsOriginal), .number(let rhsNumber, let rhsOriginal)): return lhsNumber == rhsNumber && lhsOriginal == rhsOriginal case (.parensOpen, .parensOpen), (.parensClose, .parensClose), (.colon, .colon), (.semicolon, .semicolon), (.period, .period), (.assignment, .assignment), (.at, .at), (.comma, .comma), (.exclamation, .exclamation), (.bracketsOpen, .bracketsOpen), (.bracketsClose, .bracketsClose): return true case (.equals(let lhsBool), .equals(let rhsBool)): return lhsBool == rhsBool case (.other(let lhsOther), .other(let rhsOther)): return lhsOther == rhsOther case (.whitespace(let lhsWhitespace), .whitespace(let rhsWhitespace)): return lhsWhitespace == rhsWhitespace case (.argument(let lhsArgument), .argument(let rhsArgument)): return lhsArgument == rhsArgument default: return false } } } extension Lexer { typealias TokenGenerator = (String) -> Token? static let tokenList: [(String, TokenGenerator)] = [ ("[ \t\n]", { .whitespace($0) }), ("[a-zA-Z][a-zA-Z0-9]*", { .identifier($0) }), ("-?[0-9]+(\\.[0-9]+)?", { original in Float(original).map { Token.number(value: $0, original: original) } }), ("\\(", { _ in .parensOpen }), ("\\)", { _ in .parensClose }), ("\\[", { _ in .bracketsOpen }), ("]", { _ in .bracketsClose }), (":", { _ in .colon }), (";", { _ in .semicolon }), ("\\.", { _ in .period }), ("@", { _ in .at }), ("[!=][=]", { .equals(value: Bool(equalityOperator: $0), original: $0) }), ("=", { _ in .assignment }), (",", { _ in .comma }), ("!", { _ in .exclamation }), ("\\{\\{[a-zA-Z_][a-zA-Z_0-9]*\\}\\}", { argument in .argument(argument.argumentWithoutBrackets)}) ] static func tokenize(input: String, keepWhitespace: Bool = false) -> [Token] { var tokens = [] as [Token] var content = input while content.count > 0 { var matched = false for (pattern, generator) in tokenList { if let match = content.match(regex: pattern) { if let token = generator(match) { if case .whitespace = token, !keepWhitespace { // Ignoring } else { tokens.append(token) } } content = String(content[content.index(content.startIndex, offsetBy: match.count)...]) matched = true break } } if !matched { let index = content.index(after: content.startIndex) tokens.append(.other(String(content[..<index]))) content = String(content[index...]) } } return tokens } } private var expressions = [String: NSRegularExpression]() fileprivate extension String { func match(regex: String) -> String? { let expression: NSRegularExpression if let exists = expressions[regex] { expression = exists } else { expression = try! NSRegularExpression(pattern: "^\(regex)", options: []) expressions[regex] = expression } let range = expression.rangeOfFirstMatch(in: self, options: [], range: NSMakeRange(0, self.utf16.count)) if range.location != NSNotFound { return (self as NSString).substring(with: range) } return nil } } private extension Bool { init(equalityOperator: String) { guard equalityOperator == "==" || equalityOperator == "!=" else { fatalError("Wrong equality operator!") } self = equalityOperator == "==" } } private extension String { var argumentWithoutBrackets: String { var copy = self copy.removeFirst(2) copy.removeLast(2) return copy } }
74fd6e7fcbfc460e347321d2ccf7bc0f
33.401361
120
0.5351
false
false
false
false
kumabook/StickyNotesiOS
refs/heads/master
StickyNotes/SNWebViewController.swift
mit
1
// // HelpWebViewController.swift // StickyNotes // // Created by Hiroki Kumamoto on 2017/07/06. // Copyright © 2017 kumabook. All rights reserved. // import Foundation import UIKit class SNWebViewController: UIViewController { var url: URL! var webView: UIWebView! init(url: URL) { super.init(nibName: nil, bundle: nil) self.url = url } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Help".localize() navigationItem.backBarButtonItem?.title = "" webView = UIWebView(frame: view.frame) view.addSubview(webView) let req = URLRequest(url: url) webView.loadRequest(req) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func back() { let _ = navigationController?.popViewController(animated: true) } }
8657cf5991d7c1558eab2ff3fa151c5c
22.833333
71
0.627373
false
false
false
false
openHPI/xikolo-ios
refs/heads/dev
iOS/Extensions/Binge+Video.swift
gpl-3.0
1
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import AVFoundation import Binge import Common extension BingePlayerViewController { func configure(for video: Video) { self.initiallyShowControls = false self.assetTitle = video.item?.title self.assetSubtitle = video.item?.section?.course?.title self.preferredPeakBitRate = video.preferredPeakBitRate() if UserDefaults.standard.playbackRate > 0 { self.playbackRate = UserDefaults.standard.playbackRate } if video.lastPosition > 0 { self.startPosition = video.lastPosition } if let offlinePlayableAsset = self.offlinePlayableAsset(for: video) { self.asset = offlinePlayableAsset } else if let fallbackURL = video.streamURLForDownload ?? video.singleStream?.hdURL ?? video.singleStream?.sdURL { self.asset = AVURLAsset(url: fallbackURL) } else { self.asset = nil } if let posterImageURL = video.item?.section?.course?.imageURL { DispatchQueue.main.async { if let imageData = try? Data(contentsOf: posterImageURL), let image = UIImage(data: imageData) { self.posterImage = image } } } } private func offlinePlayableAsset(for video: Video) -> AVURLAsset? { guard let localFileLocation = StreamPersistenceManager.shared.localFileLocation(for: video) else { return nil } let asset = AVURLAsset(url: localFileLocation) return asset.assetCache?.isPlayableOffline == true ? asset : nil } } extension Video { func preferredPeakBitRate() -> Double? { guard StreamPersistenceManager.shared.localFileLocation(for: self) == nil else { return nil } let videoQuality = ReachabilityHelper.connection == .wifi ? UserDefaults.standard.videoQualityOnWifi : UserDefaults.standard.videoQualityOnCellular return Double(videoQuality.rawValue) } }
b12912146d9ee1a3e5ba019a339d82cc
33.813559
155
0.659688
false
false
false
false
liuxianghong/GreenBaby
refs/heads/master
工程/greenbaby/greenbaby/ViewController/MainViewController.swift
lgpl-3.0
1
// // MainViewController.swift // greenbaby // // Created by 刘向宏 on 15/12/3. // Copyright © 2015年 刘向宏. All rights reserved. // import UIKit class MainViewController: UITabBarController { var first : Bool = true override func viewDidLoad() { super.viewDidLoad() UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] UIGraphicsBeginImageContext(CGSizeMake(1, 1)); let context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context,UIColor.mainGreenColor().CGColor); CGContextFillRect(context, CGRectMake(0, 0, 1, 1)); let img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UINavigationBar.appearance().setBackgroundImage(img, forBarPosition: .Any, barMetrics: .Default) UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().translucent = false UINavigationBar.appearance().backItem?.title = "返回" self.tabBar.tintColor = UIColor.mainGreenColor() for item in self.tabBar.items!{ item.setTitleTextAttributes( [NSForegroundColorAttributeName : UIColor.mainGreenColor()] , forState: .Selected) } UserInfo.CurrentUser().userId = nil // for _ in 1...10{ // let uuid = NSUUID() // print(uuid.UUIDString) // } // let byte : [UInt8] = [0xff, 0xd8]; // let data = NSData(bytes: byte, length: 2) // print(data) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if first{ //UserInfo.CurrentUser().userId = 19 self.performSegueWithIdentifier("loginIdentifier", sender: nil) first = false } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "shareIdentifier"{ let vc = segue.destinationViewController as! ShareViewController vc.shareImage = sender as! UIImage } else if segue.identifier == "detailSeeIdentifier"{ let vc = segue.destinationViewController as! TrainingTipsViewController vc.type = sender as! Int } } }
f97f60c3fd70a79f716791f0002cbbcd
35.822785
123
0.653489
false
false
false
false
zakkhoyt/ColorPicKit
refs/heads/1.2.3
ColorPicKit/Classes/SliderGroup.swift
mit
1
// // SliderGroup.swift // ColorPicKitExample // // Created by Zakk Hoyt on 10/26/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit @IBDesignable public class SliderGroup: UIControl, SliderControlGroup, Colorable { // MARK: Variables fileprivate var _realtimeMix: Bool = false @IBInspectable public var realtimeMix: Bool { get { return _realtimeMix } set { _realtimeMix = newValue commonInit() updateSliderColors() } } fileprivate var _showAlphaSlider: Bool = true @IBInspectable public var showAlphaSlider: Bool { get { return _showAlphaSlider } set { _showAlphaSlider = newValue for slider in sliders { slider.removeFromSuperview() } sliders.removeAll() commonInit() } } @IBInspectable public var color: UIColor { get { return colorFromSliders() } set { slidersFrom(color: newValue) } } private var _barHeight: CGFloat = 10 @IBInspectable public var barHeight: CGFloat { get { return _barHeight } set { if _barHeight != newValue { _barHeight = newValue for slider in sliders { slider.barHeight = newValue } } } } private var _knobSize: CGSize = CGSize(width: 30, height: 30) @IBInspectable public var knobSize: CGSize { get { return _knobSize } set { if _knobSize != newValue { _knobSize = newValue for slider in sliders { slider.knobSize = newValue } } } } private var _colorKnob: Bool = true @IBInspectable public var colorKnob: Bool { get { return _colorKnob } set { if _colorKnob != newValue { _colorKnob = newValue for slider in sliders { slider.colorKnob = newValue } } } } private var _borderColor: UIColor = .lightGray @IBInspectable public var borderColor: UIColor{ get { return _borderColor } set { if _borderColor != newValue { _borderColor = newValue for slider in sliders { slider.borderColor = newValue } } } } private var _borderWidth: CGFloat = 0.5 @IBInspectable public var borderWidth: CGFloat{ get { return _borderWidth } set { if _borderWidth != newValue { _borderWidth = newValue for slider in sliders { slider.borderWidth = newValue } } } } private var _roundedCornders: Bool = true @IBInspectable public var roundedCorners: Bool { get { return _roundedCornders } set { if _roundedCornders != newValue { _roundedCornders = newValue for slider in sliders { slider.roundedCorners = newValue } } } } func colorFromSliders() -> UIColor { assert(false, "child must implement"); return UIColor.clear } func slidersFrom(color: UIColor) { assert(false, "child must implement"); } let spacing: CGFloat = 4 let sliderHeight: CGFloat = 40 var sliders: [Slider] = [Slider]() // MARK: Init required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } private func commonInit() { backgroundColor = UIColor.clear for slider in sliders { slider.removeFromSuperview() } sliders.removeAll() configureSliders() for slider in sliders { slider.roundedCorners = roundedCorners slider.borderColor = borderColor slider.borderWidth = borderWidth slider.barHeight = barHeight slider.knobSize = knobSize slider.colorKnob = colorKnob slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged) slider.addTarget(self, action: #selector(sliderTouchDown), for: .touchDown) slider.addTarget(self, action: #selector(sliderTouchUpInside), for: .touchUpInside) } } func configureSliders() { assert(false, "child must implement"); } override open func layoutSubviews() { super.layoutSubviews() for (index, slider) in sliders.enumerated() { let x = CGFloat(0) let y = (CGFloat(index) * spacing) + (CGFloat(index) * sliderHeight) let w = CGFloat(bounds.width) let h = CGFloat(sliderHeight) let frame = CGRect(x: x, y: y, width: w, height: h) slider.frame = frame } } // MARK: Private methods func touchDown() { self.sendActions(for: .touchDown) } func touchUpInside() { self.sendActions(for: .touchUpInside) } func valueChanged() { self.sendActions(for: .valueChanged) } @objc func sliderValueChanged(sender: GradientSlider) { valueChanged() updateSliderColors() } @objc func sliderTouchDown(sender: GradientSlider) { valueChanged() touchDown() updateSliderColors() } @objc func sliderTouchUpInside(sender: GradientSlider) { valueChanged() touchUpInside() updateSliderColors() } func updateSliderColors() { print("Child class CAN implement (not required)") } }
cd34d806d60c703ba7eeb0f3e1bd473d
23.041509
95
0.507613
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Eurofurence/Modules/Login/LoginModuleBuilder.swift
mit
1
import EurofurenceModel class LoginModuleBuilder { private var sceneFactory: LoginSceneFactory private let authenticationService: AuthenticationService private var alertRouter: AlertRouter init(authenticationService: AuthenticationService) { self.authenticationService = authenticationService sceneFactory = LoginViewControllerFactory() alertRouter = WindowAlertRouter.shared } func with(_ sceneFactory: LoginSceneFactory) -> LoginModuleBuilder { self.sceneFactory = sceneFactory return self } func with(_ alertRouter: AlertRouter) -> LoginModuleBuilder { self.alertRouter = alertRouter return self } func build() -> LoginModuleProviding { return LoginModule(sceneFactory: sceneFactory, authenticationService: authenticationService, alertRouter: alertRouter) } }
5d443d3942260bad1f482ee7d3c53f75
29.064516
72
0.689914
false
false
false
false
EdenShapiro/tip-calculator-with-yelp-review
refs/heads/master
SuperCoolTipCalculator/Business.swift
mit
1
// // Business.swift // SuperCoolTipCalculator // // Created by Eden on 3/22/17. // Copyright © 2017 Eden Shapiro. All rights reserved. // import UIKit class Business: NSObject { let name: String? let address: String? let imageURL: URL? let categories: String? let distance: String? let ratingImageURL: URL? let reviewCount: NSNumber? let id: String? init(dictionary: NSDictionary) { name = dictionary["name"] as? String let imageURLString = dictionary["image_url"] as? String if imageURLString != nil { imageURL = URL(string: imageURLString!)! } else { imageURL = nil } let location = dictionary["location"] as? NSDictionary var address = "" if location != nil { let addressArray = location!["address"] as? NSArray if addressArray != nil && addressArray!.count > 0 { address = addressArray![0] as! String } let neighborhoods = location!["neighborhoods"] as? NSArray if neighborhoods != nil && neighborhoods!.count > 0 { if !address.isEmpty { address += ", " } address += neighborhoods![0] as! String } } self.address = address let categoriesArray = dictionary["categories"] as? [[String]] if categoriesArray != nil { var categoryNames = [String]() for category in categoriesArray! { let categoryName = category[0] categoryNames.append(categoryName) } categories = categoryNames.joined(separator: ", ") } else { categories = nil } let distanceMeters = dictionary["distance"] as? NSNumber if distanceMeters != nil { let milesPerMeter = 0.000621371 distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue) } else { distance = nil } let ratingImageURLString = dictionary["rating_img_url_large"] as? String if ratingImageURLString != nil { ratingImageURL = URL(string: ratingImageURLString!) } else { ratingImageURL = nil } reviewCount = dictionary["review_count"] as? NSNumber id = dictionary["id"] as? String } class func businesses(_ array: [NSDictionary]) -> [Business] { var businesses = [Business]() for dictionary in array { let business = Business(dictionary: dictionary) businesses.append(business) } return businesses } class func searchWithTerm(_ term: String, completion: @escaping ([Business]?, Error?) -> Void) { _ = YelpClient.sharedInstance.searchWithTerm(term, completion: completion) } class func searchWithTerm(_ term: String, userLocation: (Double, Double)?, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: @escaping ([Business]?, Error?) -> Void) -> Void { _ = YelpClient.sharedInstance.searchWithTerm(term, userLocation: userLocation, sort: sort, categories: categories, deals: deals, completion: completion) } }
415ac1c64583465239e84bc4513751d6
32.108911
199
0.568182
false
false
false
false
devxoul/Umbrella
refs/heads/master
Tests/UmbrellaAppboyTests/AppboyProviderTests.swift
mit
1
import XCTest import Umbrella import UmbrellaAppboy import Appboy_iOS_SDK final class AppboyProviderTests: XCTestCase { private enum Swizzle { static let UNUserNotificationCenter_currentNotificationCenter: Void = { guard #available(iOS 10.0, *) else { return } let cls = UNUserNotificationCenter.self let oldSelector = NSSelectorFromString("currentNotificationCenter") let newSelector = #selector(UNUserNotificationCenter.swizzled_currentNotificationCenter) guard let oldMethod = class_getClassMethod(cls, oldSelector) else { return } guard let newMethod = class_getClassMethod(cls, newSelector) else { return } method_exchangeImplementations(oldMethod, newMethod) }() } override func setUp() { super.setUp() Swizzle.UNUserNotificationCenter_currentNotificationCenter Appboy.start(withApiKey: "TEST_TOKEN", in: UIApplication.shared, withLaunchOptions: [:], withAppboyOptions: [:]) } func testAppboyProvider() { let provider = AppboyProvider() XCTAssertTrue(provider.cls === Appboy.self) XCTAssertNotNil(provider.instance) XCTAssertTrue(provider.instance === Appboy.sharedInstance()) XCTAssertEqual(provider.selector, #selector(Appboy.logCustomEvent(_:withProperties:))) XCTAssertTrue(provider.responds) } } @available(iOS 10.0, *) extension UNUserNotificationCenter { private static let currentUserNotificationCenter = UNUserNotificationCenter.perform(NSSelectorFromString("alloc"))?.takeUnretainedValue() as! UNUserNotificationCenter @objc static func swizzled_currentNotificationCenter() -> UNUserNotificationCenter { return self.currentUserNotificationCenter } }
7afd81b3ff43a2f52927f89e738b17b9
38.97619
168
0.765932
false
true
false
false
society2012/PGDBK
refs/heads/master
PGDBK/PGDBK/Code/Home/View/NoteTableViewCell.swift
mit
1
// // NoteTableViewCell.swift // PGDBK // // Created by hupeng on 2017/7/6. // Copyright © 2017年 m.zintao. All rights reserved. // import UIKit import Kingfisher class NoteTableViewCell: UITableViewCell { @IBOutlet var noteImageView: UIImageView! @IBOutlet var timeLabel: UILabel! @IBOutlet var desLabel: UILabel! @IBOutlet var titleLabel: UILabel! var newModel:NoteModel?{ didSet { self.titleLabel.text = newModel?.title self.desLabel.text = newModel?.desc let time = Int((newModel?.time)!) let timeStamp:TimeInterval = TimeInterval(time!) let date = Date(timeIntervalSince1970: timeStamp) let dformatter = DateFormatter() dformatter.dateFormat = "MM-dd HH:mm" let timeOutput = dformatter.string(from: date) self.timeLabel.text = timeOutput guard let pic = newModel?.pic else{return} let str = SERVER_IP + pic let url = URL(string: str) self.noteImageView.kf.setImage(with: url!) } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
5ccfcd32e9452e65df250a919559aa64
24.377358
61
0.545725
false
false
false
false
joshuamcshane/nessie-ios-sdk-swift2
refs/heads/test
NessieTestProj/NSEFunctionalTests.swift
mit
1
// // NSEFunctionalTests.swift // Nessie-iOS-Wrapper // // Created by Mecklenburg, William on 5/19/15. // Copyright (c) 2015 Nessie. All rights reserved. // import Foundation import NessieFmwk class AccountTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testAccountGets() testAccountPost() } func testAccountGets() { //Test with my key let getAllRequest = AccountRequest(block: {(builder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result) in var accounts = result.getAllAccounts() print("Accounts created:\(accounts)\n", terminator: "") let accountToGet = accounts![0] let accountToUpdateThenDelete = accounts![1] self.testAccountGetOne(accountToGet.accountId) self.testAccountPutDelete(accountToUpdateThenDelete.accountId) }) } func testAccountGetOne(identifier:String) { let getOneRequest = AccountRequest(block: {(builder) in builder.requestType = HTTPType.GET builder.accountId = identifier }) getOneRequest?.send({(result) in let account = result.getAccount() print("Account fetched:\(account)\n", terminator: "") }) } func testAccountPost() { let accountPostRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.POST builder.accountType = AccountType.SAVINGS builder.balance = 100 builder.nickname = "Madelyn's Savings Account" builder.rewards = 20000 builder.customerId = "55dd3baef8d87732af4687af" }) accountPostRequest?.send({(result:AccountResult) in //Should not be any result, should NSLog a message in console saying it was successful }) } func testAccountPutDelete(identifier:String) { let accountPutRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.PUT builder.accountId = identifier builder.nickname = "Victor" }) accountPutRequest?.send({(result:AccountResult) in //should not be any result let accountDeleteRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.DELETE builder.accountId = identifier }) accountDeleteRequest?.send({(result:AccountResult) in //no result }) }) } } class ATMTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testATMGetAll() } func testATMGetAll() { let atmGetAllRequest = ATMRequest(block: {(builder:ATMRequestBuilder) in builder.requestType = HTTPType.GET builder.latitude = 38.9283 builder.longitude = -77.1753 builder.radius = "1" }) atmGetAllRequest?.send({(result:ATMResult) in var atms = result.getAllATMs() print("ATMs fetched:\(atms)\n", terminator: "") let atmToGetID = atms![0].atmId let getOneATMRequest = ATMRequest(block: {(builder:ATMRequestBuilder) in builder.requestType = HTTPType.GET builder.atmId = atmToGetID }) getOneATMRequest?.send({(result:ATMResult) in let atm = result.getATM() print("ATM fetched:\(atm)\n", terminator: "") }) }) } } class BillTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllBills() } var accountToAccess:Account! var accountToPay:Account! func testGetAllBills() { let getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![2] self.accountToPay = accounts![1] self.testPostBill() /********************* Get bills for customer **********************/ BillRequest(block: {(builder:BillRequestBuilder) in builder.requestType = HTTPType.GET builder.customerId = self.accountToAccess.customerId })?.send(completion: {(result:BillResult) in let bills = result.getAllBills() print(bills) }) //create and then send shortcut BillRequest(block: {(builder:BillRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:BillResult) in var bills = result.getAllBills() let billToGet = bills![0] let billToPutDelete = bills![0] /********************* Get bill by ID **********************/ self.testGetOneBill(billToGet) /********************* Put bill **********************/ self.testPutBill(billToPutDelete) }) }) } func testGetOneBill(bill:Bill) { BillRequest(block: {(builder:BillRequestBuilder) in builder.requestType = HTTPType.GET builder.billId = bill.billId })?.send(completion: {(result:BillResult) in let billresult = result.getBill() print(billresult) }) } func testPostBill() { BillRequest(block: {(builder:BillRequestBuilder) in builder.requestType = HTTPType.POST builder.status = BillStatus.RECURRING builder.accountId = self.accountToAccess.accountId builder.recurringDate = 15 builder.paymentAmount = 10 builder.payee = self.accountToPay.accountId builder.nickname = "bill" })?.send(completion: {(result:BillResult) in }) } func testPutBill(bill:Bill) { BillRequest(block: {(builder:BillRequestBuilder) in builder.billId = bill.billId builder.nickname = "newbill" builder.requestType = HTTPType.PUT })?.send(completion: {(result:BillResult) in self.testDeleteBill(bill) }) } func testDeleteBill(bill:Bill) { BillRequest(block: {(builder:BillRequestBuilder) in builder.billId = bill.billId builder.requestType = HTTPType.DELETE })?.send(completion: {(result) in }) } } class BranchTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testBranchGetAll() } func testBranchGetAll() { /********************* Get branches **********************/ BranchRequest(block: {(builder:BranchRequestBuilder) in builder.requestType = HTTPType.GET })?.send({(result:BranchResult) in var branches = result.getAllBranches() var branchToGetID = branches![0].branchId /********************* Get 1 branch **********************/ BranchRequest(block: {(builder:BranchRequestBuilder) in builder.requestType = HTTPType.GET builder.branchId = branchToGetID })?.send({(result:BranchResult) in var branch = result.getBranch() }) }) } } class CustomerTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllCustomers() } func testGetAllCustomers() { // self.testPostCustomer() /********************* Get all customers **********************/ CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.GET })?.send({(result:CustomerResult) in var customers = result.getAllCustomers() print("Customers fetched:\(customers)\n", terminator: "") var customerToGet = customers![3] var customerToGetFromAccount = customers![customers!.count-1] /********************* Get 1 customer **********************/ self.testGetOneCustomer(customerToGet) /********************* Get customer from account **********************/ self.testGetCustomerFromAccount(customerToGetFromAccount) /********************* Get accounts from customer **********************/ self.testGetAccountsFromCustomer(customerToGetFromAccount) /********************* Get put customer **********************/ self.testUpdateCustomer(customerToGet) }) } func testGetOneCustomer(customer:Customer) { CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.GET builder.customerId = customer.customerId })?.send({(result:CustomerResult) in var customer = result.getCustomer() print("Customer fetched:\(customer)\n", terminator: "") }) } func testGetCustomerFromAccount(customer:Customer) { CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = customer.accountIds?[0] })?.send({(result:CustomerResult) in var customer = result.getCustomer() print("Customer from account fetched:\(customer)\n", terminator: "") }) } func testGetAccountsFromCustomer(customer:Customer) { AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET builder.customerId = customer.customerId })?.send({(result:AccountResult) in var accounts = result.getAllAccounts() print("Accounts from customer fetched:\(accounts)\n", terminator: "") }) } func testUpdateCustomer(customer:Customer) { CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.PUT builder.customerId = customer.customerId builder.address = Address(streetName: "streetname", streetNumber: "123", city: "city", state: "DC", zipCode: "12345") })?.send({(result) in //no result }) } func testPostCustomer() { CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.POST builder.firstName = "Elliot" builder.lastName = "Anderson" builder.address = Address(streetName: "streetname", streetNumber: "123", city: "city", state: "DC", zipCode: "12345") })?.send({(result) in //no result }) } } class DepositTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllDeposits() } var accountToAccess:Account! func testGetAllDeposits() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.testPostDeposit() //test get all }) } func testGetOneDeposit(deposit:Transaction) { DepositRequest(block: {(builder:DepositRequestBuilder) in builder.requestType = HTTPType.GET builder.depositId = deposit.transactionId })?.send(completion: {(result:DepositResult) in var depositResult = result.getDeposit() print(depositResult, terminator: "") }) } func testPostDeposit() { DepositRequest(block: {(builder:DepositRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.depositMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in DepositRequest(block: {(builder:DepositRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:DepositResult) in var deposits = result.getAllDeposits() if deposits!.count > 0 { let depositToGet = deposits![deposits!.count-1] var depositToDelete:Transaction? = nil; for deposit in deposits! { if deposit.status == "pending" { depositToDelete = deposit // self.testDeleteDeposit(depositToDelete) } } // self.testGetOneDeposit(depositToGet) self.testPutDeposit(depositToDelete) } }) }) } func testPutDeposit(deposit:Transaction?) { if (deposit == nil) { return } DepositRequest(block: {(builder:DepositRequestBuilder) in builder.depositId = deposit!.transactionId print(deposit!.status) builder.requestType = HTTPType.PUT builder.amount = 4300 builder.depositMedium = TransactionMedium.REWARDS builder.description = "updated" })?.send(completion: {(result:DepositResult) in // self.testDeleteDeposit(deposit!) }) } func testDeleteDeposit(deposit:Transaction?) { DepositRequest(block: {(builder:DepositRequestBuilder) in builder.depositId = deposit!.transactionId print(deposit!.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class PurchaseTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllPurchases() } var accountToAccess:Account! func testGetAllPurchases() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.testPostPurchase() //test get all }) } func testGetOnePurchase(purchase:Transaction) { PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.requestType = HTTPType.GET builder.purchaseId = purchase.transactionId })?.send(completion: {(result:PurchaseResult) in var purchaseResult = result.getPurchase() print(purchaseResult, terminator: "") }) } func testPostPurchase() { PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.purchaseMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId builder.merchantId = "55e9b7957bf47e14009404f0" })?.send(completion: {(result) in PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:PurchaseResult) in var purchases = result.getAllPurchases() if purchases!.count > 0 { let purchaseToGet = purchases![purchases!.count-1] var purchaseToDelete:Purchase? = nil; for purchase in purchases! { if purchase.status == "pending" { purchaseToDelete = purchase // self.testDeletePurchase(purchaseToDelete) } } //self.testGetOnePurchase(purchaseToGet) self.testPutPurchase(purchaseToDelete) } }) }) } func testPutPurchase(purchase:Purchase?) { if (purchase == nil) { return } PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.purchaseId = purchase!.purchaseId print(purchase!.status) builder.requestType = HTTPType.PUT builder.amount = 4300 builder.purchaseMedium = TransactionMedium.REWARDS builder.description = "updated" builder.payerId = "55e94a1af8d877051ab4f6c2" })?.send(completion: {(result:PurchaseResult) in // self.testDeletePurchase(purchase!) }) } func testDeletePurchase(purchase:Purchase?) { PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.purchaseId = purchase!.purchaseId print(purchase!.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class TransferTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllTransfers() } var accountToAccess:Account! func testGetAllTransfers() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.testPostTransfer() //test get all }) } func testGetOneTransfer(transfer:Transfer) { TransferRequest(block: {(builder:TransferRequestBuilder) in builder.requestType = HTTPType.GET builder.transferId = transfer.transferId })?.send(completion: {(result:TransferResult) in var transferResult = result.getTransfer() print(transferResult, terminator: "") }) } func testPostTransfer() { TransferRequest(block: {(builder:TransferRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.transferMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId builder.payeeId = "55e94a1af8d877051ab4f6c1" })?.send(completion: {(result) in TransferRequest(block: {(builder:TransferRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:TransferResult) in var transfers = result.getAllTransfers() if transfers!.count > 0 { let transferToGet = transfers![transfers!.count-1] var transferToDelete:Transfer? = nil; for transfer in transfers! { if transfer.status == "pending" { transferToDelete = transfer // self.testDeleteTransfer(transferToDelete) } } //self.testGetOneTransfer(transferToGet) //self.testPutTransfer(transferToDelete) } }) }) } func testPutTransfer(transfer:Transfer?) { if (transfer == nil) { return } TransferRequest(block: {(builder:TransferRequestBuilder) in builder.transferId = transfer!.transferId print(transfer!.status) builder.requestType = HTTPType.PUT builder.amount = 4300 builder.transferMedium = TransactionMedium.REWARDS builder.description = "updated" builder.payeeId = "55e94a1af8d877051ab4f6c2" })?.send(completion: {(result:TransferResult) in // self.testDeleteTransfer(transfer!) }) } func testDeleteTransfer(transfer:Transfer?) { TransferRequest(block: {(builder:TransferRequestBuilder) in builder.transferId = transfer!.transferId print(transfer!.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class WithdrawalTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllWithdrawals() } var accountToAccess:Account! func testGetAllWithdrawals() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.testPostWithdrawal() //test get all }) } func testGetOneWithdrawal(withdrawal:Withdrawal) { WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.requestType = HTTPType.GET builder.withdrawalId = withdrawal.withdrawalId })?.send(completion: {(result:WithdrawalResult) in var withdrawalResult = result.getWithdrawal() print(withdrawalResult, terminator: "") }) } func testPostWithdrawal() { WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.withdrawalMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:WithdrawalResult) in var withdrawals = result.getAllWithdrawals() if withdrawals!.count > 0 { let withdrawalToGet = withdrawals![withdrawals!.count-1] var withdrawalToDelete:Withdrawal? = nil; for withdrawal in withdrawals! { if withdrawal.status == "pending" { withdrawalToDelete = withdrawal //self.testDeleteWithdrawal(withdrawalToDelete) } } //self.testGetOneWithdrawal(withdrawalToGet) self.testPutWithdrawal(withdrawalToDelete) } }) }) } func testPutWithdrawal(withdrawal:Withdrawal?) { if (withdrawal == nil) { return } WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.withdrawalId = withdrawal!.withdrawalId print(withdrawal!.status) builder.requestType = HTTPType.PUT builder.amount = 4300 builder.withdrawalMedium = TransactionMedium.REWARDS builder.description = "updated" })?.send(completion: {(result:WithdrawalResult) in // self.testDeleteWithdrawal(withdrawal!) }) } func testDeleteWithdrawal(withdrawal:Withdrawal?) { WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.withdrawalId = withdrawal!.withdrawalId print(withdrawal!.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class MerchantTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testMerchants() } func testMerchants() { self.testPostMerchant() var merchantGetAllRequest = MerchantRequest(block: {(builder:MerchantRequestBuilder) in builder.requestType = HTTPType.GET builder.latitude = 38.9283 builder.longitude = -77.1753 builder.radius = "1000" }) merchantGetAllRequest?.send({(result:MerchantResult) in var merchants = result.getAllMerchants() print("Merchants fetched:\(merchants)\n", terminator: "") var merchantID = merchants![0].merchantId self.testPutMerchant(merchants![0]) var getOneMerchantRequest = MerchantRequest(block: {(builder:MerchantRequestBuilder) in builder.requestType = HTTPType.GET builder.merchantId = merchantID }) getOneMerchantRequest?.send({(result:MerchantResult) in var merchant = result.getMerchant() print("Merchant fetched:\(merchant)\n", terminator: "") }) }) } func testPutMerchant(merchant:Merchant?) { if (merchant == nil) { return } MerchantRequest(block: {(builder:MerchantRequestBuilder) in builder.merchantId = merchant!.merchantId builder.requestType = HTTPType.PUT builder.name = "Victorrrrr" builder.address = Address(streetName: "1", streetNumber: "1", city: "1", state: "DC", zipCode: "12312") builder.latitude = 38.9283 builder.longitude = -77.1753 })?.send({(result:MerchantResult) in }) } func testPostMerchant() { MerchantRequest(block: {(builder:MerchantRequestBuilder) in builder.requestType = HTTPType.POST builder.name = "Fun Merchant" builder.address = Address(streetName: "1", streetNumber: "1", city: "1", state: "DC", zipCode: "12312") builder.latitude = 38.9283 builder.longitude = -77.1753 })?.send({(result:MerchantResult) in }) } } class TransactionTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllTransactions() } var accountToAccess:Account! var accountToPay:Account! func testGetAllTransactions() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.accountToPay = accounts![1] self.testPostTransaction() //test get all TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:TransactionResult) in var transactions = result.getAllTransactions() let transactionToGet = transactions![0] var transactionToDelete:Transaction? = nil; for transaction in transactions! { if transaction.status == "pending" { transactionToDelete = transaction } } self.testGetOneTransaction(transactionToGet) self.testPutTransaction(transactionToDelete) }) }) } func testGetOneTransaction(transaction:Transaction) { TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId builder.transactionId = transaction.transactionId })?.send(completion: {(result:TransactionResult) in var transactionResult = result.getTransaction() }) } func testPostTransaction() { TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.transactionMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId builder.payeeId = self.accountToPay.accountId })?.send(completion: {(result) in }) } func testPutTransaction(transaction:Transaction?) { if (transaction == nil) { return } TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.transactionId = transaction!.transactionId print(transaction!.status) builder.requestType = HTTPType.PUT builder.accountId = self.accountToAccess.accountId builder.transactionMedium = TransactionMedium.REWARDS builder.description = "updated" })?.send(completion: {(result:TransactionResult) in self.testDeleteTransaction(transaction!) }) } func testDeleteTransaction(transaction:Transaction) { TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.transactionId = transaction.transactionId print(transaction.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class EnterpriseTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testEnterpriseGets() } func testEnterpriseGets() { EnterpriseAccountRequest()?.send({(result:AccountResult) in var accounts = result.getAllAccounts() var bills = 0 for tmp in accounts! { if (tmp.billIds != nil) { bills += tmp.billIds!.count } } EnterpriseAccountRequest(accountId: accounts![0].accountId)?.send({(result:AccountResult) in var account = result.getAccount() }) }) EnterpriseBillRequest()?.send({(result:BillResult) in var bills = result.getAllBills() var x:NSMutableSet = NSMutableSet() for bill in bills! { x.addObject(bill.billId) } EnterpriseBillRequest(billId: bills![0].billId)?.send({(result:BillResult) in var bill = result.getBill() }) }) EnterpriseCustomerRequest()?.send({(result:CustomerResult) in var customers = result.getAllCustomers() EnterpriseCustomerRequest(customerId: customers![0].customerId)?.send({(result:CustomerResult) in var customer = result.getCustomer() }) }) EnterpriseTransferRequest()?.send({(result:TransferResult) in var transfers = result.getAllTransfers() print("\(transfers)\n", terminator: "") EnterpriseTransferRequest(transactionId: transfers![0].transferId)?.send({(result:TransferResult) in var transfer = result.getTransfer() print("\(transfer)\n", terminator: "") }) }) EnterpriseDepositRequest()?.send({(result:DepositResult) in var deposits = result.getAllDeposits() print("\(deposits)\n", terminator: "") EnterpriseDepositRequest(transactionId: deposits![0].transactionId)?.send({(result:DepositResult) in var deposit = result.getDeposit() print("\(deposit)\n", terminator: "") }) }) EnterpriseWithdrawalRequest()?.send({(result:WithdrawalResult) in var withdrawals = result.getAllWithdrawals() print("\(withdrawals)\n", terminator: "") EnterpriseWithdrawalRequest(transactionId: withdrawals![0].withdrawalId)?.send({(result:WithdrawalResult) in var withdrawal = result.getWithdrawal() print("\(withdrawal)\n", terminator: "") }) }) EnterpriseMerchantRequest()?.send({(result:MerchantResult) in var merchants = result.getAllMerchants() print("\(merchants)\n", terminator: "") EnterpriseMerchantRequest(merchantId: merchants![0].merchantId)?.send({(result:MerchantResult) in var merchant = result.getMerchant() print("\(merchant)\n", terminator: "") }) }) } }
b5b71de669cf65335c772c54ec5851b4
33.634051
129
0.557266
false
true
false
false
crazypoo/PTools
refs/heads/master
Pods/KakaJSON/Sources/KakaJSON/Metadata/Type/OptionalType.swift
mit
1
// // OptionalType.swift // KakaJSON // // Created by MJ Lee on 2019/8/2. // Copyright © 2019 MJ Lee. All rights reserved. // /// Optional metadata share the same basic layout as enum metadata public class OptionalType: EnumType { public private(set) var wrapType: Any.Type = Any.self override func build() { super.build() var wt: BaseType! = self while wt.kind == .optional { wt = Metadata.type((wt as! OptionalType).genericTypes![0]) } wrapType = wt.type } override public var description: String { return "\(name) { kind = \(kind), wrapType = \(wrapType) }" } }
8fedd5f5b36034bcc9ecbc049f59f81f
24.730769
70
0.590433
false
false
false
false
openHPI/xikolo-ios
refs/heads/dev
iOS/Extensions/EmptyState/EmptyState.swift
gpl-3.0
1
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import UIKit public protocol EmptyStateDelegate: AnyObject { func didTapOnEmptyStateView() } /// This protocol provides the table view object with the information it needs to construct and modify a `EmptyStateView`. public protocol EmptyStateDataSource: AnyObject { var emptyStateTitleText: String { get } var emptyStateDetailText: String? { get } } // MARK: - EmptyStateDataSource Default public extension EmptyStateDataSource { var emptyStateDetailText: String? { nil } } enum AssociatedKeys { static var emptyStateDelegate = "emptyStateDelegate" static var emptyStateDataSource = "emptyStateDataSource" static var emptyStateView = "emptyStateView" } /// This protocol provides the basic needed to override emptyViewState on anyclass that supports it protocol EmptyStateProtocol: AnyObject { var emptyStateDelegate: EmptyStateDelegate? { get set } var emptyStateDataSource: EmptyStateDataSource? { get set } var emptyStateView: EmptyStateView { get set } var hasItemsToDisplay: Bool { get } func reloadEmptyState() } extension EmptyStateProtocol { var emptyStateView: EmptyStateView { get { guard let emptyStateView = objc_getAssociatedObject(self, &AssociatedKeys.emptyStateView) as? EmptyStateView else { let emptyStateView = EmptyStateView() emptyStateView.tapHandler = { [weak self] in self?.emptyStateDelegate?.didTapOnEmptyStateView() } self.emptyStateView = emptyStateView return emptyStateView } return emptyStateView } set { objc_setAssociatedObject(self, &AssociatedKeys.emptyStateView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// The object that acts as the delegate of the empty state view. public weak var emptyStateDelegate: EmptyStateDelegate? { get { return objc_getAssociatedObject(self, &AssociatedKeys.emptyStateDelegate) as? EmptyStateDelegate } set { if let newValue = newValue { objc_setAssociatedObject(self, &AssociatedKeys.emptyStateDelegate, newValue, .OBJC_ASSOCIATION_ASSIGN) } } } /// The object that acts as the data source of the empty state view. public weak var emptyStateDataSource: EmptyStateDataSource? { get { return objc_getAssociatedObject(self, &AssociatedKeys.emptyStateDataSource) as? EmptyStateDataSource } set { if let newValue = newValue { objc_setAssociatedObject(self, &AssociatedKeys.emptyStateDataSource, newValue, .OBJC_ASSOCIATION_ASSIGN) self.reloadEmptyState() } } } }
93ddf40006cc7fa0a7f60bb48752e29b
32.045977
127
0.684522
false
false
false
false
KBryan/SwiftFoundation
refs/heads/develop
SwiftFoundation/SwiftFoundationTests/POSIXTimeTests.swift
mit
1
// // POSIXTimeTests.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 7/22/15. // Copyright © 2015 PureSwift. All rights reserved. // import XCTest import SwiftFoundation class POSIXTimeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testGetTimeOfDay() { do { try timeval.timeOfDay() } catch { XCTFail("Error getting time: \(error)") } } func testTimeVal() { let date = Date() let time = timeval(timeInterval: date.timeIntervalSince1970) XCTAssert(Int(time.timeIntervalValue) == Int(date.timeIntervalSince1970), "TimeVal derived interval: \(time.timeIntervalValue) must equal Date's timeIntervalSince1970 \(date.timeIntervalSince1970)") } func testStaticTimeVal() { let date = Date() let time = timeval(timeInterval: 123456.7898) //XCTAssert(Int(time.timeIntervalValue) == Int(date.timeIntervalSince1970), "TimeVal derived interval: \(time.timeIntervalValue) must equal original constant") } func testTimeSpec() { let date = Date() let time = timespec(timeInterval: date.timeIntervalSince1970) XCTAssert(time.timeIntervalValue == date.timeIntervalSince1970) } }
2e0d58ab9beea597155cf0b624738eb9
26.866667
206
0.619019
false
true
false
false
huangboju/Moots
refs/heads/master
Examples/UIScrollViewDemo/UIScrollViewDemo/ExpandingCollectionView/UltravisualLayout.swift
mit
1
// // UltravisualLayout.swift // ExpandingCollectionView // // Created by Vamshi Krishna on 30/04/17. // Copyright © 2017 VamshiKrishna. All rights reserved. // import UIKit /* The heights are declared as constants outside of the class so they can be easily referenced elsewhere */ struct UltravisualLayoutConstants { struct Cell { /* The height of the non-featured cell */ static let standardHeight: CGFloat = 100 /* The height of the first visible cell */ static let featuredHeight: CGFloat = 280 } } class UltravisualLayout: UICollectionViewFlowLayout { // MARK: Properties and Variables /* The amount the user needs to scroll before the featured cell changes */ let dragOffset: CGFloat = 180.0 var cache = [UICollectionViewLayoutAttributes]() /* Returns the item index of the currently featured cell */ var featuredItemIndex: Int { get { /* Use max to make sure the featureItemIndex is never < 0 */ return max(0, Int(collectionView!.contentOffset.y / dragOffset)) } } /* Returns a value between 0 and 1 that represents how close the next cell is to becoming the featured cell */ var nextItemPercentageOffset: CGFloat { get { return (collectionView!.contentOffset.y / dragOffset) - CGFloat(featuredItemIndex) } } /* Returns the width of the collection view */ var width: CGFloat { get { return collectionView!.bounds.width } } /* Returns the height of the collection view */ var height: CGFloat { get { return collectionView!.bounds.height } } /* Returns the number of items in the collection view */ var numberOfItems: Int { get { return collectionView!.numberOfItems(inSection: 0) } } // MARK: UICollectionViewLayout /* Return the size of all the content in the collection view */ override var collectionViewContentSize: CGSize { let contentHeight = (CGFloat(numberOfItems) * dragOffset) + (height - dragOffset) return CGSize(width: width, height: contentHeight) } override func prepare() { cache.removeAll(keepingCapacity: false) let standardHeight = UltravisualLayoutConstants.Cell.standardHeight let featuredHeight = UltravisualLayoutConstants.Cell.featuredHeight var frame = CGRect.zero var y: CGFloat = 0 for item in 0 ..< numberOfItems { // 1 let indexPath = IndexPath(item: item, section: 0) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) // 2 attributes.zIndex = item var height = standardHeight // 3 if indexPath.item == featuredItemIndex { // 4 let yOffset = standardHeight * nextItemPercentageOffset y = collectionView!.contentOffset.y - yOffset height = featuredHeight } else if indexPath.item == (featuredItemIndex + 1) && indexPath.item != numberOfItems { // 5 let maxY = y + standardHeight height = standardHeight + max((featuredHeight - standardHeight) * nextItemPercentageOffset, 0) y = maxY - height } // 6 frame = CGRect(x: collectionView!.contentInset.left, y: y, width: width, height: height) attributes.frame = frame cache.append(attributes) y = frame.maxY } } /* Return all attributes in the cache whose frame intersects with the rect passed to the method */ override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return cache.filter { $0.frame.intersects(rect) } } /* Return true so that the layout is continuously invalidated as the user scrolls */ override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { let itemIndex = round(proposedContentOffset.y / dragOffset) let yOffset = itemIndex * dragOffset return CGPoint(x: 0, y: yOffset) } }
1ccf8006c27bb27fd4bf9f3ffa0760d6
33.80315
148
0.632805
false
false
false
false
laonayt/NewFreshBeen-Swift
refs/heads/master
WEFreshBeen/Classes/Other/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // WEFreshBeen // // Created by 马玮 on 16/5/26. // Copyright © 2016年 马玮. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() let isFirstOpen = NSUserDefaults.standardUserDefaults().objectForKey("isFirst") if isFirstOpen == nil { window?.rootViewController = GuidViewController() NSUserDefaults.standardUserDefaults().setObject("haveOpen", forKey: "isFirst") } else { let adViewController = ADViewController() adViewController.view.layoutIfNeeded() adViewController.imageStr = "http://img01.bqstatic.com/upload/activity/2016011111271995.jpg" window?.rootViewController = adViewController } window?.makeKeyAndVisible() return true } func turnToMainTabViewController() { window?.rootViewController = WETabBarViewController() } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
eb21939557987f7aa9f1c253585461b9
42.397059
285
0.715351
false
false
false
false
iAugux/Zoom-Contacts
refs/heads/master
Phonetic/Extensions/TopMostViewController+Extension.swift
mit
1
// // TopMostViewController.swift // // Created by Augus on 9/26/15. // Copyright © 2015 iAugus. All rights reserved. // import UIKit /** Description: the toppest view controller of presenting view controller How to use: UIApplication.topMostViewController Where to use: controllers are not complex */ extension UIApplication { class var topMostViewController: UIViewController? { var topController = UIApplication.sharedApplication().keyWindow?.rootViewController while topController?.presentedViewController != nil { topController = topController?.presentedViewController } return topController } /// App has more than one window and just want to get topMostViewController of the AppDelegate window. class var appDelegateWindowTopMostViewController: UIViewController? { let delegate = UIApplication.sharedApplication().delegate as? AppDelegate var topController = delegate?.window?.rootViewController while topController?.presentedViewController != nil { topController = topController?.presentedViewController } return topController } } /** Description: the toppest view controller of presenting view controller How to use: UIApplication.sharedApplication().keyWindow?.rootViewController?.topMostViewController Where to use: There are lots of kinds of controllers (UINavigationControllers, UITabbarControllers, UIViewController) */ extension UIViewController { var topMostViewController: UIViewController? { // Handling Modal views if let presentedViewController = self.presentedViewController { return presentedViewController.topMostViewController } // Handling UIViewController's added as subviews to some other views. else { for view in self.view.subviews { // Key property which most of us are unaware of / rarely use. if let subViewController = view.nextResponder() { if subViewController is UIViewController { let viewController = subViewController as! UIViewController return viewController.topMostViewController } } } return self } } } extension UITabBarController { override var topMostViewController: UIViewController? { return self.selectedViewController?.topMostViewController } } extension UINavigationController { override var topMostViewController: UIViewController? { return self.visibleViewController?.topMostViewController } }
68e707b86c718027af9bea3d7372fd5b
33.818182
118
0.691045
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripePayments/StripePayments/API Bindings/Models/SetupIntents/STPSetupIntentConfirmParams.swift
mit
1
// // STPSetupIntentConfirmParams.swift // StripePayments // // Created by Yuki Tokuhiro on 6/27/19. // Copyright © 2019 Stripe, Inc. All rights reserved. // import Foundation /// An object representing parameters to confirm a SetupIntent object. /// For example, you would confirm a SetupIntent when a customer hits the “Save” button on a payment method management view in your app. /// If the selected payment method does not require any additional steps from the customer, the SetupIntent's status will transition to `STPSetupIntentStatusSucceeded`. Otherwise, it will transition to `STPSetupIntentStatusRequiresAction`, and suggest additional actions via `nextAction`. /// Instead of passing this to `STPAPIClient.confirmSetupIntent(...)` directly, we recommend using `STPPaymentHandler` to handle any additional steps for you. /// - seealso: https://stripe.com/docs/api/setup_intents/confirm public class STPSetupIntentConfirmParams: NSObject, NSCopying, STPFormEncodable { @objc public var additionalAPIParameters: [AnyHashable: Any] = [:] /// Initialize this `STPSetupIntentConfirmParams` with a `clientSecret`. /// - Parameter clientSecret: the client secret for this SetupIntent @objc public init( clientSecret: String ) { self.clientSecret = clientSecret super.init() additionalAPIParameters = [:] } /// Initialize this `STPSetupIntentConfirmParams` with a `clientSecret` and `paymentMethodType`. /// Use this initializer for SetupIntents that already have a PaymentMethod attached. /// - Parameter clientSecret: the client secret for this SetupIntent /// - Parameter paymentMethodType: the known type of the SetupIntent's attached PaymentMethod @objc public init( clientSecret: String, paymentMethodType: STPPaymentMethodType ) { self.clientSecret = clientSecret self._paymentMethodType = paymentMethodType super.init() additionalAPIParameters = [:] } /// The client secret of the SetupIntent. Required. @objc public var clientSecret: String /// Provide a supported `STPPaymentMethodParams` object, and Stripe will create a /// PaymentMethod during PaymentIntent confirmation. /// @note alternative to `paymentMethodId` @objc public var paymentMethodParams: STPPaymentMethodParams? /// Provide an already created PaymentMethod's id, and it will be used to confirm the SetupIntent. /// @note alternative to `paymentMethodParams` @objc public var paymentMethodID: String? /// The URL to redirect your customer back to after they authenticate or cancel /// their payment on the payment method’s app or site. /// This should probably be a URL that opens your iOS app. @objc public var returnURL: String? /// A boolean number to indicate whether you intend to use the Stripe SDK's functionality to handle any SetupIntent next actions. /// If set to false, STPSetupIntent.nextAction will only ever contain a redirect url that can be opened in a webview or mobile browser. /// When set to true, the nextAction may contain information that the Stripe SDK can use to perform native authentication within your /// app. @objc public var useStripeSDK: NSNumber? /// Details about the Mandate to create. /// @note If this value is null and the `(self.paymentMethod.type == STPPaymentMethodTypeSEPADebit | | self.paymentMethodParams.type == STPPaymentMethodTypeAUBECSDebit || self.paymentMethodParams.type == STPPaymentMethodTypeBacsDebit) && self.mandate == nil`, the SDK will set this to an internal value indicating that the mandate data should be inferred from the current context. @objc public var mandateData: STPMandateDataParams? { set(newMandateData) { _mandateData = newMandateData } get { if let _mandateData = _mandateData { return _mandateData } switch paymentMethodType { case .AUBECSDebit, .bacsDebit, .bancontact, .iDEAL, .SEPADebit, .EPS, .sofort, .link, .USBankAccount: // Create default infer from client mandate_data let onlineParams = STPMandateOnlineParams(ipAddress: "", userAgent: "") onlineParams.inferFromClient = NSNumber(value: true) if let customerAcceptance = STPMandateCustomerAcceptanceParams( type: .online, onlineParams: onlineParams ) { return STPMandateDataParams(customerAcceptance: customerAcceptance) } default: break } return nil } } private var _mandateData: STPMandateDataParams? internal var _paymentMethodType: STPPaymentMethodType? internal var paymentMethodType: STPPaymentMethodType? { if let type = _paymentMethodType { return type } return paymentMethodParams?.type } override convenience init() { // Not a valid clientSecret, but at least it'll be non-null self.init(clientSecret: "") } /// :nodoc: @objc public override var description: String { let props = [ // Object String(format: "%@: %p", NSStringFromClass(STPSetupIntentConfirmParams.self), self), // SetupIntentParams details (alphabetical) "clientSecret = \(((clientSecret.count) > 0) ? "<redacted>" : "")", "returnURL = \(returnURL ?? "")", "paymentMethodId = \(paymentMethodID ?? "")", "paymentMethodParams = \(String(describing: paymentMethodParams))", "useStripeSDK = \(useStripeSDK ?? 0)", // Mandate "mandateData = \(String(describing: mandateData))", // Additional params set by app "additionalAPIParameters = \(additionalAPIParameters )", ] return "<\(props.joined(separator: "; "))>" } // MARK: - NSCopying /// :nodoc: @objc public func copy(with zone: NSZone? = nil) -> Any { let copy = STPSetupIntentConfirmParams() copy.clientSecret = clientSecret copy._paymentMethodType = _paymentMethodType copy.paymentMethodParams = paymentMethodParams copy.paymentMethodID = paymentMethodID copy.returnURL = returnURL copy.useStripeSDK = useStripeSDK copy.mandateData = mandateData copy.additionalAPIParameters = additionalAPIParameters return copy } // MARK: - STPFormEncodable public class func rootObjectName() -> String? { return nil } public class func propertyNamesToFormFieldNamesMapping() -> [String: String] { return [ NSStringFromSelector(#selector(getter:clientSecret)): "client_secret", NSStringFromSelector(#selector(getter:paymentMethodParams)): "payment_method_data", NSStringFromSelector(#selector(getter:paymentMethodID)): "payment_method", NSStringFromSelector(#selector(getter:returnURL)): "return_url", NSStringFromSelector(#selector(getter:useStripeSDK)): "use_stripe_sdk", NSStringFromSelector(#selector(getter:mandateData)): "mandate_data", ] } // MARK: - Utilities static private let regex = try! NSRegularExpression( pattern: "^seti_[^_]+_secret_[^_]+$", options: [] ) @_spi(STP) public static func isClientSecretValid(_ clientSecret: String) -> Bool { return (regex.numberOfMatches( in: clientSecret, options: .anchored, range: NSRange(location: 0, length: clientSecret.count) )) == 1 } }
1a0eb06b92ef1ec07587c74f3ac2755c
43.942197
384
0.661608
false
false
false
false
LonelyHusky/SCWeibo
refs/heads/master
SCWeibo/Classes/View/Home/View/SCStatusToolBar.swift
mit
1
// // SCStatusToolBar.swift // SCWeibo // // Created by 云卷云舒丶 on 16/7/24. // // import UIKit class SCStatusToolBar: UIView { override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ // 添加控件 let retweetButton = addChildButton("转发", imgName: "timeline_icon_retweet") let commentButton = addChildButton("评论", imgName: "timeline_icon_comment") let likeButton = addChildButton("赞", imgName: "timeline_icon_unlike") let sp1 = UIImageView(image: UIImage(named: "timeline_card_bottom_line")) let sp2 = UIImageView(image: UIImage(named: "timeline_card_bottom_line")) addSubview(sp1);addSubview(sp2) // 添加约束 retweetButton.snp_makeConstraints { (make) in make.leading.top.bottom.equalTo(self) make.width.equalTo(commentButton) } commentButton.snp_makeConstraints { (make) in make.leading.equalTo(retweetButton.snp_trailing) make.top.bottom.equalTo(self) make.width.equalTo(likeButton) } likeButton.snp_makeConstraints { (make) in make.trailing.top.bottom.equalTo(self) make.leading.equalTo(commentButton.snp_trailing) make.width.equalTo(retweetButton ) } sp1.snp_makeConstraints { (make) in make.centerX.equalTo(retweetButton.snp_trailing) make.centerY.equalTo(self) } sp2.snp_makeConstraints { (make) in make.centerX.equalTo(commentButton.snp_trailing) make.centerY.equalTo(self) } } private func addChildButton(title: String ,imgName: String) -> UIButton{ let button = UIButton() button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) button.setTitle(title, forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "timeline_card_bottom_background"), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "timeline_card_bottom_background_highlighted"), forState: UIControlState.Highlighted) button.setImage(UIImage(named:imgName), forState: UIControlState.Normal) addSubview(button) return button } }
e830ad32c492094871bf983cd805cb13
33.15493
134
0.643711
false
false
false
false
dasdom/DHTweak
refs/heads/master
Tweaks/TweakStore.swift
mit
2
// // TweakStore.swift // TweaksDemo // // Created by dasdom on 22.08.14. // Copyright (c) 2014 Dominik Hauser. All rights reserved. // import Foundation private let _TweakStoreSharedInstance = TweakStore(name: "DefaultTweakStore") public class TweakStore { class var sharedTweakStore: TweakStore { return _TweakStoreSharedInstance } let name: String private var namedCategories = [String:TweakCategory]() init(name: String) { self.name = name } func allCategories() -> [TweakCategory] { var categories = [TweakCategory]() for (key, value) in namedCategories { categories.append(value) } return categories } func addCategory(category: TweakCategory) { namedCategories[category.name] = category } func removeCategory(category: TweakCategory) { namedCategories.removeValueForKey(category.name) } func removeAllCategories() { namedCategories = [String:TweakCategory]() } func categoryWithName(name: String) -> TweakCategory? { return namedCategories[name] } }
481d513cd2ab4a680b0212952ef74869
22.673469
77
0.639344
false
false
false
false
rahulsend89/MemoryGame
refs/heads/master
MemoryGame/BlockCVC.swift
mit
1
// // BlockCVC.swift // MemoryGame // // Created by Rahul Malik on 7/15/17. // Copyright © 2017 aceenvisage. All rights reserved. // import UIKit.UICollectionViewCell class BlockCVC: UICollectionViewCell { // MARK: - Properties @IBOutlet weak var frontImageView: UIImageView! @IBOutlet weak var backImageView: UIImageView! var block: Block? { didSet { guard let block = block else { return } frontImageView.image = block.image } } fileprivate(set) var shown: Bool = false // MARK: - Methods func showBlock(_ show: Bool, animted: Bool) { frontImageView.isHidden = false backImageView.isHidden = false shown = show if animted { if show { UIView.transition(from: backImageView, to: frontImageView, duration: 0.5, options: [.transitionFlipFromRight, .showHideTransitionViews], completion: { (_: Bool) -> Void in }) } else { UIView.transition(from: frontImageView, to: backImageView, duration: 0.5, options: [.transitionFlipFromRight, .showHideTransitionViews], completion: { (_: Bool) -> Void in }) } } else { if show { bringSubview(toFront: frontImageView) backImageView.isHidden = true } else { bringSubview(toFront: backImageView) frontImageView.isHidden = true } } } }
5432e0866c13cedbc0880d3d671bc52d
28.633333
96
0.490439
false
false
false
false
Hout/DateInRegion
refs/heads/master
Example/Tests/DateInRegionHashableTests.swift
mit
1
// // DateInRegionEquationsTests.swift // DateInRegion // // Created by Jeroen Houtzager on 07/11/15. // Copyright © 2015 CocoaPods. All rights reserved. // import Quick import Nimble import DateInRegion class DateInRegionHashableTests: QuickSpec { override func spec() { let netherlands = DateRegion(calendarID: NSCalendarIdentifierGregorian, timeZoneID: "CET", localeID: "nl_NL") let utc = DateRegion(calendarID: NSCalendarIdentifierGregorian, timeZoneID: "UTC", localeID: "en_UK") describe("DateInRegionHashable") { it("should return an equal hash for the same date reference") { let date1 = DateInRegion(year: 1999, month: 12, day: 31)! expect(date1.hashValue) == date1.hashValue } it("should return an equal hash for the same date value") { let date1 = DateInRegion(year: 1999, month: 12, day: 31)! let date2 = DateInRegion(year: 1999, month: 12, day: 31)! expect(date1.hashValue) == date2.hashValue } it("should return an unequal hash for a different date value") { let date1 = DateInRegion(year: 1999, month: 12, day: 31)! let date2 = DateInRegion(year: 1999, month: 12, day: 30)! expect(date1.hashValue) != date2.hashValue } it("should return an unequal hash for a different time zone value") { let date = NSDate() let date1 = DateInRegion(date: date, region: netherlands) let date2 = DateInRegion(date: date, region: utc) expect(date1.hashValue) != date2.hashValue } } } }
a6c739cc2ee3081adf975589e4c63e40
31.490909
117
0.576945
false
false
false
false
ozgur/TestApp
refs/heads/master
TestApp/Extensions/Rx/MKMapView+Rx.swift
gpl-3.0
1
// // MKMapView+Rx.swift // RxCocoa // // Created by Spiros Gerokostas on 04/01/16. // Copyright © 2016 Spiros Gerokostas. All rights reserved. // import MapKit import RxSwift import RxCocoa // MARK: RxMKMapViewDelegateProxy class RxMKMapViewDelegateProxy: DelegateProxy, MKMapViewDelegate, DelegateProxyType { class func currentDelegateFor(_ object: AnyObject) -> AnyObject? { let mapView: MKMapView = (object as? MKMapView)! return mapView.delegate } class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) { let mapView: MKMapView = (object as? MKMapView)! mapView.delegate = delegate as? MKMapViewDelegate } } // MARK: MKMapView extension Reactive where Base : MKMapView { /** Reactive wrapper for `delegate`. For more information take a look at `DelegateProxyType` protocol documentation. */ var delegate: DelegateProxy { return RxMKMapViewDelegateProxy.proxyForObject(base) } // MARK: Responding to Map Position Changes var regionWillChangeAnimated: ControlEvent<Bool> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:regionWillChangeAnimated:))) .map { a in return try castOrThrow(Bool.self, a[1]) } return ControlEvent(events: source) } var regionDidChangeAnimated: ControlEvent<Bool> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:regionDidChangeAnimated:))) .map { a in return try castOrThrow(Bool.self, a[1]) } return ControlEvent(events: source) } // MARK: Loading the Map Data var willStartLoadingMap: ControlEvent<Void>{ let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewWillStartLoadingMap(_:))) .mapToVoid() return ControlEvent(events: source) } var didFinishLoadingMap: ControlEvent<Void>{ let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewDidFinishLoadingMap(_:))) .mapToVoid() return ControlEvent(events: source) } var didFailLoadingMap: Observable<NSError>{ return delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewDidFailLoadingMap(_:withError:))) .map { a in return try castOrThrow(NSError.self, a[1]) } } // MARK: Responding to Rendering Events var willStartRenderingMap: ControlEvent<Void>{ let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewWillStartRenderingMap(_:))) .mapToVoid() return ControlEvent(events: source) } var didFinishRenderingMap: ControlEvent<Bool> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewDidFinishRenderingMap(_:fullyRendered:))) .map { a in return try castOrThrow(Bool.self, a[1]) } return ControlEvent(events: source) } // MARK: Tracking the User Location var willStartLocatingUser: ControlEvent<Void> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewWillStartLocatingUser(_:))) .mapToVoid() return ControlEvent(events: source) } var didStopLocatingUser: ControlEvent<Void> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewDidStopLocatingUser(_:))) .mapToVoid() return ControlEvent(events: source) } var didUpdateUserLocation: ControlEvent<MKUserLocation> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didUpdate:))) .map { a in return try castOrThrow(MKUserLocation.self, a[1]) } return ControlEvent(events: source) } var didUpdateUserRegion: ControlEvent<MKCoordinateRegion> { let source = didUpdateUserLocation .map { location -> MKCoordinateRegion in return MKCoordinateRegionMakeWithDistance(location.coordinate, 125.0) } return ControlEvent(events: source) } var didFailToLocateUserWithError: Observable<NSError> { return delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didFailToLocateUserWithError:))) .map { a in return try castOrThrow(NSError.self, a[1]) } } public var didChangeUserTrackingMode: ControlEvent<(mode: MKUserTrackingMode, animated: Bool)> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didChange:animated:))) .map { a in return (mode: try castOrThrow(Int.self, a[1]), animated: try castOrThrow(Bool.self, a[2])) } .map { (mode, animated) in return (mode: MKUserTrackingMode(rawValue: mode)!, animated: animated) } return ControlEvent(events: source) } // MARK: Responding to Annotation Views var didAddAnnotationViews: ControlEvent<[MKAnnotationView]> { let source = delegate .methodInvoked(#selector( (MKMapViewDelegate.mapView(_:didAdd:))! as (MKMapViewDelegate) -> (MKMapView, [MKAnnotationView]) -> Void ) ) .map { a in return try castOrThrow([MKAnnotationView].self, a[1]) } return ControlEvent(events: source) } var annotationViewCalloutAccessoryControlTapped: ControlEvent<(view: MKAnnotationView, control: UIControl)> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:annotationView:calloutAccessoryControlTapped:))) .map { a in return (view: try castOrThrow(MKAnnotationView.self, a[1]), control: try castOrThrow(UIControl.self, a[2])) } return ControlEvent(events: source) } // MARK: Selecting Annotation Views var didSelectAnnotationView: ControlEvent<MKAnnotationView> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didSelect:))) .map { a in return try castOrThrow(MKAnnotationView.self, a[1]) } return ControlEvent(events: source) } var didDeselectAnnotationView: ControlEvent<MKAnnotationView> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didDeselect:))) .map { a in return try castOrThrow(MKAnnotationView.self, a[1]) } return ControlEvent(events: source) } var didChangeState: ControlEvent<(view: MKAnnotationView, newState: MKAnnotationViewDragState, oldState: MKAnnotationViewDragState)> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:annotationView:didChange:fromOldState:))) .map { a in return (view: try castOrThrow(MKAnnotationView.self, a[1]), newState: try castOrThrow(UInt.self, a[2]), oldState: try castOrThrow(UInt.self, a[3])) } .map { (view, newState, oldState) in return (view: view, newState: MKAnnotationViewDragState(rawValue: newState)!, oldState: MKAnnotationViewDragState(rawValue: oldState)!) } return ControlEvent(events: source) } // MARK: Managing the Display of Overlays var didAddOverlayRenderers: ControlEvent<[MKOverlayRenderer]> { let source = delegate .methodInvoked(#selector( (MKMapViewDelegate.mapView(_:didAdd:))! as (MKMapViewDelegate) -> (MKMapView, [MKOverlayRenderer]) -> Void ) ) .map { a in return try castOrThrow([MKOverlayRenderer].self, a[1]) } return ControlEvent(events: source) } var userLocation: Observable<MKUserLocation?> { return observeWeakly(MKUserLocation.self, "userLocation") } } extension Reactive where Base: MKMapView { var showUserLocation: UIBindingObserver<Base, Bool> { return UIBindingObserver(UIElement: base) { mapView, showsUserLocation in mapView.showsUserLocation = showsUserLocation } } }
84a14fa0216b334550b0ef0aeb16fb91
30.353414
118
0.686563
false
false
false
false
grpc/grpc-swift
refs/heads/main
Sources/GRPC/AsyncAwaitSupport/GRPCClient+AsyncAwaitSupport.swift
apache-2.0
1
/* * Copyright 2021, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if compiler(>=5.6) import SwiftProtobuf @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension GRPCClient { public func makeAsyncUnaryCall<Request: Message & Sendable, Response: Message & Sendable>( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncUnaryCall<Request, Response> { return self.channel.makeAsyncUnaryCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncUnaryCall<Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable>( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncUnaryCall<Request, Response> { return self.channel.makeAsyncUnaryCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncServerStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncServerStreamingCall<Request, Response> { return self.channel.makeAsyncServerStreamingCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncServerStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncServerStreamingCall<Request, Response> { return self.channel.makeAsyncServerStreamingCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncClientStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable >( path: String, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncClientStreamingCall<Request, Response> { return self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncClientStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncClientStreamingCall<Request, Response> { return self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncBidirectionalStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable >( path: String, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncBidirectionalStreamingCall<Request, Response> { return self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncBidirectionalStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncBidirectionalStreamingCall<Request, Response> { return self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } } // MARK: - "Simple, but safe" wrappers. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension GRPCClient { public func performAsyncUnaryCall<Request: Message & Sendable, Response: Message & Sendable>( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) async throws -> Response { let call = self.channel.makeAsyncUnaryCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await withTaskCancellationHandler { try await call.response } onCancel: { call.cancel() } } public func performAsyncUnaryCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) async throws -> Response { let call = self.channel.makeAsyncUnaryCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await withTaskCancellationHandler { try await call.response } onCancel: { call.cancel() } } public func performAsyncServerStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> { return self.channel.makeAsyncServerStreamingCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ).responseStream } public func performAsyncServerStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> { return self.channel.makeAsyncServerStreamingCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ).responseStream } public func performAsyncClientStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable, RequestStream: AsyncSequence & Sendable >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) async throws -> Response where RequestStream.Element == Request { let call = self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await self.perform(call, with: requests) } public func performAsyncClientStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable, RequestStream: AsyncSequence & Sendable >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) async throws -> Response where RequestStream.Element == Request { let call = self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await self.perform(call, with: requests) } public func performAsyncClientStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable, RequestStream: Sequence >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) async throws -> Response where RequestStream.Element == Request { let call = self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await self.perform(call, with: AsyncStream(wrapping: requests)) } public func performAsyncClientStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable, RequestStream: Sequence >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) async throws -> Response where RequestStream.Element == Request { let call = self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await self.perform(call, with: AsyncStream(wrapping: requests)) } public func performAsyncBidirectionalStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable, RequestStream: AsyncSequence & Sendable >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { let call = self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return self.perform(call, with: requests) } public func performAsyncBidirectionalStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable, RequestStream: AsyncSequence & Sendable >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { let call = self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return self.perform(call, with: requests) } public func performAsyncBidirectionalStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable, RequestStream: Sequence >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { let call = self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return self.perform(call, with: AsyncStream(wrapping: requests)) } public func performAsyncBidirectionalStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable, RequestStream: Sequence >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { let call = self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return self.perform(call, with: AsyncStream(wrapping: requests)) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension GRPCClient { @inlinable internal func perform< Request: Sendable, Response: Sendable, RequestStream: AsyncSequence & Sendable >( _ call: GRPCAsyncClientStreamingCall<Request, Response>, with requests: RequestStream ) async throws -> Response where RequestStream.Element == Request { return try await withTaskCancellationHandler { Task { do { // `AsyncSequence`s are encouraged to co-operatively check for cancellation, and we will // cancel the call `onCancel` anyway, so there's no need to check here too. for try await request in requests { try await call.requestStream.send(request) } call.requestStream.finish() } catch { // If we throw then cancel the call. We will rely on the response throwing an appropriate // error below. call.cancel() } } return try await call.response } onCancel: { call.cancel() } } @inlinable internal func perform< Request: Sendable, Response: Sendable, RequestStream: AsyncSequence & Sendable >( _ call: GRPCAsyncBidirectionalStreamingCall<Request, Response>, with requests: RequestStream ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { Task { do { try await withTaskCancellationHandler { // `AsyncSequence`s are encouraged to co-operatively check for cancellation, and we will // cancel the call `onCancel` anyway, so there's no need to check here too. for try await request in requests { try await call.requestStream.send(request) } call.requestStream.finish() } onCancel: { call.cancel() } } catch { call.cancel() } } return call.responseStream } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension AsyncStream { /// Create an `AsyncStream` from a regular (non-async) `Sequence`. /// /// - Note: This is just here to avoid duplicating the above two `perform(_:with:)` functions /// for `Sequence`. fileprivate init<T>(wrapping sequence: T) where T: Sequence, T.Element == Element { self.init { continuation in var iterator = sequence.makeIterator() while let value = iterator.next() { continuation.yield(value) } continuation.finish() } } } #endif
54ab7471f180bde15956a1b126343280
32.569072
100
0.699404
false
false
false
false
Syerram/asphalos
refs/heads/master
asphalos/FormPickerCell.swift
mit
1
// // FormPickerCell.swift // SwiftForms // // Created by Miguel Angel Ortuno on 22/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit class FormPickerCell: FormValueCell, UIPickerViewDelegate, UIPickerViewDataSource { /// MARK: Properties private let picker = UIPickerView() private let hiddenTextField = UITextField(frame: CGRectZero) /// MARK: FormBaseCell override func configure() { super.configure() accessoryType = .None picker.delegate = self picker.dataSource = self hiddenTextField.inputView = picker contentView.addSubview(hiddenTextField) } override func update() { super.update() titleLabel.text = rowDescriptor.title if rowDescriptor.value != nil { valueLabel.text = rowDescriptor.titleForOptionValue(rowDescriptor.value) } } override class func formViewController(formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { if selectedRow.rowDescriptor.value == nil { if let row = selectedRow as? FormPickerCell { let optionValue = selectedRow.rowDescriptor.options[0] as? NSObject selectedRow.rowDescriptor.value = optionValue row.valueLabel.text = selectedRow.rowDescriptor.titleForOptionValue(optionValue!) row.hiddenTextField.becomeFirstResponder() } } else { if let row = selectedRow as? FormPickerCell { let optionValue = selectedRow.rowDescriptor.value row.valueLabel.text = selectedRow.rowDescriptor.titleForOptionValue(optionValue) row.hiddenTextField.becomeFirstResponder() } } } /// MARK: UIPickerViewDelegate func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return rowDescriptor.titleForOptionAtIndex(row) } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let optionValue = rowDescriptor.options[row] as? NSObject rowDescriptor.value = optionValue valueLabel.text = rowDescriptor.titleForOptionValue(optionValue!) } /// MARK: UIPickerViewDataSource func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return rowDescriptor.options.count } }
e8ee5219a5a1d3aa597af8f7a001ba9f
32.125
124
0.655472
false
false
false
false
kissybnts/v-project
refs/heads/develop
Sources/App/MarkDown/Relations/TagNoteRelation.swift
mit
1
import Vapor import FluentProvider import HTTP final class TagNoteRelation: Model { let storage = Storage() static let entity = "tag_note" let tagId: Identifier let noteId: Identifier internal struct Properties { internal static let id = PropertyKey.id internal static let tagId = Tag.foreinIdKey internal static let noteId = Note.foreinIdKey } init(tagId: Identifier, noteId: Identifier) { self.tagId = tagId self.noteId = noteId } convenience init(tag: Tag, note: Note) throws { guard let tagId = tag.id else { throw Abort.serverError } guard let noteId = note.id else { throw Abort.serverError } self.init(tagId: tagId, noteId: noteId) } init(row: Row) throws { tagId = try row.get(Properties.tagId) noteId = try row.get(Properties.noteId) } func makeRow() throws -> Row { var row = Row() try row.set(Properties.tagId, tagId) try row.set(Properties.noteId, noteId) return row } } extension TagNoteRelation: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.foreignId(for: Tag.self) builder.foreignId(for: Note.self) } } static func revert(_ database: Database) throws { try database.delete(self) } } extension TagNoteRelation: Timestampable {} extension TagNoteRelation { internal static func delteAllByTag(tag: Tag) throws -> Void { guard let tagId = tag.id else { return } try TagNoteRelation.makeQuery().filter(Properties.tagId, tagId).delete() } internal static func deleteAllByNote(note: Note) throws -> Void { guard let noteId = note.id else { return } try TagNoteRelation.makeQuery().filter(Properties.noteId, noteId).delete() } internal static func deleteAllByUserId(userId: Identifier) throws -> Void { try TagNoteRelation.database?.raw("DELETE `tag_note` from `tag_note` INNER JOIN `notes` ON `tag_note`.`note_id` = `notes`.`id` INNER JOIN `users` ON `notes`.`user_id` = `users`.`id` WHERE `users`.`id` = ?", [userId]) } }
27ee7db5ddc6fce0049a5c2706df046a
28.3
224
0.611348
false
false
false
false
gongmingqm10/DriftBook
refs/heads/master
DriftReading/DriftReading/DiscoveryViewController.swift
mit
1
// // DiscoveryViewController.swift // DriftReading // // Created by Ming Gong on 7/7/15. // Copyright © 2015 gongmingqm10. All rights reserved. // import UIKit class DiscoveryViewController: UITableViewController { let driftAPI = DriftAPI() @IBOutlet var booksTableView: UITableView! var books: [Book] = [] let TYPE_DRIFTING = "drifting" let TYPE_READING = "reading" var selectedBook: Book? var currentType: String? override func viewDidLoad() { currentType = TYPE_DRIFTING } override func viewDidAppear(animated: Bool) { loadBooksByType() } private func loadBooksByType() { driftAPI.getBooks(currentType!, success: { (books) -> Void in self.books = books self.booksTableView.reloadData() }) { (error) -> Void in print(error.description) } } @IBAction func switchSegment(sender: UISegmentedControl) { currentType = sender.selectedSegmentIndex == 0 ? TYPE_DRIFTING : TYPE_READING loadBooksByType() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "BookDetailSegue" { let bookDetailController = segue.destinationViewController as! BookDetailViewController bookDetailController.bookId = selectedBook!.id } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return books.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.selectedBook = books[indexPath.row] self.performSegueWithIdentifier("BookDetailSegue", sender: self) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 150 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = booksTableView.dequeueReusableCellWithIdentifier("BookTableCell", forIndexPath: indexPath) as! BookTableCell let book = books[indexPath.row] cell.populate(book) return cell } }
5e2c82ad0fb0d01953d2c43e3ee39609
30.30137
127
0.661269
false
false
false
false
ldjhust/CircleBom
refs/heads/master
CircleBom/Circle.swift
mit
1
// // Circle.swift // CircleBom // // Created by ldjhust on 15/11/26. // Copyright © 2015年 ldj. All rights reserved. // import UIKit class Circle: UIView { var initialFrame = CGRectZero var progress:CGFloat = 0.5 override func drawRect(rect: CGRect) { // 获取当前画布 let offset = initialFrame.width / 3.6 let moveDistance = (initialFrame.width * 1 / 5) * CGFloat(fabs(progress - 0.5) * 2) NSLog ("%f", moveDistance) let originCenter = CGPoint(x: initialFrame.origin.x + initialFrame.width/2, y: initialFrame.origin.y + initialFrame.height/2) let pointA = CGPoint(x: originCenter.x, y: originCenter.y - initialFrame.height/2 + moveDistance) let pointB = CGPoint(x: originCenter.x + initialFrame.width/2, y: originCenter.y) let pointC = CGPoint(x: originCenter.x, y: originCenter.y + initialFrame.height/2 - moveDistance) let pointD = CGPoint(x: originCenter.x - initialFrame.width/2 - moveDistance, y: originCenter.y) let c1 = CGPoint(x: pointA.x + offset, y: pointA.y) let c2 = CGPoint(x: pointB.x, y: pointB.y - offset) let c3 = CGPoint(x: pointB.x, y: pointB.y + offset) let c4 = CGPoint(x: pointC.x + offset, y: pointC.y) let c5 = CGPoint(x: pointC.x - offset, y: pointC.y) let c6 = CGPoint(x: pointD.x, y: pointD.y + offset - moveDistance) let c7 = CGPoint(x: pointD.x, y: pointD.y - offset + moveDistance) let c8 = CGPoint(x: pointA.x - offset, y: pointA.y) let bezierPath = UIBezierPath() // 设置填充颜色 UIColor.redColor().setFill() // 开始画 bezierPath.moveToPoint(pointA) bezierPath.addCurveToPoint(pointB, controlPoint1: c1, controlPoint2: c2) bezierPath.addCurveToPoint(pointC, controlPoint1: c3, controlPoint2: c4) bezierPath.addCurveToPoint(pointD, controlPoint1: c5, controlPoint2: c6) bezierPath.addCurveToPoint(pointA, controlPoint1: c7, controlPoint2: c8) bezierPath.closePath() // 开始填充 bezierPath.fill() } }
02b01797caa131a38a18e4d3cd94bb4e
35.509091
101
0.664343
false
false
false
false
lucasharding/antenna
refs/heads/master
tvOS/Controllers/GuideChannelCollectionViewHeader.swift
gpl-3.0
1
// // GuideChannelCollectionViewHeader.swift // ustvnow-tvos // // Created by Lucas Harding on 2015-09-11. // Copyright © 2015 Lucas Harding. All rights reserved. // import UIKit open class GuideChannelCollectionViewHeader : UICollectionReusableView { var imageView: UIImageView! public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } internal func commonInit() { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(imageView) self.imageView = imageView addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1.0, constant: 0.0)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-30-|", options: [], metrics: nil, views: ["imageView": imageView])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[imageView]-20-|", options: [], metrics: nil, views: ["imageView": imageView])) } } open class GuideChannelCollectionViewBackground : UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } internal func commonInit() { let view = UIVisualEffectView(frame: self.bounds) view.effect = UIBlurEffect(style: .dark) view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] self.addSubview(view) } }
ce9ccd64db1f647eb4eefd2f0aae81ae
31.189655
167
0.674879
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AAAuthOTPViewController.swift
agpl-3.0
2
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import MessageUI public class AAAuthOTPViewController: AAAuthViewController, MFMailComposeViewControllerDelegate { private static let DIAL_SECONDS: Int = 60 let scrollView = UIScrollView() let welcomeLabel = UILabel() let validateLabel = UILabel() let hintLabel = UILabel() let codeField = UITextField() let codeFieldLine = UIView() let haventReceivedCode = UIButton() let transactionHash: String let name: String! let email: String! let phone: String! private var counterTimer: NSTimer! private var dialed: Bool = false private var counter = AAAuthOTPViewController.DIAL_SECONDS public init(email: String, transactionHash: String) { self.transactionHash = transactionHash self.name = nil self.email = email self.phone = nil super.init() } public init(email: String, name: String, transactionHash: String) { self.transactionHash = transactionHash self.name = name self.email = email self.phone = nil super.init() } public init(phone: String, transactionHash: String) { self.transactionHash = transactionHash self.name = nil self.email = nil self.phone = phone super.init() } public init(phone: String, name: String, transactionHash: String) { self.transactionHash = transactionHash self.name = name self.email = nil self.phone = phone super.init() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { view.backgroundColor = UIColor.whiteColor() scrollView.keyboardDismissMode = .OnDrag scrollView.scrollEnabled = true scrollView.alwaysBounceVertical = true welcomeLabel.font = UIFont.lightSystemFontOfSize(23) if email != nil { welcomeLabel.text = AALocalized("AuthOTPEmailTitle") } else { welcomeLabel.text = AALocalized("AuthOTPPhoneTitle") } welcomeLabel.textColor = ActorSDK.sharedActor().style.authTitleColor welcomeLabel.textAlignment = .Center validateLabel.font = UIFont.systemFontOfSize(14) if email != nil { validateLabel.text = email } else { validateLabel.text = phone } validateLabel.textColor = ActorSDK.sharedActor().style.authTintColor validateLabel.textAlignment = .Center hintLabel.font = UIFont.systemFontOfSize(14) if email != nil { hintLabel.text = AALocalized("AuthOTPEmailHint") } else { hintLabel.text = AALocalized("AuthOTPPhoneHint") } hintLabel.textColor = ActorSDK.sharedActor().style.authHintColor hintLabel.textAlignment = .Center hintLabel.numberOfLines = 2 hintLabel.lineBreakMode = .ByWordWrapping codeField.font = UIFont.systemFontOfSize(17) codeField.textColor = ActorSDK.sharedActor().style.authTextColor codeField.placeholder = AALocalized("AuthOTPPlaceholder") codeField.keyboardType = .NumberPad codeField.autocapitalizationType = .None codeField.autocorrectionType = .No codeFieldLine.backgroundColor = ActorSDK.sharedActor().style.authSeparatorColor if ActorSDK.sharedActor().supportEmail != nil { haventReceivedCode.setTitle(AALocalized("AuthOTPNoCode"), forState: .Normal) } else { haventReceivedCode.hidden = true } haventReceivedCode.titleLabel?.font = UIFont.systemFontOfSize(14) haventReceivedCode.setTitleColor(ActorSDK.sharedActor().style.authTintColor, forState: .Normal) haventReceivedCode.setTitleColor(ActorSDK.sharedActor().style.authTintColor.alpha(0.64), forState: .Highlighted) haventReceivedCode.setTitleColor(ActorSDK.sharedActor().style.authHintColor, forState: .Disabled) haventReceivedCode.addTarget(self, action: #selector(AAAuthOTPViewController.haventReceivedCodeDidPressed), forControlEvents: .TouchUpInside) scrollView.addSubview(welcomeLabel) scrollView.addSubview(validateLabel) scrollView.addSubview(hintLabel) scrollView.addSubview(codeField) scrollView.addSubview(codeFieldLine) scrollView.addSubview(haventReceivedCode) view.addSubview(scrollView) super.viewDidLoad() } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() welcomeLabel.frame = CGRectMake(15, 90 - 66, view.width - 30, 28) validateLabel.frame = CGRectMake(10, 127 - 66, view.width - 20, 17) hintLabel.frame = CGRectMake(10, 154 - 66, view.width - 20, 56) codeField.frame = CGRectMake(20, 228 - 66, view.width - 40, 44) codeFieldLine.frame = CGRectMake(10, 228 + 44 - 66, view.width - 20, 0.5) haventReceivedCode.frame = CGRectMake(20, 297 - 66, view.width - 40, 56) scrollView.frame = view.bounds scrollView.contentSize = CGSizeMake(view.width, 240 - 66) } func haventReceivedCodeDidPressed() { if ActorSDK.sharedActor().supportEmail != nil { if self.email != nil { let emailController = MFMailComposeViewController() emailController.setSubject("Activation code problem (\(self.email))") emailController.setToRecipients([ActorSDK.sharedActor().supportEmail!]) emailController.setMessageBody("Hello, Dear Support!\n\nI can't receive any activation codes to the email: \(self.email).\n\nHope, you will answer soon. Thank you!", isHTML: false) emailController.delegate = self self.presentElegantViewController(emailController) } else if self.phone != nil { let emailController = MFMailComposeViewController() emailController.setSubject("Activation code problem (\(self.phone))") emailController.setToRecipients([ActorSDK.sharedActor().supportEmail!]) emailController.setMessageBody("Hello, Dear Support!\n\nI can't receive any activation codes to the phone: \(self.phone).\n\nHope, you will answer soon. Thank you!", isHTML: false) emailController.delegate = self self.presentElegantViewController(emailController) } } } public func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } public override func nextDidTap() { let code = codeField.text!.trim() if code.length == 0 { shakeField() return } let promise = Actor.doValidateCode(code, withTransaction: self.transactionHash) .startUserAction(["EMAIL_CODE_INVALID", "PHONE_CODE_INVALID", "EMAIL_CODE_EXPIRED", "PHONE_CODE_EXPIRED"]) promise.then { (r: ACAuthCodeRes!) -> () in if r.needToSignup { if self.name == nil { self.navigateNext(AAAuthNameViewController(transactionHash: r.transactionHash)) } else { let promise = Actor.doSignupWithName(self.name, withSex: ACSex.UNKNOWN(), withTransaction: r.transactionHash) promise.then { (r: ACAuthRes!) -> () in Actor.doCompleteAuth(r).startUserAction().then { (r: JavaLangBoolean!) -> () in self.codeField.resignFirstResponder() self.onAuthenticated() } } promise.startUserAction() } } else { Actor.doCompleteAuth(r.result).startUserAction().then { (r: JavaLangBoolean!) -> () in self.codeField.resignFirstResponder() self.onAuthenticated() } } } promise.failure { (e: JavaLangException!) -> () in if let rpc = e as? ACRpcException { if rpc.tag == "EMAIL_CODE_INVALID" || rpc.tag == "PHONE_CODE_INVALID" { self.shakeField() } else if rpc.tag == "EMAIL_CODE_EXPIRED" || rpc.tag == "PHONE_CODE_EXPIRED" { AAExecutions.errorWithTag(rpc.tag, rep: nil, cancel: { () -> () in self.navigateBack() }) } } } } private func shakeField() { shakeView(codeField, originalX: 20) shakeView(codeFieldLine, originalX: 10) } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.phone != nil { updateTimerText() if !dialed { counterTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(AAAuthOTPViewController.updateTimer), userInfo: nil, repeats: true) } } } func updateTimer() { counter -= 1 if counter == 0 { dialed = true if counterTimer != nil { counterTimer.invalidate() counterTimer = nil } Actor.doSendCodeViaCall(self.transactionHash) } updateTimerText() } func updateTimerText() { if dialed { if ActorSDK.sharedActor().supportEmail != nil { haventReceivedCode.setTitle(AALocalized("AuthOTPNoCode"), forState: .Normal) haventReceivedCode.hidden = false haventReceivedCode.enabled = true } else { haventReceivedCode.hidden = true } } else { let min = counter / 60 let sec = counter % 60 let minFormatted = min.format("02") let secFormatted = sec.format("02") let time = "\(minFormatted):\(secFormatted)" let text = AALocalized("AuthOTPCallHint") .replace("{app_name}", dest: ActorSDK.sharedActor().appName) .replace("{time}", dest: time) haventReceivedCode.setTitle(text, forState: .Normal) haventReceivedCode.enabled = false haventReceivedCode.hidden = false } } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if counterTimer != nil { counterTimer.invalidate() counterTimer = nil } self.codeField.resignFirstResponder() } }
ba3a5b0e4539863186e9b25c070de842
37.040956
196
0.596896
false
false
false
false
frootloops/swift
refs/heads/master
test/SILGen/downcast_reabstraction.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s // CHECK-LABEL: sil hidden @_T022downcast_reabstraction19condFunctionFromAnyyypF // CHECK: checked_cast_addr_br take_always Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed (@in ()) -> @out (), [[YES:bb[0-9]+]], [[NO:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]] // CHECK: [[REABSTRACT:%.*]] = function_ref @_T0ytytIegir_Ieg_TR // CHECK: [[SUBST_VAL:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[ORIG_VAL]]) func condFunctionFromAny(_ x: Any) { if let f = x as? () -> () { f() } } // CHECK-LABEL: sil hidden @_T022downcast_reabstraction21uncondFunctionFromAnyyypF : $@convention(thin) (@in Any) -> () { // CHECK: unconditional_checked_cast_addr Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed (@in ()) -> @out () // CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]] // CHECK: [[REABSTRACT:%.*]] = function_ref @_T0ytytIegir_Ieg_TR // CHECK: [[SUBST_VAL:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[ORIG_VAL]]) // CHECK: [[BORROW:%.*]] = begin_borrow [[SUBST_VAL]] // CHECK: apply [[BORROW]]() // CHECK: end_borrow [[BORROW]] from [[SUBST_VAL]] // CHECK: destroy_value [[SUBST_VAL]] func uncondFunctionFromAny(_ x: Any) { (x as! () -> ())() }
adfe0a4836dcfc5e600f676b31158a96
52.851852
181
0.550206
false
false
false
false
andrea-prearo/SwiftExamples
refs/heads/master
RegionMonitor/RegionMonitor/RegionNotificationsTableViewController.swift
mit
1
// // RegionNotificationsTableViewController.swift // RegionMonitor // // Created by Andrea Prearo on 5/24/15. // Copyright (c) 2015 Andrea Prearo. All rights reserved. // import UIKit let RegionNotificationsTableViewCellId = "RegionNotificationsTableViewCell" class RegionNotificationsTableViewController: UITableViewController { var regionNotifications: [RegionNotification]? override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Region Notifications", comment: "Region Notifications") regionNotifications = RegionNotificationsStore.sharedInstance.storedItems regionNotifications?.sort(by: { $0.timestamp.timeIntervalSince1970 > $1.timestamp.timeIntervalSince1970 }) NotificationCenter.default.addObserver(self, selector: #selector(RegionNotificationsTableViewController.regionNotificationsItemsDidChange(_:)), name: NSNotification.Name(rawValue: RegionNotificationItemsDidChangeNotification), object: nil) } // MARK: UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if regionNotifications != nil { return regionNotifications!.count } return 0 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 66.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: RegionNotificationsTableViewCellId, for: indexPath) as! RegionNotificationCell let row = (indexPath as NSIndexPath).row let regionNotification = regionNotifications?[row] cell.timestamp.text = regionNotification?.displayTimestamp() cell.status.text = regionNotification?.displayAppStatus() cell.message.text = regionNotification?.message cell.event.text = regionNotification?.displayEvent() return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: regionNotifications?.remove(at: (indexPath as NSIndexPath).row) tableView.deleteRows(at: [indexPath], with: .fade) default: return } } // MARK: NSNotificationCenter Events @objc func regionNotificationsItemsDidChange(_ notification: Notification) { regionNotifications = RegionNotificationsStore.sharedInstance.storedItems regionNotifications?.sort(by: { $0.timestamp.timeIntervalSince1970 > $1.timestamp.timeIntervalSince1970 }) DispatchQueue.main.async { self.tableView.reloadData() } } }
337b64935c2f8198869bb737cbe53318
37.213333
143
0.712142
false
false
false
false
inamiy/VTree
refs/heads/master
Tests/Fixtures/VPhantom.swift
mit
1
import VTree import Flexbox /// Phantom type for `VTree` without `Message` type (for testing). public final class VPhantom<👻>: VTree { public let key: Key? public let props: [String: Any] = [:] // NOTE: `Segmentation fault: 11` if removing this line public let flexbox: Flexbox.Node? = nil public let children: [AnyVTree<NoMsg>] public init( key: Key? = nil, children: [AnyVTree<NoMsg>] = [] ) { self.key = key self.children = children } public func createView<Msg2: Message>(_ msgMapper: @escaping (NoMsg) -> Msg2) -> View { let view = View() for child in self.children { view.addSubview(child.createView(msgMapper)) } return view } }
7ab36bab7d31c3cf62cde398db27fe02
23.709677
98
0.588773
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/Issues/Managing/IssueManagingExpansionModel.swift
mit
2
// // IssueManagingExpansionModel.swift // Freetime // // Created by Ryan Nystrom on 11/13/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit final class IssueManagingExpansionModel: ListDiffable { let expanded: Bool init(expanded: Bool) { self.expanded = expanded } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return "managing-model" as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { if self === object { return true } guard let object = object as? IssueManagingExpansionModel else { return false } return expanded == object.expanded } }
1fc8a83acd77f1e4863c38be4feb0e9d
21.6875
87
0.674931
false
false
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/View/CalculatorOptions/VCalculatorOptions.swift
mit
1
import UIKit class VCalculatorOptions:VView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private weak var controller:CCalculatorOptions! private weak var collectionView:VCollection! private weak var layoutBaseBottom:NSLayoutConstraint! private let kBaseHeight:CGFloat = 280 private let kAnimationDuration:TimeInterval = 0.25 private let kCellHeight:CGFloat = 52 private let kHeaderHeight:CGFloat = 64 private let kCollectionBottom:CGFloat = 20 private let kInterItem:CGFloat = 1 override init(controller:CController) { super.init(controller:controller) backgroundColor = UIColor.clear self.controller = controller as? CCalculatorOptions let blur:VBlur = VBlur.dark() let closeButton:UIButton = UIButton() closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.addTarget( self, action:#selector(actionClose(sender:)), for:UIControlEvents.touchUpInside) let viewBase:UIView = UIView() viewBase.backgroundColor = UIColor(white:0.95, alpha:1) viewBase.translatesAutoresizingMaskIntoConstraints = false let collectionView:VCollection = VCollection() collectionView.alwaysBounceVertical = true collectionView.delegate = self collectionView.dataSource = self collectionView.registerCell(cell:VCalculatorOptionsCell.self) collectionView.registerHeader(header:VCalculatorOptionsHeader.self) self.collectionView = collectionView if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow { flow.headerReferenceSize = CGSize(width:0, height:kHeaderHeight) flow.minimumInteritemSpacing = kInterItem flow.minimumLineSpacing = kInterItem flow.sectionInset = UIEdgeInsets( top:kInterItem, left:0, bottom:kCollectionBottom, right:0) } viewBase.addSubview(collectionView) addSubview(blur) addSubview(closeButton) addSubview(viewBase) NSLayoutConstraint.equals( view:blur, toView:self) NSLayoutConstraint.equals( view:closeButton, toView:self) NSLayoutConstraint.height( view:viewBase, constant:kBaseHeight) layoutBaseBottom = NSLayoutConstraint.bottomToBottom( view:viewBase, toView:self, constant:kBaseHeight) NSLayoutConstraint.equalsHorizontal( view:viewBase, toView:self) NSLayoutConstraint.equals( view:collectionView, toView:viewBase) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { collectionView.collectionViewLayout.invalidateLayout() super.layoutSubviews() } //MARK: actions func actionClose(sender button:UIButton) { controller.back() } //MARK: private private func modelAtIndex(index:IndexPath) -> MCalculatorFunctions { let item:MCalculatorFunctions = controller.model.functions[index.item] return item } //MARK: public func viewAppeared() { layoutBaseBottom.constant = 0 UIView.animate( withDuration:kAnimationDuration, animations: { [weak self] in self?.layoutIfNeeded() }) { [weak self] (done:Bool) in guard let functionList:[MCalculatorFunctions] = self?.controller.model.functions, let selectedFunction:MCalculatorFunctions = self?.controller.model.currentFunction else { return } var indexFunction:Int = 0 for function:MCalculatorFunctions in functionList { if function === selectedFunction { break } indexFunction += 1 } let indexPath:IndexPath = IndexPath( item:indexFunction, section:0) self?.collectionView.selectItem( at:indexPath, animated:true, scrollPosition:UICollectionViewScrollPosition.centeredVertically) } } //MARK: collectionView delegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let width:CGFloat = collectionView.bounds.maxX let size:CGSize = CGSize(width:width, height:kCellHeight) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { let count:Int = controller.model.functions.count return count } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header:VCalculatorOptionsHeader = collectionView.dequeueReusableSupplementaryView( ofKind:kind, withReuseIdentifier: VCalculatorOptionsHeader.reusableIdentifier, for:indexPath) as! VCalculatorOptionsHeader header.config(controller:controller) return header } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MCalculatorFunctions = modelAtIndex(index:indexPath) let cell:VCalculatorOptionsCell = collectionView.dequeueReusableCell( withReuseIdentifier: VCalculatorOptionsCell.reusableIdentifier, for:indexPath) as! VCalculatorOptionsCell cell.config(model:item) return cell } func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { collectionView.isUserInteractionEnabled = false let item:MCalculatorFunctions = modelAtIndex(index:indexPath) controller.selectOption(item:item) } }
2caaea2598c7c6b56b245ac8191bf086
30.740566
160
0.617179
false
false
false
false
Mindera/Alicerce
refs/heads/master
Tests/AlicerceTests/AutoLayout/TrailingConstrainableProxyTestCase.swift
mit
1
import XCTest @testable import Alicerce final class TrailingConstrainableProxyTestCase: BaseConstrainableProxyTestCase { override func setUp() { super.setUp() view0.translatesAutoresizingMaskIntoConstraints = false view0.widthAnchor.constraint(equalToConstant: 100).isActive = true view0.heightAnchor.constraint(equalToConstant: 100).isActive = true } func testConstrain_WithTrailingConstraint_ShouldSupportRelativeEquality() { var constraint: NSLayoutConstraint! constrain(host, view0) { host, view0 in constraint = view0.trailing(to: host) } let expected = NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: host, attribute: .trailing, multiplier: 1, constant: 0, priority: .required, active: true ) XCTAssertConstraint(constraint, expected) host.layoutIfNeeded() XCTAssertEqual(view0.frame.maxX, host.frame.maxX) } func testConstrain_withTrailingConstraint_ShouldSupportRelativeInequalities() { var constraint1: NSLayoutConstraint! var constraint2: NSLayoutConstraint! constrain(host, view0) { host, view0 in constraint1 = view0.trailing(to: host, relation: .equalOrLess) constraint2 = view0.trailing(to: host, relation: .equalOrGreater) } let expected1 = NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: host, attribute: .trailing, multiplier: 1, constant: 0, priority: .required, active: true ) XCTAssertConstraint(constraint1, expected1) let expected2 = NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: host, attribute: .trailing, multiplier: 1, constant: 0, priority: .required, active: true ) XCTAssertConstraint(constraint2, expected2) host.layoutIfNeeded() XCTAssertEqual(view0.frame.maxX, 500) } func testConstrain_WithTrailingConstraint_ShouldSupportPositiveOffset() { var constraint: NSLayoutConstraint! constrain(host, view0) { host, view0 in constraint = view0.trailing(to: host, offset: 100) } let expected = NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: host, attribute: .trailing, multiplier: 1, constant: 100, priority: .required, active: true ) XCTAssertConstraint(constraint, expected) host.layoutIfNeeded() XCTAssertEqual(view0.frame.maxX, 500 + 100) } func testConstrain_WithTrailingConstraint_ShouldSupportNegativeOffset() { var constraint: NSLayoutConstraint! constrain(host, view0) { host, view0 in constraint = view0.trailing(to: host, offset: -100) } let expected = NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: host, attribute: .trailing, multiplier: 1, constant: -100, priority: .required, active: true ) XCTAssertConstraint(constraint, expected) host.layoutIfNeeded() XCTAssertEqual(view0.frame.maxX, 500 - 100) } func testConstrain_WithTrailingConstraint_ShouldSupportLeadingAttribute() { var constraint: NSLayoutConstraint! constrain(host, view0) { host, view0 in constraint = view0.trailingToLeading(of: host) } let expected = NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: host, attribute: .leading, multiplier: 1, constant: 0, priority: .required, active: true) XCTAssertConstraint(constraint, expected) host.layoutIfNeeded() XCTAssertEqual(view0.frame.maxX, 0) } func testConstrain_WithTrailingConstraint_ShouldSupportCenterXAttribute() { var constraint: NSLayoutConstraint! constrain(host, view0) { host, view0 in constraint = view0.trailingToCenterX(of: host) } let expected = NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: host, attribute: .centerX, multiplier: 1, constant: 0, priority: .required, active: true) XCTAssertConstraint(constraint, expected) host.layoutIfNeeded() XCTAssertEqual(view0.frame.maxX, 250) } func testConstrain_WithTrailingConstraint_ShouldSupportCustomPriority() { var constraint: NSLayoutConstraint! constrain(host, view0) { host, view0 in constraint = view0.trailing(to: host, priority: .init(666)) } let expected = NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: host, attribute: .trailing, multiplier: 1, constant: 0, priority: .init(666), active: true ) XCTAssertConstraint(constraint, expected) } func testConstrain_WithLayoutGuideTrailingConstraint_ShouldSupportRelativeEquality() { var constraint: NSLayoutConstraint! constrain(host, layoutGuide) { host, layoutGuide in constraint = layoutGuide.trailing(to: host) } let expected = NSLayoutConstraint( item: layoutGuide!, attribute: .trailing, relatedBy: .equal, toItem: host, attribute: .trailing, multiplier: 1, constant: 0, priority: .required, active: true ) XCTAssertConstraint(constraint, expected) host.layoutIfNeeded() XCTAssertEqual(layoutGuide.layoutFrame.maxX, host.frame.maxX) } func testConstrain_WithAlignTrailingConstraintAndEmptyArray_ShouldReturnEmptyArray() { let constraints = [UIView.ProxyType]().alignTrailing() XCTAssertConstraints(constraints, []) } func testConstrain_WithAlignTrailingConstraint_ShouldSupportRelativeEquality() { var constraints: [NSLayoutConstraint]! view1.translatesAutoresizingMaskIntoConstraints = false view2.translatesAutoresizingMaskIntoConstraints = false constrain(host, view0, view1, view2) { host, view0, view1, view2 in view0.trailing(to: host, offset: -50) constraints = [view0, view1, view2].alignTrailing() } let expected = [ NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: view1, attribute: .trailing, multiplier: 1, constant: 0, priority: .required, active: true ), NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: view2, attribute: .trailing, multiplier: 1, constant: 0, priority: .required, active: true ) ] XCTAssertConstraints(constraints, expected) host.layoutIfNeeded() XCTAssertEqual(view0.frame.maxX, view1.frame.maxX) XCTAssertEqual(view0.frame.maxX, view2.frame.maxX) } func testConstrain_WithTrailingConstraintAndTwoConstraintGroups_ShouldReturnCorrectIsActiveConstraint() { var constraint0: NSLayoutConstraint! var constraint1: NSLayoutConstraint! let constraintGroup0 = constrain(host, view0, activate: false) { host, view0 in constraint0 = view0.trailing(to: host) } let constraintGroup1 = constrain(host, view0, activate: false) { host, view0 in constraint1 = view0.trailing(to: host, offset: -50) } let expected = [ NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: host, attribute: .trailing, multiplier: 1, constant: 0, priority: .required, active: false ), NSLayoutConstraint( item: view0!, attribute: .trailing, relatedBy: .equal, toItem: host, attribute: .trailing, multiplier: 1, constant: -50, priority: .required, active: false ) ] XCTAssertConstraints([constraint0, constraint1], expected) constraintGroup0.isActive = true host.layoutIfNeeded() XCTAssert(constraintGroup0.isActive) XCTAssertFalse(constraintGroup1.isActive) XCTAssertEqual(view0.frame.maxX, host.frame.maxX) constraintGroup0.isActive = false constraintGroup1.isActive = true host.setNeedsLayout() host.layoutIfNeeded() XCTAssertFalse(constraintGroup0.isActive) XCTAssert(constraintGroup1.isActive) XCTAssertEqual(view0.frame.maxX, host.frame.maxX - 50) } }
f8daa32f199fcb996c9528f1ce6f10b1
27.765217
109
0.574063
false
false
false
false
Legoless/Saystack
refs/heads/master
Code/Extensions/Core/Array+Utilities.swift
mit
1
// // Array+Utilities.swift // Saystack // // Created by Dal Rupnik on 23/05/16. // Copyright © 2016 Unified Sense. All rights reserved. // import Foundation extension Array where Element : AnyObject { public mutating func remove(object: Element) { if let index = firstIndex(where: { $0 === object }) { self.remove(at: index) } } } extension Array where Element : Hashable { public func unique() -> Array { var seen: [Element : Bool] = [:] return self.filter { seen.updateValue(true, forKey: $0) == nil } } } extension Array { public mutating func shuffle() { for i in 0 ..< (count - 1) { let j = Int(arc4random_uniform(UInt32(count - i))) + i if i != j { swapAt(i, j) //swapAt(&self[i], &self[j]) } } } public func shuffled() -> Array { var shuffledArray = self shuffledArray.shuffle() return shuffledArray } } extension Array { public func containsType<T>(type: T.Type) -> Bool { for object in self { if object is T { return true } } return false } public func containsType<T>(type: T) -> Bool { return containsType(type: T.self) } } extension Array { public func distinct(_ filter: ((Element) -> String?)) -> Array { var hashes = Set<String>() var finalArray : [Element] = [] for object in self { let hash = filter(object) if let hash = hash, !hashes.contains(hash) { hashes.insert(hash) finalArray.append(object) } } return finalArray } }
65d9d5bd84b2c09432861c6092c7d0df
21.481928
72
0.491961
false
false
false
false
codeWorm2015/LRLPhotoBrowser
refs/heads/master
Sources/LRLPhotoBrowser.swift
mit
1
// // LRLPhotoBrowser.swift // FeelfelCode // // Created by liuRuiLong on 17/5/17. // Copyright © 2017年 李策. All rights reserved. // import UIKit import SnapKit public enum LRLPhotoBrowserModel{ case imageName(String) case image(UIImage) case imageUrl(ur: String, placeHolder: UIImage?) case videoUrl(url: URL, placeHolder: UIImage?) } public enum LRLPBCollectionViewPageType { case common case slide } public protocol LRLPhotoBrowserDelegate: class{ func imageDidScroll(index: Int) -> UIImageView? func imageSwipViewDismiss(imageView: UIImageView?) } public class LRLPhotoBrowser: UIView, LRLPBCollectionDelegate{ /// 所点击的 imageView public var selectedImageView: UIImageView? /// 当前所选中ImageView 相对于 pbSuperView 的位置 public var selectedFrame: CGRect? public weak var delegate: LRLPhotoBrowserDelegate? /// 是否开启拖动 public var animition = false{ didSet{ self.collectionView?.panEnable = animition } } /// 相册的实例化方法 /// /// - Parameters: /// - frame: 相册视图尺寸, 默认为屏幕尺寸 /// - dataSource: 数据源 /// - initialIndex: 初始位置 /// - selectedImageView: 所点击的imageView 根据这个imageView 内部进行动画 /// - delegate: 代理 /// - animition: 是否开启拖拽和动画 public init(frame: CGRect = UIScreen.main.bounds, dataSource: [LRLPhotoBrowserModel], initialIndex: Int, selectedImageView: UIImageView?, delegate: LRLPhotoBrowserDelegate?, animition: Bool = true, pageType: LRLPBCollectionViewPageType = .slide) { self.pageType = pageType super.init(frame:frame) self.dataSource = dataSource self.delegateHolder = LRLPBCollectionDelegateHolder(delegate: self) self.imgContentMode = contentMode self.initialIndex = initialIndex self.currentIndex = initialIndex self.selectedImageView = selectedImageView self.delegate = delegate self.animition = animition configUI() } /// 显示相册 public func show(){ guard let window = pbSuperView else{ fatalError("no superView") } if let inImageView = selectedImageView, let initialFrame = inImageView.superview?.convert(inImageView.frame, to: window){ selectedFrame = initialFrame let imageView = LRLPBImageView(frame: initialFrame) imageView.contentMode = .scaleAspectFill imageView.image = inImageView.image window.addSubview(imageView) window.isUserInteractionEnabled = false UIView.animate(withDuration: 0.2, animations: { imageView.contentMode = .scaleAspectFit imageView.frame = self.frame imageView.backgroundColor = UIColor.black }, completion: { (complete) in window.isUserInteractionEnabled = true imageView.removeFromSuperview() window.addSubview(self) }) }else{ window.addSubview(self) } } public func dismiss(){ if let cell = collectionView?.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? LRLPBImageCell{ dismissCell(cell) }else{ self.removeFromSuperview() self.delegate?.imageSwipViewDismiss(imageView: nil) } } private var dataSource:[LRLPhotoBrowserModel]? private var imgContentMode: UIViewContentMode = .scaleAspectFill private var initialIndex: Int? private var collectionView: LRLPBCollectionView? private var pageControl: UIPageControl? private var collectionDelegate: LRLPBCollectionDelegate? private var delegateHolder: LRLPBCollectionDelegateHolder? private var currentIndex:Int = 0 private var pageType: LRLPBCollectionViewPageType = .slide private var pbSuperView: UIWindow?{ get{ return UIApplication.shared.keyWindow } } required public init?(coder aDecoder: NSCoder) { fatalError() } private func configUI() { let myLayout = UICollectionViewFlowLayout() myLayout.scrollDirection = .horizontal myLayout.minimumLineSpacing = 0 myLayout.minimumInteritemSpacing = 0 collectionView = LRLPBCollectionView(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height), collectionViewLayout: myLayout) collectionView?.dismissBlock = dismissCell collectionView?.register(LRLPBImageCell.self, forCellWithReuseIdentifier: LRLPBImageCell.reuseIdentifier()) collectionView?.register(LRLPBVideoCell.self, forCellWithReuseIdentifier: LRLPBVideoCell.reuseIdentifier()) collectionView?.panEnable = self.animition collectionView?.isPagingEnabled = true collectionView?.delegate = delegateHolder collectionView?.dataSource = delegateHolder addSubview(collectionView!) if let index = initialIndex{ let index = IndexPath(item: index, section: 0) collectionView?.scrollToItem(at: index, at: .centeredHorizontally, animated: false) collectionView?.reloadData() } pageControl = UIPageControl() pageControl?.numberOfPages = self.dataSource?.count ?? 0 addSubview(pageControl!) pageControl?.addTarget(self, action: #selector(LRLPhotoBrowser.pageControlAct), for: .touchUpInside) pageControl?.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.leading.equalTo(self) make.trailing.equalTo(self) make.bottom.equalTo(self).offset(-20.0) } if let index = self.initialIndex { pageControl?.currentPage = index } } lazy private var dismissCell: (LRLPBCell) -> Void = { [weak self] (dissMissCell) in guard let s = self else{ return } let imageView = dissMissCell.showView func dismiss(){ imageView.removeFromSuperview() s.removeFromSuperview() s.delegate?.imageSwipViewDismiss(imageView: imageView.imageView) } imageView.removeFromSuperview() if let localView = UIApplication.shared.keyWindow, let loc = s.selectedFrame, s.animition{ localView.addSubview(imageView) UIView.animate(withDuration: 0.3, animations: { imageView.transform = CGAffineTransform.identity imageView.setZoomScale(scale: 1.0) imageView.contentMode = UIViewContentMode.scaleAspectFill imageView.frame = loc s.alpha = 0.0 }, completion: { (success) in dismiss() }) }else{ dismiss() } } @objc private func pageControlAct(page: UIPageControl){ if !(collectionView?.panning ?? true){ let indexPath = IndexPath(item: page.currentPage, section: 0) collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) hasScrollTo(index: page.currentPage) }else{ page.currentPage = currentIndex } } private func hasScrollTo(index:Int){ if let inImageView = self.delegate?.imageDidScroll(index: index){ self.selectedFrame = inImageView.superview?.convert(inImageView.frame, to: pbSuperView) } currentIndex = index } //MARK: UICollectionViewDataSource public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let data = dataSource?[indexPath.row] else { return UICollectionViewCell() } let cell:UICollectionViewCell switch data { case .videoUrl(url: _, placeHolder: _): cell = collectionView.dequeueReusableCell(withReuseIdentifier: LRLPBVideoCell.reuseIdentifier(), for: indexPath) as! LRLPBVideoCell default: cell = collectionView.dequeueReusableCell(withReuseIdentifier: LRLPBImageCell.reuseIdentifier(), for: indexPath) as! LRLPBImageCell } switch data { case .imageName(let name): (cell as! LRLPBImageCell).setData(imageName: name) case .imageUrl(let imageUrl, let placeHolder): (cell as! LRLPBImageCell).setData(imageUrl: imageUrl, placeHolder: placeHolder) case .image(let image): (cell as! LRLPBImageCell).setData(image: image) case .videoUrl(url: let videoUrl, placeHolder: let image): (cell as! LRLPBVideoCell).setData(videoUrl: videoUrl, placeHolder: image) } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.dataSource?.count ?? 0 } //MARK: UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) as? LRLPBCell{ dismissCell(cell) } } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { (cell as? LRLPBCell)?.endDisplay() } //MARK: UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: self.bounds.size.width, height: self.bounds.size.height) } //MARK: func scrollViewDidScroll(_ scrollView: UIScrollView) { guard pageType == .slide else { return } var offset = scrollView.contentOffset.x/scrollView.bounds.width if offset >= 0 && offset < CGFloat(self.dataSource?.count ?? 0){ let i = floor(offset) let j = ceil(offset) if i != offset || j != offset{ offset = offset - floor(offset) }else{ offset = 1.0 } if self.collectionView?.visibleCells.count ?? 0 == 2 { let cell1 = collectionView?.cellForItem(at: IndexPath(item: Int(i), section: 0)) as? LRLPBCell cell1?.changeTheImageViewLocationWithOffset(offset: offset) let cell2 = collectionView?.cellForItem(at: IndexPath(item: Int(j), section: 0)) as? LRLPBCell cell2?.changeTheImageViewLocationWithOffset(offset: offset - 1.0) } } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let index = Int(scrollView.contentOffset.x/self.bounds.size.width) self.pageControl?.currentPage = index hasScrollTo(index: index) } fileprivate class LRLPBCollectionDelegateHolder: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{ private override init() { fatalError() } init(delegate: LRLPBCollectionDelegate) { collectionDelegate = delegate } fileprivate weak var collectionDelegate: LRLPBCollectionDelegate? //MARK: UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionDelegate?.collectionView(collectionView, cellForItemAt: indexPath) ?? UICollectionViewCell() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return collectionDelegate?.collectionView(collectionView, numberOfItemsInSection: section) ?? 0 } //MARK: UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionDelegate?.collectionView(collectionView, didSelectItemAt: indexPath) } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { collectionDelegate?.collectionView(collectionView, didEndDisplaying: cell, forItemAt: indexPath) } //MARK: UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return collectionDelegate?.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath) ?? CGSize.zero } //MARK: UIScrollViewDelegate func scrollViewDidScroll(_ scrollView: UIScrollView) { collectionDelegate?.scrollViewDidScroll(scrollView) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){ collectionDelegate?.scrollViewDidEndDecelerating(scrollView) } } } fileprivate protocol LRLPBCollectionDelegate: NSObjectProtocol{ func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize func scrollViewDidScroll(_ scrollView: UIScrollView) func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) }
52f877f6a5d87043a79c6f150efeba5a
41.54908
251
0.666787
false
false
false
false
lee0741/Glider
refs/heads/master
Glider/HomeController.swift
mit
1
// // HomeController.swift // Glider // // Created by Yancen Li on 2/24/17. // Copyright © 2017 Yancen Li. All rights reserved. // import UIKit import CoreSpotlight import MobileCoreServices class HomeController: UITableViewController, UISearchResultsUpdating { let cellId = "homeId" let defaults = UserDefaults.standard var stories = [Story]() var storyType = StoryType.news var query = "" var pagination = 1 var updating = false var searchController: UISearchController! var searchResults = [Story]() var savedSearches = [String]() var searchableItems = [CSSearchableItem]() override func viewDidLoad() { super.viewDidLoad() configController() Story.getStories(type: storyType, query: query, pagination: 1) { stories in self.stories = stories UIApplication.shared.isNetworkActivityIndicatorVisible = false self.tableView.reloadData() self.setupSearchableContent(stories) } } func configController() { if let savedSearch = defaults.object(forKey: "SavedQuery") { savedSearches = savedSearch as! [String] } UIApplication.shared.isNetworkActivityIndicatorVisible = true UIApplication.shared.statusBarStyle = .lightContent if storyType == .search { navigationItem.title = query if savedSearches.contains(query) == false { let saveBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(saveAction)) navigationItem.setRightBarButton(saveBarButtonItem, animated: true) } } else { navigationItem.title = storyType.rawValue } navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) tableView.register(HomeCell.self, forCellReuseIdentifier: cellId) tableView.estimatedRowHeight = 80.0 tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorColor = .separatorColor searchController = UISearchController(searchResultsController: nil) tableView.tableHeaderView = searchController.searchBar searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false searchController.searchBar.tintColor = .mainColor searchController.searchBar.searchBarStyle = .minimal definesPresentationContext = true searchController.loadViewIfNeeded() refreshControl = UIRefreshControl() refreshControl?.tintColor = .mainColor refreshControl?.addTarget(self, action: #selector(handleRefresh(_:)), for: UIControlEvents.valueChanged) if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: view) } } func saveAction() { navigationItem.setRightBarButton(UIBarButtonItem(), animated: true) savedSearches.append(query) defaults.set(savedSearches, forKey: "SavedQuery") defaults.synchronize() } // MARK: - Spotlight Search func setupSearchableContent(_ newStories: [Story]) { newStories.forEach { story in let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String) searchableItemAttributeSet.title = story.title searchableItemAttributeSet.contentDescription = story.domain searchableItemAttributeSet.keywords = [story.title] let searchableItem = CSSearchableItem(uniqueIdentifier: "org.yancen.glider.\(story.id)", domainIdentifier: "story", attributeSet: searchableItemAttributeSet) searchableItems.append(searchableItem) } CSSearchableIndex.default().indexSearchableItems(searchableItems) { (error) -> Void in if error != nil { print(error?.localizedDescription ?? "Fail to index") } } } override func restoreUserActivityState(_ activity: NSUserActivity) { if activity.activityType == CSSearchableItemActionType { if let userInfo = activity.userInfo { let selectedStory = userInfo[CSSearchableItemActivityIdentifier] as! String let commentController = CommentController() commentController.itemId = Int(selectedStory.components(separatedBy: ".").last!)! navigationController?.pushViewController(commentController, animated: true) } } } // MARK: - Pull to Refresh func handleRefresh(_ refreshControl: UIRefreshControl) { pagination = 1 UIApplication.shared.isNetworkActivityIndicatorVisible = true Story.getStories(type: storyType, query: query, pagination: 1) { stories in self.stories = stories UIApplication.shared.isNetworkActivityIndicatorVisible = false OperationQueue.main.addOperation { self.tableView.reloadData() refreshControl.endRefreshing() self.searchableItems = [CSSearchableItem]() self.setupSearchableContent(stories) } } } // MARK: - Search Logic func filterContent(for searchText: String) { searchResults = stories.filter { (story) -> Bool in let isMatch = story.title.localizedCaseInsensitiveContains(searchText) return isMatch } } func updateSearchResults(for searchController: UISearchController) { if let searchText = searchController.searchBar.text { filterContent(for: searchText) tableView.reloadData() } } override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { searchController.searchBar.endEditing(true) } // MARK: - Table View Data Source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchController.isActive ? searchResults.count : stories.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HomeCell let story = searchController.isActive ? searchResults[indexPath.row] : stories[indexPath.row] cell.story = story cell.commentView.addTarget(self, action: #selector(pushToCommentView(_:)), for: .touchUpInside) cell.layoutIfNeeded() return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if storyType != .search && stories.count - indexPath.row < 10 && !updating && pagination < 18 { updating = true pagination += 1 UIApplication.shared.isNetworkActivityIndicatorVisible = true Story.getStories(type: storyType, query: query, pagination: pagination) { stories in self.stories += stories self.updating = false UIApplication.shared.isNetworkActivityIndicatorVisible = false self.tableView.reloadData() self.setupSearchableContent(stories) } } } // MARK: - Table View Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let story = searchController.isActive ? searchResults[indexPath.row] : stories[indexPath.row] if story.url.hasPrefix("https://news.ycombinator.com/item?id=") { let commentController = CommentController() commentController.itemId = story.id navigationController?.pushViewController(commentController, animated: true) } else { let safariController = MySafariViewContoller(url: URL(string: story.url)!) present(safariController, animated: true, completion: nil) } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return searchController.isActive ? false : true } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let story = self.stories[indexPath.row] let shareAction = UITableViewRowAction(style: .default, title: "Share", handler: { (action, indexPath) -> Void in let defaultText = story.title + " " + story.url let activityController = UIActivityViewController(activityItems: [defaultText], applicationActivities: nil) self.present(activityController, animated: true, completion: nil) }) shareAction.backgroundColor = .mainColor return [shareAction] } func pushToCommentView(_ sender: CommentIconView) { guard sender.numberOfComment != 0 else { return } let commentController = CommentController() commentController.itemId = sender.itemId navigationController?.pushViewController(commentController, animated: true) } } // MARK: - 3D Touch extension HomeController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath), let url = URL(string: stories[indexPath.row].url) else { return nil } let safariController = MySafariViewContoller(url: url) previewingContext.sourceRect = cell.frame return safariController } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { present(viewControllerToCommit, animated: true, completion: nil) } }
1248d262084d8f20c2c3cf1c487caf34
36.1875
163
0.723845
false
false
false
false
Mattmlm/codepathrottentomatoes
refs/heads/master
Rotten Tomatoes/Rotten Tomatoes/MovieDetailsViewController.swift
mit
1
// // MovieDetailsViewController.swift // Rotten Tomatoes // // Created by admin on 9/18/15. // Copyright © 2015 mattmo. All rights reserved. // import UIKit class MovieDetailsViewController: UIViewController { var movieData: NSDictionary? @IBOutlet weak var movieCoverView: UIImageView! @IBOutlet weak var movieTitleLabel: UILabel! @IBOutlet weak var movieDetailsLabel: UILabel! @IBOutlet weak var movieRatingsLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.tintColor = UIColor.blackColor() // Do any additional setup after loading the view. UIView.animateWithDuration(2) { () -> Void in self.movieCoverView.alpha = 1; } if self.movieData != nil { RTAPISupport.setMovieCover(self.movieCoverView, movieData: self.movieData!); if let title = RTAPISupport.getMovieTitle(self.movieData!) { self.movieTitleLabel.text = title; self.navigationItem.title = title; } if let ratings = RTAPISupport.getMovieRatings(self.movieData!) { self.movieRatingsLabel.text = ratings; } if let description = RTAPISupport.getMovieSynopsis(self.movieData!) { self.movieDetailsLabel.text = description; } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
179938d694dfc766791c0c5c97770e4e
30.72
88
0.631778
false
false
false
false
geekaurora/ReactiveListViewKit
refs/heads/master
ReactiveListViewKit/Supported Files/CZUtils/Sources/CZUtils/Extensions/String+.swift
mit
1
// // NSString+Additions // // Created by Cheng Zhang on 1/5/16. // Copyright © 2016 Cheng Zhang. All rights reserved. // import Foundation public extension String { /** Search substrings that matches regex pattern - parameter regex: the regex pattern - parameter excludeRegEx: indicates whether returned substrings exclude regex pattern iteself - returns: all matched substrings */ func search(regex: String, excludeRegEx: Bool = true) -> [String] { guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] } let string = self as NSString let results = regex.matches(in: self, options: [], range: NSMakeRange(0, string.length)) return results.compactMap { result in guard result.numberOfRanges > 0 else { return nil } let i = excludeRegEx ? (result.numberOfRanges - 1) : 0 return result.range(at: i).location != NSNotFound ? string.substring(with: result.range(at: i)) : nil } } /** URLHostAllowedCharacterSet "#%/<>?@\^`{|} URLQueryAllowedCharacterSet "#%<>[\]^`{|} URLFragmentAllowedCharacterSet "#%<>[\]^`{|} URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|} URLPathAllowedCharacterSet "#%;<>?[\]^`{|} URLUserAllowedCharacterSet "#%/:<>?@[\]^` http://stackoverflow.com/questions/24551816/swift-encode-url */ func urlEncoded()-> String { guard firstIndex(of: "%") == nil else { return self } let mutableString = NSMutableString(string: self) let urlEncoded = mutableString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) return urlEncoded ?? "" } var intValue: Int? { return Int(self) } // public var cgFloatValue: CGFloat? { // if let intValue = intValue { // return CGFloat(intValue) // } // return nil // } }
da2fa841a428925b9f1068274e8b7b1a
31.52459
113
0.599798
false
false
false
false
brandonlee503/Fun-Facts
refs/heads/master
Fun Facts/ViewController.swift
mit
1
// // ViewController.swift // Fun Facts // // Created by Brandon Lee on 6/25/15. // Copyright (c) 2015 Brandon Lee. All rights reserved. // import UIKit class ViewController: UIViewController { //Outlets for button and label @IBOutlet weak var funFactLabel: UILabel! @IBOutlet weak var funFactButton: UIButton! //Instance of data model let factBook = FactBook() let colorWheel = ColorWheel() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. funFactLabel.text = factBook.getRandomFact() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showFunFact() { //Get and display random color and a fact var theRandomColor = colorWheel.getRandomColor() view.backgroundColor = theRandomColor funFactButton.tintColor = theRandomColor funFactLabel.text = factBook.getRandomFact() } }
8dc50ffea9c1c819d64a0783555af16e
24.25
80
0.657966
false
false
false
false
Ghosty141/MenuBarControls
refs/heads/master
MenuBarControls/PlayerPopoverViewController.swift
gpl-3.0
1
// // PlayerPopover.swift // MenuBarControls // // Copyright © 2017 Ghostly. All rights reserved. // import Cocoa import CoreImage import ScriptingBridge class PlayerPopoverViewController: NSViewController { let appDel = NSApplication.shared.delegate as? AppDelegate var lastURL: String? var mouseoverIsActive = false var updateTimer: Timer? var settingsController: NSWindowController? let spotify = SBApplication(bundleIdentifier: "com.spotify.client")! as SpotifyApplication @IBOutlet weak var coverImage: NSImageView! @IBOutlet weak var trackLabel: NSTextField! @IBOutlet weak var albumLabel: NSTextField! @IBOutlet weak var artistLabel: NSTextField! @IBOutlet weak var trackTimeLabel: NSTextField! @IBOutlet weak var cover: NSImageCell! @IBOutlet weak var playPauseButton: NSButtonCell! @IBOutlet weak var volumeSlider: NSSliderCell! @IBOutlet weak var shuffleButton: NSButtonCell! @IBOutlet weak var repeatButton: NSButtonCell! @IBOutlet weak var track: NSTextFieldCell! @IBOutlet weak var album: NSTextFieldCell! @IBOutlet weak var artist: NSTextFieldCell! func startTimer() { if updateTimer == nil { updateTimer = Timer.scheduledTimer( timeInterval: UserDefaults.standard.double(forKey: "UpdateRate"), target: self, selector: #selector(self.checkAppStatus), userInfo: nil, repeats: true) } } func stopTimer() { if updateTimer != nil { updateTimer?.invalidate() updateTimer = nil } } @objc func checkAppStatus() { if appDel?.isSpotifyRunning() == false { appDel?.closePopover(self) } else { if spotify.playerState == .playing { if lastURL != spotify.currentTrack?.artworkUrl { updateCover() } if mouseoverIsActive { trackTimeLabel.stringValue = "- \(formatTime(using: Int32(spotify.playerPosition!))) / \(formatTime(using: Int32((spotify.currentTrack?.duration)!/1000))) -" } updateShuffleButton() updateRepeatButton() updatePlayPauseButton() volumeSlider.integerValue = spotify.soundVolume! } else { updatePlayPauseButton() if appDel?.popover.isShown == false { stopTimer() } } } } func updatePlayPauseButton() { if playPauseButton.state == NSControl.StateValue.off && spotify.playerState == .playing { playPauseButton.state = NSControl.StateValue.on } else if playPauseButton.state == NSControl.StateValue.on && spotify.playerState == .paused { playPauseButton.state = NSControl.StateValue.off } } func updateShuffleButton() { if shuffleButton.state == NSControl.StateValue.off && spotify.shuffling == true { shuffleButton.state = NSControl.StateValue.on } else if shuffleButton.state == NSControl.StateValue.on && spotify.shuffling == false { shuffleButton.state = NSControl.StateValue.off } } func updateRepeatButton() { if repeatButton.state == NSControl.StateValue.off && spotify.repeating == true { repeatButton.state = NSControl.StateValue.on } else if shuffleButton.state == NSControl.StateValue.on && spotify.repeating == false { repeatButton.state = NSControl.StateValue.off } } private func updateCover() { let dataURL = spotify.currentTrack?.artworkUrl ?? lastURL! let urlContent = try? Data(contentsOf: URL(string: dataURL)!) if let coverArt = urlContent { imageGroup.original = NSImage(data: coverArt) imageGroup.processed = blurImage(imageGroup.original!) cover.image = imageGroup.original } else { cover.image = NSImage(named: NSImage.Name(rawValue: "CoverError")) } if mouseoverIsActive { mouseOverOn() } lastURL = spotify.currentTrack?.artworkUrl } // CABasicAnimation / Core Animation is suited for this func blurImage(_ inputImage: NSImage) -> NSImage { let context = CIContext(options: nil) let image = CIImage(data: inputImage.tiffRepresentation!) // Extends the borders of the image to infinity to avoid a white lining let transform = AffineTransform.identity let extendImage = CIFilter(name: "CIAffineClamp") extendImage!.setValue(image, forKey: "inputImage") extendImage!.setValue(NSAffineTransform(transform: transform), forKey: "inputTransform") let extendedImage = extendImage?.outputImage // Generates a black image with 0.5 alpha let blackGenerator = CIFilter(name: "CIConstantColorGenerator") blackGenerator!.setValue(CIColor.init(red: 0, green: 0, blue: 0, alpha: CGFloat(UserDefaults.standard.double(forKey: "brightnessValue")) / 100), forKey: "inputColor") let black = blackGenerator!.outputImage // Crop the generated black image to the size of the input let cropBlack = CIFilter(name: "CISourceInCompositing") cropBlack!.setValue(black, forKey: "inputImage") cropBlack!.setValue(image, forKey: "inputBackgroundImage") let croppedBlack = cropBlack!.outputImage // Blurs the input let blurFilter = CIFilter(name: "CIGaussianBlur") blurFilter!.setValue(extendedImage, forKey: kCIInputImageKey) blurFilter!.setValue(CGFloat(UserDefaults.standard.integer(forKey: "blurValue")), forKey: kCIInputRadiusKey) let blurredImage = blurFilter!.outputImage // Lays the black image ontop of the original let mixFilter = CIFilter(name: "CISourceAtopCompositing") mixFilter!.setValue(croppedBlack, forKey: "inputImage") mixFilter!.setValue(blurredImage, forKey: "inputBackgroundImage") //input change let mixed = mixFilter!.outputImage // Crops it again so there aren't any borders let cropFilter = CIFilter(name: "CICrop") cropFilter!.setValue(mixed, forKey: kCIInputImageKey) cropFilter!.setValue(CIVector(cgRect: image!.extent), forKey: "inputRectangle") let cropped = cropFilter!.outputImage // Converts the CGImage to NSImage and returns it let cgimg = context.createCGImage(cropped!, from: cropped!.extent) let processedImage = NSImage(cgImage: cgimg!, size: NSSize(width: 0, height: 0)) return processedImage } func formatTime(using time: Int32) -> String { let zeroPrefixFormatter = NumberFormatter() zeroPrefixFormatter.minimumIntegerDigits = 2 return "\(time/60):\(zeroPrefixFormatter.string(from: NSNumber(value: (time-(time/60)*60)))!)" } func mouseOverOn() { mouseoverIsActive = true cover.image = imageGroup.processed track.stringValue = (spotify.currentTrack?.name)! album.stringValue = (spotify.currentTrack?.album)! artist.stringValue = (spotify.currentTrack?.artist)! trackTimeLabel.stringValue = "- \(formatTime(using: Int32(spotify.playerPosition!))) / \(formatTime(using: Int32((spotify.currentTrack?.duration)!/1000))) -" trackLabel.isHidden = !Bool(truncating: UserDefaults.standard.integer(forKey: "displayTrackTitle") as NSNumber) albumLabel.isHidden = !Bool(truncating: UserDefaults.standard.integer(forKey: "displayAlbumTitle") as NSNumber) artistLabel.isHidden = !Bool(truncating: UserDefaults.standard.integer(forKey: "displayArtistName") as NSNumber) trackTimeLabel.isHidden = !Bool(truncating: UserDefaults.standard.integer(forKey: "displayTrackTime") as NSNumber) } func mouseOverOff() { mouseoverIsActive = false coverImage.image = imageGroup.original ?? NSImage(named: NSImage.Name("CoverError")) trackLabel.isHidden = true albumLabel.isHidden = true artistLabel.isHidden = true trackTimeLabel.isHidden = true } // IBActions for the player-popover @IBAction func playPause(_ sender: Any) { spotify.playpause!() } @IBAction func volumeSlider(_ sender: NSSlider) { spotify.setSoundVolume!(sender.integerValue) } @IBAction func next(_ sender: NSButton) { spotify.nextTrack!() if UserDefaults.standard.integer(forKey: "trackInfoDelay") != 0 { mouseOverOn() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + UserDefaults.standard.double(forKey: "trackInfoDelay")) { self.mouseOverOff() } } } @IBAction func previous(_ sender: NSButton) { spotify.previousTrack!() } @IBAction func repeats(_ sender: NSButtonCell) { spotify.setRepeating!(Bool(truncating: sender.intValue as NSNumber)) } @IBAction func shuffle(_ sender: NSButtonCell) { spotify.setShuffling!(Bool(truncating: sender.intValue as NSNumber)) } @IBAction func openSettings(_ sender: NSButton) { settingsController = NSStoryboard( name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) .instantiateController( withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "SettingsWindow")) as? NSWindowController settingsController?.showWindow(self) } // Overrides override func mouseEntered(with event: NSEvent) { mouseOverOn() } override func mouseExited(with event: NSEvent) { mouseOverOff() } override func viewDidLoad() { super.viewDidLoad() startTimer() updatePlayPauseButton() updateShuffleButton() updateRepeatButton() updateCover() volumeSlider.integerValue = spotify.soundVolume! let trackingArea = NSTrackingArea(rect: coverImage.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil) coverImage.addTrackingArea(trackingArea) } override func viewDidDisappear() { super.viewDidDisappear() updateTimer?.invalidate() imageGroup = ImageMemory(originalImage: nil, processedImage: nil) } }
a8e6955eea230c69a0057e91d11fde83
36.961672
128
0.62827
false
false
false
false
laurb9/PanoController-iOS
refs/heads/master
PanoController/MenuTableViewController.swift
mit
1
// // MenuTableViewController.swift // PanoController // // Created by Laurentiu Badea on 7/30/17. // Copyright © 2017 Laurentiu Badea. // // This file may be redistributed under the terms of the MIT license. // A copy of this license has been included with this distribution in the file LICENSE. // import UIKit class MenuTableViewController: UITableViewController { var menus: Menu! override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 24.0 tableView.rowHeight = UITableViewAutomaticDimension // 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 viewWillAppear(_ animated: Bool) { print("MenuTableViewControler: \(String(describing: menus))") } 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 { return menus!.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return menus![section].name } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (menus![section] as! Menu).count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell let menuItem = menus![indexPath] switch menuItem { case let listSelector as ListSelector: cell = tableView.dequeueReusableCell(withIdentifier: "Select", for: indexPath) let selectCell = cell as! SelectTableViewCell selectCell.nameLabel?.text = listSelector.name selectCell.valueLabel?.text = listSelector.currentOptionName() case let switchControl as Switch: cell = tableView.dequeueReusableCell(withIdentifier: "Toggle", for: indexPath) let toggleCell = cell as! ToggleTableViewCell toggleCell.nameLabel?.text = switchControl.name toggleCell.switchView?.isOn = switchControl.currentState case let rangeControl as RangeSelector: cell = tableView.dequeueReusableCell(withIdentifier: "Range", for: indexPath) let rangeCell = cell as! RangeTableViewCell rangeCell.nameLabel?.text = rangeControl.name rangeCell.valueLabel?.text = "\(Int(rangeControl.current))º" rangeCell.slider.maximumValue = Float(rangeControl.max) rangeCell.slider.minimumValue = Float(rangeControl.min) as Float rangeCell.slider.setValue(Float(rangeControl.current), animated: false) default: cell = UITableViewCell() print("Unknown menuItem \(menuItem) at \(indexPath)") } return cell } // MARK: - Save Settings @IBAction func rangeUpdated(_ sender: UISlider) { let switchPosition = sender.convert(CGPoint.zero, to: tableView) if let indexPath = tableView.indexPathForRow(at: switchPosition), let menuItem = menus![indexPath] as? RangeSelector { menuItem.current = Int(sender.value) } } @IBAction func toggleChanged(_ sender: UISwitch) { let switchPosition = sender.convert(CGPoint.zero, to: tableView) if let indexPath = tableView.indexPathForRow(at: switchPosition), let menuItem = menus![indexPath] as? Switch { menuItem.currentState = sender.isOn } } // MARK: - Navigation @IBAction func unwindToSettings(sender: UIStoryboardSegue){ //if let _ = sender.source as? OptionViewController, //} if let selectedIndexPath = tableView.indexPathForSelectedRow { tableView.reloadRows(at: [selectedIndexPath], with: .none) } } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destinationController = segue.destination as? OptionViewController, let listSelector = sender as? SelectTableViewCell, let indexPath = tableView.indexPath(for: listSelector) { destinationController.menuItem = menus![indexPath] as? ListSelector destinationController.title = destinationController.menuItem?.name } } }
b452de68e8dcf5967e56ea55d3119d2a
37.620968
113
0.674253
false
false
false
false
Bing0/ThroughWall
refs/heads/master
ThroughWall/RuleListTableViewController.swift
gpl-3.0
1
// // RuleListTableViewController.swift // ThroughWall // // Created by Bin on 30/03/2017. // Copyright © 2017 Wu Bin. All rights reserved. // import UIKit class RuleListTableViewController: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate { var ruleItems = [[String]]() var rewriteItems = [[String]]() var filteredRuleItems = [[String]]() var filteredRewriteItems = [[String]]() var selectedIndex = -1 let searchController = UISearchController(searchResultsController: nil) var filterText = "" 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() navigationController?.navigationBar.barTintColor = topUIColor tableView.tableFooterView = UIView() tableView.backgroundColor = UIColor.groupTableViewBackground // self.edgesForExtendedLayout = UIRectEdge.all self.extendedLayoutIncludesOpaqueBars = true NotificationCenter.default.addObserver(self, selector: #selector(RuleListTableViewController.ruleSaved(notification:)), name: NSNotification.Name(rawValue: kRuleSaved), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RuleListTableViewController.ruleDeleted(notification:)), name: NSNotification.Name(rawValue: kRuleDeleted), object: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.delegate = self // searchController.searchBar.scopeButtonTitles = ["All", "Rewrite", "Direct", "Proxy", "Reject"] // searchController.searchBar.delegate = self tableView.tableHeaderView = searchController.searchBar definesPresentationContext = true } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kRuleSaved), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kRuleDeleted), object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) reloadItemsFromDisk() } func reloadItemsFromDisk() { ruleItems = Rule.sharedInstance.getCurrentRuleItems() rewriteItems = Rule.sharedInstance.getCurrentRewriteItems() applyFilter(withText: filterText) tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func ruleSaved(notification: Notification) { if let value = notification.userInfo?["ruleItem"] as? [String] { if selectedIndex == -1 { ruleItems.insert(value, at: 0) } else { ruleItems[selectedIndex - rewriteItems.count] = value } let content = makeRulesIntoContent() RuleFileUpdateController().saveToCustomRuleFile(withContent: content) } else if let value = notification.userInfo?["rewriteItem"] as? [String] { if selectedIndex == -1 { rewriteItems.insert(value, at: 0) } else { rewriteItems[selectedIndex] = value } let content = makeRulesIntoContent() RuleFileUpdateController().saveToCustomRuleFile(withContent: content) } reloadItemsFromDisk() } @objc func ruleDeleted(notification: Notification) { ruleDeleted() } func ruleDeleted() { if selectedIndex == -1 { return } if selectedIndex < rewriteItems.count { rewriteItems.remove(at: selectedIndex) } else { ruleItems.remove(at: selectedIndex - rewriteItems.count) } selectedIndex = -1 let content = makeRulesIntoContent() RuleFileUpdateController().saveToCustomRuleFile(withContent: content) reloadItemsFromDisk() } func makeRulesIntoContent() -> String { var content = "[URL Rewrite]\n" for rewriteItem in rewriteItems { let tmp = rewriteItem.joined(separator: " ") content.append(tmp + "\n") } content.append("[Rule]\n") for ruleItem in ruleItems { let tmp = ruleItem.joined(separator: ",") content.append(tmp + "\n") } return content } func applyFilter(withText text: String) { filteredRuleItems.removeAll() filteredRewriteItems.removeAll() for ruleItem in ruleItems { for item in ruleItem { if item.lowercased().contains(text) { filteredRuleItems.append(ruleItem) break } } } for rewriteItem in rewriteItems { for item in rewriteItem { if item.lowercased().contains(text) { filteredRewriteItems.append(rewriteItem) break } } } tableView.reloadData() } // MARK: - UISearchControllerDelegate // func willDismissSearchController(_ searchController: UISearchController) { // let indexPath = IndexPath(row: 0, section: 0) // tableView.scrollToRow(at: indexPath, at: .top, animated: false) // } // MARK: - UISearchResultsUpdating func updateSearchResults(for searchController: UISearchController) { if let text = searchController.searchBar.text { filterText = text.lowercased() applyFilter(withText: text.lowercased()) } } // 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 if searchController.isActive { return filteredRewriteItems.count + filteredRuleItems.count } return rewriteItems.count + ruleItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath) if searchController.isActive { if indexPath.row < filteredRewriteItems.count { let item = filteredRewriteItems[indexPath.row] cell.textLabel?.attributedText = usingFilterTextTohightlight(item[0]) cell.detailTextLabel?.attributedText = usingFilterTextTohightlight(item[1]) } else { let item = filteredRuleItems[indexPath.row - filteredRewriteItems.count] // cell.textLabel?.attributedText = usingFilterTextTohightlight(item[1]) // // //In fact, usingFilterTextTohightlight doesn't work now // cell.detailTextLabel?.attributedText = usingFilterTextTohightlight(attributedText: makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[2])) cell.textLabel?.attributedText = nil cell.detailTextLabel?.attributedText = nil if item.count >= 3 { cell.textLabel?.attributedText = usingFilterTextTohightlight(item[1]) cell.detailTextLabel?.attributedText = usingFilterTextTohightlight(attributedText: makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[2])) } else { cell.textLabel?.text = "" cell.detailTextLabel?.attributedText = usingFilterTextTohightlight(attributedText: makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[1])) } } } else { if indexPath.row < rewriteItems.count { let item = rewriteItems[indexPath.row] cell.textLabel?.attributedText = nil cell.detailTextLabel?.attributedText = nil cell.textLabel?.text = item[0] cell.detailTextLabel?.text = item[1] } else { let item = ruleItems[indexPath.row - rewriteItems.count] cell.textLabel?.attributedText = nil cell.detailTextLabel?.attributedText = nil if item.count >= 3 { cell.textLabel?.text = item[1] cell.detailTextLabel?.attributedText = makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[2]) } else { cell.textLabel?.text = "" cell.detailTextLabel?.attributedText = makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[1]) } } } return cell } func makeAttributeDescription(withMatchRule matchRule: String, andProxyRule proxyRule: String) -> NSAttributedString { let attributeDescription = NSMutableAttributedString(string: "") let attributeRequestType = NSAttributedString(string: matchRule, attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightGray]) attributeDescription.append(attributeRequestType) attributeDescription.append(NSAttributedString(string: " ")) switch proxyRule.lowercased() { case "direct": let attributeRule = NSAttributedString(string: proxyRule, attributes: [NSAttributedStringKey.foregroundColor: UIColor.init(red: 0.24, green: 0.545, blue: 0.153, alpha: 1.0)]) attributeDescription.append(attributeRule) case "proxy": let attributeRule = NSAttributedString(string: proxyRule, attributes: [NSAttributedStringKey.foregroundColor: UIColor.orange]) attributeDescription.append(attributeRule) default: let attributeRule = NSAttributedString(string: proxyRule, attributes: [NSAttributedStringKey.foregroundColor: UIColor.red]) attributeDescription.append(attributeRule) } return attributeDescription } func usingFilterTextTohightlight(_ text: String) -> NSAttributedString { let attributedText = NSAttributedString(string: text) return usingFilterTextTohightlight(attributedText: attributedText) } func usingFilterTextTohightlight(attributedText attributeText: NSAttributedString) -> NSAttributedString { let mutableAttText = NSMutableAttributedString(attributedString: attributeText) let text = attributeText.string for range in searchRangesOfFilterText(inString: text) { mutableAttText.addAttribute(.backgroundColor, value: UIColor.yellow, range: NSRange(range, in: text)) } return mutableAttText } func searchRangesOfFilterText(inString str: String) -> [Range<String.Index>] { var endRange = str.endIndex var ranges = [Range<String.Index>]() while true { let subString = str[..<endRange] if let range = subString.range(of: filterText, options: [.literal, .backwards]) { ranges.append(range) endRange = range.lowerBound } else { break } } return ranges } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) selectedIndex = indexPath.row performSegue(withIdentifier: "showRuleDetail", sender: nil) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let alertController = UIAlertController(title: "Delete Rule", message: nil, preferredStyle: .alert) let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { (_) in DispatchQueue.main.async { if self.searchController.isActive { if indexPath.row < self.filteredRewriteItems.count { let item = self.filteredRewriteItems[indexPath.row] let index = self.rewriteItems.index(where: { strs -> Bool in return strs == item }) self.selectedIndex = index! } else { let item = self.filteredRuleItems[indexPath.row - self.filteredRewriteItems.count] let index = self.ruleItems.index(where: { strs -> Bool in return strs == item }) self.selectedIndex = index! + self.rewriteItems.count } } else { self.selectedIndex = indexPath.row } self.ruleDeleted() } }) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(cancelAction) alertController.addAction(deleteAction) self.present(alertController, animated: true, completion: nil) } } @IBAction func addNewRule(_ sender: UIBarButtonItem) { selectedIndex = -1 performSegue(withIdentifier: "showRuleDetail", sender: nil) } // 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. if segue.identifier == "showRuleDetail" { if let desti = segue.destination as? RuleDetailTableViewController { if selectedIndex != -1 { let item: [String] if searchController.isActive { if selectedIndex < filteredRewriteItems.count { item = filteredRewriteItems[selectedIndex] desti.rewriteItem = item } else { item = filteredRuleItems[selectedIndex - filteredRewriteItems.count] desti.ruleItem = item } } else { if selectedIndex < rewriteItems.count { item = rewriteItems[selectedIndex] desti.rewriteItem = item } else { item = ruleItems[selectedIndex - rewriteItems.count] desti.ruleItem = item } } desti.showDelete = true } else { desti.showDelete = false } } } } }
99701446993982d4b56c5769bfa3a43d
39.02799
193
0.613883
false
false
false
false
i-schuetz/tableview_infinite
refs/heads/master
AsyncTableView/ViewController.swift
apache-2.0
1
// // ViewController.swift // AsyncTableView // // Created by ischuetz on 27/06/2014. // Copyright (c) 2014 ivanschuetz. All rights reserved. // import UIKit struct MyItem { let name: String init(name: String) { self.name = name } } class MyDataProvider { static var instance: MyDataProvider { return MyDataProvider() } func requestData(offset: Int, size: Int, listener: [MyItem] -> Void) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { // simulate delay sleep(2) // generate items let items = (offset...(offset + size)).map { MyItem(name: "Item \($0)") } // call listener in main thread dispatch_async(dispatch_get_main_queue()) { listener(items) } } } } class ViewController: UITableViewController { @IBOutlet var tableViewFooter: MyFooter! private let pageSize = 20 private var items: [MyItem] = [] private var loading = false { didSet { tableViewFooter.hidden = !loading } } override func scrollViewDidScroll(scrollView: UIScrollView) { let currentOffset = scrollView.contentOffset.y let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height if (maximumOffset - currentOffset) <= 40 { loadSegment(items.count, size: pageSize) } } override func viewDidLoad() { super.viewDidLoad() tableViewFooter.hidden = true loadSegment(0, size: pageSize) } func loadSegment(offset: Int, size: Int) { if (!loading) { loading = true MyDataProvider.instance.requestData(offset, size: size) {[weak self] items in for item in items { self?.items.append(item) } self?.tableView.reloadData() self?.loading = false } } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) let item = items[indexPath.row] cell.textLabel?.text = item.name return cell } }
cf81c350ea2c27de5ee9d805c27f0bd5
24.119266
118
0.565741
false
false
false
false
ephread/Instructions
refs/heads/main
Examples/Example/Sources/Core/Custom Views/CustomCoachMarkArrowView.swift
mit
1
// Copyright (c) 2015-present Frédéric Maquin <fred@ephread.com> and contributors. // Licensed under the terms of the MIT License. import UIKit import Instructions // Custom coach mark body (with the secret-like arrow) internal class CustomCoachMarkArrowView: UIView, CoachMarkArrowView { // MARK: - Internal properties var topPlateImage = UIImage(named: "coach-mark-top-plate") var bottomPlateImage = UIImage(named: "coach-mark-bottom-plate") var plate = UIImageView() var isHighlighted: Bool = false // MARK: - Private properties private var column = UIView() // MARK: - Initialization init(orientation: CoachMarkArrowOrientation) { super.init(frame: CGRect.zero) if orientation == .top { self.plate.image = topPlateImage } else { self.plate.image = bottomPlateImage } self.translatesAutoresizingMaskIntoConstraints = false self.column.translatesAutoresizingMaskIntoConstraints = false self.plate.translatesAutoresizingMaskIntoConstraints = false self.addSubview(plate) self.addSubview(column) plate.backgroundColor = UIColor.clear column.backgroundColor = UIColor.white plate.fillSuperviewHorizontally() NSLayoutConstraint.activate([ column.widthAnchor.constraint(equalToConstant: 3), column.centerXAnchor.constraint(equalTo: centerXAnchor) ]) if orientation == .top { NSLayoutConstraint.activate( NSLayoutConstraint.constraints( withVisualFormat: "V:|[plate(==5)][column(==10)]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["plate": plate, "column": column] ) ) } else { NSLayoutConstraint.activate( NSLayoutConstraint.constraints( withVisualFormat: "V:|[column(==10)][plate(==5)]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["plate": plate, "column": column] ) ) } } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding.") } }
3c655782dd3e7cc4754add418ccecd30
33.26087
82
0.60956
false
false
false
false
TigerWolf/LoginKit
refs/heads/master
LoginKit/AppearanceController.swift
bsd-3-clause
1
// // Appearance.swift // LoginKit // // Created by Kieran Andrews on 14/02/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import SVProgressHUD public let Appearance = AppearanceController.sharedInstance open class AppearanceController { static let sharedInstance = AppearanceController() open var backgroundColor = UIColor.blue open var whiteColor = UIColor.white open var buttonColor = UIColor.red open var buttonBorderColor = UIColor.white }
9b19b687fa4e22700a37317ff0bfe5b5
20.125
59
0.739645
false
false
false
false
zhihuitang/Apollo
refs/heads/master
Apollo/DeviceKit.swift
apache-2.0
1
// // DeviceKit.swift // Apollo // // Created by Zhihui Tang on 2017-09-05. // Copyright © 2017 Zhihui Tang. All rights reserved. // import Foundation class DeviceKit { /** https://stackoverflow.com/questions/31220371/detect-hotspot-enabling-in-ios-with-private-apis https://stackoverflow.com/questions/30748480/swift-get-devices-ip-address */ class func getNetWorkInfo() -> [String:String]? { var address : String? var networkInfo = [String:String]() // Get list of all interfaces on the local machine: var ifaddr : UnsafeMutablePointer<ifaddrs>? guard getifaddrs(&ifaddr) == 0 else { return nil } guard let firstAddr = ifaddr else { return nil } // For each interface ... for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { let interface = ifptr.pointee // Check for IPv4 or IPv6 interface: let addrFamily = interface.ifa_addr.pointee.sa_family if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) { // Check interface name: let name = String(cString: interface.ifa_name) //print("network name: \(name)") //if name == "en0" { // Convert interface address to a human readable string: var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) address = String(cString: hostname) networkInfo[name] = address //} } } freeifaddrs(ifaddr) return networkInfo } class func getWifiAddr() -> String? { return getNetWorkInfo()?["en0"] } }
b4b73c97efcf9591df3c4d9e5383097a
33.288136
98
0.549184
false
false
false
false
JerrySir/YCOA
refs/heads/master
YCOA/Main/Apply/Controller/OnBusinessCreatViewController.swift
mit
1
// // OnBusinessCreatViewController.swift // YCOA // // Created by Jerry on 2016/12/22. // Copyright © 2016年 com.baochunsteel. All rights reserved. // // 出差 import UIKit class OnBusinessCreatViewController: UIViewController { @IBOutlet weak var selectTypeButton: UIButton! //外出类型 @IBOutlet weak var selectStartTimeButton: UIButton! //开始时间 @IBOutlet weak var selectEndTimeButton: UIButton! //预计回岗时间 @IBOutlet weak var addressTextFiled: UITextField! //地址 @IBOutlet weak var reasonTextFiled: UITextField! //事由 @IBOutlet weak var otherInfoTextView: UITextView! //说明 @IBOutlet weak var submitButton: UIButton! //提交 @IBOutlet weak var backGroundView: UIScrollView! //背景View //同步的数据 //Private private var selectedType : String? //选择的类型 private var selectedStartTime : String? //外出时间 private var selectedEndTime : String? //回岗时间 override func viewDidLoad() { super.viewDidLoad() self.title = "出差" self.UIConfigure() self.ActionConfigure() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Action //绑定控件Action func ActionConfigure() { //外出类型 self.selectTypeButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in let type = ["外出", "出差"] UIPickerView.showDidSelectView(SingleColumnDataSource: type, onView: self.navigationController!.view, selectedTap: { (index) in self.selectedType = type[index] self.selectTypeButton.setTitle(self.selectedType!, for: .normal) }) } //外出时间 self.selectStartTimeButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in self.view.endEditing(true) UIDatePicker.showDidSelectView(minDate: Date(), maxDate: nil, onView: self.navigationController!.view, datePickerMode: .dateAndTime, tap: { (date) in self.selectedStartTime = (date as NSDate).string(withFormat: "yyyy-MM-dd HH:mm:00") self.selectStartTimeButton.setTitle(self.selectedStartTime!, for: .normal) }) } //回岗时间 self.selectEndTimeButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in self.view.endEditing(true) UIDatePicker.showDidSelectView(minDate: Date(), maxDate: nil, onView: self.navigationController!.view, datePickerMode: .dateAndTime, tap: { (date) in self.selectedEndTime = (date as NSDate).string(withFormat: "yyyy-MM-dd HH:mm:00") self.selectEndTimeButton.setTitle(self.selectedEndTime!, for: .normal) }) } //提交 self.submitButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in self.didSubmit() } //backGroundView self.backGroundView.isUserInteractionEnabled = true let tapGestureRecognizer = UITapGestureRecognizer { (sender) in self.view.endEditing(true) } self.backGroundView.addGestureRecognizer(tapGestureRecognizer) } //提交 private func didSubmit() { guard let atype_ : String = self.selectedType else { self.navigationController?.view.jrShow(withTitle: "请选择外出类型!") return } guard let outtime_ : String = self.selectedStartTime else { self.navigationController?.view.jrShow(withTitle: "请选择外出时间") return } guard let intime_ : String = self.selectedEndTime else { self.navigationController?.view.jrShow(withTitle: "请选择回岗时间") return } let address_ = self.addressTextFiled.text if(!(address_ != nil && address_!.utf8.count > 0)){ self.navigationController?.view.jrShow(withTitle: "请填写地址!") return } let reason_ = self.reasonTextFiled.text if(!(reason_ != nil && reason_!.utf8.count > 0)){ self.navigationController?.view.jrShow(withTitle: "请填写外出事由!") return } var parameters: [String : Any] = ["atype" : atype_, "outtime" : outtime_, "intime" : intime_, "address" : address_!, "reason" : reason_!] //可选 let explain_ : String = self.otherInfoTextView.text if(explain_.utf8.count > 0){ parameters["explain"] = explain_ } let url = "/index.php?d=taskrun&m=flow_waichu|appapi&a=save&ajaxbool=true&adminid=\(UserCenter.shareInstance().uid!)&timekey=\(NSDate.nowTimeToTimeStamp())&token=\(UserCenter.shareInstance().token!)&cfrom=appiphone&appapikey=\(UserCenter.shareInstance().apikey!)" YCOA_NetWork.post(url: url, parameters: parameters) { (error, returnValue) in if(error != nil){ self.navigationController?.view.jrShow(withTitle: error!.domain) return } self.navigationController?.view.jrShow(withTitle: "提交成功!") } } //MARK: - UI //配置控件UI func UIConfigure() { self.makeTextFieldStyle(sender: self.selectTypeButton) self.makeTextFieldStyle(sender: self.selectStartTimeButton) self.makeTextFieldStyle(sender: self.selectEndTimeButton) self.makeTextFieldStyle(sender: self.otherInfoTextView) self.makeTextFieldStyle(sender: self.submitButton) } ///设置控件成为TextField一样的样式 func makeTextFieldStyle(sender: UIView) { sender.layer.masksToBounds = true sender.layer.cornerRadius = 10/2 sender.layer.borderWidth = 0.3 sender.layer.borderColor = UIColor.lightGray.cgColor } /* // 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. } */ }
f869e3150c760ae6a7209b16e3583f07
35.3125
271
0.603974
false
false
false
false
hackersatcambridge/hac-website
refs/heads/master
Sources/HaCWebsiteLib/Views/Page.swift
mit
2
import HaCTML import Foundation struct Page: Nodeable { let title: String let postFixElements: Nodeable let content: Nodeable init(title: String = defaultTitle, postFixElements: Nodeable = Fragment(), content: Nodeable) { self.title = title self.postFixElements = postFixElements self.content = content } public var node: Node { return Fragment( El.Doctype, El.Html[Attr.lang => "en"].containing( El.Head.containing( El.Meta[Attr.charset => "UTF-8"], El.Meta[Attr.name => "viewport", Attr.content => "width=device-width, initial-scale=1"], El.Link[Attr.rel => "icon", Attr.type => "favicon/png", Attr.href => Assets.publicPath("/images/favicon.png")], El.Title.containing(title), Page.stylesheet(forUrl: Assets.publicPath("/styles/main.css")), postFixElements ) ), El.Body.containing( errorReport, content, GAScript() ) ) } func render() -> String { return node.render() } /// Get a view of the `swift build` output if it didn't exit with exit code zero private var errorReport: Node? { if let errorData = try? Data(contentsOf: URL(fileURLWithPath: "swift_build.log")) { return Fragment( El.Pre.containing( El.Code[Attr.className => "BuildOutput__Error"].containing(String(data: errorData, encoding: String.Encoding.utf8) as String!) ) ) } else { return nil } } private static let defaultTitle = "Cambridge's student tech society | Hackers at Cambridge" public static func stylesheet(forUrl urlString: String) -> Node { return El.Link[Attr.rel => "stylesheet", Attr.type => "text/css", Attr.href => urlString] } }
bbfeea59c76b9b2a4b68d271e775b940
29.431034
136
0.631161
false
false
false
false
Sharelink/Bahamut
refs/heads/master
Bahamut/BahamutRFKit/File/AliOSSFile.swift
mit
1
// // AliOSSFile.swift // Bahamut // // Created by AlexChow on 15/11/25. // Copyright © 2015年 GStudio. All rights reserved. // import Foundation /* POST /AliOSSFiles (fileType,fileSize) : get a new send file key for upload task */ open class NewAliOSSFileAccessInfoRequest : BahamutRFRequestBase { public override init() { super.init() self.api = "/AliOSSFiles" self.method = .post } open override func getMaxRequestCount() -> Int32 { return BahamutRFRequestBase.maxRequestNoLimitCount } open var fileType:FileType! = .noType{ didSet{ self.paramenters["fileType"] = "\(fileType!.rawValue)" } } open var fileSize:Int = 512 * 1024{ //byte didSet{ self.paramenters["fileSize"] = "\(fileSize)" } } } /* POST /AliOSSFiles/List (fileTypes,fileSizes) : get a new send files key for upload task */ open class NewAliOSSFileAccessInfoListRequest : BahamutRFRequestBase { public override init() { super.init() self.api = "/AliOSSFiles/List" self.method = .post } open var fileTypes:[FileType]!{ didSet{ if fileTypes != nil && fileTypes.count > 0 { self.paramenters["fileTypes"] = fileTypes.map{"\($0.rawValue)"}.joined(separator: "#") } } } open var fileSizes:[Int]!{ //byte didSet{ if fileSizes != nil && fileSizes.count > 0 { self.paramenters["fileSizes"] = fileSizes.map{"\($0)"}.joined(separator: "#") } } } open override func getMaxRequestCount() -> Int32 { return BahamutRFRequestBase.maxRequestNoLimitCount } }
10ab44b54c53b0573c4cab6d03ac91cc
23.273973
102
0.575056
false
false
false
false
kaideyi/KDYSample
refs/heads/master
Charting/Charting/Charts/PieChart/PieChartView.swift
mit
1
// // PieChartView.swift // Charting // // Created by mac on 17/3/6. // Copyright © 2017年 kaideyi.com. All rights reserved. // import UIKit /// 饼状图 class PieChartView: UIView { var pieLayer: CAShapeLayer! override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear drawPiesView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func drawPiesView() { let data: [CGFloat] = [25.0, 40.0, 35.0] var startA: CGFloat = 0.0 var endA: CGFloat = 0.0 pieLayer = CAShapeLayer() self.layer.addSublayer(pieLayer) let innnerRadius = self.width / 6.0 let outerRadius = self.width / 2.0 let lineWidth = outerRadius - innnerRadius let radius = (outerRadius + innnerRadius) * 0.5 for value in data { endA = CGFloat(value / 100) + startA let path = UIBezierPath() let centerPos = self.center path.addArc(withCenter: centerPos, radius: radius, startAngle: -(CGFloat)(M_PI_2), endAngle: CGFloat(M_PI_2) * 3, clockwise: true) let layer = CAShapeLayer() layer.path = path.cgPath layer.lineWidth = lineWidth layer.strokeColor = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0).cgColor layer.fillColor = UIColor.clear.cgColor layer.strokeStart = startA layer.strokeEnd = endA pieLayer.addSublayer(layer) startA = endA } let maskLayer = drawPie() pieLayer.mask = maskLayer let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = 0.0 animation.toValue = 1.0 animation.duration = 1.5 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) pieLayer.mask?.add(animation, forKey: nil) } func drawPie() -> CAShapeLayer { let innnerRadius = self.width / 6.0 let outerRadius = self.width / 2.0 let lineWidth = outerRadius - innnerRadius let radius = (outerRadius + innnerRadius) * 0.5 let path = UIBezierPath() let centerPos = self.center path.addArc(withCenter: centerPos, radius: radius, startAngle: -(CGFloat)(M_PI_2), endAngle: CGFloat(M_PI_2) * 3, clockwise: true) let layer = CAShapeLayer() layer.path = path.cgPath layer.lineWidth = lineWidth layer.strokeColor = UIColor.red.cgColor layer.fillColor = UIColor.clear.cgColor layer.strokeStart = 0.0 layer.strokeEnd = 1.0 return layer } }
b6018b044af59f36fac07f1c4cac44c5
30.478261
142
0.579765
false
false
false
false
dpskvn/PhotoBombersSwift
refs/heads/master
Photo Bombers/DetailViewController.swift
mit
1
// // DetailViewController.swift // Photo Bombers // // Created by Dino Paskvan on 09/06/14. // Copyright (c) 2014 Dino Paskvan. All rights reserved. // import UIKit class DetailViewController: UIViewController { var photo: NSDictionary? var imageView: UIImageView? var animator: UIDynamicAnimator? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 1.0, alpha: 0.95) imageView = UIImageView(frame: CGRectMake(0.0, -320.0, 320.0, 320.0)) view.addSubview(imageView) PhotoController.imageForPhoto(photo!, size: "standard_resolution", completion: { image in self.imageView!.image = image }) let tap = UITapGestureRecognizer(target: self, action: "close") view.addGestureRecognizer(tap) animator = UIDynamicAnimator(referenceView: view) } override func viewDidAppear(animated: Bool) { let snap = UISnapBehavior(item: imageView, snapToPoint: view.center) animator!.addBehavior(snap) } func close () { animator!.removeAllBehaviors() let snap = UISnapBehavior(item: imageView, snapToPoint: CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMaxY(view.bounds) + 180.0)) animator!.addBehavior(snap) self.dismissViewControllerAnimated(true, completion: {}) } }
da3d07c20ef503e279133ef0f4319fab
30.217391
140
0.641365
false
false
false
false
KaneCheshire/Communicator
refs/heads/main
Example/WatchExample Extension/InterfaceController.swift
mit
1
// // InterfaceController.swift // WatchExample Extension // // Created by Kane Cheshire on 19/07/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import WatchKit import Communicator class InterfaceController: WKInterfaceController { @IBAction func sendMessageTapped() { let message = ImmediateMessage(identifier: "message", content: ["hello": "world"]) Communicator.shared.send(message) } @IBAction func sendInteractiveMessageTapped() { let message = InteractiveImmediateMessage(identifier: "interactive_message", content: ["hello": "world"]) { reply in print("Received reply from message: \(reply)") } Communicator.shared.send(message) } @IBAction func sendGuaranteedMessageTapped() { let message = GuaranteedMessage(identifier: "guaranteed_message", content: ["hello": "world"]) Communicator.shared.send(message) { result in switch result { case .failure(let error): print("Error transferring blob: \(error.localizedDescription)") case .success: print("Successfully transferred guaranteed message to phone") } } } @IBAction func transferBlobTapped() { let data = Data("hello world".utf8) let blob = Blob(identifier: "blob", content: data) Communicator.shared.transfer(blob) { result in switch result { case .failure(let error): print("Error transferring blob: \(error.localizedDescription)") case .success: print("Successfully transferred blob to phone") } } } @IBAction func syncContextTapped() { let context = Context(content: ["hello" : "world"]) do { try Communicator.shared.sync(context) print("Synced context to phone") } catch let error { print("Error syncing context to phone: \(error.localizedDescription)") } } }
142b1d337f38c44339d0fc9c68cdd47a
32.580645
124
0.598463
false
false
false
false
webninjamobile/marys-rosary
refs/heads/master
controllers/PrayerSingleViewController.swift
gpl-2.0
1
// // PrayerSingleViewController.swift // PrayerBook // // Created by keithics on 8/12/15. // Copyright (c) 2015 Web Ninja Technologies. All rights reserved. // import UIKit import AVFoundation class PrayerSingleViewController: UIViewController , AVAudioPlayerDelegate{ var myTitle: String = "" var mysteryIndex: Int = 0 var currentProgress: Int = 0 @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var prayerTitle: UILabel! @IBOutlet weak var prayer: UILabel! @IBOutlet weak var btnToggleBgMusic: UIButton! @IBOutlet weak var btnPlay: UIButton! @IBOutlet weak var btnNext: UIButton! @IBOutlet weak var btnPrev: UIButton! let beads = [("Start",12.5),("I",20),("II",20),("III",20),("IV",20),("V",20),("End",12.5)] let beadsIndex = [8,22,36,50,64,78,86] let beadsNumPrayers = [8,14,14,14,14,13,8] var currentBead = 0; var beadsArray : [CircleProgress] = [] var beadsTap: UITapGestureRecognizer? var rosary : [(String,String,String,Int)] = [] var mp3:AVAudioPlayer = AVAudioPlayer() var backgroundMusic:AVAudioPlayer = AVAudioPlayer() var autoPlay = false var hasLoadedMp3 = false var isPlaying = false // has the user clicked the play button? var nextDelay = 0; // var isDonePlaying = false //check if the music has done playing, for pause/play let userDefaults = NSUserDefaults.standardUserDefaults() var saveDefaults = false; var isBackgroundPlaying = false override func viewDidLoad() { super.viewDidLoad() let rosary = Rosary(); self.rosary = rosary.prayRosary(self.mysteryIndex); // prepare rosary audio checkMp3(rosary) let screenSize: CGRect = UIScreen.mainScreen().bounds let screenWidth = screenSize.width let fullWidth = screenWidth/7; let pad = 4; let dimen = CGFloat(Int(fullWidth) - pad); self.title = self.myTitle; _ = 10; //create beads for i in 0...6 { let newX = CGFloat((i * Int(fullWidth)) + pad); let beadsProgress = CircleProgress(frame: CGRectMake(newX, 80, dimen, dimen)) let (title,size) = beads[i] beadsProgress.tag = i beadsProgress.progressLabel.text = title beadsProgress.progressLabel.font = UIFont(name: "KefaIIPro-Regular", size: CGFloat(size)) beadsTap = UITapGestureRecognizer(target: self , action: Selector("gotoBead:")) beadsTap!.numberOfTapsRequired = 1 beadsProgress.addGestureRecognizer(beadsTap!) self.view.addSubview(beadsProgress) beadsArray.append(beadsProgress) //DynamicView.animateProgressView() } //println(rosary.prayRosary(mysteryIndex)) self.prayer.sizeToFit() self.btnPrev.setTitle("\u{f04a}",forState: UIControlState.Normal) self.btnNext.setTitle("\u{f04e}",forState: UIControlState.Normal) self.btnPlay.setTitle("\u{f04b}",forState: UIControlState.Normal) self.btnToggleBgMusic.setTitle("\u{f001}",forState: UIControlState.Normal) // self.navigationItem.title = "asd"; //self.parentViewController.view.backgroundColor = UIColor.redColor(); //restore bead var lastProgress = 0; if self.mysteryIndex == userDefaults.integerForKey("lastMystery") { self.currentBead = userDefaults.integerForKey("lastBead"); lastProgress = userDefaults.integerForKey("lastProgress") } pray(lastProgress,recite:false) checkControls() // swipes let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:")) let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:")) leftSwipe.direction = .Left rightSwipe.direction = .Right view.addGestureRecognizer(leftSwipe) view.addGestureRecognizer(rightSwipe) let pathBackground = NSBundle.mainBundle().pathForResource("avemaria", ofType: "mp3") backgroundMusic = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: pathBackground!)) backgroundMusic.volume = 0.1 backgroundMusic.numberOfLoops = -1; backgroundMusic.prepareToPlay() } func back(){ self.navigationController?.popViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func pray(currentIndex : Int,direction : String = "forward",recite: Bool = false){ self.prayer.fadeOut() self.prayerTitle.fadeOut() let (title,content,mp3,delay) = self.rosary[currentIndex] self.prayer.text = content self.prayerTitle.text = title self.nextDelay = delay if(recite){ //do not play if last prayer playMp3(mp3,delay:delay) } self.prayer.fadeIn() self.prayerTitle.fadeIn() if(currentIndex >= self.beadsIndex[self.currentBead]){ //next bead self.currentBead++ } showHideBeadProgress(self.currentBead) let mulcrement : CGFloat = CGFloat((100/self.beadsNumPrayers[self.currentBead]))/100 let currentProgress = currentIndex < self.beadsNumPrayers[0] ? currentIndex : (currentIndex - self.beadsIndex[self.currentBead - 1]) let nextcrement : CGFloat = CGFloat(Double(currentProgress) + 1.00) if (direction == "forward"){ beadsArray[self.currentBead].animateProgressView(mulcrement * CGFloat(Double(currentProgress)) , to: mulcrement * nextcrement) }else{ //back beadsArray[self.currentBead].animateProgressView( (mulcrement * nextcrement) + mulcrement, to: mulcrement * nextcrement) } self.currentProgress = currentIndex checkControls() //save current progress if(self.saveDefaults){ userDefaults.setInteger(self.currentProgress,forKey: "lastProgress") userDefaults.setInteger(self.currentBead,forKey: "lastBead") userDefaults.setInteger(self.mysteryIndex,forKey: "lastMystery") } } @IBAction func onNext(sender: AnyObject) { self.autoPlay = false nextPrayer(false, willPause: true) } func nextPrayer(autoplay : Bool = false , willPause: Bool = false){ if willPause { pauseMp3() } userMoved() pray(self.currentProgress.maxcrement(self.rosary.count - 1),recite:autoplay) } @IBAction func onPrev(sender: AnyObject) { userMoved() pauseMp3() let currentIndex = self.currentProgress.mincrement //println(currentIndex) if(currentIndex <= self.beadsIndex[self.currentBead ]){ //clear prev bead beadsArray[self.currentBead].hideProgressView() //prev bead self.currentBead = self.currentBead.mincrement } pray(currentIndex,direction: "back") } @IBAction func onPlay(sender: AnyObject) { self.saveDefaults = true if self.hasLoadedMp3 && !isDonePlaying && !self.isPlaying { //mp3 is paused mp3.play() // play the old one playBackground() self.autoPlay = true isDonePlaying = false isPlaying = true // pray(self.currentProgress,recite:false) self.btnPlay.setTitle("\u{f04c}",forState: UIControlState.Normal) } else if !isPlaying { playBackground() self.autoPlay = true pray(self.currentProgress,recite:true) self.btnPlay.setTitle("\u{f04c}",forState: UIControlState.Normal) }else { self.btnToggleBgMusic.alpha = 1 pauseBackground() pauseMp3() } } @IBAction func toggleBgMusic(sender: AnyObject) { //TODO , set to userdefaults if(isBackgroundPlaying){ pauseBackground() }else{ playBackground() } } func playBackground(){ backgroundMusic.play() btnToggleBgMusic.alpha = 0.5 isBackgroundPlaying = true } func pauseBackground(){ backgroundMusic.pause() btnToggleBgMusic.alpha = 1 isBackgroundPlaying = false } func checkControls(){ if(self.currentProgress == 0){ btnPrev.alpha = 0.5 btnPrev.enabled = false }else{ btnPrev.alpha = 1.0 btnPrev.enabled = true } if(self.currentProgress >= self.rosary.count - 1){ btnNext.alpha = 0.5 btnNext.enabled = false }else{ btnNext.alpha = 1.0 btnNext.enabled = true } } func gotoBead(sender: UITapGestureRecognizer!){ if sender.state == .Ended { let currentBead = sender.view!.tag self.currentBead = currentBead let currentPrayer = currentBead > 0 ? self.beadsIndex[currentBead - 1] : 0; // let playmp3 = currentBead > 0 ? true : false userMoved() pauseMp3() pray(currentPrayer,recite:false) } } func showHideBeadProgress(currentBead : Int){ for i in 0..<currentBead { //println(i) beadsArray[i].showProgressView() } for i in currentBead ..< beadsArray.count { // println(currentBead) beadsArray[i].hideProgressView() } } func handleSwipes(sender:UISwipeGestureRecognizer) { if (sender.direction == .Left) { btnNext.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } if (sender.direction == .Right) { btnPrev.sendActionsForControlEvents(UIControlEvents.TouchUpInside) } } func playMp3(file : String, delay : Int) { if(delay == 0){ mp3 = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(file, ofType: "mp3")!)) }else{ //play processed audio instead let paths = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let documentsURL = paths[0] let processedAudio = documentsURL.URLByAppendingPathComponent(file.m4a) try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) mp3 = try! AVAudioPlayer(contentsOfURL: processedAudio) } mp3.prepareToPlay() self.hasLoadedMp3 = true mp3.delegate = self mp3.play() isDonePlaying = false isPlaying = true } func userMoved(){ //triggered if user taps on prev,next or beads self.isDonePlaying = true self.isPlaying = false } func pauseMp3(){ if(self.hasLoadedMp3){ self.isPlaying = false self.autoPlay = false self.mp3.pause(); self.btnPlay.setTitle("\u{f04b}",forState: UIControlState.Normal) } } /* Prepare audio and delete if audio is already processed */ func toggleControls(enable : Bool , alpha : Double){ self.btnNext.enabled = enable self.btnNext.alpha = CGFloat(alpha) self.btnPlay.enabled = enable self.btnPlay.alpha = CGFloat(alpha) } func prepareAudio(rosary : Rosary){ var status : [Bool] = [] for (_, subJson): (String, JSON) in JSON(data:rosary.rosaryJson) { if subJson["delay"] > 0 { let isOkay = Audio().merge(subJson["mp3"].stringValue,silence: Double(subJson["delay"].intValue)) status.append(isOkay) } }; for index in rosary.mysteries{ let isOkay = Audio().merge(index + "mystery",silence: 3) status.append(isOkay) } let isOK = !status.contains(true) if !isOK { notifyUserError() } userDefaults.setBool(isOK, forKey: "hasProcessed") } func checkMp3(rosary :Rosary){ if !userDefaults.boolForKey("hasProcessed"){ let qualityOfServiceClass = QOS_CLASS_BACKGROUND let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0) dispatch_async(backgroundQueue, { self.toggleControls(false,alpha: 0.5) self.prepareAudio(rosary) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.toggleControls(true,alpha: 1) }) }) }else{ var audiofiles : [String] = []; //check if mp3 files exists, just in case :) for (_, subJson): (String, JSON) in JSON(data:rosary.rosaryJson) { if subJson["delay"] > 0 { audiofiles.append(subJson["mp3"].stringValue) } }; for index in rosary.mysteries{ audiofiles.append(index + "mystery") } let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let checkValidation = NSFileManager.defaultManager() for eachAudio in audiofiles{ let exportPath = (docPath as NSString).stringByAppendingPathComponent(eachAudio.m4a) if (!checkValidation.fileExistsAtPath(exportPath)) { notifyUserError() break } } } } func notifyUserError(){ let refreshAlert = UIAlertController(title: "Error", message: "Error saving audio files. ", preferredStyle: UIAlertControllerStyle.Alert) refreshAlert.addAction(UIAlertAction(title: "Retry", style: .Default, handler: { (action: UIAlertAction) in NSUserDefaults.standardUserDefaults().setBool(false, forKey: "hasProcessed") self.back() })) self.presentViewController(refreshAlert, animated: true, completion: nil) } // delegates func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) { isDonePlaying = true if(self.autoPlay && self.currentProgress < self.rosary.count - 1){ self.nextPrayer(true) } if(self.currentProgress == self.rosary.count - 1){ // last item //change play button self.btnPlay.setTitle("\u{f04b}",forState: UIControlState.Normal) let fader = iiFaderForAvAudioPlayer(player: backgroundMusic) fader.volumeAlterationsPerSecond = 10 fader.fadeOut(7, velocity: 1) // backgroundMusic.fadeOut() } } }
e417e39d055a6f527b5b96534e492054
30.760479
145
0.568942
false
false
false
false
plus44/mhml-2016
refs/heads/master
app/Helmo/Helmo/WebServiceManager.swift
gpl-3.0
1
// // WebServiceManager.swift // Helmo // // Created by Mihnea Rusu on 10/03/17. // Copyright © 2017 Mihnea Rusu. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class WebServiceManager: NSObject { static let sharedInstance = WebServiceManager() let baseFallQueryURL = "http://123wedonthaveaservercuzshawnisaslacker.com/falls.php" /** Get 10 falls starting from an offset down the long list of falls. - Parameters: - offset: Integer offset down the list of falls from which to start fetching data - onCompletion: User-registered on-complete handler that gets called once the request has returned, with the falls in a JSON objects. */ func getFalls(offset: Int, onCompletion: @escaping (JSON) -> Void) { let parameters = ["offset" : offset] as Parameters sendGetRequest(path: baseFallQueryURL, parameters: parameters, onCompletion: onCompletion) } /** Get the total number of falls available for the authenticated user in the database. - Parameter onCompletion: A user-registered handler that will give the caller access to the returned 'count' parameter as an integer. */ func getFallCount(onCompletion: @escaping (Int) -> Void) { let parameters = ["count" : ""] as Parameters var count = 0 sendGetRequest(path: baseFallQueryURL, parameters: parameters) { json in if json != JSON.null { count = json["count"].intValue onCompletion(count) } } } /** Send a get request to the path, with given parameters encoded in the URL. - Parameters: - path: The URL path to which to send the request to. - parameters: What parameters to URL encode - onCompletion: Handler that gets called with the returned server JSON response, on the same thread as the request. If an invalid reponse is received, JSON.null will be returned as the argument */ private func sendGetRequest(path: String, parameters: Parameters, onCompletion: @escaping (JSON) -> Void) { Alamofire.request(path, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil) .response { response in if let responseJSON = response.data { onCompletion(JSON(data: responseJSON)) } else { print("\(#file): responseJSON nil") onCompletion(JSON.null) } } // end of response closure } // end of func sendGetRequest }
ad7f6be77a6d4ca2bb198cc79e366eb3
38.028986
205
0.627553
false
false
false
false
markedwardmurray/Starlight
refs/heads/master
Starlight/Starlight/Controllers/AboutTableViewController.swift
mit
1
// // AboutTableViewController.swift // Starlight // // Created by Mark Murray on 11/20/16. // Copyright © 2016 Mark Murray. All rights reserved. // import UIKit import MessageUI import Down enum AboutTVCIndex: Int { case database, sunlight, oss, github, contact } class AboutTableViewController: UITableViewController, MFMailComposeViewControllerDelegate { static let navConStoryboardId = "AboutNavigationController" @IBOutlet var menuBarButton: UIBarButtonItem! @IBOutlet var tableHeaderViewLabel: UILabel! @IBOutlet var tableFooterViewLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() if self.revealViewController() != nil { self.menuBarButton.target = self.revealViewController() self.menuBarButton.action = Selector(("revealToggle:")) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")! let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")! self.tableFooterViewLabel.text = "Made in USA\n" + "v\(appVersion) (\(build))" } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let index = AboutTVCIndex(rawValue: indexPath.row)! switch index { case .database: self.usCongressDatabaseCellSelected() break; case .sunlight: self.sunlightCellSelected() break case .oss: self.openSourceCellSelected() break case .github: self.githubCellSelected() break case .contact: self.contactCellSelected() break } tableView.deselectRow(at: indexPath, animated: true) } func usCongressDatabaseCellSelected() { guard let url = URL(string: "https://github.com/unitedstates/congress-legislators") else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } func sunlightCellSelected() { guard let url = URL(string: "https://sunlightlabs.github.io/congress") else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } func openSourceCellSelected() { let url_str = Bundle.main.path(forResource: "Pods-Starlight-acknowledgements", ofType: "markdown")! let url = URL(fileURLWithPath: url_str) var markdown = "" do { markdown = try String.init(contentsOf: url, encoding: .utf8) } catch { print(error) return } let ossVC = UIViewController() ossVC.title = "Acknowledgements" let downView = try? DownView(frame: self.view.frame, markdownString: markdown) if let downView = downView { ossVC.view.addSubview(downView) downView.translatesAutoresizingMaskIntoConstraints = false downView.leadingAnchor.constraint(equalTo: ossVC.view.leadingAnchor).isActive = true downView.topAnchor.constraint(equalTo: ossVC.view.topAnchor).isActive = true downView.trailingAnchor.constraint(equalTo: ossVC.view.trailingAnchor).isActive = true downView.bottomAnchor.constraint(equalTo: ossVC.view.bottomAnchor).isActive = true self.navigationController?.pushViewController(ossVC, animated: true); } } func githubCellSelected() { guard let url = URL(string: "https://github.com/markedwardmurray/starlight") else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } func contactCellSelected() { let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.present(mailComposeViewController, animated: true, completion: nil) } else { self.showAlertWithTitle(title: "Error!", message: "Email is not configured on this device.") } } func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setToRecipients(["starlightcongress@gmail.com"]) mailComposerVC.setSubject("iOS In-App Email") let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")! let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")! let systemVersion = UIDevice.current.systemVersion let model = UIDevice.current.model let firstLanguage = NSLocale.preferredLanguages.first! let messageBody = "\n\n\n" + "v\(appVersion) (\(build))\n" + "iOS \(systemVersion), \(model)\n" + "\(firstLanguage)" mailComposerVC.setMessageBody(messageBody, isHTML: false) return mailComposerVC } // MARK: MFMailComposeViewControllerDelegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { if error != nil { self.showAlertWithTitle(title: "Failed to Send", message: error!.localizedDescription) } else { controller.dismiss(animated: true, completion: nil) } } }
997f911e0ce405dc432b792ba9b1f6e6
36.891892
133
0.645685
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Controllers/Preferences/PreferencesViewModel.swift
mit
1
// // PreferencesViewModel.swift // Rocket.Chat // // Created by Rafael Ramos on 31/03/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import UIKit internal enum BundleInfoKey: String { case version = "CFBundleShortVersionString" case build = "CFBundleVersion" } final class PreferencesViewModel { internal let title = localized("myaccount.settings.title") internal let profile = localized("myaccount.settings.profile") internal let administration = localized("myaccount.settings.administration") internal let contactus = localized("myaccount.settings.contactus") internal let license = localized("myaccount.settings.license") internal let language = localized("myaccount.settings.language") internal let webBrowser = localized("myaccount.settings.web_browser") internal let appicon = localized("myaccount.settings.appicon") internal let review = localized("myaccount.settings.review") internal let share = localized("myaccount.settings.share") internal let theme = localized("theme.settings.title") internal let licenseURL = URL(string: "https://github.com/RocketChat/Rocket.Chat.iOS/blob/develop/LICENSE") internal let shareURL = URL(string: "https://itunes.apple.com/app/rocket-chat/id1148741252?ls=1&mt=8") internal let reviewURL = URL(string: "itms-apps://itunes.apple.com/app/id1148741252?action=write-review&mt=8") internal let trackingTitle = localized("myaccount.settings.tracking.title") internal var trackingFooterText = localized("myaccount.settings.tracking.footer") internal var serverName: String { var serverName = "Rocket.Chat" if let authServerName = AuthSettingsManager.settings?.serverName { serverName = authServerName } else if let serverURL = AuthManager.isAuthenticated()?.serverURL { if let host = URL(string: serverURL)?.host { serverName = host } else { serverName = serverURL } } return serverName } internal var logout: String { return String(format: localized("myaccount.settings.logout"), serverName) } internal var trackingValue: Bool { return !AnalyticsCoordinator.isUsageDataLoggingDisabled } internal var formattedVersion: String { return String(format: localized("myaccount.settings.version"), version, build) } internal var formattedServerVersion: String { let serverVersion = AuthManager.isAuthenticated()?.serverVersion ?? "?" return String(format: localized("myaccount.settings.server_version"), serverVersion) } internal var serverAddress: String { return AuthManager.isAuthenticated()?.apiHost?.host ?? "" } internal var user: User? { return AuthManager.currentUser() } internal var userName: String { return AuthManager.currentUser()?.displayName() ?? "" } internal var userStatus: String { guard let user = AuthManager.currentUser() else { return localized("user_menu.invisible") } switch user.status { case .online: return localized("status.online") case .offline: return localized("status.invisible") case .busy: return localized("status.busy") case .away: return localized("status.away") } } internal var version: String { return appInfo(.version) } internal var build: String { return appInfo(.build) } internal let supportEmail = "Rocket.Chat Support <support@rocket.chat>" internal let supportEmailSubject = "Support on iOS native application" internal var supportEmailBody: String { return """ <br /><br /> <b>Device information</b><br /> <b>System name</b>: \(UIDevice.current.systemName)<br /> <b>System version</b>: \(UIDevice.current.systemVersion)<br /> <b>System model</b>: \(UIDevice.current.model)<br /> <b>Application version</b>: \(version) (\(build)) """ } internal var canChangeAppIcon: Bool { return UIApplication.shared.supportsAlternateIcons } internal var canViewAdministrationPanel: Bool { return user?.canViewAdminPanel() ?? false } #if DEBUG || BETA || TEST internal let canOpenFLEX = true #else internal let canOpenFLEX = false #endif internal let numberOfSections = 7 internal func numberOfRowsInSection(_ section: Int) -> Int { switch section { case 0: return 1 case 1: return canChangeAppIcon ? 7 : 6 case 2: return canViewAdministrationPanel ? 1 : 0 case 3: return 3 case 4: return 1 case 5: return 1 case 6: return canOpenFLEX ? 1 : 0 default: return 0 } } // MARK: Helpers internal func appInfo(_ info: BundleInfoKey) -> String { return Bundle.main.infoDictionary?[info.rawValue] as? String ?? "" } }
b7af5c45ef5ea8f0b4cc796177018c42
31.927632
114
0.66014
false
false
false
false
drmohundro/Quick
refs/heads/master
Quick/Quick/Example.swift
mit
2
// // Example.swift // Quick // // Created by Brian Ivan Gesiak on 6/5/14. // Copyright (c) 2014 Brian Ivan Gesiak. All rights reserved. // import XCTest var _numberOfExamplesRun = 0 @objc public class Example { weak var group: ExampleGroup? var _description: String var _closure: () -> () public var isSharedExample = false public var callsite: Callsite public var name: String { get { return group!.name + ", " + _description } } init(_ description: String, _ callsite: Callsite, _ closure: () -> ()) { self._description = description self._closure = closure self.callsite = callsite } public func run() { if _numberOfExamplesRun == 0 { World.sharedWorld().runBeforeSpec() } for before in group!.befores { before() } _closure() for after in group!.afters { after() } ++_numberOfExamplesRun if _numberOfExamplesRun >= World.sharedWorld().exampleCount { World.sharedWorld().runAfterSpec() } } }
b161cd2a7084637996712d8d89764aef
21.06
80
0.576609
false
false
false
false
Molbie/Outlaw-SpriteKit
refs/heads/master
Sources/OutlawSpriteKit/Nodes/Display/SKLabelNode+Outlaw.swift
mit
1
// // SKLabelNode+Outlaw.swift // OutlawSpriteKit // // Created by Brian Mullen on 12/16/16. // Copyright © 2016 Molbie LLC. All rights reserved. // import SpriteKit import Outlaw import OutlawCoreGraphics import OutlawAppKit import OutlawUIKit // NOTE: Swift doesn't allow methods to be overriden // within extensions, so we are defining // explicit methods for each SKNode subclass public extension SKLabelNode { struct LabelNodeExtractableKeys { public static let verticalAlignmentMode = "verticalAlignmentMode" public static let horizontalAlignmentMode = "horizontalAlignmentMode" public static let fontName = "fontName" public static let text = "text" public static let fontSize = "fontSize" public static let fontColor = "fontColor" public static let colorBlendFactor = "colorBlendFactor" public static let color = "color" public static let blendMode = "blendMode" } private typealias keys = SKLabelNode.LabelNodeExtractableKeys } public extension SKLabelNode { /* Serializable */ func serializedLabelNode(withChildren: Bool) -> [String: Any] { var result = self.serializedNode(withChildren: withChildren) result[keys.verticalAlignmentMode] = self.verticalAlignmentMode.stringValue result[keys.horizontalAlignmentMode] = self.horizontalAlignmentMode.stringValue result[keys.fontName] = self.fontName ?? "" result[keys.text] = self.text ?? "" result[keys.fontSize] = self.fontSize if let fontColor = self.fontColor { result[keys.fontColor] = fontColor.serialized() } else { result[keys.fontColor] = SKColor.white.serialized() } result[keys.colorBlendFactor] = self.colorBlendFactor if let color = self.color { result[keys.color] = color.serialized() } result[keys.blendMode] = self.blendMode.stringValue return result } } public extension SKLabelNode { /* Updatable */ func updateLabelNode(with object: Extractable) throws { try self.updateNode(with: object) if let stringValue: String = object.optional(for: keys.verticalAlignmentMode), let verticalAlignmentMode = SKLabelVerticalAlignmentMode(stringValue: stringValue) { self.verticalAlignmentMode = verticalAlignmentMode } if let stringValue: String = object.optional(for: keys.horizontalAlignmentMode), let horizontalAlignmentMode = SKLabelHorizontalAlignmentMode(stringValue: stringValue) { self.horizontalAlignmentMode = horizontalAlignmentMode } if let fontName: String = object.optional(for: keys.fontName), !fontName.isEmpty { self.fontName = fontName } if let text: String = object.optional(for: keys.text) { self.text = text } if let fontSize: CGFloat = object.optional(for: keys.fontSize) { self.fontSize = fontSize } if let fontColor: SKColor = object.optional(for: keys.fontColor) { self.fontColor = fontColor } if let colorBlendFactor: CGFloat = object.optional(for: keys.colorBlendFactor) { self.colorBlendFactor = colorBlendFactor } if let color: SKColor = object.optional(for: keys.color) { self.color = color } if let stringValue: String = object.optional(for: keys.blendMode), let blendMode = SKBlendMode(stringValue: stringValue) { self.blendMode = blendMode } } }
5debe465a1e391f03b29ec1fea8413cb
38.866667
177
0.670569
false
false
false
false
esttorhe/SwiftSSH2
refs/heads/swift-2.0
SwiftSSH2Tests/Supporting Files/SwiftSSH2.playground/Contents.swift
mit
1
// Native Frameworks import CFNetwork import Foundation //let hostaddr = "google.com" //let host = CFHostCreateWithName(kCFAllocatorDefault, hostaddr) //host.autorelease() //let error = UnsafeMutablePointer<CFStreamError>.alloc(1) //let tHost: CFHost! = host.takeRetainedValue() //if CFHostStartInfoResolution(tHost, CFHostInfoType.Addresses, error) { // let hbr = UnsafeMutablePointer<Boolean>() // addresses = CFHostGetAddressing(host, hbr) //} // //error.dealloc(1)
94210df69302e23583007c658efc798e
28.5625
72
0.758985
false
false
false
false
ryuichis/swift-ast
refs/heads/master
Tests/ParserTests/Declaration/ParserConstantDeclarationTests.swift
apache-2.0
2
/* Copyright 2017-2018 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import AST @testable import Parser class ParserConstantDeclarationTests: XCTestCase { func testDefineConstant() { parseDeclarationAndTest("let foo", "let foo", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[0].initializerExpression) }) } func testDefineConstantWithTypeAnnotation() { parseDeclarationAndTest("let foo: Foo", "let foo: Foo", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo: Foo") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[0].initializerExpression) }) } func testDefineConstantWithInitializer() { parseDeclarationAndTest("let foo: Foo = bar", "let foo: Foo = bar", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo: Foo = bar") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNotNil(constDecl.initializerList[0].initializerExpression) }) } func testMultipleDecls() { parseDeclarationAndTest("let foo = bar, a, x = y", "let foo = bar, a, x = y", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 3) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo = bar") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNotNil(constDecl.initializerList[0].initializerExpression) XCTAssertEqual(constDecl.initializerList[1].textDescription, "a") XCTAssertTrue(constDecl.initializerList[1].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[1].initializerExpression) XCTAssertEqual(constDecl.initializerList[2].textDescription, "x = y") XCTAssertTrue(constDecl.initializerList[2].pattern is IdentifierPattern) XCTAssertNotNil(constDecl.initializerList[2].initializerExpression) }) } func testAttributes() { parseDeclarationAndTest("@a let foo", "@a let foo", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertEqual(constDecl.attributes.count, 1) ASTTextEqual(constDecl.attributes[0].name, "a") XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[0].initializerExpression) }) } func testModifiers() { parseDeclarationAndTest( "private nonmutating static final let foo = bar", "private nonmutating static final let foo = bar", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertEqual(constDecl.modifiers.count, 4) XCTAssertEqual(constDecl.modifiers[0], .accessLevel(.private)) XCTAssertEqual(constDecl.modifiers[1], .mutation(.nonmutating)) XCTAssertEqual(constDecl.modifiers[2], .static) XCTAssertEqual(constDecl.modifiers[3], .final) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo = bar") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNotNil(constDecl.initializerList[0].initializerExpression) }) } func testAttributeAndModifiers() { parseDeclarationAndTest("@a fileprivate let foo", "@a fileprivate let foo", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertEqual(constDecl.attributes.count, 1) ASTTextEqual(constDecl.attributes[0].name, "a") XCTAssertEqual(constDecl.modifiers.count, 1) XCTAssertEqual(constDecl.modifiers[0], .accessLevel(.fileprivate)) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertNil(constDecl.initializerList[0].initializerExpression) }) } func testFollowedByTrailingClosure() { parseDeclarationAndTest( "let foo = bar { $0 == 0 }", "let foo = bar { $0 == 0 }", testClosure: { decl in guard let constDecl = decl as? ConstantDeclaration else { XCTFail("Failed in getting a constant declaration.") return } XCTAssertTrue(constDecl.attributes.isEmpty) XCTAssertTrue(constDecl.modifiers.isEmpty) XCTAssertEqual(constDecl.initializerList.count, 1) XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo = bar { $0 == 0 }") XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern) XCTAssertTrue(constDecl.initializerList[0].initializerExpression is FunctionCallExpression) }) parseDeclarationAndTest( "let foo = bar { $0 = 0 }, a = b { _ in true }, x = y { t -> Int in t^2 }", "let foo = bar { $0 = 0 }, a = b { _ in\ntrue\n}, x = y { t -> Int in\nt ^ 2\n}") parseDeclarationAndTest( "let foo = bar { $0 == 0 }.joined()", "let foo = bar { $0 == 0 }.joined()") } func testFollowedBySemicolon() { parseDeclarationAndTest("let issue = 61;", "let issue = 61") } func testSourceRange() { parseDeclarationAndTest("let foo", "let foo", testClosure: { decl in XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 8)) }) parseDeclarationAndTest("@a let foo = bar, a, x = y", "@a let foo = bar, a, x = y", testClosure: { decl in XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 27)) }) parseDeclarationAndTest("private let foo, bar", "private let foo, bar", testClosure: { decl in XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 21)) }) parseDeclarationAndTest("let foo = bar { $0 == 0 }", "let foo = bar { $0 == 0 }", testClosure: { decl in XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 26)) }) } static var allTests = [ ("testDefineConstant", testDefineConstant), ("testDefineConstantWithTypeAnnotation", testDefineConstantWithTypeAnnotation), ("testDefineConstantWithInitializer", testDefineConstantWithInitializer), ("testMultipleDecls", testMultipleDecls), ("testAttributes", testAttributes), ("testModifiers", testModifiers), ("testAttributeAndModifiers", testAttributeAndModifiers), ("testFollowedByTrailingClosure", testFollowedByTrailingClosure), ("testFollowedBySemicolon", testFollowedBySemicolon), ("testSourceRange", testSourceRange), ] }
48ab47f47676e9c6dfadd815fae33ca6
41.607656
110
0.71151
false
true
false
false
fredfoc/OpenWit
refs/heads/master
OpenWit/Classes/OpenWit.swift
mit
1
// // OpenWit.swift // OpenWit // // Created by fauquette fred on 22/11/16. // Copyright © 2016 Fred Fauquette. All rights reserved. // import Foundation import Moya import Alamofire import ObjectMapper import CoreAudio /// potential OpenWit Errors /// /// - tokenIsUndefined: Wit token is not defined /// - serverTokenIsUndefined: server Wit token is not defined /// - noError: no Error (used to handle the statuscode of an answer /// - jsonMapping: jsonMapping failed /// - serialize: serializing failed /// - networkError: network error /// - underlying: underlying moya error /// - internalError: internal server error (500...) /// - authentication: authentication error (400...) /// - progress: progress statuscode (this is considered as an error but that should probably not be... pobody's nerfect) /// - redirection: redirection statuscode (this is considered as an error but that should probably not be... pobody's nerfect) /// - messageNotEncodedCorrectly: encoding of message was not possible /// - messageTooLong: message can not be more than 256 characters /// - unknown: something strange happened and it can not be described... aliens, anarchie, utopia... public enum OpenWitError: Swift.Error { case tokenIsUndefined case serverTokenIsUndefined case noError case jsonMapping(Moya.Response?) case serialize(Moya.Response?) case networkError(Moya.Response?) case underlying(Moya.Error) case internalError(Int) case authentication(Int) case progress case redirection(Int) case messageNotEncodedCorrectly case messageTooLong case unknown } enum OpenWitJsonKey: String { case entities = "entities" case quickreplies = "quickreplies" case type = "type" case confidence = "confidence" case text = "_text" case messageId = "msg_id" case mainValue = "value" case suggested = "suggested" } /// some error to handle the parsing of wit entities /// /// - unknownEntity: the entity is not known /// - mappingFailed: mapping failed (we could not parse the json to the mappable class you requested public enum OpenWitEntityError: Swift.Error { case unknownEntity case mappingFailed } ///See extension to get specific functionalities /// the OpenWit singleton class public class OpenWit { /// the sharedInstance as this is a Singleton public static let sharedInstance = OpenWit() /// WIT Token access, for public calls like message, speech, converse (should be set in AppDelegate or when needed) public var WITTokenAcces: String? /// WIT Server access (used in some calls - to get all entities for example) public var WITServerTokenAcces: String? /// a value used if you want to mock all the answers public var isMocked = false /// the api version (see WIT documentation to change it - at the time this was done it was: 20160526) public var apiVersion = "20160526" private init(){ } }
4672be139c70433b06ced3a51173660b
31.888889
126
0.716892
false
false
false
false
nathantannar4/InputBarAccessoryView
refs/heads/master
Example/Sources/InputBar Examples/GitHawkInputBar.swift
mit
1
// // GitHawkInputBar.swift // Example // // Created by Nathan Tannar on 2018-06-06. // Copyright © 2018 Nathan Tannar. All rights reserved. // import UIKit import InputBarAccessoryView final class GitHawkInputBar: InputBarAccessoryView { private let githawkImages: [UIImage] = [#imageLiteral(resourceName: "ic_eye"), #imageLiteral(resourceName: "ic_bold"), #imageLiteral(resourceName: "ic_italic"), #imageLiteral(resourceName: "ic_at"), #imageLiteral(resourceName: "ic_list"), #imageLiteral(resourceName: "ic_code"), #imageLiteral(resourceName: "ic_link"), #imageLiteral(resourceName: "ic_hashtag"), #imageLiteral(resourceName: "ic_upload")] override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure() { inputTextView.placeholder = "Leave a comment" sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) sendButton.setSize(CGSize(width: 36, height: 36), animated: false) sendButton.image = #imageLiteral(resourceName: "ic_send").withRenderingMode(.alwaysTemplate) sendButton.title = nil sendButton.tintColor = tintColor let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: 20, height: 20) layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 20) let collectionView = AttachmentCollectionView(frame: .zero, collectionViewLayout: layout) collectionView.intrinsicContentHeight = 20 collectionView.dataSource = self collectionView.showsHorizontalScrollIndicator = false collectionView.register(ImageCell.self, forCellWithReuseIdentifier: ImageCell.reuseIdentifier) bottomStackView.addArrangedSubview(collectionView) collectionView.reloadData() } } extension GitHawkInputBar: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return githawkImages.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCell.reuseIdentifier, for: indexPath) as! ImageCell cell.imageView.image = githawkImages[indexPath.section].withRenderingMode(.alwaysTemplate) cell.imageView.tintColor = .black return cell } }
e41d3bc91bd2fad675f236216276a76d
40.666667
407
0.703636
false
false
false
false
skedgo/tripkit-ios
refs/heads/main
Sources/TripKit/server/TKError.swift
apache-2.0
1
// // TKUserError.swift // TripKit // // Created by Adrian Schoenig on 20/10/2015. // Copyright © 2015 SkedGo Pty Ltd. All rights reserved. // import Foundation enum TKErrorCode: Int { case unsupportedRegionCombination = 1001 case unsupportedOriginRegion = 1002 case unsupportedDestinationRegion = 1003 case destinationTooCloseToOrigin = 1101 case noOrigin = 1102 case noDestination = 1103 case timeTooOld = 1201 case departureTimeTooOld = 1202 case arrivalTimeTooOld = 1203 case userError = 30051 case internalError = 30052 } class TKUserError: TKError { override var isUserError: Bool { return true } } class TKServerError: TKError { } public class TKError: NSError { @objc public var title: String? public var details: TKAPI.ServerError? @objc public class func error(withCode code: Int, userInfo dict: [String: Any]?) -> TKError { return TKError(domain: "com.skedgo.serverkit", code: code, userInfo: dict) } public class func error(from data: Data?, statusCode: Int) -> TKError? { if let data = data { // If there was a response body, we used that to see if it's an error // returned from the API. return TKError.error(from: data, domain: "com.skedgo.serverkit") } else { // Otherwise we check if the status code is indicating an error switch statusCode { case 404, 500...599: return TKError.error(withCode: statusCode, userInfo: nil) default: return nil } } } class func error(from data: Data, domain: String) -> TKError? { guard let parsed = try? JSONDecoder().decode(TKAPI.ServerError.self, from: data) else { return nil } var code = Int(parsed.isUserError ? TKErrorCode.userError.rawValue : TKErrorCode.internalError.rawValue) if let errorCode = parsed.errorCode { code = errorCode } let userInfo: [String: Any] = [ NSLocalizedDescriptionKey: parsed.errorMessage ?? parsed.title ?? Loc.ServerError, "TKIsUserError": parsed.isUserError ] let error: TKError if parsed.isUserError { error = TKUserError(domain: domain, code: code, userInfo: userInfo) } else { error = TKServerError(domain: domain, code: code, userInfo: userInfo) } error.title = parsed.title error.details = parsed return error } @objc public var isUserError: Bool { if let userError = userInfo["TKIsUserError"] as? Bool { return userError } else { return code >= 400 && code < 500 } } } extension TKAPI { public struct ServerError: Codable { public let errorMessage: String? public let isUserError: Bool public let errorCode: Int? public let title: String? public let recovery: String? public let url: URL? public let option: Option? public enum Option: String, Codable { case back = "BACK" case retry = "RETRY" case abort = "ABORT" } enum CodingKeys: String, CodingKey { case errorMessage = "error" case isUserError = "usererror" case errorCode case title case recovery = "recoveryTitle" case url case option = "recovery" } } }
0d07e5de69c98cda0a17d8abcc5fb1d0
26.360656
108
0.633313
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/wwdc_demo/ImageFeed/Layouts/ColumnFlowLayout.swift
mit
1
/* See LICENSE folder for this sample’s licensing information. Abstract: Custom view flow layout for single column or multiple columns. */ import UIKit class ColumnFlowLayout: UICollectionViewFlowLayout { private let minColumnWidth: CGFloat = 300.0 private let cellHeight: CGFloat = 70.0 private var deletingIndexPaths = [IndexPath]() private var insertingIndexPaths = [IndexPath]() // MARK: Layout Overrides /// - Tag: ColumnFlowExample override func prepare() { super.prepare() guard let collectionView = collectionView else { return } let availableWidth = collectionView.bounds.inset(by: collectionView.layoutMargins).width let maxNumColumns = Int(availableWidth / minColumnWidth) let cellWidth = (availableWidth / CGFloat(maxNumColumns)).rounded(.down) self.itemSize = CGSize(width: cellWidth, height: cellHeight) self.sectionInset = UIEdgeInsets(top: self.minimumInteritemSpacing, left: 0.0, bottom: 0.0, right: 0.0) if #available(iOS 11.0, *) { self.sectionInsetReference = .fromSafeArea } else { // Fallback on earlier versions } } // MARK: Attributes for Updated Items override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard let attributes = super.finalLayoutAttributesForDisappearingItem(at: itemIndexPath) else { return nil } if !deletingIndexPaths.isEmpty { if deletingIndexPaths.contains(itemIndexPath) { attributes.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) attributes.alpha = 0.0 attributes.zIndex = 0 } } return attributes } override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard let attributes = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath) else { return nil } if insertingIndexPaths.contains(itemIndexPath) { attributes.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) attributes.alpha = 0.0 attributes.zIndex = 0 } return attributes } // MARK: Updates override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) { super.prepare(forCollectionViewUpdates: updateItems) for update in updateItems { switch update.updateAction { case .delete: guard let indexPath = update.indexPathBeforeUpdate else { return } deletingIndexPaths.append(indexPath) case .insert: guard let indexPath = update.indexPathAfterUpdate else { return } insertingIndexPaths.append(indexPath) default: break } } } override func finalizeCollectionViewUpdates() { super.finalizeCollectionViewUpdates() deletingIndexPaths.removeAll() insertingIndexPaths.removeAll() } }
be88ea2ec3697c7601ae0c4cda8c34ea
33.677419
126
0.63969
false
false
false
false
apple/swift-system
refs/heads/main
Sources/System/FilePermissions.swift
apache-2.0
1
/* This source file is part of the Swift System open source project Copyright (c) 2020 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information */ /// The access permissions for a file. /// /// The following example /// creates an instance of the `FilePermissions` structure /// from a raw octal literal and compares it /// to a file permission created using named options: /// /// let perms = FilePermissions(rawValue: 0o644) /// perms == [.ownerReadWrite, .groupRead, .otherRead] // true @frozen /*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ public struct FilePermissions: OptionSet, Hashable, Codable { /// The raw C file permissions. @_alwaysEmitIntoClient public let rawValue: CInterop.Mode /// Create a strongly-typed file permission from a raw C value. @_alwaysEmitIntoClient public init(rawValue: CInterop.Mode) { self.rawValue = rawValue } @_alwaysEmitIntoClient private init(_ raw: CInterop.Mode) { self.init(rawValue: raw) } /// Indicates that other users have read-only permission. @_alwaysEmitIntoClient public static var otherRead: FilePermissions { FilePermissions(0o4) } /// Indicates that other users have write-only permission. @_alwaysEmitIntoClient public static var otherWrite: FilePermissions { FilePermissions(0o2) } /// Indicates that other users have execute-only permission. @_alwaysEmitIntoClient public static var otherExecute: FilePermissions { FilePermissions(0o1) } /// Indicates that other users have read-write permission. @_alwaysEmitIntoClient public static var otherReadWrite: FilePermissions { FilePermissions(0o6) } /// Indicates that other users have read-execute permission. @_alwaysEmitIntoClient public static var otherReadExecute: FilePermissions { FilePermissions(0o5) } /// Indicates that other users have write-execute permission. @_alwaysEmitIntoClient public static var otherWriteExecute: FilePermissions { FilePermissions(0o3) } /// Indicates that other users have read, write, and execute permission. @_alwaysEmitIntoClient public static var otherReadWriteExecute: FilePermissions { FilePermissions(0o7) } /// Indicates that the group has read-only permission. @_alwaysEmitIntoClient public static var groupRead: FilePermissions { FilePermissions(0o40) } /// Indicates that the group has write-only permission. @_alwaysEmitIntoClient public static var groupWrite: FilePermissions { FilePermissions(0o20) } /// Indicates that the group has execute-only permission. @_alwaysEmitIntoClient public static var groupExecute: FilePermissions { FilePermissions(0o10) } /// Indicates that the group has read-write permission. @_alwaysEmitIntoClient public static var groupReadWrite: FilePermissions { FilePermissions(0o60) } /// Indicates that the group has read-execute permission. @_alwaysEmitIntoClient public static var groupReadExecute: FilePermissions { FilePermissions(0o50) } /// Indicates that the group has write-execute permission. @_alwaysEmitIntoClient public static var groupWriteExecute: FilePermissions { FilePermissions(0o30) } /// Indicates that the group has read, write, and execute permission. @_alwaysEmitIntoClient public static var groupReadWriteExecute: FilePermissions { FilePermissions(0o70) } /// Indicates that the owner has read-only permission. @_alwaysEmitIntoClient public static var ownerRead: FilePermissions { FilePermissions(0o400) } /// Indicates that the owner has write-only permission. @_alwaysEmitIntoClient public static var ownerWrite: FilePermissions { FilePermissions(0o200) } /// Indicates that the owner has execute-only permission. @_alwaysEmitIntoClient public static var ownerExecute: FilePermissions { FilePermissions(0o100) } /// Indicates that the owner has read-write permission. @_alwaysEmitIntoClient public static var ownerReadWrite: FilePermissions { FilePermissions(0o600) } /// Indicates that the owner has read-execute permission. @_alwaysEmitIntoClient public static var ownerReadExecute: FilePermissions { FilePermissions(0o500) } /// Indicates that the owner has write-execute permission. @_alwaysEmitIntoClient public static var ownerWriteExecute: FilePermissions { FilePermissions(0o300) } /// Indicates that the owner has read, write, and execute permission. @_alwaysEmitIntoClient public static var ownerReadWriteExecute: FilePermissions { FilePermissions(0o700) } /// Indicates that the file is executed as the owner. /// /// For more information, see the `setuid(2)` man page. @_alwaysEmitIntoClient public static var setUserID: FilePermissions { FilePermissions(0o4000) } /// Indicates that the file is executed as the group. /// /// For more information, see the `setgid(2)` man page. @_alwaysEmitIntoClient public static var setGroupID: FilePermissions { FilePermissions(0o2000) } /// Indicates that executable's text segment /// should be kept in swap space even after it exits. /// /// For more information, see the `chmod(2)` man page's /// discussion of `S_ISVTX` (the sticky bit). @_alwaysEmitIntoClient public static var saveText: FilePermissions { FilePermissions(0o1000) } } /*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/ extension FilePermissions : CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the file permissions. @inline(never) public var description: String { let descriptions: [(Element, StaticString)] = [ (.ownerReadWriteExecute, ".ownerReadWriteExecute"), (.ownerReadWrite, ".ownerReadWrite"), (.ownerReadExecute, ".ownerReadExecute"), (.ownerWriteExecute, ".ownerWriteExecute"), (.ownerRead, ".ownerRead"), (.ownerWrite, ".ownerWrite"), (.ownerExecute, ".ownerExecute"), (.groupReadWriteExecute, ".groupReadWriteExecute"), (.groupReadWrite, ".groupReadWrite"), (.groupReadExecute, ".groupReadExecute"), (.groupWriteExecute, ".groupWriteExecute"), (.groupRead, ".groupRead"), (.groupWrite, ".groupWrite"), (.groupExecute, ".groupExecute"), (.otherReadWriteExecute, ".otherReadWriteExecute"), (.otherReadWrite, ".otherReadWrite"), (.otherReadExecute, ".otherReadExecute"), (.otherWriteExecute, ".otherWriteExecute"), (.otherRead, ".otherRead"), (.otherWrite, ".otherWrite"), (.otherExecute, ".otherExecute"), (.setUserID, ".setUserID"), (.setGroupID, ".setGroupID"), (.saveText, ".saveText") ] return _buildDescription(descriptions) } /// A textual representation of the file permissions, suitable for debugging. public var debugDescription: String { self.description } }
a94a106ab5d3049834de8c64ee324105
38.062147
85
0.736766
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/Extensions/UIViewController+Yep.swift
mit
1
// // UIViewController+Yep.swift // Yep // // Created by NIX on 15/7/27. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import SafariServices import YepKit import YepNetworking import AutoReview // MAKR: - Heights extension UIViewController { var statusBarHeight: CGFloat { if let window = view.window { let statusBarFrame = window.convertRect(UIApplication.sharedApplication().statusBarFrame, toView: view) return statusBarFrame.height } else { return 0 } } var navigationBarHeight: CGFloat { if let navigationController = navigationController { return navigationController.navigationBar.frame.height } else { return 0 } } var topBarsHeight: CGFloat { return statusBarHeight + navigationBarHeight } } // MAKR: - Report extension ReportReason { var title: String { switch self { case .Porno: return String.trans_reportPorno case .Advertising: return String.trans_reportAdvertising case .Scams: return String.trans_reportScams case .Other: return String.trans_reportOther } } } extension UIViewController { enum ReportObject { case User(ProfileUser) case Feed(feedID: String) case Message(messageID: String) } func report(object: ReportObject) { let reportWithReason: ReportReason -> Void = { [weak self] reason in switch object { case .User(let profileUser): reportProfileUser(profileUser, forReason: reason, failureHandler: { [weak self] (reason, errorMessage) in defaultFailureHandler(reason: reason, errorMessage: errorMessage) if let errorMessage = errorMessage { YepAlert.alertSorry(message: errorMessage, inViewController: self) } }, completion: { }) case .Feed(let feedID): reportFeedWithFeedID(feedID, forReason: reason, failureHandler: { [weak self] (reason, errorMessage) in defaultFailureHandler(reason: reason, errorMessage: errorMessage) if let errorMessage = errorMessage { YepAlert.alertSorry(message: errorMessage, inViewController: self) } }, completion: { }) case .Message(let messageID): reportMessageWithMessageID(messageID, forReason: reason, failureHandler: { [weak self] (reason, errorMessage) in defaultFailureHandler(reason: reason, errorMessage: errorMessage) if let errorMessage = errorMessage { YepAlert.alertSorry(message: errorMessage, inViewController: self) } }, completion: { }) } } let reportAlertController = UIAlertController(title: NSLocalizedString("Report Reason", comment: ""), message: nil, preferredStyle: .ActionSheet) let pornoReasonAction: UIAlertAction = UIAlertAction(title: ReportReason.Porno.title, style: .Default) { _ in reportWithReason(.Porno) } reportAlertController.addAction(pornoReasonAction) let advertisingReasonAction: UIAlertAction = UIAlertAction(title: ReportReason.Advertising.title, style: .Default) { _ in reportWithReason(.Advertising) } reportAlertController.addAction(advertisingReasonAction) let scamsReasonAction: UIAlertAction = UIAlertAction(title: ReportReason.Scams.title, style: .Default) { _ in reportWithReason(.Scams) } reportAlertController.addAction(scamsReasonAction) let otherReasonAction: UIAlertAction = UIAlertAction(title: ReportReason.Other("").title, style: .Default) { [weak self] _ in YepAlert.textInput(title: NSLocalizedString("Other Reason", comment: ""), message: nil, placeholder: nil, oldText: nil, confirmTitle: NSLocalizedString("OK", comment: ""), cancelTitle: String.trans_cancel, inViewController: self, withConfirmAction: { text in reportWithReason(.Other(text)) }, cancelAction: nil) } reportAlertController.addAction(otherReasonAction) let cancelAction: UIAlertAction = UIAlertAction(title: String.trans_cancel, style: .Cancel) { [weak self] _ in self?.dismissViewControllerAnimated(true, completion: nil) } reportAlertController.addAction(cancelAction) self.presentViewController(reportAlertController, animated: true, completion: nil) } } // MAKR: - openURL extension UIViewController { func yep_openURL(URL: NSURL) { if let URL = URL.yep_validSchemeNetworkURL { let safariViewController = SFSafariViewController(URL: URL) presentViewController(safariViewController, animated: true, completion: nil) } else { YepAlert.alertSorry(message: NSLocalizedString("Invalid URL!", comment: ""), inViewController: self) } } } // MARK: - Review extension UIViewController { func remindUserToReview() { let remindAction: dispatch_block_t = { [weak self] in guard self?.view.window != nil else { return } let info = AutoReview.Info( appID: "983891256", title: NSLocalizedString("Review Yep", comment: ""), message: NSLocalizedString("Do you like Yep?\nWould you like to review it on the App Store?", comment: ""), doNotRemindMeInThisVersionTitle: NSLocalizedString("Do not remind me in this version", comment: ""), maybeNextTimeTitle: NSLocalizedString("Maybe next time", comment: ""), confirmTitle: NSLocalizedString("Review now", comment: "") ) self?.autoreview_tryReviewApp(withInfo: info) } delay(3, work: remindAction) } } // MARK: - Alert extension UIViewController { func alertSaveFileFailed() { YepAlert.alertSorry(message: NSLocalizedString("Yep can not save files!\nProbably not enough storage space.", comment: ""), inViewController: self) } }
aed694ed1ec637fbb1ba0d42c930d44f
31.668367
270
0.622365
false
false
false
false
tutsplus/watchos-2-from-scratch
refs/heads/master
Stocks WatchKit Extension/YQL.swift
bsd-2-clause
1
// // YQL.swift // Stocks // // Created by Derek Jensen on 11/19/15. // Copyright © 2015 Derek Jensen. All rights reserved. // import Foundation public class YQL { private class var prefix: String { return "http://query.yahooapis.com/v1/public/yql?q=" } private class var suffix: String { return "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="; } public class func query(statement: String) -> NSDictionary { let query = "\(prefix)\(statement.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)\(suffix)" let jsonData = (try? String(contentsOfURL: NSURL(string: query)!, encoding: NSUTF8StringEncoding))?.dataUsingEncoding(NSUTF8StringEncoding) let result = { _ -> NSDictionary in if let data = jsonData { return (try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary } return NSDictionary() }() return result; } }
6c5cd3657eb9ba1182311477e2ff57a3
29.473684
150
0.634715
false
false
false
false
s-aska/Justaway-for-iOS
refs/heads/master
Justaway/NotificationsViewController.swift
mit
1
// // NotificationsViewController.swift // Justaway // // Created by Shinichiro Aska on 1/25/15. // Copyright (c) 2015 Shinichiro Aska. All rights reserved. // import Foundation import KeyClip import Async class NotificationsViewController: StatusTableViewController { var maxMentionID: String? override func saveCache() { if self.adapter.rows.count > 0 { guard let account = AccountSettingsStore.get()?.account() else { return } let key = "notifications:\(account.userID)" let statuses = self.adapter.statuses let dictionary = ["statuses": ( statuses.count > 100 ? Array(statuses[0 ..< 100]) : statuses ).map({ $0.dictionaryValue })] _ = KeyClip.save(key, dictionary: dictionary as NSDictionary) NSLog("notifications saveCache.") } } override func loadCache(_ success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) { adapter.activityMode = true maxMentionID = nil Async.background { guard let account = AccountSettingsStore.get()?.account() else { return } let oldKey = "notifications:\(account.userID)" _ = KeyClip.delete(oldKey) let key = "notifications-v2:\(account.userID)" if let cache = KeyClip.load(key) as NSDictionary? { if let statuses = cache["statuses"] as? [[String: AnyObject]], statuses.count > 0 { success(statuses.map({ TwitterStatus($0) })) return } } success([TwitterStatus]()) Async.background(after: 0.4, { () -> Void in self.loadData(nil) }) } } override func refresh() { maxMentionID = nil loadData(nil) } override func loadData(_ maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) { guard let account = AccountSettingsStore.get()?.account() else { return } if account.exToken.isEmpty { Twitter.getMentionTimeline(maxID: maxID, success: success, failure: failure) } else { let activitySuccess = { (statuses: [TwitterStatus], maxMentionID: String?) -> Void in if let maxMentionID = maxMentionID { self.maxMentionID = maxMentionID } success(statuses) } Twitter.getActivity(maxID: maxID, maxMentionID: maxMentionID, success: activitySuccess, failure: failure) } } override func loadData(sinceID: String?, maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) { guard let account = AccountSettingsStore.get()?.account() else { return } if account.exToken.isEmpty { Twitter.getMentionTimeline(maxID: maxID, sinceID: sinceID, success: success, failure: failure) } else { let activitySuccess = { (statuses: [TwitterStatus], maxMentionID: String?) -> Void in if let maxMentionID = maxMentionID { self.maxMentionID = maxMentionID } success(statuses) } Twitter.getActivity(maxID: maxID, sinceID: sinceID, maxMentionID: maxMentionID, success: activitySuccess, failure: failure) } } override func accept(_ status: TwitterStatus) -> Bool { if let event = status.event { if let accountSettings = AccountSettingsStore.get() { if let actionedBy = status.actionedBy { if accountSettings.isMe(actionedBy.userID) { return false } } else { if accountSettings.isMe(status.user.userID) { return false } } } if event == "quoted_tweet" || event == "favorited_retweet" || event == "retweeted_retweet" { return true } } if let accountSettings = AccountSettingsStore.get() { if let actionedBy = status.actionedBy { if accountSettings.isMe(actionedBy.userID) { return false } } for mention in status.mentions { if accountSettings.isMe(mention.userID) { return true } } if status.isActioned { if accountSettings.isMe(status.user.userID) { return true } } } return false } }
078a8255757625efdbbd562400794389
35.088889
171
0.54064
false
false
false
false
herveperoteau/TracktionProto2
refs/heads/master
TracktionProto2 WatchKit Extension/DateCompare.swift
mit
1
// // DateCompare.swift // TracktionProto2 // // Created by Hervé PEROTEAU on 31/01/2016. // Copyright © 2016 Hervé PEROTEAU. All rights reserved. // import Foundation func <=(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 <= rhs.timeIntervalSince1970 } func >=(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 >= rhs.timeIntervalSince1970 } func >(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 > rhs.timeIntervalSince1970 } func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970 } func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970 }
394ffbecd447acbc80e70a63f2a0e364
27.8
63
0.726008
false
false
false
false
feistydog/FeistyDB
refs/heads/master
Sources/FeistyDB/Database+Collation.swift
mit
1
// // Copyright (c) 2015 - 2020 Feisty Dog, LLC // // See https://github.com/feistydog/FeistyDB/blob/master/LICENSE.txt for license information // import Foundation import CSQLite extension Database { /// A comparator for `String` objects. /// /// - parameter lhs: The left-hand operand /// - parameter rhs: The right-hand operand /// /// - returns: The result of comparing `lhs` to `rhs` public typealias StringComparator = (_ lhs: String, _ rhs: String) -> ComparisonResult /// Adds a custom collation function. /// /// ```swift /// try db.addCollation("localizedCompare", { (lhs, rhs) -> ComparisonResult in /// return lhs.localizedCompare(rhs) /// }) /// ``` /// /// - parameter name: The name of the custom collation sequence /// - parameter block: A string comparison function /// /// - throws: An error if the collation function couldn't be added public func addCollation(_ name: String, _ block: @escaping StringComparator) throws { let function_ptr = UnsafeMutablePointer<StringComparator>.allocate(capacity: 1) function_ptr.initialize(to: block) guard sqlite3_create_collation_v2(db, name, SQLITE_UTF8, function_ptr, { (context, lhs_len, lhs_data, rhs_len, rhs_data) -> Int32 in // Have total faith that SQLite will pass valid parameters and use unsafelyUnwrapped let lhs = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: lhs_data.unsafelyUnwrapped), length: Int(lhs_len), encoding: .utf8, freeWhenDone: false).unsafelyUnwrapped let rhs = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: rhs_data.unsafelyUnwrapped), length: Int(rhs_len), encoding: .utf8, freeWhenDone: false).unsafelyUnwrapped // Cast context to the appropriate type and call the comparator let function_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: StringComparator.self) let result = function_ptr.pointee(lhs, rhs) return Int32(result.rawValue) }, { context in let function_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: StringComparator.self) function_ptr.deinitialize(count: 1) function_ptr.deallocate() }) == SQLITE_OK else { throw SQLiteError("Error adding collation sequence \"\(name)\"", takingDescriptionFromDatabase: db) } } /// Removes a custom collation function. /// /// - parameter name: The name of the custom collation sequence /// /// - throws: An error if the collation function couldn't be removed public func removeCollation(_ name: String) throws { guard sqlite3_create_collation_v2(db, name, SQLITE_UTF8, nil, nil, nil) == SQLITE_OK else { throw SQLiteError("Error removing collation sequence \"\(name)\"", takingDescriptionFromDatabase: db) } } }
0173704ae3f963938d533e9624ca99e7
42.016129
173
0.725159
false
false
false
false
CodaFi/swift
refs/heads/master
test/AutoDiff/validation-test/separate_tangent_type.swift
apache-2.0
5
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest #if canImport(Darwin) import Darwin.C #elseif canImport(Glibc) import Glibc #elseif os(Windows) import ucrt #else #error("Unsupported platform") #endif import DifferentiationUnittest var SeparateTangentTypeTests = TestSuite("SeparateTangentType") struct DifferentiableSubset : Differentiable { @differentiable(wrt: self) var w: Tracked<Float> @differentiable(wrt: self) var b: Tracked<Float> @noDerivative var flag: Bool struct TangentVector : Differentiable, AdditiveArithmetic { typealias TangentVector = DifferentiableSubset.TangentVector var w: Tracked<Float> var b: Tracked<Float> } mutating func move(along v: TangentVector) { w.move(along: v.w) b.move(along: v.b) } } SeparateTangentTypeTests.testWithLeakChecking("Trivial") { let x = DifferentiableSubset(w: 0, b: 1, flag: false) let pb = pullback(at: x) { x in x } expectEqual(pb(DifferentiableSubset.TangentVector.zero), DifferentiableSubset.TangentVector.zero) } SeparateTangentTypeTests.testWithLeakChecking("Initialization") { let x = DifferentiableSubset(w: 0, b: 1, flag: false) let pb = pullback(at: x) { x in DifferentiableSubset(w: 1, b: 2, flag: true) } expectEqual(pb(DifferentiableSubset.TangentVector.zero), DifferentiableSubset.TangentVector.zero) } SeparateTangentTypeTests.testWithLeakChecking("SomeArithmetics") { let x = DifferentiableSubset(w: 0, b: 1, flag: false) let pb = pullback(at: x) { x in DifferentiableSubset(w: x.w * x.w, b: x.b * x.b, flag: true) } expectEqual(pb(DifferentiableSubset.TangentVector.zero), DifferentiableSubset.TangentVector.zero) } runAllTests()
27227ec00c86f6ea4bfeed17ef2fd9db
30.054545
99
0.75
false
true
false
false
NoahPeeters/TCPTester
refs/heads/master
TCPTester/TCPTestData.swift
gpl-3.0
1
// // TCPTestData.swift // TCPTester // // Created by Noah Peeters on 5/5/17. // Copyright © 2017 Noah Peeters. All rights reserved. // import Foundation class TCPTestData { var host: String = "127.0.0.1"; var port: String = "22"; var messages: [TCPMessage] = []; init(host: String = "127.0.0.1", port: String = "22") { self.host = host self.port = port } init(fromJsonData data: Data) throws { guard let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String: Any], let host = json["host"] as? String, let port = json["port"] as? String, let messages = json["messages"] as? [[String: Any]] else { throw NSError(domain: "Cannot open file.", code: errAECorruptData, userInfo: nil) } self.host = host self.port = port self.messages = [] for rawMessage in messages { if let message = TCPMessage.init(json: rawMessage) { self.messages.append(message) } } } func getJsonObject() -> [String: Any] { var jsonMessages: [[String: Any]] = [] for message in messages { jsonMessages.append(message.getJsonObject()) } return [ "version": "1.0", "host": host, "port": port, "messages": jsonMessages ] } func getJsonData() throws -> Data { return try JSONSerialization.data(withJSONObject: getJsonObject(), options: JSONSerialization.WritingOptions()) } } class TCPMessage { var time: Double; var fromServer: Bool; var encoding: OutputEncoding; var message: Data; init(time: Double, fromServer: Bool, encoding: OutputEncoding, message: Data) { self.time = time; self.fromServer = fromServer self.encoding = encoding self.message = message } init?(json: [String: Any]) { guard let time = json["time"] as? Double, let fromServer = json["fromServer"] as? Bool, let encodingRawValue = json["encoding"] as? String, let encoding = OutputEncoding(rawValue: encodingRawValue), let base64message = json["message"] as? String, let message = Data(base64Encoded: base64message, options: .ignoreUnknownCharacters) else { return nil } self.message = message self.time = time self.fromServer = fromServer self.encoding = encoding } func getJsonObject() -> [String: Any] { return [ "time": time, "fromServer": fromServer, "encoding": encoding.rawValue, "message": message.base64EncodedString() ] } func getEncodedMessage() -> String { return encoding.encode(data: message) } }
85d323cac4c922409698ebf4a06114c9
27.299065
133
0.550198
false
false
false
false
michaelsabo/hammer
refs/heads/master
Hammer/Classes/Service/GifService.swift
mit
1
// // GifCollectionService.swift // Hammer // // Created by Mike Sabo on 10/13/15. // Copyright © 2015 FlyingDinosaurs. All rights reserved. // import Alamofire import SwiftyJSON import Regift class GifService { func getGifsResponse(completion: @escaping (_ success: Bool, _ gifs:Gifs?) -> Void) { Alamofire.request(Router.gifs) .responseJSON { response in if let json = response.result.value { let gifs = Gifs(gifsJSON: JSON(json)) if (response.result.isSuccess) { completion(true, gifs) } } completion(false, nil) } } func getGifsForTagSearchResponse(_ query: String, completion: @escaping (_ success: Bool, _ gifs:Gifs?) -> Void) { Alamofire.request(Router.gifsForTag(query)) .responseJSON { response in if let json = response.result.value { let gifs = Gifs(gifsJSON: JSON(json)) if (response.result.isSuccess) { completion(true, gifs) } } completion(false, nil) } } func retrieveThumbnailImageFor(_ gif: Gif, completion: @escaping (_ success: Bool, _ gif:Gif?) -> Void) { Alamofire.request(gif.thumbnailUrl, method: .get) .responseData { response in if (response.result.isSuccess) { if let data = response.result.value { gif.thumbnailData = data completion(true, gif) } } completion(false, nil) } } func retrieveImageDataFor(_ gif: Gif, completion: @escaping (_ success: Bool, _ data:Data?) -> Void) { Alamofire.request(gif.url, method: .get) .responseData { response in if (response.result.isSuccess) { if let data = response.result.value { completion(true, data) } } completion(false, nil) } } func retrieveGifForVideo(_ gif: Gif, completion: @escaping (_ success: Bool, _ data:Data?, _ byteSize:Int) -> Void) { DispatchQueue.global().async { Regift.createGIFFromSource(URL(safeString: gif.videoUrl)) { result,size in if let filePath = result { if let data = try? Data(contentsOf: filePath) { completion(true, data, size) } } completion(false, nil, 0) } } } func addGif(_ id : String, completion: @escaping (_ success: Bool) -> Void) { Alamofire.request(Router.addGif(id)) .responseJSON { response in if (response.result.isSuccess) { // let json = JSON(response.result.value!) // let gif = Gif(json: json["gif"], index: 0) completion(true) } completion(false) } } } extension URL { public init(safeString string: String) { guard let instance = URL(string: string) else { fatalError("Unconstructable URL: \(string)") } self = instance } } extension String { mutating func replaceSpaces() -> String { return self.replacingOccurrences(of: " ", with: "-") } }
0f9350f2ac7808883f3cdd5b472337ec
25.464912
119
0.589327
false
false
false
false