text
stringlengths
8
1.32M
// swift-tools-version:5.8 import PackageDescription let package = Package( name: "r2pipe", products: [ .library(name: "r2pipe", targets: ["r2pipe"]), ], dependencies: [], targets: [ .target(name: "r2pipe", path: ".", sources: ["r2pipe.swift", "r2pipeNative.swift"]), ] )
// // ArticleDetailsViewController.swift // ThePaper // // Created by Gautier Billard on 18/03/2020. // Copyright © 2020 Gautier Billard. All rights reserved. // import UIKit import WebKit class ArticleDetailsViewController: UIViewController { private var webView = WKWebView() private let k = K() var articleURL = "" override func viewDidLoad() { super.viewDidLoad() addWebView() addDismissButton() print(articleURL) let url = URL(string: articleURL) let urlRequest = URLRequest(url: url!) webView.load(urlRequest) self.view.alpha = 0.0 UIView.animate(withDuration: 0.3) { self.view.alpha = 1.0 } } private func addDismissButton() { let dismissButton = UIButton() dismissButton.setImage(UIImage(systemName: "xmark"), for: .normal) dismissButton.backgroundColor = k.mainColorTheme dismissButton.tintColor = .white dismissButton.layer.shadowOffset = CGSize(width: 0, height: 0) dismissButton.layer.shadowRadius = 4 dismissButton.layer.shadowOpacity = 0.2 dismissButton.layer.shadowColor = UIColor.gray.cgColor dismissButton.layer.cornerRadius = 20 self.view.addSubview(dismissButton) //view let fromView = dismissButton //relative to let toView = self.view! fromView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([fromView.leadingAnchor.constraint(equalTo: toView.leadingAnchor, constant: 10), fromView.widthAnchor.constraint(equalToConstant: 40), fromView.topAnchor.constraint(equalTo: toView.topAnchor, constant: 10), fromView.heightAnchor.constraint(equalToConstant: 40)]) dismissButton.addTarget(self, action: #selector(dismissPressed(_:)), for: .touchUpInside) } @IBAction private func dismissPressed(_ sender: UIButton!) { UIView.animate(withDuration: 0.3, animations: { self.view.alpha = 0.0 }) { (_) in self.willMove(toParent: nil) self.view.removeFromSuperview() self.removeFromParent() } } fileprivate func addWebView() { webView.uiDelegate = self self.view.addSubview(webView) //view let fromView = webView //relative to let toView = self.view! fromView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([fromView.leadingAnchor.constraint(equalTo: toView.leadingAnchor, constant: 0), fromView.trailingAnchor.constraint(equalTo: toView.trailingAnchor, constant: 0), fromView.topAnchor.constraint(equalTo: toView.topAnchor, constant: 0), fromView.bottomAnchor.constraint(equalTo: toView.bottomAnchor, constant: 0)]) } } extension ArticleDetailsViewController: WKUIDelegate { func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { } }
import UIKit /* Complete the 'pointsBelong' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER x1 * 2. INTEGER y1 * 3. INTEGER ×2 * 4. INTEGER y2 * 5. INTEGER X3 * 6. INTEGER у3 * 7. INTEGER xp * 8. INTEGER yp * 9. INTEGER xa * 10. INTEGER yq */ ///Solution one func pointsBelong(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int, xp: Int, yp: Int, xq: Int, yq: Int) -> Int { let A = calculateArea(x1: x1, y1: y1, x2: x2, y2: y2, x3: x3, y3: y3) let A2 = calculateArea(x1: x1, y1: y1, x2: xp, y2: yp, x3: x3, y3: y3) let A1 = calculateArea(x1: xp, y1: yp, x2: x2, y2: y2, x3: x3, y3: y3) let A3 = calculateArea(x1: x1, y1: y1, x2: x2, y2: y2, x3: xp, y3: yp) let A4 = calculateArea(x1: xq, y1: yq, x2: x2, y2: y2, x3: x3, y3: y3) let A5 = calculateArea(x1: x1, y1: y1, x2: xq, y2: yq, x3: x3, y3: y3) let A6 = calculateArea(x1: x1, y1: y1, x2: x2, y2: y2, x3: xq, y3: yq) let p = A1 + A2 + A3 let q = A4 + A5 + A6 if A == 0 { return 0 } else if A == p && A != q { return 1 } else if A != p && A == q { return 2 } else if A == p && A == q { return 3 } else if A != p && A != q { return 4 } else { return 0 } } func calculateArea(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int) -> Int { return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2) } /// Solution 2 func length(x1: Int, y1: Int, x2: Int, y2: Int) -> Double { return sqrt(pow(Double(x1 - x2), 2) + pow(Double(y1 - y2), 2)) } func areaTriangle(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int) -> Double { return abs((Double(x1) * Double(y2 - y3) + Double(x2) * Double(y3 - y1) + Double(x3) * Double(y1 - y2)) / 2.0) } func pointsBelongs(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int, xp: Int, yp: Int, xq: Int, yq: Int) -> Int { let AB = length(x1: x1, y1: y1, x2: x2, y2: y2) let BC = length(x1: x2, y1: y2, x2: x3, y2: y3) let AC = length(x1: x1, y1: y2, x2: x3, y2: y3) if AB + AC > BC && BC + AC > AB && AB + BC > AC { let areaABP = areaTriangle(x1: x1, y1: y1, x2: x2, y2: y2, x3: xp, y3: yp) let areaACP = areaTriangle(x1: x1, y1: y1, x2: x3, y2: y3, x3: xp, y3: yp) let areaBCP = areaTriangle(x1: x3, y1: y3, x2: x2, y2: y2, x3: xp, y3: yp) let areaABC = areaTriangle(x1: x1, y1: y1, x2: x2, y2: y2, x3: x3, y3: y3) let p_inside = areaABC == (areaABP + areaACP + areaBCP) let areaABQ = areaTriangle(x1: x1, y1: y1, x2: x2, y2: y2, x3: xq, y3: yq) let areaACQ = areaTriangle(x1: x1, y1: y1, x2: x3, y2: y3, x3: xq, y3: yq) let areaBCQ = areaTriangle(x1: x3, y1: y3, x2: x2, y2: y2, x3: xq, y3: yq) let q_inside = areaABC == (areaABQ + areaACQ + areaBCQ) if p_inside && !q_inside { return 1 } if !p_inside && q_inside { return 2 } if q_inside { return 3 } return 4 } return 0 } pointsBelongs(x1: 3, y1: 1, x2: 7, y2: 1, x3: 5, y3: 5, xp: 1, yp: 1, xq: 2, yq: 2) pointsBelong(x1: 3, y1: 1, x2: 7, y2: 1, x3: 5, y3: 5, xp: 1, yp: 1, xq: 2, yq: 2)
// // DetailViewController.swift // StockSearch // // Created by Michael Zhou on 11/22/17. // Copyright © 2017 michaelzhou. All rights reserved. // import UIKit import Alamofire import SwiftSpinner class DetailViewController: UIViewController { @IBOutlet weak var newsView: UIView! @IBOutlet weak var historyView: UIView! @IBOutlet weak var currentView: UIView! @IBOutlet weak var segmentControl: UISegmentedControl! var ticker: String = "" /** -------------------------- Action Bindings -------------------------- **/ @IBAction func onSegmentChange(_ sender: Any) { switch self.segmentControl.selectedSegmentIndex { case 0: switchCurrentView() case 1: switchHistoryView() case 2: switchNewsView() default: break } } /** -------------------------- Utility Function -------------------------- **/ func switchCurrentView() -> Void { self.newsView.isHidden = true self.historyView.isHidden = true self.currentView.isHidden = false } func switchHistoryView() -> Void { self.newsView.isHidden = true self.currentView.isHidden = true self.historyView.isHidden = false } func switchNewsView() -> Void { self.currentView.isHidden = true self.historyView.isHidden = true self.newsView.isHidden = false } func loadData() -> Void { SwiftSpinner.show("Loading data") self.loadQuote() self.loadNews() } func loadQuote() -> Void { if ticker.count < 0 { return } let quoteUrl = "http://ec2-18-221-164-179.us-east-2.compute.amazonaws.com/api/quote?symbol=" + ticker let currentController = self.childViewControllers[0] as! CurrentViewController Alamofire.request(quoteUrl).responseSwiftyJSON { response in SwiftSpinner.hide() if response.result.isSuccess, let json = response.result.value { // print(json) currentController.onTableDataLoaded(data: json) } else if let error = response.error { print (error) } } } func loadNews() -> Void { if ticker.count < 0 { return } let newsUrl = "http://ec2-18-221-164-179.us-east-2.compute.amazonaws.com/api/news?symbol=" + ticker let newsViewController = self.childViewControllers[2] as! NewsViewController Alamofire.request(newsUrl).responseSwiftyJSON { response in if response.result.isSuccess, let json = response.result.value { newsViewController.onNewsDataLoaded(data: json) } else { print(response.error!) } } } /** -------------------------- View Initialize -------------------------- **/ override func viewDidLoad() { super.viewDidLoad() let currentController = self.childViewControllers[0] as! CurrentViewController currentController.ticker = self.ticker let historyController = self.childViewControllers[1] as! HistoryViewController historyController.ticker = self.ticker self.title = ticker self.switchCurrentView() self.loadData() self.view.addSubview(self.currentView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
// // ProductListViewController.swift // ReadsSwift // // Created by Ketan on 20/05/20. // import UIKit import BlueShift_iOS_SDK class ProductListViewController: BaseViewController { @IBOutlet weak var tableView: UITableView! var locationManager: CLLocationManager? var roundButton = UIButton() var lblBadge: UILabel? var token: NSObjectProtocol? override func viewDidLoad() { super.viewDidLoad() setupUI() setupEvents() registerForLocation() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //set initial badge count BlueshiftInboxManager.getInboxUnreadMessagesCount({ [weak self] status, count in self?.lblBadge?.text = "\(count)" }) //refersh badge count when on inbox data change token = NotificationCenter.default.addObserver(forName: NSNotification.Name(kBSInboxUnreadMessageCountDidChange), object: nil, queue: OperationQueue.current) { Notification in BlueshiftInboxManager.getInboxUnreadMessagesCount({[weak self] status, count in self?.lblBadge?.text = "\(count)" }) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(token!) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // setPositionForFloatingButton() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) navigationController?.interactivePopGestureRecognizer?.isEnabled = false openCachedDeepLink() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) navigationController?.interactivePopGestureRecognizer?.isEnabled = true } func setupUI() { tableView.rowHeight = 120 title = "Product List" addLogoutButton() // addDebugButton() } func addInboxButton() { let filterBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30)) if #available(iOS 13.0, *) { filterBtn.setImage(UIImage(systemName: "bell.fill"), for: .normal) } else { // Fallback on earlier versions } filterBtn.addTarget(self, action: #selector(openInbox), for: .touchUpInside) lblBadge = UILabel.init(frame: CGRect.init(x: 20, y: 0, width: 15, height: 15)) lblBadge?.backgroundColor = UIColor.white lblBadge?.clipsToBounds = true lblBadge?.layer.cornerRadius = 7 lblBadge?.textColor = UIColor.black lblBadge?.adjustsFontSizeToFitWidth = true lblBadge?.textAlignment = .center lblBadge?.text = "0" if let lbl = lblBadge { filterBtn.addSubview(lbl) } self.navigationItem.rightBarButtonItems = [UIBarButtonItem.init(customView: filterBtn)] } func showInboxNavigationVC() { let inboxNavigationVC = BlueshiftInboxNavigationViewController(rootViewController: BlueshiftInboxViewController()) inboxNavigationVC.refreshControlColor = themeColor inboxNavigationVC.unreadBadgeColor = themeColor inboxNavigationVC.activityIndicatorColor = themeColor inboxNavigationVC.inboxDelegate = MobileInboxDelegate() inboxNavigationVC.noMessagesText = "No messages available \n Check again later!" inboxNavigationVC.title = "Mobile Inbox" let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black] inboxNavigationVC.navigationBar.titleTextAttributes = textAttributes inboxNavigationVC.modalPresentationStyle = .fullScreen inboxNavigationVC.navigationBar.tintColor = UIColor.white if #available(iOS 13.0, *) { let appearance = UINavigationBarAppearance() appearance.configureWithOpaqueBackground() appearance.backgroundColor = themeColor appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white] inboxNavigationVC.navigationBar.standardAppearance = appearance inboxNavigationVC.navigationBar.scrollEdgeAppearance = appearance } self.present(inboxNavigationVC, animated:true, completion: nil) } @objc func openInbox() { showInboxNavigationVC() } func addDebugButton() { roundButton = UIButton(type: .custom) roundButton.setTitleColor(UIColor.orange, for: .normal) roundButton.addTarget(self, action: #selector(showDebug), for: UIControl.Event.touchUpInside) view.addSubview(roundButton) } func addLogoutButton() { if (BlueShiftUserInfo.sharedInstance()?.email != nil || BlueShiftUserInfo.sharedInstance()?.retailerCustomerID != nil) { let logoutButton = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(showLogoutConfirmation)) navigationItem.leftBarButtonItem = logoutButton } } func openCachedDeepLink() { if let url = Utils.shared?.deepLinkURL { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.showProductDetail(animated: true, url: url, options: [:]) Utils.shared?.deepLinkURL = nil } } } func setupEvents() { if (BlueShift.sharedInstance()?.config?.enableMobileInbox == true) { addInboxButton() } //Disable push notifications in AppDelegate config and Enable & register for push notifications here if need to ask the push permission after the login BlueShift.sharedInstance()?.config?.enablePushNotification = true BlueShift.sharedInstance()?.appDelegate?.registerForNotification() } func setPositionForFloatingButton() { roundButton.layer.cornerRadius = 37.5 roundButton.backgroundColor = themeColor roundButton.clipsToBounds = true roundButton.setTitle("Debug", for: .normal) roundButton.setTitleColor(.white, for: .normal) roundButton.showsTouchWhenHighlighted = true roundButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ roundButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -25), roundButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -25), roundButton.widthAnchor.constraint(equalToConstant: 75), roundButton.heightAnchor.constraint(equalToConstant: 75)]) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showProductDetails" { if let destinationVC = segue.destination as? ProductDetailViewController { destinationVC.product = sender as? [String : String] } } } func showProductDetail(animated: Bool, product: [String: String]) { performSegue(withIdentifier: "showProductDetails", sender: product) } @objc func showDebug() { performSegue(withIdentifier: "showDebug", sender: nil) } func registerForLocation() { locationManager = CLLocationManager() locationManager?.delegate = self locationManager?.requestWhenInUseAuthorization() } @objc func showLogoutConfirmation() { let alert = UIAlertController(title: "Logout", message: "Are you sure?", preferredStyle: .alert) let yesButton = UIAlertAction(title: "Yes", style: .destructive) { _ in self.logout() } let noButton = UIAlertAction(title: "No", style: .cancel, handler: nil) alert.addAction(yesButton) alert.addAction(noButton) present(alert, animated: true, completion: nil) } func logout() { BlueShift.sharedInstance()?.trackEvent(forEventName: "Logout", canBatchThisEvent: false) blueshiftLogout() self.navigationController?.popToRootViewController(animated: true) } func blueshiftLogout() { //Set enablePush to false so that the app will not receive any push notificaiton after logout. Fire identify after setting enablePush. BlueShiftAppData.current().enablePush = false BlueShiftAppData.current().enableInApp = false // Send identify event with or without additonal details BlueShift.sharedInstance()?.identifyUser(withDetails: nil, canBatchThisEvent: false) // Reset userinfo BlueShiftUserInfo.removeCurrentUserInfo() // Reset device id and send identify, so that SDK will create a new device id. BlueShiftDeviceData.current().resetDeviceUUID() // Set enablePush and enableInApp to true for guest user and send identify BlueShiftAppData.current().enablePush = true BlueShiftAppData.current().enableInApp = true BlueShift.sharedInstance()?.identifyUser(withDetails: nil, canBatchThisEvent: false) } } extension ProductListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Utils.shared?.products.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let product = Utils.shared?.products[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "ProductTableViewCellIdentifier") as! ProductTableViewCell if let url = product?["image_url"], let imageUrl = URL(string: url) { DispatchQueue.global(qos: .userInteractive).async { let data = NSData.init(contentsOf: imageUrl) if let data = data as Data?, let image = UIImage(data: data) { DispatchQueue.main.async { Utils.shared?.productImages[url] = image cell.productImageView.image = image } } } } cell.productSKULabel.text = product?["sku"] cell.productPriceLabel.text = "$" + (product?["price"] ?? "") cell.productTitleLabel.text = product?["name"] return cell } } extension ProductListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let product = Utils.shared?.products[indexPath.row] else { return } showProductDetail(animated: true, product: product) } } extension ProductListViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last { BlueShiftDeviceData.current()?.currentLocation = location; } } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if let location = manager.location { BlueShiftDeviceData.current()?.currentLocation = location } } }
// // CategoryViewCell.swift // Mobile Store // // Created by Ashwinkarthik Srinivasan on 3/6/15. // Copyright (c) 2015 Yun Zhang. All rights reserved. // import UIKit class CategoryViewCell: UICollectionViewCell { @IBOutlet weak var categoryImage: UIImageView! @IBOutlet weak var categoryNameLabel: UILabel! var image: UIImage! var descr: String! var objID: String! }
// // IntegrationTestCase.swift // GitHubTestUITests // // Created by Bruno on 7/19/20. // Copyright © 2020 bruno. All rights reserved. // import Foundation import XCTest import KIF @testable import GitHubTest protocol IntegrationTestCaseProtocol { func withLabel(_ label: LabelViewProtocol) -> KIFUIViewTestActor? func withIdentifier(_ identifier: IdentifierViewProtocol) -> KIFUIViewTestActor? } /// IntegrationTetCase - stubs and KIF functions internal class IntegrationTestCase: KIFTestCase { let stubs = StubsNetworking() let bundleIdentifier = "bruno.GitHubTest" var application: AppDelegate? = UIApplication.shared.delegate as? AppDelegate lazy var appCoordinator: AppCoordinator? = { let appCoordinator = application?.appCoordinator return appCoordinator }() override func setUp() { super.setUp() stubs.setup() // Run the test animations super fast!!! KIFTypist.setKeystrokeDelay( 0.0025) KIFTestActor.setDefaultAnimationStabilizationTimeout(0.1) KIFTestActor.setDefaultAnimationWaitingTimeout(0.5) KIFTestActor.setDefaultTimeout(TimeInterval(3.0)) // KIFTestActor.setStepDelay(0.5) } override func tearDown() { super.tearDown() stubs.clear() appCoordinator?.window.rootViewController?.presentedViewController?.dismissAnimated() } override func beforeEach() { super.beforeEach() UserDefaults.standard.removePersistentDomain(forName: bundleIdentifier) UserDefaults.standard.removeObject(forKey: String(describing: HomeViewController.self)) } override func afterEach() { super.afterEach() //clear user status UserDefaults.standard.removePersistentDomain(forName: bundleIdentifier) } } extension IntegrationTestCase { func tester(_ file: String = #file, _ line: Int = #line) -> KIFUIViewTestActor { return KIFUIViewTestActor(inFile: file, atLine: line, delegate: self) } func testerActor(file: String = #file, _ line: Int = #line) -> KIFUITestActor { return KIFUITestActor(inFile: file, atLine: line, delegate: self) } func system(_ file: String = #file, _ line: Int = #line) -> KIFSystemTestActor { return KIFSystemTestActor(inFile: file, atLine: line, delegate: self) } func screenshot(line: UInt, name: String, _ desc: String = "") { try? UIApplication.shared.writeScreenshot(forLine: line, inFile: name, description: desc) } func findElement(_ label: String) -> Bool { do { try testerActor().tryFindingView(withAccessibilityLabel: label) return true } catch { return false } } }
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by OLEKSANDR SEMENIUK on ___DATE___. // ___COPYRIGHT___ import VRGSoftSwiftIOSKit class ___VARIABLE_cellName:identifier___CellData: SMCollectionCellData { override class var cellNibName_: String? { let result: String = String(describing: ___VARIABLE_cellName:identifier___Cell.self) return result } } class ___VARIABLE_cellName:cellName___Cell: SMBaseCollectionCell { // MARK: Lifecycle override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() } // MARK: Base Overrides override func setupCellData(_ aCellData: SMListCellData) { super.setupCellData(aCellData) } override func setupWith(model aModel: AnyObject?) { super.setupWith(model: aModel) } }
// // LeagueEventsViewController.swift // SportsApp // // Created by tasneem on 4/19/21. // Copyright © 2021 tasneem. All rights reserved. // import UIKit import CoreData class LeagueEventsViewController: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var upcommingCollectionView: UICollectionView! @IBOutlet weak var teamsCollectionView: UICollectionView! @IBOutlet weak var lastEventsTableView: UITableView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var favoriteBtn: UIButton! var lastEvents = [Events]() var upcommingEvents = [Events]() var leagueTeams = [Teams]() let leagueEventsViewModel = LeagueEventsViewModel() var leagueObj:Countrys? var isFavorite=false var idLeague="" var isInCD = false var teamDetails:Teams? var managedContext : NSManagedObjectContext! var favoritesCD:[NSManagedObject]! override func viewDidLoad() { super.viewDidLoad() self.upcommingCollectionView.delegate = self self.upcommingCollectionView.dataSource = self self.teamsCollectionView.delegate = self self.teamsCollectionView.dataSource = self lastEventsTableView.delegate=self lastEventsTableView.dataSource=self let screenRect = UIScreen.main.bounds let screenWidth = screenRect.size.width let screenHeight = screenRect.size.height self.scrollView.contentSize = CGSize(width: screenWidth, height: 1010) self.scrollView.frame = CGRect(x: 0, y: 70, width: screenWidth, height: screenHeight) scrollView.backgroundColor = UIColor.clear let appDelegate = UIApplication.shared.delegate as! AppDelegate managedContext = appDelegate.persistentContainer.viewContext print(leagueObj?.idLeague) if isFavorite { leagueEventsViewModel.fetchTeamsDataFromAPI(leagueID: (idLeague)) leagueEventsViewModel.fetchLastEventsDataFromAPI(leagueID: (idLeague)) leagueEventsViewModel.fetchUpcommingEventsDataFromAPI(leagueID: (idLeague)) }else{ leagueEventsViewModel.fetchTeamsDataFromAPI(leagueID: (leagueObj?.idLeague)!) leagueEventsViewModel.fetchLastEventsDataFromAPI(leagueID: (leagueObj?.idLeague)!) leagueEventsViewModel.fetchUpcommingEventsDataFromAPI(leagueID: (leagueObj?.idLeague)!) getFromDB(id: (leagueObj?.idLeague)!) } leagueEventsViewModel.bindUpcommingEventsViewModelToView = { self.onUpcommingEventSuccessUpdateView() self.activityIndicator.stopAnimating() } leagueEventsViewModel.bindLastEventsViewModelToView = { self.onLastEventSuccessUpdateView() self.activityIndicator.stopAnimating() } leagueEventsViewModel.bindLeagueTeamsViewModelToView = { self.onLeagueTeamsSuccessUpdateView() self.activityIndicator.stopAnimating() } leagueEventsViewModel.bindViewModelErrorToView = { self.onFailUpdateView() self.activityIndicator.stopAnimating() } } override func viewWillAppear(_ animated: Bool) { if isFavorite { favoriteBtn.tintColor = UIColor.red }else{ getFromDB(id: (leagueObj?.idLeague)!) } } func onLastEventSuccessUpdateView(){ if let events = leagueEventsViewModel.lastEvents.events{ lastEvents = leagueEventsViewModel.lastEvents.events! } self.lastEventsTableView.reloadData() } func onUpcommingEventSuccessUpdateView(){ if let event = leagueEventsViewModel.upcommingEvents.events { upcommingEvents = leagueEventsViewModel.upcommingEvents.events! } self.upcommingCollectionView.reloadData() } func onLeagueTeamsSuccessUpdateView(){ if let team = leagueEventsViewModel.leagueTeams.teams{ leagueTeams = leagueEventsViewModel.leagueTeams.teams! } self.teamsCollectionView.reloadData() self.upcommingCollectionView.reloadData() self.lastEventsTableView.reloadData() } func onFailUpdateView(){ let alert = UIAlertController(title: "Error", message: leagueEventsViewModel.showError, preferredStyle: .alert) let okAction = UIAlertAction(title: "Ok", style: .default) { (UIAlertAction) in } alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } @IBAction func favoriteBtn(_ sender: Any) { if isFavorite == false && isInCD == false && favoriteBtn.tintColor != UIColor.red { addToFavorite(leagueItem: leagueObj!) favoriteBtn.tintColor=UIColor.red }else if favoriteBtn.tintColor==UIColor.red{ if isFavorite==true{ removeFromDB(id: idLeague) isFavorite=false favoriteBtn.isHidden=true }else{ removeFromDB(id: (leagueObj?.idLeague)!) isInCD=false } } } func removeFromDB(id:String) { // let entity = NSEntityDescription.entity(forEntityName: "Favorite", in: managedContext) // let favoriteItem = NSManagedObject(entity: entity!, insertInto: managedContext) // favoriteItem.setValue(leagueItem.idLeague!, forKey: "idLeague") // favoriteItem.setValue(leagueItem.strLeague!, forKey: "strLeague") // favoriteItem.setValue(leagueItem.strBadge!, forKey: "strBadge") // favoriteItem.setValue(leagueItem.strYoutube!, forKey: "strYoutube") let fetch = NSFetchRequest<NSManagedObject>(entityName: "Favorite") do{ var favorites = try self.managedContext.fetch(fetch) print("fetch") for item in favorites { if item.value(forKey: "idLeague") as! String? == id { managedContext.delete(item) favoriteBtn.tintColor=UIColor.blue } } try managedContext.save() }catch { print("un fetch") } } func addToFavorite(leagueItem:Countrys) { let entity = NSEntityDescription.entity(forEntityName: "Favorite", in: managedContext) let favoriteItem = NSManagedObject(entity: entity!, insertInto: managedContext) favoriteItem.setValue(leagueItem.idLeague!, forKey: "idLeague") favoriteItem.setValue(leagueItem.strLeague!, forKey: "strLeague") favoriteItem.setValue(leagueItem.strBadge!, forKey: "strBadge") favoriteItem.setValue(leagueItem.strYoutube!, forKey: "strYoutube") do{ try managedContext.save() isInCD=true }catch let error as NSError{ print(error) } } func getFromDB(id:String) { let fetch = NSFetchRequest<NSManagedObject>(entityName: "Favorite") do{ self.favoritesCD = try self.managedContext.fetch(fetch) for item in favoritesCD { if item.value(forKey: "idLeague")as! String == id { isInCD = true favoriteBtn.tintColor = UIColor.red } } print("fetch") }catch { print("un fetch") } } } //Last 15 Events by League Id //https://www.thesportsdb.com/api/v1/json/1/eventspastleague.php?id=4328 // // //List all Teams in a League //https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League extension LeagueEventsViewController : UITableViewDelegate , UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { lastEvents.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as! LastEventesTableViewCell cell.countLabelView1.text = lastEvents[indexPath.row].intHomeScore cell.countLabelView2.text = lastEvents[indexPath.row].intAwayScore if let teamOne = lastEvents[indexPath.row].idHomeTeam { var pics=getTeamPic(teamOneId: lastEvents[indexPath.row].idHomeTeam!, teamTwoId: lastEvents[indexPath.row].idAwayTeam!, teams: leagueTeams) cell.imageView1.sd_setImage(with: URL(string:pics[0]), placeholderImage: UIImage(named: "placeholde")) cell.imageViw2.sd_setImage(with: URL(string:pics[1]), placeholderImage: UIImage(named: "placeholde")) cell.layer.cornerRadius=15 cell.layer.masksToBounds=true } cell.view1.layer.cornerRadius = 15.0 cell.view2.layer.cornerRadius = 15.0 cell.dateLabelView.text=lastEvents[indexPath.row].dateEvent cell.homeTeamLabel.text=lastEvents[indexPath.row].strHomeTeam cell.awayTeamLabel.text=lastEvents[indexPath.row].strAwayTeam cell.eventLabel.text=lastEvents[indexPath.row].strEvent return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{ return 170.0 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { "Last Events" } func numberOfSections(in tableView: UITableView) -> Int { 1 } } extension LeagueEventsViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == upcommingCollectionView { return upcommingEvents.count }else{ return leagueTeams.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == upcommingCollectionView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellh1", for: indexPath as IndexPath) as! UpCommingCollectionViewCell cell.labelCounter1.text = upcommingEvents[indexPath.row].intHomeScore cell.labelCounter2.text = upcommingEvents[indexPath.row].intAwayScore var pics=getTeamPic(teamOneId: upcommingEvents[indexPath.row].idHomeTeam!, teamTwoId: upcommingEvents[indexPath.row].idAwayTeam!, teams: leagueTeams) cell.imageView1.sd_setImage(with: URL(string:pics[0]), placeholderImage: UIImage(named: "placeholde")) //cell.view1.layer.cornerRadius = 20.0 //cell.view1.layer.masksToBounds=true cell.imageView2.sd_setImage(with: URL(string:pics[1]), placeholderImage: UIImage(named: "placeholde")) //cell.view2.layer.cornerRadius = 20.0 //cell.view1.layer.masksToBounds=true cell.dateLabeel.text=upcommingEvents[indexPath.row].dateEvent cell.homeTeamLabel.text=upcommingEvents[indexPath.row].strHomeTeam cell.awayTeamLabel.text=upcommingEvents[indexPath.row].strAwayTeam cell.eventLabel.text=upcommingEvents[indexPath.row].strEvent cell.layer.cornerRadius=15 cell.layer.masksToBounds=true cell.imageView1.layer.cornerRadius=15 cell.imageView1.layer.masksToBounds=true cell.imageView2.layer.cornerRadius=15 cell.imageView2.layer.masksToBounds=true cell.view1.layer.cornerRadius = 15.0 cell.view2.layer.cornerRadius = 15.0 return cell }else{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellh2", for: indexPath as IndexPath) as! TeamsCollectionViewCell cell.nameLabel.text=leagueTeams[indexPath.row].strTeam cell.teamImageViw.sd_setImage(with: URL(string:leagueTeams[indexPath.row].strTeamBadge!), placeholderImage: UIImage(named: "placeholde")) cell.teamImageViw.layer.cornerRadius = cell.teamImageViw.frame.width / 2 cell.teamImageViw.clipsToBounds = true return cell } } func numberOfSections(in collectionView: UICollectionView) -> Int { 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if collectionView == upcommingCollectionView { return CGSize(width: 300, height: 180) }else{ return CGSize(width: 150, height: 144) } } func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { teamDetails=leagueTeams[indexPath.row] return true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let vc : TeamDetailsTableViewController = segue.destination as! TeamDetailsTableViewController vc.team = self.teamDetails //print("prepatre"+(leagueObj?.idLeague)!) } func getTeamPic(teamOneId:String,teamTwoId:String,teams:[Teams]) -> [String] { var teamspics=["",""] for item in teams{ if teamOneId==item.idTeam { teamspics[0]=item.strTeamBadge! } if teamTwoId==item.idTeam { teamspics[1]=item.strTeamBadge! } } return teamspics } }
// // Colors.swift // KayakFirst Ergometer E2 // // Created by Balazs Vidumanszki on 2017. 01. 09.. // Copyright © 2017. Balazs Vidumanszki. All rights reserved. // import Foundation import UIKit struct Colors { static let colorPrimary = getColor("#f2f2f2") static let colorPrimaryTransparent = getColor("#aaf2f2f2") static let colorPrimaryDark = getColor("#000000") static let colorAccent = getColor("#ff541c") static let colorAccentDark = getColor("#ff4102") static let colorWhite = getColor("#333c41") static let colorWhiteDark = getColor("#293034") static let colorGrey = getColor("#929292") static let colorTransparent = getColor("#00000000") static let colorInactive = getColor("#4d4d4d") static let colorDashBoardDivider = getColor("#929292") static let colorBluetooth = getColor("#2196F3") static let dragDropStart = getColor("#77e25303") static let dragDropEnter = getColor("#bbe25303") static let startDelayBackground = getColor("#eedf5626") static let colorT = getColor("#333c41") static let colorStrokes = getColor("#cd2929") static let colorF = getColor("#0dd278") static let colorV = getColor("#005cff") static let colorGreen = getColor("#00b000") static let colorYellow = getColor("#c4b53c") static let colorRed = getColor("#cc0000") static let colorPauseBackground = getColor("#cccccc") static let colorFacebook = getColor("#3b5998") static let colorGoogle = getColor("#dc4e41") static let colorProfileElement = getColor("#ffffff") static let colorBatterySaverInactive = getColor("#AAAAAA") static let colorBatterySaverActive = getColor("#5EB846") static let colorPlanLight = getColor("#00b000") static let colorPlanMedium = getColor("#ffed00") static let colorPlanHard = getColor("#cc0000") static let colorDeleteStart = getColor("#cc0000") static let colorDeleteEnd = getColor("bbcc0000") static let colorKeyPressed = getColor("#e5e5e5") } func getColor(_ hex: String) -> UIColor { var cString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if cString.hasPrefix("#") { cString.remove(at: cString.startIndex) } var rgbValue: UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) let length = cString.characters.count let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0 let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0 let blue = CGFloat(rgbValue & 0x0000FF) / 255.0 var alpha: CGFloat = 1.0 if length == 8 { alpha = CGFloat((rgbValue & 0xFF000000) >> 24) / 255.0 } else if length != 6 { return UIColor.black } return UIColor( red: red, green: green, blue: blue, alpha: alpha ) }
// // GoogleChromeActivity.swift // The Tech Time // // Created by Rakshit Majithiya on 1/11/17. // // import UIKit public class GoogleChromeActivity: BrowserActivity { static var isChromeInstalled: Bool { UIApplication.shared.canOpenURL(URL(string: "googlechrome://")!) } override var foundURL: URL? { didSet { if let nsURL = NSURL(string: foundURL?.absoluteString ?? " "), let googleScheme = nsURL.scheme?.replacingOccurrences(of: "http", with: "googlechrome"), let resourceSpecifier = nsURL.resourceSpecifier { urlToOpen = URL(string: googleScheme + ":" + resourceSpecifier) } } } override public var activityTitle: String? { "Open in Chrome" } override public var activityImage: UIImage? { UIImage(named: "icon_chrome", in: Bundle.module, compatibleWith: nil) } override public var activityType: UIActivity.ActivityType { UIActivity.ActivityType.openInGoogleChrome } }
// // Metadata.swift // Ananas // // Created by Thierry Soulie on 21/11/2020. // import Foundation class Metadata: ObservableObject, Identifiable, Codable { @Published var id: Int = 0 @Published var group: String = "" @Published var key: String = "" @Published var value: String = "" // @Published var createddate: Date enum CodingKeys: String, CodingKey { case _id case metadata_group case metadata_key case metadata_value } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: CodingKeys._id) try container.encode(group, forKey: CodingKeys.metadata_group) try container.encode(key, forKey: CodingKeys.metadata_key) try container.encode(value, forKey: CodingKeys.metadata_value) } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) id = try values.decode(Int.self, forKey: ._id) group = try values.decode(String.self, forKey: .metadata_group) key = try values.decode(String.self, forKey: .metadata_key) value = try values.decode(String.self, forKey: .metadata_value) } init() { } } var sampleMetada1: Metadata { let metadata = Metadata() metadata.id = 1 metadata.group = "LN" metadata.key = "fileName" metadata.value = "Base Chômage partiel - septembre 2020.xlsx" return metadata } var sampleMetada2: Metadata { let metadata = Metadata() metadata.id = 2 metadata.group = "LN" metadata.key = "lastLoaded" metadata.value = "samedi 31 octobre 2020 à 10:50:33" return metadata } var sampleMetada3: Metadata { let metadata = Metadata() metadata.id = 3 metadata.group = "ANOMALIES" metadata.key = "lastLoaded" metadata.value = "samedi 31 octobre 2020 à 10:50:33" return metadata } var sampleMetadataList = [sampleMetada1, sampleMetada2, sampleMetada3]
// // Copyright © 2020 Tasuku Tozawa. All rights reserved. // import Common import Domain import RealmSwift // swiftlint:disable contains_over_filter_is_empty public class ReferenceClipStorage { public struct Configuration { let realmConfiguration: Realm.Configuration } let configuration: Realm.Configuration private let logger: TBoxLoggable private var realm: Realm? // MARK: - Lifecycle public init(config: ReferenceClipStorage.Configuration, logger: TBoxLoggable) throws { self.configuration = config.realmConfiguration self.logger = logger } } extension ReferenceClipStorage: ReferenceClipStorageProtocol { // MARK: - ReferenceClipStorageProtocol public var isInTransaction: Bool { return self.realm?.isInWriteTransaction ?? false } public func beginTransaction() throws { if let realm = self.realm, realm.isInWriteTransaction { realm.cancelWrite() } self.realm = try Realm(configuration: self.configuration) self.realm?.beginWrite() } public func commitTransaction() throws { guard let realm = self.realm else { return } try realm.commitWrite() } public func cancelTransactionIfNeeded() { defer { self.realm = nil } guard let realm = self.realm, realm.isInWriteTransaction else { return } realm.cancelWrite() } // MARK: Read public func readAllDirtyTags() -> Result<[ReferenceTag], ClipStorageError> { guard let realm = try? Realm(configuration: self.configuration) else { return .failure(.internalError) } let tags = realm.objects(ReferenceTagObject.self) .filter { $0.isDirty } .map { ReferenceTag.make(by: $0) } return .success(Array(tags)) } public func readAllTags() -> Result<[ReferenceTag], ClipStorageError> { guard let realm = try? Realm(configuration: self.configuration) else { return .failure(.internalError) } let tags = realm.objects(ReferenceTagObject.self) .map { ReferenceTag.make(by: $0) } return .success(Array(tags)) } // MARK: Create public func create(tag: ReferenceTag) -> Result<Void, ClipStorageError> { guard let realm = self.realm, realm.isInWriteTransaction else { return .failure(.internalError) } if realm.object(ofType: ReferenceTagObject.self, forPrimaryKey: tag.id.uuidString) != nil { return .failure(.duplicated) } if realm.objects(ReferenceTagObject.self).filter("name = '\(tag.name)'").isEmpty == false { return .failure(.duplicated) } let obj = ReferenceTagObject() obj.id = tag.id.uuidString obj.name = tag.name obj.isDirty = tag.isDirty realm.add(obj, update: .modified) return .success(()) } // MARK: Update public func updateTag(having id: ReferenceTag.Identity, nameTo name: String) -> Result<Void, ClipStorageError> { guard let realm = self.realm, realm.isInWriteTransaction else { return .failure(.internalError) } let tag = realm.object(ofType: ReferenceTagObject.self, forPrimaryKey: id.uuidString) tag?.name = name return .success(()) } public func updateTag(having id: ReferenceTag.Identity, byHiding isHidden: Bool) -> Result<Void, ClipStorageError> { guard let realm = self.realm, realm.isInWriteTransaction else { return .failure(.internalError) } let tag = realm.object(ofType: ReferenceTagObject.self, forPrimaryKey: id.uuidString) tag?.isHidden = isHidden return .success(()) } public func updateTags(having ids: [ReferenceTag.Identity], toDirty isDirty: Bool) -> Result<Void, ClipStorageError> { guard let realm = self.realm, realm.isInWriteTransaction else { return .failure(.internalError) } let tags = ids .map { realm.object(ofType: ReferenceTagObject.self, forPrimaryKey: $0.uuidString) } tags.forEach { $0?.isDirty = isDirty } return .success(()) } // MARK: Delete public func deleteTags(having ids: [ReferenceTag.Identity]) -> Result<Void, ClipStorageError> { guard let realm = self.realm, realm.isInWriteTransaction else { return .failure(.internalError) } ids .compactMap { realm.object(ofType: ReferenceTagObject.self, forPrimaryKey: $0.uuidString) } .forEach { realm.delete($0) } return .success(()) } }
// // LineOb.swift // lab3 // // Created by David Schonfeld on 2/15/17. // Copyright © 2017 schon. All rights reserved. // import Foundation import UIKit struct LineOb { var points = [CGPoint]() var radius: CGFloat var color: UIColor var opacity: CGFloat }
import Foundation import CoreLocation struct LocationLogger { private static var fileUrl = { () -> URL in let dir: URL = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last! return dir.appendingPathComponent("location.log") }() func removeLogFile() { try? FileManager.default.removeItem(at: LocationLogger.fileUrl) } func writeLocationToFile(location: CLLocation) { let string = "\(NSDate())&\(location.coordinate.latitude)&\(location.coordinate.longitude)\n" let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)! if FileManager.default.fileExists(atPath: LocationLogger.fileUrl.path) { let fileHandle = try! FileHandle(forWritingTo: LocationLogger.fileUrl) fileHandle.seekToEndOfFile() fileHandle.write(data) fileHandle.closeFile() } else { try! data.write(to: LocationLogger.fileUrl) } } func readLocation() -> [CLLocation]? { do { let data = try String(contentsOf: LocationLogger.fileUrl) let locationStrings = data.components(separatedBy: .newlines) var locations:[CLLocation] = [] locationStrings.forEach({ locString in let coordinateString = locString.split(separator: "&") if coordinateString.count > 2 { let lat = Double(coordinateString[1]) let long = Double(coordinateString[2]) locations.append(CLLocation(latitude: lat!, longitude: long!)) } }) return locations } catch { return nil } } }
// // SettingsCellDataModel.swift // // import Foundation public class SettingsCellDataModel { let key: String let title: String let detail: String? public init(_ key: String, title: String, detail: String? = nil) { self.key = key self.title = title self.detail = detail } }
/* * Copyright (c) 2019, Okta, Inc. and/or its affiliates. All rights reserved. * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.") * * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and limitations under the License. */ import Foundation open class OktaAuthStatusLockedOut : OktaAuthStatus { public override init(currentState: OktaAuthStatus, model: OktaAPISuccessResponse) throws { try super.init(currentState: currentState, model: model) statusType = .lockedOut } open func canUnlock() -> Bool { guard model.links?.next?.href != nil else { return false } return true } open func unlock(username: String, factorType: OktaRecoveryFactors, onStatusChange: @escaping (_ newStatus: OktaAuthStatus) -> Void, onError: @escaping (_ error: OktaError) -> Void) { guard canUnlock() else { onError(.wrongStatus("Can't find 'next' link in response")) return } do { let unauthenticated = try OktaAuthStatusUnauthenticated(currentState: self, model: self.model) unauthenticated.unlockAccount(username: username, factorType: factorType, onStatusChange: onStatusChange, onError: onError) } catch let error { onError(error as! OktaError) } } }
//// //// Created by Yunarta on 19/9/18. //// Copyright (c) 2018 mobilesolution works. All rights reserved. //// // //import Foundation //import RealmSwift //import RxSwift //import RxRealm // //public class RealmPlantCredentialManager: PlantCredentialManager { // // let realm: Realm // // internal init(_ configuration: Realm.Configuration) throws { // realm = try Realm(configuration: configuration) // } //} // //public class RealmCredentialResolver<Credential>: StrutCredentialResolver where Credential: Object & ShortCredential { // // let configuration: Realm.Configuration // // public init(configuration: Realm.Configuration) { // self.configuration = configuration // } // // public func resolve(credential: ShortCredential) -> Maybe<Credential> { // return Maybe.create { observer in // do { // if credential is Credential { // let realm = try Realm(configuration: self.configuration) // if let credential = realm.object(ofType: Credential.self, forPrimaryKey: credential.id) { // observer(.success(credential)) // } // } // observer(.completed) // } catch { // observer(.error(error)) // } // // return Disposables.create() // } // } //} // //public class RealmStrutCredentialManager<Credential>: InternalStrutCredentialManager // where Credential: Object & ShortCredential { // // typealias StaticSelf = RealmStrutCredentialManager<Credential> // // let reference: Realm // // let configuration: Realm.Configuration // // let internalCredentialResolved: RealmCredentialResolver<Credential> // public var credentialResolver: RealmCredentialResolver<Credential> { // return internalCredentialResolved // } // // internal init(_ configuration: Realm.Configuration) throws { // self.configuration = configuration // // internalCredentialResolved = RealmCredentialResolver(configuration: configuration) // reference = try Realm(configuration: configuration) // } // // public func list() -> Single<OnDemandArray<ShortCredential>> { // return Single.create { observer in // do { // let realm = try Realm(configuration: self.configuration) // let result: OnDemandArray<ShortCredential> = StaticSelf.create(transforming: AnyRealmCollection(realm.objects(Credential.self))) // // observer(.success(result)) // } catch { // observer(.error(error)) // } // // return Disposables.create() // } // } // // public func observeList() -> Observable<OnDemandArray<ShortCredential>> { // return Observable.deferred { // return Observable.changeset(from: try Realm(configuration: self.configuration).objects(Credential.self)) // .map { (arg) -> OnDemandArray<ShortCredential> in // let (collection, _) = arg // return StaticSelf.create(transforming: AnyRealmCollection(collection)) // } // } // } // // public func get(id: String) -> Maybe<ShortCredential> { // return Maybe.create { observer in // do { // let realm = try Realm(configuration: self.configuration) // if let credential = realm.object(ofType: Credential.self, forPrimaryKey: id) { // observer(.success(credential)) // } // observer(.completed) // } catch { // observer(.error(error)) // } // // return Disposables.create() // } // } // // public func observe(id: String) -> Observable<ShortCredential> { // return Observable.deferred { // do { // let realm = try Realm(configuration: self.configuration) // // if let credential = realm.object(ofType: Credential.self, forPrimaryKey: id) { // return Observable.from(object: credential).map { credential in // return credential // } // } else { // return Observable.empty() // } // } catch { // return Observable.error(error) // } // } // } // // public func insertOrReplace(_ credential: Credential) -> Completable { // return Completable.create { observer in // do { // let realm = try Realm(configuration: self.configuration) // try realm.write { // realm.add(credential, update: true) // } // observer(.completed) // } catch { // observer(.error(error)) // } // // return Disposables.create() // } // } // // public func remove(_ credential: Credential) -> Single<Bool> { // return Single.create { observer in // do { // let realm = try Realm(configuration: self.configuration) // try realm.write { // if let found = realm.object(ofType: Credential.self, forPrimaryKey: credential.id) { // realm.delete(found) // observer(.success(true)) // } else { // observer(.success(false)) // } // } // } catch { // observer(.error(error)) // } // // return Disposables.create() // } // } // // static func create(transforming sequence: AnyRealmCollection<Credential>) -> OnDemandArray<ShortCredential> { // return OnDemandArray<ShortCredential>(buffer: sequence, count: { [weak sequence = sequence] in // sequence?.underestimatedCount ?? 0 // }, subscript: { [weak sequence = sequence] index -> ShortCredential in // guard let sequence = sequence else { // fatalError("calling array where the data is closed already") // } // return sequence[index] // }) // } //} // //public class RealmCredentialManagerFactory { // // let name: String // // public init(app name: String) { // self.name = name // } // // public func createPlantManager(inMemory: Bool = true) throws -> PlantCredentialManager { // var configuration = Realm.Configuration() // configuration.inMemoryIdentifier = "credential.realm" // if (!inMemory) { // configuration.fileURL = try FileManagerHelpers.applicationLibrary(for: name)?.appendingPathComponent("credentials.realm") // } // // return try RealmPlantCredentialManager(configuration) // } // // public func createStrutManager<Credential>(id: String, for _: Credential.Type, inMemory: Bool = true) throws -> RealmStrutCredentialManager<Credential> // where Credential: Object & ShortCredential { // var configuration = Realm.Configuration() // configuration.inMemoryIdentifier = "\(id)-credential" // // if (!inMemory) { // configuration.fileURL = try FileManagerHelpers.applicationLibrary(for: name)?.appendingPathComponent("\(id).realm") // } // // return try RealmStrutCredentialManager<Credential>(configuration) // } //}
// // HomeViewController.swift // loginscreen // // Created by Rizul goyal on 2019-10-28. // Copyright © 2019 Rizul goyal. All rights reserved. // import UIKit class HomeViewController: UIViewController { @IBOutlet weak var labelWelcome: UILabel! public var name : String? override func viewDidLoad() { super.viewDidLoad() if let nm = name { labelWelcome.text="Welcome \(nm)" } navigationItem.hidesBackButton=true allLogOutButton() // Do any additional setup after loading the view. } private func allLogOutButton() { let btnLogOut = UIBarButtonItem(title: "Logout", style: .done, target: self, action: #selector(HomeViewController.logout(sender:))) // navigationItem.leftBarButtonItem = btnLogOut navigationItem.leftBarButtonItems = [btnLogOut,btnLogOut] } @objc func logout(sender: UIBarButtonItem) { navigationController?.popViewController(animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // CTFSemanticDifferentialScaleFormParameters.swift // Impulse // // Created by James Kizer on 12/19/16. // Copyright © 2016 James Kizer. All rights reserved. // import UIKit import Gloss class CTFSemanticDifferentialScaleFormParameters: Decodable { let text: String? let title: String? let items: [CTFSemanticDifferentialScaleFormItemDecriptor]! required public init?(json: JSON) { guard let items: [CTFSemanticDifferentialScaleFormItemDecriptor] = "items" <~~ json else { return nil } self.items = items self.text = "text" <~~ json self.title = "title" <~~ json } }
// // AccController.swift // CosRemote // // Created by 郭 又鋼 on 2016/3/2. // Copyright © 2016年 郭 又鋼. All rights reserved. // import Foundation import UIKit import CoreMotion class AccController: UIViewController { let cmManager = CMMotionManager() @IBOutlet var lbZ: UILabel! @IBOutlet var lbY: UILabel! @IBOutlet var lbX: UILabel! @IBOutlet var pbX: UIProgressView! @IBOutlet var pbY: UIProgressView! @IBOutlet var pbZ: UIProgressView! @IBOutlet var lbCurrentColor: UILabel! override func viewDidLoad() { } var r:Int = 0 ; var g:Int = 0 ; var b:Int = 0 ; let SKIP_TIMES = 8 // 每n個少一個byte var skip:Int = 0 ; override func viewWillAppear(animated: Bool) { if cmManager.accelerometerAvailable{ let queue = NSOperationQueue() cmManager.startAccelerometerUpdatesToQueue(queue, withHandler: self.accHandler) } else { print("Accelerometer is not available") } self.navigationItem.title = "三軸加速度感測器" ; } func accHandler(data:CMAccelerometerData?, error:NSError?) { guard let data = data else{ return } self.r = self.normalize(data.acceleration.x) self.g = self.normalize(data.acceleration.y) self.b = self.normalize(data.acceleration.z) print(", \(r) X = \(data.acceleration.x)") print(", \(g) Y = \(data.acceleration.y)") print(", \(b) Z = \(data.acceleration.z)") skip = skip + 1 ; if ( skip != SKIP_TIMES ) { } else { skip = 0 dispatch_async(dispatch_get_main_queue(),{ // do ui update self.lbX.text = String(format: "X: %3d", self.r) self.lbY.text = String(format: "Y: %3d", self.g) self.lbZ.text = String(format: "Z: %3d", self.b) self.pbX.setProgress( Float(self.r) / 255.0, animated: true) self.pbY.setProgress( Float(self.g) / 255, animated: true) self.pbZ.setProgress( Float(self.b) / 255 , animated: true) ; self.lbCurrentColor.backgroundColor = UIColor(red: CGFloat(self.pbX.progress), green: CGFloat(self.pbY.progress), blue: CGFloat(self.pbZ.progress), alpha: 1) ; if let remote = Common.global.cosRemote { remote.setAllLed(self.r, g: self.g, b: self.b) ; } }) } } func normalize( dd:Double ) -> Int { var d = dd ; if ( d <= -1 ) { return 0 ; } else if ( d >= 1 ) { return 255 ; } else { d = d + 1 ; d = d * 255 / 2 } return Int(d) ; } override func viewDidDisappear(animated: Bool) { cmManager.stopAccelerometerUpdates() ; } }
// // People.swift // FindPerson // // Created by Pavel Tertyshnyy on 24/10/2019. // Copyright © 2019 Pavel Tertyshnyy. All rights reserved. // import Foundation internal struct People { let name: String let birthYear: String let height: String let mass: String let created: Date let edited: Date let gender: Gender? } internal enum Gender: String { case male = "Мужчина" case female = "Женщина" case unknown = "Неисвестно" case na = "n/a" }
// // MimicTests.swift // MimicTests // // Created by Felipe Ruz on 5/23/19. // Copyright © 2019 Felipe Ruz. All rights reserved. // @testable import Mimic import XCTest class MimicsRandomizeTests: XCTestCase { var exp: XCTestExpectation! var oneReceived: Bool! var twoReceived: Bool! override func setUp() { super.setUp() oneReceived = false twoReceived = false } override func tearDown() { Mimic.stopAllMimics() exp = nil oneReceived = nil twoReceived = nil super.tearDown() } func testRandomizeMimics() { let url = "http://localhost/randomize" Mimic.randomizeMimics = true Mimic.mimic( request: request(with: .get, url: url), response: response(with: ["message": "one"]) ) Mimic.mimic( request: request(with: .get, url: url), response: response(with: ["message": "two"]) ) exp = expectation(description: "testRandomizeMimics") exp.expectedFulfillmentCount = 2 executeRequest(url: url, method: .get, headers: nil) { one, two in XCTAssertTrue(one) XCTAssertTrue(two) } wait(for: [exp], timeout: 10) } private func executeRequest( url: String, method: MimicHTTPMethod, headers: [String: String]?, completionHandler: @escaping (Bool, Bool) -> Void ) { makeRequest(url: url, method: method, headers: headers) { [weak self] jsonDict in let value = jsonDict["message"] if value == "one", let one = self?.oneReceived, !one { self?.oneReceived = true self?.exp.fulfill() } if value == "two", let two = self?.twoReceived, !two { self?.twoReceived = true self?.exp.fulfill() } if let one = self?.oneReceived, let two = self?.twoReceived, !one || !two { self?.executeRequest( url: url, method: method, headers: headers, completionHandler: completionHandler ) } } } private func makeRequest( url: String, method: MimicHTTPMethod, headers: [String: String]?, completionHandler: @escaping ([String: String]) -> Void ) { guard let url = URL(string: url) else { return } var request = URLRequest(url: url) request.httpMethod = method.description request.allHTTPHeaderFields = headers let task = URLSession.shared.dataTask(with: request) { data, _, _ in guard let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]), let jsonDict = json as? [String: String] else { XCTFail("Failed to create JSON from data") return } completionHandler(jsonDict) } task.resume() } }
// // LoginViewController.swift // MPM-Sft-Eng-Proj // // Created by Harrison Ellerm on 12/05/18. // Copyright © 2018 Harrison Ellerm. All rights reserved. // import Foundation import UIKit import SwiftValidator import FirebaseAuth import LBTAComponents import JGProgressHUD import FirebaseStorage import FirebaseDatabase import GoogleSignIn import SwiftSpinner import SwiftyBeaver class LoginViewConroller: UIViewController, UITextFieldDelegate, ValidationDelegate, GIDSignInUIDelegate { private let validator = Validator() private let appDelegate = UIApplication.shared.delegate as! AppDelegate private let log = SwiftyBeaver.self private let loginLabel: UILabel = { let label = UILabel() label.text = "Get started below" label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont(name: "HelveticaNeue-Thin", size: 30) label.textColor = UIColor.white return label }() private let emailTextField: UITextField = { let textField = UITextField() let attributedPlaceholder = NSAttributedString(string: "email", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.backgroundColor: UIColor(red: 48 / 255, green: 48 / 255, blue: 43 / 255, alpha: 1)]) textField.attributedPlaceholder = attributedPlaceholder textField.backgroundColor = UIColor(red: 48 / 255, green: 48 / 255, blue: 43 / 255, alpha: 1) textField.textColor = UIColor.white textField.autocapitalizationType = UITextAutocapitalizationType.none textField.addIcon(imageName: "mail") textField.setBottomBorder(backgroundColor: UIColor(red: 60 / 255, green: 60 / 255, blue: 60 / 255, alpha: 1), borderColor: .white) return textField }() private let passwordTextField: UITextField = { let textField = UITextField() let attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]) textField.attributedPlaceholder = attributedPlaceholder textField.backgroundColor = UIColor(red: 48 / 255, green: 48 / 255, blue: 43 / 255, alpha: 1) textField.textColor = UIColor.white textField.isSecureTextEntry = true textField.autocapitalizationType = UITextAutocapitalizationType.none textField.addIcon(imageName: "password") textField.setBottomBorder(backgroundColor: UIColor(red: 60 / 255, green: 60 / 255, blue: 60 / 255, alpha: 1), borderColor: .white) return textField }() private lazy var forgotPasswordButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor(red: 48 / 255, green: 48 / 255, blue: 48 / 255, alpha: 1) let attributeTitle = NSMutableAttributedString(string: "Forgot your password? ", attributes: [NSAttributedStringKey.foregroundColor: UIColor(red: 216 / 255, green: 161 / 255, blue: 72 / 255, alpha: 1.0), NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)]) button.setAttributedTitle(attributeTitle, for: .normal) button.addTarget(self, action: #selector(forgotPasswordAction), for: .touchUpInside) return button }() private var loginButton: UIButton = { var button = UIButton(type: .system) button.setTitleColor(UIColor(red: 48 / 255, green: 48 / 255, blue: 43 / 255, alpha: 1), for: .normal) button.setTitle("Sign In", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: Service.buttonFontSize) button.layer.cornerRadius = Service.buttonCornerRadius button.addTarget(self, action: #selector(handleNormalLogin), for: .touchUpInside) return button }() private let googleButton: GIDSignInButton = { var button = GIDSignInButton() return button }() @objc private func forgotPasswordAction() { var inputTextField: UITextField? let alert = UIAlertController(title: "Reset password", message: "Please enter the email address associated with your account.", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: { (action) -> Void in self.log.info("User cancelled reset of password") })) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (action) in let entryStr: String = (inputTextField?.text)!.trimmingCharacters(in: .whitespaces) self.log.info("User requested email reset with email: \(entryStr)") Auth.auth().sendPasswordReset(withEmail: entryStr, completion: { (error) in if let err = error { self.log.error("An error ocurred when requesting password reset: \(err.localizedDescription)") Service.notifyStaffOfError(#file, "\(#function) \(#line): An error ocurred when requesting password reset: \(err.localizedDescription)") } let notif = UIAlertController(title: "Reset", message: "Please check your email for instructions on how to reset your password", preferredStyle: UIAlertControllerStyle.alert) notif.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (action) -> Void in self.log.info("User notified about password reset") })) self.present(notif, animated: true, completion: nil) }) })) alert.addTextField(configurationHandler: { (textField: UITextField!) in textField.placeholder = "email" inputTextField = textField }) self.present(alert, animated: true, completion: nil) } @objc private func handleNormalLogin() { //First validate text fields. validator.validate(self) } /** This method is used to validate an email and password. */ func validationSuccessful() { SwiftSpinner.show("Signing In...") guard let email = emailTextField.text else { return } guard let password = passwordTextField.text else { return } Auth.auth().signIn(withEmail: email, password: password) { (user, error) in if let error = error { self.log.error("There was an error signing in: \(error.localizedDescription)") Service.notifyStaffOfError(#file, "\(#function) \(#line): There was an error signing in: \(error.localizedDescription)") SwiftSpinner.show("Failed to sign in...") SwiftSpinner.hide() return } SwiftSpinner.hide() self.view.endEditing(true) self.appDelegate.handleLogin(withWindow: self.appDelegate.window) } } /** This method is used to validate a single field registered to Validator. If validation is unsuccessful,field gets removed from view controller. */ func validationFailed(_ errors: [(Validatable, ValidationError)]) { for (_, error) in errors { if let present = self.presentedViewController { present.removeFromParentViewController() } if presentedViewController == nil { Service.showAlert(on: self, style: .alert, title: "Error", message: error.errorMessage) } } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(red: 48 / 255, green: 48 / 255, blue: 43 / 255, alpha: 1) emailTextField.backgroundColor = UIColor(red: 48 / 255, green: 48 / 255, blue: 43 / 255, alpha: 1) passwordTextField.backgroundColor = UIColor(red: 48 / 255, green: 48 / 255, blue: 43 / 255, alpha: 1) loginButton.backgroundColor = UIColor.white forgotPasswordButton.backgroundColor = UIColor(red: 48 / 255, green: 48 / 255, blue: 43 / 255, alpha: 1) setupNavBar() setUpViews() setUpTextFields() //Setup Google Auth GIDSignIn.sharedInstance().uiDelegate = self //register text fields that will be validated validator.registerField(emailTextField, rules: [RequiredRule(message: "Please provide a email!"), EmailRule(message: "Please provide a valid email!")]) validator.registerField(passwordTextField, rules: [RequiredRule(message: "Password Required!")]) view.accessibilityIdentifier = "loginViewController" } private func setupNavBar() { navigationController?.navigationBar.isTranslucent = false let navigationBarAppearnce = UINavigationBar.appearance() navigationBarAppearnce.barTintColor = UIColor(red: 48 / 255, green: 48 / 255, blue: 43 / 255, alpha: 1) navigationBarAppearnce.tintColor = UIColor(red: 216 / 255, green: 161 / 255, blue: 72 / 255, alpha: 1.0) self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow") self.navigationController?.navigationBar.isHidden = false self.navigationController!.navigationBar.topItem!.title = "Back" } private func setUpViews() { view.addSubview(loginLabel) anchorLoginLabel(loginLabel) view.addSubview(emailTextField) anchorEmailTextField(emailTextField) view.addSubview(passwordTextField) anchorPasswordTextField(passwordTextField) view.addSubview(loginButton) anchorLoginButton(loginButton) view.addSubview(googleButton) anchorGoogleButton(googleButton) view.addSubview(forgotPasswordButton) anchorForgotPasswordButton(forgotPasswordButton) } private func anchorLoginLabel(_ label: UILabel) { label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true } private func anchorEmailTextField(_ textField: UITextField) { textField.anchor(loginLabel.bottomAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 50, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 30) } private func anchorPasswordTextField(_ textField: UITextField) { textField.anchor(emailTextField.bottomAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 16, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 30) } private func anchorLoginButton(_ button: UIButton) { button.anchor(passwordTextField.bottomAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 16, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50) } private func anchorGoogleButton(_ button: GIDSignInButton) { button.anchor(loginButton.bottomAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 16, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50) } private func anchorForgotPasswordButton(_ button: UIButton) { button.anchor(nil, left: view.safeAreaLayoutGuide.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 0, leftConstant: 16, bottomConstant: 8, rightConstant: 16, widthConstant: 0, heightConstant: 30) } private func setUpTextFields() { emailTextField.delegate = self passwordTextField.delegate = self } //Allows text fields to dissapear once they have been delegated func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
// // Kind.swift // AsteroidUI // // Created by Xiaodong Ye on 2020/8/13. // Copyright © 2020 Xiaodong Ye. All rights reserved. // import Foundation struct Kind: Command { // MARK: - Command func versionAsync(completion: CompletionHandler? = nil) { Bash().runAsync(commandName: "/bin/sh", arguments: ["-c", "~/.vctl/bin/kind version"], environment: [:], process: { (output) -> String? in if let output = output { let substrings = output.split(separator: " ") if substrings.count > 1 { return String(substrings[1]) } } return nil }) { output in completion?(output) } } }
// // CacheDataStore.swift // intermine-ios // // Created by Nadia on 5/7/17. // Copyright © 2017 Nadia. All rights reserved. // import Foundation import CoreData class CacheDataStore { private let modelName = General.modelName private let debug = true private let minesUpdateInterval: Double = 86400 //1 day // MARK: Shared Instance static let sharedCacheDataStore : CacheDataStore = { let instance = CacheDataStore() return instance }() // MARK: Public methods func getParamsForListCall(mineUrl: String, type: String) -> [String]? { if let model = MineModel.getMineModelByUrl(url: mineUrl, context: self.managedContext) { if let fileName = model.xmlFile { let modelParser = MineModelParser(fromFileWithName: fileName) return modelParser.getViewNames(forType: type) } } return nil } func updateRegistryIfNeeded(completion: @escaping (_ mines: [Mine]?, _ error: NetworkErrorType?) -> ()) { if Connectivity.isConnectedToInternet() { if registryNeedsUpdate() { IntermineAPIClient.fetchRegistry { (jsonRes, error) in guard let jsonRes = jsonRes else { completion(nil, error) return } // update registry in Core Data self.eraseRegistry() var mineObjects: [Mine] = [] if let instances = jsonRes["instances"] as? [[String: AnyObject]] { for instance in instances { if let mineObj = Mine.createMineFromJson(json: instance, context: self.managedContext), let mineUrl = mineObj.url { IntermineAPIClient.fetchOrganismsForMine(mineUrl: mineUrl, completion: { (res, error) in mineObj.organisms = res as NSArray }) mineObjects.append(mineObj) } } self.save() completion(mineObjects, error) } else { completion(nil, error) } } } else { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: { let mines = Mine.getAllMines(context: self.managedContext) completion(mines, nil) }) } } else { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: { let mines = Mine.getAllMines(context: self.managedContext) completion(mines, nil) }) } } func save() { saveContext() } func registrySize() -> Int { if let registry = self.fetchCachedRegistry() { return registry.count } else { return 0 } } func allRegistry() -> Array<Mine>? { return self.fetchCachedRegistry()?.sorted(by: { (mine0, mine1) -> Bool in guard let name0 = mine0.name, let name1 = mine1.name else { return false } return name0 < name1 }) } func findMineByUrl(url: String) -> Mine? { return Mine.getMineByUrl(url: url, context: self.managedContext) } func findMineByName(name: String) -> Mine? { return Mine.getMineByName(name: name, context: self.managedContext) } func updateRegistryModelsIfNeeded(mines: [Mine]) { for mine in mines { if let mineUrl = mine.url { self.updateModelIfNeeded(mineUrl: mineUrl) } } } func getMineNames() -> [String] { var mineNames: [String] = [] if let registry = self.fetchCachedRegistry() { for mine in registry { if let mineName = mine.name { mineNames.append(mineName) } } } mineNames.sort { (name1, name2) -> Bool in return name1 < name2 } return mineNames } func saveSearchResult(searchResult: SearchResult) { if let type = searchResult.getType(), let id = searchResult.getId(), let mineName = searchResult.getMineName() { FavoriteSearchResult.createFavoriteSearchResult(type: type, fields: searchResult.viewableRepresentation() as NSDictionary, mineName: mineName, id: id, context: self.managedContext) save() } } func unsaveSearchResult(withId: String) { if let searchResult = getSavedSearchById(id: withId) { delete(obj: searchResult) } } func getSavedSearchResults() -> [FavoriteSearchResult]? { return FavoriteSearchResult.getAllSavedSearches(context: self.managedContext) } func getSavedSearchById(id: String) -> FavoriteSearchResult? { return FavoriteSearchResult.getFavoriteSearchResultById(id: id, context: self.managedContext) } // MARK: Private methods private func delete(obj: NSManagedObject) { self.managedContext.delete(obj) save() } private func updateModelIfNeeded(mineUrl: String) { if debug { self.createMineModel(mineUrl: mineUrl) return } // check if xml is present, get MineModel by url if let model = MineModel.getMineModelByUrl(url: mineUrl, context: self.managedContext) { // check if model.xmlFile is a valid url to existing resource if let fileName = model.xmlFile { if FileHandler.doesFileExist(fileName: fileName) { // since it is called after mines version is uptated // we can use mines version if let mine = Mine.getMineByUrl(url: mineUrl, context: self.managedContext) { if let releaseId = mine.releaseVersion { if !(releaseId.isEqualTo(comparedTo: model.releaseId)) { // release ids differ, needs an update self.updateMineModel(model: model, releaseId: releaseId, xmlFile: nil) return } } } } else { // xml does not exist in documents directory, model needs an udpate with new xml self.delete(obj: model) self.createMineModel(mineUrl: mineUrl) return } } } else { // no model found, create mine model self.createMineModel(mineUrl: mineUrl) return } return } private func createMineModel(mineUrl: String) { if let mine = Mine.getMineByUrl(url: mineUrl, context: self.managedContext), let mineName = mine.name { let fileName = mineName + ".xml" IntermineAPIClient.fetchModel(mineUrl: mineUrl, completion: { (xmlString, error) in if let xmlString = xmlString as String? { FileHandler.writeToFile(fileName: fileName, contents: xmlString) if let releaseId = mine.releaseVersion { MineModel.createMineModel(url: mineUrl, releaseId: releaseId, xmlFile: fileName, versionId: nil, context: self.managedContext) self.save() } } }) } } private func updateMineModel(model: MineModel, releaseId: String?, xmlFile: String?) { var changeCount = 0 if let releaseId = releaseId { model.releaseId = releaseId changeCount += 1 } if let xmlFile = xmlFile { model.xmlFile = xmlFile changeCount += 1 } if changeCount >= 1 { self.save() } } private func fetchCachedRegistry() -> Array<Mine>? { do { if let registry = try self.managedContext.fetch(Mine.fetchRequest()) as? Array<Mine> { return registry } else { return [] } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") return nil } } private func registryNeedsUpdate() -> Bool { if debug == true { return true } if let registry = fetchCachedRegistry(), registry.count > 0 { if let mine: Mine = registry.first, let lastUpdated = mine.lastTimeUpdated { return NSDate.hasIntervalPassed(lastUpdated: lastUpdated, timeInterval: minesUpdateInterval) } return true } else { return true } } private func eraseRegistry() { if let registry = fetchCachedRegistry() { for mine in registry { self.managedContext.delete(mine) } } } // MARK: Core Data stack private lazy var managedContext: NSManagedObjectContext = { return self.storeContainer.viewContext }() private lazy var storeContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: self.modelName) container.loadPersistentStores { (storeDescription, error) in if let error = error as NSError? { print("Unresolved error \(error), \(error.userInfo)") } } return container }() private func saveContext () { guard managedContext.hasChanges else { return } do { try managedContext.save() } catch let error as NSError { print("Unresolved error \(error), \(error.userInfo)") } } }
// // UploadCollectionViewCell.swift // Hippo // // Created by Neha Vaish on 03/05/23. // import UIKit class UploadCollectionViewCell: UICollectionViewCell { @IBOutlet weak var dashedView: UIView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
public func map<A, B>(_ f: @escaping Func<A, B>) -> Func<A, B> { { a in f(a) } } public func map<A, B>(_ f: @escaping Func<A, B>) -> Func<[A], [B]> { { a in a.map(f) } } public func map<A, B>(_ keyPath: KeyPath<A, B>) -> Func<A, B> { { a in a[keyPath: keyPath] } } public func map<A, B>(_ keyPath: KeyPath<A, B>) -> Func<[A], [B]> { { a in a.map { $0[keyPath: keyPath] } } } public func compactMap<A, B>(_ f: @escaping Func<A, B?>) -> Func<[A], [B]> { { a in a.compactMap(f) } } public func compactMap<A, B>(_ keyPath: KeyPath<A, B?>) -> Func<[A], [B]> { { a in a.compactMap { $0[keyPath: keyPath] } } } public func flatMap<A, B>(_ f: @escaping Func<A, [B]>) -> Func<[A], [B]> { { a in a.flatMap(f) } } public func filter<A>(_ f: @escaping Func<A, Bool>) -> Func<A, A?> { { a in f(a) ? a : nil } } public func filter<A>(_ f: @escaping Func<A, Bool>) -> Func<[A], [A]> { { a in a.filter(f) } } public func forEach<A>(_ f: @escaping Handler<A>) -> Handler<[A]> { { a in a.forEach(f) } }
// // Settings.swift // Adapt // // Created by 599944 on 2/22/19. // Copyright © 2019 TheATeam. All rights reserved. // import Foundation public var isPG13: Bool = true
// // PopUpViewWithDescription.swift // Top News // // Created by Egor on 16.08.17. // Copyright © 2017 Egor. All rights reserved. // import UIKit class PopUpViewWithDescription: UIView { var delegate: PoPUpDelegate? @IBOutlet weak var descriptionLabel: UILabel! @IBAction func hidePopUpView(_ sender: Any) { delegate?.closePopUpWithDescription() } }
// // CatImages UITest.swift // Catty Project UITests // // Created by Сергей on 04.08.2020. // Copyright © 2020 Sergey Korshunov. All rights reserved. // import XCTest class CatImages_UITests: XCTestCase { let app = XCUIApplication() override func setUp() { app.launch() } func testTapFavouriteButton() { let favButtons = app.collectionViews["CatImagesCollection"].cells.buttons for _ in 1...10 { guard let nextButton = favButtons.allElementsBoundByIndex.randomElement() else { continue } if !nextButton.isHittable { continue } let id = nextButton.identifier nextButton.tap() XCTAssertNotEqual(id, nextButton.identifier) if Bool.random() { app.swipeUp() } } } func testOpenDetail() { let catCollection = app.collectionViews["CatImagesCollection"] let catCells = catCollection.cells XCTAssertTrue(catCollection.isHittable) XCTAssertTrue(catCells["CatCell"].waitForExistence(timeout: 1)) for _ in 1...10 { catCells.element(boundBy: Int.random(in: 0...6)).tap() XCTAssertFalse(catCollection.isHittable) app.navigationBack() XCTAssertTrue(catCollection.isHittable) if Bool.random() { app.swipeUp() } } } func testSearchFilters() { for _ in 1...10 { app.navigationBars.buttons["filterButton"].tap() if Bool.random() { app.segmentedControls.buttons.allElementsBoundByIndex.randomElement()?.tap() } if Bool.random() { app.switches.element.tap() } if Bool.random() { app.tables.cells.allElementsBoundByIndex.randomElement()?.tap() } if Bool.random() { app.buttons["Apply"].tap() } else { app.navigationBack() } } app.navigationBars.buttons["filterButton"].tap() app.tables.cells.firstMatch.tap() app.buttons["Apply"].tap() } }
// // ViewController.swift // ButinDV_HW2.10 // // Created by Dmitriy Butin on 28.02.2020. // Copyright © 2020 Dmitriy Butin. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var infoLabel: UILabel! var countryDetail: Countryes! override func viewDidLoad() { super.viewDidLoad() infoLabel.text = "Название: \(countryDetail.name)\n Столица: \(countryDetail.capital)\n Регион: \(countryDetail.region)\n Суб. Регион: \(countryDetail.subregion)\n Население: \(countryDetail.population) чел." } }
// // DeckType.swift // PlanningPoker // // Created by david.gonzalez on 27/10/16. // Copyright © 2016 BEEVA. All rights reserved. // enum DeckType { case numbers case sizes }
// // Character.swift // Rick-and-Morty // // Created by Mordvintseva Alena on 17/03/2019. // Copyright © 2019 Mordvintseva Alena. All rights reserved. // import Foundation import RealmSwift struct Character: Decodable { let id: Int let name: String let status: String let species: String let type: String let gender: String let origin: Location let location: Location let image: String let episode: [String] let url: String let created: String }
// // RegisterUserViewController.swift // Transact // // Created by An Nguyen on 4/2/20. // Copyright © 2020 An Nguyen. All rights reserved. // import UIKit class RegisterUserViewController: UIViewController { @IBOutlet weak var UserNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var firstNameTextField: UITextField! @IBOutlet weak var lastNameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var phoneNumberTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func registerButton(_ sender: Any) { print("register buttons selected") //validate required field are not empty if(firstNameTextField.text?.isEmpty)! || (lastNameTextField.text?.isEmpty)! || (emailTextField.text?.isEmpty)! || (passwordTextField.text?.isEmpty)! || (UserNameTextField.text?.isEmpty)! || (phoneNumberTextField.text?.isEmpty)! { //Display Alert messgae and return displayMessage(userMessage: "All field are required to fill in") return } //Create Activity Indicator let myActivityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.medium) //Position Activity Indicator in the center of the main view myActivityIndicator.center = view.center //If need, prevent Activity Indocator from hiding when stopAnimating() is called myActivityIndicator.hidesWhenStopped = false //Start Activity Indicator myActivityIndicator.startAnimating() view.addSubview(myActivityIndicator) //Send HTTP Requeste to register new user let myURL = "http://translocationserver.eastus.cloudapp.azure.com:3000/adduser" guard let resourceURL = URL(string: myURL) else {fatalError()} var request = URLRequest(url:resourceURL) request.httpMethod = "POST" //compose a query string request.addValue("application/json", forHTTPHeaderField: "content-type") request.addValue("application/json", forHTTPHeaderField: "Accept") let postString = [ "username": UserNameTextField.text!, "password": passwordTextField.text!, "firstname": firstNameTextField.text!, "lastname":lastNameTextField.text!, "email":emailTextField.text!, "phone":phoneNumberTextField.text!] as [String : String] do { request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted) } catch let error { print(error.localizedDescription) displayMessage(userMessage: "Something went wrong. Try again later 78.") return } let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in self.removeActivityIndicator(activityIndicator: myActivityIndicator) if error != nil{ self.displayMessage(userMessage: "Could not successfully perform this request. Please try again later 86") print("error=\(String(describing: error))") return } else{ self.displayMessage(userMessage: "Successfully register a new account. Please sign in to continue!") } } task.resume() } func removeActivityIndicator(activityIndicator: UIActivityIndicatorView){ DispatchQueue.main.async { activityIndicator.stopAnimating() activityIndicator.removeFromSuperview() } } @IBAction func signInButton(_ sender: Any) { print("sign in button selected") let signInViewController = self.storyboard?.instantiateViewController(identifier:"SignInViewController") as! SignInViewController self.present(signInViewController, animated: true) } func displayMessage(userMessage:String) -> Void { DispatchQueue.main.async { let alertController = UIAlertController(title: "Alert", message: userMessage, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in //Code in this block will trigger when OK button is tapped. print("OK button is selected") DispatchQueue.main.async { self.dismiss(animated: true, completion: nil) } } alertController.addAction(OKAction) self.present(alertController, animated: true, completion: nil) } } }
import Cocoa import SwiftUI struct SearchField: NSViewRepresentable { @Binding var text: String private var placeholder: String init(text: Binding<String>, placeholder: String) { _text = text self.placeholder = placeholder } private let refTag = 1000 func makeNSView(context: Context) -> NSVisualEffectView { let wrapperView = NSVisualEffectView() let searchField = NSSearchField(string: "") searchField.delegate = context.coordinator searchField.isBordered = false searchField.isBezeled = true searchField.bezelStyle = .roundedBezel searchField.placeholderString = placeholder searchField.translatesAutoresizingMaskIntoConstraints = false searchField.tag = refTag wrapperView.addSubview(searchField) NSLayoutConstraint.activate([ searchField.topAnchor.constraint(equalTo: wrapperView.topAnchor), searchField.bottomAnchor.constraint(equalTo: wrapperView.bottomAnchor), searchField.leadingAnchor.constraint(equalTo: wrapperView.leadingAnchor), searchField.trailingAnchor.constraint(equalTo: wrapperView.trailingAnchor) ]) return wrapperView } func updateNSView(_ nsView: NSVisualEffectView, context: Context) { (nsView.viewWithTag(refTag) as? NSSearchField)?.stringValue = text } func makeCoordinator() -> Coordinator { Coordinator { self.text = $0 } } final class Coordinator: NSObject, NSSearchFieldDelegate { var mutator: (String) -> Void init(_ mutator: @escaping (String) -> Void) { self.mutator = mutator } func controlTextDidChange(_ notification: Notification) { if let textField = notification.object as? NSTextField { mutator(textField.stringValue) } } } }
// // TimeUnit.swift // TimerX // // Created by 이광용 on 10/05/2019. // Copyright © 2019 GwangYongLee. All rights reserved. // import Foundation enum TimeUnit: CustomStringConvertible { case hour, minute, second, milliSecond var description: String { switch self { case .hour: return "hours" case .minute: return "min" case .second: return "sec" case .milliSecond: return "." } } }
// // SimpleTextField.swift // MockApp // // Created by M. Ensar Baba on 27.03.2019. // Copyright © 2019 MobileNOC. All rights reserved. // import UIKit class SimpleTextField: UITextField { public var doneAccessory: Bool = true { didSet { if doneAccessory { addDoneButtonOnKeyboard() } } } func addDoneButtonOnKeyboard() { let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50)) doneToolbar.barStyle = .default let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction)) let items = [flexSpace, done] doneToolbar.items = items doneToolbar.sizeToFit() self.inputAccessoryView = doneToolbar } @objc func doneButtonAction() { self.resignFirstResponder() } public init() { super.init(frame: .zero) self.initialize() } public override init(frame: CGRect) { super.init(frame: frame) self.initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } func initialize() { self.autocorrectionType = .no self.doneAccessory = true self.textColor = .black self.snp.makeConstraints { (make) in make.height.equalTo(40) } } }
// // PostInformationViewController.swift // OnTheMap // // Created by Aniket Ghode on 4/11/17. // Copyright © 2017 Aniket Ghode. All rights reserved. // import UIKit import MapKit class PostInformationViewController: UIViewController { // MARK: Properties var keyboardOnScreen = false var location: CLPlacemark? // MARK: Outlets @IBOutlet weak var locationTextField: UITextField! @IBOutlet weak var findLocationButton: UIButton! override func viewDidLoad() { super.viewDidLoad() subscribeToNotification(.UIKeyboardWillShow, selector: #selector(keyboardWillShow)) subscribeToNotification(.UIKeyboardWillHide, selector: #selector(keyboardWillHide)) subscribeToNotification(.UIKeyboardDidShow, selector: #selector(keyboardDidShow)) subscribeToNotification(.UIKeyboardDidHide, selector: #selector(keyboardDidHide)) } @IBAction func findLocationOnMap(_ sender: Any) { if locationTextField.text!.isEmpty { print("Empty string for location") displayError("Please enter location") return } ActivityIndicator.sharedInstance().startActivityIndicator(self) getLocationData(fromSearchString: locationTextField.text!) { (success, placeMark, errorString) in performUIUpdatesOnMain { ActivityIndicator.sharedInstance().stopActivityIndicator(self) if (success) { self.location = placeMark self.performSegue(withIdentifier: "findLocation", sender: self) } else { self.displayError(errorString) } } } } @IBAction func cancelButtonPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "findLocation" { let findLocationVC = segue.destination as! FindLocationViewController findLocationVC.mapAnnotation = self.location } } private func getLocationData(fromSearchString searchString: String, completionHandlerForLocationData: @escaping (_ success: Bool, _ locationData: CLPlacemark?, _ errorString: String?) -> Void ){ let geocoder = CLGeocoder() geocoder.geocodeAddressString(searchString, completionHandler: { (placemarks: [CLPlacemark]?, error: Error?) -> Void in if let placemark = placemarks?[0] { completionHandlerForLocationData(true, placemark, nil) } else { if let error = error { print(error) } completionHandlerForLocationData(false, nil, "Location data not found for the entered string, please try again!!") } }) } // display an error if something goes wrong private func displayError(_ errorString: String?) { let alertController = UIAlertController(title: "Error", message: errorString, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil)) self.present(alertController, animated: true, completion: nil) } } //MARK:- TextField Delegate extension PostInformationViewController: UITextFieldDelegate { // MARK: UITextFieldDelegate func textFieldDidBeginEditing(_ textField: UITextField) { textField.text = "" } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // MARK: Show/Hide Keyboard func keyboardWillShow(_ notification: Notification) { if !keyboardOnScreen { // Move View just enough to show the Find Location button view.frame.origin.y -= findLocationButton.frame.origin.y + 20.0 } } func keyboardWillHide(_ notification: Notification) { if keyboardOnScreen { view.frame.origin.y = 0 } } func keyboardDidShow(_ notification: Notification) { keyboardOnScreen = true } func keyboardDidHide(_ notification: Notification) { keyboardOnScreen = false } private func keyboardHeight(_ notification: Notification) -> CGFloat { let userInfo = (notification as NSNotification).userInfo let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue return keyboardSize.cgRectValue.height } private func resignIfFirstResponder(_ textField: UITextField) { if textField.isFirstResponder { textField.resignFirstResponder() } } } // MARK: - PostInformationViewController (Notifications) private extension PostInformationViewController { func subscribeToNotification(_ notification: NSNotification.Name, selector: Selector) { NotificationCenter.default.addObserver(self, selector: selector, name: notification, object: nil) } func unsubscribeFromAllNotifications() { NotificationCenter.default.removeObserver(self) } }
// // AuthAuthViewOutput.swift // Weather // // Created by KONSTANTIN KUSAINOV on 01/04/2018. // Copyright © 2018 Konstantin. All rights reserved. // protocol AuthViewOutput { /** @author KONSTANTIN KUSAINOV Notify presenter that view is ready */ func viewIsReady() func didSignOutAction() }
// // LiveFeedList.swift // BilibiliAPI // // Created by YaeSakura on 2017/7/22. // Copyright © 2017年 YaeSakura. All rights reserved. // import Foundation public struct LiveFeedList: Codable { }
// // ModuleFabric.swift // AirCollection // // Created by Lysytsia Yurii on 04.10.2020. // Copyright © 2020 Lysytsia Yurii. All rights reserved. // import UIKit enum ModuleFabric { static func createStaticTableModule() -> UIViewController { let view = StaticTableViewController() let presenter = StaticTablePresenter(view: view) view.output = presenter return view } static func createDynamicTableModule() -> UIViewController { let view = DynamicTableViewController() let presenter = DynamicTablePresenter(view: view) view.output = presenter return view } static func createDynamicUserTableModule(user: User) -> UIViewController { let view = DynamicUserTableViewController() let presenter = DynamicUserTablePresenter(user: user, view: view) view.output = presenter return view } static func createDynamicStoryTableModule(story: Story) -> UIViewController { let view = DynamicStoryTableViewController() let presenter = DynamicStoryTablePresenter(story: story, view: view) view.output = presenter return view } static func createTableHighlightAndSelectModule() -> UIViewController { let view = TableHighlightAndSelectViewController() let presenter = TableHighlightAndSelectPresenter(view: view) view.output = presenter return view } static func createCollectionHighlightAndSelectModule() -> UIViewController { let view = CollectionHighlightAndSelectViewController() let presenter = CollectionHighlightAndSelectPresenter(view: view) view.output = presenter return view } }
// // ViewController.swift // autolayout_stackview_tutorial // // Created by 백승엽 on 2020/11/20. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
// // FrutaApp.swift // Fruta // // Created by Katsuya Nakagawa on 2021/08/12. // import SwiftUI @main struct FrutaApp: App { @StateObject private var model = Model() var body: some Scene { WindowGroup { ContentView() .environmentObject(model) } } }
// // CreateNoteViewController.swift // Notes // // Created by Андрей Олесов on 9/7/19. // Copyright © 2019 Andrei Olesau. All rights reserved. // import UIKit class CreateNoteViewController: UIViewController, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var dateImage: UIImageView! @IBOutlet weak var dateField: UITextField! @IBOutlet weak var attachmentImage: UIImageView! @IBOutlet weak var cameraImage: UIImageView! @IBOutlet weak var doneNavButton: UIBarButtonItem! @IBOutlet var statusButtons: [UIButton]! @IBOutlet weak var text: UITextView! let placeHolder = "Write down your note" let imagePicker = UIImagePickerController() let datePiker = UIDatePicker() var note:BlackNote? var numOfCurrentNoteInNotesCollection:Int? var listOfNotesSize:Int? @IBAction func changeStatus(_ sender: UIButton) { if sender.backgroundColor == .black{ for i in 0..<statusButtons.count{ statusButtons[i].backgroundColor = .black } sender.backgroundColor = sender.tintColor } else { sender.backgroundColor = .black } } @IBAction func addNewNote(_ sender: UIBarButtonItem) { if text.text == placeHolder{ showWarning() } else{ saveNote() } } @IBAction func tapOnView(_ sender: UITapGestureRecognizer) { self.view.endEditing(true) } @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let pickerImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage{ attachmentImage.image = pickerImage } dismiss(animated: true, completion: nil) } private func saveNote(){ var imageToSave:UIImage? if attachmentImage.image == UIImage(named: "emptyImage"){ imageToSave = nil } else{ imageToSave = attachmentImage.image } if let note = note{ DBUtil.updateNote(newNote: BlackNote(id: note.id, text: text.text, date: Date(), status: self.status, remind: dateField.text?.toDateTime(), image:imageToSave)) if let date = dateField.text?.toDateTime(){ NotificationsUtil.createNotification(inSeconds: date.timeIntervalSinceNow, withIdentificator: String(note.id), withText: text.text) } else { NotificationsUtil.removeNotification(withIdentificator: [String(note.id)]) } } else{ let id = DefaultsUtil.getNewId() if let date = dateField.text?.toDateTime(){ NotificationsUtil.createNotification(inSeconds: date.timeIntervalSinceNow, withIdentificator: String(id), withText: text.text) } DBUtil.saveNote(noteToSave: BlackNote(id: id,text: text.text, date: Date(), status: self.status, remind: dateField.text?.toDateTime(), image:imageToSave)) } navigationController?.popToRootViewController(animated: true) } private var status: Status { switch getNumOfFilledStatusButton(){ case 0: return .normal case 1: return .specific case 2: return .important default: return .normal } } private func getNumOfFilledStatusButton() -> Int{ for i in 0..<statusButtons.count{ if statusButtons[i].backgroundColor != .black{ return i } } return 0 } func getDateFromPicker(){ let formatter = DateFormatter() formatter.dateFormat = "dd/MM/yyyy HH:mm" dateField.text = formatter.string(from: datePiker.date) } @objc func doneToolBarButtonAction(_ sender: UIBarButtonItem){ getDateFromPicker() view.endEditing(true) UIView.animate(withDuration: 0.7, animations: { self.dateImage.tintColor = .white }) } @objc func cancelToolBarButtonAction(_ sender: UIBarButtonItem){ dateField.text = nil view.endEditing(true) UIView.animate(withDuration: 0.7, animations: { self.dateImage.tintColor = .black }) } override func viewDidLoad() { super.viewDidLoad() setUpViewSettings() setUpStatusButtons() setUpTextNote() setUpDatePicker() setKeyBoardNotifications() setUpAttachemntGesture() } func setUpViewSettings(){ cameraImage.tintColor = .white dateImage.tintColor = .black dateImage.backgroundColor = .purple dateImage.layer.cornerRadius = 6 } func setKeyBoardNotifications(){ text.delegate = self self.addDoneButtonOnKeyboard() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } func setUpAttachemntGesture(){ imagePicker.delegate = self imagePicker.allowsEditing = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapOnImage(_ :))) cameraImage.addGestureRecognizer(tapGesture) cameraImage.isUserInteractionEnabled = true attachmentImage.tintColor = .white let tapGestureAttachment = UITapGestureRecognizer(target: self, action: #selector(tapOnAttachement(_ :))) attachmentImage.addGestureRecognizer(tapGestureAttachment) attachmentImage.isUserInteractionEnabled = true } func setUpDatePicker(){ dateField.inputView = datePiker datePiker.datePickerMode = .dateAndTime datePiker.backgroundColor = .black datePiker.setValue(UIColor.white, forKey: "textColor") let localeID = Locale.preferredLanguages.first datePiker.locale = Locale(identifier: localeID!) let toolBar = UIToolbar() toolBar.barTintColor = .black toolBar.sizeToFit() let doneToolBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneToolBarButtonAction(_:))) let cancelToolBarButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelToolBarButtonAction(_:))) let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolBar.setItems([cancelToolBarButton, flexSpace, doneToolBarButton], animated: true) dateField.inputAccessoryView = toolBar } @objc func tapOnAttachement(_ sender: UITapGestureRecognizer){ guard (attachmentImage.image != UIImage(named: "emptyImage")) else {return} let VC = storyboard?.instantiateViewController(withIdentifier: "FullScreenViewController") as! FullScreenViewController VC.imageForDisplay = attachmentImage.image navigationController?.pushViewController(VC, animated: true) } @objc func tapOnImage(_ sender: UITapGestureRecognizer){ let alert = UIAlertController(title: "Choose source", message: nil, preferredStyle: .actionSheet) let cameraAlert = UIAlertAction(title: "Camera", style: .default, handler: { (alert) in self.imagePicker.sourceType = .camera self.present(self.imagePicker, animated: true, completion: nil) }) let libraryAlert = UIAlertAction(title: "Library", style: .default, handler: { (alert) in self.imagePicker.sourceType = .photoLibrary self.present(self.imagePicker, animated: true, completion: nil) }) let cancelAlert = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(cameraAlert) alert.addAction(libraryAlert) alert.addAction(cancelAlert) present(alert, animated: true, completion: nil) } @objc func adjustForKeyboard(notification: Notification) { guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } let keyboardScreenEndFrame = keyboardValue.cgRectValue let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window) if notification.name == UIResponder.keyboardWillHideNotification { text.contentInset = .zero } else { text.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height - view.safeAreaInsets.bottom, right: 0) } text.scrollIndicatorInsets = text.contentInset let selectedRange = text.selectedRange text.scrollRangeToVisible(selectedRange) } func addDoneButtonOnKeyboard() { let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 50)) doneToolbar.barStyle = UIBarStyle.black doneToolbar.tintColor = .white let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil) let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneButtonAction)) var items = [UIBarButtonItem]() items.append(flexSpace) items.append(done) doneToolbar.items = items doneToolbar.sizeToFit() self.text.inputAccessoryView = doneToolbar } @objc func doneButtonAction() { self.view.endEditing(true) } func textViewDidBeginEditing(_ textView: UITextView) { if text.textColor == #colorLiteral(red: 0.5704585314, green: 0.5704723597, blue: 0.5704649091, alpha: 1) { text.text = "" text.textColor = UIColor.white } } func textViewDidEndEditing(_ textView: UITextView) { if text.text == "" { text.text = placeHolder text.textColor = #colorLiteral(red: 0.5704585314, green: 0.5704723597, blue: 0.5704649091, alpha: 1) } } func showWarning(){ let alert = UIAlertController(title: "You tried to create empty note", message: "Please, add note", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil) } private func setUpTextNote(){ if note != nil{ text.textColor = .white self.text.text = note!.text if let date = note?.remind?.toString(withTime: true){ self.dateField.text = date dateImage.tintColor = .white } if note?.image == nil{ attachmentImage.image = UIImage(named: "emptyImage") } else{ attachmentImage.image = note?.image } } else { text.textColor = #colorLiteral(red: 0.5704585314, green: 0.5704723597, blue: 0.5704649091, alpha: 1) text.text = placeHolder } } private func setUpStatusButtons(){ for i in 0..<statusButtons.count{ statusButtons[i].backgroundColor = .black } if note != nil { let numOfStatusButtons:Int = Int(note!.statusInInt()) - 1 statusButtons![numOfStatusButtons].backgroundColor = statusButtons![numOfStatusButtons].tintColor } else{ statusButtons[0].backgroundColor = statusButtons[0].tintColor } } }
// // DataManager.swift // Schuylkill // // Created by Sam Hicks on 1/30/21. // import CoreData import CoreMotion import Foundation public class CoreDataManager { static let shared = CoreDataManager() private var managedObjectContext: NSManagedObjectContext! public init() { abort() } init(completionClosure: @escaping () -> Void = {}) { // This resource is the same name as your xcdatamodeld contained in your project guard let modelURL = Bundle.main.url(forResource: "WorkoutModel", withExtension: "momd") else { fatalError("Error loading model from bundle") } // The managed object model for the application. It is a fatal error for // the application not to be able to find and load its model. guard let mom = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("Error initializing mom from: \(modelURL)") } let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = psc let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background) queue.async { guard let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else { fatalError("Unable to resolve document directory") } let storeURL = docURL.appendingPathComponent("DataModel.sqlite") do { try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil) // The callback block is expected to complete the User Interface and therefore // should be presented back on the main queue so that the user interface does // not need to be concerned with which queue this call is coming from. // DispatchQueue.main.sync(execute: completionClosure) } catch { fatalError("Error migrating store: \(error)") } } } func save() throws { managedObjectContext.performAndWait { // Perform operations with the context. do { try managedObjectContext.save() } catch { print("Error saving context: \(error)") objc_exception_rethrow() } } } } extension CoreDataManager { func writeAcceleramotorData(accelerometerData: CMAccelerometerData) { let data = NSEntityDescription.insertNewObject(forEntityName: "AccelerometerData", into: managedObjectContext) data.x = accelerometerData.acceleration.x data.y = accelerometerData.acceleration.y data.z = accelerometerData.acceleration.z data.timestamp = accelerometerData.timestamp } func writeAttitude(motion: CMDeviceMotion) { let data = NSEntityDescription.insertNewObject(forEntityName: "MotionAttitude", into: managedObjectContext) data.pitch = motion.attitude.pitch data.yaw = motion.attitude.yaw data.roll = motion.attitude.roll data.timestamp = motion.timestamp } }
// // Protocol.swift // 6.1-cta // // Created by Levi Davis on 12/3/19. // Copyright © 2019 Levi Davis. All rights reserved. // import Foundation protocol EventCellDelegate: AnyObject { func faveEvent(tag: Int) } protocol EventDelegate: AnyObject { func callActionSheet(tag: Int) }
// // DragGesture_3.swift // LearningSwiftUI // // Created by Metin HALILOGLU on 5/4/21. // import SwiftUI struct DragGesture_3: View { @State private var daireninKonumu = CGPoint(x: 100, y: 100) @State private var lblDaire = "100,100" init() { } var body: some View { VStack{ Text("Drag Gesture Örnek - 1").font(.largeTitle) Text("Giriş").font(.title).foregroundColor(.gray) .padding(.bottom, 40) Circle() .frame(width: 150, height: 150) .foregroundColor(Color.blue) .cornerRadius(40) .overlay(Text(lblDaire).bold()) .position(daireninKonumu) .gesture(DragGesture().onChanged({deger in self.daireninKonumu = deger.location self.lblDaire = "\(Int(deger.location.x)),\(Int(deger.location.y))" })) }.onAppear{ }.onDisappear{ } } } struct DragGesture_3_Previews: PreviewProvider { static var previews: some View { DragGesture_3() } }
// // BoroughList.swift // iOS // // Created by Chris Sanders on 6/23/20. // import SwiftUI struct BoroughList: View { @ObservedObject var routeInfoViewModel: RouteInfoViewModel @State private var showAboutModal = false var body: some View { NavigationView { List(content: content) .listStyle(InsetGroupedListStyle()) .navigationTitle(Text("Boroughs")) .navigationBarItems( trailing: VStack { Button(action: { self.showAboutModal.toggle() }, label: { Image(systemName: "info.circle") }) }) } .sheet(isPresented: $showAboutModal) { AboutModal() } } } extension BoroughList { func content() -> some View { ForEach(routeInfoViewModel.boroughs, id: \.self) { borough in NavigationLink(destination: BoroughDetail(borough: borough)) { Text(borough.name) } } } } struct BoroughList_Previews: PreviewProvider { static var routeInfoViewModel = RouteInfoViewModel() static var previews: some View { BoroughList(routeInfoViewModel: routeInfoViewModel) } }
// // ZLMainViewController.swift // TestProject // // Created by DanaLu on 2018/4/17. // Copyright © 2018年 gh. All rights reserved. // import UIKit import SnapKit struct Vector2D { var x = 0.0, y = 0.0 } extension Vector2D { static func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } } class ZLMainViewController: ZLBaseViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "首页"; // Do any additional setup after loading the view. let button: UIButton = UIButton() self.view.addSubview(button) button.backgroundColor = UIColor.blue button.snp.makeConstraints { (make) in make.center.equalToSuperview() make.size.equalTo(CGSize.init(width: 100, height: 100)) } button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func testError() throws -> String { let random = 123 return "123434" } // MARK: event @objc func buttonClicked() { // let domainChangeController = ZLDomainSwitchController() // self.navigationController?.pushViewController(domainChangeController, animated: true) // var a = 13 // var b = 54 // swapValue(&a, second: &b) // print(a,b) let a1: Vector2D = Vector2D(x: 10, y: 10) let a2: Vector2D = Vector2D(x: 15, y: 23) let a3 = a1 + a2 print(a3) } func swapValue<T: Equatable>(_ first: inout T, second: inout T) { let temp = first first = second second = temp } /* // 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. } */ }
// // ErrorMessage.swift // TakeawayAssignment // // Created by Alex Gordon on 19.11.17. // Copyright © 2017 Alex Gordon. All rights reserved. // import Foundation import UIKit enum ErrorMessage { case unknownError() case custom(error: Error) public func show(on viewController: UIViewController, customActionTitle: String = "Ok", customAction: (() -> ())? = nil) { let alert = UIAlertController(title: title(), message: message(), preferredStyle: .alert) let action = UIAlertAction(title: customActionTitle, style: .default) {(action) in if let customAction = customAction { customAction() } } alert.addAction(action) DispatchQueue.main.async { viewController.present(alert, animated: true, completion: nil) } } } private extension ErrorMessage { private func title() -> String { switch self { case .custom(_): return "Error" case .unknownError(): return "Oops..." } } private func message() -> String { switch self { case .custom(let error): return error.localizedDescription case .unknownError(): return "We are sorry, an unknown error has happened. Please try again later or call support." } } }
// // Test.swift // ReusableXib // // Created by Luis Henrique Mendonça Grassi on 02/05/17. // Copyright © 2017 Luis Henrique Mendonça Grassi. All rights reserved. // import UIKit @IBDesignable class Test: UIView { @IBOutlet weak var button : UIButton! @IBOutlet weak var label : UILabel! var contentView : UIView! override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } func xibSetup() { contentView = loadViewFromNib() // use bounds not frame or it'll be offset contentView.frame = bounds // Make the view stretch with containing view contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] // Adding custom subview on top of our view (over any custom drawing > see note below) addSubview(contentView) } func loadViewFromNib() -> UIView! { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil).first as! UIView return view } }
// // Match.swift // marcadores // // Created by Pereiro, Delfin on 18/06/16. // Copyright © 2016 Pereiro, Delfin. All rights reserved. // import Foundation class Match: NSObject { let id : NSInteger let tournamentId : NSInteger let name : String let statusShortDesc : String let homeTeam : Team let visitorTeam : Team init (id : NSInteger, tournamentId : NSInteger, name : String, statusShortDesc : String, homeTeam :Team, visitorTeam: Team){ self.id = id self.tournamentId = tournamentId self.name = name self.statusShortDesc = statusShortDesc self.homeTeam = homeTeam self.visitorTeam = visitorTeam } convenience init? (matchData : [String:AnyObject]?) { let teamsArray = matchData?["teams"] as? [[String:AnyObject]] if teamsArray?.count < 2 { return nil } if let id = matchData?["id"] as? NSInteger, tournamentId = matchData?["tournamentId"] as? NSInteger, name = matchData?["name"] as? String, statusShortDesc = matchData?["statusShortDesc"] as? String, homeTeam = Team(teamData: teamsArray?[0]), visitorTeam = Team(teamData: teamsArray?[1]){ self.init(id: id, tournamentId: tournamentId, name: name, statusShortDesc: statusShortDesc, homeTeam: homeTeam,visitorTeam: visitorTeam) } else { return nil } } }
// // MonthCal.swift // MonthViewerWidget // // Created by Le Huu Tri on 11/4/15. // Copyright © 2015 Le Huu Tri. All rights reserved. // import Foundation class MonthCal { let today = NSDate() let calendar = NSCalendar.currentCalendar() var day = 0 var month = 0 var year = 0 var dow = 0 var num_days = 0 var month_title: String { get { let formatter = NSDateFormatter() formatter.dateFormat = "MMMM yyyy" return formatter.stringFromDate(today).uppercaseString } } var dow_header = "Su Mo Tu We Th Fr Sa" init(m:Int? = nil, y:Int? = nil) { var components = calendar.components([.Year, .Month, .Day], fromDate: today) day = components.day if let um = m { month = um } else { month = components.month } if let uy = y { year = uy } else { year = components.year } components.year = year components.month = month components.day = 1 let firstday = calendar.dateFromComponents(components) components = calendar.components([.Weekday], fromDate: firstday!) dow = components.weekday num_days = calendar.rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate:firstday!).length } func to_text() -> String { var content = "" let col_len = 3; let front_padding = String(count: col_len * (dow - 1), repeatedValue: Character(" ")) content += front_padding for d in 1...num_days { let s = String(format: "%2d ", d) content += s if (dow + d - 1) % 7 == 0 { content += "\n" } } let back_padding = String(count: col_len * (35 - num_days) - 1, repeatedValue: Character(" ")) content += back_padding content += "\n" return content } }
import UIKit import Material class TableViewController: UITableViewController { var menuDelegate: BurgerMenuEnter! init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 60 } func reloadData() { tableView.reloadData() if tableView.numberOfRowsInSection(0) > 0 { tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0,inSection: 0), atScrollPosition: .Top, animated: true) } } }
import SwiftUI struct PagerView: View { //let posts: [Post] @EnvironmentObject var homeViewModel: HomeViewModel @EnvironmentObject var filterViewModel: FilterViewModel @State private var offset: CGFloat = 0 @State private var isUserSwiping: Bool = false //@Binding var postPos: Int @Binding var showNav: Bool @Binding var currentPost: Int var body: some View { GeometryReader { geometry in ScrollView(.vertical, showsIndicators: false) { VStack(alignment: .center, spacing: 0) { ForEach(Array(zip(self.homeViewModel.activePostList.indices, self.homeViewModel.activePostList)), id: \.0){ index, item in //ForEach(self.homeViewModel.activePostList, id: \.self){viewData in //ForEach(self.posts) { viewData in ZStack{ Group{ EventView(isSelected: Binding<Bool>(get: { self.homeViewModel.currentPost == self.homeViewModel.currentPost }, set: { _ in }), index: index, event: item) .frame(width: geometry.size.width, height: geometry.size.height) } Group{ if (self.homeViewModel.showingEventList){ EventListView(showNav:self.$showNav).environmentObject(self.homeViewModel) //.animation(.easeInOut(duration: 0.1)) //.transition(.asymmetric(insertion: .opacity, removal: .move(edge: .bottom))) }else{ ZStack{ HStack{ Rectangle().fill(Color.green).opacity(0.01).frame(width: geometry.size.width/2, height: geometry.size.height*0.6).padding(.trailing,1).onTapGesture { if self.homeViewModel.postPos != 0{ self.homeViewModel.decrementPost() } } Spacer() Rectangle().fill(Color.blue).opacity(0.01).frame(width: geometry.size.width/2, height: geometry.size.height*0.6).padding(.trailing,1).onTapGesture { self.homeViewModel.incrementPost() } } Spacer() } } } Group{ if (self.filterViewModel.GetActivatedFilter() != FILTERS.FORYOU && self.homeViewModel.postPos == 0){ VStack{ Spacer() Spacer() Spacer() FilterButtonsView(showNav:self.$showNav).environmentObject(self.homeViewModel).environmentObject(self.filterViewModel) Spacer() } } } } } } } .content.offset(y: self.isUserSwiping ? self.offset : CGFloat(self.homeViewModel.currentPost) * -geometry.size.height) .frame(height: geometry.size.height, alignment: .top) .gesture( DragGesture() .onChanged({ value in if self.homeViewModel.showingEventList == false && self.homeViewModel.postPos == 0{ self.isUserSwiping = true self.offset = value.translation.height + -geometry.size.height * CGFloat(self.homeViewModel.currentPost) } }) .onEnded({ value in if self.homeViewModel.showingEventList == false && self.homeViewModel.postPos == 0{ if value.predictedEndTranslation.height < -geometry.size.height / 2, self.homeViewModel.currentPost < self.homeViewModel.activePostList.count - 1 { self.homeViewModel.currentPost += 1 //zero //if self.homeViewModel.viewedPosts.contains(self.homeViewModel.currentPost){ // print("not the first time viewing post") //need to fix for different filter //}else{ // self.homeViewModel.viewedPosts.append(self.homeViewModel.currentPost) // print("first time viewing post") //} } if value.predictedEndTranslation.height > geometry.size.height / 2, self.homeViewModel.currentPost > 0 { self.homeViewModel.currentPost -= 1 } withAnimation { self.isUserSwiping = false } } }) ) } } } /* //ForEach(self.homeViewModel.activePostList) { viewData in ZStack{ EventView(event: self.homeViewModel.activePostList[self.homeViewModel.currentPost] ).environmentObject(self.homeViewModel).frame(width: geometry.size.width,height: geometry.size.height) VStack{ Spacer() Spacer() Spacer() if (self.filterViewModel.GetActivatedFilter() != FILTERS.FORYOU){ FilterButtonsView(showNav:self.$showNav).environmentObject(self.homeViewModel).environmentObject(self.filterViewModel) } Spacer() } }.frame(width: geometry.size.width, height: geometry.size.height) */ /* if (self.homeViewModel.showingEventList){ ZStack{ //Image(homeViewModel.activePostList[homeViewModel.currentPost].image) // .resizable() // .clipped() // .edgesIgnoringSafeArea(.all) //Image("loadingImage").resizable().clipped().edgesIgnoringSafeArea(.all) HStack { EventListView(showNav:self.$showNav).environmentObject(self.homeViewModel) .animation(.easeInOut(duration: 0.1)) .transition(.asymmetric(insertion: .opacity, removal: .move(edge: .bottom))) }.padding(.top,10) } } */ /* EventView(event: self.homeViewModel.activePostList[self.homeViewModel.currentPost]) .environmentObject(self.homeViewModel).frame(width: geometry.size.width,height: geometry.size.height) */
//===--- CocoaArray.swift - A subset of the NSArray interface -------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // To implement bridging, the core standard library needs to interact // a little bit with Cocoa. Because we want to keep the core // decoupled from the Foundation module, we can't use NSArray // directly. We _can_, however, use an @objc protocol with a // compatible API. That's _NSArrayCore. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims /// A wrapper around any `_NSArrayCore` that gives it /// `Collection` conformance. Why not make /// `_NSArrayCore` conform directly? It's a class, and I /// don't want to pay for the dynamic dispatch overhead. internal struct _CocoaArrayWrapper : RandomAccessCollection { typealias Indices = CountableRange<Int> var startIndex: Int { return 0 } var endIndex: Int { return buffer.count } subscript(i: Int) -> AnyObject { return buffer.objectAt(i) } /// Returns a pointer to the first element in the given non-empty `subRange` /// if the subRange is stored contiguously. Otherwise, return `nil`. /// /// The "non-empty" condition saves a branch within this method that can /// likely be better handled in a caller. /// /// - Note: This method should only be used as an optimization; it /// is sometimes conservative and may return `nil` even when /// contiguous storage exists, e.g., if array doesn't have a smart /// implementation of countByEnumerating. func contiguousStorage( _ subRange: Range<Int> ) -> UnsafeMutablePointer<AnyObject>? { _sanityCheck(!subRange.isEmpty) var enumerationState = _makeSwiftNSFastEnumerationState() // This function currently returns nil unless the first // subRange.upperBound items are stored contiguously. This is an // acceptable conservative behavior, but could potentially be // optimized for other cases. let contiguousCount = withUnsafeMutablePointer(&enumerationState) { self.buffer.countByEnumerating(with: $0, objects: nil, count: 0) } return contiguousCount >= subRange.upperBound ? UnsafeMutablePointer<AnyObject>(enumerationState.itemsPtr!) + subRange.lowerBound : nil } @_transparent init(_ buffer: _NSArrayCore) { self.buffer = buffer } var buffer: _NSArrayCore } #endif
// // DBManager.swift // DemoRealm // // Created by Taof on 11/8/19. // Copyright © 2019 Taof. All rights reserved. // import Foundation import RealmSwift class DBManager { // Khai báo biến tham chiếu tới cơ sở dữ liệu Realm private var database: Realm // Biến toàn cục chứa thực thể duy nhất của lớp DBManager static let sharedInstance = DBManager() static var autoID: Int = 0 var userData: UserDefaults! // Hàm khởi tạo private init() { // Khởi tạo database realm database = try! Realm() print(database.configuration.fileURL) userData = UserDefaults.standard // Đọc thông tin auID đã lưu nếu có DBManager.autoID = userData.integer(forKey: "autoID") } // Hàm lấy về danh sách dữ liệu có trong cơ sở dữ liệu func getDataFromDB() -> Results<Item> { let results: Results<Item> = database.objects(Item.self) return results } // Hàm insert dữ liệu func addData(object: Item) { try! database.write { // database.add(object, update: true) print("Add new object") userData.set(DBManager.autoID, forKey: "autoID") DBManager.autoID += 1 object.ID = DBManager.autoID database.add(object) } } // Hàm xoá tất cả dữ liệu func deleteAllFromDatabase() { try! database.write { database.deleteAll() } } // Hàm xoá 1 đối trượng trong cơ sở dữ liệu func deleteFromDb(object: Item) { try! database.write { database.delete(object) } } }
// // Request.swift // iVPN-Mac // // Created by Steven on 15/11/5. // Copyright © 2015年 Neva. All rights reserved. // import Alamofire import SwiftyJSON import SSObject // 天行VPN的API struct APIStore { struct API { let URL: String let method: Alamofire.Method let parameters: [String: AnyObject]? init(URL url: String, method: Alamofire.Method, parameters: [String: AnyObject]? = nil) { self.URL = url self.method = method self.parameters = parameters } } /********** 获取版本更新信息(GET) http://60.173.12.48/xksyvpn/ios/vesion_vpn_ini.php { "v": 1.04, "log": ["v1.04正式版发布", "1.连接国家服务器组优化", "2.修复部分用户不能登录的问题"] } **********/ static let updateVersion = API( URL: "http://60.173.12.48/xksyvpn/ios/vesion_vpn_ini.php", method: .GET) /********** 获取登录服务器列表(POST) http://114.80.116.142:81/serviceAddress/geturl.php 返回参数: docurl: 服务器 docurlbk: 备份服务器 disblexinjiang: [未知参数] ischeck: [未知参数] 返回数据样本: { "docurl": "http://106.185.48.189/loginserver/", "docurlbk": "http://114.80.116.142:81/loginserver/", "disblexinjiang": "0", "ischeck" = "1.06" } **********/ static let serverList = API( URL: "http://114.80.116.142:81/serviceAddress/geturl.php", method: .POST) /********** 注册账号(POST) http://106.185.48.189/loginserver/interFace/vpninterFace/register.php 请求参数: Equipment: iPhone7,2 keychain: AF9E5382-39B7-42E1-BF37-CA2A51526433 plat: 1 system: 9.0.2 返回参数与登陆服务器接口相同 **********/ static let register = API( URL: "interFace/vpninterFace/register.php", method: .POST, parameters: ["Equipment": $.platform, "keychain": $.UUID, "plat": 1, "system": $.system]) /********** 登陆获取服务器列表(POST) 参数: keychain: AF9E5382-39B7-42E1-BF37-CA2A51526433 plat: 1 http://106.185.48.189/loginserver/interFace/vpninterFace/login.php 返回参数说明: info: 登陆信息 "username": "AF9E5382-39B7-42E1-BF37-CA2A51526433", "password": "888888", "uid": "AF9E5382-39B7-42E1-BF37-CA2A51526433", "srvname": "免费体验套餐", "englishsrvname": "Free Trial Plan", "limitexpiration": 0, "srvid": 44, "enableuser": "1", "startime": "2015-07-08 15:54:30", "expiration": "0000-00-00 00:00:00", "enablenas": "0", "servstatus": -1 servergroup: 服务器列表数组 "vip": "0", "groupid": "3", "groupname": "免费-美国,弗里莱特", "image": "http://114.80.116.142:81/interFace/servimage/serve_meiguo.png", "englishname": "Free-Fremont, USA", "nas": 服务器配置信息 "nasname": "74.207.246.72", "shortname": "ipsec*USA09", "id": "33", "onlineuser": "17" **********/ static let login = API( URL: "interFace/vpninterFace/login.php", method: .POST, parameters: ["keychain": $.UUID, "plat": 1]) /********** 获取消息通知(GET) http://114.80.116.142:81/interFace/iosvpnnotice.php?channel=1 { "v": "1015", "con": "尊敬的天行用户:机房故障已修复!请您关闭软件,重新尝试连接,给您带来的不便,敬请谅解。", "enddatetime": "2015-9-11 15:30:00" } **********/ static let notice = API( URL: "http://114.80.116.142:81/interFace/iosvpnnotice.php?channel=1", method: .GET) } public extension Alamofire.Request { func responseJSONObject(handler: Response<JSON, NSError> -> Void) -> Self { return response(responseSerializer: ResponseSerializer(serializeResponse: { (request, response, data, error) -> Result<JSON, NSError> in guard error == nil else { return .Failure(error!) } if let d = data { let json = JSON(data: d) print("URL:\(request!.URL!)", json) return .Success(json) } else { return .Success(nil) } }), completionHandler: handler) } public func responseObjects<T: SSObject> (type: T.Type, completion: (NSURLRequest, NSURLResponse?, [T]?, NSError?)->()) -> Self { return response(responseSerializer: Request.JSONResponseSerializer(options: .AllowFragments), completionHandler: { (response) -> Void in if let error = response.result.error { completion(response.request!, response.response, nil, error) } else { let objects = T.arrayWithDictionarys(response.result.value as? [AnyObject]) as? [T] print("URL:\(response.request!.URL)", response.result.value) completion(response.request!, response.response, objects, nil) } }) } public func responseObject<T: SSObject> (type: T.Type, completion: (NSURLRequest, NSURLResponse?, T?, NSError?)->()) -> Self { return response(responseSerializer: Request.JSONResponseSerializer(options: .AllowFragments), completionHandler: { (response) -> Void in if let error = response.result.error { completion(response.request!, response.response, nil, error) } else { let object = T(dictionary: response.result.value as? [NSObject: AnyObject]) print("URL:\(response.request!.URL)", response.result.value) completion(response.request!, response.response, object, nil) } }) } } extension $ { // 掉用API class func request(api: APIStore.API, handler: (request: Alamofire.Request) -> Void ) { // 用是否包含http前缀判断是否为绝对路径 let hasHTTPPrefix = api.URL.lowercaseString.hasPrefix("http") if !hasHTTPPrefix && loginServerIP == nil { // 获取服务器IP request(APIStore.serverList, handler: { (request) -> Void in request.responseJSONObject({ (response) -> Void in if let json = response.result.value { // $.loginServerIP = json["docurl"].string $.loginServerIP = json["docurl"].string $.request(api, handler: handler) } }) }) } else { // 调用API var URL: String if hasHTTPPrefix { URL = api.URL } else { URL = loginServerIP!.stringByAppendingString(api.URL) } handler( request: Alamofire.request(api.method, URL, parameters: api.parameters) ) } } // 登录 class func login( handler: (info: LoginInfo?) -> Void ) { $.request(APIStore.login) { (request) -> Void in request.responseObject(LoginInfo.self) { (_, _, info, _) -> () in if info?.errorcode?.integerValue > 0 { // 掉用注册接口 $.request(APIStore.register, handler: { (request) -> Void in request.responseObject(LoginInfo.self) { (_, _, info, _) -> () in handler(info: info) } }) } else { // 登录成功,该干嘛干嘛 handler( info: info ) } } } } }
// // NavigationBar.swift // FlightMap-Demo-iOS // // Created by Intern on 22/06/20. // Copyright © 2020 Intern. All rights reserved. // import Foundation import UIKit class NavigationBar: UIView { // MARK: Outlets @IBOutlet weak var view: UIView! @IBOutlet weak var leftBarButton: UIButton! @IBOutlet weak var navigationTitle: UILabel! @IBOutlet weak var rightBarButton: UIButton! // MARK: Properties static let NIB_NAME = "NavigationBar" var title: String = "" { didSet { self.navigationTitle.text = title } } override func awakeFromNib() { } }
// // MySwiftUITreasureApp.swift // MySwiftUITreasure // // Created by mengjiao on 9/21/21. // import SwiftUI @main struct MySwiftUITreasureApp: App { var body: some Scene { WindowGroup { ScrollViewReaderDemo() } } }
// // OnboardPartFive.swift // Tipper // // Created by Ryan Romanchuk on 9/27/15. // Copyright © 2015 Ryan Romanchuk. All rights reserved. // import UIKit class OnboardPartFour: GAITrackedViewController, StandardViewController { var provider: AWSCognitoCredentialsProvider! var currentUser: CurrentUser! var className = "OnboardPartThree" var managedObjectContext: NSManagedObjectContext? var market: Market! weak var containerController: OnboardingViewController? override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "remoteRegistrationComplete", name: "didFailToRegisterForRemoteNotificationsWithError", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "remoteRegistrationComplete", name: "didRegisterForRemoteNotificationsWithDeviceToken", object: nil) // Do any additional setup after loading the view. } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func didTapButton(sender: UIButton) { log.verbose("") currentUser.registerForRemoteNotificationsIfNeeded() } func remoteRegistrationComplete() { log.verbose("") (parentViewController as? OnboardingPageControllerViewController)?.autoAdvance() } }
// // AylaNetworks+Utils.swift // iOS_Aura // // Created by Emanuel Peña Aguilar on 4/12/17. // Copyright © 2017 Ayla Networks. All rights reserved. // import Foundation import iOS_AylaSDK extension AylaNetworks { /// Aura extension of initialize with local device support /// /// - Parameters: /// - settings: Settings of the SDK /// - enableLocalDevices: true if local device plugin should be installed, false otherwise static func initialize(_ settings: AylaSystemSettings, withLocalDevices enableLocalDevices: Bool) { AylaNetworks.initialize(with: settings) if enableLocalDevices { let localDeviceManager = AuraLocalDeviceManager(); AylaNetworks.shared().installPlugin(localDeviceManager, id: PLUGIN_ID_DEVICE_CLASS) AylaNetworks.shared().installPlugin(localDeviceManager, id: AuraLocalDeviceManager.PLUGIN_ID_LOCAL_DEVICE) AylaNetworks.shared().installPlugin(localDeviceManager, id: PLUGIN_ID_DEVICE_LIST) } } }
@testable import TMDb import XCTest final class PersonServiceTests: XCTestCase { var service: PersonService! var apiClient: MockAPIClient! override func setUp() { super.setUp() apiClient = MockAPIClient() service = PersonService(apiClient: apiClient) } override func tearDown() { apiClient = nil service = nil super.tearDown() } func testDetailsReturnsPerson() async throws { let expectedResult = Person.johnnyDepp let personID = expectedResult.id apiClient.result = .success(expectedResult) let result = try await service.details(forPerson: personID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, PeopleEndpoint.details(personID: personID).path) } func testCombinedCreditsReturnsCombinedCredits() async throws { let mock = PersonCombinedCredits.mock() let expectedResult = PersonCombinedCredits(id: mock.id, cast: mock.cast, crew: mock.crew) let personID = expectedResult.id apiClient.result = .success(expectedResult) let result = try await service.combinedCredits(forPerson: personID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, PeopleEndpoint.combinedCredits(personID: personID).path) } func testMovieCreditsReturnsMovieCredits() async throws { let mock = PersonMovieCredits.mock() let expectedResult = PersonMovieCredits(id: mock.id, cast: mock.cast, crew: mock.crew) let personID = expectedResult.id apiClient.result = .success(expectedResult) let result = try await service.movieCredits(forPerson: personID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, PeopleEndpoint.movieCredits(personID: personID).path) } func testTVShowCreditsReturnsTVShowCredits() async throws { let mock = PersonTVShowCredits.mock() let expectedResult = PersonTVShowCredits(id: mock.id, cast: mock.cast, crew: mock.crew) let personID = expectedResult.id apiClient.result = .success(expectedResult) let result = try await service.tvShowCredits(forPerson: personID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, PeopleEndpoint.tvShowCredits(personID: personID).path) } func testImagesReturnsImageCollection() async throws { let expectedResult = PersonImageCollection.mock() let personID = expectedResult.id apiClient.result = .success(expectedResult) let result = try await service.images(forPerson: personID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, PeopleEndpoint.images(personID: personID).path) } func testKnownForReturnsShows() async throws { let credits = PersonCombinedCredits.mock() let personID = credits.id apiClient.result = .success(credits) let topCastShows = Array(credits.cast.prefix(10)) let topCrewShows = Array(credits.crew.prefix(10)) var topShows = topCastShows + topCrewShows topShows = topShows.reduce([], { shows, show in var shows = shows if !shows.contains(where: { $0.id == show.id }) { shows.append(show) } return shows }) topShows.sort { $0.popularity ?? 0 > $1.popularity ?? 0 } let expectedResult = Array(topShows.prefix(10)) let result = try await service.knownFor(forPerson: personID) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, PeopleEndpoint.combinedCredits(personID: personID).path) } func testPopularWithDefaultParametersReturnsPeople() async throws { let expectedResult = PersonPageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.popular() XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, PeopleEndpoint.popular().path) } func testPopularReturnsPeople() async throws { let expectedResult = PersonPageableList.mock() apiClient.result = .success(expectedResult) let result = try await service.popular(page: nil) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, PeopleEndpoint.popular().path) } func testPopularWithPageReturnsPeople() async throws { let expectedResult = PersonPageableList.mock() let page = expectedResult.page apiClient.result = .success(expectedResult) let result = try await service.popular(page: page) XCTAssertEqual(result, expectedResult) XCTAssertEqual(apiClient.lastPath, PeopleEndpoint.popular(page: page).path) } }
// // Root.swift // Fraktal // // Created by Dmitry Levsevich on 3/18/17. // Copyright © 2017 Home. All rights reserved. // import Foundation import ReactiveSwift final class Root { fileprivate var child = MutableProperty<Child>(.none) enum Child { case none case main(MainViewModel) } init() { let vm = MainViewModel(dependencies: MainViewModel.Dependencies(), context: MainViewModel.Context()) child.value = .main(vm) } } extension Root: Presentable { struct RootPresentersContainer { let mainPresenter: Presenter<AnyPresentableType<MainPresentersContainer>> let nonePresenter: Presenter<()> } typealias Presenters = RootPresentersContainer var present: (Presenters) -> Disposable? { return { presenters in let childPresenter = Presenter<Child>.UI { switch $0 { case .none: return presenters.nonePresenter <~ () case .main(let viewModel): return presenters.mainPresenter <~ viewModel } } return CompositeDisposable([ childPresenter.serial() <~ self.child]) } } }
// // ResultsViewController.swift // RockPaperScissors // // Created by Evan Barbour on 2/17/19. // Copyright © 2019 Evan Barbour. All rights reserved. // import UIKit enum GameChoices: String { case rock = "Rock" case paper = "Paper" case scissors = "Scissors" static func randomChoice() -> GameChoices { let randChoice = Int(arc4random_uniform(3)) let choices = ["Rock", "Paper", "Scissors"] return GameChoices(rawValue: choices[randChoice])! } } class ResultsViewController: UIViewController { var userChoice: GameChoices! let opponentChoice: GameChoices = GameChoices.randomChoice() @IBOutlet weak var resultsLabel: UILabel! @IBOutlet weak var playagainButton: UIButton! override func viewDidLoad() { super.viewDidLoad() gameResult() } func gameResult() { var text: String let match = "\(userChoice.rawValue) vs. \(opponentChoice.rawValue)" switch (userChoice!, opponentChoice) { case let (user, opponent) where user == opponent: text = "\(match): it's a tie!" case (.rock, .scissors), (.scissors, .paper), (.paper, .rock): text = "\(match): you win!" default: text = "\(match): you lose!" } resultsLabel.text = text } @IBAction func playAgain() { performSegue(withIdentifier: "playAgain", sender: playagainButton) } }
// // ViewController.swift // Network // // Created by Evgeniy on 22.08.2021. // import UIKit class ViewController: UIViewController { private let urlRequestFactory = APIURLRequestsFactory(cachePolicy: .reloadIgnoringCacheData) private let urlBuilder = APIURLBuilder(baseURL: "https://jsonplaceholder.typicode.com", apiVersion: "", apiVersionPrefix: "") static let reachabilityChecker: ReachabilityChecking = { #if targetEnvironment(simulator) return ReachabilityChecker(hostname: nil, reachabilityStrategy: .wifiOnly) #else return ReachabilityChecker(hostname: nil, reachabilityStrategy: .wifiOrCellular) #endif }() private var dataTaskBuilder: APIDataTasksBuilder? @IBAction func sendRequest() { let request: URLRequest let startDate = Date() do { let methodPath = MethodPath.todos(identifier: 1) let url = try urlBuilder.buildURL(methodPath: methodPath) request = try urlRequestFactory.loadTodos(url: url) } catch { debugPrint(error) return } let completion: LoadTodoCorrectTaskCompletion = { response in debugPrint("Execution: \(Date().timeIntervalSince(startDate))") switch response { case let .success(responseObject): debugPrint(responseObject) case let .failure(error): debugPrint(error) } } let dataTask = dataTaskBuilder?.buildDataTask(request: request, completion: completion) dataTask?.resume() } @IBAction func sendWrongRequest() { let request: URLRequest do { let methodPath = MethodPath.todos(identifier: 1) let url = try urlBuilder.buildURL(methodPath: methodPath) request = try urlRequestFactory.loadTodos(url: url) } catch { debugPrint(error) return } let completion: LoadTodoWrongTaskCompletion = { response in switch response { case .success: debugPrint("YOPEE") case let .failure(error): debugPrint(error) } } let dataTask = dataTaskBuilder?.buildDataTask(request: request, completion: completion) dataTask?.resume() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. do { try ViewController.reachabilityChecker.start() } catch {} dataTaskBuilder = buildDataTaskBuilder() } private func buildDataTaskBuilder() -> APIDataTasksBuilder { let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.httpCookieAcceptPolicy = .never sessionConfiguration.httpCookieStorage = nil sessionConfiguration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData sessionConfiguration.urlCache = nil let urlSession = URLSession(configuration: sessionConfiguration) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let dataTaskBuilder = BaseDataTasksBuilder( session: urlSession, reachabilityChecker: ViewController.reachabilityChecker ) return APIDataTasksBuilder( baseDataTasksBuilder: dataTaskBuilder, decoder: decoder ) } }
// // NowViewController.swift // WeatherProj // // Created by Julien Bankier on 5/25/17. // Copyright © 2017 Julien Bankier. All rights reserved. // import UIKit class NowViewController: UIViewController { private let dataManager = DataManager(baseURL: API.AuthenticatedBaseURL) let currentTemp = UILabel(frame: CGRect(x: 100, y: 100, width: 1000, height: 1000)) // calling data on main thread override func viewDidLoad() { super.viewDidLoad() dataManager.weatherDataForLocation(latitude: Defaults.Latitude, longitude: Defaults.Longitude) { (response, error) in let weather = WeatherData(JSON: response) // get current time, find the one that corresponds, and display it let temp = weather?.hourData[0].temperature let tempString = String(describing: temp) self.currentTemp.text = tempString self.setUpView() } self.view.backgroundColor = UIColor.gray } override func viewDidAppear(_ animated: Bool) { setUpView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func setUpView(){ self.view.addSubview(currentTemp) } }
// // EventViewController.swift // Book Phui // // Created by Thanh Tran on 3/12/17. // Copyright © 2017 Half Bird. All rights reserved. // import UIKit class EventViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var events: [Event] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tableView.register(UINib(nibName: String(describing: EventViewCell.self), bundle: nil), forCellReuseIdentifier: "Cell") self.navigationController?.isNavigationBarHidden = false self.navigationItem.title = "Sự kiện" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Api.getEvents(completion: { events in self.events = events self.tableView.reloadData() }) } } extension EventViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return events.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! EventViewCell let item = self.events[indexPath.row] cell.selectionStyle = .none cell.config(with: item) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 250 } }
// // HistoryViewController.swift // reactive-running-app // // Created by Michal Klein on 13/02/2017. // Copyright © 2017 Michal Klein. All rights reserved. // import UIKit import ReactiveSwift final class HistoryViewController: BaseViewController { private enum Constants { static let activityCellHeight: CGFloat = 100 } // MARK: Dependencies let viewModel: HistoryViewModeling let activityDetailVCFactory: ActivityDetailViewControllerFactory weak var tableView: UITableView! // MARK: Initializers required init(viewModel: HistoryViewModeling, activityDetailVCFactory: @escaping ActivityDetailViewControllerFactory) { self.viewModel = viewModel self.activityDetailVCFactory = activityDetailVCFactory super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Bindings private func setupBindings() { tableView.reactive.reloadData <~ viewModel.outputs.activities.map { _ in } } // MARK: View Life Cycle override func loadView() { super.loadView() title = L10n.activityTitle.string let tableView = UITableView() tableView.rowHeight = Constants.activityCellHeight tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none tableView.backgroundColor = .cycloLightGray view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalToSuperview() } self.tableView = tableView } override func viewDidLoad() { super.viewDidLoad() setupBindings() } } // MARK: UITableViewDelegate extension HistoryViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let activity = viewModel.outputs.activities.value[indexPath.item] navigationController?.pushViewController(activityDetailVCFactory(activity), animated: true) } } extension HistoryViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.outputs.activities.value.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ActivityCell = tableView.dequeueReusableCell(for: indexPath) cell.viewModel = ActivityCellViewModel(activity: viewModel.outputs.activities.value[indexPath.item]) return cell } }
// // SwiftIconFont+UITabBarItem.swift // SwiftIconFont // // Created by Sedat Gökbek ÇİFTÇİ on 13.10.2017. // Copyright © 2017 Sedat Gökbek ÇİFTÇİ. All rights reserved. // import UIKit public extension UITabBarItem { func iconWithSwiftIcon(defaultIcon: SwiftIcon) { self.image = UIImage.icon(from: defaultIcon.font, iconColor: defaultIcon.color, code: defaultIcon.code, imageSize: defaultIcon.imageSize, ofSize: defaultIcon.fontSize) } func icon(from font: Fonts, code: String, iconColor: Color, imageSize: CGSize, ofSize size: CGFloat) { self.image = UIImage.icon(from: font, iconColor: iconColor, code: code, imageSize: imageSize, ofSize: size) } func iconWithSelectedIcon(from defaultIcon: SwiftIcon, selectedIcon: SwiftIcon) { self.image = UIImage.icon(from: defaultIcon.font, iconColor: defaultIcon.color, code: defaultIcon.code, imageSize: defaultIcon.imageSize, ofSize: defaultIcon.fontSize) self.selectedImage = UIImage.icon(from: selectedIcon.font, iconColor: selectedIcon.color, code: selectedIcon.code, imageSize: selectedIcon.imageSize, ofSize: selectedIcon.fontSize) } }
//: Playground - noun: a place where people can play import UIKit /* "4" RULES OF INITIALIZERS 1. DI's in subclasses MUST call DIs from superclasses * DIs ALWAYS delegate UPward to other DIs and NEVER CIs 2. CIs MUST call other initializers (DIs or CIs) defined in the SAME class. * CIs always delegate sideways and may NOT walk up the chain to a superclass 3. CIs MUST end up redirecting to a DI in the same class and it must do so by calling a DI declared in the same class as itself 4. Any class that inherits OR overrides its superclass MAY inherit its convenience initializers */ /* DESIGNATED INITIALIZERS - responsible for initializing all properties in class AND require all values to be sent in for each property */ class RootClass { var a : Int // Local storage for property a // Designated initializer init(a: Int) { self.a = a // initialization for a } } // CREATE AN INSTANCE var newInstance = RootClass(a: 4) print(newInstance.a) // ANOTHER EXAMPLE class Person { let name: String let age: Int init (name: String, age: Int){ // DESIGNATED INITIALIZER self.name = name self.age = age } /* CONVENIENCE INITIALIZER - provides secondary construction utility, or just helps out with a value that doesn't require manual input e.g. timestamp ,enables it to piggyback on other DI's or to create defaults, CIs must delegate to another CI or DIs - think train rails */ convenience init (name: String) { self.init(name: name, age: 18) } convenience init(){ self.init(name: "Cartman") } } // CREATE SOME INSTANCES let aPerson = Person(name: "Dave", age: 30) print("Here's \(aPerson.name), who's \(aPerson.age) years old") let aPersonWithDefaultAge = Person(name: "Sue") print("Here's \(aPersonWithDefaultAge.name), who's \(aPersonWithDefaultAge.age) years old by default") let defaultPerson = Person() print("Here's the default clone of a person, \(defaultPerson.name), who's \(defaultPerson.age) years old by default") /* SUBCLASS - the subclass' DI sets its new properties 1st and then its superclass' DI in their immediate parent class */ class ChildClass: RootClass { var b : String init(a: Int, b: String) { // DESIGNATED INITIALIZER self.b = b // initialize own property first // Need to call super init to bring in the properties from the superclass super.init(a:a) /* initialize superclass 2nd, DI walks UP the superclass ladder super.init redirects to superclass */ } /* CI's delegate across like train rails and always end at some point to a DI in same class DI's of subclasses MUST call other DI's of their superclass therefore if you try to call the CI of the superclass = compile error*/ convenience override init(a: Int) { // OVERRIDE using a CI self.init(a:a, b:"red") } } var newChildInstance = ChildClass(a: 5, b: "blue") var newChildInstanceConv = ChildClass(a: 6) print(newChildInstance.b) print(newChildInstance.a) print(newChildInstanceConv.b) print(newChildInstanceConv.a) // ANOTHER SUBCLASS EXAMPLE class Student: Person { let studentId: String init(studentId: String, name: String, age: Int){ self.studentId = studentId super.init(name:name, age:age) // Note that the CI's from the superclass don't carry over if no override CI used, // test this out by omitting name or age at instantiation, before adding the CI below } // OVERRIDE using a CI, will inherit CI's of the superclass convenience override init(name:String, age:Int) { self.init(studentId: "001a", name: name, age: age) } } let aStudent = Student(studentId: "123a", name: "Bob", age: 20) print("Here's \(aStudent.name), who's \(aStudent.age) years old with student id #\(aStudent.studentId)") let StudentB = Student( name: "Bob") print("Here's \(StudentB.name), who's \(StudentB.age) years old (CI from superclass carries over) with default student id #\(StudentB.studentId)") /* Subclasses inherit DI's & CI's if they don't add new variables that need initialization this applies to classes that don't define add'l stored properties and classes whose new properties are default values defined ouside initializers E.G. var x: Int = 5 */ class Employee: Person { var company: String = "Apple Inc" } var anEmployee = Employee() print("\(anEmployee.name) is an employee of \(anEmployee.company).")
// // VideoCompositionWriter.swift // AVFoundationMyExample // // Created by Евгений Полюбин on 24.08.2021. // import AVFoundation import UIKit class VideoCompositionWriter: NSObject { func merge(arrayVideos: [AVAsset]) -> AVMutableComposition { let mainComposition = AVMutableComposition() let compositionVideoTrack = mainComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) compositionVideoTrack?.preferredTransform = CGAffineTransform(rotationAngle: .pi / 2) var insertTime = CMTime.zero for videoAsset in arrayVideos { try! compositionVideoTrack?.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: .video)[0], at: insertTime) insertTime = CMTimeAdd(insertTime, videoAsset.duration) } return mainComposition } func mergeAudioVideo(_ documentDirectory: URL, filename: String, clips: [String], completion: @escaping (Bool, URL?) -> Void) { var assets: [AVAsset] = [] var totalDuration = CMTime.zero for clip in clips { let videoFile = documentDirectory.appendingPathComponent(clip) let asset = AVURLAsset(url: videoFile) assets.append(asset) totalDuration = CMTimeAdd(totalDuration, asset.duration) } let mixComposition = merge(arrayVideos: assets) guard let audioUrl = Bundle.main.url(forResource: "Bill_Withers_Sunshine", withExtension: "mp3") else { print("Music not found in bundle") return } let loadedAudioAsset = AVURLAsset(url: audioUrl) let audioTrack = mixComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: 0) do { try audioTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: totalDuration), of: loadedAudioAsset.tracks(withMediaType: .audio)[0], at: .zero) } catch { print("Failed to insert music") } let url = documentDirectory.appendingPathComponent("out_\(filename)") guard let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) else { return } exporter.outputURL = url exporter.outputFileType = .mov exporter.shouldOptimizeForNetworkUse = true exporter.exportAsynchronously { DispatchQueue.main.async { if exporter.status == .completed { completion(true, exporter.outputURL) } else { completion(false, nil) } } } } }
// // Datastore.swift // incognito // // Created by yang zhong on 3/3/18. // Copyright © 2018 yang zhong. All rights reserved. // import Foundation import Firebase import Kingfisher class DataStore { // Instantiate the singleton object. static let shared = DataStore() static let storage = Storage.storage() private var ref: DatabaseReference! private var Users: [User]! private var Posts: [Post]! private var Comments: [Comment]! // Making the init method private means only this class // can instantiate an object of this type. private init() { // Get a database reference. // Needed before we can read/write to/from the firebase database. ref = Database.database().reference() } func getUser(index: Int) -> User { return Users[index] } func countPost() -> Int { return Posts.count } func reloadPost(){ loadPost() } func reloadComment() { loadComment() } func loadUser() { // Start with an empty array of User objects. Users = [User]() // Fetch the data from Firebase and store it in our internal people array. // This is a one-time listener. ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in // Get the top-level dictionary. let value = snapshot.value as? NSDictionary if let users = value { // Iterate over the person objects and store in our internal people array. for p in users { let id = p.key as! String let user = p.value as! [String:Any] let username = user["username"] let password = user["password"] let email = user["email"] let class_year = user["class_year"] let posts = user["posts"] let gender = user["gender"] let avatar = user["avatar"] let newUser = User(username: username! as! String, password: password! as! String, email:email! as! String , class_year: class_year! as! String, posts : posts as! [String], gender: gender! as! String, avatar: avatar! as! String ) self.Users.append(newUser) } } }) { (error) in print(error.localizedDescription) } } // Add a new user. func addUser(id: String, user: User) { // define array of key/value pairs to store for this person. let userRecord = [ "username": user.username, "password": user.password, "email": user.email, "class_year": user.class_year, "posts": user.posts, "gender" : user.gender, "avatar" : user.avatar, ] as [String : Any] // Save to Firebase. self.ref.child("users").child(id).setValue(userRecord) // Also save to our internal array, to stay in sync with what's in Firebase. Users.append(user) } // ********************************************************************** // ******************* ******************** // ******************* load comment and add comment ******************** // ******************* ******************** // ********************************************************************** func getPost(index: Int) -> Post{ return Posts[index] } func getPostByID(idArray: [String]) -> [Post]{ var postsListByID = [Post]() for id in idArray { if id == "None" { //print("y") //continue } else if let i = Posts.index(where: {$0.id == id}) { postsListByID.append(Posts[i]) //print("gg") } //print("id: \(id)") //print(Posts.index(where: {$0.id == id})) } return postsListByID } func loadPost(){ Posts = [Post]() ref.child("posts").observeSingleEvent(of: .value, with: { (snapshot) in // Get the top-level dictionary. let value = snapshot.value as? NSDictionary if let posts = value { // Iterate over the person objects and store in our internal people array. for p in posts { let post_id = p.key as! String let post = p.value as! [String:Any] let post_user = post["post_user"] let post_image = post["post_image"] let post_location = post["post_location"] let post_text = post["post_text"] let post_time = post["post_time"] let post_like = post["post_like"] let post_comment = post["post_comment"] let newPost = Post(id: post_id, uid:post_user as! String, text:post_text as! String, image: post_image as! [String], location: post_location as! String, time: post_time as! String, like : post_like as! [String], comments: post_comment as! [String]) self.Posts.append(newPost) } } }) { (error) in print(error.localizedDescription) } } var PostImage = ["None"] var current_key = "None" // *************************** Add Post. *********************************** func addPost(post: Post, ImgList: [UIImage]) { // Create a new key in firease that represent this new post's id. let key = self.ref.child("posts").childByAutoId().key // save the key in dataStore wide. self.current_key = key // Get current user's id. let userID = Auth.auth().currentUser?.uid let postRecord:[String:Any] = [ "id": key, "post_user": post.uid, "post_image": post.image, "post_location": post.location, "post_text": post.text, "post_time": post.time, "post_like": post.like, "post_comment" : post.comments ] // Upload the post object to firebase. self.ref.child("posts").child(key).setValue(postRecord) // Update the user's post list. ref.child("users").child(userID!).child("posts").observeSingleEvent(of: .value, with: { (snapshot) in // Get user value let value = snapshot.value as? NSArray var post_list = value as! [String] post_list.append(key) self.ref.child("users").child(userID!).updateChildValues(["posts" : post_list]) }) { (error) in print(error.localizedDescription) } // Save image url to post_image in Firebase. var Finish:Int = ImgList.count - 1 while (Finish >= 0){ var data = NSData() data = UIImageJPEGRepresentation(ImgList[Finish], 0.8)! as NSData let filePath = "\(Auth.auth().currentUser!.uid)/\(key)/\(Finish)" Finish = Finish - 1 let metaData = StorageMetadata() metaData.contentType = "image/jpg" DataStore.storage.reference().child(filePath).putData(data as Data, metadata: metaData){(metaData,error) in if let error = error { print(error.localizedDescription) return }else{ //store downloadURL let downloadURL = metaData!.downloadURL()!.absoluteString self.ref.child("posts").child(self.current_key).observeSingleEvent(of: .value, with: { (snapshot) in // Get user value let Post = snapshot.value as? NSDictionary let IMages = Post?["post_image"] as? [String] var Postimage = IMages as! [String] Postimage.append(downloadURL) post.image.append(downloadURL) self.ref.child("posts").child(self.current_key).updateChildValues(["post_image" : Postimage]) }){ (error) in print(error.localizedDescription) } } } } post.id = key // Also save to our internal array, to stay in sync with what's in Firebase. Posts.append(post) } // ********************************************************************** // ******************* ******************** // ******************* load comment and add comment ******************** // ******************* ******************** // ********************************************************************** var cur_commentkey = "None" func getComment(id: String) -> Any { for i in Comments { if (i.id == id) { return i } } return 0 } func loadComment(){ // Start with an empty array of User objects. Comments = [Comment]() // Fetch the data from Firebase and store it in our internal Comments array. // This is a one-time listener. ref.child("comments").observeSingleEvent(of: .value, with: { (snapshot) in // Get the top-level dictionary. let value = snapshot.value as? NSDictionary if let comments = value{ // Iterate over the person objects and store in our internal people array. for c in comments { let comment_id = c.key as! String let comment = c.value as! [String:Any] let comment_postid = comment["comment_postid"] let comment_time = comment["comment_time"] let comment_by = comment["comment_by"] let comment_text = comment["comment_text"] // Create a comment object. let newComment = Comment(id: comment_id, post_id: comment_postid as! String, text: comment_text as! String, comment_by: comment_by! as! String, time: comment_time! as! String) self.Comments.append(newComment) } } }) { (error) in print(error.localizedDescription) } } func addComment(comment:Comment){ // define array of key/value pairs to store for this comment. let key = self.ref.child("comments").childByAutoId().key let postid = comment.post_id comment.id = key // define array of key/value pairs to store for this comment. let commentRecord = [ "comment_id": key, "comment_postid": comment.post_id, "comment_time": comment.time, "comment_by": comment.comment_by, "comment_text": comment.text ] as [String : Any] // save to Firebase self.ref.child("comments").child(key).setValue(commentRecord) // also save to our internal array, to stay in sync with what's in Firebase Comments.append(comment) print("the last comment is \(Comments[Comments.count-1].id)") if let found = Posts.index(where: {$0.id == postid}){ Posts[found].comments.append(key) } // Update the user's post's comments list. ref.child("posts").child(postid).child("post_comment").observeSingleEvent(of: .value, with: { (snapshot) in // Get user value let value = snapshot.value as? NSArray var comments = value as! [String] comments.append(key) self.ref.child("posts").child(postid).updateChildValues(["post_comment" : comments]) }) { (error) in print(error.localizedDescription) } Comments.append(comment) } // Get All Comments to Current user. func getCommentByID(UserPostList: [Post]) -> [Comment] { var UserComments = [Comment]() // Check each post, find all comments of this post. for i in UserPostList { let CommentOfthisPost = i.comments // load the Comments with given commentID. for comment in CommentOfthisPost { if comment != "none" { if let found = Comments.index(where: {$0.id == comment}) { // Add it into the UsersComment array. UserComments.append(Comments[found]) } } } } return UserComments } // Show user's avatar. func ShowAvatarName(uid: String, Avatar: UIImageView, Name: UILabel){ let usersRef = Database.database().reference().child("users").child(uid) // observe the current user once and store all the basic information. usersRef.observeSingleEvent(of: .value, with: { snapshot in if !snapshot.exists() { return} let userInfo = snapshot.value as! NSDictionary let username = userInfo["username"] as! String Name.text = username let profileUrl = userInfo["avatar"] as! String // If the user hasn't set up avatar, use the default one. if (profileUrl == "None"){ Avatar.image = UIImage(named: "icon2") return } // Download the avatar from firebase and update the poster's avatar. // let storageRef = Storage.storage().reference(forURL: profileUrl) // storageRef.downloadURL(completion: { (url, error) in // if let error = error{ // print(error.localizedDescription) // return // }else{ // let data = NSData(contentsOf: url!) // let image = UIImage(data: data! as Data) // Avatar.image = image // } // }) // Implementation on downloading user avatar. let url = URL(string: (profileUrl)) Avatar.kf.setImage(with: url,placeholder: UIImage(named: "icon2")) }) } // Update user's gender and class func updateGenderClassName (gender: String, classYear: String, userName: String) { let userID = Auth.auth().currentUser?.uid self.ref.child("users").child(userID!).updateChildValues(["gender" : gender]) self.ref.child("users").child(userID!).updateChildValues(["class_year" : classYear]) self.ref.child("users").child(userID!).updateChildValues(["username" : userName]) print ("Successfully update user's name, gender and class") } // Like function. func DidpressLike( postid: String, Likeperson: String) -> Int{ // 0 means cancel liked. 1 means didlike. var status = 1 let currentPost = self.ref.child("posts").child(postid) // observe the current post once and store all the basic information. currentPost.observeSingleEvent(of: .value, with: { snapshot in if !snapshot.exists() { return} let PostInform = snapshot.value as! NSDictionary let Likelist = PostInform["post_like"] as! [String] var NewLikelist = Likelist // If the user has liked the post, Then he chose to dislike. if Likelist.contains(Likeperson){ NewLikelist = NewLikelist.filter{$0 != Likeperson} status = 0 print("User dislikes the post and the status is \(status)") // The user has not liked the post. Click to like. } else { NewLikelist.append(Likeperson) status = 1 print(" User Liked the post and the status is \(status)") } self.ref.child("posts").child(postid).updateChildValues(["post_like" : NewLikelist]) }){ (error) in print(error.localizedDescription) } return status } // ************ Delete a post. ******************** func deletePost(postid: String, UserId: String) -> Void { // Delete the post from Posts. self.ref.child("posts").child(postid).removeValue() var localcomments = [String]() // Delete all comments to the corresponding post. _ = self.ref.child("comments").observeSingleEvent(of: .value, with: { (snapshot) in // Get user value let value = snapshot.value as? NSDictionary if let commentList = value { for p in commentList { let comment1 = p.value as! [String:Any] localcomments.append(comment1["comment_id"] as! String) if comment1["comment_postid"] as! String == postid { // Remove Current's post's all comments. self.ref.child("comments").child(comment1["comment_id"] as! String).removeValue() } } } }) { (error) in print(error.localizedDescription) } // Delete comments in local cache. for c in localcomments { self.Comments = self.Comments.filter{$0.id != c} } // Delete the Post from current user's postlist. let usersRef = Database.database().reference().child("users").child(UserId) // observe the current user once and store all the basic information. usersRef.observeSingleEvent(of: .value, with: { snapshot in if !snapshot.exists() { return} let userInfo = snapshot.value as! NSDictionary let userpost = userInfo["posts"] as! [String] var NewPostlist = userpost NewPostlist = NewPostlist.filter{$0 != postid} self.ref.child("users").child(UserId).updateChildValues(["posts" : NewPostlist]) }) // Delete Current Post from local cache. Posts = Posts.filter{$0.id != postid} } // Fetch Comment details。 func GetComment(Avatar: UIImageView, Postid: String, index: Int, CurrentPost: Post, Content: UILabel, time: UILabel) { let commentID = CurrentPost.comments[index+1] let Comment1 = getComment(id: commentID) as! Comment let commentUser = Comment1.comment_by Content.text = Comment1.text // get comment time and display let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" dateFormatter.timeZone = TimeZone.current let commentTime = dateFormatter.date(from: Comment1.time) // let lastUpate = post.time as? Date if commentTime != nil{ time.text = timeAgoSinceDate(commentTime!) // print(timeAgoSinceDate(lastUpdate!)) } else{ time.text = Comment1.time } // time.text = Comment1.time as! String // Fetch Comment user's avatar. let usersRef = self.ref.child("users").child(commentUser) // observe the current user once and store all the basic information. usersRef.observeSingleEvent(of: .value, with: { snapshot in if !snapshot.exists() { return} let userInfo = snapshot.value as! NSDictionary // Using KingFisher to download and save avatar. let UserUrl = userInfo["avatar"] as! String let url = URL(string: (UserUrl)) Avatar.kf.setImage(with: url) print("show comment avatar") }) } func timeAgoSinceDate(_ date:Date, numericDates:Bool = false) -> String { let calendar = Calendar.current let unitFlags: Set<Calendar.Component> = [.minute, .hour, .day, .weekOfYear, .month, .year, .second] let now = Date() let earliest = now < date ? now : date let latest = (earliest == now) ? date : now let components = calendar.dateComponents(unitFlags, from: earliest, to: latest) if (components.year! >= 2) { return "\(components.year!) years ago" } else if (components.year! >= 1){ if (numericDates){ return "1 year ago" } else { return "Last year" } } else if (components.month! >= 2) { return "\(components.month!) months ago" } else if (components.month! >= 1){ if (numericDates){ return "1 month ago" } else { return "Last month" } } else if (components.weekOfYear! >= 2) { return "\(components.weekOfYear!) weeks ago" } else if (components.weekOfYear! >= 1){ if (numericDates){ return "1 week ago" } else { return "Last week" } } else if (components.day! >= 2) { return "\(components.day!) days ago" } else if (components.day! >= 1){ if (numericDates){ return "1 day ago" } else { return "Yesterday" } } else if (components.hour! >= 2) { return "\(components.hour!) hours ago" } else if (components.hour! >= 1){ if (numericDates){ return "1 hour ago" } else { return "An hour ago" } } else if (components.minute! >= 2) { return "\(components.minute!) minutes ago" } else if (components.minute! >= 1){ if (numericDates){ return "1 minute ago" } else { return "A minute ago" } } else if (components.second! >= 3) { return "\(components.second!) seconds ago" } else { return "Just now" } } func GetCommentForProfile(UserAvatar: UIImageView, CommentContent: UILabel, CommentTime: UILabel, comment: Comment) { let commentUser = comment.comment_by CommentContent.text = comment.text // get comment time and display let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" dateFormatter.timeZone = TimeZone.current let commentTime = dateFormatter.date(from: comment.time) // let lastUpate = post.time as? Date if commentTime != nil{ CommentTime.text = timeAgoSinceDate(commentTime!) // print(timeAgoSinceDate(lastUpdate!)) } else{ CommentTime.text = comment.time } // time.text = Comment1.time as! String // Fetch Comment user's avatar. let usersRef = self.ref.child("users").child(commentUser) // observe the current user once and store all the basic information. usersRef.observeSingleEvent(of: .value, with: { snapshot in if !snapshot.exists() { return} let userInfo = snapshot.value as! NSDictionary // Using KingFisher to download and save avatar. let UserUrl = userInfo["avatar"] as! String let url = URL(string: (UserUrl)) UserAvatar.kf.setImage(with: url) print("show comment avatar") }) } }
// // Matrix.swift // Metal Tutorial 1 // // Created by Sean Fitzgerald on 1/8/19. // Copyright © 2019 Sean Fitzgerald. All rights reserved. // import Foundation import Metal // TODO: Include ShaderHelper.h using an objective-C bridging header // FUTURE TODO: allow arbitrary number of axes struct Matrix { // Static Properties static let GPU = MTLCreateSystemDefaultDevice() static let CommandQueue = Matrix.GPU?.makeCommandQueue() static let DefaultLibrary = Matrix.GPU?.makeDefaultLibrary() // Matrix-Matrix Kernels static let HadamardKernel = Matrix.DefaultLibrary?.makeFunction(name: "hadamardProductKernel") static let SubtractKernel = Matrix.DefaultLibrary?.makeFunction(name: "subtractKernel") static let AddKernel = Matrix.DefaultLibrary?.makeFunction(name: "addKernel") // Matrix-RowVector Kernels static let HadamardProductRowVectorKernel = Matrix.DefaultLibrary?.makeFunction(name: "hadamardProductRowVectorKernel") static let AddRowVectorKernel = Matrix.DefaultLibrary?.makeFunction(name: "addRowVectorKernel") static let SubtractRowVectorKernel = Matrix.DefaultLibrary?.makeFunction(name: "subtractRowVectorKernel") // Matrix-ColumnVector Kernels static let HadamardProductColumnVectorKernel = Matrix.DefaultLibrary?.makeFunction(name: "hadamardProductColumnVectorKernel") static let AddColumnVectorKernel = Matrix.DefaultLibrary?.makeFunction(name: "addColumnVectorKernel") static let SubtractColumnVectorKernel = Matrix.DefaultLibrary?.makeFunction(name: "subtractColumnVectorKernel") // Matrix-Scalar Kernels static let MultiplyScalarKernel = Matrix.DefaultLibrary?.makeFunction(name: "multiplyScalarKernel") static let AddScalarKernel = Matrix.DefaultLibrary?.makeFunction(name: "addScalarKernel") static let SubtractScalarKernel = Matrix.DefaultLibrary?.makeFunction(name: "subtractScalarKernel") // Common Parallel Operation Kernels static let ExponentKernel = Matrix.DefaultLibrary?.makeFunction(name: "exponentKernel") let dataTexture:MTLTexture let width:Int let height:Int init(data:[Float], width:Int, height:Int) { // TODO: Build an init that accepts an array with a structure self.width = width self.height = height let texDescriptor = MTLTextureDescriptor.textureBufferDescriptor(with: .r32Float, width: self.width * self.height, resourceOptions: .storageModeManaged, usage: [.shaderRead, .shaderWrite]) guard let dataTexture = Matrix.GPU?.makeTexture(descriptor: texDescriptor) else { print("Could not create texture in Matrix initializer") exit(EXIT_FAILURE) } self.dataTexture = dataTexture self.dataTexture.replace(region: MTLRegionMake1D(0, self.width * self.height), mipmapLevel: 0, withBytes: UnsafeRawPointer(data), bytesPerRow: 64) } // TODO: Implement transpose in shader or here??? // TODO: Implement sum() function // TODO: Protect each function against incorrect dimensions for arguments // Overload Operators // TODO: Overload the following operators // https://www.raywenderlich.com/2271-operator-overloading-in-swift-tutorial // * vector(Rx1, 1xC), + vector(Rx1, 1xC), - vector(Rx1, 1xC) (These should be special cases in the normal *, +, and - overloads) // +=, -=, ++, --, // /, /=, *=, // ^ // ==, !=, <, >, >=, <= // @ (matrix multiply), ~ (dot product), exp(Matrix) static func *(left:Matrix, right:Matrix) -> Matrix { if (left.width == right.width) && (left.height == right.height) { return executeSymmetricResultKernel(left: left, right: right, function: self.HadamardKernel!) } else if (right.width == 1) && (right.height == left.height) { // TODO: Implement (below is incorrect) return executeSymmetricResultKernel(left: left, right: right, function: self.HadamardKernel!) } else if (right.height == 1) && (right.width == left.width) { // TODO: Implement (below is incorrect) return executeSymmetricResultKernel(left: left, right: right, function: self.HadamardKernel!) } else { // TODO: Make errors more descriptive print("Argument error between left and right.") exit(1) } } static func +(left:Matrix, right:Matrix) -> Matrix { if (left.width == right.width) && (left.height == right.height) { return executeSymmetricResultKernel(left: left, right: right, function: self.HadamardKernel!) } else if (right.width == 1) && (right.height == left.height) { // TODO: Implement (below is incorrect) return executeSymmetricResultKernel(left: left, right: right, function: self.HadamardKernel!) } else if (right.height == 1) && (right.width == left.width) { // TODO: Implement (below is incorrect) return executeSymmetricResultKernel(left: left, right: right, function: self.HadamardKernel!) } else { // TODO: Make errors more descriptive print("Argument error between left and right.") exit(1) } } static func -(left:Matrix, right:Matrix) -> Matrix { if (left.width == right.width) && (left.height == right.height) { return executeSymmetricResultKernel(left: left, right: right, function: self.HadamardKernel!) } else if (right.width == 1) && (right.height == left.height) { // TODO: Implement (below is incorrect) return executeSymmetricResultKernel(left: left, right: right, function: self.HadamardKernel!) } else if (right.height == 1) && (right.width == left.width) { // TODO: Implement (below is incorrect) return executeSymmetricResultKernel(left: left, right: right, function: self.HadamardKernel!) } else { // TODO: Make errors more descriptive print("Argument error between left and right.") exit(1) } } static func executeSymmetricResultKernel(left:Matrix, right:Matrix, function:MTLFunction) -> Matrix { let result = Matrix(data:[Float](repeating: 0, count: left.width*left.height), width:left.width, height:left.height) do { guard let computePipelineState = try Matrix.GPU?.makeComputePipelineState(function: function), let commandBuffer = Matrix.CommandQueue?.makeCommandBuffer(), let computeEncoder = commandBuffer.makeComputeCommandEncoder() else { print("Could not create initialize GPU stuff in overloaded *()") exit(EXIT_FAILURE) } computeEncoder.setComputePipelineState(computePipelineState) computeEncoder.setTexture(left.dataTexture, index: 0) computeEncoder.setTexture(right.dataTexture, index: 1) computeEncoder.setTexture(result.dataTexture, index: 2) let threadGroupSize = MTLSize(width: 16, height: 1, depth: 1) let threadGroupCount = MTLSize(width: 1, height: 1, depth: 1) computeEncoder.dispatchThreadgroups(threadGroupCount, threadsPerThreadgroup: threadGroupSize) computeEncoder.endEncoding() commandBuffer.commit() commandBuffer.waitUntilCompleted() } catch { print("Could not initialize ComputePipelineState in overloaded *()") exit(EXIT_FAILURE) } return result } }
// // graphql.swift // GraphQL // // Created by Darrell Richards on 11/8/20. // import Foundation import Apollo class GraphqlService { static let shared = GraphqlService() private(set) lazy var apollo = ApolloClient(url: URL(string: "http://localhost:3000")!) func clearCache() { apollo.clearCache() } }
// // NavigationBuilder.swift // ViperProyectoUdemy // // Created by Jose Leoncio Quispe Rodriguez on 9/27/20. // Copyright © 2020 Jose Leoncio Quispe Rodriguez. All rights reserved. // import UIKit typealias NavigationFactory = (UIViewController) -> (UINavigationController) class NavigationBuilder { //metodo suficiente para hacer la navegacion static func Builder(rootview: UIViewController) -> UINavigationController { let navigationControler = UINavigationController(rootViewController: rootview) //metodo para darle color forma y estilo al tituclo del controlador // navigationControler.navigationBar.tintColor = UIColor.systemBlue let font = UIFont.systemFont(ofSize: 30) let shadow = NSShadow() //shadow.shadowColor = shadow.shadowBlurRadius = 6 let atributes: [NSAttributedString.Key: Any] = [ .font: font, .foregroundColor: UIColor.brown, .shadow: shadow ] let fontLarge = UIFont.systemFont(ofSize: 60) let atributesLarge: [NSAttributedString.Key: Any] = [ .font: fontLarge, .foregroundColor: UIColor.brown, .shadow: shadow ] navigationControler.navigationBar.titleTextAttributes = atributes navigationControler.navigationBar.largeTitleTextAttributes = atributesLarge navigationControler.navigationBar.prefersLargeTitles = true return navigationControler } }
// // Helper.swift // Barrowmatic // // Created by Peyman Attarzadeh on 6/10/16. // Copyright © 2016 PeymaniuM. All rights reserved. // import Foundation import UIKit class Helper { static let instance = Helper() func ScaleImage(image : UIImage, width:CGFloat, height: CGFloat) -> UIImage { let oldWidth = image.size.width let oldHeight = image.size.height let scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight let newWidth = oldWidth * scaleFactor let newHeight = oldHeight * scaleFactor let scaledImage = self.CreateScaledImage(image, toSize: CGSizeMake(newWidth, newHeight)) return scaledImage } private func CreateScaledImage(image:UIImage, toSize:CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(toSize, false, UIScreen.mainScreen().scale) image.drawInRect(CGRectMake(0, 0, toSize.width, toSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
// // User.swift // {{cookiecutter.app_name}} // // Copyright © 2020 {{cookiecutter.company_name}}. All rights reserved. // import Foundation public struct User: Codable { public let login: String public let id: String? public let nodeId: String public let avatarUrl: URL public let gravatarId: String public let url: URL public let receivedEventsUrl: URL public let type: String public init(login: String, id: String, nodeId: String, avatarUrl: URL, gravatarId: String, url: URL, receivedEventsUrl: URL, type: String) { self.login = login self.id = id self.nodeId = nodeId self.avatarUrl = avatarUrl self.gravatarId = gravatarId self.url = url self.receivedEventsUrl = receivedEventsUrl self.type = type } } extension User { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) login = try values.decodeWithString(forKey: .login) id = try values.decodeWithOptionalString(forKey: .id) nodeId = try values.decodeWithString(forKey: .nodeId) avatarUrl = try values.decode(URL.self, forKey: .avatarUrl) gravatarId = try values.decodeWithString(forKey: .gravatarId) url = try values.decode(URL.self, forKey: .url) receivedEventsUrl = try values.decode(URL.self, forKey: .receivedEventsUrl) type = try values.decodeWithString(forKey: .type) } }
// // MainScoreboardController.swift // ScoreboardAndRidingTimeClock // // Created by David Rice on 1/30/16. // Copyright © 2016 DrsCreations. All rights reserved. // import Foundation
// // Constants.swift // Classy // // Created by admin on 1/19/18. // Copyright © 2018 kimboss. All rights reserved. // import Foundation let USERdb = "Users" let profileURLdb = "profileUrl"
// // HomepageViewController.swift // StudyUp // // Created by Mitchel Eppich on 2017-03-04. // Copyright © 2017 SFU Health++. All rights reserved. // import UIKit import FirebaseAuth class HomepageViewController: UIViewController, UserDelegate { @IBOutlet var profileBtn: UIButton! @IBOutlet var timerBtn: UIButton! @IBOutlet var mapBtn: UIButton! @IBOutlet var groupBtn: UIButton! @IBOutlet weak var supportBtn: UIButton! @IBOutlet var menuBtn: [UIButton]! // At the start of the app retreive the current user local save if applicable // Check if able to connect to the server, if able : check if the local save is either // newer or older than the server save, depending on which save is newer, retain the newer data // and overwrite the other data // This allows for users to user our app offline and have no worry about data loss at any time of use override func viewDidLoad() { super.viewDidLoad() updateTableGroup.removeAll() updateTableUser.removeAll() if current_user.verified { self.mapBtn.isEnabled = true self.groupBtn.isEnabled = true } applyShadow(view: mapBtn) applyShadow(view: supportBtn) applyShadow(view: groupBtn) applyShadow(view: timerBtn) applyShadow(view: profileBtn) } // Check if the user is verified to allow certain functions // if the user is not logged in then show the login/signup screen override func viewDidAppear(_ animated: Bool) { current_user.checkNotification(self) } 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. } */ //func tap (gesture: UITapGestureRecognizer){ @IBAction func tap(_ sender: AnyObject) { //@IBAction func tap(_ sender: UITapGestureRecognizer) { print("\n\n\n\tap recgonizer working for home page \n\n\n") let buttonArray = menuBtn.sorted() { a, b in return a.layer.zPosition < b.layer.zPosition } for (i,image) in buttonArray.enumerated() { //for (i,image) in menuBtn.enumerated() { let location = sender.location(in: image) let alpha = image.alphaAtPoint(point: location) print ("alpha = ",alpha, "\n") if alpha > 50.0 { print("selected image #\(i) \(image.layer.zPosition)\n\n\n\n\n\n\n") if !current_user.verified { if i == 3 || i == 1 { print("Not verified") return } } view.addSubview(image) image.sendActions(for: .touchUpInside) return } } } func applyShadow(view: UIView){ view.layer.shadowColor = UIColor.black.cgColor view.layer.shadowOffset = CGSize(width: 2, height: 3) view.layer.shadowOpacity = 0.8 view.layer.shadowRadius = 5 view.clipsToBounds = false } } extension UIButton { func alphaAtPoint(point: CGPoint) -> CGFloat { var pixel: [UInt8] = [0, 0, 0, 0] let colorSpace = CGColorSpaceCreateDeviceRGB(); let alphaInfo = CGImageAlphaInfo.premultipliedLast.rawValue guard let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: alphaInfo) else { return 0 } context.translateBy(x: -point.x, y: -point.y); self.layer.render(in: context) let floatAlpha = CGFloat(pixel[3]) return floatAlpha } }
// // Item+CoreDataClass.swift // SplitBill // // Created by Clive Liu on 11/23/20. // // import Foundation import CoreData @objc(Item) public class Item: NSManagedObject { private var selected = false } extension Item: SBObject { var isSelected: Bool { get { return selected } set { selected = newValue } } var identifier: String { return name } var amount: Double { guard let count = owners?.count else { return value } return (value * (1 + (tax / 100))) / max(1, Double(count)) } var toll: Double { return tax } }
// // AuthViewController.swift // CuidooApp // // Created by Júlio John Tavares Ramos on 19/11/19. // Copyright © 2019 Júlio John Tavares Ramos. All rights reserved. // import UIKit class AuthViewController: UIViewController { //Outlets @IBOutlet weak var userTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButtonOutlet: UIButton! @IBAction func backToAuthScreenUnwind(_ segue : UIStoryboardSegue){ } override func viewDidLoad() { super.viewDidLoad() self.loginButtonOutlet.layer.cornerRadius = 13 } @IBAction func loginButton(_ sender: Any) { //Validar os campos let email = userTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" let password = passwordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" MatchServices.userLogin(email: email, password: password) { //Atualiza meu usuario local MatchServices.getLoggedUser(completion: { (loggedUser) in if let isBaba = loggedUser?.isBaba { if isBaba { self.performSegue(withIdentifier: "SearchBabaSegue", sender: nil) } else { self.performSegue(withIdentifier: "SearchSegue", sender: nil) } } else { print("Não foi possível acessar esse dado!") } }) } } }
// // CitiesProtocols.swift // carWash // // Created by Juliett Kuroyan on 26.11.2019. // Copyright © 2019 VooDooLab. All rights reserved. // import Foundation // MARK: - View protocol CitiesViewProtocol: class { func update(currentCity: String, cities: [String], titles: [String]) func requestDidSend() func responseDidRecieve() } // MARK: - Presenter protocol CitiesPresenterProtocol: class { func popView() func viewDidLoad() func didSelectCity(row: Int, isCurrent: Bool) } // MARK: - Router protocol CitiesRouterProtocol { func popView() } // MARK: - Interactor protocol CitiesInteractorProtocol: class { func getCities(onSuccess: @escaping ([CityResponse]) -> (), onFailure: @escaping () -> ()?) func postCity(city: String, onSuccess: @escaping () -> (), onFailure: @escaping () -> ()?) } // MARK: - Configurator protocol CitiesConfiguratorProtocol { }
// // LoginViewController.swift // OnboardingAssignmentmorning // // Created by Abdulghafar Al Tair on 5/31/16. // Copyright © 2016 Abdulghafar Al Tair. All rights reserved. // import UIKit class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailField: EmailValidatedTextField! @IBOutlet weak var passwordField: UITextField! var email:String? var password:String? override func viewDidLoad() { super.viewDidLoad() title = "Login" emailField.delegate = self passwordField.delegate = self // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { self.navigationController?.navigationBarHidden = false } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // passwordField.delegate = nil if textField == emailField { // textfield.text + string because we still havent made the change when we call textfield here. Change is made when we return true print("Email \(textField.text! + string)") } else if textField == passwordField { print("Password \(textField.text!)") } return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginButtonTapped(sender: UIButton) { email = emailField.text password = passwordField.text UserController.sharedInstance.loginUser(email!, password: password!, presentingViewController: self, viewControllerCompletionFunction: {(user,message) in self.loginComplete(user,string:message)}) } func loginComplete(user: User?, string: String?) -> () { if (user != nil) { let alert = UIAlertController(title:"Login Successful", message:"You will now be logged in", preferredStyle: UIAlertControllerStyle.Alert) let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action) in //when the user clicks "Ok", do the following let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.navigateToBoardViewNavigationController() }) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) // at this point we are happy to login the user. So lets store the persistant value NSUserDefaults.standardUserDefaults().setValue("TRUE", forKey: "userIsLoggedIn") } else if (string != nil) { print("\(string)") let alert = UIAlertController(title:"Login Failed", message:string!, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: { }) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // File.swift // MC2 User Profile // // Created by Thomas Pratama Putra on 17/07/19. // Copyright © 2019 thomaspputra. All rights reserved. // import UIKit extension UIViewController { func loadUserDefaults() -> User { let defaults = UserDefaults.standard if defaults.string(forKey: Key.userFullName) == nil { let generateUser = User(userProfileImage: #imageLiteral(resourceName: "userPhotoProfile_1"), userFullName: "JENNIE RUBY JANE", userBowlerStatus: "OCCASIONAL PLAYER", userGender: "FEMALE", userWeight: 50, userHeight: 163) generateUser.userBallWeight = generateUser.ballWeight() defaults.set((generateUser.userProfileImage).jpegData(compressionQuality: 1.0), forKey: Key.userProfileImage) defaults.set(generateUser.userFullName, forKey: Key.userFullName) defaults.set(generateUser.userBowlerStatus, forKey: Key.userBowlerStatus) defaults.set(generateUser.userGender, forKey: Key.userGender) defaults.set(generateUser.userWeight, forKey: Key.userWeight) defaults.set(generateUser.userHeight, forKey: Key.userHeight) defaults.set(generateUser.userBallWeight, forKey: Key.userBowlingBallWeight) return generateUser } else { let generateUser = User(userProfileImage: UIImage(data: defaults.data(forKey: Key.userProfileImage)!, scale: 1.0)!, userFullName: defaults.string(forKey: Key.userFullName)!, userBowlerStatus: defaults.string(forKey: Key.userBowlerStatus)!, userGender: defaults.string(forKey: Key.userGender)!, userWeight: defaults.integer(forKey: Key.userWeight), userHeight: defaults.integer(forKey: Key.userHeight)) generateUser.userBallWeight = generateUser.ballWeight() return generateUser } } } extension UILabel { func startBlink() { UIView.animate(withDuration: 0.8, delay:0.0, options:[.allowUserInteraction, .curveEaseInOut, .autoreverse, .repeat], animations: { self.alpha = 0.02 }, completion: nil) } func stopBlink() { layer.removeAllAnimations() alpha = 1.0 } }
// // ViewController.swift // Unit System Conversion Practice // // Created by susanne on 2020/6/12. // Copyright © 2020 Mike Wu. All rights reserved. // import UIKit class ViewController: UIViewController, UIPopoverPresentationControllerDelegate { var inMetricMode: Bool! @IBOutlet var lengthDescription: UILabel! @IBOutlet var lengthTextField: UITextField! @IBOutlet var widthDescription: UILabel! @IBOutlet var widthTextField: UITextField! @IBOutlet var summaryLabel: UILabel! @IBOutlet var resultLabel: UILabel! @IBOutlet var metricButton: UIButton! @IBOutlet var imperialButton: UIButton! override func viewDidLoad() { super.viewDidLoad() resultLabel.layer.cornerRadius = 10.0 metricButton.layer.cornerRadius = 5.0 imperialButton.layer.cornerRadius = 5.0 inMetricMode = true } // Disable Keyboard from screen when tapped elsewhere override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { UIView.animate(withDuration: 0) { self.view.endEditing(true) } } // Texfield touched to edit, pop-up input Reminder @IBAction func textFieldsEditBegan(_ sender: UITextField) { performSegue(withIdentifier: "popoverSegue", sender: sender) } // Whenver Edit has been changed, update result as possible @IBAction func textFieldsEditChanged(_ sender: UITextField) { // Checking Numeric inputs, DO NOTHING if either is INVALID guard let lengthInput = lengthTextField.text, let length = Double(lengthInput), let widthInput = widthTextField.text, let width = Double(widthInput) else { return } let area = areaCalculation(by: length, and: width) // Show Result in Metric Mode if inMetricMode == true { summaryLabel.text = "You entered dimensions of" + "\n" + "\(length) meters by \(width) meters" let result = convertMeterToFootBySquare(with: area) resultLabel.text = "The area is" + "\n" + String(result) + " in feet" // Show Result in Imperial Mode } else { summaryLabel.text = "You entered dimensions of" + "\n" + "\(length) feet by \(width) feet" let result = convertFootToMeterBySquare(with: area) resultLabel.text = "The area is" + "\n" + String(result) + " in meters" } } @IBAction func textFieldsEditEnd(_ sender: UITextField) { // Checking Numeric Inputs if let lengthInput = lengthTextField.text, let length = Double(lengthInput), let widthInput = widthTextField.text, let width = Double(widthInput) { let area = areaCalculation(by: length, and: width) // Show Result in Metric Mode if inMetricMode == true { summaryLabel.text = "You entered dimensions of" + "\n" + "\(length) meters by \(width) meters" let result = convertMeterToFootBySquare(with: area) resultLabel.text = "The area is" + "\n" + String(result) + " in feet" // Show Result in Imperial Mode } else { summaryLabel.text = "You entered dimensions of" + "\n" + "\(length) feet by \(width) feet" let result = convertFootToMeterBySquare(with: area) resultLabel.text = "The area is" + "\n" + String(result) + " in meters" } // If either input is INVALID } else { performSegue(withIdentifier: "popoverSegue", sender: sender) // Shaking animation on Result Label UIView.animate(withDuration: 0.1, animations: { self.resultLabel.transform = CGAffineTransform(translationX: 5, y: 0) }) { (_) in self.resultLabel.transform = CGAffineTransform.identity } } } @IBAction func metricButtonTapped(_ sender: UIButton) { // Checking Numeric Inputs if let lengthInput = lengthTextField.text, let length = Double(lengthInput), let widthInput = widthTextField.text, let width = Double(widthInput) { let area = areaCalculation(by: length, and: width) // Do NOTHING if it's already in Metric Mode if inMetricMode == true { return // Switching to Metric Mode } else { inMetricMode = true lengthDescription.text = "The length of the square in meters?" widthDescription.text = "The width of the square in meters?" summaryLabel.text = "You entered dimensions of" + "\n" + "\(length) meters by \(width) meters" let result = convertMeterToFootBySquare(with: area) resultLabel.text = "The area is" + "\n" + String(result) + " in feet" } // Input has invalid value, only switching interface } else { // Do NOTHING if it's already in Metric Mode if inMetricMode == true { return // Switching to Metric Mode } else { inMetricMode = true lengthDescription.text = "The length of the square in meters?" widthDescription.text = "The width of the square in meters?" return } } } @IBAction func imperialButtonTapped(_ sender: UIButton) { // Checking Numeric Inputs if let lengthInput = lengthTextField.text, let length = Double(lengthInput), let widthInput = widthTextField.text, let width = Double(widthInput) { let area = areaCalculation(by: length, and: width) // Switching to Imperial Mode if inMetricMode == true { inMetricMode = false lengthDescription.text = "The length of the square in foot?" widthDescription.text = "The width of the square in foot?" summaryLabel.text = "You entered dimensions of" + "\n" + "\(length) feet by \(width) feet" let result = convertFootToMeterBySquare(with: area) resultLabel.text = "The area is" + "\n" + String(result) + " in meters" // Do NOTHING if it's already in Imperial Mode } else { return } // Input has invalid value, only switching interface } else { // Switching to Metric Mode if inMetricMode == true { inMetricMode = false lengthDescription.text = "The length of the square in feet?" widthDescription.text = "The width of the square in feet?" return // Do NOTHING if it's already in Imperial Mode } else { return } } } // MARK: - TOOLS func convertMeterToFootBySquare (with input: Double) -> Double { return input / 0.09290304 } func convertFootToMeterBySquare (with input: Double) -> Double{ return input / 10.7639 } func areaCalculation (by a: Double, and b: Double) -> Double { return a * b } func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } // MARK: - NAVIGATIONS override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let popoverControl = segue.destination.popoverPresentationController if sender is UITextField { popoverControl?.sourceRect = (sender as! UITextField).bounds } popoverControl?.delegate = self adaptivePresentationStyle(for: popoverControl!) } }
// // Alert.swift // BarcodeScanner // // Created by Oscar Santos on 11/8/20. // import SwiftUI struct AlertItem: Identifiable { let id = UUID() let title: String let message: String let dismissButton: Alert.Button } struct AlertContext { static let invalidDeviceInput = AlertItem(title: "Something is wrong with the camera", message: "We are unable to capture the input.", dismissButton: .default(Text("OK"))) static let invalidScannedValue = AlertItem(title: "The value scanned is not valid", message: "This app scans EAN-- and EAN-13.", dismissButton: .default(Text("OK"))) }
// // SplitViewController.swift // MyMacOSApp // // Created by steve.ham on 2020/12/30. // import Cocoa class SplitViewController: NSSplitViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } @IBAction private func clickMenuItemFromSVC(_ menuItem: NSMenuItem) { // Need to make Auto Enable Items of Menu off NSApplication.shared.mainMenu?.items.forEach({ menuItem in if menuItem.title == "MyMenu" { menuItem.menu?.items.forEach({ menuItem2 in if menuItem2.title == "Say Goodbye" { menuItem2.isEnabled = false } }) } }) } }
// // ExtensionToolkitTests.swift // ExtensionToolkitTests // // Created by Bjørn Vidar Dahle on 12/03/2018. // Copyright © 2018 Bjørn Vidar Dahle. All rights reserved. // import XCTest @testable import ExtensionToolkit class ExtensionToolkitTests: XCTestCase { func testParseHMS() { let testNumber = Int.parseHMS(hms: "01:01:01") XCTAssert(testNumber == 3661, "Could not parse String to correct Int") } }
// // SZButton.swift // UberEATS // // Created by Sean Zhang on 7/30/18. // Copyright © 2018 Sean Zhang. All rights reserved. // import UIKit class SZButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func jitter() { let animation = CABasicAnimation(keyPath: "position") animation.duration = 0.05 animation.repeatCount = 6 animation.autoreverses = true animation.fromValue = NSValue(cgPoint: CGPoint.init(x: self.center.x - 7.0, y: self.center.y)) animation.toValue = NSValue(cgPoint: CGPoint.init(x: self.center.x, y: self.center.y)) layer.add(animation, forKey: "position") } }
// // NotificationActionID.swift // Pruebas // // Created by Julio Banda on 11/17/18. // Copyright © 2018 Julio Banda. All rights reserved. // import Foundation enum NotificationActionID : String { case timer = "userNotification.action.timer" case date = "userNotification.action.date" case location = "userNotification.action.location" }
// // GitHubRepositoryListView.swift // GitHubViewer // // Created by Yu Tawata on 2019/12/31. // Copyright © 2019 Yu Tawata. All rights reserved. // import SwiftUI import Combine import Mocha struct Logging: Interceptor { func request(_ request: URLRequest) -> URLRequest { debugPrint(request) return request } func response(_ request: URLRequest, data: Data?, response: URLResponse?, error: Error?) { let json = try! JSONSerialization.jsonObject(with: data!, options: .fragmentsAllowed) debugPrint(json) } } class GitHubRepositoryListViewModel: ObservableObject { @Published var items = [GitHub.Repository]() private let client: GitHubClient private var cancellables = [AnyCancellable]() init(client: GitHubClient = .default) { self.client = client client.network.interceptors.append(Logging()) } func fetch() { client.publisher(for: GitHub.GetRepositories()) .receive(on: DispatchQueue.main) .sink(receiveCompletion: { completion in switch completion { case .failure(let error): debugPrint(error) case .finished: break } }, receiveValue: { [weak self] in self?.items = $0 }) .store(in: &cancellables) } } struct GitHubRepositoryListView: View { @ObservedObject private var viewModel = GitHubRepositoryListViewModel() var body: some View { List(viewModel.items, id: \.id) { Text($0.fullName) } .onAppear { self.viewModel.fetch() } } } struct GitHubRepositoryListView_Previews: PreviewProvider { static var previews: some View { GitHubRepositoryListView() } }
// // AddContactFormViewController.swift // Djed // // Created by Kyle Kirkland on 7/8/15. // Copyright (c) 2015 Kyle Kirkland. All rights reserved. // import UIKit class AddContactFormViewController: UIViewController { @IBOutlet weak var contentView: DesignableView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var emailAddressTextField: MKTextField! @IBOutlet weak var phoneNumberTextField: MKTextField! @IBOutlet weak var wayToRememberTextField: MKTextField! @IBOutlet weak var lastNameTextField: MKTextField! @IBOutlet weak var firstNameTextField: MKTextField! @IBOutlet weak var profilePictureButton: DesignableButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var saveButton: UIButton! @IBOutlet weak var dropButton2: UIButton! @IBOutlet weak var dropButton1: UIButton! var textFields: [MKTextField]! var dropButtons: [UIButton]! var actionButtons: [UIButton]! var keyboardShown = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. textFields = [self.emailAddressTextField, self.phoneNumberTextField, wayToRememberTextField, lastNameTextField, firstNameTextField] dropButtons = [dropButton1, dropButton2] actionButtons = [cancelButton, saveButton] self.configureView() self.contentView.userInteractionEnabled = true self.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTapBackground:")) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillShow(notification: NSNotification) { if !keyboardShown { self.scrollView.contentOffset.y += 75 keyboardShown = true } } func keyboardWillHide(notification: NSNotification) { if keyboardShown { self.scrollView.contentOffset.y -= 75 keyboardShown = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(0.2, animations: { () -> Void in self.scrollView.alpha = 1.0 for button in self.actionButtons { button.alpha = 1.0 } }) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().postNotificationName("DidDismissAddContactVCNotification", object: nil) } func configureView() { self.configureProfilePhotoButton() self.configureTextFields() //self.configureDropButtons() self.configureActionButtons() //self.scrollView.alpha = 0.0 } func configureProfilePhotoButton() { self.profilePictureButton.addDashedBorder() } func configureTextFields() { for textField in textFields { textField.layer.borderColor = UIColor.clearColor().CGColor textField.floatingPlaceholderEnabled = true textField.rippleLocation = .Right textField.cornerRadius = 0 textField.bottomBorderEnabled = true textField.delegate = self } } func configureDropButtons() { for button in dropButtons { button.layer.cornerRadius = 4.0 button.layer.shadowOpacity = 0.3 button.layer.shadowRadius = 1 button.layer.shadowColor = UIColor.blackColor().CGColor button.layer.shadowOffset = CGSize(width: 0, height: 0.5) } } func configureActionButtons() { for button in actionButtons { button.layer.cornerRadius = 5.0 var attrString = NSMutableAttributedString(string: button.titleLabel!.text!) attrString.addAttribute(NSKernAttributeName, value: 2.0, range: NSMakeRange(0, attrString.length)) button.setAttributedTitle(attrString, forState: .Normal) button.layer.shadowOpacity = 0.3 button.layer.shadowRadius = 1 button.layer.shadowColor = UIColor.blackColor().CGColor button.layer.shadowOffset = CGSize(width: 0, height: 0.5) button.alpha = 0.0 } } func didTapBackground(tap: UITapGestureRecognizer) { for field in textFields { field.resignFirstResponder() } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension AddContactFormViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == self.firstNameTextField { self.lastNameTextField.becomeFirstResponder() } else if textField == self.lastNameTextField { self.wayToRememberTextField.becomeFirstResponder() } else if textField == self.wayToRememberTextField { self.phoneNumberTextField.becomeFirstResponder() } else if textField == self.phoneNumberTextField { self.emailAddressTextField.becomeFirstResponder() } else if textField == self.emailAddressTextField { self.firstNameTextField.becomeFirstResponder() } return true } }
import Foundation enum GeneratorError: Error { }
// // Skater.swift // Skating Friends // // Created by Jake Oscar Te Lem on 6/11/18. // Copyright © 2018 Jake Oscar Te Lem. All rights reserved. // import Foundation import SpriteKit class Catoko : Skater { var spinPower: Double = 5 var spiralPower : Double = 5 var artistry: Double = 10 var reputation: Double = 10 var rotationSpeed: Double = 0.3 var size : Double = 225 var airTime : Double = 0.9 var jumpHeight : Double = 130 var control : Double = 0.9 var maxSpeed : Double = 1800 var sprite = SKSpriteNode(imageNamed: "Catoko_0") var midair: SKAction! var rotate : SKAction! let skaterName = "Catoko Meowahara" var upStep = SKAction(named:"CatokoTwizzle", duration: 0.45)! var spiral = SKAction(named:"CatokoSpiral", duration: 1.5)! var spiralEntrance = SKAction(named:"CatokoSpiralEntrance", duration: 0.2)! var leftStep = SKAction.sequence([SKAction(named:"CatokoBackTurn", duration: 0.3)!, SKAction(named:"CatokoBackSkate", duration: 0.3)!, SKAction(named:"CatokoBackTurn", duration: 0.3)!.reversed()]) var rightStep = SKAction(named:"CatokoSkating")! var downStep = SKAction.sequence([SKAction(named:"CatokoBackTurn", duration: 0.3)!, SKAction(named:"CatokoBackSkate", duration: 0.3)!, SKAction(named:"CatokoBackTurn", duration: 0.3)!.reversed()]) let skating = SKAction(named:"CatokoSkating")! let backTurn = SKAction(named:"CatokoBackTurn", duration: 0.3)! let lutzTakeoff = SKAction(named:"CatokoLutz", duration: 0.2)! let flipTakeoff = SKAction(named:"CatokoLutz", duration: 0.2)! let loopTakeoff = SKAction(named:"CatokoLoop", duration: 0.2)! let toeTakeoff = SKAction(named:"CatokoToe", duration: 0.2)! let salTakeoff = SKAction(named:"CatokoSal", duration: 0.2)! let axelTakeoff = SKAction(named:"CatokoAxel", duration: 0.2)! var spin = SKAction(named:"MeowSpiral", duration: 1.5)! var footDiv: Double = 3 let landing = SKAction(named:"CatokoLanding", duration: 0.5)! let fall = SKAction(named:"CatokoFall", duration: 1)! let bow = SKAction(named:"CatokoBow", duration: 2)! let jumpTrans = SKAction(named:"CatokoRotate", duration: 0)! required init () { sprite.name = "Catoko Meowahara" sprite.size = CGSize (width: size, height: size) sprite.position = CGPoint(x: -200, y:-200 ) sprite.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "Catoko_5"), size: sprite.size) sprite.physicsBody?.allowsRotation = false sprite.physicsBody!.affectedByGravity = true midair = SKAction(named:"CatokoMidair", duration: airTime)! rotate = SKAction(named:"CatokoRotate", duration: rotationSpeed)! } func setSize(withSize: Double) { size = withSize sprite.size = CGSize (width: size, height: size) } func setRotationSpeed(withTime: Double) { if withTime < 0.12 { rotationSpeed = 0.12 } else { rotationSpeed = withTime } rotate = SKAction(named:"CatokoRotate", duration: rotationSpeed)! } func setAirTime (withTime: Double) { midair = SKAction(named:"CatokoMidair", duration: withTime)! } func setSpinTrans(spinType: Tech, stage: Int) { switch spinType { case .Layback: switch stage { case 0: spin = SKAction(named:"CatokoLaybackEntrance")! print("0") case 1: spin = SKAction(named:"CatokoLaybackEntrance")! print("1") case 2: let trans = SKAction(named:"CatokoLayback2", duration: 0.3)! spin = trans case 3: spin = SKAction(named:"CatokoLayback23", duration: 0.3)! case 4: spin = SKAction(named:"CatokoLayback34", duration: 0.3)! case 5: spin = SKAction(named:"CatokoLayback4", duration: 0.3)! default: print("EXIt") spin = SKAction(named:"CatokoSpinExit", duration: 0.3)! } case .ComboSpin: break default: break } } func setSpin(spinType: Tech, stage: Int) -> Bool { switch spinType { case .Layback: switch stage { case 1: spin = SKAction.sequence([SKAction(named:"CatokoLaybackEntrance")!, SKAction.repeatForever(SKAction(named:"CatokoLayback1", duration: 0.3)!)]) return false case 2: spin = SKAction.repeatForever(SKAction(named:"CatokoLayback2", duration: 0.3)!) return false case 3: spin = SKAction.repeatForever(SKAction(named:"CatokoLayback3", duration: 0.3)!) return false case 4: spin = SKAction.repeatForever(SKAction(named:"CatokoLayback4", duration: 0.3)!) return false default: return true } case .ComboSpin: break default: break } return true } func executeMove (withName: Move) { switch withName { case .lutzTakeoff: sprite.run(SKAction.sequence([lutzTakeoff,midair])) case .rotate : sprite.run(SKAction(named:"CatokoRotate")!) case .backTurn : sprite.run(backTurn) case .landing : sprite.run(landing) default: sprite.run(SKAction(named:"CatokoSkating")!) } } }
// // DailyViewController.swift // GREApp // // Created by 홍창남 on 2017. 7. 16.. // Copyright © 2017년 홍창남. All rights reserved. // import UIKit import RealmSwift class DailyViewController: UIViewController { let dailyCellId = "dailyCellId" var days: Results<Day>! let realm = try! Realm() @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var topConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() days = realm.objects(Day.self) self.navigationController?.navigationBar.tintColor = #colorLiteral(red: 0.3058823529, green: 0.7294117647, blue: 0.2901960784, alpha: 1) if #available(iOS 11, *) { } else { topConstraint.constant = -60 } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.collectionView.reloadData() } } // MARK: DataSource extension DailyViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return days.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: dailyCellId, for: indexPath) as! DailyLearnCell let item = days[indexPath.row] cell.configureCell(day: item) return cell } } // MARK: segue 데이터 전송 extension DailyViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { performSegue(withIdentifier: "dailyToCover", sender: indexPath.row + 1) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "dailyToCover" { if let destination = segue.destination as? DailyCoverViewController { destination.date = sender as? Int } } } } // MARK: FlowLayout extension DailyViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let length = (self.view.bounds.size.width - 30 - 30) / 3 return CGSize(width: length, height: length) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 15 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 15 } }
// // ViewController.swift // Gesture1106 // // Created by 503-12 on 06/11/2018. // Copyright © 2018 The. All rights reserved. // import UIKit class ViewController: UIViewController { //탭 동작이 발생했을 때 수행할 메소드 @objc func tapMethod(sender: UITapGestureRecognizer){ print("더블클릭") } @IBOutlet weak var 토끼: UIImageView! override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(tapMethod(sender:))) //제약조건 설정 tapGesture.numberOfTapsRequired = 2 //뷰와 제스쳐 연결 토끼.addGestureRecognizer(tapGesture) } }
// // SignViewController.swift // wkTest // // Created by MIT.LI on 17/10/17. // Copyright © 2017 MIT.LI. All rights reserved. // import UIKit class SignViewController: UIViewController { @IBOutlet weak var mail: UITextField! @IBOutlet weak var pass: UITextField! @IBOutlet weak var veryCode: UITextField! var stringPassed = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func but(_ sender: Any) { let usrName = mail.text let passWord = pass.text let verify = veryCode.text regisAction(usrName!,passWord!,verify!) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(false) } func regisAction(_ user:String,_ pass:String,_ very:String) { let url = URL(string:"http://192.168.1.9:3000/verify") let session = URLSession.shared let request = NSMutableURLRequest(url:url as! URL) request.httpMethod = "Post" let paramToSend = "username=" + user+"&password="+pass+"&verifyCode="+very request.httpBody = paramToSend.data(using:String.Encoding.utf8) let task = session.dataTask(with: request as URLRequest, completionHandler:{(data,Response,error) in guard let _:Data = data else { return } do { print("result is ") let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:String] let curValue = json["message"] as! String print(curValue) if curValue == "true" { DispatchQueue.main.async { let alertController = UIAlertController( title: "Sucessfully", message: "Register success", preferredStyle: UIAlertControllerStyle.alert ) let confirmAction = UIAlertAction( title: "OK", style: UIAlertActionStyle.default) { (action) in let tab = self.storyboard?.instantiateViewController(withIdentifier: "tab") as! UITabBarController let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = tab } alertController.addAction(confirmAction) self.present(alertController, animated: true, completion: nil) } } else { DispatchQueue.main.async { let alertController = UIAlertController( title: "Failed", message: "Incorrect verify code", preferredStyle: UIAlertControllerStyle.alert ) let cancelAction = UIAlertAction( title: "Cancel", style: UIAlertActionStyle.destructive) { (action) in } alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } } } catch { print("error is :") print(error) } }) task.resume() } }