text
stringlengths
8
1.32M
import UIKit class CompsVC: UIViewController { // lazy var header: UILabel = { // let label = UILabel() // label.font = UIFont(name: "AvenirNext-UltraLight", size: 40) // label.text = "Comps" // label.textAlignment = .center // label.textColor = .white // return label // }() lazy var compsCV: UICollectionView = { let layout = UICollectionViewFlowLayout() let cv = UICollectionView() layout.scrollDirection = .vertical cv.backgroundColor = .clear // cv.dataSource = self // cv.delegate = self cv.register(CompsCVC.self, forCellWithReuseIdentifier: "compCell") return cv }() override func viewDidLoad() { super.viewDidLoad() compsVCSetUp() } func setNavigationBar() { let screenSize: CGRect = UIScreen.main.bounds let navBar = UINavigationBar(frame: CGRect(x: 0, y: 35, width: screenSize.width, height: 144)) let navItem = UINavigationItem(title: "COMPETITIONS") // let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.edit, target: nil, action: #selector(done)) // navItem.rightBarButtonItem = doneItem navBar.setItems([navItem], animated: false) self.view.addSubview(navBar) } private func compsVCSetUp() { view.addSubview(compsCV) compsCV.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ compsCV.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), compsCV.leadingAnchor.constraint(equalTo: view.leadingAnchor), compsCV.trailingAnchor.constraint(equalTo: view.trailingAnchor), compsCV.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ]) } }
// // MainTabBarViewController.swift // CleansePlayground // // Created by Tzatzo, Marsel, Vodafone Greece on 10/02/2020. // Copyright © 2020 Tzatzo, Marsel, Vodafone Greece. All rights reserved. // import UIKit import Cleanse import RxSwift class MainTabBarViewController: UITabBarController { init() { super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("MainTabBarViewController init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() } struct Module: Cleanse.Module { static func configure(binder: Binder<Unscoped>) { binder .bind(MainTabBarViewController.self) .to(factory: { (viewControllers: [UIViewController]) -> MainTabBarViewController in let mainTabBarViewController = MainTabBarViewController.init() mainTabBarViewController.viewControllers = viewControllers return mainTabBarViewController }) binder .bind() .tagged(with: UIViewController.Root.self) .to { $0 as MainTabBarViewController } } } }
import Foundation func crypto(_ f: (UnsafeMutablePointer<UInt8>, UnsafePointer<UInt8>) -> Int32, _ a: @autoclosure () -> Data, _ b: Data) -> Data? { var a = a() guard a.withUnsafeMutableBytes({ a in b.withUnsafeBytes { b in f(a, b) } }) == 0 else { return nil } return a } func crypto(_ f: (UnsafeMutablePointer<UInt8>, UnsafePointer<UInt8>, UnsafePointer<UInt8>) -> Int32, _ a: @autoclosure () -> Data, _ b: Data, _ c: Data) -> Data? { var a = a() guard a.withUnsafeMutableBytes({ a in b.withUnsafeBytes { b in c.withUnsafeBytes { c in f(a, b, c) } } }) == 0 else { return nil } return a }
// // RowServerStatusView.swift // MockApp // // Created by M. Ensar Baba on 28.03.2019. // Copyright © 2019 MobileNOC. All rights reserved. // import UIKit class RowServerStatusView: UIView { public lazy var status = UIView() public override init(frame: CGRect) { super.init(frame: .zero) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } public func commonInit() { self.setBorder(border: .left, weight: 1.0, color: .mockGray) self.addSubview(status) status.snp.makeConstraints({ (make) in make.height.width.equalTo(40) make.center.equalToSuperview() }) status.layer.cornerRadius = 20 status.clipsToBounds = true let view = UIView() view.backgroundColor = .white self.addSubview(view) view.snp.makeConstraints { (make) in make.width.height.equalTo(10) make.center.equalToSuperview() } view.layer.cornerRadius = 5 view.clipsToBounds = true self.bringSubviewToFront(view) } }
// // ViewController.swift // Swift Test 2 // // Created by Daniel Katz on 3/5/16. // Copyright © 2016 OK. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIPopoverPresentationControllerDelegate, DestinationViewDelegate { var gameMode: String = "Random" var pickedSeed: Int = 0 @IBOutlet var displayTimeLabel: UILabel! @IBOutlet var scrollView: UIScrollView! @IBOutlet var embeddedCollectionView: UICollectionView! @IBOutlet var keyboardCollectionView: UICollectionView! var screenSize = UIScreen.main.bounds var screenWidth: CGFloat = 0.0 var screenHeight: CGFloat = 0.0 var keyboardOriginY: CGFloat = 0.0 @IBOutlet var movieName: UILabel! @IBOutlet var hintButton: UIButton! @IBOutlet var menuButton: UIButton! var seed: Int = 0 var resetSeed: Int = 0 var seedsUsed: [Int] = [] var Quote: QuoteObject! var symbolArray: [String] = [] var answerQuote: String = "" var lineAdjustedAnswerQuote = "" var quoteSpaceCount: Int = 0 var vowelPositionArray: [Int] = [] var quoteDifficulty: Int = 0 var userInputDictionary: [IndexPath:String] = [:] var keyboardData: [String] = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "_"] var showVowels: Bool = false var autoFill: Bool = false var hintsGiven: [String] = [] var hintsUsed: Int = 0 var spaceIndexPath : [IndexPath] = [] let quoteDictionarySize = UInt32(QuoteDictionary(seed: 0).quoteList.count) // Variables to determine time spent on quote let calendar = Calendar.current let startTime = Date() var endTime = Date() var compQuoteList: [Int] = [] // Category completion tracking variables let quoteDict = QuoteDictionary(seed: 0) var compQuoteCategoryList: [String] = [] var compCDCategoriesList: [String] = [] var compCategories: [String] = [] override func viewDidLoad() { //scrollView.indicatorStyle = UIScrollViewIndicatorStyle.White print("Quote dictionary size: ", quoteDictionarySize) self.view.backgroundColor = UIColor.black self.screenWidth = screenSize.width self.screenHeight = screenSize.height var seedUsed: Bool = false if gameMode == "Random" { while seedUsed == false { self.seed = Int(arc4random_uniform(quoteDictionarySize)) if seedsUsed.contains(seed) == false { seedsUsed.append(seed) seedUsed = true print("seedsUsed append seed: ", seedsUsed) } else { if seedsUsed.count == Int(quoteDictionarySize) { seedUsed = true print("all seeds used") } } } print("Seeds Used:",seedsUsed) } else { seed = pickedSeed } self.Quote = QuoteObject(seed: seed) self.symbolArray = Quote.quoteControl() self.answerQuote = Quote.formattedAnswerQuote() self.quoteSpaceCount = Quote.numberOfSpaces() self.vowelPositionArray = Quote.vowelPosition() movieName.text = Quote.getQuoteSource() // self.spaceIndexPath = getSpaceIndices() self.lineAdjustedAnswerQuote = Quote.lineAdjustedAnswerQuote() self.quoteDifficulty = Quote.getDifficulty() print("viewDidLoad embeddedHeight Constant", embeddedHeight.constant) print("viewDidLoad embeddedCollectionView content Size", embeddedCollectionView.contentSize) //self.embeddedCollectionView.backgroundColor = UIColor(red:255.0, green:179.0, blue:179.0, alpha:1.0) self.embeddedCollectionView.backgroundColor = UIColor.lightGray self.scrollView.layer.cornerRadius = 10 self.embeddedCollectionView.layer.cornerRadius = 10 self.scrollView.indicatorStyle = UIScrollViewIndicatorStyle.black self.hintButton.layer.borderWidth = 1 self.menuButton.layer.borderWidth = 1 self.hintButton.layer.cornerRadius = 10 self.menuButton.layer.cornerRadius = 10 self.hintButton.layer.borderColor = self.view.tintColor.cgColor self.menuButton.layer.borderColor = self.view.tintColor.cgColor print("viewdidload keyboard content size: ", keyboardCollectionView.contentSize.height) print("screen height: ", self.screenHeight) print("screen width: ", self.screenWidth) print("viewdidload keyboard cell count: ", keyboardCollectionView.numberOfItems(inSection: 0)) print("viewdidload Keyboard content layout height: ", keyboardCollectionView.collectionViewLayout.collectionViewContentSize.height) // startTimer() } override func viewWillAppear(_ animated: Bool) { keyboardOriginY = keyboardCollectionView.frame.origin.y keyboardCollectionView.reloadData() keyboardCollectionView.layoutIfNeeded() print("viewWillAppear Keyboard Y Origin: ", keyboardOriginY) print("viewWillAppear Keyboard content size: ", keyboardCollectionView.contentSize.height) print("viewWillAppear Keyboard content layout height: ", keyboardCollectionView.collectionViewLayout.collectionViewContentSize.height) print("viewWillAppear keyboard cell count: ", keyboardCollectionView.numberOfItems(inSection: 0)) } @IBOutlet var movieNameHeightConstraint: NSLayoutConstraint! @IBOutlet var scrollViewHeightConstraint: NSLayoutConstraint! @IBOutlet var keyboardHeightConstraint: NSLayoutConstraint! @IBOutlet var embeddedHeight: NSLayoutConstraint! func configureColletion() { //movieNameHeightConstraint.constant = CGFloat(movieName.intrinsicContentSize().height + 3) print("config collection keyboard content size: ", keyboardCollectionView.contentSize.height) // Get starting Y for the scrollview let scrollViewOriginY = scrollView.frame.origin.y print("configure collection scrollView Y Origin: ", scrollViewOriginY) // Get starting Y for the keyboard collection view //let keyboardOriginY = keyboardCollectionView.frame.origin.y print("configure collection keyboard Y Origin: ", keyboardOriginY) let scrollViewKeyboardHeightDiff = keyboardOriginY - scrollViewOriginY print("config collection scrollView Keyboard Height Diff: ", scrollViewKeyboardHeightDiff) // Get the content height of the quote and set quote collection height to content + 10 or so let contentHeight = embeddedCollectionView.contentSize.height + 5 //If the QuoteCollection height is < the distance between the top of the scrollview and the top of the keyboard, then set the ScrollView height = QuoteCollection height if contentHeight < scrollViewKeyboardHeightDiff { scrollViewHeightConstraint.constant = contentHeight print("Content Height less than") } //If the QuoteCollection height is >= the distance between the top of the scrollview and the top of the keyboard, then set the ScrollView height = the distance between the top of the ScrollView and the top of the keyboard - 10 or so else { scrollViewHeightConstraint.constant = scrollViewKeyboardHeightDiff - 10 print("Content height >=") } embeddedHeight.constant = CGFloat(contentHeight) } func configureKeyboardCollection() { let keyboardHeight = keyboardCollectionView.collectionViewLayout.collectionViewContentSize.height keyboardHeightConstraint.constant = CGFloat(keyboardHeight) } override func viewDidLayoutSubviews() { print("keyboard y origin before config keyboard", keyboardOriginY) // Calling this here makes sure that the proper keyboard Y origin is used if keyboardCollectionView.frame.origin.y != 0.0{ keyboardOriginY = keyboardCollectionView.frame.origin.y } print("keyboard y origin before config keyboard 2", keyboardOriginY) configureKeyboardCollection() keyboardCollectionView.layoutIfNeeded() print("keyboard y origin after config keyboard", keyboardOriginY) configureColletion() //self.movieName.layoutIfNeeded() scrollView.reloadInputViews() scrollView.layoutIfNeeded() embeddedCollectionView.layoutIfNeeded() // Get starting Y for the scrollview let scrollViewOriginY = scrollView.frame.origin.y print("viewDidLayoutSubviews scrollView Y Origin: ", scrollViewOriginY) // Get starting Y for the keyboard collection view print("viewDidLayoutSubviews keyboard Y Origin: ", keyboardOriginY) // print("contentSize Height:", embeddedCollectionView.contentSize.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView.tag == 2 { return symbolArray.count } else{ return keyboardData.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView.tag == 2 { let cell: colViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! colViewCell if symbolArray[(indexPath as NSIndexPath).row] != " " && symbolArray[(indexPath as NSIndexPath).row] != "." && symbolArray[(indexPath as NSIndexPath).row] != "," && symbolArray[(indexPath as NSIndexPath).row] != "?" && symbolArray[(indexPath as NSIndexPath).row] != "!" && symbolArray[(indexPath as NSIndexPath).row] != "'" { cell.layer.cornerRadius = 5 cell.labelCell.text = symbolArray[(indexPath as NSIndexPath).row] cell.inputCellButton.layer.cornerRadius = 5 cell.inputCellButton.setTitleColor(UIColor(red:0.0, green:0.5, blue:0.0, alpha:1.0), for: .disabled) } else { if symbolArray[(indexPath as NSIndexPath).row] == " " { cell.labelCell.text = " " cell.inputCellButton.setTitle(" ", for: UIControlState()) } if symbolArray[(indexPath as NSIndexPath).row] == "." { cell.labelCell.text = " " cell.inputCellButton.setTitle(".", for: UIControlState()) } if symbolArray[(indexPath as NSIndexPath).row] == "," { cell.labelCell.text = " " cell.inputCellButton.setTitle(",", for: UIControlState()) } if symbolArray[(indexPath as NSIndexPath).row] == "!" { cell.labelCell.text = " " cell.inputCellButton.setTitle("!", for: UIControlState()) } if symbolArray[(indexPath as NSIndexPath).row] == "?" { cell.labelCell.text = " " cell.inputCellButton.setTitle("?", for: UIControlState()) } if symbolArray[(indexPath as NSIndexPath).row] == "'" { cell.labelCell.text = " " cell.inputCellButton.setTitle("'", for: UIControlState()) } if cell.inputCellButton.titleLabel?.text == " " || cell.inputCellButton.titleLabel?.text == "." || cell.inputCellButton.titleLabel?.text == "," || cell.inputCellButton.titleLabel?.text == "!" || cell.inputCellButton.titleLabel?.text == "?" { cell.inputCellButton.isEnabled = false } } // print("row is \(indexPath.row)") return cell } else{ let cell: keyBoardViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "keyBoardCell", for: indexPath) as! keyBoardViewCell cell.keyBoardCellButton.setTitle(keyboardData[(indexPath as NSIndexPath).row], for: UIControlState()) cell.keyBoardCellButton.layer.cornerRadius = 5 // cell.keyBoardCellButton.layer.backgroundColor = UIColor.darkGrayColor().CGColor cell.keyBoardCellButton.layer.backgroundColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:0.2).cgColor return cell } } /* func getSpaceIndices() -> [NSIndexPath] { var indexPaths = [NSIndexPath]() for i in vowelPositionArray { let cellPath = NSIndexPath(forRow: i, inSection: 0) indexPaths.append(cellPath) } return indexPaths }*/ func updateCells() { let userInputCollection = self.view.viewWithTag(2) as! UICollectionView userInputCollection.performBatchUpdates({userInputCollection.reloadItems(at: self.spaceIndexPath)}, completion: nil) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if collectionView.tag == 2 { let numberOfCellInRow : Int = 11 let padding : Int = 5 let collectionCellWidth : CGFloat = (self.view.frame.size.width/CGFloat(numberOfCellInRow)) - CGFloat(padding) return CGSize(width: collectionCellWidth , height: collectionCellWidth * 2) } else{ return CGSize(width: screenWidth / 10, height: (screenWidth / 10) * 0.85) // let numberOfCellInRow : Int = 9 // let padding : Int = 9 // let collectionCellWidth : CGFloat = (self.view.frame.size.width/CGFloat(numberOfCellInRow)) - CGFloat(padding) // return CGSize(width: collectionCellWidth , height: collectionCellWidth) } } func highlightedCellCount() -> Int { var count: Int = 0 let userInputCollection = self.view.viewWithTag(2) as! UICollectionView for cell in userInputCollection.visibleCells as! [colViewCell] { if cell.inputCellButton.userHighlighted == true { count += 1 } } return count } func resetCellTextColor() { let userInputCollection = self.view.viewWithTag(2) as! UICollectionView for cell in userInputCollection.visibleCells as! [colViewCell] { // print("title label text out of if: ", cell.inputCellButton.titleLabel?.text) if cell.inputCellButton.isEnabled == true { // print("enabled text: ", cell.inputCellButton.titleLabel?.text) cell.inputCellButton.setTitleColor(UIColor.black, for: UIControlState()) } } } func resetCellColor() { // print("reset cell color called") let userInputCollection = self.view.viewWithTag(2) as! UICollectionView for cell in userInputCollection.visibleCells as! [colViewCell] { // print("title label text out of if: ", cell.inputCellButton.titleLabel?.text) if cell.inputCellButton.isEnabled == true { // print("enabled text: ", cell.inputCellButton.titleLabel?.text) cell.inputCellButton.layer.backgroundColor = UIColor.lightGray.cgColor cell.inputCellButton.userHighlighted = false } } if showVowels == true { for i in vowelPositionArray { let cellPath = IndexPath(row: i, section: 0) let vowelCell = userInputCollection.cellForItem(at: cellPath) as! colViewCell // vowelCell.inputCellButton.backgroundColor = UIColor.darkGrayColor() // vowelCell.inputCellButton.backgroundColor = UIColor(red:192.0, green:192.0, blue:192.0, alpha:0.0) vowelCell.inputCellButton.backgroundColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:0.0) vowelCell.inputCellButton.userHighlighted = false } } } func emptyCellCount() -> Int { var emptyCount: Int = 0 let dictionaryValues = [String](userInputDictionary.values) for value in dictionaryValues { if value == " " || value == "," || value == "." || value == "!" || value == "?" || value == "'" { emptyCount += 1 } } return emptyCount } @IBAction func inputButtonPressed (_ sender: InputButton) { resetCellTextColor() let count = highlightedCellCount() let userInputCollection = self.view.viewWithTag(2) as! UICollectionView var indexRow: Int = 0 if let cell = (sender as UIView?)!.parentViewOfType(UICollectionViewCell.self) { let indexPath = userInputCollection.indexPath(for: cell) indexRow = ((indexPath as NSIndexPath?)?.row)! } // if autoFill is off if autoFill == false { if sender.titleLabel?.text != " " && sender.titleLabel?.text != "." && sender.titleLabel?.text != "," && sender.titleLabel?.text != "?" && sender.titleLabel?.text != "!" && sender.titleLabel?.text != "'" { // no highlighted cells then highlight this cell if count == 0 { sender.backgroundColor = UIColor.yellow sender.userHighlighted = true } else { // this cell is already highlighted and it isn't a vowel then background = black if count != 0 && sender.userHighlighted == true && vowelPositionArray.contains(indexRow) == false { sender.userHighlighted = false sender.backgroundColor = UIColor.lightGray } else { // this cell is already highlighted and it is a vowel and showVowels is on then background = gray if sender.userHighlighted == true && vowelPositionArray.contains(indexRow) == true && showVowels == true { resetCellColor() sender.userHighlighted = false // sender.backgroundColor = UIColor.darkGrayColor() sender.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha:0.0) // sender.backgroundColor = UIColor(red: 192.0, green: 192.0, blue: 192.0, alpha:0.0) } else { // this cell is already highlighted and it is a vowel and showVowels is off then background = black if sender.userHighlighted == true && vowelPositionArray.contains(indexRow) == true && showVowels == false { sender.userHighlighted = false sender.backgroundColor = UIColor.lightGray } else { // another cell is highlighted if count != 0 && sender.userHighlighted == false { resetCellColor() sender.backgroundColor = UIColor.yellow sender.userHighlighted = true } } } } } } } else { // print(count) if autoFill == true { if count != 0 && sender.userHighlighted == true { resetCellColor() } else { resetCellColor() for cell in userInputCollection.visibleCells as! [colViewCell] { let labelText = sender.parentViewOfType(colViewCell.self)?.labelCell?.text if labelText != " " && labelText != "." && labelText != "," && labelText != "?" && labelText != "!" && labelText != "'" { if cell.labelCell?.text == labelText { //cell.inputCellButton.layer.backgroundColor = UIColor(red: 255.0, green: 255.0, blue: 0.0, alpha:0.4).cgColor cell.inputCellButton.layer.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 0.0, alpha:0.4).cgColor cell.inputCellButton.userHighlighted = true sender.layer.backgroundColor = UIColor.yellow.cgColor } } } } } } } @IBAction func keyboardButtonPressed (_ sender: KeyboardButton) { resetCellTextColor() let count = highlightedCellCount() let userInputCollection = self.view.viewWithTag(2) as! UICollectionView // var index: Int = 0 let AnswerStringLength = lineAdjustedAnswerQuote.characters.count // Initialize the userInputDictionary with all of the cell paths if userInputDictionary.count == 0 { // for index = 0; index < AnswerStringLength; index += 1 for index in (0..<AnswerStringLength) { let cellPath = IndexPath(row: index, section: 0) userInputDictionary[cellPath] = " " } } else { if count != 0 { for cell in userInputCollection.visibleCells as! [colViewCell] { if cell.inputCellButton.userHighlighted == true { if sender.titleLabel?.text != "_" { if autoFill == true { // 1. Get the sender text character let senderLetter = sender.titleLabel!.text // 2. Find all of the matching symbols for where the text was inputted let highLightedCellPath = userInputCollection.indexPath(for: cell) let highLightedCellSymbol = symbolArray[(highLightedCellPath! as NSIndexPath).row] // print("highlighted cell symbol",highLightedCellSymbol) let inputSymbolArray: [Int] = returnIndices(highLightedCellSymbol, localSymbolArray: symbolArray) // print("input symbol array",inputSymbolArray) // 3. Update the rest of the symbols based on the list of indices for i in inputSymbolArray { let symbolCellPath = IndexPath(row: i, section: 0) let symbolCell = userInputCollection.cellForItem(at: symbolCellPath) as! colViewCell symbolCell.inputCellButton.setTitle(senderLetter, for: UIControlState()) userInputDictionary[userInputCollection.indexPath(for: symbolCell)!] = senderLetter // print(userInputDictionary) } } else { cell.inputCellButton.setTitle(sender.titleLabel?.text, for: UIControlState()) userInputDictionary[userInputCollection.indexPath(for: cell)!] = sender.titleLabel?.text // print(userInputDictionary) } } else { cell.inputCellButton.setTitle(sender.titleLabel?.text, for: UIControlState()) userInputDictionary[userInputCollection.indexPath(for: cell)!] = " " // print(userInputDictionary) } } } } // if all cells are filled in aka if NO CELL == "_" let emptyCount = emptyCellCount() // print(emptyCount) if emptyCount == quoteSpaceCount { resetCellColor() let correctAnswer = checkTheAnswer(lineAdjustedAnswerQuote) // print(correctAnswer) if correctAnswer == true { userWins() } else { incorrectAnswer() } } } } func checkHintForCorrectAlready(_ hintLetterString: String) -> Bool { var correctAlready: Bool = false let answerHintLetterPositionList = Quote.letterPosition(hintLetterString) print("hint letter :", hintLetterString) var userInputHintLetterPositionList: [Int] = [] for input in userInputDictionary { // print("Input.0.row :", input.0.row, "Input.1: ", input.1) if input.1 == hintLetterString { userInputHintLetterPositionList.append((input.0 as NSIndexPath).row) } } print("unsortedAnswerList: ", answerHintLetterPositionList) print("unsortedUserList: ", userInputHintLetterPositionList) let sortedAnswerList = answerHintLetterPositionList.sorted(by: <) let sortedUserList = userInputHintLetterPositionList.sorted(by: <) print("sortedAnswerList: ", sortedAnswerList) print("sortedUserList: ", sortedUserList) if sortedAnswerList == sortedUserList { correctAlready = true } return correctAlready } // Triggered by keyboard event that fills up last empty input square func checkTheAnswer(_ AnswerString: String) -> Bool { let AnswerStringLength = AnswerString.characters.count print("AnswerLen",AnswerStringLength) // print("UserInputLen",userInputDictionary) var userInputArray: [String] = [] var correct: Bool // Sort the dictionary keys let dictionaryIndexKeys = [IndexPath](userInputDictionary.keys) let sortedKeys = dictionaryIndexKeys.sorted {($0 as NSIndexPath).row < ($1 as NSIndexPath).row} for key in sortedKeys { userInputArray.append(userInputDictionary[key]!) } let userInputString = userInputArray.joined(separator: "") // print("userinput",userInputString) // print("answer",answerQuote) if(AnswerString == userInputString) { correct = true } else { correct = false } return correct } func userWins() { resetCellColor() self.performSegue(withIdentifier: "quoteToQuoteWin", sender: nil) } func incorrectAnswer() { // print("incorrect, try again") let alertController = UIAlertController(title: "Sorry, that's incorrect.", message: "", preferredStyle: .alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Keep trying", style: .cancel) { action -> Void in } let goHome: UIAlertAction = UIAlertAction(title: "Give up", style: .default) { action -> Void in self.performSegue(withIdentifier: "quoteToHome", sender: nil) } alertController.addAction(cancelAction) alertController.addAction(goHome) self.present(alertController, animated: true, completion: nil) } @IBAction func AutoFill(_ sender: UISegmentedControl) { let userInputCollection = self.view.viewWithTag(2) as! UICollectionView var yellowCellExists: Bool = false var yellowCellPath: IndexPath = IndexPath(row: 0, section: 0) for cell in userInputCollection.visibleCells as! [colViewCell] { if cell.inputCellButton.backgroundColor == UIColor.yellow { print("yellow cell: ", userInputCollection.indexPath(for: cell)!) yellowCellPath = userInputCollection.indexPath(for: cell)! yellowCellExists = true } } if sender.selectedSegmentIndex == 0 { autoFill = true if yellowCellExists == true { let yellowCell = userInputCollection.cellForItem(at: yellowCellPath) as! colViewCell for cell in userInputCollection.visibleCells as! [colViewCell] { if cell.labelCell.text == yellowCell.labelCell.text && cell != yellowCell { cell.inputCellButton.userHighlighted = true cell.inputCellButton.layer.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 0.0, alpha:0.4).cgColor } yellowCell.inputCellButton.userHighlighted = true } } } else { autoFill = false if yellowCellExists == true { let yellowCell = userInputCollection.cellForItem(at: yellowCellPath) as! colViewCell for cell in userInputCollection.visibleCells as! [colViewCell] { if cell != yellowCell { cell.inputCellButton.userHighlighted = false cell.inputCellButton.layer.backgroundColor = UIColor.lightGray.cgColor } } } } for cell in userInputCollection.visibleCells as! [colViewCell] { if cell.inputCellButton.userHighlighted == true { print("highlighted cell rows :", (userInputCollection.indexPath(for: cell) as NSIndexPath?)?.row as Any) } } } @IBAction func ShowVowels(_ sender: UISegmentedControl) { let userInputCollection = self.view.viewWithTag(2) as! UICollectionView if sender.selectedSegmentIndex == 0 { for i in vowelPositionArray { let cellPath = IndexPath(row: i, section: 0) let cell = userInputCollection.cellForItem(at: cellPath) as! colViewCell // cell.backgroundColor = UIColor(red:192.0, green:192.0, blue:192.0, alpha:0.2) cell.backgroundColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:0.2) if cell.inputCellButton.userHighlighted == false { cell.inputCellButton.backgroundColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:0.0) } } showVowels = true } else { for i in vowelPositionArray { let cellPath = IndexPath(row: i, section: 0) let cell = userInputCollection.cellForItem(at: cellPath) as! colViewCell cell.backgroundColor = UIColor.lightGray if cell.inputCellButton.userHighlighted == false { cell.inputCellButton.backgroundColor = UIColor.lightGray } } showVowels = false } } @IBAction func Hint(_ sender: UIButton) { let keyboardCollection = self.view.viewWithTag(1) as! UICollectionView let userInputCollection = self.view.viewWithTag(2) as! UICollectionView // var index: Int = 0 let AnswerStringLength = lineAdjustedAnswerQuote.characters.count // When hint is pressed before any other letter input, initializes the userInputDictionary with all of the cell paths here if userInputDictionary.count == 0 { // for index = 0; index < AnswerStringLength; index += 1 for index in (0..<AnswerStringLength) { let cellPath = IndexPath(row: index, section: 0) userInputDictionary[cellPath] = " " } } if hintsGiven != [] { var alreadyInHintArray: Bool = true // also includes inputAlreadyCorrect // if hints have already been given, keep pulling hints until a new one is generated while alreadyInHintArray == true { let getHint = QuoteObject(seed: seed).getHint() let (hintLetter, _ ) = getHint let hintLetterString = String(hintLetter) // if a new hint is found and the user doesn't already have the letter correct, append the hint letter to the hints given array so it won't be used again if hintsGiven.contains(hintLetterString!) == false && checkHintForCorrectAlready(hintLetterString!) == false { hintsGiven.append(hintLetterString!) alreadyInHintArray = false let ( _, hintIndexArray) = getHint for i in hintIndexArray { let cellPath = IndexPath(row: i, section: 0) let cell = userInputCollection.cellForItem(at: cellPath) as! colViewCell cell.inputCellButton.setTitle(hintLetterString, for: .disabled) userInputDictionary[userInputCollection.indexPath(for: cell)!] = hintLetterString if vowelPositionArray.contains(((userInputCollection.indexPath(for: cell) as NSIndexPath?)?.row)!) == true { cell.inputCellButton.layer.backgroundColor = UIColor(white: 1.0, alpha: 0.0).cgColor } else { cell.inputCellButton.layer.backgroundColor = UIColor.lightGray.cgColor } cell.inputCellButton.userHighlighted = false cell.inputCellButton.isEnabled = false } for i in (0..<keyboardCollectionView.visibleCells.count) { let cellPath = IndexPath(row: i, section: 0) let cell = keyboardCollection.cellForItem(at: cellPath) as! keyBoardViewCell if cell.keyBoardCellButton.titleLabel?.text == hintLetter { cell.keyBoardCellButton.isEnabled = false } } } } } // if no hints have been given yet, check if the letter for the pulled hint is already correct and if not then give the hint and append the hint letter to the hints given array else { var inputCorrectTest: Bool = false while inputCorrectTest == false { let getHint = QuoteObject(seed: seed).getHint() let (hintLetter, _ ) = getHint // print(hintLetter) let hintLetterString = String(hintLetter) if checkHintForCorrectAlready(hintLetterString!) == false { hintsGiven.append(hintLetterString!) inputCorrectTest = true let ( _, hintIndexArray) = getHint // print(hintIndexArray) for i in hintIndexArray { let cellPath = IndexPath(row: i, section: 0) let cell = userInputCollection.cellForItem(at: cellPath) as! colViewCell cell.inputCellButton.setTitle(hintLetterString, for: .disabled) userInputDictionary[userInputCollection.indexPath(for: cell)!] = hintLetterString if vowelPositionArray.contains(((userInputCollection.indexPath(for: cell) as NSIndexPath?)?.row)!) == true { cell.inputCellButton.layer.backgroundColor = UIColor(white: 1.0, alpha: 0.0).cgColor } else { cell.inputCellButton.layer.backgroundColor = UIColor.lightGray.cgColor } cell.inputCellButton.userHighlighted = false cell.inputCellButton.isEnabled = false // print(userInputDictionary) } // print("keyboard collection visible cell count: ",keyboardCollection.visibleCells().count) for i in (0..<keyboardCollection.visibleCells.count) { let cellPath = IndexPath(row: i, section: 0) let cell = keyboardCollection.cellForItem(at: cellPath) as! keyBoardViewCell // print("title label: ",cell.keyBoardCellButton.titleLabel?.text, "hintLetter :", hintLetter) if cell.keyBoardCellButton.titleLabel?.text == hintLetter { cell.keyBoardCellButton.isEnabled = false } } } } } // Once the hint has been given... let emptyCount = emptyCellCount() // print("emptycount ",emptyCount) if emptyCount == quoteSpaceCount { resetCellColor() let correctAnswer = checkTheAnswer(lineAdjustedAnswerQuote) // print(correctAnswer) if correctAnswer == true { userWins() } } } func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.none } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "quoteToQuoteWin" { let destination = segue.destination as! QuoteWinViewController let elapsedTime = stopTimer() destination.elapsedTime = elapsedTime destination.quoteLabelText = QuoteDictionary(seed: seed).generateQuote() destination.seedsPass = seedsUsed print("Seeds Sent: ",destination.seedsPass) destination.hintCount = hintsGiven.count destination.quoteDifficulty = quoteDifficulty destination.score = calculateScore() if gameMode == "Category" { // Save the completed quote getCompletedQuotes() if compQuoteList.contains(seed) == false { saveCompletedQuote(compQuoteSeed: seed, compQuoteDifficulty: quoteDifficulty, compQuoteScore: calculateScore(), compQuoteTime: elapsedSeconds(), compQuoteHintsUsed: hintsUsed, compQuoteCategory: Quote.getQuoteCategory()) } // Update Completed Categories // get completed quote category names (needed to build completed categories list) getCompletedQuoteCategoryNames() // returns list of completed categories (without core data) compCategories = getCompletedCategories() // pull the current core data completed categories list fetchCompletedCategories() // save any new completed categories to core data saveCompletedCategories(categoriesToSave: compCategories) } } if segue.identifier == "newQuoteSegue" { let destination = segue.destination as! ViewController destination.seedsUsed = seedsUsed print(destination.seedsUsed) } if segue.identifier == "menuPopoverSegue" { let popoverViewController = segue.destination as! MenuViewController popoverViewController.delegate=self popoverViewController.popoverPresentationController?.delegate=self popoverViewController.currentSeed = seed popoverViewController.seedsPass = seedsUsed print("Current seed sent on popover view: ", popoverViewController.currentSeed) print("Seed list on popover view: ", popoverViewController.seedsPass) } } func returnIndices(_ symbol: String, localSymbolArray: [String]) -> [Int] { var tempIndexArray: [Int] = [] var indexArray: [Int] = [] var count: Int = 0 for character in localSymbolArray { if character == symbol { tempIndexArray.append(count) count += 1 } else { tempIndexArray.append(999) count += 1 } } indexArray = tempIndexArray.filter { $0 != 999 } return indexArray } func randomSeed() -> Int { let seed = Int(arc4random_uniform(5)) return seed } func timeDiff(_ startTime: Date, endTime: Date) -> String { let calendar = Calendar.current let flags = NSCalendar.Unit.second let components = (calendar as NSCalendar).components(flags, from: startTime, to: endTime, options: []) let secDiff = components.second var seconds = secDiff var minutes = 00 var hours = 00 if secDiff! >= 60 { seconds = secDiff! % 60 minutes = (secDiff! / 60) % 60 hours = ((secDiff! / 60) / 60) % 60 } let timeString = String(format: "%02d:%02d:%02d", hours, minutes, seconds!) return (timeString) } var counterStartTime = TimeInterval() func updateTime() { let currentTime = Date.timeIntervalSinceReferenceDate //Find the difference between current time and start time. var elapsedTime: TimeInterval = currentTime - counterStartTime //calculate the hours in elapsed time. let hours = Int((elapsedTime / 60.0) / 60.0) elapsedTime -= ((TimeInterval(hours) * 60) * 60) //calculate the minutes in elapsed time. let minutes = UInt8(elapsedTime / 60.0) elapsedTime -= (TimeInterval(minutes) * 60) //calculate the seconds in elapsed time. let seconds = UInt8(elapsedTime) elapsedTime -= TimeInterval(seconds) //find out the fraction of milliseconds to be displayed. //let fraction = UInt8(elapsedTime * 100) //add the leading zero for minutes, seconds and millseconds and store them as string constants let strHours = String(format: "%02d", hours) let strMinutes = String(format: "%02d", minutes) let strSeconds = String(format: "%02d", seconds) // let strFraction = String(format: "%02d", fraction) //concatenate minuets, seconds and milliseconds as assign it to the UILabel if hours < 100 { displayTimeLabel.text = strHours + ":" + strMinutes + ":" + strSeconds } else { displayTimeLabel.text = "Need some hints?" } } var timer = Timer() func startTimer() { if !timer.isValid { let aSelector : Selector = #selector(ViewController.updateTime) timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true) counterStartTime = Date.timeIntervalSinceReferenceDate } } func stopTimer() -> String { let elapsedTime = displayTimeLabel.text timer.invalidate() return elapsedTime! } func invalidateTimer() { timer.invalidate() if !timer.isValid { print("no valid timers") } else { print("timer still valid") } } /* @IBAction func start(sender: AnyObject) { if !timer.valid { let aSelector : Selector = #selector(SWViewController.updateTime) timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true) startTime = NSDate.timeIntervalSinceReferenceDate() } } @IBAction func stop(sender: AnyObject) { timer.invalidate() // timer == nil } */ func reset(){ let alertController = UIAlertController(title: "Are you sure you want to reset?", message: "", preferredStyle: .alert) let cancelAction: UIAlertAction = UIAlertAction(title: "No", style: .cancel) { action -> Void in } alertController.addAction(cancelAction) let resetQuote: UIAlertAction = UIAlertAction(title: "Yes", style: .default) { action -> Void in let userInputCollection = self.view.viewWithTag(2) as! UICollectionView let keyboardCollection = self.view.viewWithTag(1) as! UICollectionView for cell in userInputCollection.visibleCells as! [colViewCell] { cell.inputCellButton.isEnabled = true if cell.inputCellButton.titleLabel!.text != " " && cell.inputCellButton.titleLabel!.text != "." && cell.inputCellButton.titleLabel!.text != "," && cell.inputCellButton.titleLabel!.text != "?" && cell.inputCellButton.titleLabel!.text != "!" && cell.inputCellButton.titleLabel!.text != "'" { cell.inputCellButton.setTitle("_", for: UIControlState()) } } for cell in keyboardCollection.visibleCells as! [keyBoardViewCell] { cell.keyBoardCellButton.isEnabled = true } self.resetCellColor() self.userInputDictionary = [:] self.hintsGiven = [] } alertController.addAction(resetQuote) self.present(alertController, animated: true, completion: nil) } func checkAnswers() { var userInputList: [String] = [] var answerList: [String] = [] for letter in lineAdjustedAnswerQuote.characters { answerList.append(String(letter)) } let dictionaryIndexKeys = [IndexPath](userInputDictionary.keys) let sortedKeys = dictionaryIndexKeys.sorted {($0 as NSIndexPath).row < ($1 as NSIndexPath).row} for key in sortedKeys { userInputList.append(userInputDictionary[key]!) } var correctAnswers: [Int] = [] var incorrectAnswers: [Int] = [] for i in (0..<userInputList.count) { if userInputList[i] == answerList[i] { correctAnswers.append(i) } else { incorrectAnswers.append(i) } } let userInputCollection = self.view.viewWithTag(2) as! UICollectionView for i in correctAnswers { let cellPath = IndexPath(row: i, section: 0) let cell = userInputCollection.cellForItem(at: cellPath) as! colViewCell cell.inputCellButton.layer.backgroundColor = UIColor.lightGray.cgColor cell.inputCellButton.userHighlighted = false cell.inputCellButton.isEnabled = false } for i in incorrectAnswers { let cellPath = IndexPath(row: i, section: 0) let cell = userInputCollection.cellForItem(at: cellPath) as! colViewCell //cell.inputCellButton.titleLabel?.textColor = UIColor.redColor() if cell.inputCellButton.titleLabel?.text != "_" { cell.inputCellButton.setTitleColor(UIColor.red, for: UIControlState()) } // add to user input button pressed if any color is redcolor then reset? } } func calculateScore() -> Int { hintsUsed = hintsGiven.count let score = quoteDifficulty - hintsUsed // Add in time element return score } func elapsedSeconds() -> Int { return 0 } /******************** Core Data Functions *********************/ func getContext () -> NSManagedObjectContext { let CDStack = CoreDataStack() return CDStack.persistentContainer.viewContext } func saveCompletedQuote (compQuoteSeed: Int, compQuoteDifficulty: Int, compQuoteScore: Int, compQuoteTime: Int, compQuoteHintsUsed: Int, compQuoteCategory: String) { let context = getContext() //retrieve the entity that we just created let entity = NSEntityDescription.entity(forEntityName: "CdCompletedQuote", in: context) let transc = NSManagedObject(entity: entity!, insertInto: context) //set the entity values transc.setValue(compQuoteSeed, forKey: "seed") transc.setValue(compQuoteDifficulty, forKey: "difficulty") transc.setValue(compQuoteScore, forKey: "score") transc.setValue(compQuoteTime, forKey: "time") transc.setValue(compQuoteHintsUsed, forKey: "hintsUsed") transc.setValue(compQuoteCategory, forKey: "category") //save the object do { try context.save() print("saved!") } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } catch { } } func getCompletedQuotes () { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "CdCompletedQuote") do { //go get the results let searchResults = try getContext().fetch(fetchRequest) //I like to check the size of the returned results! print ("num of results = \(searchResults.count)") //You need to convert to NSManagedObject to use 'for' loops for trans in searchResults as! [NSManagedObject] { compQuoteList.append(trans.value(forKey: "seed") as! Int) print("seed: ", trans.value(forKey: "seed") as Any) } } catch { print("Error with request: \(error)") } } func getCompletedQuoteCategoryNames () { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "CdCompletedQuote") do { //go get the results let searchResults = try getContext().fetch(fetchRequest) //I like to check the size of the returned results! print ("num of results = \(searchResults.count)") //You need to convert to NSManagedObject to use 'for' loops for trans in searchResults as! [NSManagedObject] { compQuoteCategoryList.append(trans.value(forKey: "category") as! String) print("category: ", trans.value(forKey: "category") as Any) } } catch { print("Error with request: \(error)") } } func getCompletedCategories() -> [String] { // Get list of categories from quote dictionary let categoryList = quoteDict.listOfCategories() var compCategories: [String] = [] // for each unique category in the list from the quote dictionary for category in categoryList { print("category in categoryList: ", category) // count of quotes in quote dictionary for a particular category let categoryQuoteCount = quoteDict.quotesFromSpecificCategory(category).count print("categoryQuoteCount: ", categoryQuoteCount) var compQuoteCategoryCount: [String] = [] // get list of completed quotes in the category for compQuoteCategory in compQuoteCategoryList { print("compQuoteCategory: ", compQuoteCategory) if compQuoteCategory == category { compQuoteCategoryCount.append(compQuoteCategory) } } print("compQuoteCategoryCount: ",compQuoteCategoryCount) // append completed categories if compQuoteCategoryCount.count == categoryQuoteCount { print("equal") print("categoryQuoteCount: ", categoryQuoteCount) print("compQuoteCategoryCount.count: ", compQuoteCategoryCount.count) compCategories.append(category) } } return compCategories } // fetch completed categories func fetchCompletedCategories () { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "CdCompletedCategory") do { //go get the results let searchResults = try getContext().fetch(fetchRequest) //I like to check the size of the returned results! print ("num of results CD Categories = \(searchResults.count)") //You need to convert to NSManagedObject to use 'for' loops for trans in searchResults as! [NSManagedObject] { compCDCategoriesList.append(trans.value(forKey: "category") as! String) print("category: ", trans.value(forKey: "category") as Any) } } catch { print("Error with request: \(error)") } } // save completed categories not already in core data func saveCompletedCategories (categoriesToSave: [String]) { let context = getContext() for category in categoriesToSave { if compCDCategoriesList.contains(category) == false { //retrieve the entity that we just created let entity = NSEntityDescription.entity(forEntityName: "CdCompletedCategory", in: context) let transc = NSManagedObject(entity: entity!, insertInto: context) //set the entity values transc.setValue(category, forKey: "category") //save the object do { try context.save() print("saved!") } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } catch { } } } } }
// // Copyright © 2021 Tasuku Tozawa. All rights reserved. // import Combine import Common import UIKit class TextEditAlertController: NSObject { typealias TextEditAlertStore = Store<TextEditAlertState, TextEditAlertAction, TextEditAlertDependency> private class AlertController: UIAlertController { weak var store: TextEditAlertStore? deinit { store?.execute(.dismissed) } } private class Dependency: TextEditAlertDependency { // swiftlint:disable identifier_name var _textValidator: ((String?) -> Bool)? weak var _textEditAlertDelegate: TextEditAlertDelegate? var textValidator: (String?) -> Bool { return { [weak self] text in guard let validator = self?._textValidator else { return true } return validator(text) } } var textEditAlertDelegate: TextEditAlertDelegate? { _textEditAlertDelegate } } private(set) var store: TextEditAlertStore private let dependency = Dependency() private weak var presentingAlert: AlertController? private weak var presentingSaveAction: UIAlertAction? private var subscriptions: Set<AnyCancellable> = .init() var textEditAlertDelegate: TextEditAlertDelegate? { get { dependency._textEditAlertDelegate } set { dependency._textEditAlertDelegate = newValue } } // MARK: - Lifecycle init(state: TextEditAlertState) { self.store = .init(initialState: state, dependency: dependency, reducer: TextEditAlertReducer.self) super.init() bind() } // MARK: - Methods func present(with text: String, validator: @escaping (String?) -> Bool, on viewController: UIViewController) { guard presentingAlert == nil else { RootLogger.shared.write(ConsoleLog(level: .info, message: "既にアラート表示中のためpresentを無視します")) return } dependency._textValidator = validator store.execute(.textChanged(text: text)) let alert = AlertController(title: store.stateValue.title, message: store.stateValue.message, preferredStyle: .alert) let saveAction = UIAlertAction(title: L10n.confirmAlertSave, style: .default) { [weak self] _ in self?.store.execute(.saveActionTapped) } alert.addAction(saveAction) saveAction.isEnabled = store.stateValue.shouldReturn let cancelAction = UIAlertAction(title: L10n.confirmAlertCancel, style: .cancel) { [weak self] _ in self?.store.execute(.cancelActionTapped) } alert.addAction(cancelAction) alert.addTextField { [weak self] textField in guard let self = self else { return } textField.placeholder = self.store.stateValue.placeholder textField.delegate = self textField.text = self.store.stateValue.text textField.addTarget(self, action: #selector(self.textFieldDidChange(sender:)), for: .editingChanged) } alert.store = store presentingAlert = alert presentingSaveAction = saveAction viewController.present(alert, animated: true) { [weak self] in self?.store.execute(.presented) } } @objc private func textFieldDidChange(sender: UITextField) { RunLoop.main.perform { [weak self] in self?.store.execute(.textChanged(text: sender.text ?? "")) } } } // MARK: - UITextFieldDelegate extension TextEditAlertController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { return store.stateValue.shouldReturn } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { RunLoop.main.perform { [weak self] in self?.store.execute(.textChanged(text: textField.text ?? "")) } return true } } // MARK: - Bind extension TextEditAlertController { func bind() { store.state .receive(on: DispatchQueue.main) .sink { [weak self] state in self?.presentingSaveAction?.isEnabled = state.shouldReturn } .store(in: &subscriptions) } }
// // WebService.swift // APPFORMANAGEMENT // // Created by Chanakan Jumnongwit on 1/24/2560 BE. // Copyright © 2560 REVO. All rights reserved. // import UIKit import Alamofire import Foundation protocol WebServiceResponseProtocol : class { func loginResponse(response:DataResponse<Any>) func forgetPasswordResponse(response:DataResponse<Any>) func realtimeTransactionResponse(response:DataResponse<Any>) func realtimeTransactionDetailResponse(response:DataResponse<Any>) func getRealtimeTransactionResponse(response:DataResponse<Any>) func woodpiecesResponse(response:DataResponse<Any>) func incomingoutcomingResponse(response:DataResponse<Any>) func profitlossDetailResponse(response:DataResponse<Any>) func intensivePerformanceResponse(response:DataResponse<Any>) func firewoodResponse(response:DataResponse<Any>) func weightoutcoming(response:DataResponse<Any>) func checkwoodpiecesResponse(response:DataResponse<Any>) func checkfirewoodResponse(response:DataResponse<Any>) func checkweightoutcomingResponse(response:DataResponse<Any>) func checkprofitlossResponse(response:DataResponse<Any>) } class WebService: NSObject { weak var delegate:WebServiceResponseProtocol? private let httpclient = httpClientUtil() class var shareInstance : WebService{ struct Static{ static let instance = WebService() } return Static.instance } //MARK: func (method:get,post) /* * Key : Int (enum) * parameter : [String:String] NSDictionary */ func login(parameter:Parameters ,Key:Int ){ let loginUrlString = String(format: "%@api/user/user-login",SERVER_PATH) httpclient.delegate = self; httpclient.postDataToWS(requestURL: loginUrlString, parameter: parameter, Key: Key); } func forgetPassword(parameter:Parameters, Key:Int){ let forgetPasswordUrlString = String(format: "%@api/user/forget-password",SERVER_PATH) httpclient.delegate = self; httpclient.postDataToWS(requestURL: forgetPasswordUrlString, parameter: parameter, Key: Key) } /* * Realtime Report */ func postRealtimeTransaction(parameter:Parameters ,Key:Int){ let realtimetransactionUrlString = String(format: "%@api/transaction/realtime-transaction",SERVER_PATH) httpclient.delegate = self; httpclient.postDataToWS(requestURL: realtimetransactionUrlString, parameter: parameter, Key: Key) } func postRealtimeTransactionDetail(parameter:Parameters,Key:Int){ let detailUrlString = String(format: "%@api/transaction/transaction-detail",SERVER_PATH) httpclient.delegate = self; httpclient.postDataToWS(requestURL: detailUrlString, parameter: parameter, Key: Key) } func postRealtimeReport(parameter:Parameters,Key:Int){ let postRealtimeReport = String(format: "%@api/transaction/realtime-report",SERVER_PATH) httpclient.delegate = self; httpclient.postDataToWS(requestURL: postRealtimeReport, parameter: parameter, Key: Key) } /* * END */ /* * Dialy Report */ func postWoodPieces(parameter:Parameters , Key:Int){ let woodpiecesUrlString = String(format: "%@api/dialyreport/wood-pieces",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: woodpiecesUrlString, parameter: parameter, Key: Key) } func postFireWood(parameter:Parameters , Key:Int){ let firewoodUrlString = String(format: "%@api/dialyreport/fire-wood",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: firewoodUrlString, parameter: parameter, Key: Key) } func postWeightOutcoming(parameter:Parameters , Key:Int){ let weightoutUrlString = String(format: "%@api/dialyreport/weight-outcoming",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: weightoutUrlString, parameter: parameter, Key: Key) } func postCheckWoodpieces(parameter:Parameters , Key:Int){ let stringurl = String(format: "%@api/dialyreport/check-woodpieces",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: stringurl, parameter: parameter, Key: Key) } func postCheckFirewood(parameter:Parameters , Key:Int){ let stringurl = String(format: "%@api/dialyreport/check-firewood",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: stringurl, parameter: parameter, Key: Key) } func postCheckWeightoutcoming(parameter:Parameters , Key:Int){ let stringurl = String(format: "%@api/dialyreport/check-weightoutcoming",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: stringurl, parameter: parameter, Key: Key) } /* * END */ /* * ProfitandLoss Report */ func postIncomingOutcoming(parameter:Parameters,Key:Int){ let InOutComingUrlString = String(format: "%@api/profit/incoming-outcoming",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: InOutComingUrlString, parameter: parameter, Key: Key) } func postProfitLossDetail(parameter:Parameters,Key:Int){ let ProfitLossUrlString = String(format: "%@api/profit/profit-loss",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: ProfitLossUrlString, parameter: parameter, Key: Key) } func postCheckProfitloss(parameter:Parameters , Key:Int){ let urlstring = String(format: "%@api/profit/check-profitloss",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: urlstring, parameter: parameter, Key: Key) } /* * END */ /* * Performance Report */ func postIntensivePerformance(parameter:Parameters,Key:Int){ let intensiveUrlString = String(format : "%@api/performance/intensive-performance",SERVER_PATH) httpclient.delegate = self httpclient.postDataToWS(requestURL: intensiveUrlString, parameter: parameter, Key: Key) } } //MARK: httpClientUtil Protocol extension WebService : httpClientUtilDelegate { func onSuccess(response: DataResponse<Any>, Key: Int) { switch Key { case ServiceKey.LOGIN_USER_RESPONSE.rawValue: self.delegate?.loginResponse(response: response); break case ServiceKey.FORGET_PASSWORD_RESPONSE.rawValue: self.delegate?.forgetPasswordResponse(response: response) break case ServiceKey.SAWMILL_REALTIME_TRANSACTION.rawValue: self.delegate?.realtimeTransactionResponse(response: response) break case ServiceKey.SAWMILL_REALTIME_TRANSACTION_DETAIL.rawValue: self.delegate?.realtimeTransactionDetailResponse(response: response) break case ServiceKey.SAWMILL_POST_REALTIME_TRANSACTION.rawValue: self.delegate?.getRealtimeTransactionResponse(response: response) break case ServiceKey.WOOD_PIECES.rawValue: self.delegate?.woodpiecesResponse(response: response) break case ServiceKey.INCOMING_OUTCOMING.rawValue: self.delegate?.incomingoutcomingResponse(response: response) break case ServiceKey.PROFIT_LOSS_DETAIL.rawValue: self.delegate?.profitlossDetailResponse(response: response) break case ServiceKey.INTENSIVE_PERFORMANCE.rawValue: self.delegate?.intensivePerformanceResponse(response: response) break case ServiceKey.FIRE_WOOD.rawValue: self.delegate?.firewoodResponse(response: response) break case ServiceKey.WEIGHT_OUT_COMING.rawValue: self.delegate?.weightoutcoming(response: response) break case ServiceKey.CHECK_WOOD_PIECES.rawValue: self.delegate?.checkwoodpiecesResponse(response: response) break case ServiceKey.CHECK_FIRE_WOOD.rawValue: self.delegate?.checkfirewoodResponse(response: response) break case ServiceKey.CHECK_WEIGHT_OUTCOMING.rawValue: self.delegate?.checkweightoutcomingResponse(response: response) break case ServiceKey.CHECK_PROFIT_LOSS.rawValue: self.delegate?.checkprofitlossResponse(response: response) break default: break } } func onFailure(message: String, statuscode: NSInteger, Key: Int) { switch Key { case ServiceKey.LOGIN_USER_RESPONSE.rawValue: print("LOGIN_USER_RESPONSE_ERROR_ERROR" , message , "::" , statuscode) break case ServiceKey.FORGET_PASSWORD_RESPONSE.rawValue: print("FORGET_PASSWORD_RESPONSE_ERROR" , message , "::" , statuscode) break case ServiceKey.SAWMILL_REALTIME_TRANSACTION.rawValue: print("SAWMILL_REALTIME_TRANSACTION_RESPONSE_ERROR" , message , "::" , statuscode) break case ServiceKey.SAWMILL_REALTIME_TRANSACTION_DETAIL.rawValue: print("SAWMILL_REALTIME_TRANSACTION_DETAIL_ERROR" , message , "::" , statuscode) break default: break } } }
// // LocationResultHit.swift // PTR // // Created by Hussein AlRyalat on 2/2/19. // Copyright © 2019 SketchMe. All rights reserved. // import Foundation typealias LocationSelectionResult = [LocationSearchHit] struct LocationSearchHit: Hashable, Codable { var title: String { return (administrative.first ?? "") + ", " + country } var coordinates: PTCoordinates { return PTCoordinates(longitude: geoloc.lng, latitude: geoloc.lat) } let country: String let countryCode: String let isCity: Bool let administrative: [String] let localeNames: [String] let geoloc: LocationResultCoordinates enum CodingKeys: String, CodingKey { case country case countryCode = "country_code" case isCity = "is_city" case administrative case localeNames = "locale_names" case geoloc = "_geoloc" } } struct LocationResultCoordinates: Hashable, Codable { let lat, lng: Double }
import UIKit class FrameView: UIView { lazy var label: UILabel = self.makeLabel() // lazy var gradientLayer: CAGradientLayer = self.makeGradientLayer() lazy var selectedImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: Config.Grid.SelectedImage.Width, height: Config.Grid.SelectedImage.Height)) // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Setup private func setup() { selectedImageView.layer.addSublayer(makeShareLayer()) addSubview(selectedImageView) selectedImageView.g_pinCenter() addSubview(label) label.g_pinCenter() } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() selectedImageView.center = self.center } // MARK: - Controls private func makeShareLayer() -> CAShapeLayer { let circlePath = UIBezierPath(arcCenter: CGPoint(x: 0, y: 0), radius: CGFloat(Config.Grid.SelectedImage.CircleRadius), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true) let shapeLayer = CAShapeLayer() shapeLayer.path = circlePath.cgPath shapeLayer.fillColor = Config.Grid.SelectedImage.CircleFillColor.cgColor return shapeLayer } private func makeLabel() -> UILabel { let label = UILabel() label.font = Config.Grid.SelectedImage.LabelFont label.textColor = UIColor.white return label } // // private func makeGradientLayer() -> CAGradientLayer { // let layer = CAGradientLayer() // layer.colors = [ // Config.Grid.FrameView.fillColor.withAlphaComponent(0.25).cgColor, // Config.Grid.FrameView.fillColor.withAlphaComponent(0.4).cgColor // ] // // return layer // } }
// // Syndrome.swift // ToddsSyndromeIdentification // // Created by Marina Butovich on 9/24/16. // Copyright © 2016 Marina Butovich. All rights reserved. // import Foundation public enum SyndromeType: Int { case toddsSyndrome init?(description: String) { switch description { case "Todd's Syndrome": self = .toddsSyndrome default: return nil } } } extension SyndromeType: CustomStringConvertible { public var description: String { get { switch self { case .toddsSyndrome: return "Todd's Syndrome" } } } } public struct Syndrome { let type: SyndromeType var probability: Double } public extension Syndrome { func dictionaryRepresentation() -> NSDictionary { return ["type": self.type.description, "probability": self.probability] as NSDictionary } init?(dict: NSDictionary) { guard let typeString = dict["type"] as? String, let type = SyndromeType(description: typeString), let probability = dict["probability"] as? Double else { return nil } self.init(type: type, probability: probability) } }
// // CountdownWidgetSmall.swift // CountdownsExtension // // Created by zachary on 29/1/21. // import SwiftUI import WidgetKit // fetches event by id , else if cannot be found , the recent one will be return else if defaultview func fetchEvent(entry:EventEntry) -> Event { for event in entry.event{ if entry.configuration.Event != nil { if(entry.configuration.Event!.identifier == event.id){ return event } } else { print("Doesn’t contain a value.") } } WidgetCenter.shared.reloadAllTimelines() if entry.event.count > 0 { return entry.event[0] } return EventEntry.defaultview.event[0] } // helper function to check if a entry is a placeholder //func shouldDisplayView(entry:EventEntry) -> Bool{ // return entry.isPlaceholder //} struct CountdownWidgetSmall: View { let entry:EventEntry let utils:Utility = Utility() var body: some View { let event:Event = fetchEvent(entry: entry) let combined = utils.combineDateAndTime(event.date, event.time, event.includedTime) let days = utils.calculateCountDown(combined) ZStack(alignment: .topLeading){ Color(utils.colourSchemeList[event.colour].colorWithHexString()).edgesIgnoringSafeArea(.all) VStack(alignment: .leading){ HStack(){ Text(event.emoji.decodeEmoji).foregroundColor(.black) Text(event.name).bold().foregroundColor(.black).font(.subheadline).lineLimit(2) }.lineSpacing(1) Spacer() VStack(alignment: .leading) { Text(String(days)).font(.title).foregroundColor(.black) Text(utils.getCountDownDesc(combined)).foregroundColor(.black).font(.system(size: 12)) } Spacer() HStack{ Text(utils.convertDateToString(event)).foregroundColor(.black).font(.system(size: 13)).lineLimit(2) } }.padding(15) } } } struct CountdownWidgetSmall_Previews: PreviewProvider { static var previews: some View { CountdownWidgetSmall(entry:EventEntry.placeholder).previewContext(WidgetPreviewContext(family: .systemSmall)) } }
class BlockchainSettingsStorage { let storage: IBlockchainSettingsRecordStorage let derivationKey = "derivation" let initialSyncKey = "initial_sync" init(storage: IBlockchainSettingsRecordStorage) { self.storage = storage } } extension BlockchainSettingsStorage: IBlockchainSettingsStorage { func derivationSetting(coinType: CoinType) -> DerivationSetting? { guard let coinTypeKey = BlockchainSettingRecord.key(for: coinType) else { return nil } return storage.blockchainSettings(coinTypeKey: coinTypeKey, settingKey: derivationKey) .flatMap { record in guard let derivation = MnemonicDerivation(rawValue: record.value) else { return nil } return DerivationSetting(coinType: coinType, derivation: derivation) } } func save(derivationSettings: [DerivationSetting]) { let settingRecords: [BlockchainSettingRecord] = derivationSettings.compactMap { setting in guard let coinTypeKey = BlockchainSettingRecord.key(for: setting.coinType) else { return nil } return BlockchainSettingRecord(coinType: coinTypeKey, key: derivationKey, value: setting.derivation.rawValue) } storage.save(blockchainSettings: settingRecords) } func deleteDerivationSettings() { storage.deleteAll(settingKey: derivationKey) } func initialSyncSetting(coinType: CoinType) -> InitialSyncSetting? { guard let coinTypeKey = BlockchainSettingRecord.key(for: coinType) else { return nil } return storage.blockchainSettings(coinTypeKey: coinTypeKey, settingKey: initialSyncKey) .flatMap { record in guard let syncMode = SyncMode(rawValue: record.value) else { return nil } return InitialSyncSetting(coinType: coinType, syncMode: syncMode) } } func save(initialSyncSettings: [InitialSyncSetting]) { let settingRecords: [BlockchainSettingRecord] = initialSyncSettings.compactMap { setting in let coinType = setting.coinType guard let coinTypeKey = BlockchainSettingRecord.key(for: coinType) else { return nil } return BlockchainSettingRecord(coinType: coinTypeKey, key: initialSyncKey, value: setting.syncMode.rawValue) } storage.save(blockchainSettings: settingRecords) } }
// // LibraryViewController.swift // Anghami-Playlists-Reimagined // // Created by Omar Khodr on 7/27/20. // Copyright © 2020 Omar Khodr. All rights reserved. // import UIKit class LibraryViewController: UIViewController { @IBOutlet weak var segmentedControl: UISegmentedControl! var lists = [ "https://bus.anghami.com/public/user/playlists", "https://bus.anghami.com/public/user/albums", "https://bus.anghami.com/public/user/artists" ] var pageVC: LibraryPageViewController? var currentIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ToPages" { pageVC = segue.destination as? LibraryPageViewController pageVC?.delegate = self } } @IBAction func valueChanged(_ sender: UISegmentedControl) { guard let pageVC = pageVC else { fatalError("pageVC not initialized!!") } let nextIndex = sender.selectedSegmentIndex let nextVC = pageVC.viewMusicController(nextIndex) if currentIndex > nextIndex { pageVC.setViewControllers([nextVC!], direction: .reverse, animated: true, completion: nil) } else { pageVC.setViewControllers([nextVC!], direction: .forward, animated: true, completion: nil) } currentIndex = nextIndex } } extension LibraryViewController: UIPageViewControllerDelegate { func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { if let next = pendingViewControllers.first as? MusicViewController { segmentedControl.selectedSegmentIndex = next.listIndex currentIndex = next.listIndex } } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if (!finished || !completed), let previous = previousViewControllers.first as? MusicViewController { segmentedControl.selectedSegmentIndex = previous.listIndex currentIndex = previous.listIndex } } }
// // GuideVC.swift // Qvafy // // Created by ios-deepak b on 11/06/20. // Copyright © 2020 IOS-Aradhana-cat. All rights reserved. // import UIKit import WebKit class GuideVC: UIViewController ,WKNavigationDelegate{ @IBOutlet weak var viewAdd: UIView! @IBOutlet weak var viewImgAdd: UIView! @IBOutlet weak var btnAdd: UIButton! @IBOutlet weak var vwBack: UIView! @IBOutlet weak var webkitView: WKWebView! //Loclization @IBOutlet weak var lblGuideHowWork: UILabel! // var strURL: String = "http://design.mindiii.com/gourav/terms/bang/" var strURL: String = "" var strHeaderText: String = "" override func viewDidLoad() { super.viewDidLoad() self.viewAdd.layer.cornerRadius = 17.5 self.viewAdd.layer.masksToBounds = true; self.viewAdd.layer.shadowColor = UIColor.lightGray.cgColor self.viewAdd.layer.shadowOpacity = 0.8 self.viewAdd.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) self.viewAdd.layer.shadowRadius = 6.0 self.viewAdd.layer.masksToBounds = false self.btnAdd.layer.cornerRadius = 15 self.callWsForGetContent() // self.vwBack.setCornerRadius(radius: 8) // self.viewHeader.isHidden = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.lblGuideHowWork.text = "Guide_How_Work".localize self.btnAdd.setTitle("Next".localize, for: .normal) } @IBAction func btnBack(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @IBAction func btnAddAction(_ sender: Any) { // let role = UserDefaults.standard.string(forKey:UserDefaults.KeysDefault.kRole) if objAppShareData.UserDetail.strRole == "1"{ objAppDelegate.showCustomerTabbar() } else if objAppShareData.UserDetail.strRole == "2"{ objAppDelegate.showTexiDriverTabbar() }else{ objAppDelegate.showFoodDeliveryTabbar() } } //MARK:- WKNavigationDelegate func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { } } extension GuideVC { // TODO: Webservice For Get Content func callWsForGetContent(){ if !objWebServiceManager.isNetworkAvailable(){ objWebServiceManager.StopIndicator() objAlert.showAlert(message: NoNetwork.localize , title: kAlert.localize , controller: self) return } objWebServiceManager.StartIndicator() objWebServiceManager.requestGet(strURL: WsUrl.content ,Queryparams: nil, body: nil, strCustomValidation: "", success: {response in print(response) let status = (response["status"] as? String) let message = (response["message"] as? String) objWebServiceManager.StopIndicator() if status == "success" { let dict = response["data"] as? [String:Any] if let content = dict?["content_url"] as? [String:Any]{ if let faq = content["how_to_work_url"]as? String{ self.strURL = faq if let url = URL(string: faq) { let request = URLRequest(url: url) self.webkitView.navigationDelegate = self self.webkitView.load(request) } } } }else { objAlert.showAlert(message:message ?? "", title: kAlert.localize, controller: self) } }, failure: { (error) in print(error) objWebServiceManager.StopIndicator() objAlert.showAlert(message:kErrorMessage.localize, title: kAlert.localize, controller: self) }) } }
// // Waze.swift // iOSCopilot // // Created by William Rory Kronmiller on 2/11/18. // Copyright © 2018 William Rory Kronmiller. All rights reserved. // import Foundation import CoreLocation class TrafficStatus: NSObject { private let receiverConfig: LocationReceiverConfig private let webUplink: WebUplink private var lastFetched: Date? = nil private var lastStatus: TrafficConditions? = nil private var lastWaypoint: Waypoint? = nil override init() { self.receiverConfig = LocationReceiverConfig() self.receiverConfig.maxUpdateFrequencyMs = 20 * 1000 // 20 seconds self.webUplink = CopilotAPI.shared super.init() } private func mkUrl(location: CLLocation) -> URL { let latitude = location.coordinate.latitude let longitude = location.coordinate.longitude return URL(string: "\(Configuration.shared.apiGatewayCore)/waze/\(latitude)/\(longitude)")! } private func extractLine(data: [String: Any]) -> [CLLocation] { let rawLine = data["line"] as! [[String: Double]] return rawLine.map{coordDict in return CLLocation(latitude: coordDict["y"]!, longitude: coordDict["x"]!) } } private func extractJams(data: [String : Any]) -> [TrafficJam] { if let rawJams = data["jams"] as? [[String: Any]] { let jams = rawJams.map{jam -> TrafficJam in let line = self.extractLine(data: jam) let speed = jam["speed"] as! Double let severity = jam["severity"] as! Int return TrafficJam(line: line, severity: severity, speed: speed) } return jams } return [] } private func extractAlerts(data: [String: Any]) -> [TrafficAlert] { let rawAlerts = data["alerts"] as? [[String: Any]] if(rawAlerts == nil) { NSLog("Error unpacking traffic alerts from \(data)") return [] } return rawAlerts!.map{alert in let rawLocation = alert["location"] as! [String: Double] let latitude = rawLocation["y"]! let longitude = rawLocation["x"]! let location = CLLocation(latitude: latitude, longitude: longitude) let type = alert["type"] as! String let uuid = alert["uuid"] as! String let waypoint = getWaypoint(data: alert)! return TrafficAlert(type: type, uuid: uuid, location: location, waypoint: waypoint) } } private func getWaypoint(data: [String: Any]) -> Waypoint? { let rawWaypoint = data["waypoint"] as? [String: Any] if(rawWaypoint == nil) { return nil } let latitude = rawWaypoint!["latitude"] as! Double let longitude = rawWaypoint!["longitude"] as! Double let coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) return Waypoint(location: coordinates, name: rawWaypoint!["name"] as? String) } func getLastStatus() -> TrafficConditions? { return self.lastStatus } func getLastFetched() -> Date? { return self.lastFetched } func getWaypoint() -> Waypoint? { return self.lastWaypoint } func fetch(location: CLLocation, completionHandler: @escaping (TrafficConditions?) -> Void) { let url = mkUrl(location: location) if self.receiverConfig.shouldUpdate() { NSLog("Updating traffic status") self.receiverConfig.setUpdating() CopilotAPI.shared.get(url: url, completionHandler: {(data, error) in if error != nil { NSLog("Error loading traffic \(error!)") self.receiverConfig.didUpdate() return } self.lastFetched = Date() let jams = self.extractJams(data: data!) let alerts = self.extractAlerts(data: data!) self.lastWaypoint = self.getWaypoint(data: data!) self.lastStatus = TrafficConditions(jams: jams, alerts: alerts) self.receiverConfig.didUpdate() completionHandler(self.lastStatus) }) } else { NSLog("Skipping traffic stats update") completionHandler(self.lastStatus) } } }
// // CardModel.swift // PlateiOS // // Created by Nick Machado on 11/11/17. // Copyright © 2017 Renner Leite Lucena. All rights reserved. // import Foundation class PromotionModel: Decodable, Hashable { var hashValue: Int { return promotion_id.hashValue } static func == (lhs: PromotionModel, rhs: PromotionModel) -> Bool { return lhs.promotion_id == rhs.promotion_id } var promotion_id: String = "" var title: String = "" var start_time: String = "" var end_time: String = "" var location: String = "" init(promotion_id: String, title: String, start_time: String, end_time: String, location: String) { self.promotion_id = promotion_id self.title = title self.start_time = formatTime(time: start_time) self.end_time = formatTime(time: end_time) self.location = location } } extension PromotionModel { fileprivate func formatTime(time: String) -> String { // Check if it is already on the right format let dateFormatterOutput = DateFormatter() dateFormatterOutput.dateFormat = "yyyy-MM-dd HH:mm:ss" let time_output: Date? = dateFormatterOutput.date(from: time) if time_output != nil { return time } // If not, creates input formatter that finally outputs what we want. let dateFormatterInput = DateFormatter() // Change how database store, and this function later to avoid this check. dateFormatterInput.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let time_input: Date? = dateFormatterInput.date(from: time) if let time_input = time_input { // Output returned return dateFormatterOutput.string(from: time_input) } // If did not returned so far, return time - error probably happened. return time } public func getParsedDateTime() -> String { // The input will always be "yyyy-MM-dd HH:mm:ss". Our desired output is // "EEEE, MMMM-dd h:mm a". let dateFormatterInput = DateFormatter() dateFormatterInput.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" var startDateObject = dateFormatterInput.date(from: start_time) var endDateObject = dateFormatterInput.date(from: end_time) // Change this later - add 8 hours to solve timezone problem if(startDateObject == nil || endDateObject == nil) { dateFormatterInput.dateFormat = "yyyy-MM-dd HH:mm:ss" startDateObject = dateFormatterInput.date(from: start_time) endDateObject = dateFormatterInput.date(from: end_time) }else { let calendar = Calendar.current startDateObject = calendar.date(byAdding: .hour, value: +8, to: startDateObject!) endDateObject = calendar.date(byAdding: .hour, value: +8, to: endDateObject!) } if let startDateObject = startDateObject, let endDateObject = endDateObject { // Change format to desired output let dateFormatterOutput = DateFormatter() // Output month weekday and day first. Check if we are in the same week to do this. var dateString = "" let calendar = Calendar.current let startDay = calendar.ordinality(of: .day, in: .month, for: Date())! let endDay = calendar.ordinality(of: .day, in: .month, for: startDateObject)! let daysDifference = endDay - startDay // Checks and setup of dateString if(daysDifference < 7) { if(daysDifference == 0) { dateString = "Today" }else if(daysDifference == 1) { dateString = "Tomorrow" }else { dateFormatterOutput.dateFormat = "EEEE" dateString = dateFormatterOutput.string(from: startDateObject) } }else { dateFormatterOutput.dateFormat = "MMMM dd" dateString = dateFormatterOutput.string(from: startDateObject) } // Output symbol either AM or PM dateFormatterOutput.dateFormat = "a" dateFormatterOutput.amSymbol = "AM" dateFormatterOutput.pmSymbol = "PM" // Output hours with dateFormatterOutput.dateFormat = "h:mm a" let startTimeString = dateFormatterOutput.string(from: startDateObject) let endTimeString = dateFormatterOutput.string(from: endDateObject) // Complete string returned return (dateString + " from " + startTimeString + " to " + endTimeString) }else { // Error in parsing return "Monday from 0:00 to 0:00 AM" } } fileprivate func getDate(time: String) -> String { let start = time.startIndex let end = time.index(time.startIndex, offsetBy: 10) let range = start..<end let dateSubstring = time[range] return String(dateSubstring) } fileprivate func getTime(time: String) -> String { let start = time.index(time.startIndex, offsetBy: 11) let end = (time.count != 19) ? time.index(time.endIndex, offsetBy: -8) : time.index(time.endIndex, offsetBy: -3) let range = start..<end let timeSubstring = time[range] return String(timeSubstring) } }
// // MyCollectionViewCell.swift // Sample // // Created by PranayBansal on 16/04/19. // Copyright © 2019 PranayBansal. All rights reserved. // import UIKit internal class MyCollectionViewCell: UICollectionViewCell { @IBOutlet weak var ivPoop: UIImageView! @IBOutlet weak var mText: UILabel! }
// // AgentReferralViewController.swift // hecApp-iOS // // Created by Asianark on 15/3/2016. // Copyright © 2016 Asianark. All rights reserved. // import UIKit class AgentReferralViewController: UIViewController , UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var note1: UIImageView! @IBOutlet weak var msg1: UILabel! @IBOutlet weak var fram1: UIView! @IBOutlet weak var quota: UILabel! @IBOutlet weak var link: UILabel! @IBOutlet weak var rebate: UIButton! var rebateList = [Double]() var quotasList = [NSDictionary]() var selected = -1 var ctrl = UIView() var clip = UIView() var mask = UIView() var picker = UIPickerView() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.hecNaviBarGreenColor() self.setupCtrlView() self.setupMaskView() self.setupClipView() rebate.imageEdgeInsets.left = UIScreen.mainScreen().bounds.width - 56 rebate.titleEdgeInsets.left = rebate.imageView!.bounds.width * -1 Agent.getOneWithUrl("rebates", done: { (Agent:Agent) -> Void in if let _ = Agent.rebates { self.rebateList = Agent.rebates! } }) Agent.getOneWithUrl("quotas", done: { (Agent:Agent) -> Void in if let _ = Agent.quotas { self.quotasList = Agent.quotas! } }) } func setupMaskView(){ mask = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width , height: UIScreen.mainScreen().bounds.height )) mask.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5) } func setupCtrlView(){ ctrl = UIView() ctrl.backgroundColor = UIColor.whiteColor() ctrl.frame = CGRect(x: 0, y: UIScreen.mainScreen().bounds.height - 200 , width: UIScreen.mainScreen().bounds.width, height: 200 ) let btnCancel = UIButton(frame: CGRect(x: 0, y: 0, width: (UIScreen.mainScreen().bounds.width)/2 , height: 50 )) btnCancel.addTarget(self, action: #selector(AgentReferralViewController.cancil), forControlEvents: .TouchUpInside) btnCancel.setTitle("取消", forState: .Normal) btnCancel.setTitleColor(UIColor.colorWithHexString("A2A2A2"), forState: .Normal) btnCancel.backgroundColor = UIColor.colorWithHexString("F5F5F5") ctrl.addSubview(btnCancel) let btnConfirm = UIButton(frame: CGRect(x: (UIScreen.mainScreen().bounds.width)/2, y: 0 , width: (UIScreen.mainScreen().bounds.width)/2 , height: 50 )) btnConfirm.addTarget(self, action: #selector(AgentReferralViewController.confirm), forControlEvents: .TouchUpInside) btnConfirm.setTitle("确认", forState: .Normal) btnConfirm.setTitleColor(UIColor.colorWithHexString("A2A2A2"), forState: .Normal) btnConfirm.backgroundColor = UIColor.colorWithHexString("EDEDED") ctrl.addSubview(btnConfirm) let picker = UIPickerView(frame: CGRect(x: 0, y: 50, width: ctrl.frame.width , height: 150 )) picker.delegate = self; picker.dataSource = self; ctrl.addSubview(picker) } func setupClipView(){ clip = UIView() clip.backgroundColor = UIColor.whiteColor() clip.frame = CGRect(x: 32, y: UIScreen.mainScreen().bounds.height / 2.0 - 25 , width: UIScreen.mainScreen().bounds.width - 64 , height: 50 ) let label = UILabel(frame: CGRect(x: 50, y: 0 , width: UIScreen.mainScreen().bounds.width - 64 - 50 , height: 50 )) label.text = "已复制链结到剪贴簿" label.backgroundColor = UIColor.colorWithHexString("F0F0F0") label.textAlignment = .Center label.tintColor = UIColor.colorWithHexString("606060") label.font = label.font.fontWithSize(16) clip.addSubview(label) let image = UIImageView(frame: CGRect(x: 8, y: 8, width: 34 , height: 34 )) image.image = UIImage(named: "icon_green_tick") clip.addSubview(image) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if self.view.subviews.contains(clip){ if touches.first != nil { mask.removeFromSuperview() clip.removeFromSuperview() } } } func cancil(){ mask.removeFromSuperview() ctrl.removeFromSuperview() } func confirm(){ if(selected != -1){ if note1.hidden == false { onErrorChange(true, view: fram1) } note1.hidden = true msg1.hidden = true quota.text = "" rebate.setTitle(String(rebateList[selected] * 100) + "%", forState: .Normal) for item in quotasList { if rebateList[selected] == item["rebate"] as! Double { quota.text = String(item["quota"]!) + " 个" } } if quota.text == "" { quota.text = "无限制" } } mask.removeFromSuperview() ctrl.removeFromSuperview() } @IBAction func open(sender: AnyObject) { self.view.addSubview(mask) self.view.addSubview(ctrl) } @IBAction func gen(sender: AnyObject) { if note1.hidden == false { onErrorChange(true, view: fram1) } note1.hidden = true msg1.hidden = true if selected != -1 { var rawValue = rebate.titleLabel!.text! rawValue.removeAtIndex(rawValue.endIndex.predecessor()) Agent.getOneWithUrl( "referral?rebate=" + String(Double(rawValue)!/100), done: { (agent:Agent) -> Void in self.link.text = agent.url }) } else { onErrorChange(false, view: fram1) note1.hidden = false msg1.hidden = false msg1.text = "请选择返点" } } @IBAction func copyLink(sender: AnyObject) { self.view.addSubview(mask) self.view.addSubview(clip) UIPasteboard.generalPasteboard().string = link.text! } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return rebateList.count } // The data to return for the row and component (column) that's being passed in func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return String(rebateList[row] * 100) + "%" } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selected = row } }
// // ErrorRouter.swift // Encompass_Example // // Created by Nduati Kuria on 06/09/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import Foundation import Encompass let ErrorRouter = Encompasser<Routes.ErrorRoute>() extension Routes { enum ErrorRoute: RouteConvertible { static var All: [ErrorRoute] = [ .error(error: ExampleErrors.Offline) ] case error(error: PrintableError) var routeHandler: RouteHandler { switch self { case .error: return RouteHandler({ (payload, currentController) in guard let error = payload["error"] as? PrintableError else { return } let alert = UIAlertController(title: error.title, message: error.message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) currentController.present(alert, animated: true, completion: nil) }) } } } } protocol PrintableError { var title: String? { get } var message: String? { get } } enum ExampleErrors: Error, PrintableError { case Offline case LoggedOut var title: String? { switch self { case .Offline: return "Offline" case .LoggedOut: return "LoggedOut" } } var message: String? { return "Do something about it" } }
import Foundation class UserSession { static let shared = UserSession() var usersArray: [User] = [] private init() { } }
// // SignUpViewController.swift // iNote // // Created by Arthur Ataide on 2020-06-10. // Copyright © 2020 Arthur Ataide and Jose Marmolejos. All rights reserved. // import UIKit import Amplify import AmplifyPlugins class SignUpViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var firstNameTextField: UITextField! @IBOutlet weak var lastNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var confirmPasswordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // emailTextField.layer.borderWidth = 1.0 // emailTextField.layer.masksToBounds = true // emailTextField.layer.borderColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) // emailTextField.layer.cornerRadius = 15 //emailTextField.backgroundColor = UIColor.clear // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { self.navigationController?.view.backgroundColor = UIColor.clear self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } @IBAction func signUpTapped(_ sender: UIButton) { if (vaidateFields()){ signUp(username: usernameTextField.text!, password: passwordTextField.text!, email: emailTextField.text!, givenName: firstNameTextField.text!, familyName: lastNameTextField.text!) } } @IBAction func signUpGoogleTapped(_ sender: UIButton) { } func vaidateFields() -> Bool { if (usernameTextField.text!.isEmpty){ showMessage("Sign Up", "Username is required.", "OK") return false } if (firstNameTextField.text!.isEmpty){ showMessage("Sign Up", "First Name is required.", "OK") return false } if (lastNameTextField.text!.isEmpty){ showMessage("Sign Up", "Last Name is required.", "OK") return false } if (emailTextField.text!.isEmpty){ showMessage("Sign Up", "Email is required.", "OK") return false } if (passwordTextField.text!.isEmpty){ showMessage("Sign Up", "Password is required.", "OK") return false } if (passwordTextField.text! != confirmPasswordTextField.text!){ showMessage("Sign Up", "Please make sure passwords match.", "OK") return false } if (!emailTextField.text!.contains("@") || !emailTextField.text!.contains(".")){ showMessage("Sign Up", "Please enter a valid Email address. For example jhon@email.com.", "OK") return false } return true } func showMessage(_ title:String, _ message:String, _ actionMessage:String){ let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString(actionMessage, comment: actionMessage), style: .default)) self.present(alert, animated: true, completion: nil) } func signUp(username: String, password: String, email: String, givenName:String, familyName:String) { let userAttributes = [AuthUserAttribute(.email, value: email), AuthUserAttribute(.givenName, value: givenName), AuthUserAttribute(.familyName, value: familyName)] let options = AuthSignUpRequest.Options(userAttributes: userAttributes) _ = Amplify.Auth.signUp(username: username, password: password, options: options) { result in switch result { case .success(let signUpResult): var message = "" if case let .confirmUser(deliveryDetails, _) = signUpResult.nextStep { message = "SignUp Complete. Must confirm account." print("Delivery details \(String(describing: deliveryDetails))") } else { message = "SignUp Complete" } DispatchQueue.main.async { self.successSignUp(message) } print(message) case .failure(let error): DispatchQueue.main.async { self.showMessage("Sign Up", "An error occured while registering a user \(error)", "OK") } print("An error occured while registering a user \(error)") } } } func successSignUp(_ message:String) { let alert = UIAlertController(title: "Sign Up", message:message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "OK"), style: .default,handler: { alert -> Void in self.navigationController?.popViewController(animated: true) })) self.present(alert, animated: true, completion: 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.destination. // Pass the selected object to the new view controller. } */ }
// // Token.swift // RxSwift_Part1 // // Created by shengling on 2018/6/14. // Copyright © 2018 ShengLing. All rights reserved. // import Foundation public class Token { static let key = "token" static let headerKey = "Authorization" static func setToken(token: HTTPCookie) { UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: token), forKey: Token.key) UserDefaults.standard.synchronize() } static func getToken() -> HTTPCookie? { if let data = UserDefaults.standard.value(forKey: Token.key) as? Data { return NSKeyedUnarchiver.unarchiveObject(with: data) as? HTTPCookie } return nil } static var current: HTTPCookie? { return getToken() } static func setHeader(header: [String: String]?) { UserDefaults.standard.setValue(header?[headerKey], forKeyPath: headerKey) UserDefaults.standard.synchronize() } static func getHeader() -> [String: String]? { if let value = UserDefaults.standard.value(forKey: headerKey) as? String { return [headerKey: value] } return nil } static var currentHeader: [String: String]? { return getHeader() } }
import XCTest import commenterTests var tests = [XCTestCaseEntry]() tests += commenterTests.allTests() XCTMain(tests)
// // ContentView.swift // CalendarSwiftUI // // Created by Nelson Gonzalez on 12/30/19. // Copyright © 2019 Nelson Gonzalez. All rights reserved. // import SwiftUI struct ContentView: View { @ObservedObject var dateModelController = DateModelController() var body: some View { VStack { Text("Please choose a delivery date.").font(.title).bold() ScrollView(.horizontal, showsIndicators: false, content: { HStack(spacing: 10) { ForEach(dateModelController.listOfValidDates, id: \.self) { date in GridView(date: date).onTapGesture { self.dateModelController.toggleIsSelected(date: date) } } } }) HStack { Text("Your scheduled delivery date is: ") Text("\(self.dateModelController.selectedDate)").foregroundColor(.red).bold() }.padding(.top, 20) Spacer() }.padding().padding(.top, 30) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // Keychain.swift // EosioSwiftVault // // Created by Todd Bowden on 7/11/18. // Copyright (c) 2017-2019 block.one and its contributors. All rights reserved. // import Foundation import Security import EosioSwift import BigInt import CommonCrypto /// General class for interacting with the Keychain and Secure Enclave. public class Keychain { /// Accessibility of keychain item. public enum AccessibleProtection { case whenUnlocked case afterFirstUnlock case whenPasscodeSetThisDeviceOnly case whenUnlockedThisDeviceOnly case afterFirstUnlockThisDeviceOnly var cfstringValue: CFString { switch self { case .whenUnlocked: return kSecAttrAccessibleWhenUnlocked case .afterFirstUnlock: return kSecAttrAccessibleAfterFirstUnlock case .whenPasscodeSetThisDeviceOnly: return kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly case .whenUnlockedThisDeviceOnly: return kSecAttrAccessibleWhenUnlockedThisDeviceOnly case .afterFirstUnlockThisDeviceOnly: return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly } } } /// The accessGroup allows multiple apps (including extensions) in the same team to share the same Keychain. public let accessGroup: String /// Init with accessGroup. The accessGroup allows multiple apps (including extensions) in the same team to share the same Keychain. /// /// - Parameter accessGroup: The access group should be an `App Group` on the developer account. public init(accessGroup: String) { self.accessGroup = accessGroup } /// Save a value to the Keychain. /// /// - Parameters: /// - name: The name associated with this item. /// - value: The value to save as String. /// - service: The service associated with this item. /// - protection: The device status protection level associated with this item. /// - bioFactor: The biometric presence factor associated with this item. /// - Returns: True if saved, otherwise false. public func saveValue(name: String, value: String, service: String, protection: AccessibleProtection = .afterFirstUnlockThisDeviceOnly, bioFactor: BioFactor = .none) -> Bool { guard let data = value.data(using: String.Encoding.utf8) else { return false } return saveValue(name: name, value: data, service: service, protection: protection, bioFactor: bioFactor) } /// Save a value to the Keychain. /// /// - Parameters: /// - name: The name associated with this item. /// - value: The value to save as Data. /// - service: The service associated with this item. /// - protection: The device status protection level associated with this item. /// - bioFactor: The biometric presence factor associated with this item. /// - Returns: True if saved, otherwise false. public func saveValue(name: String, value: Data, service: String, protection: AccessibleProtection = .afterFirstUnlockThisDeviceOnly, bioFactor: BioFactor = .none) -> Bool { var query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: name, kSecAttrService as String: service, kSecValueData as String: value, kSecAttrAccessGroup as String: accessGroup, kSecAttrSynchronizable as String: false, kSecAttrIsInvisible as String: true ] // Due to a bug in the iOS simulator when it is running iOS 13, adding values // to the keychain with kSecAttrAccessControl makes them unreadable in the // simulator only. Works fine on real devices. So if biometrics are not // desired, use kSecAttrAccessible instead to allow the simulator to be used // in these circumstances. Filed as: http://openradar.appspot.com/7251207 // Hopefully Apple will fix this at some point. switch bioFactor { case .fixed, .flex: guard let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault, protection.cfstringValue, bioFactor.accessFlag ?? [], nil) else { return false } query[kSecAttrAccessControl as String] = access case .none: query[kSecAttrAccessible as String] = protection.cfstringValue } let status = SecItemAdd(query as CFDictionary, nil) return status == errSecSuccess } /// Update a value in the Keychain. /// /// - Parameters: /// - name: The name associated with this item. /// - value: The updated value. /// - service: The service associated with this item. /// - Returns: True if updated, otherwise false. public func updateValue(name: String, value: String, service: String) -> Bool { guard let data = value.data(using: String.Encoding.utf8) else { return false } return updateValue(name: name, value: data, service: service) } /// Update a value in the Keychain. /// /// - Parameters: /// - name: The name associated with this item. /// - value: The updated value. /// - service: The service associated with this item. /// - Returns: True if updated, otherwise false. public func updateValue(name: String, value: Data, service: String) -> Bool { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: name, kSecAttrService as String: service, kSecAttrAccessGroup as String: accessGroup ] let attributes: [String: Any] = [kSecValueData as String: value] let status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) return status == errSecSuccess } /// Delete an item from the Keychain. /// /// - Parameters: /// - name: The name of the item to delete. /// - service: The service associated with this item. public func delete(name: String, service: String) { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: name, kSecAttrService as String: service, kSecAttrAccessGroup as String: accessGroup ] SecItemDelete(query as CFDictionary) } /// Get a value from the Keychain. /// /// - Parameters: /// - name: The name of the item. /// - service: The service associated with this item. /// - Returns: The value for the specified item as Data. public func getValueAsData(name: String, service: String) -> Data? { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: name, kSecAttrService as String: service, kSecAttrAccessGroup as String: accessGroup, kSecReturnData as String: true ] var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &item) guard status == errSecSuccess else { return nil } let data = item as! CFData // swiftlint:disable:this force_cast return data as Data } /// Get a value from the Keychain. /// /// - Parameters: /// - name: The name of the item. /// - service: The service associated with this item. /// - Returns: The value for the specified item as String. public func getValue(name: String, service: String) -> String? { guard let data = getValueAsData(name: name, service: service) else { return nil } guard let value = String(data: data, encoding: .utf8) else { return nil } return value } /// Get a dictionary of values from the Keychain for the specified service. /// /// - Parameter service: A service name. /// - Returns: A dictionary of names and Data values for the specified service. public func getValuesAsData(service: String) -> [String: Data]? { var values = [String: Data]() guard let array = getValuesAsAny(service: service) else { return nil } for item in array { if let name = item[kSecAttrAccount as String] as? String, let data = item["v_Data"] as? Data { values[name] = data } } return values } /// Get a dictionary of values from the Keychain for the specified service. /// /// - Parameter service: A service name. /// - Returns: A dictionary of names and String values for the specified service. public func getValues(service: String) -> [String: String]? { var values = [String: String]() guard let array = getValuesAsAny(service: service) else { return nil } for item in array { if let name = item[kSecAttrAccount as String] as? String, let data = item["v_Data"] as? Data, let value = String(data: data as Data, encoding: .utf8) { values[name] = value } } return values } /// Retrieve all values for service private func getValuesAsAny(service: String) -> [[String: Any]]? { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccessGroup as String: accessGroup, kSecMatchLimit as String: kSecMatchLimitAll, kSecReturnAttributes as String: true, kSecReturnRef as String: true ] var items: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &items) guard status == errSecSuccess else { return nil } guard let array = items as? [[String: Any]] else { return nil } return array } /// Make query for Key. private func makeQueryForKey(key: SecKey) -> [String: Any] { return [ kSecValueRef as String: key, kSecAttrAccessGroup as String: accessGroup, kSecReturnRef as String: true ] } /// Make query for ecKey. private func makeQueryForKey(ecKey: ECKey) -> [String: Any] { let query: [String: Any] = [ kSecValueRef as String: ecKey.privateSecKey, kSecAttrAccessGroup as String: accessGroup, kSecReturnRef as String: true ] return query } /// Make query to retrieve all elliptic curve keys in the Keychain. private func makeQueryForAllEllipticCurveKeys(tag: String? = nil, label: String? = nil, secureEnclave: Bool = false ) -> [String: Any] { var query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecMatchLimit as String: kSecMatchLimitAll, kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrAccessGroup as String: accessGroup, kSecReturnRef as String: true ] if let tag = tag { query[kSecAttrApplicationTag as String] = tag } if let label = label { query[kSecAttrLabel as String] = label } if secureEnclave { query[kSecAttrTokenID as String] = kSecAttrTokenIDSecureEnclave } return query } /// Delete key given the SecKey. /// /// - Parameter secKey: The SecKey to delete. public func deleteKey(secKey: SecKey) { let query = makeQueryForKey(key: secKey) SecItemDelete(query as CFDictionary) } /// Delete key if public key exists. /// /// - Parameter publicKey: The public key of the key to delete. public func deleteKey(publicKey: Data) { guard let privateSecKey = getPrivateSecKey(publicKey: publicKey) else { return } deleteKey(secKey: privateSecKey) } /// Update label. /// /// - Parameters: /// - label: The new label value. /// - publicKey: The public key of the key to update. public func update(label: String, publicKey: Data) { guard let ecKey = getEllipticCurveKey(publicKey: publicKey) else { return } let query = makeQueryForKey(ecKey: ecKey) let attributes: [String: Any] = [ kSecAttrLabel as String: label ] _ = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) } /// Get elliptic curve key -- getting the key from the Keychain given the key is used for testing. public func getSecKey(key: SecKey) -> SecKey? { let query = makeQueryForKey(key: key) var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &item) guard status == errSecSuccess else { return nil } let key = item as! SecKey // swiftlint:disable:this force_cast return key } /// Get an elliptic curve key given the public key. /// IMPORTANT: If the key requires a biometric check for access, the system will prompt the user for FaceID/TouchID /// /// - Parameter publicKey: The public key. /// - Returns: An ECKey corresponding to the public key. public func getEllipticCurveKey(publicKey: Data) -> ECKey? { do { let eckey: ECKey = try getEllipticCurveKey(publicKey: publicKey) return eckey } catch { return nil } } /// Get all elliptic curve keys with option to filter by tag. /// IMPORTANT: If any of the keys returned by the search query require a biometric check for access, the system will prompt the user for FaceID/TouchID /// /// - Parameter tag: The tag to filter by (defaults to `nil`). /// - Returns: An array of ECKeys. /// - Throws: If there is an error in the key query. public func getAllEllipticCurveKeys(tag: String? = nil, label: String? = nil) throws -> [ECKey] { var keys = [ECKey]() let array = try getAttributesForAllEllipticCurveKeys(tag: tag, label: label) for attributes in array { if let key = ECKey(attributes: attributes) { keys.append(key) } else { // if error try to lookup this key again using the applicationLabel (sha1 of the public key) // sometimes if there are a large number of keys returned, the key ref seems to be missing, but getting the key again with the application label works if let applicationLabel = attributes[kSecAttrApplicationLabel as String] as? Data, let key = try? getEllipticCurveKey(applicationLabel: applicationLabel) { keys.append(key) } } } if keys.count == 0 && array.count > 0 { throw EosioError(.keyManagementError, reason: "Unable to create any ECKeys from \(array.count) items.") } return keys } /// Get all attributes for elliptic curve keys with option to filter by tag. /// IMPORTANT: If any of the keys returned by the search query require a biometric check for access, the system will prompt the user for FaceID/TouchID /// /// - Parameter tag: The tag to filter by (defaults to `nil`). /// - Returns: An array of ECKeys. /// - Throws: If there is an error in the key query. public func getAttributesForAllEllipticCurveKeys(tag: String? = nil, label: String? = nil, matchLimitAll: Bool = true) throws -> [[String: Any]] { var query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrAccessGroup as String: accessGroup, kSecReturnAttributes as String: true, kSecReturnRef as String: true ] if matchLimitAll { query[kSecMatchLimit as String] = kSecMatchLimitAll } else { query[kSecMatchLimit as String] = kSecMatchLimitOne } if let tag = tag { query[kSecAttrApplicationTag as String] = tag } if let label = label { query[kSecAttrLabel as String] = label } var items: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &items) if status == errSecItemNotFound { return [[String: Any]]() } guard status == errSecSuccess else { throw EosioError(.keyManagementError, reason: "Get Attributes query error \(status).") } guard let array = items as? [[String: Any]] else { throw EosioError(.keyManagementError, reason: "Get Attributes items not an array of dictionaries.") } return array } /// Get an elliptic curve keys for the provided application label (for ec keys this is the sha1 hash of the public key) /// IMPORTANT: If the key requires a biometric check for access, the system will prompt the user for FaceID/TouchID /// /// - Parameter applicationLabel: The application label to search for /// - Throws: If there is a error getting the key /// - Returns: An ECKey public func getEllipticCurveKey(applicationLabel: Data) throws -> ECKey { //print(applicationLabel.hex) let query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrAccessGroup as String: accessGroup, kSecReturnAttributes as String: true, kSecReturnRef as String: true, kSecMatchLimit as String: kSecMatchLimitOne, kSecAttrApplicationLabel as String: applicationLabel ] var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &item) if status == errSecItemNotFound { throw EosioError(.keyManagementError, reason: "\(applicationLabel) not found.") } guard status == errSecSuccess else { throw EosioError(.keyManagementError, reason: "Get key query error \(status)") } guard let attributes = item as? [String: Any] else { throw EosioError(.keyManagementError, reason: "Cannot get attributes for \(applicationLabel)") } return try ECKey.new(attributes: attributes) } /// Get an elliptic curve keys for the provided public key /// IMPORTANT: If the key requires a biometric check for access, the system will prompt the user for FaceID/TouchID /// /// - Parameter publicKey: The publickey /// - Throws: If there is a error getting the key /// - Returns: An ECKey public func getEllipticCurveKey(publicKey: Data) throws -> ECKey { let uncPublicKey = try uncompressedPublicKey(data: publicKey) return try getEllipticCurveKey(applicationLabel: uncPublicKey.sha1) } /// Get all elliptic curve private Sec Keys. /// For Secure Enclave private keys, the SecKey is a reference. It's not posible to export the actual private key data. /// /// - Parameter tag: The tag to filter by (defaults to `nil`). /// - Returns: An array of SecKeys. public func getAllEllipticCurvePrivateSecKeys(tag: String? = nil) -> [SecKey]? { let query = makeQueryForAllEllipticCurveKeys(tag: tag) var items: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &items) guard status == errSecSuccess else { return nil } guard let keys = items as? [SecKey] else { return nil } return keys } /// Get all elliptic curve keys and return the public keys. /// IMPORTANT: If any of the keys returned by the search query require a biometric check for access, the system will prompt the user for FaceID/TouchID /// /// - Returns: An array of public SecKeys. public func getAllEllipticCurvePublicSecKeys() -> [SecKey]? { guard let privateKeys = getAllEllipticCurvePrivateSecKeys() else { return nil } var publicKeys = [SecKey]() for privateKey in privateKeys { if let publicKey = SecKeyCopyPublicKey(privateKey) { publicKeys.append(publicKey) } } return publicKeys } /// Get the private SecKey for the public key if the key exists in the Keychain. /// Public key data can be in either compressed or uncompressed format. /// IMPORTANT: If the key requires a biometric check for access, the system will prompt the user for FaceID/TouchID /// /// - Parameter publicKey: A public key in either compressed or uncompressed format. /// - Returns: A SecKey. public func getPrivateSecKey(publicKey: Data) -> SecKey? { return getEllipticCurveKey(publicKey: publicKey)?.privateSecKey } /// Create a **NON**-Secure-Enclave elliptic curve private key. /// /// - Parameter isPermanent: Is the key stored permanently in the Keychain? /// - Returns: A SecKey. public func createEllipticCurvePrivateKey(isPermanent: Bool = false) -> SecKey? { guard let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, [], nil) else { return nil } let attributes: [String: Any] = [ kSecUseAuthenticationUI as String: kSecUseAuthenticationContext, kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeySizeInBits as String: 256, kSecPrivateKeyAttrs as String: [ kSecAttrIsPermanent as String: isPermanent, kSecAttrAccessControl as String: access ] ] var error: Unmanaged<CFError>? guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else { return nil } return privateKey } /// Calculate the Y component of an elliptic curve from the X and the curve params /// - Parameters: /// - x: x /// - a: curve param a /// - b: curve param b /// - p: curve param p /// - isOdd: isOdd /// - Returns: The Y component as a bigUInt func ellipticCurveY(x: BigInt, a: BigInt, b: BigInt, p: BigInt, isOdd: Bool) -> BigUInt { // swiftlint:disable:this identifier_name let y2 = (x.power(3, modulus: p) + (a * x) + b).modulus(p) // swiftlint:disable:this identifier_name var y = y2.power((p+1)/4, modulus: p) // swiftlint:disable:this identifier_name let yMod2 = y.modulus(2) if isOdd && yMod2 != 1 || !isOdd && yMod2 != 0 { y = p - y } return BigUInt(y) } /// Compute the uncompressed public key from the compressed key /// - Parameter data: A public key /// - Parameter curve: The curve (R1 and K1 are supported) /// - Throws: If the data is not a valid public key /// - Returns: The uncompressed public key func uncompressedPublicKey(data: Data, curve: String = "R1") throws -> Data { guard let firstByte = data.first else { throw EosioError(.keyManagementError, reason: "No key data provided.") } guard firstByte == 2 || firstByte == 3 || firstByte == 4 else { throw EosioError(.keyManagementError, reason: "\(data.hex) is not a valid public key.") } if firstByte == 4 { guard data.count == 65 else { throw EosioError(.keyManagementError, reason: "\(data.hex) is not a valid public key. Expecting 65 bytes.") } return data } guard data.count == 33 else { throw EosioError(.keyManagementError, reason: "\(data.hex) is not a valid public key. Expecting 33 bytes.") } let xData = data[1..<data.count] let x = BigInt(BigUInt(xData)) var p: BigInt // swiftlint:disable:this identifier_name var a: BigInt // swiftlint:disable:this identifier_name var b: BigInt // swiftlint:disable:this identifier_name switch curve.uppercased() { case "R1" : p = BigInt(BigUInt(Data(hexString: "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF")!)) a = BigInt(-3) b = BigInt(BigUInt(Data(hexString: "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B")!)) case "K1" : p = BigInt(BigUInt(Data(hexString: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F")!)) a = BigInt(0) b = BigInt(7) default: throw EosioError(.keyManagementError, reason: "\(curve) is not a valid curve.") } let y = ellipticCurveY(x: x, a: a, b: b, p: p, isOdd: firstByte == 3) // swiftlint:disable:this identifier_name let four: UInt8 = 4 var yData = y.serialize() while yData.count < 32 { yData = [0x00] + yData } return [four] + xData + yData } /// Import an external elliptic curve private key into the Keychain. /// /// - Parameters: /// - privateKey: The private key as data (97 bytes). /// - tag: A tag to associate with this key. /// - label: A label to associate with this key. /// - protection: Accessibility defaults to .whenUnlockedThisDeviceOnly. /// - accessFlag: The accessFlag for this key. /// - Returns: The imported key as an ECKey. /// - Throws: If the key is not valid or cannot be imported. // swiftlint:disable:next cyclomatic_complexity public func importExternal(privateKey: Data, tag: String? = nil, label: String? = nil, // swiftlint:disable:this function_body_length protection: AccessibleProtection = .whenUnlockedThisDeviceOnly, accessFlag: SecAccessControlCreateFlags? = nil) throws -> ECKey { //check data length guard privateKey.count == 97 else { throw EosioError(.keyManagementError, reason: "Private Key data should be 97 bytes, found \(privateKey.count) bytes") } let publicKey = privateKey.prefix(65) if getEllipticCurveKey(publicKey: publicKey) != nil { throw EosioError(.keyManagementError, reason: "Key already exists") } guard let access = makeSecSecAccessControl(secureEnclave: false, protection: protection, accessFlag: accessFlag) else { throw EosioError(.keyManagementError, reason: "Error creating Access Control") } var attributes: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, kSecAttrKeySizeInBits as String: 256, kSecAttrAccessGroup as String: accessGroup, kSecAttrIsPermanent as String: true, kSecPrivateKeyAttrs as String: [ kSecAttrIsPermanent as String: true, kSecAttrAccessControl as String: access ] ] if let tag = tag { attributes[kSecAttrApplicationTag as String] = tag } if let label = label { attributes[kSecAttrLabel as String] = label } var error: Unmanaged<CFError>? guard let secKey = SecKeyCreateWithData(privateKey as CFData, attributes as CFDictionary, &error) else { print(error.debugDescription) throw EosioError(.keyManagementError, reason: error.debugDescription) } // We need to add: // // kSecAttrAccessControl as String: access // // to this to make the system respect the biometric requirements for access. // However if we do that right now the import process does several readbacks // and this triggers the biometric challenges, which is not what we want to // do. We'll need to rework the import flow to not require those readbacks // before we can add that here and fix the issue. SMM 2020/04/07 // // Added. See comment below. THB 2020/05/13 attributes = [ kSecClass as String: kSecClassKey, kSecValueRef as String: secKey, kSecAttrAccessGroup as String: accessGroup, kSecAttrAccessControl as String: access ] if let tag = tag { attributes[kSecAttrApplicationTag as String] = tag } if let label = label { attributes[kSecAttrLabel as String] = label } let status = SecItemAdd(attributes as CFDictionary, nil) guard status == errSecSuccess else { throw EosioError(.keyManagementError, reason: "Unable to add key \(publicKey) to Keychain") } // Previously at this point the key was read back from the keychain and returned. (See comment above) // However, if the key had a biometric restriction, the system would prompt with a biometric challenge. // So, instead construct the key attributes dictionary from in scope data to create the ECKey to return var keyatt: [String: Any] = [ kSecAttrAccessGroup as String: accessGroup, kSecValueRef as String: secKey ] if let tag = tag { keyatt[kSecAttrApplicationTag as String] = tag } if let label = label { keyatt[kSecAttrLabel as String] = label } let key = try ECKey.new(attributes: keyatt) return key } /// Make SecAccessControl private func makeSecSecAccessControl(secureEnclave: Bool, protection: AccessibleProtection = .whenUnlockedThisDeviceOnly, accessFlag: SecAccessControlCreateFlags? = nil) -> SecAccessControl? { var flags: SecAccessControlCreateFlags if let accessFlag = accessFlag { if secureEnclave { flags = [.privateKeyUsage, accessFlag] } else { flags = [accessFlag] } } else { if secureEnclave { flags = [.privateKeyUsage] } else { flags = [] } } return SecAccessControlCreateWithFlags( kCFAllocatorDefault, protection.cfstringValue, flags, nil ) } /// Create a new Secure Enclave key. /// /// - Parameters: /// - tag: A tag to associate with this key. /// - label: A label to associate with this key. /// - accessFlag: accessFlag for this key. /// - Returns: A Secure Enclave SecKey. /// - Throws: If a key cannot be created. public func createSecureEnclaveSecKey(tag: String? = nil, label: String? = nil, accessFlag: SecAccessControlCreateFlags? = nil) throws -> SecKey { return try createEllipticCurveSecKey(secureEnclave: true, tag: tag, label: label, accessFlag: accessFlag) } /// Create a new elliptic curve key. /// /// - Parameters: /// - secureEnclave: Generate this key in Secure Enclave? /// - tag: A tag to associate with this key. /// - label: A label to associate with this key. /// - protection: Accessibility defaults to whenUnlockedThisDeviceOnly. /// - accessFlag: The accessFlag for this key. /// - Returns: A SecKey. /// - Throws: If a key cannot be created. public func createEllipticCurveSecKey(secureEnclave: Bool, tag: String? = nil, label: String? = nil, protection: AccessibleProtection = .whenUnlockedThisDeviceOnly, accessFlag: SecAccessControlCreateFlags? = nil) throws -> SecKey { guard let access = makeSecSecAccessControl(secureEnclave: secureEnclave, protection: protection, accessFlag: accessFlag) else { throw EosioError(.keyManagementError, reason: "Error creating Access Control") } var attributes: [String: Any] = [ kSecUseAuthenticationUI as String: kSecUseAuthenticationContext, kSecUseOperationPrompt as String: "", kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeySizeInBits as String: 256, kSecAttrAccessGroup as String: accessGroup, kSecPrivateKeyAttrs as String: [ kSecAttrIsPermanent as String: true, kSecAttrAccessControl as String: access ] ] if secureEnclave { attributes[kSecAttrTokenID as String] = kSecAttrTokenIDSecureEnclave } if let tag = tag { attributes[kSecAttrApplicationTag as String] = tag } if let label = label { attributes[kSecAttrLabel as String] = label } var error: Unmanaged<CFError>? guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else { throw EosioError(.keyManagementError, reason: error.debugDescription) } return privateKey } /// Create a new elliptic curve key. /// /// - Parameters: /// - secureEnclave: Generate this key in Secure Enclave? /// - tag: A tag to associate with this key. /// - label: A label to associate with this key. /// - protection: Accessibility defaults to whenUnlockedThisDeviceOnly. /// - accessFlag: The accessFlag for this key. /// - Returns: An ECKey. /// - Throws: If a key cannot be created. public func createEllipticCurveKey(secureEnclave: Bool, tag: String? = nil, label: String? = nil, protection: AccessibleProtection = .whenUnlockedThisDeviceOnly, accessFlag: SecAccessControlCreateFlags? = nil) throws -> ECKey { let secKey = try createEllipticCurveSecKey(secureEnclave: secureEnclave, tag: tag, label: label, protection: protection, accessFlag: accessFlag) var keyatt: [String: Any] = [ kSecAttrAccessGroup as String: accessGroup, kSecValueRef as String: secKey ] if let tag = tag { keyatt[kSecAttrApplicationTag as String] = tag } if let label = label { keyatt[kSecAttrLabel as String] = label } let key = try ECKey.new(attributes: keyatt) return key } /// Sign if the key is in the Keychain. /// /// - Parameters: /// - publicKey: The public key corresponding to a private key to use for signing. /// - data: The data to sign. /// - Returns: A signature. /// - Throws: If private key is not available. public func sign(publicKey: Data, data: Data) throws -> Data { guard let privateKey = getPrivateSecKey(publicKey: publicKey) else { throw EosioError(.keyManagementError, reason: "Private key is not available for public key \(publicKey.hex)") } return try sign(privateKey: privateKey, data: data) } /// Sign with Secure Enclave or Keychain. /// /// - Parameters: /// - privateKey: The private key to use for signing. /// - data: The data to sign. /// - Returns: A signature. /// - Throws: If an error is encountered attempting to sign. public func sign(privateKey: SecKey, data: Data) throws -> Data { let algorithm: SecKeyAlgorithm = .ecdsaSignatureMessageX962SHA256 guard SecKeyIsAlgorithmSupported(privateKey, .sign, algorithm) else { throw EosioError(.keySigningError, reason: "Algorithm \(algorithm) is not supported") } var error: Unmanaged<CFError>? guard let der = SecKeyCreateSignature(privateKey, algorithm, data as CFData, &error) else { throw EosioError(.keyManagementError, reason: error.debugDescription) } return der as Data } /// Decrypt data using `SecKeyAlgorithm.eciesEncryptionCofactorVariableIVX963SHA256AESGCM`. /// /// - Parameters: /// - publicKey: The public key corresponding to a private key to use for decrypting. /// - message: The encrypted message. /// - Returns: The decrypted message. /// - Throws: If the private key is not found or the message cannot be decrypted. public func decrypt(publicKey: Data, message: Data) throws -> Data { // lookup ecKey in the Keychain guard let ecKey = getEllipticCurveKey(publicKey: publicKey) else { throw EosioError(.keyManagementError, reason: "key not found") } // decrypt var error: Unmanaged<CFError>? let algorithm = SecKeyAlgorithm.eciesEncryptionCofactorVariableIVX963SHA256AESGCM guard let decryptedData = SecKeyCreateDecryptedData(ecKey.privateSecKey, algorithm, message as CFData, &error) else { throw EosioError(.keyManagementError, reason: error.debugDescription) } return decryptedData as Data } } private extension Data { var toUnsafeMutablePointerBytes: UnsafeMutablePointer<UInt8> { let pointerBytes = UnsafeMutablePointer<UInt8>.allocate(capacity: self.count) self.copyBytes(to: pointerBytes, count: self.count) return pointerBytes } var toUnsafePointerBytes: UnsafePointer<UInt8> { return UnsafePointer(self.toUnsafeMutablePointerBytes) } /// Returns the SHA1hash of the data. var sha1: Data { var hash = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) let p = self.toUnsafePointerBytes // swiftlint:disable:this identifier_name _ = CC_SHA1(p, CC_LONG(self.count), &hash) p.deallocate() return Data(hash) } } public extension Data { /// Compress an uncompressed 65 byte public key to a 33 byte compressed public key. var compressedPublicKey: Data? { guard self.count == 65 else { return nil } let uncompressedKey = self guard uncompressedKey[0] == 4 else { return nil } let x = uncompressedKey[1...32] let yLastByte = uncompressedKey[64] let flag: UInt8 = 2 + (yLastByte % 2) let compressedKey = Data([flag]) + x return compressedKey } } public extension SecKey { /// The externalRepresentation of a SecKey in ANSI X9.63 format. var externalRepresentation: Data? { var error: Unmanaged<CFError>? if let cfdata = SecKeyCopyExternalRepresentation(self, &error) { return cfdata as Data } return nil } /// The public key for a private SecKey. var publicKey: SecKey? { return SecKeyCopyPublicKey(self) } }
// // UICollectionView+Extension.swift // AirCollection // // Created by Lysytsia Yurii on 15.07.2020. // Copyright © 2020 Developer Lysytsia. All rights reserved. // import struct Foundation.IndexPath import class UIKit.UICollectionView import class UIKit.UICollectionViewCell import class UIKit.UICollectionReusableView public extension UICollectionView { /// Register a class for use in creating new collection view cells. func register<T: UICollectionViewCell>(_ cellClass: T.Type) where T: IdentificableView { self.register(cellClass, forCellWithReuseIdentifier: cellClass.viewIdentifier) } /// Register a nib file for use in creating new collection view cells func register<T: UICollectionViewCell>(_ cellClass: T.Type) where T: NibLoadableView & IdentificableView { self.register(cellClass.viewNib, forCellWithReuseIdentifier: cellClass.viewIdentifier) } /// Registers a class for use in creating supplementary views for the collection view func register<T: UICollectionReusableView>(_ viewClass: T.Type, for kind: CollectionViewElementKindSection) where T: IdentificableView { self.register(viewClass, forSupplementaryViewOfKind: kind.rawValue, withReuseIdentifier: viewClass.viewIdentifier) } /// Registers a nib file for use in creating supplementary views for the collection view func register<T: UICollectionReusableView>(_ viewClass: T.Type, for kind: CollectionViewElementKindSection) where T: NibLoadableView & IdentificableView { self.register(viewClass.viewNib, forSupplementaryViewOfKind: kind.rawValue, withReuseIdentifier: viewClass.viewIdentifier) } /// Gets the index path of supplementary view of the specified type. /// - Parameters: /// - supplementaryView: The supplementary view object whose index path you want. /// - kind: The kind of supplementary view to locate. This value is defined by the layout object. This parameter must not be nil func indexPath(forSupplementaryView supplementaryView: UICollectionReusableView, of elementKind: CollectionViewElementKindSection) -> IndexPath? { let visibleIndexPaths = self.indexPathsForVisibleSupplementaryElements(ofKind: elementKind.rawValue) return visibleIndexPaths.first(where: { self.supplementaryView(forElementKind: elementKind.rawValue, at: $0) == supplementaryView }) } }
// // SCNVector3+Arithmetic.swift // ARWig // // Created by Esteban Arrúa on 11/21/18. // Copyright © 2018 Hattrick It. All rights reserved. // import Foundation import SceneKit extension SCNVector3 { func normalized() -> SCNVector3 { let lenght = self.lenght() return SCNVector3Make(x/lenght, y/lenght, z/lenght) } func lenght() -> Float { return sqrtf(x * x + y * y + z * z) } static func crossProduct(left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x).normalized() } static func diference(left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z) } static func angle(left: SCNVector3, right: SCNVector3) -> Float { let cosAngle = dotProduct(left: left, right: right) / left.lenght() * right.lenght() return acos(cosAngle) } static func dotProduct(left: SCNVector3, right: SCNVector3) -> Float { return left.x * right.x + left.y * right.y + left.z * right.z } static func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z) } static func += (left: inout SCNVector3, right: SCNVector3) { left = left + right } static func * (vector: SCNVector3, scalar: Float) -> SCNVector3 { return SCNVector3Make(vector.x * scalar, vector.y * scalar, vector.z * scalar) } static func / (vector: SCNVector3, scalar: Float) -> SCNVector3 { return SCNVector3Make(vector.x / scalar, vector.y / scalar, vector.z / scalar) } static func distance(from left: SCNVector3, to right: SCNVector3) -> Float { let xDist = (left.x - right.x) let yDist = (left.y - right.y) let zDist = (left.z - right.z) return sqrt(pow(xDist, 2) + pow(yDist, 2) + pow(zDist, 2)) } static func midpoint(of points: [SCNVector3]) -> SCNVector3 { var vector = SCNVector3Make(0, 0, 0) guard points.count != 0 else { return SCNVector3Zero } for point in points { vector += point } vector = vector / Float(points.count) return vector } }
// // UserApiContainer.swift // Mitter // // Created by Rahul Chowdhury on 12/11/18. // Copyright © 2018 Chronosphere Technologies Pvt. Ltd. All rights reserved. // import Foundation import Swinject import Moya class UserApiContainer { private let applicationId: String private let userAuthToken: String private let container: Container init(applicationId: String, userAuthToken: String) { self.applicationId = applicationId self.userAuthToken = userAuthToken container = Container() registerUserApiLayers() } func getPushMessageManager() -> PushMessageManager { return PushMessageManager(fcmMessageProcessor: getFcmMessageProcessor()) } func getFetchUserAction() -> FetchUserAction { return FetchUserAction(userRepository: getUserRepository()) } func getFetchUserPresencesAction() -> FetchUserPresencesAction { return FetchUserPresencesAction(userRepository: getUserRepository()) } func getFetchUsersByLocatorsAction() -> FetchUsersByLocatorsAction { return FetchUsersByLocatorsAction(userRepository: getUserRepository()) } func getUpdateUserPresenceAction() -> UpdateUserPresenceAction { return UpdateUserPresenceAction(userRepository: getUserRepository()) } func getAddFcmDeliveryEndpointAction() -> AddFcmDeliveryEndpointAction { return AddFcmDeliveryEndpointAction(userRepository: getUserRepository()) } func getAuthenticateGoogleSignInAction() -> AuthenticateGoogleSignInAction { return AuthenticateGoogleSignInAction(userRepository: getUserRepository()) } private func getFcmMessageProcessor() -> FcmMessageProcessor { return FcmMessageProcessor() } private func registerUserApiLayers() { container.register(UserRepositoryContract.self, name: Constants.Users.userRemoteSource) { _ in UserRemoteSource( apiProvider: MoyaProvider<UserApiService>( plugins: [ ApiAuthPlugin( applicationId: self.applicationId, userAuthToken: self.userAuthToken ), NetworkLoggerPlugin(verbose: true) ] ) ) } container.register(UserRepositoryContract.self, name: Constants.Users.userRepository) { resolver in UserRepository( userRemoteSource: resolver.resolve( UserRepositoryContract.self, name: Constants.Users.userRemoteSource ) as! UserRemoteSource ) } } private func getUserRepository() -> UserRepository { return container.resolve( UserRepositoryContract.self, name: Constants.Users.userRepository ) as! UserRepository } }
// // CharacterUnplayableData.swift // RPGMill // // Created by William Young on 1/17/19. // Copyright © 2019 William Young. All rights reserved. // import Cocoa class CharacterUnplayableData: NSObject, NSCoding { static let keyName = "characterUnplayables" unowned var parent: GameData @objc var id: String { didSet { guard id != oldValue else { return } parent.undoManager?.setActionName("Change NPC Name") parent.undoManager?.registerUndo(withTarget: self, selector: #selector(setter: MapData.id), object: oldValue) } } @objc var image: NSImage? { didSet { guard image != oldValue else { return } parent.undoManager?.setActionName("Change NPC Image") parent.undoManager?.registerUndo(withTarget: self, selector: #selector(setter: image), object: oldValue) } } @objc var location: LocationData { didSet { guard location != oldValue else { return } parent.undoManager?.setActionName("Change NPC Location") parent.undoManager?.registerUndo(withTarget: self, selector: #selector(setter: location), object: oldValue) } } @objc var phrase: String { didSet { guard phrase != oldValue else { return } parent.undoManager?.setActionName("Change NPC Phrase") parent.undoManager?.registerUndo(withTarget: self, selector: #selector(setter: phrase), object: oldValue) } } var imageName: String { return "\(uuid).tiff" } var rtfName: String { return "\(uuid).rtf" } let uuid: String var rtf: Data? init(id: String, uuid: String, location: LocationData, phrase: String, rtf: Data?, gameData: GameData){ self.id = id self.uuid = uuid self.location = location self.phrase = phrase self.rtf = rtf self.parent = gameData } convenience init(id: String, location: LocationData, phrase: String, rtf: Data?, gameData: GameData){ self.init(id: id, uuid: "character_\(UUID().uuidString)", location: location, phrase: phrase, rtf: rtf, gameData: gameData) } required convenience init?(coder aDecoder: NSCoder) { guard let id = aDecoder.decodeObject(forKey: "id") as? String, let uuid = aDecoder.decodeObject(forKey: "uuid") as? String, let location = aDecoder.decodeObject(forKey: "location") as? LocationData, let phrase = aDecoder.decodeObject(forKey: "phrase") as? String, let gameData = aDecoder.decodeObject(forKey: "gameData") as? GameData else { return nil } self.init(id: id, uuid: uuid, location: location, phrase: phrase, rtf: nil, gameData: gameData) } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: "id") aCoder.encode(uuid, forKey: "uuid") aCoder.encode(location, forKey: "location") aCoder.encode(phrase, forKey: "phrase") aCoder.encode(parent, forKey: "gameData") } func readFileWrapper(fileWrapper: FileWrapper) { if let imageData = fileWrapper.fileWrappers?[imageName]?.regularFileContents { self.image = NSImage(data: imageData) } if let rtf = fileWrapper.fileWrappers?[rtfName]?.regularFileContents { self.rtf = rtf } } func fileWrapper() -> FileWrapper? { var items = [String:FileWrapper]() if let image = image?.tiffRepresentation { items[imageName] = FileWrapper(regularFileWithContents: image) } if let rtf = rtf { items[rtfName] = FileWrapper(regularFileWithContents: rtf) } return FileWrapper(directoryWithFileWrappers: items) } } extension CharacterUnplayableData: OverviewItem { func viewFor(outlineView: NSOutlineView, tableColumn: NSTableColumn?) -> NSView? { if let itemCell = outlineView.makeView(withIdentifier: .itemCell, owner: self) as? NSTableCellView { itemCell.textField?.stringValue = self.id return itemCell } return nil } }
// // pDollar.swift // DollarPRecognizer // // Created by Ed Southwood on 13/04/2017. // Copyright © 2017 Ed Southwood. All rights reserved. // import Foundation import UIKit struct point { var point : CGPoint var strokeID : Int init() { point = CGPoint.zero strokeID = 0 } init(point: CGPoint) { self.point = point //use the self bit to beable to use the same variable name strokeID = 0 } init(point: CGPoint, strokeID: Int) { self.point = point self.strokeID = strokeID } init(point: (Double, Double), strokeID: Int) { self.point = CGPoint(x: point.0, y: point.1) self.strokeID = strokeID } } func translateToOrigin (points: inout [point], n: Int) -> [point] { //inout keyword allows variables passed to the function to be modified var c: CGPoint = CGPoint.zero //this becomes the centroid for p in points { c.x = c.x + p.point.x c.y = c.y + p.point.y } c.x = c.x/CGFloat(n) c.y = c.y/CGFloat(n) for index in points.indices { points[index].point.x = points[index].point.x - c.x points[index].point.y = points[index].point.y - c.y } return points } func scale (points: inout [point]) -> [point] { var x_min: CGFloat = CGFloat.infinity var x_max: CGFloat = 0 var y_min: CGFloat = CGFloat.infinity var y_max: CGFloat = 0 for p in points { x_min = min(x_min, p.point.x) y_min = min(y_min, p.point.y) x_max = max(x_max, p.point.x) y_max = max(y_max, p.point.y) } let scale = max((x_max - x_min), (y_max - y_min)) for index in points.indices { points[index].point.x = (points[index].point.x - x_min)/scale points[index].point.y = (points[index].point.y - y_min)/scale } return points } func pathLength (points: [point]) -> CGFloat { var d : CGFloat = 0 for x in points.indices { if x != 0 { //ignore first point to enable finding distance between points if points[x].strokeID == points[x-1].strokeID { //check points are in the same stroke d = d + euclidianDistance(a: points[x].point, b: points[x-1].point) } } } return d } func euclidianDistance(a: CGPoint, b: CGPoint) -> CGFloat { return (((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y))).squareRoot() } func resample (points: inout [point], n: Int) -> [point] { let I = pathLength(points: points) / CGFloat(n - 1) var D : CGFloat = 0 var d : CGFloat = 0 var q = point() var newPoints = [point]() newPoints.append(points[0]) var x = 0 var indices = 1 while x < indices { if x != 0 { //ignore first point if points[x].strokeID == points[x-1].strokeID { //check points are in the same stroke d = euclidianDistance(a: points[x-1].point, b: points[x].point) if ((D + d) > I) || fabs((D + d) - I) < 0.000000000001 { //required since D + d == I evaluated to false when they appeared equal due to floating point errors - this is optomised for 64bit processors q.point.x = points[x-1].point.x + ((I - D)/d) * (points[x].point.x - points[x-1].point.x) q.point.y = points[x-1].point.y + ((I - D)/d) * (points[x].point.y - points[x-1].point.y) q.strokeID = points[x].strokeID newPoints.append(q) points.insert(q, at: x) D = 0 } else { D = D + d } } } x = x + 1 indices = points.count } return newPoints } func normalize (points: inout [point], n: Int) { points = resample(points: &points, n: n) _ = scale(points: &points) // _ = ignores the return value of the function _ = translateToOrigin(points: &points, n: n) } func cloudDistance (points: [point], template: [point], n: Int, start: Int) -> CGFloat { var sum : CGFloat = 0 var matched = Array(repeating: false, count: n) var i = start var min : CGFloat var d : CGFloat var index : Int = 0 repeat { min = CGFloat.infinity for j in matched.indices { if !matched[j] { d = euclidianDistance(a: points[i].point, b: template[j].point) if d < min { min = d index = j } } } matched[index] = true let weight = 1 - CGFloat(((i - start + n) % n))/CGFloat(n) sum = sum + weight * min i = (i + 1) % n } while i != start return sum } func greedyCloudMatch(points: [point], template: [point], n: Int) -> CGFloat { let E = 0.5 let step = Int(floor(pow(Double(n),(1-E)))) var minimum = CGFloat.infinity for i in stride(from: 0, to: n, by: step) { let d1 = cloudDistance(points: points, template: template, n: n, start: i) let d2 = cloudDistance(points: template, template: points, n: n, start: i) minimum = min(minimum,d1,d2) } return minimum } // changed to give a better return result func pRecogniser(points: inout [point], templates: [ (String , [point] ) ]) -> (String,CGFloat) { let n = 32 //this is where n is set for the rest of the functions normalize(points: &points, n: n) var score = CGFloat.infinity //var result : [point] = templates[0].1 //forced to avoid an error should be written over in the loop var result = "none" for i in templates.indices { //normalize(points: &templates[i].1, n: n) // this should already be done Remove later - and code can be simplified let d = greedyCloudMatch(points: points, template: templates[i].1, n: n) if score > d { score = d result = templates[i].0 } } score = max(((2.0 - score)/2.0), 0.0) return (result,score) }
// // SignUpViewController.swift // Jarvis // // Created by apple on 2017. 9. 13.. // Copyright © 2017년 apple. All rights reserved. // import UIKit import SnapKit import FirebaseAuth import Firebase struct NickDistinction { var nick : String } class SignUpViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { //회원가입 뷰 @objc var EmailText = UITextField() @objc var PasswordText = UITextField() @objc var yearText = UITextField() @objc var NicknameText = UITextField() @objc var twicePass = UITextField() @objc var signButton = UIButton() @objc var picker = UIPickerView() @objc var ref : DatabaseReference? var handle : DatabaseHandle? @objc var pickOption = ["20대", "30대", "40대", "50대"] @objc let toolbar = UIToolbar() @objc var backimage = UIImageView() var List : [NickDistinction] = [] @IBOutlet weak var navi: UINavigationBar! @objc func displayErrorMessage(title : String , message : String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let confirm = UIAlertAction(title: "확인", style: .default) { (action : UIAlertAction) -> Void in } alert.addAction(confirm) present(alert, animated: true, completion: nil) } @objc func SuccessSignup(title : String, message : String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let confirm = UIAlertAction(title: "확인", style: .default) { (action : UIAlertAction) -> Void in self.performSegue(withIdentifier: "MainPage", sender: self) } alert.addAction(confirm) present(alert, animated: true, completion: nil) } @objc func Create() { handle = ref?.child("NickNameForLoginData").observe(.value, with: { (snapshot) in if snapshot.value is NSNull { Auth.auth().createUser(withEmail: self.EmailText.text!, password: self.PasswordText.text!, completion: { (user, error) in if user != nil { print("success") let data = ["Email_Name" : self.EmailText.text!] let data1 = ["generation" : self.yearText.text!] let data2 = ["NickName" : self.NicknameText.text!] self.ref?.child("User").child((user?.user.uid)!).child("UserProfile").setValue(data)// 유저 란 밑에 아이디 self.ref?.child("User").child((user?.user.uid)!).child("UserProfile").updateChildValues(data1) self.ref?.child("User").child((user?.user.uid)!).child("UserProfile").updateChildValues(data2) self.ref?.child("NickNameForLoginData").child(self.NicknameText.text!).setValue(["Email" : self.EmailText.text!]) self.ref?.child("NickNameForLoginData").child(self.NicknameText.text!).updateChildValues(["Password" : self.PasswordText.text!]) self.ref?.child("NickNameForLoginData").child(self.NicknameText.text!).updateChildValues(["TwicePass" : self.twicePass.text!]) self.ref?.child("NickNameForLoginData").child(self.NicknameText.text!).updateChildValues(["NickName" : self.NicknameText.text!]) self.SuccessSignup(title: "회원가입을 환영합니다.", message: "") } else { if let myError = error?.localizedDescription { print(myError) } else { print("error") } } }) } else { self.handle = self.ref?.child(snapshot.key).child(self.NicknameText.text!).observe(.value, with: { (snapshot) in if snapshot.exists() { // 회원 계정이 있을 때 닉네임 텍스트필드에 값이 키로 존재하면 self.displayErrorMessage(title: "닉네임 중복입니다.", message: "다시 입력해주십시오") } else { // 존재하지 않는다? == 중복이 없다. Auth.auth().createUser(withEmail: self.EmailText.text!, password: self.PasswordText.text!, completion: { (user, error) in if user != nil { print("success") let data = ["Email_Name" : self.EmailText.text!] let data1 = ["generation" : self.yearText.text!] let data2 = ["NickName" : self.NicknameText.text!] self.ref?.child("User").child((user?.user.uid)!).child("UserProfile").setValue(data)// 유저 란 밑에 아이디 self.ref?.child("User").child((user?.user.uid)!).child("UserProfile").updateChildValues(data1) self.ref?.child("User").child((user?.user.uid)!).child("UserProfile").updateChildValues(data2) self.ref?.child("NickNameForLoginData").child(self.NicknameText.text!).setValue(["Email" : self.EmailText.text!]) self.ref?.child("NickNameForLoginData").child(self.NicknameText.text!).updateChildValues(["Password" : self.PasswordText.text!]) self.ref?.child("NickNameForLoginData").child(self.NicknameText.text!).updateChildValues(["TwicePass" : self.twicePass.text!]) self.ref?.child("NickNameForLoginData").child(self.NicknameText.text!).updateChildValues(["NickName" : self.NicknameText.text!]) self.SuccessSignup(title: "회원가입을 환영합니다.", message: "") } else { if let myError = error?.localizedDescription { print(myError) } else { print("error") } } }) } }) } }) } @objc func Signup(sender : UIButton!) { if EmailText.text != "" && PasswordText.text != "" && yearText.text != "" && NicknameText.text != "" && twicePass.text != "" { // 전부 다 공백이 아니면 if (twicePass.text?.count)! == 4 { // 공백 아닌 상태에서 네자리가 맞다.? 그럼 닉네임 중복검사 Create() } else { displayErrorMessage(title: "2차 비밀번호는 4자리 입니다.", message: "") } } else { //공백이 있는경우. displayErrorMessage(title: "공백이 있습니다.", message: "입력 해주세요") } } @objc func donePicker(sender : UIBarButtonItem!) { yearText.resignFirstResponder() } @objc func dismisskeyboard() { view.endEditing(true) } override func viewDidLoad() { super.viewDidLoad() let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismisskeyboard)) view.addGestureRecognizer(tap) ref = Database.database().reference() backimage = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)) backimage.image = UIImage(named: "signup.png") let superView = self.view! superView.insertSubview(backimage, belowSubview: navi) picker.delegate = self toolbar.barStyle = .default toolbar.sizeToFit() let donebutton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donePicker)) toolbar.setItems([donebutton], animated: false) toolbar.isUserInteractionEnabled = true yearText.inputAccessoryView = toolbar EmailText = UITextField(frame: CGRect(x: 0, y: 0, width: superView.frame.width/4, height: 30)) EmailText.placeholder = "Email" PasswordText.placeholder = "Password" NicknameText.placeholder = "별명" yearText.placeholder = "ex) 20대 30대" twicePass.placeholder = "2차 비밀번호 4자리" UINavigationBar.appearance().tintColor = UIColor.black UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "THECandybar", size: 20)!] EmailText.backgroundColor = UIColor.white PasswordText.backgroundColor = UIColor.white NicknameText.backgroundColor = UIColor.white yearText.backgroundColor = UIColor.white twicePass.backgroundColor = UIColor.white EmailText.borderStyle = .roundedRect PasswordText.borderStyle = .roundedRect NicknameText.borderStyle = .roundedRect yearText.borderStyle = .roundedRect twicePass.borderStyle = .roundedRect yearText.inputView = picker EmailText.autocapitalizationType = .none PasswordText.autocapitalizationType = .none PasswordText.isSecureTextEntry = true twicePass.autocapitalizationType = .none NicknameText.autocapitalizationType = .none twicePass.isSecureTextEntry = true twicePass.adjustsFontSizeToFitWidth = true EmailText.autocorrectionType = .no PasswordText.autocorrectionType = .no NicknameText.autocorrectionType = .no superView.addSubview(EmailText) superView.addSubview(PasswordText) superView.addSubview(NicknameText) superView.addSubview(signButton) superView.addSubview(yearText) superView.addSubview(twicePass) signButton.setImage(UIImage(named: "membership.png"), for: .normal) signButton.isHighlighted = true signButton.addTarget(self, action: #selector(self.Signup), for: .touchUpInside) EmailText.snp.makeConstraints { (make) in make.top.equalTo(superView).offset(self.view.frame.height/5) make.left.equalTo(superView).offset(self.view.frame.width/4) make.right.equalTo(superView).offset(-(self.view.frame.width/4)) } PasswordText.snp.makeConstraints { (make) in make.size.equalTo(EmailText) make.top.equalTo(EmailText.snp.bottom).offset(25) make.left.equalTo(EmailText) make.right.equalTo(EmailText) } signButton.snp.makeConstraints { (make) in make.size.equalTo(superView.frame.width/3) make.top.equalTo(twicePass.snp.bottom).offset(25) make.centerX.equalTo(twicePass.snp.centerX) } NicknameText.snp.makeConstraints { (make) in make.size.equalTo(EmailText) make.top.equalTo(PasswordText.snp.bottom).offset(25) make.left.equalTo(EmailText) make.right.equalTo(EmailText) } yearText.snp.makeConstraints { (make) in make.size.equalTo(EmailText) make.top.equalTo(NicknameText.snp.bottom).offset(25) make.left.equalTo(EmailText) make.right.equalTo(EmailText) } twicePass.snp.makeConstraints { (make) in make.size.equalTo(twicePass) make.top.equalTo(yearText.snp.bottom).offset(25) make.left.equalTo(EmailText) make.right.equalTo(EmailText) } navi.snp.makeConstraints { (make) in make.top.equalTo(superView.snp.top).offset(3) make.left.equalTo(superView.snp.left) make.right.equalTo(superView.snp.right) } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickOption.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickOption[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { yearText.text = pickOption[row] } /* // 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. } */ }
// // LogoutViewController.swift // MovieMemo // // Created by 신미지 on 2021/07/07. // import UIKit class LogoutViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func logoutBtnTap(_ sender: Any) { ModalVC.AlertVC(title: "⚠", msg: "정말 로그아웃하시겠습니까?", action: { (_) in UserDefaults.standard.removeObject(forKey: "token") let wnd = UIApplication.shared.windows.filter {$0.isKeyWindow}.first let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") wnd?.rootViewController = loginVC }, view: self) } @IBAction func cancelBtnTap(_ sender: Any) { self.dismiss(animated: true, completion: nil) } }
// // Basket.swift // eDairy // // Created by Daniel Bolivar herrera on 4/10/17. // Copyright © 2017 R3PI. All rights reserved. // import UIKit class Basket: NSObject { public private(set) var items: [String : Int] //Dictionary of Product name (must be unique) (key) and amount of that item (value) override init() { self.items = Dictionary() } func addProduct(product: Product) { if let productAmount = self.items[product.id] { //If product exist, add one self.items[product.id] = productAmount+1 } else { //Add key if it does not exist self.items[product.id] = 1 } } func removeProduct(product: Product) { if let productAmount = self.items[product.id] { //If product exist, add one if productAmount == 1 { self.items.removeValue(forKey: product.id) } else { self.items[product.id] = productAmount-1 } } else { print("Error: Trying to remove a product that is not in the basket") } } func removeProductCompletely(product: Product) { self.items.removeValue(forKey: product.id) } }
var boxIds: [String] = []; while let boxId = readLine() { boxIds.append(boxId) } let targetFreqs = [2, 3] var count: [Int: Int] = [:] for f in targetFreqs { count[f] = 0 } for boxId in boxIds { var charFreqs: [Character: Int] = [:] #if swift(>=4.0) let idChars = boxId #elseif swift(>=3.0) let idChars = boxId.characters #endif for c in idChars { charFreqs[c] = (charFreqs[c] ?? 0) + 1 } var found: [Int: Bool] = [:] for f in targetFreqs { found[f] = false } for (_, val) in charFreqs { if targetFreqs.contains(val) { found[val] = true } var allFound = true for (_, val) in found { allFound = allFound && val } if allFound { break } } for (key, val) in found { if val { count[key] = (count[key] ?? 0) + 1 } } } var checksum = 1 for (_, val) in count { checksum *= val } print("\(checksum)")
// // CollectionViewCell.swift // ShiritoriWalk // // Created by esaki yuki on 2020/06/05. // Copyright © 2020 esaki yuKki. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet var tangoLabel: UILabel! @IBOutlet var photoImageView: UIImageView! }
// // CGPoint.swift // MyGestureRecognizer // // Created by Marcin on 08.07.2017. // Copyright © 2017 Marcin Włoczko. All rights reserved. // import UIKit extension CGPoint { func distanceTo(point: CGPoint) -> CGFloat { let x = point.x - self.x let y = point.y - self.y return sqrt(x * x + y * y) } }
// // Product.swift // CategoryAverage // // Created by Suraj Pathak on 26/6/17. // Copyright © 2017 Suraj Pathak. All rights reserved. // import Foundation struct Product { let title: String let category: String let weight: Double let length: Double let width: Double let height: Double var cubicWeight: Double { return (length/100 * width/100 * height/100) * 250 } static func averageCubicWeight(_ products: [Product]) -> Double { let total = products.reduce(0) { (result, product) -> Double in return result + product.cubicWeight } return total/Double(products.count).rounded() } } extension Product { init?(raw: [String: Any]) { guard let title = raw["title"] as? String, let category = raw["category"] as? String, let weight = raw["weight"] as? Double, let size = raw["size"] as? [String: Double], let length = size["length"], let width = size["width"], let height = size["height"] else { return nil } self.title = title self.category = category self.weight = weight self.length = length self.width = width self.height = height } }
// // ProfileViewController.swift // stay-safe // // Created by Cristian Gonzales on 7/21/17. // Copyright © 2017 Northrop Grumman. All rights reserved. // import UIKit class ProfileViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var firstNameField: UITextField! @IBOutlet weak var lastNameField: UITextField! @IBOutlet weak var phoneNumField: UITextField! @IBAction func nextButton(_ sender: Any) { } }
// // UserListViewController.swift // iOS-MVVMC-Architecture // // Created by Takahiro Nishinobu on 2017/06/15. // Copyright © 2017年 hachinobu. All rights reserved. // import UIKit import RxSwift import RxCocoa import Kingfisher final class UserListViewController: UIViewController, UserListViewProtocol { fileprivate let selectedUserObserver = PublishSubject<String>() lazy var selectedUser: Observable<String> = { return self.selectedUserObserver.asObservable() }() var viewModel: UserListViewModelProtocol! fileprivate lazy var loadingIndicatorView = LoadingIndicatorView.loadView() let bag = DisposeBag() @IBOutlet weak var tableView: UITableView! lazy var reachedBottom: ControlEvent<Void> = { return self.tableView.rx.reachedBottom }() override func viewDidLoad() { super.viewDidLoad() setupUI() viewModel.bindReachedBottom(reachedBottom: tableView.rx.reachedBottom.asDriver()) bindTimeLineFetch() bindTableView() } } extension UserListViewController { fileprivate func setupUI() { //TableView Setting tableView.dataSource = nil tableView.delegate = nil tableView.tableFooterView = loadingIndicatorView tableView.estimatedRowHeight = 70 tableView.rowHeight = UITableViewAutomaticDimension tableView.register(withType: UserListCell.self) } fileprivate func bindTimeLineFetch() { viewModel.error .drive(onNext: { error in print(error) }).addDisposableTo(bag) } fileprivate func bindTableView() { viewModel.loadingIndicatorAnimation .drive(loadingIndicatorView.indicator.rx.isAnimating) .addDisposableTo(bag) viewModel.loadingIndicatorAnimation.map { !$0 } .drive(loadingIndicatorView.indicator.rx.isHidden) .addDisposableTo(bag) //TableViewCellのBind viewModel.users.drive(tableView.rx.items(cellIdentifier: UserListCell.nibName, cellType: UserListCell.self)) { row, cellViewModel, cell in cellViewModel.userName.bind(to: cell.userNameLabel.rx.text).addDisposableTo(cell.bag) cellViewModel.screenName.bind(to: cell.screenNameLabel.rx.text).addDisposableTo(cell.bag) cellViewModel.description.bind(to: cell.descriptionLabel.rx.text).addDisposableTo(cell.bag) cellViewModel.profileURL .filter { $0 != nil } .subscribe(onNext: { [weak cell] url in let imageURL = url! let resource = ImageResource(downloadURL: imageURL, cacheKey: imageURL.absoluteString) cell?.iconImageView.kf.indicatorType = .activity cell?.iconImageView.kf.setImage(with: resource, placeholder: nil, options: [.transition(ImageTransition.fade(1.0)), .cacheMemoryOnly], progressBlock: nil, completionHandler: nil) }).addDisposableTo(cell.bag) }.addDisposableTo(bag) tableView.rx.modelSelected(UserListCellViewModelProtocol.self).do(onNext: { [weak self] _ in if let selectedIndexPath = self?.tableView.indexPathForSelectedRow { self?.tableView.deselectRow(at: selectedIndexPath, animated: true) } }).map { $0.userId.description }.bind(to: selectedUserObserver).addDisposableTo(bag) } }
import UIKit import MapKit class shopLocationViewController: UIViewController { private var datas: [ShopsL] = [] @IBOutlet weak var mapView: MKMapView! /* var coordinate2D = CLLocationCoordinate2DMake(50.725830, -1.865020) func updateMapRegion(rangeSpan: CLLocationDistance){ let region = MKCoordinateRegion(center: coordinate2D, latitudinalMeters: rangeSpan, longitudinalMeters: rangeSpan) mapView.region = region } */ override func viewDidLoad() { super.viewDidLoad() let initialLocation = CLLocation(latitude: 50.720191, longitude: -1.879161) //Bmouth Town Center will be the centre // updateMapRegion(rangeSpan: 800) mapView.centerToLocation(initialLocation) let asdaLoc = CLLocation(latitude: 50.726586, longitude: -1.865241) let region = MKCoordinateRegion( center: asdaLoc.coordinate, latitudinalMeters: 50000, longitudinalMeters: 60000) mapView.setCameraBoundary( MKMapView.CameraBoundary(coordinateRegion: region), animated: true) let zoomRange = MKMapView.CameraZoomRange(maxCenterCoordinateDistance: 200000) mapView.setCameraZoomRange(zoomRange, animated: true) mapView.delegate = self /* mapView.register(shopView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier) loadInitialData() mapView.addAnnotation(datas) */ let asDa = ShopsL( title: "Asda Bournemouth", category: "Supermarket", address: "Bournemouth", coordinate: CLLocationCoordinate2D(latitude: 50.726586, longitude: -1.865241)) mapView.addAnnotation(asDa) } } private extension MKMapView { func centerToLocation( _ location: CLLocation, regionRadius: CLLocationDistance = 1000 ) { let coordinateRegion = MKCoordinateRegion( center: location.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius) setRegion(coordinateRegion, animated: true) } //OPEN UP MAPS START: func mapView( _ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl ) { guard let asDa = view.annotation as? ShopsL else { return } let launchOptions = [ MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving ] asDa.mapItem?.openInMaps(launchOptions: launchOptions) } //OPEN UP MAPS END } extension shopLocationViewController: MKMapViewDelegate { // 1 func mapView( _ mapView: MKMapView, viewFor annotation: MKAnnotation ) -> MKAnnotationView? { // 2 guard let annotation = annotation as? ShopsL else { return nil } // 3 let identifier = "asDa" var view: MKMarkerAnnotationView // 4 if let dequeuedView = mapView.dequeueReusableAnnotationView( withIdentifier: identifier) as? MKMarkerAnnotationView { dequeuedView.annotation = annotation view = dequeuedView } else { // 5 view = MKMarkerAnnotationView( annotation: annotation, reuseIdentifier: identifier) view.canShowCallout = true view.calloutOffset = CGPoint(x: -5, y: 5) view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } return view } }
// // RmdProfitCell.swift // EEPCShop // // Created by Mac Pro on 2019/5/1. // Copyright © 2019年 CHENNIAN. All rights reserved. // import UIKit class RmdProfitCell: SNBaseTableViewCell { var model:RmdProfitModel?{ didSet{ guard let cellModel = model else { return } num.text = "+ \(cellModel.num)" time.text = cellModel.add_time } } let num = UILabel().then{ $0.text = "+100" $0.textColor = Color(0x262626) $0.font = Font(32) } let time = UILabel().then{ $0.text = "2019-04-27" $0.textColor = Color(0xa9aebe) $0.font = Font(32) } override func setupView() { self.contentView.addSubviews(views: [self.num,self.time]) num.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.left.equalToSuperview().snOffset(65) } time.snp.makeConstraints { (make) in make.right.equalToSuperview().snOffset(-30) make.centerY.equalToSuperview() } } }
// // AEBaseView.swift // AESwiftWorking_Example // // Created by Adam on 2021/3/30. // Copyright © 2021 CocoaPods. All rights reserved. // import UIKit class AEBaseView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.configEvent() self.configUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { print("\(self) deinit") } } extension AEBaseView: ICBaseProtocol { @objc func configUI() { } @objc func configEvent() { } } extension AEBaseView { /// 设置headerview自适应 override func didMoveToSuperview() { super.didMoveToSuperview() if superview != nil { snp.remakeConstraints { (make) in make.width.equalTo(superview!) make.edges.equalTo(superview!) } layoutIfNeeded() } } } protocol ICBaseProtocol { func configUI() func configEvent() }
// // Constants.swift // ShoppingCart // // Created by toq33r on 09/11/2020. // Copyright © 2020 Testing. All rights reserved. // import UIKit class Constants: NSObject { static var baseUrl = "https://www.fakestoreapi.com/products" static let SCREENWIDTH = UIScreen.main.bounds.width static let SCREENHEIGHT = UIScreen.main.bounds.height }
// // ZPseudoView.swift // Seriously // // Created by Jonathan Sand on 10/23/21. // Copyright © 2021 Zones. All rights reserved. // import Foundation #if os(OSX) import Cocoa #elseif os(iOS) import UIKit #endif enum ZDrawPhase: String { case pLines = "l" case pHighlights = "h" case pDots = "d" } let gAllDrawPhases: [ZDrawPhase] = [.pHighlights, .pLines, .pDots] // draw dots last so they can "cover" the ends of lines class ZPseudoView: NSObject { var isHovering = false var identifier = NSUserInterfaceItemIdentifier("") var subpseudoviews = [ZPseudoView] () var absoluteFrame = CGRect.zero var absoluteHitRect = CGRect.zero var bounds = CGRect.zero var frame = CGRect.zero var drawnSize = CGSize.zero { didSet { bounds = CGRect(origin: .zero, size: drawnSize) } } var toolTip : String? { didSet { updateToolTipTag() } } var absoluteCenter : CGPoint { return absoluteFrame.center } var isLinearMode : Bool { return mode == .linearMode } var isCircularMode : Bool { return mode == .circularMode } var isBigMap : Bool { return controller?.isBigMap ?? true } var gapDistance : CGFloat { return (controller?.fontSize ?? kDefaultFontSize) * 0.6 } var dotPlusGap : CGFloat { return (controller?.dotWidth ?? .zero) + gapDistance } var mode : ZMapLayoutMode { return controller?.mapLayoutMode ?? .linearMode } var controller : ZMapController? { return nil } var superpseudoview : ZPseudoView? var toolTipTag : ZToolTipTag? var absoluteView : ZView? var drawnView : ZView? override var description: String { return toolTip ?? super.description } func draw(_ phase: ZDrawPhase) {} // overridden in all subclasses func setFrameSize(_ newSize: NSSize) { frame.size = newSize } func setupDrawnView() { drawnView = absoluteView } func debug(_ rect: CGRect, _ message: String = kEmpty) {} init(view: ZView?) { super.init() absoluteView = view setupDrawnView() } func updateToolTipTag() { if let t = toolTipTag { absoluteView?.removeToolTip(t) } toolTipTag = (toolTip == nil) ? nil : absoluteView?.addToolTip(absoluteFrame, owner: self, userData: nil) } func convertPoint(_ point: NSPoint, toRootPseudoView view: ZPseudoView?) -> NSPoint { if let s = superpseudoview, s != self, view != self { if s == view, controller?.isExemplar ?? false { return point } let p = point + s.frame.origin return s.convertPoint(p, toRootPseudoView: view) // recurse } return point } func convertRect(_ rect: NSRect, toRootPseudoView pseudoView: ZPseudoView?) -> NSRect { let o = convertPoint(rect.origin, toRootPseudoView: pseudoView) return CGRect(origin: o, size: rect.size) } func relayoutAbsoluteFrame(relativeTo controller: ZMapController?) { if let map = controller?.mapPseudoView { absoluteFrame = convertRect(frame, toRootPseudoView: map) // debug(absoluteFrame, "ABS FRAME") } } func addSubpseudoview(_ sub: ZPseudoView?) { if let s = sub { subpseudoviews.append(s) s.superpseudoview = self } } func removeAllSubpseudoviews() { var index = subpseudoviews.count while index > 0 { index -= 1 subpseudoviews.remove(at: index) } } func removeFromSuperpseudoview() { if var siblings = superpseudoview?.subpseudoviews, let index = siblings.firstIndex(of: self) { siblings.remove(at: index) superpseudoview?.subpseudoviews = siblings } } }
// // ViewController.swift // FlipViewDemo // // Created by Eiji Kushida on 2018/01/06. // Copyright © 2018年 Eiji Kushida. All rights reserved. // import UIKit final class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let flipView = FlipView(frame: CGRect(x: 100, y: 100, width: 100, height: 100)) self.view.addSubview(flipView) } }
// // PostDetailTableViewCell.swift // CoupgonCodingChallenge // // Created by Mubarak Sadoon on 2017-05-01. // Copyright © 2017 Coupgon. All rights reserved. // import UIKit class PostDetailTableViewCell: UITableViewCell { @IBOutlet weak var bodyText: UILabel! @IBOutlet weak var title: UILabel! @IBOutlet weak var postImageView: UIImageView! @IBOutlet weak var author: UILabel! @IBOutlet weak var like_button:UIButton! weak var delegate:FavouritesDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code like_button.setImage(UIImage(named:"unliked"), for: UIControlState.normal) like_button.setImage(UIImage(named:"liked"), for: UIControlState.selected) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func favPressed(_ sender: UIButton) { like_button.isSelected = !like_button.isSelected if like_button.isSelected { self.delegate?.addToFavourites() } else { self.delegate?.removeFromFavourites() } } }
// // Receta_Ingrediente.swift // recetas // // Created by Eugenia Perez Velasco on 26/4/15. // Copyright (c) 2015 Roberto Dehesa. All rights reserved. // import Foundation import CoreData class Receta_Ingrediente: NSManagedObject { @NSManaged var articulo_id: NSNumber @NSManaged var cantidad: String @NSManaged var cesta_id: NSNumber @NSManaged var idreceta_ingrediente: NSNumber @NSManaged var orden: NSNumber @NSManaged var receta_id: NSNumber @NSManaged var newRelationship: Receta @NSManaged var newRelationship1: Articulo @NSManaged var newRelationship2: Cesta }
// // Page2ViewController.swift // Lowes Presentation // // Created by Jasmine Reyes on 7/18/20. // Copyright © 2020 Josh Jaslow. All rights reserved. // import UIKit import SwiftUI class JasminePage2ViewController: UIViewController, Storyboarded { @IBOutlet weak var label: UITextView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 0.89, green: 0.87, blue: 0.85, alpha: 1.00) updateUI() } @objc func updateUI() { let bullet = "★ " var strings = [String]() strings.append("Add to Cart Button UI") strings.append("Customize Button UI") strings.append("UI Testing") strings.append("Data Analytics for Collection user interaction") strings.append("Unit Testing") strings = strings.map { return bullet + $0 } var attributes = [NSAttributedString.Key: Any]() attributes[.font] = UIFont.preferredFont(forTextStyle: .body) attributes[.foregroundColor] = UIColor.darkGray let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.headIndent = (bullet as NSString).size(withAttributes: attributes).width attributes[.paragraphStyle] = paragraphStyle let string = strings.joined(separator: "\n\n") label.attributedText = NSAttributedString(string: string, attributes: attributes) } }
// // CalendarCell.swift // BookingVP // // Created by HoangVanDuc on 11/28/19. // Copyright © 2019 HoangVanDuc. All rights reserved. // import UIKit import JTAppleCalendar class CalendarCell: JTAppleCell { @IBOutlet weak var viewSelect: UIView! @IBOutlet weak var lbDay: UILabel! @IBOutlet weak var background: UIView! @IBOutlet weak var ivSelect: UIImageView! override func awakeFromNib() { super.awakeFromNib() self.viewSelect.layer.cornerRadius = self.viewSelect.frame.size.width/2 self.lbDay.layer.cornerRadius = self.lbDay.frame.size.width/2 self.background.layer.cornerRadius = self.background.frame.size.width/2 } }
// // Constants.swift // ClubApp // // Created by intellye labs on 11/07/17. // Copyright © 2017 intellye labs. All rights reserved. // import Foundation struct Constants { static let BASEURL = "http://intellyze.hol.es/ClubApp/api/v1/" }
// // AppDelegate.swift // GitRx // // Created by Михаил Нечаев on 21.12.2019. // Copyright © 2019 Михаил Нечаев. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { }
import SwiftUI import UIKit struct PagedViewController<Element: Identifiable, Content: View>: UIViewControllerRepresentable { let transitionStyle: UIPageViewController.TransitionStyle let navigationOrientation: UIPageViewController.NavigationOrientation let options: [UIPageViewController.OptionsKey: Any]? let objects: [Element] let config: (Element) -> Content func makeUIViewController(context: UIViewControllerRepresentableContext<PagedViewController>) -> UIPageViewController { let vc = UIPageViewController(transitionStyle: transitionStyle, navigationOrientation: navigationOrientation, options: options) vc.dataSource = context.coordinator return vc } func updateUIViewController(_ uiViewController: UIPageViewController, context: UIViewControllerRepresentableContext<PagedViewController>) { uiViewController.setViewControllers([context.coordinator.firstViewController()], direction: .forward, animated: false, completion: nil) } func makeCoordinator() -> Coordinator<Element, Content> { return Coordinator(objects: objects, config: config) } final class Coordinator<Element, Content: View>: NSObject, UIPageViewControllerDataSource where Element: Identifiable { private let objects: [Element] private let config: (Element) -> Content init(objects: [Element], config: @escaping (Element) -> Content) { assert(!objects.isEmpty, "Objects need to have at least one Element") self.objects = objects self.config = config } func firstViewController() -> UIViewController { return ContentViewController(element: objects[0], rootView: config(objects[0])) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let contentVC = viewController as? ContentViewController<Element, Content>, let index = objects.firstIndex(of: contentVC.element), index > 0 else { return nil } return ContentViewController(element: objects[index - 1], rootView: config(objects[index - 1])) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let contentVC = viewController as? ContentViewController<Element, Content>, let index = objects.firstIndex(of: contentVC.element), index < objects.count - 1 else { return nil } return ContentViewController(element: objects[index + 1], rootView: config(objects[index + 1])) } } private final class ContentViewController<Element: Identifiable, Content: View>: UIHostingController<Content> { let element: Element init(element: Element, rootView: Content) { self.element = element super.init(rootView: rootView) } required init?(coder aDecoder: NSCoder) { fatalError() } } }
// // ContentView.swift // multiplatform-template // // Created by Luca Spinazzola on 7/12/19. // Copyright © 2019 lucaspinazzola. All rights reserved. // import SwiftUI import app import URLImage import Grid struct ContentView : View { @ObservedObject private var vm = RickAndMortyVmObserver() var body: some View { ScrollView { Grid(vm.imgs, id: \.self) { img in URLImage(URL.init(string: img.url)!, placeholder: { ProgressView($0) { progress in ZStack { if progress > 0.0 { CircleProgressView(progress).stroke(lineWidth: 8.0) } else { CircleActivityView().stroke(lineWidth: 50.0) } } } .frame(width: 50.0, height: 50.0) }, content: { $0.image .resizable() .aspectRatio(contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 5)) .padding(.leading, 5.0) .padding(.trailing, 5.0) .shadow(radius: 2.0) }) } }.gridStyle( ModularGridStyle(columns: 2, rows: .fixed(200)) ) } } #if DEBUG struct ContentView_Previews : PreviewProvider { static var previews: some View { ContentView() } } #endif
// // NotificationView.swift // Fizza // // Created by Sai Raghu Varma Kallepalli on 7/9/20. // import SwiftUI struct NotificationView: View { @State var showBanner: Bool = false var body: some View { VStack { NotificationBanner(showBanner: $showBanner) Spacer() Button("Place order") { self.showBanner.toggle() } Spacer() } } } struct NotificationView_Previews: PreviewProvider { static var previews: some View { NotificationView() } }
// // DexSellBuyViewController.swift // WavesWallet-iOS // // Created by Pavel Gubin on 9/8/18. // Copyright © 2018 Waves Platform. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxFeedback import WavesSDKExtensions import WavesSDK import Extensions import DomainLayer private enum Constants { static let percent50 = 50 static let percent10 = 10 static let percent5 = 5 static let minusTopOffsetForIPhone5: CGFloat = 13 } final class DexCreateOrderViewController: UIViewController { var input: DexCreateOrder.DTO.Input! { didSet { order = DexCreateOrder.DTO.Order(amountAsset: input.amountAsset, priceAsset: input.priceAsset, type: input.type, amount: Money(0, input.amountAsset.decimals), price: input.price ?? Money(0, input.priceAsset.decimals), total: Money(0, input.priceAsset.decimals), expiration: DexCreateOrder.DTO.Expiration.expiration29d, fee: 0, feeAssetId: WavesSDKConstants.wavesAssetId) feeAssets = [DomainLayer.DTO.Dex.Asset(id: WavesSDKConstants.wavesAssetId, name: WavesSDKConstants.wavesAssetId, shortName: WavesSDKConstants.wavesAssetId, decimals: WavesSDKConstants.WavesDecimals)] } } @IBOutlet private weak var segmentedControl: DexCreateOrderSegmentedControl! @IBOutlet private weak var inputAmount: DexCreateOrderInputView! @IBOutlet private weak var inputPrice: DexCreateOrderInputView! @IBOutlet private weak var inputTotal: DexCreateOrderInputView! @IBOutlet private weak var labelFeeLocalization: UILabel! @IBOutlet private weak var labelExpiration: UILabel! @IBOutlet private weak var labelExpirationDays: UILabel! @IBOutlet private weak var buttonSellBuy: HighlightedButton! @IBOutlet private weak var segmentedTopOffset: NSLayoutConstraint! @IBOutlet private weak var inputAmountTopOffset: NSLayoutConstraint! @IBOutlet private weak var inputPriceTopOffset: NSLayoutConstraint! @IBOutlet private weak var inputTotalTopOffset: NSLayoutConstraint! @IBOutlet private weak var viewFeeTopOffset: NSLayoutConstraint! @IBOutlet private weak var buttonSellBuyBottomOffset: NSLayoutConstraint! @IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView! @IBOutlet private weak var viewErrorFee: UIView! @IBOutlet private weak var labelErrorFee: UILabel! @IBOutlet private weak var labelFee: UILabel! @IBOutlet private weak var activityIndicatorViewFee: UIActivityIndicatorView! @IBOutlet private weak var iconArrowCustomFee: UIImageView! private var order: DexCreateOrder.DTO.Order! private var isCreatingOrderState: Bool = false private var isDisabledBuySellButton: Bool = false private var errorSnackKey: String? private var feeAssets: [DomainLayer.DTO.Dex.Asset] = [] var presenter: DexCreateOrderPresenterProtocol! weak var moduleOutput: DexCreateOrderModuleOutput? private let sendEvent: PublishRelay<DexCreateOrder.Event> = PublishRelay<DexCreateOrder.Event>() override func viewDidLoad() { super.viewDidLoad() viewErrorFee.isHidden = true setupFeedBack() setupData() setupLocalization() setupButtonSellBuy() setupUIForIPhone5IfNeed() labelFee.isHidden = true iconArrowCustomFee.isHidden = true } } //MARK: - UI State private extension DexCreateOrderViewController { func showFee(fee: Money) { activityIndicatorViewFee.stopAnimating() labelFee.isHidden = false let feeAssetName = feeAssets.first(where: {$0.id == order.feeAssetId})?.shortName ?? "" labelFee.text = fee.displayText + " " + feeAssetName iconArrowCustomFee.isHidden = feeAssets.count <= 1 } func setupCreatingOrderState() { isCreatingOrderState = true setupButtonSellBuy() activityIndicatorView.isHidden = false activityIndicatorView.startAnimating() view.isUserInteractionEnabled = false } func setupDefaultState() { isCreatingOrderState = false setupButtonSellBuy() activityIndicatorView.stopAnimating() view.isUserInteractionEnabled = true } } //MARK: - FeedBack private extension DexCreateOrderViewController { func setupFeedBack() { let feedback = bind(self) { owner, state -> Bindings<DexCreateOrder.Event> in return Bindings(subscriptions: owner.subscriptions(state: state), events: owner.events()) } presenter.system(feedbacks: [feedback], feeAssetId: order.feeAssetId) } func events() -> [Signal<DexCreateOrder.Event>] { return [sendEvent.asSignal()] } func subscriptions(state: Driver<DexCreateOrder.State>) -> [Disposable] { let subscriptionSections = state .drive(onNext: { [weak self] state in guard let self = self else { return } self.updateState(state) }) return [subscriptionSections] } func updateState(_ state: DexCreateOrder.State) { self.isDisabledBuySellButton = state.isDisabledSellBuyButton self.setupFeeError(error: state.displayFeeErrorState) switch state.action { case .none: return default: break } switch state.action { case .showCreatingOrderState: self.setupCreatingOrderState() case .orderDidFailCreate(let error): self.showNetworkErrorSnack(error: error) self.setupDefaultState() case .orderDidCreate(let output): moduleOutput?.dexCreateOrderDidCreate(output: output) case .orderNotValid(let error): let callback: ((_ isSuccess: Bool) -> Void) = { [weak self] isSuccess in if isSuccess { self?.sendEvent.accept(.sendOrder) } else { self?.sendEvent.accept(.cancelCreateOrder) } } switch error { case .invalid: break case .priceHigherMarket: moduleOutput?.dexCreateOrderWarningForPrice(isPriceHigherMarket: true, callback: callback) case .priceLowerMarket: moduleOutput?.dexCreateOrderWarningForPrice(isPriceHigherMarket: false, callback: callback) } case .didGetFee(let feeSettings): self.feeAssets = feeSettings.feeAssets.map{ $0.asset } self.showFee(fee: feeSettings.fee) self.order.fee = feeSettings.fee.amount self.updateInputDataFields() self.sendEvent.accept(.updateInputOrder(self.order)) self.setupValidationErrors() self.setupButtonSellBuy() self.setupInputAmountData() self.setupInputTotalData() case .showDeffaultOrderState: setupDefaultState() case .none: break } } } // MARK: - Validation private extension DexCreateOrderViewController { var isValidWavesFee: Bool { if input.availableWavesBalance.amount >= order.fee { return true } if order.amountAsset.id == WavesSDKConstants.wavesAssetId && order.type == .buy { if order.amount.isZero { return isValidPriceAssetBalance } return order.amount.amount > order.fee } else if order.priceAsset.id == WavesSDKConstants.wavesAssetId && order.type == .sell { if order.total.isZero { return isValidAmountAssetBalance } return order.total.amount > order.fee } return false } var isValidOrder: Bool { return !order.amount.isZero && !order.price.isZero && !order.total.isZero && isValidAmountAssetBalance && isValidPriceAssetBalance && !isCreatingOrderState && isValidWavesFee && order.fee > 0 && isDisabledBuySellButton == false } var availableAmountAssetBalance: Money { if order.amountAsset.id == WavesSDKConstants.wavesAssetId { let amount = input.availableAmountAssetBalance.amount - Int64(order.fee) return Money(amount < 0 ? 0 : amount, input.availableAmountAssetBalance.decimals) } return input.availableAmountAssetBalance } var availablePriceAssetBalance: Money { if order.priceAsset.id == WavesSDKConstants.wavesAssetId { let amount = input.availablePriceAssetBalance.amount - Int64(order.fee) return Money(amount < 0 ? 0 : amount, input.availablePriceAssetBalance.decimals) } return input.availablePriceAssetBalance } var isValidAmountAssetBalance: Bool { if order.type == .sell { return order.amount.decimalValue <= availableAmountAssetBalance.decimalValue } return true } var isValidPriceAssetBalance: Bool { if order.type == .buy { return order.total.decimalValue <= availablePriceAssetBalance.decimalValue } return true } } //MARK: - Actions private extension DexCreateOrderViewController { @IBAction func customFeeTapped(_ sender: Any) { guard feeAssets.count > 1 else { return } let vc = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) for asset in feeAssets { let action = UIAlertAction(title: asset.shortName, style: .default) { (action) in if self.order.feeAssetId != asset.id { self.order.feeAssetId = asset.id self.sendEvent.accept(.feeAssetNeedUpdate(asset.id)) self.feeAssets = [] self.order.fee = 0 self.activityIndicatorViewFee.isHidden = false self.activityIndicatorViewFee.startAnimating() self.labelFee.isHidden = true self.iconArrowCustomFee.isHidden = true self.setupButtonSellBuy() } } vc.addAction(action) } let cancel = UIAlertAction(title: Localizable.Waves.Dexcreateorder.Button.cancel, style: .cancel, handler: nil) vc.addAction(cancel) present(vc, animated: true, completion: nil) } func dismissController() { if let parent = self.parent as? PopupViewController { parent.dismissPopup() } } @IBAction func buttonSellBuyTapped(_ sender: UIButton) { sendEvent.accept(.createOrder) } @IBAction func changeExpiration(_ sender: UIButton) { let values = [DexCreateOrder.DTO.Expiration.expiration5m, DexCreateOrder.DTO.Expiration.expiration30m, DexCreateOrder.DTO.Expiration.expiration1h, DexCreateOrder.DTO.Expiration.expiration1d, DexCreateOrder.DTO.Expiration.expiration1w, DexCreateOrder.DTO.Expiration.expiration29d] let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let cancel = UIAlertAction(title: Localizable.Waves.Dexcreateorder.Button.cancel, style: .cancel, handler: nil) controller.addAction(cancel) for value in values { let action = UIAlertAction(title: value.text, style: .default) { (action) in if self.order.expiration != value { self.order.expiration = value self.setupLabelExpiration() self.sendEvent.accept(.updateInputOrder(self.order)) } } controller.addAction(action) } present(controller, animated: true, completion: nil) } func setupLabelExpiration() { labelExpirationDays.text = order.expiration.text } } //MARK: - DexCreateOrderSegmentedControlDelegate extension DexCreateOrderViewController: DexCreateOrderSegmentedControlDelegate { func dexCreateOrderDidChangeType(_ type: DomainLayer.DTO.Dex.OrderType) { order.type = type setupButtonSellBuy() setupValidationErrors() setupInputAmountData() setupInputTotalData() sendEvent.accept(.updateInputOrder(order)) } } //MARK: - DexCreateOrderInputViewDelegate extension DexCreateOrderViewController: DexCreateOrderInputViewDelegate { func dexCreateOrder(inputView: DexCreateOrderInputView, didChangeValue value: Money) { if inputView == inputAmount { order.amount = value if !order.price.isZero && !order.amount.isZero { let total = order.price.decimalValue * order.amount.decimalValue order.total = Money(value: total, order.total.decimals) inputTotal.setupValue(order.total) } } else if inputView == inputPrice { order.price = value if !order.price.isZero && !order.amount.isZero { let total = order.price.decimalValue * order.amount.decimalValue order.total = Money(value: total, order.total.decimals) inputTotal.setupValue(order.total) } } else if inputView == inputTotal { order.total = value if !order.total.isZero && !order.price.isZero { let amount = order.total.decimalValue / order.price.decimalValue order.amount = Money(value: amount, order.amount.decimals) inputAmount.setupValue(order.amount) } } setupButtonSellBuy() setupValidationErrors() sendEvent.accept(.updateInputOrder(order)) } } //MARK: - Data private extension DexCreateOrderViewController { func updateInputDataFields() { if let price = input.price { order.price = price inputPrice.setupValue(price) if let sum = input.sum { if order.type == .buy { if sum.decimalValue > availablePriceAssetBalance.decimalValue { inputTotal.updateAmount(availablePriceAssetBalance) } else { inputTotal.updateAmount(sum) } } else { let amount = sum.decimalValue / price.decimalValue if amount > availableAmountAssetBalance.decimalValue { inputAmount.updateAmount(availableAmountAssetBalance) } else { inputTotal.updateAmount(sum) } } } setupValidationErrors() } } func setupData() { segmentedControl.type = input.type segmentedControl.delegate = self inputAmount.delegate = self inputAmount.maximumFractionDigits = input.amountAsset.decimals inputPrice.delegate = self inputPrice.maximumFractionDigits = input.priceAsset.decimals inputPrice.isShowInputWhenFilled = true inputTotal.delegate = self inputTotal.maximumFractionDigits = input.priceAsset.decimals setupInputAmountData() setupInputTotalData() setupInputPriceData() inputAmount.input = { [weak self] in guard let self = self else { return [] } return self.amountValues } inputPrice.input = { [weak self] in guard let self = self else { return [] } return self.priceValues } inputTotal.input = { [weak self] in guard let self = self else { return []} return self.totalValues } updateInputDataFields() } func setupInputPriceData() { var fields: [String] = [] if input.bid != nil { fields.append(Localizable.Waves.Dexcreateorder.Button.bid) } if input.ask != nil { fields.append(Localizable.Waves.Dexcreateorder.Button.ask) } if input.last != nil { fields.append(Localizable.Waves.Dexcreateorder.Button.last) } inputPrice.update(with: fields) } func setupInputTotalData() { var fields: [String] = [] if order.type == .buy && !availablePriceAssetBalance.isZero { fields.append(Localizable.Waves.Dexcreateorder.Button.useTotalBalanace) fields.append(String(Constants.percent50) + "%") fields.append(String(Constants.percent10) + "%") fields.append(String(Constants.percent5) + "%") } inputTotal.update(with: fields) } func setupInputAmountData() { var fields: [String] = [] if order.type == .sell && !availableAmountAssetBalance.isZero { fields.append(Localizable.Waves.Dexcreateorder.Button.useTotalBalanace) fields.append(String(Constants.percent50) + "%") fields.append(String(Constants.percent10) + "%") fields.append(String(Constants.percent5) + "%") } inputAmount.update(with: fields) } var amountValues: [Money] { var values: [Money] = [] if order.type == .sell && !availableAmountAssetBalance.isZero { let totalAmount: Int64 = availableAmountAssetBalance.amount let decimals = availableAmountAssetBalance.decimals let totalAmountMoney = Money(totalAmount, decimals) let n5 = Decimal(totalAmountMoney.amount) * (Decimal(Constants.percent5) / 100.0) let n10 = Decimal(totalAmountMoney.amount) * (Decimal(Constants.percent10) / 100.0) let n50 = Decimal(totalAmountMoney.amount) * (Decimal(Constants.percent50) / 100.0) let valuePercent50 = Money(n50.int64Value, decimals) let valuePercent10 = Money(n10.int64Value, decimals) let valuePercent5 = Money(n5.int64Value, decimals) values.append(totalAmountMoney) values.append(valuePercent50) values.append(valuePercent10) values.append(valuePercent5) } return values } var priceValues: [Money] { var values: [Money] = [] if let bid = input.bid { values.append(bid) } if let ask = input.ask { values.append(ask) } if let last = input.last { values.append(last) } return values } var totalValues: [Money] { var values: [Money] = [] if order.type == .buy && !availablePriceAssetBalance.isZero { let decimals = availablePriceAssetBalance.decimals let totalAmount: Int64 = availablePriceAssetBalance.amount let totalAmountMoney = Money(totalAmount, decimals) let n5 = Decimal(totalAmountMoney.amount) * (Decimal(Constants.percent5) / 100.0) let n10 = Decimal(totalAmountMoney.amount) * (Decimal(Constants.percent10) / 100.0) let n50 = Decimal(totalAmountMoney.amount) * (Decimal(Constants.percent50) / 100.0) let valuePercent50 = Money(n50.int64Value, decimals) let valuePercent10 = Money(n10.int64Value, decimals) let valuePercent5 = Money(n5.int64Value, decimals) values.append(totalAmountMoney) values.append(valuePercent50) values.append(valuePercent10) values.append(valuePercent5) } return values } } //MARK: - UI private extension DexCreateOrderViewController { func setupLocalization() { setupLabelExpiration() labelFeeLocalization.text = Localizable.Waves.Dexcreateorder.Label.fee labelExpiration.text = Localizable.Waves.Dexcreateorder.Label.expiration inputAmount.setupTitle(title: Localizable.Waves.Dexcreateorder.Label.amountIn + " " + input.amountAsset.shortName) inputPrice.setupTitle(title: Localizable.Waves.Dexcreateorder.Label.limitPriceIn + " " + input.priceAsset.shortName) inputTotal.setupTitle(title: Localizable.Waves.Dexcreateorder.Label.totalIn + " " + input.priceAsset.shortName) labelErrorFee.text = Localizable.Waves.Dexcreateorder.Label.Error.notFundsFee } func setupButtonSellBuy() { buttonSellBuy.isUserInteractionEnabled = isValidOrder if order.type == .sell { buttonSellBuy.setTitle(Localizable.Waves.Dexcreateorder.Button.sell + " " + input.amountAsset.shortName, for: .normal) buttonSellBuy.backgroundColor = isValidOrder ? .error400 : .error100 buttonSellBuy.highlightedBackground = .error200 } else { buttonSellBuy.setTitle(Localizable.Waves.Dexcreateorder.Button.buy + " " + input.amountAsset.shortName, for: .normal) buttonSellBuy.backgroundColor = isValidOrder ? .submit400 : .submit200 buttonSellBuy.highlightedBackground = .submit300 } } func setupValidationErrors() { if order.type == .sell { inputAmount.showErrorMessage(message: Localizable.Waves.Dexcreateorder.Label.notEnough + " " + input.amountAsset.shortName, isShow: !isValidAmountAssetBalance) var message = "" if order.total.isBigAmount { message = Localizable.Waves.Dexcreateorder.Label.bigValue } else if order.total.isSmallAmount { message = Localizable.Waves.Dexcreateorder.Label.smallValue } inputTotal.showErrorMessage(message: message, isShow: order.total.isBigAmount || order.total.isSmallAmount) } else { var amountError = "" if order.total.isBigAmount { amountError = Localizable.Waves.Dexcreateorder.Label.bigValue } else if order.total.isSmallAmount { amountError = Localizable.Waves.Dexcreateorder.Label.smallValue } inputAmount.showErrorMessage(message: amountError, isShow: order.amount.isBigAmount || order.amount.isSmallAmount) var totalError = "" if order.total.isBigAmount { totalError = Localizable.Waves.Dexcreateorder.Label.bigValue } else if order.total.isSmallAmount { totalError = Localizable.Waves.Dexcreateorder.Label.smallValue } else if !isValidPriceAssetBalance { totalError = Localizable.Waves.Dexcreateorder.Label.notEnough + " " + input.priceAsset.shortName } inputTotal.showErrorMessage(message: totalError, isShow: !isValidPriceAssetBalance || order.total.isBigAmount || order.total.isSmallAmount) } viewErrorFee.isHidden = isValidWavesFee } func setupFeeError(error: DisplayErrorState) { switch error { case .error(let error): switch error { case .globalError(let isInternetNotWorking): if isInternetNotWorking { errorSnackKey = showWithoutInternetSnack { [weak self] in guard let self = self else { return } self.sendEvent.accept(.refreshFee) } } else { errorSnackKey = showErrorNotFoundSnack(didTap: { [weak self] in guard let self = self else { return } self.sendEvent.accept(.refreshFee) }) } case .internetNotWorking: errorSnackKey = showWithoutInternetSnack { [weak self] in guard let self = self else { return } self.sendEvent.accept(.refreshFee) } case .message(let text): errorSnackKey = showErrorSnack(title: text, didTap: { [weak self] in guard let self = self else { return } self.sendEvent.accept(.refreshFee) }) case .none, .scriptError: errorSnackKey = showErrorNotFoundSnack(didTap: { [weak self] in guard let self = self else { return } self.sendEvent.accept(.refreshFee) }) } case .none: if let errorSnackKey = errorSnackKey { hideSnack(key: errorSnackKey) } case .waiting: break } } } //MARK: - Setup UI for iPhone5 private extension DexCreateOrderViewController { func setupUIForIPhone5IfNeed() { if Platform.isIphone5 { segmentedTopOffset.constant = 0 inputAmountTopOffset.constant -= Constants.minusTopOffsetForIPhone5 inputPriceTopOffset.constant -= Constants.minusTopOffsetForIPhone5 inputTotalTopOffset.constant -= Constants.minusTopOffsetForIPhone5 viewFeeTopOffset.constant -= Constants.minusTopOffsetForIPhone5 buttonSellBuyBottomOffset.constant -= Constants.minusTopOffsetForIPhone5 } } }
// // Face.swift // ARWig // // Created by Esteban Arrúa on 12/18/18. // Copyright © 2018 Hattrick It. All rights reserved. // import Foundation import CoreGraphics import SceneKit class Face { let max2DDistance: CGFloat = 30.0 let max3DDistance: Float = 0.005 let maxSamples = 10 let outlierRatio = 0.7 let ratio: Float = 80.0 var faces2D: [Face2D] = [] var faces3D: [Face3D] = [] var active: Bool = true func addNewValue(face2D: Face2D, face3D: Face3D) -> Bool { if faces2D.isEmpty { faces2D.append(face2D) faces3D.append(face3D) return true } else { var minDistance = max2DDistance for face in faces2D { let distance = CGPoint.distance(from: face.btwEyes, to: face2D.btwEyes) if distance < minDistance { minDistance = distance } } if minDistance < max2DDistance { faces2D.append(face2D) faces3D.append(face3D) if (faces2D.count > maxSamples) { faces2D.removeFirst() faces3D.removeFirst() } return true } else { return false } } } func getPosition() -> SCNVector3 { var divisor = 0 var vector = SCNVector3Make(0, 0, 0) for (index, face) in faces3D.enumerated() { if isOutlier(index: index) { divisor += 1 vector += face.btwEyes } else { divisor += Int(ratio) vector += face.btwEyes * ratio } } vector = vector / Float(divisor) return vector } func getYaw() -> NSNumber? { var yaw : NSNumber? for (_, face) in faces2D.enumerated() { yaw = face.yaw } return yaw } func getFaceContour() -> [CGPoint] { var points: [CGPoint] = [] for (_, face) in faces2D.enumerated() { points = face.faceContourPoints! } return points } func getFaceSize() -> Float { var divisor = 0 var size: Float = 0 for (index, face) in faces3D.enumerated() { if isOutlier(index: index) { divisor += 1 size += face.getFaceSize() } else { divisor += Int(ratio) size += face.getFaceSize() * ratio } } return size / Float(divisor) } fileprivate func isOutlier(index: Int) -> Bool { var pointDiferents = 0 for face in faces3D { let distance = SCNVector3.distance(from: faces3D[index].btwEyes, to: face.btwEyes) if distance >= max3DDistance { pointDiferents += 1 } } return Float(pointDiferents) > Float(maxSamples) * Float(outlierRatio) } }
// // MovieSearchTableViewCell.swift // MyMovies // // Created by Paul Yi on 2/22/19. // Copyright © 2019 Lambda School. All rights reserved. // import UIKit protocol MovieSearchTableViewCellDelegate: class { func addMovieButtonAction(on cell: MovieSearchTableViewCell) } class MovieSearchTableViewCell: UITableViewCell { weak var delegate: MovieSearchTableViewCellDelegate? var movieRepresentation: MovieRepresentation? { didSet { updateViews() } } @IBOutlet weak var titleLabel: UILabel! @IBAction func addButtonAction(_ sender: Any) { delegate?.addMovieButtonAction(on: self) } func updateViews() { guard let movie = movieRepresentation else { return } titleLabel.text = movie.title } }
// // ViewController.swift // TheMovieDB // // Created by Jaime Laino on 1/24/17. // Copyright © 2017 Globant. All rights reserved. // import UIKit class ViewController: UIViewController { let movieFacade = WebServices() var moviesList = [Movie]() var list: List! var numberOfPage = 1 override func viewDidLoad() { super.viewDidLoad() switch UIDevice.current.userInterfaceIdiom { case .phone: self.list = TableMovieList() case .pad: self.list = CollectionMovieList() default: self.list = TableMovieList() } self.list.listDelegate = self self.view.addSubview((self.list as! UIView)) movieFacade.getMovies(numberOfPage: self.numberOfPage) { [weak self](movies) in self?.moviesList = movies self?.list.reloadData() } numberOfPage = numberOfPage + 1 } override func viewWillAppear(_ animated: Bool) { (self.list as! UIView).frame = self.view.bounds } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension ViewController: MoviesListDelegate{ func willDisplay(indexPath: IndexPath) { if indexPath.row == moviesList.count-1 { movieFacade.getMovies(numberOfPage: self.numberOfPage) { [weak self](movies) in self?.moviesList.append(contentsOf: movies) self?.list.reloadData() } numberOfPage = numberOfPage + 1 } } func numberOfItems() -> Int { return moviesList.count } func configureCell(cell: ListCell, atIndexPath: IndexPath) { let movie = moviesList[atIndexPath.row] cell.title?.text = movie.title let image_path = movie.imageLink if let imageURL = URL(string: image_path!){ cell.movieImage?.af_setImage(withURL: imageURL) print("CARECHIMBA") } } func didSelectRowAt(indexPath: IndexPath){ let selectedCell = indexPath.row let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let newViewController = storyBoard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController newViewController.movie = moviesList[selectedCell] self.navigationController?.pushViewController(newViewController, animated: true) } }
// // HallScene.swift // CagesFarm // // Created by Beatriz Carlos on 08/04/21. // import SpriteKit import GameplayKit //swiftlint:disable unused_optional_binding class HallScene: SKScene, DialogueBoxDelegate, ImageRetriever { var closeCallbackToMenu: (() -> Void)? private var dialogBox = DialogueBox() private var lastInteraction: LastInteraction? private lazy var background: SKSpriteNode = { let node = SKSpriteNode(imageNamed: "hall") node.zPosition = -1 return node }() private var tony : Characters = { let node = Characters(characterType: .tony) node.zPosition = +2 node.position = CGPoint(x: 250, y: -35) node.size = CGSize(width: 120, height: 120) return node }() lazy var doorOne: InteractableObjects = { let node = InteractableObjects(objectType: .doorOne) node.setScale(0.65) node.position = CGPoint(x: -360, y: 18) node.zPosition = +1 return node }() lazy var doorTwo: InteractableObjects = { let node = InteractableObjects(objectType: .doorTwo) node.setScale(0.65) node.position = CGPoint(x: -25, y: 18) node.zPosition = +1 return node }() lazy var doorThree: InteractableObjects = { let node = InteractableObjects(objectType: .doorThree) node.setScale(0.65) node.position = CGPoint(x: 320, y: 18) node.zPosition = +1 return node }() override func sceneDidLoad() { tony.isWalking = false setScene() } private func setScene() { self.scaleMode = .aspectFit addChild() dialogBox.delegate = self dialogBox.zPosition = +2 } private func addChild() { self.addChild(tony) self.addChild(background) self.addChild(doorOne) self.addChild(doorTwo) self.addChild(doorThree) } func touchDown(atPoint pos : CGPoint) { print(tony.isWalking) self.makeMCWalk(pos: pos) interactionObject(pos: pos) dialogBox.zPosition = +2 } func interactionObject(pos: CGPoint) { guard let objectInTouch = atPoint(pos) as? InteractableObjects else { if let _ = atPoint(pos) as? DialogueBox { tony.isWalking = false self.dialogBox.removeFromParent() } return } if objectInTouch.isCloseInteract { // MUDAR PRA TORNAR MAIS AUTOMATICO PRA TODOS OBJETOS if dialogBox.parent == nil { let actualAnswerID = objectInTouch.actualAnswer self.addChild(dialogBox) guard let answer = objectInTouch.answers else {return} self.dialogBox.nextText(answer: answer[actualAnswerID]) tony.isWalking = true lastInteraction = nil lastInteraction = LastInteraction(objectType: objectInTouch, currentAnswer: objectInTouch.actualAnswer) if objectInTouch.canProceedInteraction { objectInTouch.nextDialogue() } } if objectInTouch.objectType == .doorThree { let otherWait = SKAction.wait(forDuration: 2) let fadOut = SKAction.fadeOut(withDuration: 2) let sequence = SKAction.sequence([otherWait, fadOut]) self.run(sequence) { self.closeCallbackToMenu?() } } } } private func makeMCWalk(pos: CGPoint) { let itIsInventory = atPoint(pos) if !(itIsInventory is Inventory) && !(itIsInventory is SKShapeNode) { if !tony.isWalking && pos.x < tony.frame.minX { tony.xScale = -1 } else if !tony.isWalking && pos.x >= tony.frame.minX { tony.xScale = +1 } if !tony.isWalking { tony.walk(posx: pos.x,gameScene: self) } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchDown(atPoint: t.location(in: self)) } } func didFinishShowingText() {} override func update(_ currentTime: TimeInterval) { doorOne.microInteraction(player: tony) doorTwo.microInteraction(player: tony) doorThree.microInteraction(player: tony) } }
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /// A set of utility routines useful for all kinds of ANTLR trees. public class Trees { /* public class func getPS(t: Tree, _ ruleNames: Array<String>, _ fontName: String, _ fontSize: Int) -> String { let psgen: TreePostScriptGenerator = TreePostScriptGenerator(ruleNames, t, fontName, fontSize) return psgen.getPS() } public class func getPS(t: Tree, _ ruleNames: Array<String>) -> String { return getPS(t, ruleNames, "Helvetica", 11) } //TODO: write to file public class func writePS(t: Tree, _ ruleNames: Array<String>, _ fileName: String, _ fontName: String, _ fontSize: Int) throws { var ps: String = getPS(t, ruleNames, fontName, fontSize) var f: FileWriter = FileWriter(fileName) var bw: BufferedWriter = BufferedWriter(f) try { bw.write(ps) } defer { bw.close() } } public class func writePS(t: Tree, _ ruleNames: Array<String>, _ fileName: String) throws { writePS(t, ruleNames, fileName, "Helvetica", 11) } */ /// Print out a whole tree in LISP form. _#getNodeText_ is used on the /// node payloads to get the text for the nodes. Detect /// parse trees and extract data appropriately. /// public static func toStringTree(_ t: Tree) -> String { let rulsName: Array<String>? = nil return toStringTree(t, rulsName) } /// Print out a whole tree in LISP form. _#getNodeText_ is used on the /// node payloads to get the text for the nodes. Detect /// parse trees and extract data appropriately. /// public static func toStringTree(_ t: Tree, _ recog: Parser?) -> String { let ruleNamesList: [String]? = recog?.getRuleNames() return toStringTree(t, ruleNamesList) } /// Print out a whole tree in LISP form. _#getNodeText_ is used on the /// node payloads to get the text for the nodes. Detect /// parse trees and extract data appropriately. /// public static func toStringTree(_ t: Tree, _ ruleNames: Array<String>?) -> String { let s = Utils.escapeWhitespace(getNodeText(t, ruleNames), false) if t.getChildCount() == 0 { return s } var buf = "(\(s) " let length = t.getChildCount() for i in 0..<length { if i > 0 { buf += " " } buf += toStringTree(t.getChild(i)!, ruleNames) } buf += ")" return buf } public static func getNodeText(_ t: Tree, _ recog: Parser?) -> String { return getNodeText(t, recog?.getRuleNames()) } public static func getNodeText(_ t: Tree, _ ruleNames: Array<String>?) -> String { if let ruleNames = ruleNames { if let ruleNode = t as? RuleNode { let ruleIndex: Int = ruleNode.getRuleContext().getRuleIndex() let ruleName: String = ruleNames[ruleIndex] let altNumber = (t as! RuleContext).getAltNumber() if altNumber != ATN.INVALID_ALT_NUMBER { return "\(ruleName):\(altNumber)" } return ruleName } else { if let errorNode = t as? ErrorNode { return errorNode.description } else if let terminalNode = t as? TerminalNode { if let symbol = terminalNode.getSymbol() { let s: String = symbol.getText()! return s } } } } // no recog for rule names let payload: AnyObject = t.getPayload() if let token = payload as? Token { return token.getText()! } return "\(t.getPayload())" } /// Return ordered list of all children of this node public static func getChildren(_ t: Tree) -> Array<Tree> { var kids: Array<Tree> = Array<Tree>() let length = t.getChildCount() for i in 0..<length { kids.append(t.getChild(i)!) } return kids } /// Return a list of all ancestors of this node. The first node of /// list is the root and the last is the parent of this node. /// public static func getAncestors(_ t: Tree) -> Array<Tree> { var ancestors: Array<Tree> = Array<Tree>() if t.getParent() == nil { return ancestors //return Collections.emptyList(); } var tp = t.getParent() while let tpWrap = tp { ancestors.insert(t, at: 0) //ancestors.add(0, t); // insert at start tp = tpWrap.getParent() } return ancestors } public static func findAllTokenNodes(_ t: ParseTree, _ ttype: Int) -> Array<ParseTree> { return findAllNodes(t, ttype, true) } public static func findAllRuleNodes(_ t: ParseTree, _ ruleIndex: Int) -> Array<ParseTree> { return findAllNodes(t, ruleIndex, false) } public static func findAllNodes(_ t: ParseTree, _ index: Int, _ findTokens: Bool) -> Array<ParseTree> { var nodes: Array<ParseTree> = Array<ParseTree>() _findAllNodes(t, index, findTokens, &nodes) return nodes } public static func _findAllNodes(_ t: ParseTree, _ index: Int, _ findTokens: Bool, _ nodes: inout Array<ParseTree>) { // check this node (the root) first if let tnode = t as? TerminalNode , findTokens { if tnode.getSymbol()!.getType() == index { nodes.append(t) } } else { if let ctx = t as? ParserRuleContext , !findTokens { if ctx.getRuleIndex() == index { nodes.append(t) } } } // check children let length = t.getChildCount() for i in 0..<length { _findAllNodes(t.getChild(i) as! ParseTree, index, findTokens, &nodes) } } public static func descendants(_ t: ParseTree) -> Array<ParseTree> { var nodes: Array<ParseTree> = [t] let n: Int = t.getChildCount() for i in 0..<n { //nodes.addAll(descendants(t.getChild(i))); if let child = t.getChild(i) { nodes.concat(descendants(child as! ParseTree)) } } return nodes } /// Find smallest subtree of t enclosing range startTokenIndex..stopTokenIndex /// inclusively using postorder traversal. Recursive depth-first-search. /// /// - Since: 4.5.1 /// public static func getRootOfSubtreeEnclosingRegion(_ t: ParseTree, _ startTokenIndex: Int, _ stopTokenIndex: Int) -> ParserRuleContext? { let n: Int = t.getChildCount() for i in 0..<n { //TODO t.getChild(i) nil //Added by janyou guard let child = t.getChild(i) as? ParseTree else { return nil } if let r = getRootOfSubtreeEnclosingRegion(child, startTokenIndex, stopTokenIndex) { return r } } if let r = t as? ParserRuleContext { if startTokenIndex >= r.getStart()!.getTokenIndex() && // is range fully contained in t? stopTokenIndex <= r.getStop()!.getTokenIndex() { return r } } return nil } private init() { } }
// // UITextView+SWFBuilder.swift // TestSwift // // Created by wsy on 2018/1/10. // Copyright © 2018年 wangshengyuan. All rights reserved. // import Foundation import UIKit func TextView() -> UITextView { return UITextView() } func TextView(_ rect: CGRect) -> UITextView { return UITextView(frame: rect) } extension UITextView { func textViewborder(_ width: CGFloat, _ borderColor: UIColor) -> UITextView { self.layer.borderWidth = width self.layer.borderColor = borderColor.cgColor return self } func textViewIsEdit(_ editable: Bool) -> UITextView { self.isEditable = editable return self } func textViewIsSelect(_ isSelect: Bool) -> UITextView { self.isSelectable = isSelect return self } func textViewFont(_ font: UIFont) -> UITextView { self.font = font return self } func textViewTextColor(_ color: UIColor) -> UITextView { self.textColor = color return self } func textViewText(_ text: String?) -> UITextView { self.text = text return self } func textViewAlign(_ align: NSTextAlignment) -> UITextView { self.textAlignment = align return self } func textViewDetectorTypes(_ type: UIDataDetectorTypes) -> UITextView { self.dataDetectorTypes = type return self } func textViewTintColor(_ color: UIColor) -> UITextView { self.tintColor = color return self } func textViewDelegate(_ delegate: UITextViewDelegate?) -> UITextView { self.delegate = delegate return self } func textViewInputView(_ view: UIView?) -> UITextView { self.inputView = view return self } func textViewAccessoryView(_ view: UIView?) -> UITextView { self.inputAccessoryView = view return self } func textViewAttributeText(_ text: NSAttributedString) -> UITextView { self.attributedText = text return self } func textViewLinkType(_ link: [String : Any]) -> UITextView { self.linkTextAttributes = link return self } func textViewKeyBoardType(_ type: UIKeyboardType) -> UITextView { self.keyboardType = type return self } func textViewReturnKeyType(_ type: UIReturnKeyType) -> UITextView { self.returnKeyType = type return self } }
// // AppDelegate.swift // weather_forecast // // Created by Thinh Nguyen on 9/30/20. // Email: thinhnguyen12389@gmail.com // import UIKit import Swinject import IQKeyboardManagerSwift import SVProgressHUD import CoreLocation import ReSwift import Alamofire import TSwiftHelper // MARK: - Global Properties let mainAssemblerResolver = AppDelegate.assembler.resolver var APP_ID = "" var globalSettings: Settings? @main class AppDelegate: UIResponder, UIApplicationDelegate { private(set) static var assembler: Assembler = Assembler(AppAssembly.allAssemblies) var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { loadEnvironment() setupThirdPartyServices(launchOptions: launchOptions) launchStartPage() return true } } // MARK: - Private Functions extension AppDelegate { final private func loadEnvironment() { switch environment { case .development: APP_ID = "60c6fbeb4b93ac653c492ba806fc346d" case .production: APP_ID = "60c6fbeb4b93ac653c492ba806fc346d" } } // MARK: setupThirdPartyServices final private func setupThirdPartyServices(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) { // MARK: IQKeyboardManager IQKeyboardManager.shared.enable = true // MARK: SVProgressHUD SVProgressHUD.setMaxSupportedWindowLevel(.alert) SVProgressHUD.setDefaultMaskType(.clear) // MARK: Load all fonts FontHelper.loadAll() } // MARK: Launch Start Page Function final private func launchStartPage() { window = UIWindow() let splashVC = mainAssemblerResolver.resolve(SplashVC.self)! let navigationController = UINavigationController(rootViewController: splashVC) navigationController.setNavigationBarHidden(true, animated: false) window?.rootViewController = navigationController window?.makeKeyAndVisible() let navigationBarAppearace = UINavigationBar.appearance() navigationBarAppearace.tintColor = .black navigationBarAppearace.barTintColor = .white } }
// // DependancyControllers.swift // RxSwiftFactory // // Created by Jonathan French on 25/04/2019. // import UIKit public class AppDependencyContainer { let sharedAppViewModel: AppViewModel public init() { func makeAppViewModel() -> AppViewModel { return AppViewModel() } self.sharedAppViewModel = makeAppViewModel() } public func makeContainerViewController() -> ContainerViewController { let navigationControllerFactory = { return self.makeNavigationController(rootView: self.makeCenterViewController()) } let dependencyContainer = ContainerDependancyContainer(appDependencyContainer: self) return dependencyContainer.makeContainerViewController(viewModel: sharedAppViewModel, navigationController: navigationControllerFactory()) } public func makeCenterViewController() -> CenterViewController { let dependencyContainer = CenterDependencyContainer(appDependencyContainer: self) return dependencyContainer.makeCenterViewController() } public func makeNavigationController(rootView:NiblessViewController) -> RxSwiftFactoryNavigationController { print("makeNavController") let rootNavController = RxSwiftFactoryNavigationController(rootViewController:rootView) rootNavController.navigationBar.prefersLargeTitles = true return rootNavController } public func makeContainerViewModel() -> ContainerViewModel { return ContainerViewModel() } // public func makeCenterViewModel() -> CenterViewModel { // return CenterViewModel() // } // // public func makeSidePanelViewModel() -> SidePanelViewModel { // return SidePanelViewModel(sharedAppViewModel: sharedAppViewModel) // } } extension AppDependencyContainer: ContainerViewModelFactory {} public extension UIStoryboard { static func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: Bundle.main) } }
// // TimeConversion.swift // TemperatureConverter // // Created by Milap Jhumkhawala on 04/08/16. // Copyright © 2016 Milap Jhumkhawala. All rights reserved. // import UIKit import DropDown import SnapKit class TimeConversion: UIView { var slider = UISlider() var upperLabel = UILabel() var lowerLabel = UILabel() var dropDown1 = DropDown() var dropDown2 = DropDown() var button1 = UIButton() var button2 = UIButton() var button1Label = UILabel() var button2Label = UILabel() var r = Float(0.0) var arrow = "dropDownArrow.png" var dropArrow1 = UIImageView() var dropArrow2 = UIImageView() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup(){ addSubview(slider) addSubview(upperLabel) addSubview(lowerLabel) addSubview(button1) addSubview(button2) addSubview(button1Label) addSubview(button2Label) addSubview(dropArrow1) addSubview(dropArrow2) slider.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(0) make.centerY.equalTo(0) make.width.equalTo(250) make.height.equalTo(30) } slider.minimumValue = 0 slider.maximumValue = 100 slider.tintColor = UIColor.orangeColor() upperLabel.textAlignment = NSTextAlignment.Center upperLabel.text = "0.0" upperLabel.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(0) make.centerY.equalTo(-50) make.width.equalTo(50) make.height.equalTo(30) } lowerLabel.textAlignment = NSTextAlignment.Center lowerLabel.text = "0.0" lowerLabel.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(0) make.centerY.equalTo(50) make.width.equalTo(100) make.height.equalTo(30) } button1.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(0) make.centerY.equalTo(-90) make.width.equalTo(150) make.height.equalTo(30) } button1.layer.borderColor = UIColor.grayColor().CGColor button1.layer.borderWidth = 0.8 button1.layer.cornerRadius = 5 button2.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(0) make.centerY.equalTo(90) make.width.equalTo(150) make.height.equalTo(30) } button2.layer.borderColor = UIColor.grayColor().CGColor button2.layer.borderWidth = 0.8 button2.layer.cornerRadius = 5 dropArrow1.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(65) make.centerY.equalTo(-90) make.width.equalTo(10) make.height.equalTo(10) } dropArrow1.image = UIImage(named : arrow) dropArrow2.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(65) make.centerY.equalTo(90) make.width.equalTo(10) make.height.equalTo(10) } dropArrow2.image = UIImage(named : arrow) button1Label.textAlignment = NSTextAlignment.Center button1Label.font = UIFont.systemFontOfSize(15) button1Label.text = "Select Input" button1Label.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(0) make.centerY.equalTo(-90) make.width.equalTo(150) make.height.equalTo(30) } button2Label.textAlignment = NSTextAlignment.Center button2Label.font = UIFont.systemFontOfSize(15) button2Label.text = "Select Output" button2Label.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(0) make.centerY.equalTo(90) make.width.equalTo(150) make.height.equalTo(30) } dropDown1.anchorView = button1 dropDown2.anchorView = button2 dropDown1.dataSource = ["Years", "Month", "Days", "Hours", "Minutes", "Seconds", "Miliseconds", "Microseconds", "Nanoseconds"] dropDown2.dataSource = ["Years", "Month", "Days", "Hours", "Minutes", "Seconds", "Miliseconds", "Microseconds", "Nanoseconds"] button1.addTarget(self, action: #selector(TemperatureConversion.showList1), forControlEvents: UIControlEvents.TouchUpInside ) button2.addTarget(self, action: #selector(TemperatureConversion.showList2), forControlEvents: UIControlEvents.TouchUpInside) dropDown1.selectionAction = { [unowned self] (index: Int, item: String) in self.button1Label.text = item self.upperLabel.text = "0.0" self.lowerLabel.text = "0.0" self.slider.value = 0 } dropDown2.selectionAction = { [unowned self] (index: Int, item: String) in self.button2Label.text = item self.upperLabel.text = "0.0" self.lowerLabel.text = "0.0" self.slider.value = 0 } slider.addTarget(self, action: #selector(TemperatureConversion.numberValueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged ) } func showList1() { dropDown1.show() print("button clicked") } func showList2(){ dropDown2.show() print("button clicked") } }
// // Constants.swift // Nalssi // // Created by Farah Nedjadi on 27/06/2018. // Copyright © 2018 mti. All rights reserved. // import Foundation import Alamofire struct Constants { struct Url { static let ENTRY_API_URL = "http://api.openweathermap.org/data/2.5" static let WEATHER = "/weather" static let DAILY = "/forecast" static let UVI = "/uvi" static let DAILYUVI = "/uvi/forecast" } struct Headers { static let Api_Key = "d849e137d6f4d444bc6877ab440e3468" static let headers: HTTPHeaders = [ "api_key": Headers.Api_Key ] } }
// // TilingView.swift // PagingImageGallery // // Created by Chen, Irene (398N-Affiliate) on 7/31/18. // Copyright © 2018 Chen, Irene (398N-Affiliate). All rights reserved. // import UIKit public class TilingView: UIView { var dziFile: Dzifile var tilingView: TilingView? let tileBoundsVisible = true override public class var layerClass: AnyClass { return CATiledLayer.self } var tiledLayer: CATiledLayer { return self.layer as! CATiledLayer } override public var contentScaleFactor: CGFloat { didSet { super.contentScaleFactor = 1 } } init(dziFile: Dzifile, imageSize: CGSize){//}, delegate:ImageDelegate?) { self.dziFile = dziFile super.init(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: imageSize.width, height: imageSize.height)) tiledLayer.levelsOfDetail = 4 } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Tile Drawing override public func draw(_ rect: CGRect) { print("DRAW RECT: \(rect.width) + \(rect.height)") let context = UIGraphicsGetCurrentContext()! // get the scale from the context by getting the current transform matrix, then asking for // its "a" component, which is one of the two scale components. We need to also ask for the "d" component as it might not be precisely the same as the "a" component, even at the "same" scale. let scaleX: CGFloat = context.ctm.a let scaleY: CGFloat = context.ctm.d var tileSize = CGSize(width: self.dziFile.tileSize, height: self.dziFile.tileSize) // Even at scales lower than 100%, we are drawing into a rect in the coordinate system of the full // image. One tile at 50% covers the width (in original image coordinates) of two tiles at 100%. // So at 50% we need to stretch our tiles to double the width and height; at 25% we need to stretch // them to quadruple the width and height; and so on. // (Note that this means that we are drawing very blurry images as the scale gets low. At 12.5%, // our lowest scale, we are stretching about 6 small tiles to fill the entire original image area. // But this is okay, because the big blurry image we're drawing here will be scaled way down before // it is displayed.) tileSize.width /= scaleX tileSize.height /= -scaleY // calculate the rows and columns of tiles that intersect the rect we have been asked to draw let firstCol: Int = Int(floor(rect.minX/tileSize.width)) let lastCol: Int = Int(floor((rect.maxX-1)/tileSize.width)) let firstRow: Int = Int(floor(rect.minY/tileSize.height)) let lastRow: Int = Int(floor((rect.maxY-1)/tileSize.height)) for row in firstRow...lastRow { for col in firstCol...lastCol { guard let tile = tileFor(scale: scaleX, row: row, col: col) else { return } var tileRect = CGRect(x: (tileSize.width)*CGFloat(col), y: (tileSize.height)*CGFloat(row), width: tileSize.width, height: tileSize.height) // if the tile would stick outside of our bounds, we need to truncate it so as // to avoid stretching out the partial tiles at the right and bottom edges tileRect = self.bounds.intersection(tileRect) tile.draw(in: tileRect) if tileBoundsVisible { drawTileBounds(in: context, withScale: scaleX, inVisibleBounds: tileRect) } } } } //MARK: - Tile Fetching func tileFor(scale: CGFloat, row: Int, col: Int) -> UIImage? { let scale = scale < 1.0 ? Int(1/CGFloat(Int(1/scale))*1000) : Int(scale*1000) let calibratedScale:CGFloat = CGFloat(scale) / 1000 let tileURL = NSURL(fileURLWithPath: self.dziFile.tileSourceUrl).appendingPathComponent("\(folderLevelForScale(scale: calibratedScale))")?.appendingPathComponent("\(col)_\(row).\(self.dziFile.format)") let imageData = NSData(contentsOf: tileURL as! URL) var image = UIImage(data: imageData as! Data) return image } //MARK: - Math Stuff func maximumTileLevel() -> Double { return Double(ceil(log2(Double(max(self.dziFile.width, self.dziFile.height))))) } func folderLevelForScale(scale: CGFloat) -> Int { return Int(ceil(maximumTileLevel() + Double(log2(Double(scale))))) } //MARK: - Debugging Tools // Used for debugging func drawTileBounds(in context: CGContext, withScale scale: CGFloat, inVisibleBounds rect: CGRect) { UIColor.white.set() context.setLineWidth(6.0/scale) context.stroke(rect) } }
import UIKit class BlurredLoader: UIView { private var contentView: UIView! @IBOutlet private weak var activityIndicator: UIActivityIndicatorView! override func awakeFromNib() { super.awakeFromNib() xibSetup() } override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } private func xibSetup() { guard let view = loadViewFromNib() else { return } view.frame = bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(view) contentView = view contentView.layer.cornerRadius = 16 } private func loadViewFromNib() -> UIView? { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: "BlurredLoader", bundle: bundle) return nib.instantiate(withOwner: self, options: nil).first as? UIView } func startAnimating() { isHidden = false activityIndicator.startAnimating() UIView.animate(withDuration: 0.2, animations: { self.alpha = 1 }, completion: nil) } func stopAnimating() { UIView.animate(withDuration: 0.2, animations: { self.alpha = 0 }, completion: { (value: Bool) in self.activityIndicator.stopAnimating() self.isHidden = true }) } var shouldStartActivityIndicator: Bool = false func startAnimatingWith(delay: Double) { shouldStartActivityIndicator = true DispatchQueue.main.asyncAfter(deadline: .now() + delay) { if self.shouldStartActivityIndicator { self.startAnimating() } } } func stopAnimatingWithDelay() { shouldStartActivityIndicator = false self.stopAnimating() } func centerInto(view: UIView) { translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ centerXAnchor.constraint(equalTo: view.centerXAnchor), centerYAnchor.constraint(equalTo: view.centerYAnchor), heightAnchor.constraint(equalToConstant: 100), widthAnchor.constraint(equalToConstant: 100) ]) } }
// // Comic+Fixture.swift // PlumTestTask // // Created by Adrian Śliwa on 25/06/2020. // Copyright © 2020 sliwa.adrian. All rights reserved. // @testable import PlumTestTask extension Comic { static func fixture(number: Int) -> Comic { return Comic(name: "Comic #\(number)", resourceURI: "") } }
// // Constants.swift // MovieDB // // Created by Teja Bethina on 6/1/21. // import Foundation struct Constants { static let apiKey = "5885c445eab51c7004916b9c0313e2d3" static let errorMsg = "Something went wrong. Please try again later" static let moviesSearchURL = "https://api.themoviedb.org/3/search/movie?api_key=5885c445eab51c7004916b9c0313e2d3&language=en-US&page=1&include_adult=false" }
// // Plane.swift // LightPaint // // Created by LOK on 3/8/2017. // Copyright © 2017 WONG LOK. All rights reserved. // import Foundation import Metal import MetalKit class Plane{ var vertexBuffer: MTLBuffer! var verticesArray: Array<Vertex>! var vertexCount: Int! init (device: MTLDevice) { let A = Vertex(x: -1.0 * 0.5, y: 1.0 * 0.5, z: 0.0, w: 1.0) let B = Vertex(x: -1.0 * 0.5, y: -1.0 * 0.5, z: 0.0, w: 1.0) let C = Vertex(x: 1.0 * 0.5, y: -1.0 * 0.5, z: 0.0, w: 1.0) let D = Vertex(x: 1.0 * 0.5, y: 1.0 * 0.5, z: 0.0, w: 1.0) verticesArray = [ A,B,C ,A,C,D //Front ] self.makeBuffer(device: device) } func makeBuffer (device: MTLDevice) { var vertexData = [Float]() for vertex in verticesArray{ vertexData += vertex.floatBuffer() } vertexCount = verticesArray.count // 2 let dataSize = vertexData.count * MemoryLayout.size(ofValue: vertexData[0]) vertexBuffer = device.makeBuffer(bytes: vertexData, length: dataSize, options: []) } }
// Five Little Monkeys 🐵🙉🙊🙈🐒 // Alex DiStasi // Purpose: Prints the lyrics to Five Little Monkeys song // numMonkeys represents number of monkeys on bed var numMonkeys: Int = 5 // Lyrics will print while numMonkeys is greater than 1 while numMonkeys > 1 { print ("\(numMonkeys) little monkeys jumping on the bed.") print ("One fell off and bumped their head!") print ("Mama called the doctor and the doctor said") print ("'No more monkeys jumping on the bed!'\n") numMonkeys -= 1 } // Print the final lyrics print ("\(numMonkeys) little monkey jumping on the bed.") print ("They fell off and bumped their head!") print ("Mama called the doctor and the doctor said") print ("'Put those monkeys straight to bed!'") // Solution to optional challenge 2 /* // numOfMonkeys represents number of monkeys on bed var numOfMonkeys: Int = 5 // Lyrics will print and decrease from 5 to the last one for numOfMonkeys in stride(from: 5, to: 0, by: -1) { // "line[number]Lyric" represents the line of the lyric on a verse let line1Lyric: String = "\n\(numOfMonkeys) little Monkeys jumping on the bed..." let line2Lyric: String = "\nOne fell off and bumped her head..." let line3Lyric: String = "\nMama called the doctor and the doctor said..." let line4Lyric: String = "\n'Hello? No more Monkeys jumping on the bed!'" // Print the lyric iteration print("\(line1Lyric) \(line2Lyric)\(line3Lyric)\(line4Lyric)") } // Last lyric var lastVerse: String = "\nNo little Monkeys jumping on the bed...\nThey fell asleep while laying their heads...\nDoctor called Mama and Mama said...\n'Hello? No more Monkeys jumping on the bed!'" // Print the final lyrics print("\(lastVerse)") */
// // LessonsTableViewController.swift // Meet Swift // // Created by Filip on 10/12/2018. // Copyright © 2018 Filip. All rights reserved. // import UIKit import RealmSwift var buyedContent = false class LessonsTableViewController: UITableViewController { lazy var realm = try! Realm() var resultsOfCollectionOfLessons: Results<CollectionOfLessons>! override func viewDidLoad() { super.viewDidLoad() loadItems() try! realm.write { resultsOfCollectionOfLessons[0].lessons[0].subLessons[5].lessonDescription = "write variable \"firstInteger\" with 101 value" } //print(Realm.Configuration.defaultConfiguration.fileURL!) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) applyTheme() tableView.reloadData() } // MARK: - TableView Section settings override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } override func numberOfSections(in tableView: UITableView) -> Int { return resultsOfCollectionOfLessons?.count ?? 1 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() let headerButton:UIButton = { let button = UIButton() button.frame = CGRect(x: 0, y: 4, width: UIScreen.main.bounds.width, height: 35) button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0) button.setTitle(resultsOfCollectionOfLessons?[section].lvlTitle, for: .normal) button.contentHorizontalAlignment = .left button.titleLabel?.font = UIFont.systemFont(ofSize: 20.0) button.addTarget(self, action: #selector(handleOpenClose), for: .touchUpInside) button.tag = section return button }() let headerCounterLabel: UILabel = { let label = UILabel() label.frame = CGRect(x: UIScreen.main.bounds.width - 50, y: 4, width: 35, height: 35) label.font = UIFont.systemFont(ofSize: 14.0) label.textAlignment = .right return label }() view.addSubview(headerCounterLabel) view.addSubview(headerButton) view.backgroundColor = Theme.current.headerBackgroundColor headerCounterLabel.textColor = Theme.current.textColor if (resultsOfCollectionOfLessons?[section].isExpanded)! { headerButton.setTitleColor(Theme.current.pressedSectionButton, for: .normal) } else { headerButton.setTitleColor(Theme.current.buttonColor, for: .normal) } let sumOfLessonsInSection = resultsOfCollectionOfLessons?[section].lessons.count var sumOfDoneLessonsInSection = 0 for lessons in 0..<sumOfLessonsInSection! { var sumOfCompletedLessonInSubLessonsForSection = 0 let subLessonsInLessons = resultsOfCollectionOfLessons?[section].lessons[lessons].subLessons.count for sublessons in 0..<subLessonsInLessons! { if resultsOfCollectionOfLessons[section].lessons[lessons].subLessons[sublessons].completion == true { sumOfCompletedLessonInSubLessonsForSection += 1 } } if sumOfCompletedLessonInSubLessonsForSection == subLessonsInLessons { sumOfDoneLessonsInSection += 1 } } if section == 0 { headerCounterLabel.text = "\(sumOfDoneLessonsInSection)/\(sumOfLessonsInSection!)" } else { headerCounterLabel.text = "soon" //headerCounterLabel.isHidden = true } return view } // MARK: - TableView Row settings override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if !(resultsOfCollectionOfLessons?[section].isExpanded)! { return 0 } return (resultsOfCollectionOfLessons?[section].lessons.count)! } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "LessonsCell", for: indexPath) as! CustomLessonsCell let cellResults = resultsOfCollectionOfLessons[indexPath.section].lessons[indexPath.row] var sumOfCompletedLessonInSubLessonsForCell = 0 let subLessonsCounterForProgressBar = cellResults.subLessons.count // MARK: - Liczymy rozwiązane w podrozdziale for n in 0..<subLessonsCounterForProgressBar { if cellResults.subLessons[n].completion == true { sumOfCompletedLessonInSubLessonsForCell += 1 } } let backgroundView = UIView() backgroundView.backgroundColor = Theme.current.selectedRow cell.selectedBackgroundView = backgroundView cell.backgroundColor = Theme.current.cellBackgroundColor cell.lessonsNumber.textColor = Theme.current.textColor cell.lessonsTitle.textColor = Theme.current.textColor cell.progressLabel.textColor = Theme.current.textColor cell.progressBar.progressTintColor = Theme.current.progressTintColor cell.progressBar.trackTintColor = Theme.current.buttonColor if subLessonsCounterForProgressBar == 0 { cell.progressBar.progress = 0.0 } else if subLessonsCounterForProgressBar == sumOfCompletedLessonInSubLessonsForCell { cell.progressBar.progress = 1 } else { cell.progressBar.progress = Float((Double(100/subLessonsCounterForProgressBar) * 0.01) * Double(sumOfCompletedLessonInSubLessonsForCell)) } if cellResults.subLessons.count > 0 { cell.lessonsNumber.text = "\(indexPath.row + 1)." cell.lessonsTitle.text = cellResults.title cell.progressLabel.text = "\(sumOfCompletedLessonInSubLessonsForCell)/\(subLessonsCounterForProgressBar)" } else { cell.lessonsNumber.text = "\(indexPath.row + 1)." cell.lessonsTitle.text = cellResults.title cell.progressLabel.text = "soon" //cell.progressBar.isHidden = true } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "goToSubLessonsView", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "goToSubLessonsView" { let subLessonsTableVC = segue.destination as! SubLessonsTableViewController subLessonsTableVC.indexesToSublessons.append(self.tableView!.indexPathForSelectedRow!.section) subLessonsTableVC.indexesToSublessons.append(self.tableView!.indexPathForSelectedRow!.row) } } // MARK: - HandleOpenClosefunction @objc func handleOpenClose(headerButton: UIButton) { let section = headerButton.tag var indexPaths = [IndexPath]() for row in resultsOfCollectionOfLessons[section].lessons.indices { let indexPath = IndexPath(row: row, section: section) indexPaths.append(indexPath) } let isExpanded = resultsOfCollectionOfLessons[section].isExpanded try! realm.write { resultsOfCollectionOfLessons[section].isExpanded = !isExpanded } if isExpanded { tableView.deleteRows(at: indexPaths, with: .fade) headerButton.setTitleColor(Theme.current.buttonColor, for: .normal) } else { tableView.insertRows(at: indexPaths, with: .fade) headerButton.setTitleColor(Theme.current.pressedSectionButton, for: .normal) } if section == 0 { tableView.scrollsToTop = true } else { tableView.layoutIfNeeded() tableView.scrollRectToVisible(CGRect(x: 0 , y: tableView.contentSize.height - tableView.bounds.size.height , width: tableView.bounds.size.width, height: tableView.bounds.size.height), animated: true) } } // MARK: - LoadRealm function private func loadItems() { resultsOfCollectionOfLessons = realm.objects(CollectionOfLessons.self) tableView.reloadData() } // MARK: - Theme function private func applyTheme() { navigationController?.navigationBar.barStyle = Theme.current.style navigationController?.navigationBar.tintColor = Theme.current.buttonColor // color of navigationbar buttons navigationController?.navigationBar.barTintColor = Theme.current.navigationColor // color of navigationbar view.backgroundColor = Theme.current.viewControllerBackgroundColor navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.shadowImage = UIImage() } }
// // ResultCell.swift // Millionaire // // Created by Vitaly Khomatov on 24.04.2020. // Copyright © 2020 Macrohard. All rights reserved. // import UIKit class ResultCell: UITableViewCell { @IBOutlet weak var DateLabel: UILabel! @IBOutlet weak var PrizeLabel: UILabel! @IBOutlet weak var RightAnswersCountLabel: UILabel! @IBOutlet weak var ShuffleAnswersLabel: UILabel! @IBOutlet weak var PromptsUseCountLabel: UILabel! // override func awakeFromNib() { // super.awakeFromNib() // // self.isSelected = false // // // Initialization code // } // override func setSelected(_ selected: Bool, animated: Bool) { // super.setSelected(selected, animated: animated) // // // Configure the view for the selected state // } }
// // DateFormatHelper.swift // RESS // // Created by Luiz Fernando Silva on 16/06/15. // Copyright (c) 2015 Luiz Fernando Silva. All rights reserved. // import Foundation /// Default RFC3339 date formatter let rfc3339DateTimeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" return formatter }() /// Formats a given date string from the API from RFC3339 format into an Date instance func dateTimeFromRFC3339(string: String) -> Date? { return rfc3339DateTimeFormatter.date(from: string) } /// Formats a given date into a RFC3339 date stirng func rfc3339StringFrom(date: Date) -> String { return rfc3339DateTimeFormatter.string(from: date) } func formatTimestamp(_ timestamp: TimeInterval, withMode mode: TimestampMode = .hoursMinutesSeconds) -> String { let hours = timestamp / 60 / 60 let minutes = (timestamp / 60).truncatingRemainder(dividingBy: 60) switch mode { case .hoursMinutesSeconds: let seconds = timestamp.truncatingRemainder(dividingBy: 60) return String(format: "%02d:%02d:%02d", Int(hours), Int(minutes), Int(seconds)) case .hoursMinutes: return String(format: "%02d:%02d", Int(hours), Int(minutes)) } } /// Formats a timestamp with hours, minutes and components only if these components are present. /// Eg: /// 3600 -> '01h' /// 3601 -> '01h01s' /// 4600 -> '01h16m40s' func formatTimestampCompact(_ timestamp: TimeInterval) -> String { let minutes = Int((timestamp / 60).truncatingRemainder(dividingBy: 60)) let seconds = Int(timestamp.truncatingRemainder(dividingBy: 60)) let hours = Int(timestamp / 60 / 60) var output = "" if(hours > 0) { output += String(format: "%02dh", hours) } if(minutes > 0) { output += String(format: "%02dm", minutes) } if(seconds > 0) { output += String(format: "%02ds", seconds) } // Empty time - return 0s string if(output == "") { output = "0s" } return output } /// Specifies the mode for a timestamp generation with the formatTimestamp function enum TimestampMode { case hoursMinutesSeconds case hoursMinutes }
// // SoundPlayViewController.swift // PitchPerfect // // Created by Francis McCabe on 3/11/15. // Copyright (c) 2015 Francis McCabe. All rights reserved. // import UIKit import AVFoundation class SoundPlayViewController: UIViewController, AVAudioPlayerDelegate { var player: AVAudioPlayer! var audioToPlay : RecordedAudio! var audioEngine : AVAudioEngine! var audioFile : AVAudioFile! @IBOutlet weak var stopButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.player = AVAudioPlayer(contentsOfURL: audioToPlay.path, error: nil) self.audioEngine = AVAudioEngine() self.audioFile = AVAudioFile(forReading: audioToPlay.path, error: nil) player.delegate = self player.enableRate = true } func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) { println("Finished playing the track") stopButton.enabled = false } private func startPlaying(rate:Float) { stopPlaying() player.rate = rate stopButton.enabled = true player.play() } private func stopPlaying(){ if player.playing { player.stop() player.currentTime = NSTimeInterval(0) } if audioEngine.running { audioEngine.stop() audioEngine.reset() } stopButton.enabled = false } func playAudioWithVariablePitch(pitch: Float){ stopPlaying() var audioPlayerNode = AVAudioPlayerNode() audioEngine.attachNode(audioPlayerNode) var changePitchEffect = AVAudioUnitTimePitch() changePitchEffect.pitch = pitch audioEngine.attachNode(changePitchEffect) audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil) audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil) audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: { self.stopButton.enabled = false} ) audioEngine.startAndReturnError(nil) audioPlayerNode.play() } @IBAction func playSlowly(sender: UIButton) { startPlaying(0.5) } @IBAction func playQuickly(sender: UIButton) { startPlaying(2.0) } @IBAction func playChipmunk(sender: AnyObject) { playAudioWithVariablePitch(1000) stopButton.enabled = true } @IBAction func playDarthVader(sender: UIButton) { playAudioWithVariablePitch(-1000) stopButton.enabled = true } @IBAction func stopPlaying(sender: UIButton) { stopPlaying() } }
// // PPNewFileToast.swift // ProtoPipe // // Created by 吉乞悠 on 2020/6/18. // Copyright © 2020 吉乞悠. All rights reserved. // import UIKit typealias NewFileToastModel = ( // For Internal Transfer title: String, devices: [(device: PPDevice, isSelected: Bool)], templates: [(template: PPTemplate, isSelected: Bool)]) class NewFileModel: NSObject { // For Export let title: String let device: PPDevice let template: PPTemplate init(title: String, device: PPDevice, template: PPTemplate) { self.title = title self.device = device self.template = template } } class PPNewFileToast: PPToastViewController { var fileNameLbl: UILabel! var fileNameTextField: UITextField! var deviceLbl: UILabel! var deviceCollectionView: UICollectionView! var templateLbl: UILabel! var templateCollectionView: UICollectionView! var cancelBtn: UIButton! var confirmBtn: UIButton! var model: NewFileToastModel = ("", [], []) weak var delegate: PPToastViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() // Prepare Model for type in PPNewFileToast.DeviceTypeList { let device = PPDevice(type: type) model.devices.append((device, false)) } model.devices[0].isSelected = true for type in PPNewFileToast.TemplateTypeList { let template = PPTemplate(type: type) model.templates.append((template, false)) } model.templates[0].isSelected = true // Prepare UI toastNavigationBar.title = "New File" fileNameLbl = makeTitleLabel(title: "File Name") contentView .addSubview(fileNameLbl) fileNameLbl.snp.makeConstraints { (make) in make.top.equalTo(18) make.left.equalTo(28) } fileNameTextField = UITextField() fileNameTextField.delegate = self fileNameTextField.font = UIFont.systemFont(ofSize: 18) fileNameTextField.backgroundColor = .textFieldGray fileNameTextField.textColor = .titleWhite fileNameTextField.borderStyle = .roundedRect fileNameTextField.returnKeyType = .continue fileNameTextField.spellCheckingType = .no contentView.addSubview(fileNameTextField) fileNameTextField.snp.makeConstraints { (make) in make.top.equalTo(fileNameLbl.snp.bottom).offset(14) make.left.equalTo(28) make.width.equalTo(300) make.height.equalTo(40) } deviceLbl = makeTitleLabel(title: "Device") contentView.addSubview(deviceLbl) deviceLbl.snp.makeConstraints { (make) in make.top.equalTo(fileNameTextField.snp.bottom).offset(18) make.left.equalTo(28) } deviceCollectionView = makeCollectionView() deviceCollectionView.register(PPNewFileToastDeviceCell.self, forCellWithReuseIdentifier: PPNewFileToast.DeviceCellID) contentView.addSubview(deviceCollectionView) deviceCollectionView.snp.makeConstraints { (make) in make.top.equalTo(deviceLbl.snp.bottom).offset(14) make.left.right.equalTo(view) make.height.equalTo(120) } templateLbl = makeTitleLabel(title: "Template") contentView.addSubview(templateLbl) templateLbl.snp.makeConstraints { (make) in make.top.equalTo(deviceCollectionView.snp.bottom).offset(18) make.left.equalTo(28) } templateCollectionView = makeCollectionView() templateCollectionView.register(PPNewFileToastTemplateCell.self, forCellWithReuseIdentifier: PPNewFileToast.TemplateCellID) contentView.addSubview(templateCollectionView) templateCollectionView.snp.makeConstraints { (make) in make.top.equalTo(templateLbl.snp.bottom).offset(14) make.left.right.equalTo(view) make.height.equalTo(120) } cancelBtn = PPActionButton(type: .Cancel) contentView.addSubview(cancelBtn) cancelBtn.addTarget(self, action: #selector(cancel(sender:)), for: .touchUpInside) cancelBtn.snp.makeConstraints { (make) in make.top.equalTo(templateCollectionView.snp.bottom).offset(35) make.centerX.equalToSuperview().offset(-100) make.width.equalTo(120) make.height.equalTo(49) make.bottom.equalTo(-35) } confirmBtn = PPActionButton(type: .Confirm) contentView.addSubview(confirmBtn) confirmBtn.addTarget(self, action: #selector(confirm(sender:)), for: .touchUpInside) confirmBtn.snp.makeConstraints { (make) in make.top.equalTo(templateCollectionView.snp.bottom).offset(35) make.centerX.equalToSuperview().offset(100) make.width.equalTo(120) make.height.equalTo(49) make.bottom.equalTo(-35) } } } // MARK: - Target Actions extension PPNewFileToast { @objc func cancel(sender: UIButton) { delegate?.toastViewControllerDidClickCancelBtn(self) } @objc func confirm(sender: UIButton) { if fileNameTextField.text?.isEmpty == true { print("empty") } else { delegate?.newFileToastDidClickConfirmBtn?(self, newFileModel: getFilteredModel()) } } } // MARK: - UICollectionViewDelegate & UICollectionViewDataSource extension PPNewFileToast: UICollectionViewDelegate, UICollectionViewDataSource { static let DeviceCellID = "DeviceCollectionViewCell" static let TemplateCellID = "TemplateCollectionViewCell" func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == deviceCollectionView { return model.devices.count } else if collectionView == templateCollectionView { return model.templates.count } return 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == deviceCollectionView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PPNewFileToast.DeviceCellID, for: indexPath) as! PPNewFileToastDeviceCell cell.device = model.devices[indexPath.row] return cell } else if collectionView == templateCollectionView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PPNewFileToast.TemplateCellID, for: indexPath) as! PPNewFileToastTemplateCell cell.template = model.templates[indexPath.row] return cell } return UICollectionViewCell() } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if collectionView == deviceCollectionView { for i in 0...model.devices.count - 1 { model.devices[i].isSelected = false } model.devices[indexPath.row].isSelected.toggle() collectionView.reloadData() } else if collectionView == templateCollectionView { for i in 0...model.templates.count - 1 { model.templates[i].isSelected = false } model.templates[indexPath.row].isSelected.toggle() collectionView.reloadData() } } } // MARK: - Helper extension PPNewFileToast { private func makeTitleLabel(title: String) -> UILabel { let lbl = UILabel() lbl.text = title lbl.font = UIFont.systemFont(ofSize: 24, weight: .semibold) lbl.textColor = .subtitleGray lbl.textAlignment = .left return lbl } private func makeCollectionView() -> UICollectionView { let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: 100, height: 120) flowLayout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: flowLayout) collectionView.contentInset = UIEdgeInsets(top: 0, left: 28, bottom: 0, right: 28) collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.backgroundColor = .clear collectionView.delegate = self collectionView.dataSource = self return collectionView } private func getFilteredModel() -> NewFileModel { var newFileModel = (fileNameTextField.text, PPDevice(type: .Custom), PPTemplate(type: .Blank)) for i in 0...model.devices.count - 1 { if model.devices[i].isSelected { newFileModel.1 = model.devices[i].device; break } } for i in 0...model.templates.count - 1 { if model.templates[i].isSelected { newFileModel.2 = model.templates[i].template; break } } return NewFileModel(title: newFileModel.0 ?? "File", device: newFileModel.1, template: newFileModel.2) } } // MARK: - UITextFieldDelegate extension PPNewFileToast: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { return textField.resignFirstResponder() } } // MARK: - Static Model extension PPNewFileToast { static let DeviceTypeList: [PPDeviceType] = [.iPhoneX, .iPhone8, .iPhoneSE, .iPhone8p, .iPhone11p, .Custom] static let TemplateTypeList: [PPTemplateType] = [.Blank, .Tab, .List, .Camera, .Map, .Secret] }
// // Products.swift // SealSounds // // Created by Samuel Germain on 2019-11-05. // Copyright © 2019 Sam G. All rights reserved. // import Foundation public struct Products{ public static let premium = "1985162691" private static let productIdentifiers: Set<ProductIdentifier> = [Products.premium] public static let store = IAPHelper(productIds: Products.productIdentifiers) } func resourceNameForProductIdentifier(_ productIdentifier: String) -> String? { return productIdentifier.components(separatedBy: ".").last }
// // RecordViewController.swift // PitchPerfect // // Created by Rafi Khan on 2017/05/31. // Copyright © 2017 Rafi Khan. All rights reserved. // import UIKit import AVFoundation class RecordViewController: UIViewController, AVAudioRecorderDelegate { @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var stopButton: UIButton! var recordingSession:AVAudioSession! var recorder:AVAudioRecorder! var audioURL:URL! // MARK: Delegate methods override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. recordingSession = AVAudioSession.sharedInstance() do { try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord) try recordingSession.setActive(true) // Get audio permission and handle error cases. recordingSession.requestRecordPermission() { [unowned self] allowed in DispatchQueue.main.async { if allowed { // print("Initialized!") } else { // Would send alert to user here. print("Couldn't get recording permissions") } } } } catch { // Would also send alert to user here. print("Error in creating AudioSession") } } override func viewDidAppear(_ animated:Bool) { enableVisuals() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Could use delegate here, but decided not to. // func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, // successfully flag: Bool) { // if (flag) { // print("Audio saved") // performSegue(withIdentifier: "audioSaved", sender: stopButton) // } else { // print("Error in recording audio") // } // } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "audioSaved" { let playVC:PlayViewController = segue.destination as! PlayViewController playVC.audioURL = audioURL // Pass audio file to new view. } } // MARK: Actions @IBAction func recordAudio(_ sender: UIButton) { disableVisuals() audioURL = getDocumentsDirectory().appendingPathComponent("recording.wav") do { recorder = try AVAudioRecorder(url: audioURL, settings: [:]) recorder.delegate = self recorder.prepareToRecord() recorder.record() print("Recording...") } catch { print("Error recording") } } @IBAction func saveAudio(_ sender: UIButton) { enableVisuals() recorder.stop() performSegue(withIdentifier: "audioSaved", sender: sender) } @IBAction func unwindToRecordVC(segue:UIStoryboardSegue) { } // MARK: Helpers func disableVisuals() { recordButton.isEnabled = false recordButton.alpha = 0.5 stopButton.isEnabled = true stopButton.alpha = 1.0 } func enableVisuals() { recordButton.isEnabled = true recordButton.alpha = 1.0 stopButton.isEnabled = false stopButton.alpha = 0.5 } func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } }
// // Constants.swift // Channelier new // // Created by Himanshu Jha on 23/10/19. // Copyright © 2019 Himanshu Jha. All rights reserved. // import Foundation import UIKit let APP_BASE_URL = "https://beta.channelier.com/index.php?route=feed/rest_api_v2/forgotten&email="
// // AppDelegate.swift // MusicBrainz // // Created BOGU$ on 20/05/2019. // Copyright © 2019 lyzkov. All rights reserved. // import UIKit final class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let appDependencies = AppDependencies.shared func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow() appDependencies.installRootViewController(into: window!) window?.makeKeyAndVisible() return true } }
// Copyright © 2019 Keith Harrison. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. import UIKit final class LibraryContainerViewController: UIViewController { private let library = [ Book(title: "Alice's Adventures in Wonderland", author: "Lewis Caroll", firstLine: "Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, ‘and what is the use of a book,’ thought Alice ‘without pictures or conversations?’"), Book(title: "Emma", author: "Jane Austen", firstLine: "Emma Woodhouse, handsome, clever, and rich, with a comfortable home and happy disposition, seemed to unite some of the best blessings of existence; and had lived nearly twenty-one years in the world with very little to distress or vex her."), Book(title: "Great Expectations", author: "Charles Dickens", firstLine: "My father's family name being Pirrip, and my Christian name Philip, my infant tongue could make of both names nothing longer or more explicit than Pip."), Book(title: "Metamorphosis", author: "Franz Kafka", firstLine: "One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin."), Book(title: "Peter Pan", author: "James M. Barrie", firstLine: "All children, except one, grow up.") ] private var previewController: MessageViewController? private var listTableViewController: BookListTableViewController? } extension LibraryContainerViewController: SegueHandler { enum SegueIdentifier: String { case embedList case embedPreview } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segueIdentifier(for: segue) { case .embedList: guard let childController = segue.destination as? BookListTableViewController else { fatalError("Missing ListTableViewController") } listTableViewController = childController listTableViewController?.list = library listTableViewController?.delegate = self case .embedPreview: guard let childController = segue.destination as? MessageViewController else { fatalError("Missing MessageViewController") } previewController = childController previewController?.message = "Choose a book..." previewController?.view.translatesAutoresizingMaskIntoConstraints = false } } } extension LibraryContainerViewController: BookListDelegate { func didSelect(index: Int) { previewController?.message = library[index].firstLine } }
// // SignUpViewController.swift // FoodFunds // // Created by Jason Carter on 2016-01-13. // Copyright © 2016 Jason Carter. All rights reserved. // import UIKit import Parse class SignUpViewController: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var errorField: UILabel! override func viewDidLoad() { super.viewDidLoad() activityIndicator.hidden = true activityIndicator.hidesWhenStopped = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func SignUpTouchUpInside(sender: AnyObject) { // Guard against nil or empty guard let userEmailAddress = emailField?.text, userPassword = passwordField?.text where userEmailAddress.characters.count > 0 && userPassword.characters.count > 0 else { return } // Ensure username/email is lowercase let userEmail = userEmailAddress.lowercaseString // Add email address validation // Start activity indicator activityIndicator.hidden = false activityIndicator.startAnimating() // Create the user let user = PFUser() user.username = userEmail user.password = userPassword user.email = userEmailAddress user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in if error == nil { // Need to update the UI dispatch_async(dispatch_get_main_queue()) { let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Home") self.presentViewController(viewController, animated: true, completion: nil) } } else { self.activityIndicator.stopAnimating() if let message = error!.userInfo["error"] { self.errorField.text = "\(message)" } } } } }
// // ReactiveFetch+NSFetchedResultsController.swift // Pink Pill // // Created by Peter Christian Glade on 20.05.16. // Copyright © 2016 Peter Christian Glade (iLem0n). All rights reserved. // import Foundation import ReactiveCocoa import CoreData extension ReactiveFetch: NSFetchedResultsControllerDelegate { public func controllerWillChangeContent(controller: NSFetchedResultsController) { print(#function, controller) self.isChangingData.value = true } public func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { print(#function, controller, sectionInfo, sectionIndex, type) var changeType: CoreDataChangeType! switch type { case .Insert: changeType = .SectionInsert case .Delete: changeType = .SectionDelete default: break } changesObserver.sendNext(CoreDataChange(type: changeType, object: nil, sectionIndex: sectionIndex, indexPath: nil, secondIndexPath: nil)) } public func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { print(#function, controller, anObject, indexPath, type, newIndexPath) var changeType: CoreDataChangeType! switch type { case .Insert: changeType = .RowInsert case .Move: changeType = .RowMove case .Delete: changeType = .RowDelete case .Update: changeType = .RowUpdate } changesObserver.sendNext(CoreDataChange(type: changeType, object: anObject as! T, sectionIndex: nil, indexPath: indexPath, secondIndexPath: newIndexPath)) } public func controllerDidChangeContent(controller: NSFetchedResultsController) { print(#function, controller) self.isChangingData.value = false } }
// // BaseImageView.swift // NewsApp // // Created by Al-sawafta, Amjad on 11/11/18. // Copyright © 2018 AlFuttam. All rights reserved. // import UIKit class BaseImageView: UIImageView { /** pass url to Image View for lazy loading */ var url : String? = nil { didSet{ ImageLoader.load(with: url, into: self) } } }
#if canImport(UIKit) import UIKit private extension UIImage { convenience init?(color: UIColor, size: CGSize) { if size.width <= 0 || size.height <= 0 { self.init() return nil } UIGraphicsBeginImageContext(size) defer { UIGraphicsEndImageContext() } let rect = CGRect(origin: CGPoint.zero, size: size) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.setFillColor(color.cgColor) context.fill(rect) guard let image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { return nil } self.init(cgImage: image) } } internal final class ZoomIndicatorButton: UIButton { // MARK: - UIView Extension @IBInspectable dynamic var cornerRadius: CGFloat { get { layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable dynamic var borderColor: UIColor? { get { if let cgColor = layer.borderColor { return UIColor(cgColor: cgColor) } else { return nil } } set { layer.borderColor = newValue?.cgColor } } @IBInspectable dynamic var borderWidth: CGFloat { get { layer.borderWidth } set { layer.borderWidth = newValue } } // MARK: - UIButton Extension private func setBackgroundColor(_ color: UIColor?, for state: UIControl.State) { if let color = color { let image = UIImage(color: color, size: bounds.size) setBackgroundImage(image, for: state) } else { setBackgroundImage(nil, for: state) } } @IBInspectable dynamic var normalBackgroundColor: UIColor? { get { nil // dummy } set { setBackgroundColor(newValue, for: .normal) } } @IBInspectable dynamic var highlightedBackgroundColor: UIColor? { get { nil // dummy } set { setBackgroundColor(newValue, for: .highlighted) } } @IBInspectable dynamic var disabledBackgroundColor: UIColor? { get { nil // dummy } set { setBackgroundColor(newValue, for: .disabled) } } // MARK: - Initializer required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) updateTitleForCurrentZoomFactor() SimpleCamera.shared.add(simpleCameraObserver: self) } // MARK: - func updateTitleForCurrentZoomFactor() { let zoomFactor = SimpleCamera.shared.zoomFactor let zoomFactorString = String(format: "%.1f", zoomFactor) let title: String if zoomFactorString.hasSuffix(".0") { let l = zoomFactorString.count - 2 title = zoomFactorString.prefix(l) + "x" } else { title = zoomFactorString + "x" } setTitle(title, for: .normal) } } import AVFoundation extension ZoomIndicatorButton: SimpleCameraObservable { func simpleCameraDidStartRunning(simpleCamera: SimpleCamera) {} func simpleCameraDidStopRunning(simpleCamera: SimpleCamera) {} func simpleCameraDidChangeFocusPointOfInterest(simpleCamera: SimpleCamera) {} func simpleCameraDidChangeExposurePointOfInterest(simpleCamera: SimpleCamera) {} func simpleCameraDidResetFocusAndExposure(simpleCamera: SimpleCamera) {} func simpleCameraDidSwitchCameraInput(simpleCamera: SimpleCamera) {} // func simpleCameraSessionRuntimeError(simpleCamera: SimpleCamera, error: AVError) {} // @available(iOS 9.0, *) // func simpleCameraSessionWasInterrupted(simpleCamera: SimpleCamera, reason: AVCaptureSession.InterruptionReason) {} func simpleCameraSessionInterruptionEnded(simpleCamera: SimpleCamera) {} internal func simpleCameraDidChangeZoomFactor(simpleCamera: SimpleCamera) { updateTitleForCurrentZoomFactor() } } #endif
// // LeftTableCell.swift // Project // // Created by 张凯强 on 2019/8/17. // Copyright © 2019年 HHCSZGD. All rights reserved. // import UIKit class LeftTableCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none // Initialization code } @IBOutlet var title: UILabel! var model: TimeModel? { didSet{ guard let myModel = self.model else { return } self.title.text = myModel.title + "年" if myModel.isSelected { self.title.textColor = UIColor.colorWithHexStringSwift("ea9061") self.contentView.backgroundColor = UIColor.colorWithRGB(red: 255, green: 255, blue: 255) }else { self.title.textColor = UIColor.colorWithHexStringSwift("333333") self.contentView.backgroundColor = UIColor.colorWithRGB(red: 242, green: 242, blue: 242) } } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
import UIKit import Combine // MARK: - Collect /// collect all values and give you an array of items /// can be used as collect (n) where n is how many items you want to group together func collectOperator(_ itemsPerGroup: Int = 0) { /// if itemsPerGroup == 0 then it works as .collect() ["A", "B", "C", "D", "E"].publisher.collect(itemsPerGroup).sink { print($0) } } //collectOperator(4) // MARK: - Map /// takes an array of items and transforms it into a diferent set of items func mapOperator() { let formatter = NumberFormatter() formatter.numberStyle = .spellOut [123, 45, 67].publisher.map { formatter.string(from: NSNumber(integerLiteral: $0)) ?? "" }.sink { print($0) } } //mapOperator() // MARK: - MapKeypath /// can be used to access diferent attributes from an object and will be able to work with the output as you would in a normal map operator func mapKeypathOperator() { struct Point { let x: Int let y: Int } let publisher = PassthroughSubject<Point, Never>() publisher.map(\.x, \.y).sink { x, y in print("x is \(x) and y is \(y)") } publisher.send(Point(x: 2, y: 10)) } //mapKeypathOperator() // MARK: - FlatMap /// can be used to flatten the multiple upstream publishers into a single downstream publisher struct School { let name: String let noOfStudents: CurrentValueSubject<Int, Never> init(name: String, noOfStudents: Int) { self.name = name self.noOfStudents = CurrentValueSubject(noOfStudents) } } func flatMapOperator() { let citySchool = School(name: "Universidad Tecnologica Nacional", noOfStudents: 100) let school = CurrentValueSubject<School,Never>(citySchool) /// by adding flatMap we are able to receive notifications on the particular attribute that is being changed school.flatMap { $0.noOfStudents } .sink { print($0) } citySchool.noOfStudents.value = 105 } //flatMapOperator() // MARK: - ReplaceNil /// self explanatory func replaceNilOperator() { ///Take into consideration that if we use replaceNil then our values will be of optional type. ["A", "B", "C", "D", nil, "F"].publisher.replaceNil(with: "*") ///by using the map operator we can safely force unwrap the values, Because it's impossible to have nil values remaining .map { $0! } .sink { print($0) } } //replaceNilOperator() // MARK: - replaceEmpty func replaceEmptyOperator() { let empty = Empty<Int, Never>() /// we can use replaceEmpty to obtain a desired value in case of an Empty event empty .replaceEmpty(with: 1) .sink(receiveCompletion: { print($0) }, receiveValue: { print($0) }) } //replaceEmptyOperator() //MARK: - Scan func scanOperator() { ///acts as an accumulator, collecting and modifying values and publishing intermediate results let publisher = (1...10).publisher publisher.scan([]) { numbers, value -> [Int] in /// just a reminder a single value with no return assumes a return is being used. numbers + [value] } .sink { print($0) } }
// // CustomSegmentedControl.swift // Teachify // // Created by Bastian Kusserow on 17.04.18. // Copyright © 2018 Christian Pfeiffer. All rights reserved. // import UIKit @IBDesignable class CustomSegmentedControl: UICollectionView, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { private var action : (() -> Void)? var selectedSegmentIndex = 0 func addTarget(action: @escaping () -> Void){ self.action = action } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "segmentCell", for: indexPath) cell.layer.cornerRadius = 15 return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let action = action { action() } } func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) { selectedSegmentIndex = indexPath.item } override func awakeFromNib() { super.awakeFromNib() setup() } private func setup(){ backgroundColor = .teacherLightBlue //self.dataSource = self self.delegate = self self.selectItem(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: []) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 10 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.width/4, height: collectionView.bounds.height*4/5) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { if let layout = collectionViewLayout as? UICollectionViewFlowLayout{ let spacing = self.collectionView(self, layout: layout, minimumInteritemSpacingForSectionAt: 0) return UIEdgeInsets(top: 0, left: collectionView.bounds.width/8 - 10 - spacing, bottom: 0, right: collectionView.bounds.width/8 - spacing) } return UIEdgeInsets.zero } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() } }
import NIO /** Decodes a `ByteBuffer` packed in an `AddressedEnvelope` into its `Message` representation returned packed into an `AddressedEnvelope`. */ final class MessageDecoder: ChannelInboundHandler { typealias InboundIn = AddressedEnvelope<ByteBuffer> typealias InboundOut = AddressedEnvelope<Message> func channelRead(context: ChannelHandlerContext, data: NIOAny) { do { let envelope = self.unwrapInboundIn(data) // Get the slice of the buffer that contains the readable bytes. // The index of the first byte is now 0 and allows the decoder the decode compressed domain labels. var buffer = envelope.data.slice() // Read the message from the buffer. LIFXDeviceManager.logger.debug( """ Recieved from \(envelope.remoteAddress.description): [\n\( (0..<buffer.readableBytes) .compactMap({ buffer.getInteger(at: buffer.readerIndex.advanced(by: $0), as: UInt8.self) }) .enumerated() .map({ (index: Int, byte: UInt8) -> String in " Byte \(index): 0x\(String(byte, radix: 16, uppercase: true))" }) .joined(separator: "\n") )\n] """ ) let message = try buffer.readMessage() // The decoded message is passed inbound to the next `ChannelInboundHandler`. context.fireChannelRead(wrapInboundOut(AddressedEnvelope(remoteAddress: envelope.remoteAddress, data: message))) } catch { LIFXDeviceManager.logger.info("Dropped Message: \(self.unwrapInboundIn(data))") } } }
// // MemberListVC.swift // TJQS // // Created by X on 16/9/9. // Copyright © 2016年 QS. All rights reserved. // import UIKit class MemberListVC: UIViewController,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource { @IBOutlet var edit: UITextField! @IBOutlet var all: UILabel! @IBOutlet var table: XTableView! var isEdit = false override func pop() { edit.removeTextChangeBlock() super.pop() } // func toEdit() // { // isEdit = !isEdit // for item in table.httpHandle.listArr // { // (item as! MemberModel).enable = isEdit // (item as! MemberModel).selected = false // } // // table.reloadData() // // } func toSearch(str:String) { if str.length() == 11 { table.httpHandle.url = "http://182.92.70.85/hfshopapi/Public/Found/?service=Shopd.getUserInfoM&mobile="+str+"&shopid="+SID table.httpHandle.reSet() table.httpHandle.handle() } else if str.length() == 0 { let url = APPURL+"Public/Found/?service=Shopd.getShopUser&id="+SID+"&page=[page]&perNumber=20" table.httpHandle.url = url table.httpHandle.reSet() table.httpHandle.handle() } else { all.text = "全部共0位会员" table.httpHandle.url = "" table.httpHandle.reSet() table.httpHandle.listArr.removeAll(keepCapacity: false) table.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.title = "会员管理" self.addBackButton() // self.addNvButton(false, img: "add.png", title: nil) {[weak self] (btn) in // self?.toEdit() // } edit.addEndButton() edit.delegate = self let leftView = UIView() leftView.frame = CGRectMake(0, 0, 42, 42) let left = UIImageView() left.frame = CGRectMake(8, 6, 30, 30) left.image = "search.png".image leftView.addSubview(left) edit.leftView = leftView edit.leftViewMode = .Always edit.onTextChange {[weak self] (txt) in self?.toSearch(txt) } table.cellHeight = 90.0 table.Delegate(self) table.DataSource(self) table.httpHandle.BeforeBlock { [weak self](arr) in self?.all.text = "全部共\(arr.count)位会员" } let url = APPURL+"Public/Found/?service=Shopd.getShopUser&id="+SID+"&page=[page]&perNumber=20" table.setHandle(url, pageStr: "[page]", keys: ["data","info"], model: MemberModel.self, CellIdentifier: "MemberListCell") table.show() } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEdit() return true } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if isEdit { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MemberListCell { cell.model.selected = !cell.model.selected cell.btn.selected = cell.model.selected } } else { let vc = "MemberInfoVC".VC("Main") as! MemberInfoVC vc.model = table.httpHandle.listArr[indexPath.row] as! MemberModel self.navigationController?.pushViewController(vc, animated: true) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? { return "删除" } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if(editingStyle == UITableViewCellEditingStyle.Delete) { let id=(self.table.httpHandle.listArr[indexPath.row] as! MemberModel).id let url=APPURL+"Public/Found/?service=Shopd.delShopUser&id="+id XHttpPool.requestJson(url, body: nil, method: .GET, block: { (json) in if let status = json?["data"]["code"].int { if status == 0 { self.table.httpHandle.listArr.removeAtIndex(indexPath.row) self.table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) self.all.text = "全部共\(self.table.httpHandle.listArr.count)位会员" } else { ShowMessage(json!["data"]["msg"].stringValue) } } else { ShowMessage("删除会员失败!") } }) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } deinit { print("OpenCardVC deinit !!!!!!!!!!!!") } }
// // ProfileData.swift // HealthKit-Chart // // Created by Nguyen The Phuong on 10/19/18. // Copyright © 2018 Nguyen The Phuong. All rights reserved. // import Foundation import HealthKit class ProfileData{ static func getUserProfile() -> (age: Int?, biologicalSex: HKBiologicalSex?, bloodType: HKBloodType?){ let healthKitStore = HKHealthStore() let birthdayComponents = try? healthKitStore.dateOfBirthComponents() let biologicalSex = try? healthKitStore.biologicalSex() let bloodType = try? healthKitStore.bloodType() let today = Date() let calendar = Calendar.current let todayDateComponents = calendar.dateComponents([.year], from: today) let thisYear = todayDateComponents.year let age: Int? = { if let year = thisYear, let birthday = birthdayComponents?.year{ return year - birthday } else { return nil } }() let unwrappedBiologicalSex = biologicalSex?.biologicalSex let unwrappedBloodType = bloodType?.bloodType return (age, unwrappedBiologicalSex, unwrappedBloodType) } }
// // RPPoetryDetailCell.swift // RYPoetry // // Created by 王荣庆 on 2017/10/17. // Copyright © 2017年 RyukieSama. All rights reserved. // import UIKit class RPPoetryDetailCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code setupUI() } func bindPoetryModel(poetry : RPPoetryBaseModel) { } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: - UI @IBOutlet weak var lbText: UILabel! private func setupUI() { contentView.backgroundColor = UIColor.gray //文字 lbText.textColor = UIColor.black lbText.font = RYFontHelper.contentFont() lbText.text = "啊实打实大声大声打的见你人贵人屠洪刚一和人体UK基督教看去玩儿推哦平地方规划九克拉啊实打实大声大声打的见你人贵人屠洪刚一和人体UK基督教看去玩儿推哦平地方规划九克拉" } }
// // Coordinator.swift // iOS-MVVMC-Architecture // // Created by Takahiro Nishinobu on 2017/05/09. // Copyright © 2017年 hachinobu. All rights reserved. // import UIKit protocol Coordinator: class { func start() }
// // EditVehicleInfoVC.swift // Qvafy // // Created by ios-deepak b on 22/07/20. // Copyright © 2020 IOS-Aradhana-cat. All rights reserved. // import UIKit class EditVehicleInfoVC: UIViewController ,UIImagePickerControllerDelegate, UINavigationControllerDelegate , UITextFieldDelegate, UIGestureRecognizerDelegate , VehicleSheetVCDelegate { //MARK: - Outlets // @IBOutlet weak var vwBack: UIView! @IBOutlet weak var vwUpdate: UIView! @IBOutlet weak var vwImgUpdate: UIView! // @IBOutlet weak var vwProgress: UIView! // @IBOutlet weak var vwRound: UIView! @IBOutlet weak var vwRegistration: UIView! @IBOutlet weak var vwImgRegistration: UIView! @IBOutlet weak var vwLicense: UIView! @IBOutlet weak var vwImgLicense: UIView! @IBOutlet weak var vwYear: UIView! @IBOutlet weak var vwModel: UIView! @IBOutlet weak var vwNumber: UIView! @IBOutlet weak var vwMake: UIView! @IBOutlet weak var vwType: UIView! @IBOutlet weak var vwBlur: UIView! @IBOutlet weak var vwTable: UIView! @IBOutlet weak var imgRegistration: UIImageView! @IBOutlet weak var imgLicense: UIImageView! @IBOutlet weak var txtYear: UITextField! @IBOutlet weak var txtModel: UITextField! @IBOutlet weak var txtNumber: UITextField! @IBOutlet weak var lblMake: UILabel! @IBOutlet weak var lblType: UILabel! @IBOutlet weak var lblMakePalceHolder: UILabel! @IBOutlet weak var lblTypePalceHolder: UILabel! //localization outlets- @IBOutlet weak var lblLocEditProfileHeader: UILabel! @IBOutlet weak var lblLocPleaseFillAllInfo: UILabel! @IBOutlet weak var lblLocYear: UILabel! @IBOutlet weak var lblLocModel: UILabel! @IBOutlet weak var lblLocMake: UILabel! @IBOutlet weak var lblLocVehicleType: UILabel! @IBOutlet weak var lblVehicleNumber: UILabel! @IBOutlet weak var lblLocRegistration: UILabel! @IBOutlet weak var lblLocLicense: UILabel! @IBOutlet weak var lblLocUploadId: UILabel! @IBOutlet weak var btnCancel: UIButton! @IBOutlet weak var lblLocUploadLicense: UILabel! // @IBOutlet weak var lblHeaderText: UILabel! //@IBOutlet weak var lblProgress: UILabel! @IBOutlet weak var btnUpdate: UIButton! // bottom sheet @IBOutlet weak var lblTableHeader: UILabel! @IBOutlet weak var tblBottom: UITableView! // @IBOutlet weak var tblHeight: NSLayoutConstraint! // @IBOutlet weak var tblBottomConstraint: NSLayoutConstraint! // @IBOutlet weak var vwTableBottomConstraint: NSLayoutConstraint! @IBOutlet weak var tblHeightConstraint: NSLayoutConstraint! @IBOutlet weak var vwTableHeightConstraint: NSLayoutConstraint! // // deepak new //MARK: - Variables var imagePicker = UIImagePickerController() var pickedImage:UIImage? var pickedImageRegistration:UIImage? var pickedImageLicense:UIImage? var strType: Int = 0 var strDriverType:String = "2" var strMake: Int = 0 var arrMake:[VehicleModel] = [] var arrType:[VehicleModel] = [] var strVehicleTypeId: String = "" var strMakeId: String = "" var strMakeSelection = "" var strTypeSelection = "" var isFromLogin:Bool = false var strVehicleInfoId = "" var isLicense:Bool = false var isRegistration:Bool = false var isFormFoodDriver = false var isFirstAppear = false var arrTxtID:[Int] = [] var arrTxtName:[String] = [] var registrationUpdate = false var licenseUpdate = false //MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() self.isFirstAppear = true self.setUI() self.imagePicker.delegate = self let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:))) self.view.addGestureRecognizer(tap) tap.delegate = self print("self.isFormFoodDriver is \(self.isFormFoodDriver)") // if self.isFormFoodDriver == true { // self.strDriverType = "3" // }else{ // self.strDriverType = "2" // // } self.callWsForUserVehicleRole() self.tblBottom.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.localization() } //MARK: - Functions func setData() { if let vehicleInfoID = objAppShareData.dictVichleInfo["vehicleInfoID"]as? String{ self.strVehicleInfoId = vehicleInfoID } if let vehicleYear = objAppShareData.dictVichleInfo["vehicle_year"]as? String{ self.txtYear.text = vehicleYear } if let modelNumber = objAppShareData.dictVichleInfo["model_number"]as? String{ self.txtModel.text = modelNumber } if let vehicleNumber = objAppShareData.dictVichleInfo["vehicle_number"]as? String{ self.txtNumber.text = vehicleNumber } if let vehicleType = objAppShareData.dictVichleInfo["vehicle_type"]as? String{ self.lblTypePalceHolder.isHidden = true self.lblType.text = vehicleType objAppShareData.strSelectedModelNames = vehicleType } if let make = objAppShareData.dictVichleInfo["make"]as? String{ self.lblMakePalceHolder.isHidden = true self.lblMake.text = make objAppShareData.strSelectedCompanyNames = make } if let vehicleCompanyID = objAppShareData.dictVichleInfo["vehicleCompanyID"]as? String{ self.strMakeId = vehicleCompanyID objAppShareData.strSelectedVehicleCompanyId = vehicleCompanyID } if let vehicleMetaID = objAppShareData.dictVichleInfo["vehicleMetaID"]as? String{ self.strVehicleTypeId = vehicleMetaID objAppShareData.strSelectedVehicleMetaId = vehicleMetaID } if let type = objAppShareData.dictVichleInfo["type"]as? String{ self.strDriverType = type } if let license = objAppShareData.dictVichleInfo["license"]as? String{ self.vwImgLicense.isHidden = false self.vwLicense.isHidden = true if license != "" { let url = URL(string: license) self.imgLicense.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "inactive_profile_ico")) self.isLicense = true } } if let registration = objAppShareData.dictVichleInfo["registration"]as? String{ self.vwImgRegistration.isHidden = false self.vwRegistration.isHidden = true if registration != "" { let url = URL(string: registration) self.imgRegistration.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "inactive_profile_ico")) self.isRegistration = true } } } func setUI(){ self.vwBlur.isHidden = true // self.vwImgLicense.isHidden = true // self.vwImgRegistration.isHidden = true self.vwYear.setCornerRadiusQwafy(vw: self.vwYear) self.vwMake.setCornerRadiusQwafy(vw: self.vwMake) self.vwModel.setCornerRadiusQwafy(vw: self.vwModel) self.vwType.setCornerRadiusQwafy(vw: self.vwType) self.vwNumber.setCornerRadiusQwafy(vw: self.vwNumber) self.vwImgRegistration.setCornerRadius(radius: 14) self.vwImgLicense.setCornerRadius(radius: 14) self.vwUpdate.setButtonView(vwOuter : self.vwUpdate , vwImage : self.vwImgUpdate, btn: self.btnUpdate ) self.vwTable.roundCorners(corners: [.topLeft, .topRight], radius: 20.0) self.vwBlur.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:)))) self.setData() } @objc func tap(_ gestureRecognizer: UITapGestureRecognizer) { self.vwBlur.isHidden = true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == self.txtYear{ // self.txtYear.resignFirstResponder() self.txtModel.becomeFirstResponder() }else if textField == self.txtModel{ // self.txtModel.resignFirstResponder() self.txtNumber.becomeFirstResponder() }else if textField == self.txtNumber{ self.txtNumber.resignFirstResponder() } return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let str = (textField.text! as NSString).replacingCharacters(in: range, with: string) if textField == self.txtYear{ return checkAccountNumberFormat(string: string, str: str) }else if textField == txtModel{ let maxLength = 30 let currentString: NSString = textField.text! as NSString let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString if newString.length == 31{ //textField.resignFirstResponder() } return newString.length <= maxLength }else if textField == txtNumber{ let maxLength = 20 let currentString: NSString = textField.text! as NSString let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString if newString.length == 21{ //textField.resignFirstResponder() } return newString.length <= maxLength } else{ return true } } func checkAccountNumberFormat(string: String?, str: String?) -> Bool{ var isbool: Bool = false if string == ""{ isbool = true } else if str!.count > 4 { isbool = false }else{ isbool = true } return isbool } func validationForBasicInfo(){ self.txtYear.text = self.txtYear.text!.trimmingCharacters(in: .whitespacesAndNewlines) self.txtModel.text = self.txtModel.text!.trimmingCharacters(in: .whitespacesAndNewlines) self.txtNumber.text = self.txtNumber.text!.trimmingCharacters(in: .whitespacesAndNewlines) // let strYear = self.txtYear.text?.count ?? 0 // let strModel = self.txtModel.text?.count ?? 0 // let strNumber = self.txtNumber.text?.count ?? 0 let currentYear = Calendar.current.component(.year, from: Date()) let enterYear = Int(txtYear.text ?? "") if self.txtYear.text?.isEmpty == true{ objAlert.showAlert(message: BlankYear.localize, title: kAlert.localize, controller: self) } else if self.txtModel.text?.isEmpty == true{ objAlert.showAlert(message: BlankModel.localize, title: kAlert.localize, controller: self) } // else if strModel < 5{ // objAlert.showAlert(message: ModelValidation, title: kAlert, controller: self) // } else if self.lblMake.text?.isEmpty == true{ objAlert.showAlert(message: BlankMake.localize, title: kAlert.localize, controller: self) }else if self.lblType.text?.isEmpty == true{ objAlert.showAlert(message: BlankVehicle, title: kAlert.localize, controller: self) }else if self.txtNumber.text?.isEmpty == true{ objAlert.showAlert(message: BlankNumber.localize, title: kAlert.localize, controller: self) } // else if strNumber < 5 { // objAlert.showAlert(message: NumberValidation, title: kAlert, controller: self) // } // else if self.pickedImageRegistration == nil{ // objAlert.showAlert(message: BlankRegistration, title: kAlert, controller: self) // }else if self.pickedImageLicense == nil{ // objAlert.showAlert(message: BlankLicense, title: kAlert, controller: self) // } else if self.isRegistration == false{ objAlert.showAlert(message: BlankRegistration.localize, title: kAlert.localize, controller: self) }else if self.isLicense == false{ objAlert.showAlert(message: BlankLicense.localize, title: kAlert.localize, controller: self) }else if enterYear ?? 0 > currentYear { objAlert.showAlert(message: "You can't enter future date", title: kAlert.localize, controller: self) } else{ // objAlert.showAlert(message: "Under Development", title: kAlert, controller: self) self.callWsForVehicleDetails() } } func localization(){ self.lblLocEditProfileHeader.text = "Edit_Profile".localize self.lblLocPleaseFillAllInfo.text = "Please,fill_all_information".localize self.lblLocModel.text = "Model_Number".localize self.lblLocVehicleType.text = "Vehicle_Type".localize self.lblVehicleNumber.text = "Vehicle_Number".localize self.lblLocYear.text = "Year".localize self.lblLocRegistration.text = "Registration".localize self.lblLocLicense.text = "License".localize self.lblLocMake.text = "Make".localize self.lblMakePalceHolder.text = "Select_Make".localize self.lblTypePalceHolder.text = "Select_vehicle_type".localize self.lblLocUploadLicense.text = "Upload_License".localize self.lblLocUploadId.text = "Upload_Id".localize self.txtYear.placeholder = "Enter_year".localize self.txtModel.placeholder = "Model_Number".localize self.txtNumber.placeholder = "Enter_vehicle_number".localize self.btnUpdate.setTitle("Update_Profile".localize, for: .normal) self.btnCancel.setTitle("Cancel".localize, for: .normal) } //MARK: - Button Actions @objc func handleTap(_ sender: UITapGestureRecognizer? = nil) { self.view.endEditing(true) // handling code } @IBAction func btnBack(_ sender: UIButton) { self.view.endEditing(true) self.navigationController?.popViewController(animated: true) } @IBAction func btnUpdateAction(_ sender: UIButton) { self.view.endEditing(true) self.validationForBasicInfo() // objAlert.showAlert(message: "Under Development", title: kAlert, controller: self) } @IBAction func btnRegistration(_ sender: UIButton) { self.view.endEditing(true) print("btn Registration is click") self.strType = 0 self.setImage() } @IBAction func btnLicense(_ sender: UIButton) { self.view.endEditing(true) print("btn License is click") self.strType = 1 self.setImage() } @IBAction func btnDeleteRegistration(_ sender: UIButton) { self.view.endEditing(true) print("btn DeleteRegistration is click") self.strType = 0 self.setImage() } @IBAction func btnDeleteLicense(_ sender: UIButton) { self.view.endEditing(true) print("btn DeleteLicense is click") // self.vwImgLicense.isHidden = true // self.vwLicense.isHidden = false // self.isLicense = false self.strType = 1 self.setImage() } @IBAction func btnMake(_ sender: Any) { self.view.endEditing(true) self.strMake = 0 self.showBotttomSheet(arr: self.arrMake,str: "Select_Make".localize, makeId : self.strMakeId, vehicleTypeId: "") } @IBAction func btnType(_ sender: Any) { self.view.endEditing(true) if self.strMakeId == "" { objAlert.showAlert(message: "Please_select_make_first".localize, title: kAlert.localize, controller: self) }else{ // self.vwBlur.isHidden = false // self.lblTableHeader.text = "Select Vehicle Type" // self.tblBottom.reloadData() // self.callWsForUserVehicleRole() self.strMake = 1 self.showBotttomSheet(arr: self.arrType,str: "Select_vehicle_type".localize, makeId : "", vehicleTypeId: self.strVehicleTypeId) } } func showBotttomSheet(arr : Array<Any>, str: String , makeId: String , vehicleTypeId: String){ let sb = UIStoryboard.init(name: "TaxiDProfile", bundle:Bundle.main) let vc = sb.instantiateViewController(withIdentifier:"VehicleSheetVC") as! VehicleSheetVC vc.arrBottom = arr as! [VehicleModel] vc.strHeader = str vc.strMakeId = makeId vc.strVehicleTypeId = vehicleTypeId vc.modalPresentationStyle = .overCurrentContext vc.delegate = self // new deepak vc.closerCallApi = { isClearListData in if isClearListData{ self.isFirstAppear = false self.callWsForUserVehicleRole() } } // new deepak self.present(vc, animated: false, completion: nil) } func sendObjFromVehicleSheetVC(obj: VehicleModel) { self.arrType.removeAll() print("obj is \(obj.strModel)") self.arrType = obj.arrVehicleType print("arrType count is \(self.arrType.count)") } //MARK: step 6 finally use the method of the contract func sendDataFromVehicleSheetVC(strId: String, strName: String) { print(" my strId is \(strId)") print(" my strName is \(strName)") if self.strMake == 0 { self.strMakeId = strId self.lblMake.text = strName self.strMakeSelection = strName self.lblMakePalceHolder.isHidden = true // new deepak print(" self.strMakeId is \(self.strMakeId)") print(" objAppShareData.strSelectedVehicleCompanyId is \(objAppShareData.strSelectedVehicleCompanyId)") self.lblTypePalceHolder.isHidden = false self.lblType.isHidden = true self.strVehicleTypeId = "" self.lblType.text = "" // new deepak } else if self.strMake == 1 { self.lblTypePalceHolder.isHidden = true self.lblType.isHidden = false self.strVehicleTypeId = strId self.lblType.text = strName self.strTypeSelection = strName self.lblTypePalceHolder.isHidden = true } } @IBAction func btnCancle(_ sender: Any) { self.view.endEditing(true) self.vwBlur.isHidden = true } @IBAction func btnCancleCross(_ sender: Any) { self.view.endEditing(true) //self.ResetRoot() self.navigationController?.popViewController(animated: true) } func ResetRoot(){ if self.isFormFoodDriver == true{ for vc in (self.navigationController?.viewControllers) ?? []{ if vc is FoodDriverProfileVC { self.navigationController?.popToViewController(vc, animated: false) break }else{ self.navigationController?.popViewController(animated: true) } } } else { for vc in (self.navigationController?.viewControllers) ?? []{ if vc is TaxiDriverProfileVC{ self.navigationController?.popToViewController(vc, animated: false) break }else{ self.navigationController?.popViewController(animated: true) } } } } //MARK: - imagePicker Actions func setImage(){ imagePicker.allowsEditing = true imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary let alert:UIAlertController=UIAlertController(title: "Choose_Image".localize, message: nil, preferredStyle: UIAlertController.Style.actionSheet) let cameraAction = UIAlertAction(title: "Camera".localize, style: UIAlertAction.Style.default) { UIAlertAction in self.openCamera() } let galleryAction = UIAlertAction(title: "Gallery".localize, style: UIAlertAction.Style.default) { UIAlertAction in self.openGallery() } let cancelAction = UIAlertAction(title:"Cancel".localize, style: UIAlertAction.Style.cancel) { UIAlertAction in } alert.addAction(cameraAction) alert.addAction(galleryAction) alert.addAction(cancelAction) alert.popoverPresentationController?.sourceView = self.view self.present(alert, animated: true, completion: nil) } // Open camera func openCamera() { if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera)) { imagePicker.sourceType = UIImagePickerController.SourceType.camera imagePicker.modalPresentationStyle = .fullScreen imagePicker.allowsEditing = true self .present(imagePicker, animated: true, completion: nil) } else { self.openGallery() print("Camera is not open in Simulator") } } // Open gallery func openGallery() { imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary imagePicker.modalPresentationStyle = .fullScreen imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let editedImage = info[.editedImage] as? UIImage { if self.strType == 0 { self.isRegistration = true self.pickedImageRegistration = editedImage self.vwImgRegistration.isHidden = false self.vwRegistration.isHidden = true // self.imgRegistration.image = self.pickedImage self.imgRegistration.image = self.pickedImageRegistration self.registrationUpdate = true }else{ self.isLicense = true self.pickedImageLicense = editedImage self.vwImgLicense.isHidden = false self.vwLicense.isHidden = true // self.imgLicense.image = self.pickedImage self.imgLicense.image = self.pickedImageLicense self.licenseUpdate = true } imagePicker.dismiss(animated: true, completion: nil) } // else if let originalImage = info[.originalImage] as? UIImage { // // self.pickedImage = originalImage // // self.imgProfile.image = pickedImage // // imagePicker.dismiss(animated: true, completion: nil) // // } } } extension EditVehicleInfoVC { // TODO: Webservice For UserVehicleRole func callWsForUserVehicleRole(){ if !objWebServiceManager.isNetworkAvailable(){ objWebServiceManager.StopIndicator() objAlert.showAlert(message: NoNetwork.localize , title: kAlert.localize , controller: self) return } if self.isFirstAppear == true{ objWebServiceManager.StartIndicator() } //objWebServiceManager.StartIndicator() var param: [String: Any] = [:] param = [ WsParam.vehicleType: self.strDriverType ] as [String : Any] print(param) objWebServiceManager.requestGet(strURL: WsUrl.vehicleList ,Queryparams: param, body: param, strCustomValidation: "", success: {response in print(response) objWebServiceManager.StopIndicator() let status = (response["status"] as? String) let message = (response["message"] as? String) if status == "success" { let dict = response["data"] as? [String:Any] // if let data = response["data"] as? [String:Any] if let arrVehicleData = dict?["vehicle_list"] as? [[String:Any]]{ self.arrMake.removeAll() self.arrType.removeAll() // if let arrVehicleData = dict["vehicle_list"] as! [[String: Any]]{ for dictVehicleData in arrVehicleData{ let objVehicleData = VehicleModel.init(dict: dictVehicleData) self.arrMake.append(objVehicleData) } let objData = self.arrMake.filter(({ $0.strVehicleCompanyId == self.strMakeId })) if objData.count > 0 { self.arrType = objData[0].arrVehicleType } // for obj in self.arrMake{ // // new deepak // print("self.strMakeId is \(self.strMakeId)") // if self.strMakeId == obj.strVehicleCompanyId {. // self.arrType.append(contentsOf: obj.arrVehicleType) // // }// new deepak // } print("arrMake count is \(self.arrMake.count)") } self.tblBottom.reloadData() }else { objAlert.showAlert(message:message ?? "", title: kAlert.localize, controller: self) } }, failure: { (error) in print(error) // objWebServiceManager.StopIndicator() objAlert.showAlert(message:kErrorMessage.localize, title: kAlert.localize, controller: self) }) } // TODO: Webservice For Vehicle Details func callWsForVehicleDetails(){ if !objWebServiceManager.isNetworkAvailable(){ objWebServiceManager.StopIndicator() objAlert.showAlert(message: NoNetwork.localize, title: kAlert.localize , controller: self) return } objWebServiceManager.StartIndicator() var param = [String:Any]() var arrDataa = [Data]() var arrParam = [String]() var imageData1 : Data? var imageData2 : Data? // let imageData1 = (self.pickedImageRegistration?.jpegData(compressionQuality: 1.0)) ?? (self.imgRegistration.image?.jpegData(compressionQuality: 1.0)) // // let imageData2 = (self.pickedImageLicense?.jpegData(compressionQuality: 1.0)) ?? (self.imgLicense.image?.jpegData(compressionQuality: 1.0)) if self.pickedImageRegistration != nil{ // let jpegData = pickedImageRegistration?.jpegData(compressionQuality: 1.0) imageData1 = objAppShareData.compressImage(image: self.pickedImageRegistration!) as Data? // (img?.jpegData(compressionQuality: 1.0)) ?? (self.imgRegistration.image?.jpegData(compressionQuality: 1.0)) // arrDataa.append(imageData1!) } if self.pickedImageLicense != nil{ imageData2 = objAppShareData.compressImage(image: self.pickedImageLicense!) as Data? // arrDataa.append(imageData2!) } if self.registrationUpdate == true { arrDataa.append(imageData1!) arrParam.append(contentsOf: ["registration_image"]) } if self.licenseUpdate == true{ arrDataa.append(imageData2!) arrParam.append(contentsOf: ["license_image"]) }else{ arrParam.append(contentsOf: ["",""]) } param = ["vehicle_info_id": self.strVehicleInfoId, "year": self.txtYear.text ?? "", "model_number":self.txtModel.text ?? "", "vehicle_number": self.txtNumber.text ?? "", "make": self.strMakeId, "vehicle_type": self.strVehicleTypeId ] print(param) objWebServiceManager.uploadMultipartMultipleImagesData(strURL: WsUrl.updateVehicleInfo, params: param, showIndicator: false, imageData: imageData1, imageToUpload: arrDataa, imagesParam: arrParam, fileName: "", mimeType: "image/jpeg", success: { response in print(response) objWebServiceManager.StopIndicator() let status = (response["status"] as? String) let message = (response["message"] as? String) if status == "success" { self.updateAlert(msg: "Profile_updated_successfully".localize) // self.ResetRoot() } else { objAlert.showAlert(message:message ?? "", title: kAlert.localize, controller: self) } }, failure: { (error) in print(error) objWebServiceManager.StopIndicator() objAlert.showAlert(message:kErrorMessage.localize, title: kAlert.localize, controller: self) }) } func updateAlert(msg : String){ let alert = UIAlertController(title: kAlert.localize, message: msg , preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK".localize, style: UIAlertAction.Style.default, handler: { (action: UIAlertAction!) in // self.navigationController?.popViewController(animated: true) self.ResetRoot() })) self.present(alert, animated: true, completion: nil) } } extension EditVehicleInfoVC : UITableViewDelegate ,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.arrMake.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tblBottom.dequeueReusableCell(withIdentifier: "BasicInfoCell")as! BasicInfoCell return cell } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { DispatchQueue.main.async { } } @objc func buttonClicked(sender:UIButton) { } }
// // MedicineModel.swift // szenzormodalitasok // // Created by Tóth Zoltán on 2021. 05. 07.. // Copyright © 2021. Tóth Zoltán. All rights reserved. // // Imports import Foundation // MedicinesID typealias typealias MedicineID = Int // MedicineModel struct struct MedicineModel : Codable { // Variables let medicineID: MedicineID let medicineName: String let factoryMedicineName: String let activeSubstanceName: String let package: String let recommendedDosage: String let administrationMethod: String let suggestionForUse: String let warningsContraindications: String // Null Object Design Pattern static var empty = MedicineModel( medicineID: 0, medicineName: "", factoryMedicineName: "", activeSubstanceName: "", package: "", recommendedDosage: "", administrationMethod: "", suggestionForUse: "", warningsContraindications: "") }
/** * Copyright IBM Corporation 2016, 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Kitura import KituraNet import LoggerAPI import Credentials import Foundation // MARK CredentialsGitHub /// Authentication using GitHub web login with OAuth. /// See [GitHub manual](https://developer.github.com/v3/oauth/#web-application-flow) /// for more information. public class CredentialsGitHub: CredentialsPluginProtocol { private var clientId: String private var clientSecret: String private let scopes: [String] /// The URL that GitHub redirects back to. public var callbackUrl: String /// The User-Agent to be passed along on GitHub API calls. /// User-Agent must be set in order to access GitHub API (i.e., to get user profile). /// See [GitHub manual](https://developer.github.com/v3/#user-agent-required) /// for more information. public private(set) var userAgent: String /// The name of the plugin. public let name = "GitHub" /// An indication as to whether the plugin is redirecting or not. public let redirecting = true /// User profile cache. public var usersCache: NSCache<NSString, BaseCacheElement>? /// A delegate for `UserProfile` manipulation. public let userProfileDelegate: UserProfileDelegate? /// Initialize a `CredentialsGitHub` instance. /// /// - Parameter clientId: The Client ID of the app in the GitHub Developer applications. /// - Parameter clientSecret: The Client Secret of the app in the GitHub Developer applications. /// - Parameter callbackUrl: The URL that GitHub redirects back to. public init (clientId: String, clientSecret: String, callbackUrl: String, userAgent: String?=nil, options: [String: Any] = [:]) { self.clientId = clientId self.clientSecret = clientSecret self.callbackUrl = callbackUrl self.scopes = options[CredentialsGitHubOptions.scopes] as? [String] ?? [] self.userAgent = userAgent ?? "Kitura-CredentialsGitHub" self.userProfileDelegate = options[CredentialsGitHubOptions.userProfileDelegate] as? UserProfileDelegate } /// Authenticate incoming request using GitHub web login with OAuth. /// /// - Parameter request: The `RouterRequest` object used to get information /// about the request. /// - Parameter response: The `RouterResponse` object used to respond to the /// request. /// - Parameter options: The dictionary of plugin specific options. /// - Parameter onSuccess: The closure to invoke in the case of successful authentication. /// - Parameter onFailure: The closure to invoke in the case of an authentication failure. /// - Parameter onPass: The closure to invoke when the plugin doesn't recognize the /// authentication data in the request. /// - Parameter inProgress: The closure to invoke to cause a redirect to the login page in the /// case of redirecting authentication. public func authenticate (request: RouterRequest, response: RouterResponse, options: [String:Any], onSuccess: @escaping (UserProfile) -> Void, onFailure: @escaping (HTTPStatusCode?, [String:String]?) -> Void, onPass: @escaping (HTTPStatusCode?, [String:String]?) -> Void, inProgress: @escaping () -> Void) { if let code = request.queryParameters["code"] { // query contains code: exchange code for access token var requestOptions: [ClientRequest.Options] = [] requestOptions.append(.schema("https://")) requestOptions.append(.hostname("github.com")) requestOptions.append(.method("POST")) requestOptions.append(.path("/login/oauth/access_token?client_id=\(clientId)&redirect_uri=\(callbackUrl)&client_secret=\(clientSecret)&code=\(code)")) var headers = [String:String]() headers["Accept"] = "application/json" requestOptions.append(.headers(headers)) let requestForToken = HTTP.request(requestOptions) { fbResponse in if let fbResponse = fbResponse, fbResponse.statusCode == .OK { // get user profile with access token do { var body = Data() try fbResponse.readAllData(into: &body) if let jsonBody = try JSONSerialization.jsonObject(with: body, options: []) as? [String : Any], let token = jsonBody["access_token"] as? String { requestOptions = [] requestOptions.append(.schema("https://")) requestOptions.append(.hostname("api.github.com")) requestOptions.append(.method("GET")) requestOptions.append(.path("/user")) headers = [String:String]() headers["Accept"] = "application/json" headers["User-Agent"] = self.userAgent headers["Authorization"] = "token \(token)" requestOptions.append(.headers(headers)) let requestForProfile = HTTP.request(requestOptions) { profileResponse in if let profileResponse = profileResponse, profileResponse.statusCode == .OK { do { body = Data() try profileResponse.readAllData(into: &body) if let userDictionary = try JSONSerialization.jsonObject(with: body, options: []) as? [String : Any], let userProfile = self.createUserProfile(from: userDictionary) { if let delegate = self.userProfileDelegate { delegate.update(userProfile: userProfile, from: userDictionary) } onSuccess(userProfile) return } } catch { Log.error("Failed to read \(self.name) response") } } else { onFailure(nil, nil) } } requestForProfile.end() } } catch { Log.error("Failed to read \(self.name) response") } } else { onFailure(nil, nil) } } requestForToken.end() } else { // Log in var scopeParameters = "" if !scopes.isEmpty { scopeParameters = "&scope=" for scope in scopes { // space delimited list: https://developer.github.com/v3/oauth/#parameters // trailing space character is probably OK scopeParameters.append(scope + " ") } } do { try response.redirect("https://github.com/login/oauth/authorize?client_id=\(clientId)&redirect_uri=\(callbackUrl)&response_type=code\(scopeParameters)") inProgress() } catch { Log.error("Failed to redirect to \(name) login page") } } } // GitHub user profile response format looks like this: /* { "login" : "<string>", "id" : <int>, "avatar_url" : "<string>", "gravatar_id" : "", "url" : "<string>", "html_url" : "<string>", "followers_url" : "<string>", "following_url" : "<string>", "gists_url" : "<string>", "starred_url" : "<string>", "subscriptions_url" : "<string>", "organizations_url" : "<string>", "repos_url" : "<string>", "events_url" : "<string>", "received_events_url" : "<string>", "type" : "User", "site_admin" : <bool>, "name" : "<string>", "company" : "<string>", "blog" : null, "location" : null, "email" : null, "hireable" : null, "bio" : null, "public_repos" : <int>, "public_gists" : <int>, "followers" : <int>, "following" : <int>, "created_at" : "<time stamp string>", "updated_at" : "<time stamp string>" } */ private func createUserProfile(from userDictionary: [String: Any]) -> UserProfile? { guard let id = userDictionary["id"] as? Int else { return nil } let name = userDictionary["name"] as? String ?? "" var userProfileEmails: [UserProfile.UserProfileEmail]? if let email = userDictionary["email"] as? String { userProfileEmails = [UserProfile.UserProfileEmail(value: email, type: "public")] } var userProfilePhotos: [UserProfile.UserProfilePhoto]? if let photoURL = userDictionary["avatar_url"] as? String { userProfilePhotos = [UserProfile.UserProfilePhoto(photoURL)] } return UserProfile(id: String(id), displayName: name, provider: self.name, emails: userProfileEmails, photos: userProfilePhotos) } }
// // RoundViewController.swift // Tabu // // Created by Damian Ferens on 25.10.2016. // Copyright © 2016 Damian Ferens. All rights reserved. // import UIKit import UICircularProgressRing import MZTimerLabel var winnerTeam = "" var maxPoints = 0 extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } } class RoundViewController: UIViewController { @IBOutlet weak var scoreTextField: UITextField! @IBOutlet var timerLabel: MZTimerLabel! @IBOutlet weak var tabooWordTextField: UITextField! @IBOutlet weak var firstWordTextField: UITextField! @IBOutlet weak var secondWordTextField: UITextField! @IBOutlet weak var thirdWordTextField: UITextField! @IBOutlet weak var fourthWordTextField: UITextField! @IBOutlet weak var fifthWordTextField: UITextField! @IBOutlet weak var viewTableWithWords: UIView! @IBOutlet weak var viewTabooWord: UIView! @IBOutlet var circuralTimer: UICircularProgressRingView! var seconds = 0 var timer = Timer() func fillTextFields() { let nextWord = ContentProvider.sharedInstance.getNextRandomCard() self.tabooWordTextField.text = nextWord[0].keyWord self.firstWordTextField.text = nextWord[0].words[0] self.secondWordTextField.text = nextWord[0].words[1] self.thirdWordTextField.text = nextWord[0].words[2] self.fourthWordTextField.text = nextWord[0].words[3] self.fifthWordTextField.text = nextWord[0].words[4] } func circuralTimerColor(player: Player) { let userDefault = UserDefaults.standard var teamColorName = String() if (player == Player.firstPlayer){ teamColorName = "First team color" self.circuralTimer.outerRingColor = UIColor(netHex:0xCD8B1F) } else { teamColorName = "Second team color" self.circuralTimer.outerRingColor = UIColor(netHex:0x225EA4) } if (userDefault.value(forKey: teamColorName) != nil){ let temp = userDefault.value(forKey: teamColorName) as! String switch temp{ case "orangeTeamColor": let color = UIColor(netHex:0xCD8B1F) self.circuralTimer.outerRingColor = color case "blueTeamColor": let color = UIColor(netHex:0x225EA4) self.circuralTimer.outerRingColor = color case "yellowTeamColor": let color = UIColor(netHex:0xE8DA2B) self.circuralTimer.outerRingColor = color case "redTeamColor": let color = UIColor(netHex:0xFF5454) self.circuralTimer.outerRingColor = color case "violetTeamColor": let color = UIColor(netHex:0xB231CD) self.circuralTimer.outerRingColor = color case "greenTeamColor": let color = UIColor(netHex:0x7ED321) self.circuralTimer.outerRingColor = color default: print("error") } } } func checkPoints() { if(GameViewController.updateScore.teamChooser == Player.secondPlayer){ if (GameViewController.updateScore.firstTeamPoints >= maxPoints || GameViewController.updateScore.secondTeamPoints >= maxPoints) { if (GameViewController.updateScore.firstTeamPoints > GameViewController.updateScore.secondTeamPoints) { winnerTeam = GameViewController.teamName.firstTeamName + " wygywają" maxPoints = GameViewController.updateScore.firstTeamPoints print(GameViewController.teamName.firstTeamName) } else if (GameViewController.updateScore.firstTeamPoints == GameViewController.updateScore.secondTeamPoints) { winnerTeam = "Remis" maxPoints = GameViewController.updateScore.firstTeamPoints } else { winnerTeam = GameViewController.teamName.secondTeamName + " wygywają" maxPoints = GameViewController.updateScore.secondTeamPoints print(GameViewController.teamName.secondTeamName) } let vc : AnyObject! = self.storyboard!.instantiateViewController(withIdentifier: "summaryVC") self.show(vc as! UIViewController, sender: vc) timer.invalidate() } else { _ = self.navigationController?.popViewController(animated: true) timer.invalidate() } }else { _ = self.navigationController?.popViewController(animated: true) timer.invalidate() } } func changeTeam() { if(GameViewController.updateScore.teamChooser == Player.firstPlayer){ GameViewController.updateScore.teamChooser = Player.secondPlayer } else if(GameViewController.updateScore.teamChooser == Player.secondPlayer){ GameViewController.updateScore.teamChooser = Player.firstPlayer } } func updateTimer() { self.seconds -= 1 if (self.seconds == 0) { if(GameViewController.updateScore.teamChooser == Player.firstPlayer){ GameViewController.updateScore.teamChooser = Player.secondPlayer _ = self.navigationController?.popViewController(animated: true) timer.invalidate() } else if(GameViewController.updateScore.teamChooser == Player.secondPlayer){ checkPoints() GameViewController.updateScore.teamChooser = Player.firstPlayer } } else { circuralTimer.value = CGFloat(seconds) timerLabel.setCountDownTime(TimeInterval(self.seconds)) } } @IBAction func goodAnswerButton(_ sender: AnyObject) { if(GameViewController.updateScore.teamChooser == Player.firstPlayer){ GameViewController.updateScore.firstTeamPoints += 1 self.scoreTextField.text = String(GameViewController.updateScore.firstTeamPoints) } else { GameViewController.updateScore.secondTeamPoints += 1 self.scoreTextField.text = String(GameViewController.updateScore.secondTeamPoints) } fillTextFields() } @IBAction func wrongAnswerButton(_ sender: AnyObject) { if(GameViewController.updateScore.teamChooser == Player.firstPlayer){ GameViewController.updateScore.firstTeamPoints -= 1 self.scoreTextField.text = String(GameViewController.updateScore.firstTeamPoints) } else { GameViewController.updateScore.secondTeamPoints -= 1 self.scoreTextField.text = String(GameViewController.updateScore.secondTeamPoints) } fillTextFields() } @IBAction func backButton(_ sender: AnyObject) { let alert = UIAlertController(title: "Czy na pewno chcesz wyjść?", message: "", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Graj dalej", style: UIAlertActionStyle.default, handler: { action in })) alert.addAction(UIAlertAction(title: "Zakończ rundę", style: UIAlertActionStyle.default, handler: { action in self.checkPoints() self.changeTeam() })) alert.addAction(UIAlertAction(title: "Zakończ grę", style: UIAlertActionStyle.destructive, handler: { action in _ = self.navigationController?.popToRootViewController(animated: true) clearPoints() })) self.present(alert, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() viewTableWithWords.layer.cornerRadius = 7.0 viewTableWithWords.layer.borderWidth = 1.5 viewTableWithWords.layer.borderColor = UIColor.white.cgColor viewTabooWord.layer.cornerRadius = 5.0 viewTabooWord.layer.borderWidth = 1.5 viewTabooWord.layer.borderColor = UIColor.white.cgColor maxPoints = 50 self.seconds = 60 fillTextFields() if(GameViewController.updateScore.teamChooser == Player.firstPlayer){ self.scoreTextField.text = String(GameViewController.updateScore.firstTeamPoints) } else { self.scoreTextField.text = String(GameViewController.updateScore.secondTeamPoints) } let userDefault = UserDefaults.standard if(userDefault.value(forKey: "Time") != nil){ self.seconds = userDefault.value(forKey: "Time") as! Int } if(userDefault.value(forKey: "Max Points") != nil){ maxPoints = (userDefault.value(forKey: "Max Points") as! Int) } circuralTimerColor(player: GameViewController.updateScore.teamChooser) timerLabel.timeFormat = "m:ss" timerLabel.timeLabel.textColor = UIColor.white timerLabel.timerType = MZTimerLabelTypeTimer timerLabel.setCountDownTime(TimeInterval(self.seconds)) circuralTimer.value = CGFloat(self.seconds) circuralTimer.maxValue = CGFloat(self.seconds) timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(RoundViewController.updateTimer)), userInfo: nil, repeats: true) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // Event.swift // UdeChile // // Created by Alejandro Villalobos on 9/8/19. // Copyright © 2019 Club Universidad de Chile. All rights reserved. // import Foundation import EventKit struct EventManager { let eventStore : EKEventStore = EKEventStore() func addEventToCalendar(startingDate: Date, title: String){ var success = false eventStore.requestAccess(to: .event) { (granted, error) in if (granted) && (error == nil) { //print("granted \(granted)") //print("error \(error)") let event:EKEvent = EKEvent(eventStore: self.eventStore) event.title = title event.startDate = startingDate event.endDate = startingDate+7400 event.notes = "Nota creada en app UdeChile" event.calendar = self.eventStore.defaultCalendarForNewEvents do { try self.eventStore.save(event, span: .thisEvent) } catch let error as NSError { print("Failed to save event with error : \(error)") } print("Event Saved") } else{ print("Failed to save event with error : \(String(describing: error)) or access not granted") } } } }
// // PostsDetailRouter.swift // DemoVIPER // // Created by Mahesh Mavurapu on 21/11/19. // Copyright © 2019 Mahesh Mavurapu. All rights reserved. // import Foundation import UIKit protocol PostDetailRouterProtocol: class { static func createPostDetailModule(forPost post: PostsModel) -> UIViewController } class PostsDetailRouter: PostDetailRouterProtocol { class func createPostDetailModule(forPost post: PostsModel) -> UIViewController { let viewController = mainStoryboard.instantiateViewController(withIdentifier: "PostsDetailViewController") if let view = viewController as? PostsDetailViewController { let presenter: PostDetailPresenterProtocol = PostsDetailPresenter() let router: PostDetailRouterProtocol = PostsDetailRouter() view.presenter = presenter presenter.view = view presenter.post = post presenter.router = router return viewController } return UIViewController() } static var mainStoryboard: UIStoryboard { return UIStoryboard(name: "Main", bundle: Bundle.main) } }
// // TweetTableViewCell.swift // Smashtag // // Created by hyf on 16/10/20. // Copyright © 2016年 hyf. All rights reserved. // import UIKit import Twitter class TweetTableViewCell: UITableViewCell { @IBOutlet weak var tweetProfileImageView: UIImageView! @IBOutlet weak var tweetScreenNameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var tweetCreatedLabel: UILabel! var tweet: Twitter.Tweet? { didSet { updateUI() } } fileprivate func updateUI() { // reset any existing tweet information tweetTextLabel?.attributedText = nil tweetScreenNameLabel?.text = nil tweetProfileImageView?.image = nil tweetCreatedLabel?.text = nil // load new information from our tweet (if any) if let tweet = self.tweet { tweetTextLabel?.text = tweet.text if tweetTextLabel?.text != nil { for _ in tweet.media { tweetTextLabel.text! += " 📷" } //Enhance Smashtag from lecture to highlight (in a different color for each) hashtags, //urls and user screen names mentioned in the text of each Tweet //tweetTextLabel.attributedText = attributedString(tweet, string: tweetTextLabel.text!) tweetTextLabel?.attributedText = getColorfulAttributedText(tweet, plainText: tweetTextLabel.text!) } tweetScreenNameLabel?.text = "\(tweet.user)" // tweet.user.description if let profileImageURL = tweet.user.profileImageURL { DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { let imageData = try? Data(contentsOf: profileImageURL) DispatchQueue.main.async { if profileImageURL == self.tweet?.user.profileImageURL { if imageData != nil { self.tweetProfileImageView?.image = UIImage(data: imageData!) } } } } } let formatter = DateFormatter() if Date().timeIntervalSince(tweet.created) > 24*60*60 { formatter.dateStyle = DateFormatter.Style.short } else { formatter.timeStyle = DateFormatter.Style.short } tweetCreatedLabel?.text = formatter.string(from: tweet.created) } } fileprivate struct MentionColor { static let user = UIColor.purple static let hashtag = UIColor.brown static let url = UIColor.blue } /* tweetTextLabel.attributedText = attributedString(tweet, string: tweetTextLabel.text!) private struct AttributedItem { var range: NSRange var color: UIColor } private func attributedString(tweet: Twitter.Tweet, string: String) -> NSAttributedString { var attributedList = [AttributedItem]() var attributedItems = [AttributedItem]() // user mention attributedItems = tweet.userMentions.map { (mention: Mention) -> AttributedItem in return AttributedItem(range: mention.nsrange,color: UIColor.purpleColor()) } attributedList += attributedItems // urls attributedItems = tweet.urls.map { (mention: Mention) -> AttributedItem in return AttributedItem(range: mention.nsrange,color: UIColor.blueColor()) } attributedList += attributedItems // hashtags attributedItems = tweet.hashtags.map { (mention: Mention) -> AttributedItem in return AttributedItem(range: mention.nsrange,color: UIColor.brownColor()) } attributedList += attributedItems let attributedString = NSMutableAttributedString(string: string) for item in attributedList { attributedString.addAttribute(NSForegroundColorAttributeName, value: item.color, range: item.range) } return attributedString } */ fileprivate func getColorfulAttributedText(_ tweet: Twitter.Tweet, plainText: String) -> NSAttributedString { let attributedString = NSMutableAttributedString(string: plainText) attributedString.setMentionsColor(tweet.userMentions, color: MentionColor.user) attributedString.setMentionsColor(tweet.hashtags, color: MentionColor.hashtag) attributedString.setMentionsColor(tweet.urls, color: MentionColor.url) return attributedString } } private extension NSMutableAttributedString { func setMentionsColor(_ mentions: [Twitter.Mention], color: UIColor) { for mention in mentions { addAttribute(NSForegroundColorAttributeName, value: color, range: mention.nsrange) } } }