text
stringlengths
8
1.32M
// // TertiaryQuestionData.swift // TuVosUstedMeConfuden // // Created by Matthew Beynon on 4/27/19. // Copyright © 2019 Matthew Beynon. All rights reserved. // import Foundation struct Tertiary { var optionsArrayInEnglish = [[String]]() var optionsArrayInSpanish = [[String]]() var superarray = [[[String]]]() // ENGLISH let countriesInEnglish = ["Colombia", "Cuba", "Ecuador", "El Salvador", "Guatemala", "Honduras", "Mexico", "Peru", "Puerto Rico", "Uruguay", "Venezuela"] let colombiaOptionsInEnglish = ["Caribbean coast", "Pacific coast", "Quindío, Risaldo, Antioquia, or Risaralda States", "Anywhere Else"] let cubaOptionsInEnglish = ["Mountainous region or countryside", "Anywhere else"] let ecuadorOptionsInEnglish = ["North and Central Mountainous Regions", "Anywhere else"] let elSalvadorOptionsInEnglish = ["Yes", "No"] let guatemalaOptionsInEnglish = ["Yes", "No"] let hondurasOptionsInEnglish = ["Yes", "No"] let mexicoOptionsInEnglish = ["Indigenous villages in Chiapas, Tabasco, Yucatán, or Quintana Roo", "Anywhere else"] let peruOptionsInEnglish = ["Andean regions or Cajamarca", "Anywhere else"] let puertoRicoOptionsInEnglish = ["Eastern end of island", "Anywhere else"] let uruguayOptionsInEnglish = ["Rocha, Rivera, or areas bordering Brazil", "Anywhere else"] let venezuelaOptionsInEnglish = ["Zalia State", "Anywhere else"] // SPANISH let countriesInSpanish = ["Colombia", "Cuba", "Ecuador", "El Salvador", "Guatemala", "Honduras", "México", "Perú", "Puerto Rico", "Uruguay", "Venezuela"] let colombiaOptionsInSpanish = ["Costa caribeña", "Costa pacifica", "Estados de Quindío, Risaldo, Antioquia, o Risaralda", "Cualquier otro lugar"] let cubaOptionsInSpanish = ["Regiones montañosas o el campo", "Cualquier otro lugar"] let ecuadorOptionsInSpanish = ["Regiones montañosas del norte y centro", "Cualquier otro lugar"] let elSalvadorOptionsInSpanish = ["Sí", "No"] let guatemalaOptionsInSpanish = ["Sí", "No"] let hondurasOptionsInSpanish = ["Sí", "No"] let mexicoOptionsInSpanish = ["Pueblos indígenas en Chiapas, Tabasco, Yucatán o Quintana Roo", "Cualquier otro lugar"] let peruOptionsInSpanish = ["Regiones andinas o cajamarca", "Cualquier otro lugar"] let puertoRicoOptionsInSpanish = ["Extremo oriental de la isla", "Cualquier otro lugar"] let uruguayOptionsInSpanish = ["Rocha, Rivera, o zonas limítrofes con Brasil", "Cualquier otro lugar"] let venezuelaOptionsInSpanish = ["Estado Zalia", "Cualquier otro lugar"] // COUNTRIES THAT REQUIRE "UNORTHODOX UI ELEMENT POSITIONING" let specialOptions = ["El Salvador", "Guatemala", "Honduras"] init() { optionsArrayInEnglish.append(colombiaOptionsInEnglish) optionsArrayInEnglish.append(cubaOptionsInEnglish) optionsArrayInEnglish.append(ecuadorOptionsInEnglish) optionsArrayInEnglish.append(elSalvadorOptionsInEnglish) optionsArrayInEnglish.append(guatemalaOptionsInEnglish) optionsArrayInEnglish.append(hondurasOptionsInEnglish) optionsArrayInEnglish.append(mexicoOptionsInEnglish) optionsArrayInEnglish.append(peruOptionsInEnglish) optionsArrayInEnglish.append(puertoRicoOptionsInEnglish) optionsArrayInEnglish.append(uruguayOptionsInEnglish) optionsArrayInEnglish.append(venezuelaOptionsInEnglish) optionsArrayInSpanish.append(colombiaOptionsInSpanish) optionsArrayInSpanish.append(cubaOptionsInSpanish) optionsArrayInSpanish.append(ecuadorOptionsInSpanish) optionsArrayInSpanish.append(elSalvadorOptionsInSpanish) optionsArrayInSpanish.append(guatemalaOptionsInSpanish) optionsArrayInSpanish.append(hondurasOptionsInSpanish) optionsArrayInSpanish.append(mexicoOptionsInSpanish) optionsArrayInSpanish.append(peruOptionsInSpanish) optionsArrayInSpanish.append(puertoRicoOptionsInSpanish) optionsArrayInSpanish.append(uruguayOptionsInSpanish) optionsArrayInSpanish.append(venezuelaOptionsInSpanish) superarray.append(optionsArrayInSpanish) superarray.append(optionsArrayInSpanish) } }
import XCTest import UiTests var tests = [XCTestCaseEntry]() tests += UiTests.allTests() XCTMain(tests)
import UIKit import AVFoundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryPlayback) } catch { print("Audio session setCategory failed") } return true } }
// // Provider.swift // RyujumeApp // // Created by baby1234 on 27/08/2019. // Copyright © 2019 baby1234. All rights reserved. // import Foundation import RxSwift import RxCocoa protocol AuthAPIProvider { func postLogin(userID: String, userPW: String) -> Observable<LoginModel?> func postRegister(userID: String, userPW: String, userName: String) -> Observable<Result> } protocol MyPageAPIProvider { func postUpdateProfileImg(identityImg: String) -> Observable<Result> func putUpdateInfo(ryujume: MyRyujumeModel) -> Observable<MyRyujumeModel?> func getReadLikeInfo() -> Observable<[SimpleRyujumesModel]?> func getReadMyInfo() -> Observable<MyRyujumeModel?> } protocol MainAPIProvider { func getLatestInfo() -> Observable<[SimpleRyujumesModel]?> func getLikeInfo() -> Observable<[SimpleRyujumesModel]?> func getDetailRyujume(ryujumeId: String) -> Observable<RyujumeModel?> func postLikePress(ryujumeId: String, isLiked: Bool) -> Observable<Result> } protocol HTTPClientProvider { func get(url: String) -> Observable<Data?> func post(url: String, params: [String: Any]) -> Observable<Data?> func put(url: String, params: [String: Any]) -> Observable<Data?> }
// // ThirdViewController.swift // Eating With Allergies // // Created by Peter McCarthy on 4/24/16. // Copyright © 2016 Peter McCarthy. All rights reserved. // import UIKit class ThirdViewController: UIViewController { // MARK: Properties @IBOutlet weak var MapSearch: UISearchBar! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can recreated. } }
import Foundation import Yams internal struct SpecDocumentNode<T: Codable> { // MARK: - Instance Properties internal let document: SpecDocument internal let value: T // MARK: - Initializers internal init(content: String, url: URL? = nil, codingPath: [String] = []) throws { let decoder = YAMLDecoder() do { document = SpecDocument(url: url, codingPath: codingPath) value = try decoder.decode( T.self, from: content, userInfo: [ .specComponentRegistry: document, .specReferenceRegistry: document ], codingPath: codingPath ) } catch { throw SpecError.decodingFailed(error, documentURL: url) } } internal init(data: Data, url: URL? = nil, codingPath: [String] = []) throws { if let content = String(data: data, encoding: .utf8) { try self.init(content: content, url: url, codingPath: codingPath) } else if let content = String(data: data, encoding: .utf16) { try self.init(content: content, url: url, codingPath: codingPath) } else if let content = String(data: data, encoding: .ascii) { try self.init(content: content, url: url, codingPath: codingPath) } else { throw SpecError.wrongEncoding(documentURL: url) } } internal init(url: URL, codingPath: [String] = []) throws { let data: Data do { data = try Data(contentsOf: url) } catch { throw SpecError.loadingFailed(error, documentURL: url) } try self.init(data: data, url: url, codingPath: codingPath) } internal init(filePath: String, codingPath: [String] = []) throws { try self.init(url: URL(fileURLWithPath: filePath), codingPath: codingPath) } }
// // CitySelectionViewModel.swift // Weathards // // Created by Waind Storm on 15.10.21. // import Foundation final class CitySelectionViewModel: ObservableObject { @Published var cityList: [City] @Published var selectedCity: City { didSet { UserDefaulsService.shared.saveCity(name: selectedCity.name) } } init() { cityList = JSONReaderService.shared.getCities() selectedCity = JSONReaderService.shared.getCities().filter { $0.name == UserDefaulsService.shared.getCity() }.first ?? City(name: "Minsk", country: "Belarus") } }
// // UserInfoEntity.swift // TXVideoDome // // Created by 98data on 2019/12/13. // Copyright © 2019 98data. All rights reserved. // import Foundation class UserInfoEntity { var nick_name = "" // 可以提现的x金额 var money = 0.0 var allMoney = 0.0 // 不能提现 的金额 var coldMoney = 0.0 var integral = 0.0 var bank_card = "" var avatar = "" var bank_name = "" var bank_address = "" var insurance_end_time = "" var car_reg_time = "" var car_end_time = "" var brands = "" var iDCard = "" var name = "" var id = 0 var address = "" var username = "" var car_type = "" // var car_brands = CarBrandsEntity() var insuranceMileage = "" var sex = 0 var birthday = "" var bank_holder = "" var level = "" var ipoIntegral = 0 // 推荐码 var recommendCode = "" static func initJsonWithEntity(jsonData:JSON) -> UserInfoEntity { let entity = UserInfoEntity() let jsonDic = jsonData.dictionaryValue GeneralObjects.jsondic = jsonDic if GeneralObjects().jsonValueToString(key: "NickName") != "" { entity.nick_name = GeneralObjects().jsonValueToString(key: "NickName") }else if GeneralObjects().jsonValueToString(key: "Nickname") != "" { entity.nick_name = GeneralObjects().jsonValueToString(key: "Nickname") } // if jsonDic["NickName"]?.string != nil { // entity.nick_name = jsonDic["NickName"]!.stringValue // }else { // entity.nick_name = jsonDic["Nickname"]!.stringValue // } entity.money = jsonDic["Money"]?.doubleValue == nil ? 0.0 : jsonDic["Money"]!.doubleValue entity.allMoney = jsonDic["MoneyAll"]?.doubleValue == nil ? 0.0 : jsonDic["MoneyAll"]!.doubleValue entity.coldMoney = jsonDic["ColdMoney"]?.doubleValue == nil ? 0.0 : jsonDic["ColdMoney"]!.doubleValue entity.integral = jsonDic["Integral"]?.double == nil ? 0.0 : jsonDic["Integral"]!.doubleValue entity.bank_card = jsonDic["BankCard"]?.string == nil ? "" : jsonDic["BankCard"]!.stringValue entity.bank_name = jsonDic["BankName"]?.string == nil ? "" : jsonDic["BankName"]!.stringValue entity.bank_address = jsonDic["BankAddress"]?.string == nil ? "" : jsonDic["BankAddress"]!.stringValue entity.avatar = jsonDic["Avatar"]?.string == nil ? "" : jsonDic["Avatar"]!.stringValue entity.insurance_end_time = jsonDic["InsuranceEndTime"]?.string == nil ? "" : jsonDic["InsuranceEndTime"]!.stringValue entity.car_reg_time = jsonDic["CarRegTime"]?.string == nil ? "" : jsonDic["CarRegTime"]!.stringValue // entity.car_end_time = jsonDic["CarEndTime"]!.stringValue entity.brands = jsonDic["Brands"]?.string == nil ? "" : jsonDic["Brands"]!.stringValue entity.iDCard = jsonDic["IDCard"]?.string == nil ? "" : jsonDic["IDCard"]!.stringValue entity.name = jsonDic["Name"]?.string == nil ? "" : jsonDic["Name"]!.stringValue entity.id = jsonDic["Id"]?.int == nil ? 0 : jsonDic["Id"]!.intValue entity.address = jsonDic["Address"]?.string == nil ? "" : jsonDic["Address"]!.stringValue entity.username = jsonDic["Username"]?.string == nil ? "" : jsonDic["Username"]!.stringValue entity.car_type = jsonDic["CarType"]?.string == nil ? "" : jsonDic["CarType"]!.stringValue // entity.car_brands = jsonDic["CarBrands"]!.stringValue // entity.car_brands = CarBrandsEntity.initJsonWithEntity(json: jsonDic["CarBrands"]?.dictionaryValue) entity.insuranceMileage = jsonDic["InsuranceMileage"]?.string == nil ? "" : jsonDic["InsuranceMileage"]!.stringValue entity.sex = jsonDic["Sex"]?.int == nil ? 0 : jsonDic["Sex"]!.intValue entity.birthday = jsonDic["Birthday"]?.string == nil ? "" : jsonDic["Birthday"]!.stringValue entity.bank_holder = jsonDic["BankHolder"]?.string == nil ? "" : jsonDic["BankHolder"]!.stringValue entity.recommendCode = jsonDic["RecommendCode"]?.string == nil ? "" : jsonDic["RecommendCode"]!.stringValue let levelCount = GeneralObjects().jsonValueToInt(key: "Level") if levelCount == 0 { entity.level = "下载用户" }else if levelCount == 1 { entity.level = "普通用户" }else if levelCount == 2 { entity.level = "业务员" }else if levelCount == 3 { entity.level = "经理" } entity.ipoIntegral = GeneralObjects().jsonValueToInt(key: "IPOIntegral") GeneralObjects().reMoveJsonInit() return entity } }
// // ViewController.swift // Leap_Year // // Created by Raksha Singh on 29/06/18. // Copyright © 2018 Raksha Singh. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var txtOutlet: UITextField! @IBOutlet weak var lblOutlet: UILabel! @IBAction func btnAction(_ sender: Any) { if let value: String = txtOutlet.text{ if(value.characters.count != 0){ var n : Int = 0 n = Int(value)! if(n % 4 == 0 && n % 100 != 0 || n % 100 == 00 && n % 400 == 00){ self.lblOutlet.text = "Leap Year" } else{ self.lblOutlet.text = " Not Leap Year " } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // PaisViewController.swift // Tarea2 // // Created by Giovanni Ascarza on 2/19/20. // Copyright © 2020 Giovanni Ascarza. All rights reserved. // import UIKit class PaisViewController: UIViewController, UITableViewDataSource { var paises: [Pais] = [] override func viewDidLoad() { super.viewDidLoad() paises = PaisFactory.crearPaises() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let paisDetalleVC = segue.destination as? PaisDetalleViewController, let paisCell = sender as? PaisCell { /* paisDetalleVC.pais?.nombre = paisCell.nombre paisDetalleVC.pais?.paisId = paisCell.paisId paisDetalleVC.pais?.detalle = paisCell.detalle */ } } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return paises.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "paisCell", for: indexPath) let pais = paises[indexPath.row] print("Antes : \(pais)") cell.textLabel?.text = pais.nombre cell.detailTextLabel?.text = pais.description return cell } }
// // DisplayedItemsInteractor.swift // walkdelivery // // Created by AndreyLebedev on 10/06/2017. // Copyright © 2017 lebedac. All rights reserved. // import Foundation class DisplayedItemsInteractor { weak var output: DisplayedItemsInteractorOutput? var itemsStoreService: ItemsStoreServiceProtocol? } extension DisplayedItemsInteractor: DisplayedItemsInteractorInput { func requestItems() { let request = ItemsRequest() itemsStoreService?.getItems(request: request) { [weak self] result in switch result { case .Success(let remoteItems): self?.output?.present(items: remoteItems) case .Failure( _): self?.output?.present(error: ErrorEntity(description: "")) } } } }
// // DriveDetailViewController.swift // Driver-Logger // // Created by Developer on 2/1/17. // Copyright © 2017 rtbdesigns. All rights reserved. // import UIKit class DriveDetailViewController: UIViewController { @IBOutlet weak var startDate: UIDatePicker! @IBOutlet weak var endDate: UIDatePicker! @IBOutlet weak var startMileLabel: UILabel! @IBOutlet weak var endMileLabel: UILabel! @IBOutlet weak var totalMileLabel: UILabel! var startMileage: String = "" var startD: Date = Date() var endD: Date = Date() var endMileage: String = "" var totalMileage: String = "" override func viewDidLoad() { super.viewDidLoad() self.startMileLabel.text = self.startMileage self.endMileLabel.text = self.endMileage self.totalMileLabel.text = self.totalMileage self.startDate.date = startD self.endDate.date = endD // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // BarrageDescriptor.swift // BarrageDemo // // Created by Guo Zhiqiang on 17/3/14. // Copyright © 2017年 Guo Zhiqiang. All rights reserved. // import UIKit struct BarrageDescriptor { var text: String var type: Int var time: TimeInterval var color: UIColor }
// // SettingsContainer.swift // CoAssetsApps // // Created by Linh NGUYEN on 3/10/16. // Copyright © 2016 TruongVO07. All rights reserved. // import UIKit class SettingsContainer: NSObject { static let userDefault = NSUserDefaults.standardUserDefaults() static var accessToken: String? { set { if let myValue = newValue { userDefault.setObject(myValue, forKey: AppDefine.UserDefaultKey.COAccessToken) } else { userDefault.removeObjectForKey(AppDefine.UserDefaultKey.COAccessToken) } userDefault.synchronize() } get { return userDefault.stringForKey(AppDefine.UserDefaultKey.COAccessToken) } } static var tokenType: String? { set { if let myValue = newValue { userDefault.setObject(myValue, forKey: AppDefine.UserDefaultKey.COTypeToken) } else { userDefault.removeObjectForKey(AppDefine.UserDefaultKey.COTypeToken) } userDefault.synchronize() } get { return userDefault.stringForKey(AppDefine.UserDefaultKey.COTypeToken) } } static var refreshToken: String? { set { if let myValue = newValue { userDefault.setObject(myValue, forKey: AppDefine.UserDefaultKey.CORefreshToken) } else { userDefault.removeObjectForKey(AppDefine.UserDefaultKey.CORefreshToken) } userDefault.synchronize() } get { return userDefault.stringForKey(AppDefine.UserDefaultKey.CORefreshToken) } } static var deviceToken: String? { set { if let myValue = newValue { userDefault.setObject(myValue, forKey: AppDefine.UserDefaultKey.CODeviceToken) } else { userDefault.removeObjectForKey(AppDefine.UserDefaultKey.CODeviceToken) } userDefault.synchronize() } get { return userDefault.stringForKey(AppDefine.UserDefaultKey.CODeviceToken) } } static var sentDeviceToken: Bool { set { userDefault.removeObjectForKey(AppDefine.UserDefaultKey.COSentDeviceToken) userDefault.setBool(newValue, forKey: AppDefine.UserDefaultKey.COSentDeviceToken) userDefault.synchronize() } get { return userDefault.boolForKey(AppDefine.UserDefaultKey.COSentDeviceToken) } } }
// // ViewController.swift // calculator // // Created by Takumi ERA on 2019/07/21. // Copyright © 2019年 inmotion. All rights reserved. // import UIKit import Expression class ViewController: UIViewController { @IBOutlet weak var resultLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // 計算結果のラベルを空にする resultLabel.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** * 各種計算ボタンの押下 */ @IBAction func inputFormula(_ sender: UIButton) { // 計算結果を取得 guard let formulaText = resultLabel.text else { return } // どのボタンを押下したかを取得 guard let senderedText = sender.titleLabel?.text else { return } // 計算結果の末尾にボタン名をつける resultLabel.text = formulaText + senderedText } /** * クリアボタンの押下 */ @IBAction func clearCalculation(_ sender: UIButton) { // 計算結果のラベルを空にする resultLabel.text = "" } /** * イコールボタンの押下 */ @IBAction func calculateAnswer(_ sender: UIButton) { // ここまでの計算式を取得する guard let formulaText = resultLabel.text else { return } // 計算式を評価 let formula: String = formatFormula(formulaText) // 計算結果のラベルに反映 resultLabel.text = evalFormula(formula) } private func formatFormula(_ formula: String) -> String { // 入力された整数には「.0」を追加して小数として評価する。「÷」を「/」に、「×」を「*」に置換する return formula.replacingOccurrences( of: "(?<=^|[÷×\\+\\-\\(])([0-9]+)(?=[÷×\\+\\-\\)]|$)", with: "$1.0", options: NSString.CompareOptions.regularExpression, range: nil) .replacingOccurrences( of: "÷", with: "/") .replacingOccurrences( of: "×", with: "*" ) } private func evalFormula(_ formula: String) -> String { do { let expression = Expression(formula) let answer = try expression.evaluate() return formatAnswer(String(answer)) } catch { return "式を正しく入力してください" } } private func formatAnswer(_ answer: String) -> String { // 答えの小数点以下が「.0」だった場合は、「.0」を削除して答えを整数で表示する return answer.replacingOccurrences( of: "\\.0$", with: "", options: NSString.CompareOptions.regularExpression, range: nil) } }
import UIKit class ViewController: UIViewController { let defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() if defaults.bool(forKey: "First Launch") == true { print("Second+") // Run Code After First Launch defaults.set(true, forKey: "First Launch") } else { print("First") // Run Code During First Launch defaults.set(true, forKey: "First Launch") } } }
// // GalleryGridVC.swift // SaneScanner // // Created by Stanislas Chevallier on 24/02/2019. // Copyright © 2019 Syan. All rights reserved. // #if !targetEnvironment(macCatalyst) import UIKit import DiffableDataSources import SYKit class GalleryGridVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .background navigationController?.navigationBar.setBackButtonImage(.icon(.left)) emptyStateView.backgroundColor = .background emptyStateLabel.adjustsFontForContentSizeCategory = true collectionViewLayout.maxSize = 320/3 collectionViewLayout.margin = 6 collectionViewLayout.linesHorizontalInset = 16 collectionViewLayout.cellZIndex = 20 // default header zIndex is 10 collectionView.dataSource = galleryDataSource collectionView.backgroundColor = .background collectionView.allowsSelection = true collectionView.contentInsetAdjustmentBehavior = .never if #available(iOS 13.0, *) { collectionView.automaticallyAdjustsScrollIndicatorInsets = false } if #available(iOS 14.0, *) { // allow drag selection on iOS 14+ collectionView.allowsMultipleSelectionDuringEditing = true } collectionView.collectionViewLayout = collectionViewLayout collectionView.registerSupplementaryView(GalleryGridHeader.self, kind: UICollectionView.elementKindSectionHeader, xib: false) collectionView.registerCell(GalleryThumbnailCell.self, xib: false) toolbarItems = [ UIBarButtonItem.delete(target: self, action: #selector(self.deleteButtonTap(sender:))), UIBarButtonItem.flexibleSpace, UIBarButtonItem(title: "PDF", style: .plain, target: self, action: #selector(self.pdfButtonTap(sender:))), UIBarButtonItem.flexibleSpace, UIBarButtonItem.share(target: self, action: #selector(self.shareButtonTap(sender:))) ] GalleryManager.shared.addDelegate(self) updateNavBarContent(animated: false) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateNavBarContent(animated: false) updateToolbarVisibility(animated: false) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if isEditing { setEditing(false, animated: false) } } // MARK: Properties private var hasInitiallyScrolledToBottom = false private lazy var galleryDataSource = CollectionViewDiffableDataSource<GalleryGroup, GalleryItem>(collectionView: collectionView, viewsProvider: self) private func updateDataSource(using groups: [GalleryGroup], animated: Bool) { var snapshot = DiffableDataSourceSnapshot<GalleryGroup, GalleryItem>() groups.forEach { group in snapshot.appendSections([group]) snapshot.appendItems(group.items, toSection: group) } galleryDataSource.apply(snapshot, animatingDifferences: animated) collectionView.reloadVisibleSectionHeaders { (indexPath: IndexPath, header: GalleryGridHeader) in header.group = groups[indexPath.section] } updateEmptyState() } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if #available(iOS 13.0, *) { // prevent dismissal of this view as a modal when editing isModalInPresentation = editing } updateNavBarContent(animated: animated) updateToolbarVisibility(animated: animated) collectionView.visibleCells.forEach { ($0 as? GalleryThumbnailCell)?.showSelectionIndicator = editing } collectionView.allowsMultipleSelection = editing if #available(iOS 14.0, *) { collectionView.isEditing = editing } if !editing { collectionView.indexPathsForSelectedItems?.forEach { collectionView.deselectItem(at: $0, animated: false) } } } // MARK: Views @IBOutlet private var emptyStateView: UIView! @IBOutlet private var emptyStateLabel: UILabel! private let collectionViewLayout = GalleryGridLayout() @IBOutlet private var collectionView: UICollectionView! // MARK: Actions #if DEBUG @objc private func addTestImagesButtonTap() { GalleryManager.shared.createRandomTestImages(count: 10) } #endif private func openGallery(on item: GalleryItem) { let imagesVC = GalleryImagesVC() imagesVC.initialIndex = GalleryManager.shared.galleryItems.firstIndex(of: item) navigationController?.pushViewController(imagesVC, animated: true) } @objc private func deleteButtonTap(sender: UIBarButtonItem) { guard let selectedIndices = collectionView.indexPathsForSelectedItems, !selectedIndices.isEmpty else { return } // keep a ref to the items, since we'll be deleting one by one and thus indices // may become invalid, ending up deleting the wrong files let selectedItems = selectedIndices.compactMap { self.galleryDataSource.itemIdentifier(for: $0) } deleteGalleryItems(selectedItems, sender: sender) { self.setEditing(false, animated: true) } } @objc private func pdfButtonTap(sender: UIBarButtonItem) { guard let selected = collectionView.indexPathsForSelectedItems, !selected.isEmpty else { return } let hud = HUDAlertController.show(in: self) // needed to let HUD appear, even if PDF is generated on main thread DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.shareSelectedItemsAsPDF(sender: sender, hud: hud) } } @objc private func shareButtonTap(sender: UIBarButtonItem) { let urls = self.selectedURLs() guard !urls.isEmpty else { return } UIActivityViewController.showForURLs(urls, from: sender, presentingVC: self, completion: nil) } // MARK: Sharing private func selectedURLs() -> [URL] { return (collectionView.indexPathsForSelectedItems ?? []) .sorted() .compactMap { self.galleryDataSource.itemIdentifier(for: $0)?.url } } private func shareSelectedItemsAsPDF(sender: UIBarButtonItem, hud: HUDAlertController?) { let urls = self.selectedURLs() guard !urls.isEmpty else { return } let tempURL = GalleryManager.shared.tempPdfFileUrl() do { try PDFGenerator.generatePDF(destination: tempURL, images: selectedURLs(), pageSize: Preferences.shared.pdfSize) } catch { HUDAlertController.dismiss(hud) { UIAlertController.show(for: error, in: self) } return } HUDAlertController.dismiss(hud) { UIActivityViewController.showForURLs([tempURL], from: sender, presentingVC: self) { // is called when the interaction with the PDF is done. It's either been copied, imported, // displayed, shared or printed, but we can dispose of it GalleryManager.shared.deleteTempPDF() } } } @objc private func editButtonTap() { setEditing(!isEditing, animated: true) } @objc private func closeButtonTap() { dismiss(animated: true, completion: nil) } // MARK: Content private func updateEmptyState() { let text = NSMutableAttributedString() text.append("GALLERY EMPTY TITLE".localized, font: .preferredFont(forTextStyle: .body), color: .normalText) text.append("\n\n", font: .preferredFont(forTextStyle: .subheadline), color: .normalText) text.append("GALLERY EMPTY SUBTITLE".localized, font: .preferredFont(forTextStyle: .subheadline), color: .altText) emptyStateLabel.attributedText = text emptyStateView.isHidden = galleryDataSource.totalCount > 0 collectionView.isHidden = !emptyStateView.isHidden } private func updateNavBarContent(animated: Bool) { // Title if isEditing { let selectedCount = collectionView.indexPathsForSelectedItems?.count ?? 0 title = "GALLERY SELECTED ITEMS COUNT %d".localized(quantity: selectedCount) } else { title = "GALLERY OVERVIEW TITLE".localized } // Left if navigationController?.isModal == true && !isEditing { navigationItem.setLeftBarButton(.edit(target: self, action: #selector(self.editButtonTap)), animated: animated) } else { navigationItem.setLeftBarButton(.done(target: self, action: #selector(self.editButtonTap)), animated: animated) } // Right if !isEditing { navigationItem.setRightBarButton(.close(target: self, action: #selector(self.closeButtonTap)), animated: animated) } else { navigationItem.setRightBarButton(nil, animated: animated) #if DEBUG let testButton = UIBarButtonItem(title: "Add test images", style: .plain, target: self, action: #selector(self.addTestImagesButtonTap)) navigationItem.setRightBarButton(testButton, animated: animated) Snapshot.setup { _ in navigationItem.setRightBarButton(nil, animated: animated) } #endif } } private func updateToolbarVisibility(animated: Bool) { navigationController?.setToolbarHidden(!isEditing, animated: animated) view.setNeedsLayout() } // MARK: Layout override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // we can't directly use `collectionView.contentInsetAdjustmentBehavior = .never`, or the bottom // offset will move around when the toolbar is shown/hidden, which is a problem for a view // who opens by default at the bottom... let bottomInsets = collectionViewLayout.linesHorizontalInset collectionView.contentInset = .init( top: view.safeAreaInsets.top + 20, left: view.safeAreaInsets.left, bottom: (view.window?.safeAreaInsets.bottom ?? 0) + (navigationController?.toolbar.bounds.height ?? 0) + bottomInsets, right: view.safeAreaInsets.right ) collectionView.scrollIndicatorInsets = collectionView.contentInset collectionView.scrollIndicatorInsets.top -= 20 collectionView.layoutIfNeeded() if !hasInitiallyScrolledToBottom, let lastIndexPath = galleryDataSource.lastIndexPath { hasInitiallyScrolledToBottom = true collectionView.scrollToItem(at: lastIndexPath, at: .bottom, animated: false) } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory { collectionView.collectionViewLayout.invalidateLayout() } } } extension GalleryGridVC : CollectionViewDiffableDataSourceViewsProvider { typealias SectionIdentifier = GalleryGroup typealias ItemIdentifier = GalleryItem func collectionView(_ collectionView: UICollectionView, cellForItem item: GalleryItem, at indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueCell(GalleryThumbnailCell.self, for: indexPath) cell.update(item: item, displayedOverTint: false) cell.showSelectionIndicator = isEditing cell.accessibilityIdentifier = "gallery-grid-\(indexPath.section)-\(indexPath.item)" return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueSupplementaryView(GalleryGridHeader.self, kind: UICollectionView.elementKindSectionHeader, for: indexPath) header.group = galleryDataSource.snapshot().sectionIdentifiers[indexPath.section] return header } } extension GalleryGridVC : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { let isLast = section == galleryDataSource.snapshot().numberOfSections - 1 return UIEdgeInsets( top: 0, left: self.collectionViewLayout.linesHorizontalInset, bottom: isLast ? 0 : 20, right: self.collectionViewLayout.linesHorizontalInset ) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return GalleryGridHeader.size(for: galleryDataSource.snapshot().sectionIdentifiers[section], in: collectionView) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if isEditing { updateNavBarContent(animated: false) } else { collectionView.deselectItem(at: indexPath, animated: true) if let item = galleryDataSource.itemIdentifier(for: indexPath) { openGallery(on: item) } } } @available(iOS 13.0, *) func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { guard let item = galleryDataSource.itemIdentifier(for: indexPath) else { return nil } guard let cell = collectionView.cellForItem(at: indexPath) else { return nil } let configuration = item.contextMenuConfiguration(for: self, sender: cell, openGallery: { self.openGallery(on: item) }) configuration.indexPath = indexPath return configuration } @available(iOS 13.0, *) func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) { guard let indexPath = configuration.indexPath, let item = galleryDataSource.itemIdentifier(for: indexPath) else { return } animator.addCompletion { self.openGallery(on: item) } } func collectionView(_ collectionView: UICollectionView, shouldBeginMultipleSelectionInteractionAt indexPath: IndexPath) -> Bool { return true } func collectionView(_ collectionView: UICollectionView, didBeginMultipleSelectionInteractionAt indexPath: IndexPath) { setEditing(true, animated: true) } } extension GalleryGridVC : UICollectionViewDragDelegate { func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { guard let item = galleryDataSource.itemIdentifier(for: indexPath) else { return [] } return [UIDragItem(itemProvider: NSItemProvider(object: item))] } } extension GalleryGridVC : GalleryManagerDelegate { func galleryManager(_ manager: GalleryManager, didUpdate items: [GalleryItem], newItems: [GalleryItem], removedItems: [GalleryItem]) { updateDataSource(using: manager.galleryGroups, animated: true) } } #endif
// // Video.swift // SmartStreetProject // // Created by Maryam Jafari on 10/24/17. // Copyright © 2017 Maryam Jafari. All rights reserved. // import UIKit import AVFoundation import Social import MobileCoreServices import AssetsLibrary import MessageUI import MediaPlayer import MobileCoreServices class Video: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate, MFMailComposeViewControllerDelegate { var treeBarcode : String! var audioPlayer: AVAudioPlayer? var audioRecorder: AVAudioRecorder? var videoURL: URL! var soundFileURL: URL! var isVideo : Bool = false override func viewDidLoad() { super.viewDidLoad() playButton.isEnabled = false stopButton.isEnabled = false let fileMgr = FileManager.default let dirPaths = fileMgr.urls(for: .documentDirectory, in: .userDomainMask) soundFileURL = dirPaths[0].appendingPathComponent("sound.caf") let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue, AVEncoderBitRateKey: 16, AVNumberOfChannelsKey: 2, AVSampleRateKey: 44100.0] as [String : Any] let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory( AVAudioSessionCategoryPlayAndRecord) } catch let error as NSError { print("audioSession error: \(error.localizedDescription)") } do { try audioRecorder = AVAudioRecorder(url: soundFileURL, settings: recordSettings as [String : AnyObject]) audioRecorder?.prepareToRecord() } catch let error as NSError { print("audioSession error: \(error.localizedDescription)") } } @IBAction func playVideo(_ sender: Any) { startMediaBrowserFromViewController(viewController: self, usingDelegate: self) } @IBAction func recordVideo(_ sender: Any) { isVideo = true startCameraFromViewController(viewController: self, withDelegate: self) } @IBAction func recordAudio(_ sender: AnyObject) { if audioRecorder?.isRecording == false { playButton.isEnabled = false stopButton.isEnabled = true audioRecorder?.record() } } @IBOutlet weak var stopButton: UIButton! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var recordButton: UIButton! @IBAction func stopAudio(_ sender: AnyObject) { stopButton.isEnabled = false playButton.isEnabled = true recordButton.isEnabled = true if audioRecorder?.isRecording == true { audioRecorder?.stop() } else { audioPlayer?.stop() } } @IBAction func playAudio(_ sender: AnyObject) { if audioRecorder?.isRecording == false { stopButton.isEnabled = true recordButton.isEnabled = false do { try audioPlayer = AVAudioPlayer(contentsOf: (audioRecorder?.url)!) audioPlayer!.delegate = self audioPlayer!.prepareToPlay() audioPlayer!.play() } catch let error as NSError { print("audioPlayer error: \(error.localizedDescription)") } } } func sendMail (attachmentURL : String){ if( MFMailComposeViewController.canSendMail() ) { print("Can send email.") let mailComposer = MFMailComposeViewController() mailComposer.mailComposeDelegate = self //Set the subject and message of the email mailComposer.setSubject("This is a voice recorded") mailComposer.setMessageBody("This is what they sound like.", isHTML: false) mailComposer.delegate = self let fileparts = attachmentURL.components(separatedBy: ".") let filename = fileparts[0] let fileExtention = fileparts[1] if isVideo{ mailComposer.setSubject("video recorded") mailComposer.setMessageBody("This is a video recorded", isHTML: false) if let fileData = NSData(contentsOf: videoURL) { mailComposer.addAttachmentData(fileData as Data, mimeType: "MOV", fileName: "myfile.MOV") } } else{ mailComposer.setSubject("voice recorded") mailComposer.setMessageBody("This is a voice recorded", isHTML: false) if let fileData = NSData(contentsOf: soundFileURL) { print("File data loaded.") mailComposer.addAttachmentData(fileData as Data, mimeType: fileExtention, fileName: filename) } } self.present(mailComposer, animated: true, completion: nil) } } @IBAction func shareWithEmail(_ sender: Any) { sendMail(attachmentURL: "sound.caf") } func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { self.dismiss(animated: true, completion: nil) } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { switch result { case .cancelled: break case .saved: break case .sent: break case .failed: break } controller.dismiss(animated: true, completion: nil) } @objc func video(videoPath: NSString, didFinishSavingWithError error: NSError?, contextInfo info: AnyObject) { var title = "Success" var message = "Video was saved" if let _ = error { title = "Error" message = "Video failed to save" } let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)) present(alert, animated: true, completion: nil) } func startCameraFromViewController(viewController: UIViewController, withDelegate delegate: UIImagePickerControllerDelegate & UINavigationControllerDelegate) -> Bool { if UIImagePickerController.isSourceTypeAvailable(.camera) == false { return false } let cameraController = UIImagePickerController() cameraController.sourceType = .camera cameraController.mediaTypes = [kUTTypeMovie as NSString as String] cameraController.allowsEditing = false cameraController.delegate = delegate present(cameraController, animated: true, completion: nil) return true } @IBAction func shareWithFB(_ sender: Any) { let composeSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook) composeSheet?.setInitialText("Hello, Facebook!") composeSheet?.add(UIImage(named: "6.png")) print(videoURL) composeSheet?.add(videoURL) self.present(composeSheet!, animated: true, completion: nil) } @IBAction func shareWithMessage(_ sender: Any) { } func startMediaBrowserFromViewController(viewController: UIViewController, usingDelegate delegate: UINavigationControllerDelegate & UIImagePickerControllerDelegate) -> Bool { // 1 if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) == false { return false } // 2 let mediaUI = UIImagePickerController() mediaUI.sourceType = .savedPhotosAlbum mediaUI.mediaTypes = [kUTTypeMovie as NSString as String] mediaUI.allowsEditing = true mediaUI.delegate = delegate // 3 present(mediaUI, animated: true, completion: nil) return true } } // MARK: - UIImagePickerControllerDelegate extension Video: UIImagePickerControllerDelegate { private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { // 1 let mediaType = info[UIImagePickerControllerMediaType] as! NSString // 2 dismiss(animated: true) { // 3 if mediaType == kUTTypeMovie { let moviePlayer = AVPlayer(url: (info[UIImagePickerControllerMediaURL] as! NSURL) as URL!) moviePlayer.play() } } } internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let mediaType = info[UIImagePickerControllerMediaType] as! NSString videoURL = ((info[UIImagePickerControllerMediaURL] as! NSURL) as URL!) dismiss(animated: true, completion: nil) // Handle a movie capture if mediaType == kUTTypeMovie { guard let path = (info[UIImagePickerControllerMediaURL] as! NSURL).path else { return } if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path) { UISaveVideoAtPathToSavedPhotosAlbum(path, self, #selector(Video.video(videoPath:didFinishSavingWithError:contextInfo:)), nil) } } } } // MARK: - UINavigationControllerDelegate extension Video: UINavigationControllerDelegate { }
import Foundation import RxSwift import RxRelay import RxCocoa import CurrencyKit import MarketKit class NftAssetOverviewViewModel { private let service: NftAssetOverviewService private let disposeBag = DisposeBag() private let viewItemRelay = BehaviorRelay<ViewItem?>(value: nil) private let loadingRelay = BehaviorRelay<Bool>(value: false) private let syncErrorRelay = BehaviorRelay<Bool>(value: false) private let openTraitRelay = PublishRelay<String>() init(service: NftAssetOverviewService) { self.service = service subscribe(disposeBag, service.stateObservable) { [weak self] in self?.sync(state: $0) } sync(state: service.state) } private func sync(state: DataStatus<NftAssetOverviewService.Item>) { switch state { case .loading: viewItemRelay.accept(nil) loadingRelay.accept(true) syncErrorRelay.accept(false) case .completed(let item): viewItemRelay.accept(viewItem(item: item)) loadingRelay.accept(false) syncErrorRelay.accept(false) case .failed: viewItemRelay.accept(nil) loadingRelay.accept(false) syncErrorRelay.accept(true) } } private func viewItem(item: NftAssetOverviewService.Item) -> ViewItem { let asset = item.asset let collection = item.collection return ViewItem( nftImage: item.assetNftImage, name: asset.name ?? "#\(service.nftUid.tokenId)", providerCollectionUid: asset.providerCollectionUid, collectionName: collection.name, lastSale: priceViewItem(priceItem: item.lastSale), average7d: priceViewItem(priceItem: item.average7d), average30d: priceViewItem(priceItem: item.average30d), collectionFloor: priceViewItem(priceItem: item.collectionFloor), bestOffer: priceViewItem(priceItem: item.bestOffer), sale: saleViewItem(saleItem: item.sale), traits: asset.traits.enumerated().map { traitViewItem(index: $0, trait: $1, totalSupply: collection.totalSupply) }, description: asset.description, contractAddress: service.nftUid.contractAddress, tokenId: service.nftUid.tokenId, schemaName: asset.contract.schema, blockchain: service.nftUid.blockchainType.uid, links: linkViewItems(asset: asset, collection: collection), sendVisible: item.isOwned ) } private func saleViewItem(saleItem: NftAssetOverviewService.SaleItem?) -> SaleViewItem? { guard let saleItem = saleItem, let listing = saleItem.bestListing else { return nil } return SaleViewItem( untilDate: "nft_asset.until_date".localized(DateHelper.instance.formatFullTime(from: listing.untilDate)), type: saleItem.type, price: PriceViewItem( coinValue: coinValue(priceItem: listing.price), fiatValue: fiatValue(priceItem: listing.price) ) ) } private func priceViewItem(priceItem: NftAssetOverviewService.PriceItem?) -> PriceViewItem? { guard let priceItem = priceItem else { return nil } return PriceViewItem( coinValue: coinValue(priceItem: priceItem), fiatValue: fiatValue(priceItem: priceItem) ) } private func coinValue(priceItem: NftAssetOverviewService.PriceItem) -> String { let price = priceItem.nftPrice let coinValue = CoinValue(kind: .token(token: price.token), value: price.value) return ValueFormatter.instance.formatShort(coinValue: coinValue) ?? "---" } private func fiatValue(priceItem: NftAssetOverviewService.PriceItem) -> String { guard let coinPrice = priceItem.coinPrice else { return "---" } return ValueFormatter.instance.formatShort(currency: coinPrice.price.currency, value: priceItem.nftPrice.value * coinPrice.price.value) ?? "---" } private func traitViewItem(index: Int, trait: NftAssetMetadata.Trait, totalSupply: Int?) -> TraitViewItem { var percentString: String? if let totalSupply = totalSupply, trait.count != 0, totalSupply != 0 { let percent = Double(trait.count) * 100.0 / Double(totalSupply) let rounded: Double if percent >= 10 { rounded = round(percent) } else if percent >= 1 { rounded = Double(round(percent * 10) / 10) } else { rounded = Double(round(percent * 100) / 100) } percentString = String(format: "%g", rounded) } return TraitViewItem( index: index, type: trait.type.capitalized, value: trait.value.capitalized, percent: percentString.map { "\($0)%" } ) } private func linkViewItems(asset: NftAssetMetadata, collection: NftCollectionMetadata) -> [LinkViewItem] { var viewItems = [LinkViewItem]() if let url = asset.externalLink { viewItems.append(LinkViewItem(type: .website, url: url)) } if let title = service.providerTitle, let link = asset.providerLink { viewItems.append(LinkViewItem(type: .provider(title: title), url: link)) } if let url = collection.discordLink { viewItems.append(LinkViewItem(type: .discord, url: url)) } if let username = collection.twitterUsername { viewItems.append(LinkViewItem(type: .twitter, url: "https://twitter.com/\(username)")) } return viewItems } } extension NftAssetOverviewViewModel { var viewItemDriver: Driver<ViewItem?> { viewItemRelay.asDriver() } var loadingDriver: Driver<Bool> { loadingRelay.asDriver() } var syncErrorDriver: Driver<Bool> { syncErrorRelay.asDriver() } var openTraitSignal: Signal<String> { openTraitRelay.asSignal() } var nftUid: NftUid { service.nftUid } var blockchainType: BlockchainType { service.nftUid.blockchainType } var providerTitle: String? { service.providerTitle } func onTapRetry() { service.resync() } func onSelectTrait(index: Int) { guard case .completed(let item) = service.state else { return } guard index < item.asset.traits.count else { return } let trait = item.asset.traits[index] guard let traitName = trait.type.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let traitValue = trait.value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return } guard let providerTraitLink = item.asset.providerTraitLink else { return } let url = providerTraitLink .replacingOccurrences(of: "$traitName", with: traitName) .replacingOccurrences(of: "$traitValue", with: traitValue) openTraitRelay.accept(url) } } extension NftAssetOverviewViewModel { struct ViewItem { let nftImage: NftImage? let name: String let providerCollectionUid: String let collectionName: String let lastSale: PriceViewItem? let average7d: PriceViewItem? let average30d: PriceViewItem? let collectionFloor: PriceViewItem? let bestOffer: PriceViewItem? let sale: SaleViewItem? let traits: [TraitViewItem] let description: String? let contractAddress: String let tokenId: String let schemaName: String? let blockchain: String let links: [LinkViewItem] let sendVisible: Bool } struct SaleViewItem { let untilDate: String let type: NftAssetMetadata.SaleType let price: PriceViewItem } struct PriceViewItem { let coinValue: String let fiatValue: String } struct TraitViewItem { let index: Int let type: String let value: String let percent: String? } struct LinkViewItem { let type: LinkType let url: String } enum LinkType { case website case provider(title: String) case discord case twitter } }
//: Playground - noun: a place where people can play import Cocoa /* Write a program generates * ** *** **** ***** ****** ******* ******** ********* ********** */ for index in 1...5 { let stars = String(repeating: "*", count: index); print(stars) }
// // StdSocketConfig.swift // codegenv // // Created by Bernardo Breder on 12/11/16. // // import Foundation open class StdSocketConfig { public let port: Int public var queueSize: Int = 100 public init(port: Int = 8080) { self.port = port } }
// // Detail.swift // HowSay // // Created by AsianTech on 7/23/15. // Copyright (c) 2015 asiantech. All rights reserved. // import UIKit class Detail: UIView { @IBOutlet weak var imvImage: UIImageView! @IBOutlet weak var btnName: UIButton! var word: WordObject? { willSet{ btnName.setTitle(newValue?.keyword, forState: UIControlState.Normal) var imageString = String() if (newValue?.image != nil) { imageString = newValue!.image } let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory,nsUserDomainMask, true) { if paths.count > 0 { if let dirPath = paths[0] as? String { let readPath = dirPath.stringByAppendingPathComponent(imageString) let image = UIImage(contentsOfFile: readPath) imvImage.image = image } } } } } override func awakeFromNib() { imvImage.layer.cornerRadius = imvImage.frame.height/2 imvImage.layer.borderColor = UIColor.whiteColor().CGColor imvImage.layer.borderWidth = 2 } @IBAction func namePlay(sender: AnyObject) { print("Play Audio") } }
// // TapTempoPickerViewModel.swift // Metronome iOS // // Created by luca strazzullo on 14/10/19. // Copyright © 2019 luca strazzullo. All rights reserved. // import Foundation import Combine class TapTempoPickerViewModel: ObservableObject { @Published private(set) var selectedTempoBpm: Int? var isAutomaticCommitActive: Bool = false private let controller: SessionController private var tapTimestamps: [TimeInterval] = [] private var cancellables: Set<AnyCancellable> = [] // MARK: Object life cycle init(controller: SessionController) { self.controller = controller self.$selectedTempoBpm .debounce(for: 0.8, scheduler: DispatchQueue.main) .filter({ [weak self] _ in self?.isAutomaticCommitActive ?? false }) .sink(receiveValue: { [weak self] _ in self?.commit() }) .store(in: &cancellables) } // MARK: Public methods func update(with timestamp: TimeInterval) { if let frequency = getFrequency(withNew: timestamp) { selectedTempoBpm = controller.session?.configuration.getBpm(with: frequency) } } func commit() { if let bpm = selectedTempoBpm { controller.set(tempoBpm: bpm) } } // MARK: Private helper methods private func getFrequency(withNew timestamp: TimeInterval) -> TimeInterval? { tapTimestamps.append(timestamp) if tapTimestamps.count > 5 { tapTimestamps.remove(at: 0) } return getFrequency() } private func getFrequency() -> TimeInterval? { guard tapTimestamps.count >= 2 else { return nil } let frequencies: [Double] = tapTimestamps.enumerated().compactMap { index, timestamp in if index + 1 == tapTimestamps.count { return nil } else { return tapTimestamps[index + 1] - timestamp } } return frequencies.reduce(0, +) / Double(frequencies.count) } }
// // SettingsView.swift // ControlViewProject // // Created by Karin Prater on 14.08.20. // Copyright © 2020 Karin Prater. All rights reserved. // import SwiftUI import StoreKit struct SettingsView: View { @ObservedObject var settings = SettingsManager() var body: some View { NavigationView { Form { Section(header: Text("Profile")) { TextField("username", text: $settings.username) Toggle(isOn: $settings.isPrivate) { Text("Private Account") } NavigationLink(destination: SignUpView()) { Text("Sign Up") } } Section(header: Text("Notification")) { Toggle(isOn: $settings.notificationsEnabled) { Text("enable Notifications") } Picker(selection: $settings.selectedPreviewOption, label: Text("preview option")) { ForEach(PreviewOptions.allCases, id: \.self) { option in Text(option.rawValue) } } } Section(header: Text("About")) { HStack { Text("Version") Spacer() Text("2.0") } NavigationLink(destination: WebActiveView(url: URL(string: "https://www.apple.com")!)) { Text("Terms of Use") } NavigationLink(destination: WebActiveView(url: URL(string: "https://www.apple.com")!)) { Text("Privacy Policy") } } Section { Button(action: { SKStoreReviewController.requestReview() }) { Text("Giva a 5 stare rating") } } } .navigationBarTitle("Settings") } } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView() } }
// // LibraryContainerCell.swift // SpotifyClone // // Created by JAYANTA GOGOI on 1/25/20. // Copyright © 2020 JAYANTA GOGOI. All rights reserved. // import UIKit class PlayListCell: CollectionBaseCell{ override func setupView() { addSubview(imgArtwork) addSubview(title) addSubview(subTitle) imgArtwork.image = #imageLiteral(resourceName: "details_tracks_placeholder") title.text = "Liked Songs" subTitle.text = "12 songs" subTitle.font = UIFont.systemFont(ofSize: 12) imgArtwork.widthAnchor.constraint(equalToConstant: 80).isActive = true imgArtwork.heightAnchor.constraint(equalToConstant: 80).isActive = true imgArtwork.topAnchor.constraint(equalTo: self.topAnchor).isActive = true imgArtwork.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true title.centerYAnchor.constraint(equalTo: imgArtwork.centerYAnchor).isActive = true title.leadingAnchor.constraint(equalTo: imgArtwork.trailingAnchor, constant: 10).isActive = true title.heightAnchor.constraint(equalToConstant: 25).isActive = true title.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true subTitle.topAnchor.constraint(equalTo: self.title.bottomAnchor).isActive = true subTitle.heightAnchor.constraint(equalToConstant: 18).isActive = true subTitle.leadingAnchor.constraint(equalTo: imgArtwork.trailingAnchor, constant: 10).isActive = true } } class MusicContainerCell: CollectionBaseCell { let btnPlayList: UIButton = { let btn = UIButton() btn.noAutoConst() return btn }() let btnArtists: UIButton = { let btn = UIButton() btn.noAutoConst() return btn }() let btnAlbums: UIButton = { let btn = UIButton() btn.noAutoConst() return btn }() let collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let collView = UICollectionView(frame: .zero, collectionViewLayout: layout) collView.isPagingEnabled = true collView.showsHorizontalScrollIndicator = false collView.backgroundColor = .clear collView.noAutoConst() return collView }() let identifier = "musicIdentifier" override func setupView() { setNormalTitle() btnPlayList.setAttributedTitle(attrText(title: "Playlists", color: .white), for: .normal) addSubview(btnPlayList) addSubview(btnArtists) addSubview(btnAlbums) btnPlayList.topAnchor.constraint(equalTo: self.topAnchor).isActive = true btnPlayList.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10).isActive = true btnPlayList.heightAnchor.constraint(equalToConstant: 40).isActive = true btnPlayList.widthAnchor.constraint(equalToConstant: 80).isActive = true btnArtists.topAnchor.constraint(equalTo: self.topAnchor).isActive = true btnArtists.leadingAnchor.constraint(equalTo: self.btnPlayList.trailingAnchor, constant: 10).isActive = true btnArtists.heightAnchor.constraint(equalToConstant: 40).isActive = true btnArtists.widthAnchor.constraint(equalToConstant: 100).isActive = true btnAlbums.topAnchor.constraint(equalTo: self.topAnchor).isActive = true btnAlbums.leadingAnchor.constraint(equalTo: self.btnArtists.trailingAnchor, constant: 10).isActive = true btnAlbums.heightAnchor.constraint(equalToConstant: 40).isActive = true btnAlbums.widthAnchor.constraint(equalToConstant: 80).isActive = true btnPlayList.addTarget(self, action: #selector(onTapEpisodes), for: .touchUpInside) btnArtists.addTarget(self, action: #selector(onTapDownloads), for: .touchUpInside) btnAlbums.addTarget(self, action: #selector(onTapShow), for: .touchUpInside) addSubview(collectionView) collectionView.register(PlayListCell.self, forCellWithReuseIdentifier: identifier) collectionView.delegate = self collectionView.dataSource = self collectionView.topAnchor.constraint(equalTo: btnPlayList.bottomAnchor).isActive = true collectionView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true collectionView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 60).isActive = true } private func setNormalTitle(){ btnPlayList.setAttributedTitle(attrText(title: "Playlists", color: .lightGray), for: .normal) btnArtists.setAttributedTitle(attrText(title: "Artists", color: .lightGray), for: .normal) btnAlbums.setAttributedTitle(attrText(title: "Albums", color: .lightGray), for: .normal) } private func attrText(title: String, color: UIColor)-> NSAttributedString{ let attrString = NSAttributedString(string: "\(title)", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: color]) return attrString } @objc private func onTapEpisodes(){ setNormalTitle() btnPlayList.setAttributedTitle(attrText(title: "Playlists", color: .white), for: .normal) self.collectionView.scrollToItem(at: IndexPath(row: 0, section: 0), at: .centeredHorizontally, animated: true) } @objc private func onTapDownloads(){ setNormalTitle() btnArtists.setAttributedTitle(attrText(title: "Artists", color: .white), for: .normal) self.collectionView.scrollToItem(at: IndexPath(row: 0, section: 1), at: .centeredHorizontally, animated: true) } @objc private func onTapShow(){ setNormalTitle() btnAlbums.setAttributedTitle(attrText(title: "Albums", color: .white), for: .normal) self.collectionView.scrollToItem(at: IndexPath(row: 0, section: 2), at: .centeredHorizontally, animated: true) } } //MARK: - Collection View Functionality extension MusicContainerCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 3 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 15 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! PlayListCell return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.size.width, height: 80) } }
// // UrlConnection.swift // RecentContest // // Created by zhu peijun on 10/8/14. // Copyright (c) 2014 my. All rights reserved. // import UIKit class UrlConnection: NSObject { var url: String init(url: String) { self.url = url super.init() } func getUrlData() -> NSData? { let request = NSURLRequest(URL: NSURL(string: url)!) let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil let error: NSErrorPointer = nil var data: NSData? do { data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: response) } catch let error1 as NSError { error.memory = error1 data = nil } if(error != nil) { print("[ERROR] Can not get the data from the url.\(error)") } return data } func getJSONObject() -> NSDictionary? { let data = getUrlData() if (data != nil) { do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary return jsonResult } catch { print("[ERROR] Can not parse the JSON result to JSONObject.") } } return nil } func getJSONArray() -> NSArray? { let data = getUrlData() if (data != nil) { do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSArray return jsonResult } catch { print("[ERROR] Can not parse the JSON result to JSONArray.") } } return nil } func getJSONObjectAsync(callback: NSDictionary? -> Void) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let object = self.getJSONObject() dispatch_async(dispatch_get_main_queue(), { callback(object) }) }) } func getJSONArrayAsync(callback: NSArray? -> Void) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let array = self.getJSONArray() dispatch_async(dispatch_get_main_queue(), { callback(array) }) }) } }
import UIKit // Скажите, а вы знакомы с принципами SOLID? // Как думаете, изменение поведения метода в подклассе при наследовании нарушает какой-нибудь принцип из SOLID? // Полагаю, таким образом нарушается принцип открытости-закрытости, open closed principle. // Знаком, однако в работе ими пользоваться не доводилось — затратно по времени на планирование архитектуры и реализацию, а фичи, придуманные дизайнерами, должны приносить деньги уже сейчас. Так что у нас есть и гигантский мегакласс GameController, нужный всегда, даже время узнать у него спрашиваем, и нет прокладок в виде интерфейсов (в С++ — чисто абстрактных классов) и потому минорное изменение/дополнение какого-то мелкого часто используемого класса приводит к долгой перекомпиляции проекта. Не, мы потом-то взялись за ум и перестали пихать весь функционал в мегакласс, но такое решение в начале разработки игры привело к тому, что есть. // Так и не понял, зачем нужен был пустой протокол Obstacle. // Чтобы typeкастить оператором as. Подразумевается, что мы определяем проходимость ячейки на карте так: есть ли что-то в ячейке? если есть, кастуем находящийся объест к Obstacle и не идём туда, если результат приведения типа не nil. Для этой операции никакие дополнительные данные не нужны, только пустой тип. // 1. Посмотреть видео про методы композиции и агрегации по ссылке https://www.youtube.com/watch?v=N7DzmfLBolM // Автор путано изложил, мне больше нравится https://habr.com/ru/post/354046/ и https://ru.wikipedia.org/wiki/Агрегирование_(программирование) // В этих статьях композиция описывается как такой способ владения, когда компонент существует только как часть целого, уничтожается вместе с этим объектом. Агрегация — когда компонент может существовать отдельно от объекта. Как пример можно привести отношения внутри простого окна с TableView внутри: /* class RatingDialog { public: RatingDialog() { // конструктор m_tableView = TableView.create(m_dataSource) } ~RatingDialog() { if (m_tableView != nullptr) { delete m_tableView; } } private: somesdk::TableView* m_tableView; RatingDataSource m_dataSource; } */ // RatingDialog состоит из m_dataSource и m_tableView, оба компонента включены в диалог с помощью композиции. Создаваемая внутри диалога таблица требует источник данных, он ей предоставляется извне, это агрегация — я могу удалить таблицу, создать новую и передать ей тот же DataSource. // 2. Привести по два примера с использованием композиции и агрегации. Объяснить, почему в каждом примере использована композиция/агрегация. /* protocol Stream { func write(String, Int) } class Logger { init(stream: Stream) func log(_ str: String, severity: Int = 0) } Класс Logger пишет логи в Stream. Куда именно эти логи попадают в конечном итоге скрыто реализацией. В файл, в консоль, в эппл, в базу данных. protocol Listener {} class Processor {} class Server { var listeners = [Listener] var processor = Processor } Какой-то абстрактный сервер, обрабатывающий запросы. Просто суёт запрос в Processor и возвращает полученный ответ обратно в Listener. Запросы в данном случае однотипные, потому нужен только один и только этот Processor и потому здесь композиция Запросы могут поступать из разных источников, по разным протоколам, например UPD, HTTPS, в разных форматах — plain text, JSON. Для каждого конкретного случая пишется свой Listener, который получает запрос и преобразует его к утверждённому виду. Здесь использована агрегация, позволяющая менять эти объекты struct Point { var x, y: Float } struct Size { var width, height: Float } struct Rect { var origin: Point var size: Size } Здесь композиция во всех трех структурах — базовые вещи, не предназначенные как-то измениться в будущем. Rect всегда состоит из Point и Size. Только композиция */ // 3. Создается приложение интернет-магазин для продажи книг. // Реализуйте модели данных (используя классы, структуры, перечисления на ваш выбор): // - заказ // - платеж // - чек // - книга // - пользователь // Добавьте любые свойства на ваше усмотрение, которые необходимы для работоспособности интернет-магазина. struct Order { let orderId: Int let clientId: Int let date: Int64 // UNIX time let books: [String] let isPaid: Bool // false, станет true когда будет получен Receipt с таким orderId let isShipped: Bool // false, станет true когда товар будет передан в доставку let shipmentData: ShipmentData } struct Receipt { let receiptId: Int let orderId: Int let date: Int64 // UNIX time let paymentProvider: PaymentProvider } struct PaymentProvider { // любые данные для идентификации и связи с банком, эплстором, ОПСОСом } struct Book { let bookId: String let authorId: Int // для удобности поиска let title: String let description: String let cover: String // обложка } struct Author { let authorId: Int64 let name: String } struct Client { let clientId: Int let firstName, lastName, MiddleName: String // а то СДЭКом не отправить let email: String // чтобы задалбывать скидками и акциями let birthDate: Int64 // чтобы задалбывать персональными предложениями var discount: Float // пересчитывается в момент получения очередного Receipt, зависит от суммы всех платежей enum OrdersKind {case All, Created, Paid, Shipped} func getOrders(_ kind: OrdersKind) -> [Order] { return [] } var address: [ShipmentData] } struct ShipmentData { var address: String var shipmentProvider: Int // тут ещё данные о доставке, о которых я не могу знать } // 4. Создать модель данных для приложения TODO. struct Entry { var icon: Int // индекс var Title: String var Description: String? // на случай, если надо что-то дополнить enum Priority { case Lowest, Low, Medium, High, Highest} var priority: Priority var dueDate: Int64 var isComplete: Bool var children: [Entry]? // для подзадач, когда понадобится } struct Entries { var icon: Int // индекс var name: String var entries: [Entry] } // TODO List представлен как структура Entries, в которой есть икона, название и массив записей. Таких списков может быть несколько // Запись Entry имеет икону, текст, большой текст на всякий случай не на каждый день, значок приоритетности, дедлайн, по желанию поздзадачи
// // SignUpController.swift // collexapp // // Created by Lex on 18/5/20. // Copyright © 2020 Lex. All rights reserved. // import UIKit import FirebaseFirestore import GoogleSignIn import ObjectMapper class SignUpController: UIViewController, GIDSignInDelegate { private let defaults = UserDefaults.standard let db = Firestore.firestore() var previousController: UIViewController! override func viewDidLoad() { super.viewDidLoad() GIDSignIn.sharedInstance()?.delegate = self GIDSignIn.sharedInstance()?.presentingViewController = self initialView() } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if let error = error { if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue { print("The user has not signed in before or they have since signed out.") } else { print("\(error.localizedDescription)") } return } // Perform any operations on signed in user here. let userId = user.userID! // For client-side use only! // let idToken = user.authentication.idToken // Safe to send to the server let fullName = user.profile.name! // let givenName = user.profile.givenName // let familyName = user.profile.familyName let email = user.profile.email! print("This is my signin email \(String(email))") print("This is my fullname \(String(fullName))") print("Checking userID \(String(userId))") checkExistsGoogleAccount(user: user) } override func viewWillAppear(_ animated: Bool) { navigationController?.isNavigationBarHidden = true } private func initialView() { let view = SignUpView(frame: self.view.frame) self.view = view } @IBAction func handleLogo(_ sender: Any?) { self.navigationController?.popToRootViewController(animated: true) } @IBAction func handleGoogleSignUp(_ sender: Any?) { print("Click Google SignUp") } @IBAction func handleNext(_ sender: Any?) { } @IBAction func handleLogIn(_ sender: Any?) { guard let mainControllers: [UIViewController] = self.navigationController?.viewControllers else { return } if previousController == mainControllers[0] { let logInController = LogInController() logInController.previousController = self self.navigationController?.pushViewController(logInController, animated: true) } else { self.navigationController?.popViewController(animated: true) } } private func checkExistsGoogleAccount(user: GIDGoogleUser) { db.collection("users") .whereField("email.id", in: [user.profile.email!]) .getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { if querySnapshot!.documents.count == 0 { let viewController = SetupAccountController() viewController.userGoogle = user self.navigationController?.pushViewController(viewController, animated: true) } else { for document in querySnapshot!.documents { let user = Mapper<User>().map(JSONObject: document.data())! let userJson = Mapper().toJSONString(user, prettyPrint: true)! print("Current data: \(userJson)") let initiateUser = ["login": true, "id": user.id!] as [String: Any] self.defaults.set(initiateUser, forKey: "user") let mainTabBarController = MainTabBarController() mainTabBarController.user = user mainTabBarController.modalPresentationStyle = .fullScreen self.present(mainTabBarController, animated: true, completion: nil) return } } } } } }
// Generated using Sourcery 0.7.2 — https://github.com/krzysztofzablocki/Sourcery // DO NOT EDIT // swiftlint:disable cyclomatic_complexity file_length function_body_length line_length import Foundation // //import Sourcery_AutoJSONSerializable // // MARK: - AutoJSONSerializable for classes, protocols, structs // MARK: - Person AutoJSONSerializable extension Person: JSONSerializable { internal func toJSONObject() -> Any { var jsonObject = [String: Any]() let firstName = self.firstName jsonObject["firstName"] = firstName let lastName = self.lastName jsonObject["lastName"] = lastName let age = self.age jsonObject["age"] = age let email = self.email jsonObject["email"] = email return jsonObject } } // MARK: -
// // LeftViewController.swift // NeCTARClient // // Created by Ding Wang on 16/8/14. // Copyright © 2017年 Xinrui Xu. All rights reserved. // import UIKit import SnapKit class LeftViewController: BaseViewController { @IBOutlet var tenantName: UILabel! @IBOutlet var userName: UILabel! @IBOutlet var contentView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // add constrains to make the menu weigth is appriate for the screen self.contentView.snp_makeConstraints{ (make) -> Void in make.width.equalTo(Common.screenWidth * 0.8) } self.tenantName.snp_makeConstraints{(make) -> Void in make.width.equalTo(Common.screenWidth * 0.8 - 80 ) } self.userName.snp_makeConstraints{(make) -> Void in make.width.equalTo(Common.screenWidth * 0.8 - 80) } tenantName.text = UserService.sharedService.user?.tenantName userName.text = UserService.sharedService.user?.username } @IBAction func toOverView(sender: AnyObject) { turnToOtherPage("Overview") } @IBAction func toInstance(sender: AnyObject) { turnToOtherPage("Instance") } @IBAction func toAbout(sender: AnyObject) { turnToOtherPage("About") } @IBAction func toVolumes(sender: AnyObject) { turnToOtherPage("Volumes") } // button hidden and disabled @IBAction func toImage(sender: AnyObject) { turnToOtherPage("Images") } // buton hidden and disabled @IBAction func toSecurity(sender: AnyObject) { turnToOtherPage("Access & Security") } @IBAction func logout(sender: AnyObject) { UserService.sharedService.logout() loginRequired () } func turnToOtherPage (title: String) { let viewController = UIApplication.sharedApplication().keyWindow?.rootViewController as! ViewController viewController.homeViewController.titleOfOtherPages = title if(title != "Overview"){ viewController.homeViewController.performSegueWithIdentifier("showOtherPages", sender: self) } viewController.showHome() } }
// // CustomIdentityProvider.swift // Harvey // // Created by Sean Hart on 8/29/17. // Copyright © 2017 TangoJ Labs, LLC. All rights reserved. // import AWSCognito import Foundation class CustomIdentityProvider: NSObject, AWSIdentityProviderManager { /** Each entry in logins represents a single login with an identity provider. The key is the domain of the login provider (e.g. 'graph.facebook.com') and the value is the OAuth/OpenId Connect token that results from an authentication with that login provider. */ var tokens : [NSString : NSString]? init(tokens: [NSString : NSString]) { self.tokens = tokens } // @objc func logins() -> AWSTask<AnyObject> { // return AWSTask(result: tokens) // } public func logins() -> AWSTask<NSDictionary> { return AWSTask(result: tokens! as NSDictionary) } }
// Created on 2020/12/11. import ArgumentParser struct Day202202Solution: Solution { func solve1(for input: String, verbose: Bool) throws -> String { let parsed = try Day2Parser.parse(input) parsed.printContents(verbose: verbose) let score = parsed.reduce(0) { acc, next in acc + next.0.value + Shape.play(me: next.0, opponent: next.1) } return String(score) } func solve2(for input: String, verbose: Bool) throws -> String { let parsed = try Day2Parser.parse2(input) parsed.printContents(verbose: verbose) let score = parsed.reduce(0) { acc, next in acc + next.0.value + Shape.play(me: next.0, opponent: next.1) } return String(score) } }
// // ViewController.swift // To-Do List // // Created by Stefan Pel on 01-03-17. // Copyright © 2017 Stefan Pel. All rights reserved. // import UIKit import SQLite // MARK: Alert user. extension UIViewController { func show(errorMessage: String) { let viewController = UIAlertController(title: "Something went wrong", message: errorMessage, preferredStyle: .alert) viewController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)) self.present(viewController, animated: true, completion: nil) } } class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource { // Array for todo's. var toDos: [(id: Int64, text: String)] = [] // MARK: Outlets @IBOutlet weak var textInputField: UITextField! @IBOutlet weak var tableView: UITableView! // func search all func searchAll() { toDos.removeAll() guard let results = try? database?.prepare(todolist) else { return } for item in results! { if item[todoitem].isEmpty != true { toDos.append((id: item[id], text: item[todoitem])) } } } // MARK: Setting up SQlite database. var database: Connection? let todolist = Table("todolist") let id = Expression<Int64>("id") let todoitem = Expression<String>("todoitem") // Setting up database. private func setupDatabase() { defer { if self.database == nil { self.show(errorMessage: "Could not create database.") } } guard let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return } do { database = try Connection("\(path)/db.sqlite3") createTable() } catch let error { self.show(errorMessage: error.localizedDescription) } } // Create todolist table. private func createTable() { do { try database?.run(todolist.create(ifNotExists: true) { t in t.column(id, primaryKey: .autoincrement) t.column(todoitem) }) } catch let error { self.show(errorMessage: error.localizedDescription) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard self.database == nil else { return } setupDatabase() createTable() searchAll() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // Putting textfield text in database. func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let text = textField.text else { return false } let insertToDo = todolist.insert(todoitem <- text) do { try database?.run(insertToDo) } catch let error { self.show(errorMessage: error.localizedDescription) } searchAll() self.tableView.reloadData() textInputField.text = "" textField.resignFirstResponder() return true } // MARK: tableview. func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return toDos.count } // Filling in the cells. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ToDoListCell cell.toDoLabel.text = toDos[indexPath.row].text return cell } // MARK: To delete and check off To-DO's. func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexpath: IndexPath) { if (editingStyle == UITableViewCellEditingStyle.delete) { let itemToDelete = todolist.filter(id == toDos[indexpath.row].id) do { try database!.run(itemToDelete.delete()) searchAll() } catch { self.show(errorMessage: "Could not delete this item, try again") } } tableView.deleteRows(at: [indexpath], with: .fade) } // Let the user check off items. var ticked = Bool() func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if !ticked { tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark ticked = true } else { tableView.cellForRow(at: indexPath)?.accessoryType = .none ticked = false } } }
import CoreGraphics import Cassowary import struct Simplex.Solution import class Simplex.Variable /// Cassowary UI Solver. public struct Solver { private var cassowary: Cassowary.Solver private var views: Set<Weak<View>> /// Cached latest solution. public var cachedSolution: [Variable: Double] { return self.cassowary.cachedSolution } public init() { self.cassowary = Cassowary.Solver() self.views = [] } public mutating func reset() { self = Solver() } // MARK: Add Constraints @discardableResult public mutating func addConstraints( _ view1: View, _ view2: View, setup: (Pair2, Pair2) -> [Constraint] ) throws -> [Constraint] { return try self.addConstraints([view1, view2]) { pairs in return setup(pairs[0], pairs[1]) } } @discardableResult public mutating func addConstraints( _ view1: View, _ view2: View, _ view3: View, setup: (Pair2, Pair2, Pair2) -> [Constraint] ) throws -> [Constraint] { return try self.addConstraints([view1, view2, view3]) { pairs in return setup(pairs[0], pairs[1], pairs[2]) } } @discardableResult public mutating func addConstraints( _ view1: View, _ view2: View, _ view3: View, _ view4: View, setup: (Pair2, Pair2, Pair2, Pair2) -> [Constraint] ) throws -> [Constraint] { return try self.addConstraints([view1, view2, view3, view4]) { pairs in return setup(pairs[0], pairs[1], pairs[2], pairs[3]) } } @discardableResult public mutating func addConstraints( _ view1: View, _ view2: View, _ view3: View, _ view4: View, _ view5: View, setup: (Pair2, Pair2, Pair2, Pair2, Pair2) -> [Constraint] ) throws -> [Constraint] { return try self.addConstraints([view1, view2, view3, view4, view5]) { pairs in return setup(pairs[0], pairs[1], pairs[2], pairs[3], pairs[4]) } } @discardableResult public mutating func addConstraints( _ views: [View], setup: ([Pair2]) -> [Constraint] ) throws -> [Constraint] { for view in views { self.views.insert(Weak(view)) } let constraints = setup(views.map { $0._pair2 }) let backup = self.cassowary do { try self.cassowary.addConstraints(constraints) try self.cassowary.solve() } catch let error { self.cassowary = backup throw error } return constraints } public mutating func solve() throws { try self.cassowary.solve() } // MARK: Remove Constraints /// - Throws: `Solver.RemoveError.notFound` public mutating func removeConstraints(_ constraints: Constraint...) throws { try self.removeConstraints(constraints) } /// - Throws: `Solver.RemoveError.notFound` public mutating func removeConstraints(_ constraints: [Constraint]) throws { try self.cassowary.removeConstraints(constraints) try self.cassowary.solve() } // MARK: Layout public func applyLayout() { /// Sort views for breadth-first layouting. let views = self.views .flatMap { $0.value } .sorted(by: { $0.depth < $1.depth }) for view in views { let x = self.cachedSolution[view.cassowary.left] ?? Double(view.frame.origin.x) let y = self.cachedSolution[view.cassowary.top] ?? Double(view.frame.origin.y) let x2 = self.cachedSolution[view.cassowary.right] ?? Double(view.frame.size.width + view.frame.origin.x) let y2 = self.cachedSolution[view.cassowary.bottom] ?? Double(view.frame.size.height + view.frame.origin.y) let absoluteFrame = CGRect(x: x, y: y, width: x2 - x, height: y2 - y) let relativeFrame = view.superview!.convert(absoluteFrame, from: nil) view.frame = relativeFrame } } // MARK: Edit /// Register stay variables and edit variables via `register` closure to start `suggestValue`, /// e.g. `solver.beginEdit { $0.addEditVariable(x1) }`. /// /// - Note: `endEdit()` will remove registered stay variables and edit variables. /// - Note: Supports nested `beginEdit()`. /// /// - Parameter register: Closure with passed `BeginEditProxy` that can add stay variables and edit variables. /// /// - Throws: /// - `Error.addError(.editVariableExists(variable))` /// - `Error.addError(.stayVariableExists(variable))` /// - `Error.optimizeError(.unbounded)` public mutating func beginEdit(_ register: (inout Cassowary.Solver.BeginEditProxy) throws -> ()) throws { try self.cassowary.beginEdit(register) } /// Unregister latest stay variables and edit variables from stack. /// /// - Throws: /// - `Error.removeError(.constraintNotFound(constraint))` /// - `Error.optimizeError(.dualOptimizeFailed)` public mutating func endEdit() throws { try self.cassowary.endEdit() } /// Register suggesting values for `editVariable`s via `register` closure, /// e.g. `solver.suggest { $0.suggestValue(123, for: x1) }`. /// /// - Important: /// `beginEdit()` with registering edit variable is required before calling this method. /// /// - Throws: /// - `Error.editError(.editVariableNotFound(editVariable, suggestedValue: value))` /// - `Error.optimizeError(.unbounded)` /// - `Error.optimizeError(.dualOptimizeFailed)` public mutating func suggest(_ register: (inout Cassowary.Solver.SuggestProxy) throws -> ()) throws { try self.cassowary.suggest(register) self.applyLayout() } } extension View { fileprivate var depth: Int { var depth = 0 var view = self while let superview = view.superview { view = superview depth += 1 } return depth } }
// // Coordinator.swift // TsumTestApp // // Created by Semen Matsepura on 13.04.2018. // Copyright © 2018 Semen Matsepura. All rights reserved. // import UIKit protocol Coordinator { func start() func stop() func navigate(from source: UIViewController, to destination: UIViewController, with identifier: String?, and sender: AnyObject?) } extension Coordinator { func navigate(from source: UIViewController, to destination: UIViewController, with identifier: String?, and sender: AnyObject?) { } func stop() { } }
//** - Комментарии проверяющего // - Комментарии разработчика //** Генератор данных почти полностью был написан на заняти // Homework 3. School /* Школа и ученики Ученики параметры : ФИО, Мама, Папа, Телефон, Расстояние дома от школы Школа: Список классов (1-11, буквы а б в), в каждом классе может быть от 15 до 25 учеников, предметы: 5 шт, Оценка ученика: за 4 четверти Д/з Существует база данных школы, в которой учатся ученики. необходимо: 1) Вывести в отсортированном виде учеников: а) по дальности проживания (по всей школе и по классу) от самого ближнего к самому дальнему и от самого дальнего к самому ближнему б) по алфавиту (фио) (по всей школе и по классу) от а до я и от я до а в) по успеваемости (среднее арифметическое из всех оценок) (по всей школе и по классу) от лучшей успеваемости до худшей и от худшей успеваемости до лучшей 2) Организовать простой поиск учеников по всем параметрам: а) ФИО (искать можно как по целому ФИО, так и по имени, фамилии, отчеству, или по части имени, фамилии, отчества) б) По дальности от школы (в промежутке о a…b) в) По успеваемости (по определенному одному предмету, по всем предметам) 3) Вывести общую информацию про учеников школы. а) Количество классов б) Количество учеников в школе и в каждом классе в) Средняя успеваемость учеников по каждому предмету г) Учеников, которые претендуют на золотую медаль (только для 11 классов) */ import Foundation; class DataGenerator { private static let arMaleSurNames: [String] = ["Иванов", "Сидоров", "Петров", "Фролов", "Антонов", "Сергеев", "Ревин", "Севрюков", "Казаков", "Тюняев"]; private static let arFemaleSurNames: [String] = ["Ивановa", "Сидоровa", "Петровa", "Фроловa", "Антоновa", "Сергеевa", "Ревинa", "Севрюковa", "Казаковa", "Тюняевa"]; private static let arMaleNames: [String] = ["Николай", "Дмитрий", "Петр", "Олег", "Артём", "Василий", "Валентин", "Фёдор", "Александр", "Алексей"]; private static let arFemaleNames: [String] = ["Ольга", "Ксения", "Валентина", "Виктория", "Алина", "Светлана", "Людмила", "Марина", "Татьяна", "Вера"]; private static var arMaleSecondNames: [String] = ["Сергеевич", "Александрович", "Иванович", "Николаевич", "Аркадьевич", "Андреевич", "Васильевич", "Олегович", "Валентинович", "Евгеньевич"];; private static var arFemaleSecondNames: [String] = ["Сергеевна", "Александровна", "Ивановна", "Николаевна", "Аркадьевна", "Андреевна", "Васильевна", "Олеговна", "Валентиновна", "Евгеньевна"];; private static let arLesson: [String] = ["Математика","Русский язык","Литература","Физика","Геометрия"]; private static var cLastIndexs = (name: -1, surName: -1, secondName: -1); public class func getRandNubmer(number: Int) -> Int { return Int(arc4random_uniform(UInt32(number))); } public class func getSurName (bMale: Bool = true, bUseLastIndex: Bool = false) -> String { let arValue: [String] = bMale ? arMaleSurNames : arFemaleSurNames; var nIndex = getRandNubmer(number: arValue.count); if (bUseLastIndex) { nIndex = cLastIndexs.surName; } else { cLastIndexs.surName = nIndex; } return arValue[nIndex]; } public class func getName (bMale: Bool = true) -> String { let arValue: [String] = bMale ? arMaleNames : arFemaleNames; let nIndex = getRandNubmer(number: arValue.count); return arValue[nIndex]; } public class func getSecondName(bMale: Bool = true, bUseLastIndex: Bool = false) -> String { let arValue: [String] = bMale ? arMaleSecondNames : arFemaleSecondNames; var nIndex = getRandNubmer(number: arValue.count); if (bUseLastIndex) { nIndex = cLastIndexs.secondName; } else { cLastIndexs.secondName = nIndex; } return arValue[nIndex]; } public class func getDistance () -> Double { return Double(getRandNubmer(number: 500)) / 10.0 + 1.0; } public class func getLessons (count: Int) -> Set<String> { var arLessons = Set<String>(); repeat { let lesson = arLesson[getRandNubmer(number: arLesson.count)]; arLessons.insert(lesson); } while count > arLessons.count return arLessons; } public class func arrayGenerator(count: Int, distans: (min: Int, max: Int)) -> [Int8] { var arResult = [Int8](); for _ in 0..<count { arResult.append(Int8(rand(min: distans.min, max: distans.max))); } return arResult; } public class func getRates (count: Int) -> [(lesson: String, rate: [Int8])] { var arRates = [(String, [Int8])](); // print(count); let arLesson = getLessons(count: count); // print(arLesson); for lesson in arLesson { let rate = (lesson: lesson, rate: arrayGenerator(count: 4, distans: (min: 2, max: 5))); arRates.append(rate); } return arRates; } public class func rand(min: Int, max: Int) -> Int { let delta = max - min + 1; return getRandNubmer(number: delta) + min; } } class Tools { public static func getSortByDistance(arLearners:[Learner] = [], bDesc: Bool = false) -> [Learner] { var arLearnersOut: [Learner] = []; arLearnersOut = arLearners.sorted { bDesc ? $0.dDistance > $1.dDistance : $0.dDistance < $1.dDistance } return arLearnersOut; } public static func getSortByFio(arLearners:[Learner] = [], bDesc: Bool = false) -> [Learner] { var arLearnersOut: [Learner] = []; arLearnersOut = arLearners.sorted { bDesc ? $0.sFio > $1.sFio : $0.sFio < $1.sFio } return arLearnersOut; } public static func getSortByRates(arLearners:[Learner] = [], bDesc: Bool = false) -> [Learner] { var arLearnersOut: [Learner] = []; arLearnersOut = arLearners.sorted { bDesc ? $0.dAvarageRate > $1.dAvarageRate : $0.dAvarageRate < $1.dAvarageRate } return arLearnersOut; } public static func printLearners (arLearners: [Learner]) -> String { var sResult = ""; for (index, learner) in arLearners.enumerated() { sResult += "\(index+1). \(learner.sFio), дистанция \(learner.dDistance), средний бал \(learner.dAvarageRate)\(learner.sDescription.isEmpty ? "" : ", " + learner.sDescription)\n"; } return sResult; } } class School { private var arClassRoom: [(letter: String, num: Int, char: String, list: ClassRoom)] = []; private static let nCountClass: Int = 11; private static let arLetters: [String] = ["а", "б", "в"]; public static func generate() -> School { let obSchool = School(); for classNumber in 1...nCountClass { let nLetterCount = DataGenerator.rand(min: 1, max: 3); for indexLetter in 0..<nLetterCount { let classChar = arLetters[indexLetter]; let sClassName = String(classNumber) + classChar; obSchool.arClassRoom.append((letter: sClassName, num: classNumber, char: classChar, list: ClassRoom.generate())); } } return obSchool; } public func getClassRooms() -> [(letter: String, num: Int, char: String, list: ClassRoom)] { return arClassRoom; } public func getClassRoomCount() -> Int { return arClassRoom.count; } public func getAllLearners() -> [Learner] { var arLeaners: [Learner] = []; for cClassRoom in arClassRoom { arLeaners += cClassRoom.list.getLearners(); } return arLeaners; } public func getSortByDistance(bDesc: Bool = false) -> [Learner] { return Tools.getSortByDistance(arLearners: self.getAllLearners(), bDesc: bDesc); } public func getSortByFio(bDesc: Bool = false) -> [Learner] { return Tools.getSortByFio(arLearners: self.getAllLearners(), bDesc: bDesc); } public func getSortByRates(bDesc: Bool = false) -> [Learner] { return Tools.getSortByRates(arLearners: self.getAllLearners(), bDesc: bDesc); } public func getClassList() -> String { var sResult = ""; for obj in arClassRoom { sResult += "Класс \(obj.letter):\n"; sResult += "\(obj.list.getClassRoomLeanerList())"; } return sResult; } } class ClassRoom { private var arLearners: [Learner] = []; public static func generate() -> ClassRoom { let classRoom = ClassRoom(); let count = DataGenerator.rand(min: 15, max: 25); var arFio: [String] = []; for _ in 0..<count { let obLeaner: Learner = Learner.generate(); let sFio = obLeaner.sFio; if (!arFio.contains(sFio)) { classRoom.arLearners.append(obLeaner); arFio.append(sFio); } } return classRoom; } public func getLearners() -> [Learner] { return arLearners; } public func getCount() -> Int { return arLearners.count; } public func getSortByDistance(bDesc: Bool = false) -> [Learner] { return Tools.getSortByDistance(arLearners: arLearners, bDesc: bDesc); } public func getSortByFio(bDesc: Bool = false) -> [Learner] { return Tools.getSortByFio(arLearners: arLearners, bDesc: bDesc); } public func getSortByRates(bDesc: Bool = false) -> [Learner] { return Tools.getSortByRates(arLearners: arLearners, bDesc: bDesc); } public func getClassRoomLeanerList() -> String { var sResult = ""; for (index, obj) in arLearners.enumerated() { sResult += "\(index + 1). \(obj.sFio)\n"; } return sResult; } } class Learner { var sFio: String = ""; var sMotherFio: String = ""; var sFatherFio: String = ""; var dDistance: Double = 0.0; var arRates: [(lesson: String, rate: [Int8])] = []; var dAvarageRate: Double = 0.0; var sDescription: String = ""; // динамические описание public func getInfo() -> String { var sResult = ""; sResult += "ФИО: \(sFio)\n"; sResult += " ФИО матери: \(sMotherFio)\n"; sResult += " ФИО отца: \(sFatherFio)\n"; sResult += " Дистанция: \(dDistance)\n"; sResult += " Успеваемость:\n"; for lesson in arRates { sResult += " \(lesson.lesson): "; for (index, rate) in lesson.rate.enumerated() { sResult += "\(rate)"; if (index != lesson.rate.count - 1) { sResult += ", "; } } sResult += "\n"; } return sResult; } public func getAvarageRate() -> [String:Double] { var arResult: [String:Double] = [:]; for obj in arRates { let nRateCount = Double(obj.rate.count); var dCount = 0.0; if let key = String(obj.lesson) { //for rate in obj.rate { // nCount += Double(rate); // dCount = Double(obj.rate.reduce(0, +)); dCount /= nRateCount; arResult[key] = dCount; } } return arResult; } public func isGold() -> Bool { var bRes = true; var nCountAll: Int = 0, nFourtyCount: Int = 0, nResult: Double = 0.0; // проверим на наличие оценок ниже 4 loop: for oRate in arRates { for rate in oRate.rate { if (rate < 4) { bRes = false; break loop; } } } if (bRes) { // будем считать оценки не более 25% четверок for oRate in arRates { nCountAll += oRate.rate.count; for rate in oRate.rate { if (rate == 4) { nFourtyCount += 1; } } } nResult = round(Double(nCountAll / 4)); bRes = Int(nResult) >= nFourtyCount; } return bRes; } public static func generate() -> Learner { let leaner = Learner(); let isMale = DataGenerator.getRandNubmer(number: 2) == 1; // 0 - ж, 1 - м let fatherSurName = DataGenerator.getSurName(); let fatherSecondName = DataGenerator.getSecondName(); let motherSurName = DataGenerator.getSurName(bMale: false, bUseLastIndex: true); let motherSecondName = DataGenerator.getSecondName(bMale: false, bUseLastIndex: true); leaner.sFatherFio = "\(fatherSurName) \(DataGenerator.getName()) \(fatherSecondName)"; leaner.sMotherFio = "\(motherSurName) \(DataGenerator.getName(bMale: false)) \(motherSecondName)"; leaner.sFio = "\(isMale ? fatherSurName : motherSurName) " + (DataGenerator.getName(bMale: isMale)) + " \(isMale ? fatherSecondName : motherSecondName)"; leaner.dDistance = DataGenerator.getDistance(); leaner.arRates = DataGenerator.getRates(count: 5); let arAvarageRates: [String: Double] = leaner.getAvarageRate(); if (!arAvarageRates.isEmpty) { var dCount:Double = 0.0; for (_, value) in arAvarageRates { dCount += value; } leaner.dAvarageRate = dCount/Double(arAvarageRates.count); } return leaner; } } //** класс SchoolResult в таком формате не долен сущестоввать. //** все функции поиска нужно было вшить в классы Learner, ClassRoom и School: /* Пример: поиск по ФИО ClassRoom.find(fio:String)->[Learner] {...} // поиск ученика по фамилии в классе, метод должен быть объявлен в классе CGroup CSchool.find(fio:String)->[CPerson] { // поиск ученика в школе, метод должен быть объявлен в классе CSchool ... for ... in ... { Learner.find(fio:String)->[CPerson] {...} } ...} */ class SchoolResult { private var obSchool: School; public init(obSchool: School) { self.obSchool = obSchool; } private func getClassRooms() -> [(letter: String, num: Int, char: String, list: ClassRoom)]{ return obSchool.getClassRooms(); } // Количество классов public func getClassRoomCount() -> String { let nCount = obSchool.getClassRoomCount(); var sResult = "В школе нет классов"; if (nCount > 0) { sResult = "Количество классов в школе: \(nCount)"; } return sResult; } //Количество учеников в школе и в каждом классе public func getLeanerCount() -> String { let arClassRooms = self.getClassRooms(); var sResult = "Количество учеников в классе:\n", nCountAll = 0; for cClassList in arClassRooms { let nCount = cClassList.list.getCount(); sResult += "\(cClassList.letter): \(nCount)\n"; nCountAll += nCount; } sResult += "Всего в школе учеников: \(nCountAll)"; return sResult; } //Средняя успеваемость учеников по каждому предмету public func getLeanersStat() -> String { let arClassRooms = self.getClassRooms(); var sResult = "Средняя успеваемость учеников по каждому предмету:\n"; var arResult: [String:Double] = [:]; var nLearnerCount = 0; for cClassList in arClassRooms { let arLearners = cClassList.list.getLearners(); for obLearner in arLearners { let arAvarage = obLearner.getAvarageRate(); //print(arAvarage); if arResult.isEmpty { for index in arAvarage.keys { arResult[index] = 0; } } for (lesson, value) in arAvarage { if let val = arResult[lesson] { arResult[lesson] = val + value; } } nLearnerCount += 1; } } if (nLearnerCount > 0) { for (lesson, value) in arResult { let _value = value / Double(nLearnerCount); sResult += "\(lesson): \(String(format: "%.2f", _value))\n"; } } return sResult; } //Ученики, которые претендуют на золотую медаль (только для 11 классов) // Алгоритм такой: все оценки должны быть 5 и 4, преобладание 4 не более чам 25% от общего числа public func getGoldLeaners() -> String { let arClassRooms = self.getClassRooms(); var sResult = ""; for cClassList in arClassRooms { if (cClassList.num != 11) { continue; } let arLearners = cClassList.list.getLearners(); for obLearner in arLearners { if (obLearner.isGold()) { sResult += "\(obLearner.sFio)\n"; } } } sResult = "Претенденты на медаль:\n\(sResult.isEmpty ? "Нет медалистов в этом году" : sResult)"; return sResult; } public func getSortResult () -> String { var sResult = ""; sResult += "По классам:\n"; sResult += "Дальности проживания по возрастание:\n"; for cClassList in self.getClassRooms() { sResult += "Класс \(cClassList.letter):\n"; sResult += Tools.printLearners(arLearners: cClassList.list.getSortByDistance()); } sResult += "\n\n"; sResult += "Дальности проживания по убыванию:\n"; for cClassList in self.getClassRooms() { sResult += "Класс \(cClassList.letter):\n"; sResult += Tools.printLearners(arLearners: cClassList.list.getSortByDistance(bDesc: true)); } sResult += "\n\n"; sResult += "По алфавиту по возрастанию:\n"; for cClassList in self.getClassRooms() { sResult += "Класс \(cClassList.letter):\n"; sResult += Tools.printLearners(arLearners: cClassList.list.getSortByFio()); } sResult += "\n\n"; sResult += "По алфавиту по убыванию:\n"; for cClassList in self.getClassRooms() { sResult += "Класс \(cClassList.letter):\n"; sResult += Tools.printLearners(arLearners: cClassList.list.getSortByFio(bDesc: true)); } sResult += "\n\n"; sResult += "Успеваемость по возрастание:\n"; for cClassList in self.getClassRooms() { sResult += "Класс \(cClassList.letter):\n"; sResult += Tools.printLearners(arLearners: cClassList.list.getSortByRates()); } sResult += "\n\n"; sResult += "Успеваемость по убыванию:\n"; for cClassList in self.getClassRooms() { sResult += "Класс \(cClassList.letter):\n"; sResult += Tools.printLearners(arLearners: cClassList.list.getSortByRates(bDesc: true)); } sResult += "\n\n"; sResult += "По всей школе:\n"; sResult += "Дальности проживания по возрастание:\n"; sResult += Tools.printLearners(arLearners: obSchool.getSortByDistance()); sResult += "\n"; sResult += "Дальности проживания по убыванию:\n"; sResult += Tools.printLearners(arLearners: obSchool.getSortByDistance(bDesc: true)); sResult += "\n\n"; sResult += "По алфавиту по возрастанию:\n"; sResult += Tools.printLearners(arLearners: obSchool.getSortByFio()); sResult += "\n"; sResult += "По алфавиту по убыванию:\n"; sResult += Tools.printLearners(arLearners: obSchool.getSortByFio(bDesc: true)) sResult += "\n\n"; sResult += "Успеваемость по возрастание:\n"; sResult += Tools.printLearners(arLearners: obSchool.getSortByRates()); sResult += "\n"; sResult += "Успеваемость по убыванию:\n"; sResult += Tools.printLearners(arLearners: obSchool.getSortByRates(bDesc: true)); return sResult; } public func getAllResult() -> String { var sResult = ""; /* 3) Вывести общую информацию про учеников школы. а) Количество классов б) Количество учеников в школе и в каждом классе в) Средняя успеваемость учеников по каждому предмету г) Учеников, которые претендуют на золотую медаль (только для 11 классов) */ sResult += "Общая информация про учеников школы:\n"; sResult += self.getClassRoomCount(); sResult += "\n\n"; sResult += self.getLeanerCount(); sResult += "\n\n"; sResult += self.getLeanersStat(); sResult += "\n\n"; sResult += self.getGoldLeaners(); sResult += "\n\n------------------------------\n\n"; /* 1) Вывести в отсортированном виде учеников: а) по дальности проживания (по всей школе и по классу) от самого ближнего к самому дальнему и от самого дальнего к самому ближнему б) по алфавиту (фио) (по всей школе и по классу) от а до я и от я до а в) по успеваемости (среднее арифметическое из всех оценок) (по всей школе и по классу) от лучшей успеваемости до худшей и от худшей успеваемости до лучшей */ sResult += "Отсортированные ученики:\n"; sResult += self.getSortResult(); sResult += "\n\n------------------------------\n\n"; return sResult; } // 3) Организовать простой поиск учеников по параметрам: // а) ФИО (искать можно как по целому ФИО, так и по имени, фамилии, отчеству, или по части имени, фамилии, отчества) public func searchFio(sSearch: String) -> String { var sResult = "Поиск по ФИО:\n"; if (sSearch.isEmpty) { sResult += "Вы ввели пустой поисковой запрос"; } else { var arResultLearners: [Learner] = []; let sSearchLower = sSearch.lowercased(); for learner in self.obSchool.getAllLearners() { let sFio = learner.sFio.lowercased(); if (sFio.contains(sSearchLower)) { arResultLearners.append(learner); } } if (!arResultLearners.isEmpty) { sResult += Tools.printLearners(arLearners: arResultLearners); } else { sResult += "Никого не найдено"; } } return sResult; } private func checkInterval(dStart: Double, dEnd: Double, sError: inout String) -> Bool { var bResult = true; if (dStart < 0 || dEnd < 0) { bResult = false; sError += "Параметры поиска должны быть больше нуля\n"; } else if (dStart <= 0 && dEnd <= 0) { bResult = false; sError += "Два параметра не могут быть равны 0. Введите другие значения\n"; } else if (dStart > dEnd) { bResult = false; sError += "Параметр правой границы не может быть меньше левой\n"; } if (!bResult) { sError = "Ошибка: \(sError)"; } return bResult; } // б) По дальности от школы (в промежутке о a…b) public func searchDistance(dStart: Double = 0, dEnd: Double = 100) -> String { var sResult = "Поиск по дистанации от дома до школы:\n"; var sError = ""; if (self.checkInterval(dStart: dStart, dEnd: dEnd, sError: &sError)) { var arResultLearners: [Learner] = []; for learner in self.obSchool.getAllLearners() { let distance = learner.dDistance; if (dStart <= distance && dEnd >= distance) { arResultLearners.append(learner); } } if (!arResultLearners.isEmpty) { // отсортируем по дистанции по возрастанию arResultLearners = Tools.getSortByDistance(arLearners: arResultLearners); sResult += Tools.printLearners(arLearners: arResultLearners); } else { sResult += "Никого не найдено"; } } else { sResult += sError; } return sResult; } // в) По успеваемости по всем предметам (общей) public func searchRatesAll(dStart: Double = 0, dEnd: Double = 5) -> String { var sResult = "Поиск по общей успеваемости:\n"; var sError = ""; if (self.checkInterval(dStart: dStart, dEnd: dEnd, sError: &sError)) { var arResultLearners: [Learner] = []; for learner in self.obSchool.getAllLearners() { let avarageRate = learner.dAvarageRate; if (dStart <= avarageRate && dEnd >= avarageRate) { arResultLearners.append(learner); } } if (!arResultLearners.isEmpty) { // отсортируем по общему среднему балу по возрастанию arResultLearners = Tools.getSortByRates(arLearners: arResultLearners); sResult += Tools.printLearners(arLearners: arResultLearners); } else { sResult += "Никого не найдено"; } } else { sResult += sError; } return sResult; } // в) По успеваемости по определенному одному предмету public func searchRatesByLesson(sLesson: String, dStart: Double = 0, dEnd: Double = 5) -> String { var sResult = ""; var sError = ""; if (self.checkInterval(dStart: dStart, dEnd: dEnd, sError: &sError)) { var arResultLearners: [Learner] = []; var arLearners: [(dAvarageRate: Double, obLearner: Learner)] = []; var bIssetLesson = false; var dCount: Double = 0; for learner in self.obSchool.getAllLearners() { dCount = 0; for obRate in learner.arRates { if (obRate.lesson != sLesson) { continue; } bIssetLesson = true; dCount = Double(obRate.rate.reduce(0, +)); dCount /= Double(obRate.rate.count); } if (bIssetLesson) { if (dStart <= dCount && dEnd >= dCount) { learner.sDescription += "Средний бал по предмету \(sLesson) - \(dCount)"; arLearners.append((dAvarageRate: dCount, obLearner: learner)); } } else { sResult += "Ошибка: Предмет не найден.\n"; break; } } if (!arLearners.isEmpty) { // отсортируем по возрастанию средней оценки по заданному предмету arLearners = arLearners.sorted { $0.dAvarageRate < $1.dAvarageRate } for cLearner in arLearners { arResultLearners.append(cLearner.obLearner); } sResult += Tools.printLearners(arLearners: arResultLearners); } else if (sResult.isEmpty) { sResult += "Никого не найдено"; } } else { sResult += sError; } sResult = "Поиск по общей успеваемости:\n\(sResult)"; return sResult; } } let school = School.generate(); let obSchoolResult = SchoolResult(obSchool: school); print(obSchoolResult.getAllResult()); print(obSchoolResult.searchFio(sSearch: "Николай")); print(obSchoolResult.searchDistance(dStart: 39.1, dEnd: 41)); print(obSchoolResult.searchRatesAll(dStart: 3, dEnd: 3.85)); print(obSchoolResult.searchRatesByLesson(sLesson: "Русский язык", dStart: 4.5, dEnd: 5)); // Итог: /* Плюсы: 1) Хорошо читаемый код 2) Присутвует понимание задачи Минусы: 1) класс SchoolResult в таком формате не долен сущестоввать. все функции поиска нужно было вшить в классы Learner, ClassRoom и School. */
// // BrandList.swift // gjs_user // // Created by 大杉网络 on 2019/9/19. // Copyright © 2019 大杉网络. All rights reserved. // import UIKit @available(iOS 11.0, *) class BrandItem: UIView { var navC : UINavigationController? override init(frame: CGRect) { super.init(frame: frame) } // (kScreenW - 60) * 0.25 * 0.52 + 72 + (kScreenW - 70)/3 convenience init(frame: CGRect, data: brandItem, nav: UINavigationController) { self.init(frame: frame) self.navC = nav self.backgroundColor = colorwithRGBA(251, 122, 30, 1) self.layer.cornerRadius = 5 // self.layer.masksToBounds = true self.configureLayout { (layout) in layout.isEnabled = true layout.width = YGValue(kScreenW - 30) layout.marginLeft = 15 } let titleView = UIView() titleView.configureLayout { (layout) in layout.isEnabled = true layout.width = YGValue(kScreenW - 30) layout.flexDirection = .row layout.justifyContent = .spaceBetween layout.alignItems = .center layout.padding = 10 } self.addSubview(titleView) let logo = UIImageView() logo.layer.cornerRadius = 5 logo.layer.masksToBounds = true logo.configureLayout { (layout) in layout.isEnabled = true layout.width = YGValue((kScreenW - 60) * 0.25) layout.height = YGValue((kScreenW - 60) * 0.25 * 0.52) } var url : URL? if let logo = data.brand_logo { url = URL(string: logo)! } let placeholderImage = UIImage(named: "loading") logo.af_setImage(withURL: url!, placeholderImage: placeholderImage) titleView.addSubview(logo) let nameView = UIView() nameView.configureLayout { (layout) in layout.isEnabled = true layout.flexDirection = .column layout.alignItems = .center layout.justifyContent = .center } titleView.addSubview(nameView) let brandName = UILabel() brandName.text = data.fq_brand_name! brandName.font = FontSize(14) brandName.textColor = .white brandName.configureLayout { (layout) in layout.isEnabled = true } nameView.addSubview(brandName) let explain = UILabel() explain.text = "--品牌直销--" explain.font = FontSize(14) explain.textColor = .white explain.configureLayout { (layout) in layout.isEnabled = true layout.marginTop = 5 } nameView.addSubview(explain) // 更多 let moreBtn = UIButton() moreBtn.tag = Int(data.id!)! moreBtn.addTarget(self, action: #selector(toGoodsList), for: .touchUpInside) moreBtn.backgroundColor = .clear moreBtn.layer.cornerRadius = 12 moreBtn.layer.borderColor = UIColor.white.cgColor moreBtn.layer.borderWidth = 1 moreBtn.configureLayout { (layout) in layout.isEnabled = true layout.flexDirection = .row layout.justifyContent = .center layout.alignItems = .center layout.width = 70 layout.height = 24 } titleView.addSubview(moreBtn) let moreLabel = UILabel() moreLabel.text = "更多" moreLabel.font = FontSize(14) moreLabel.textColor = .white moreLabel.configureLayout { (layout) in layout.isEnabled = true layout.marginRight = 5 } moreBtn.addSubview(moreLabel) let mareArrow = UIImageView(image: UIImage(named: "arrow-white")) mareArrow.configureLayout { (layout) in layout.isEnabled = true layout.height = 14 layout.width = 7 } moreBtn.addSubview(mareArrow) // 品牌商品 let goodsList = UIView() goodsList.backgroundColor = .white goodsList.layer.cornerRadius = 5 goodsList.configureLayout { (layout) in layout.isEnabled = true layout.flexDirection = .row layout.width = YGValue(kScreenW - 30) layout.padding = 10 layout.paddingRight = 0 } self.addSubview(goodsList) for item in data.item! { let goodsItem = UIButton() goodsItem.tag = Int(item.itemid!)! goodsItem.addTarget(self, action: #selector(toDetail), for: .touchUpInside) goodsItem.configureLayout { (layout) in layout.isEnabled = true layout.width = YGValue((kScreenW - 70)/3) layout.marginRight = 10 } goodsList.addSubview(goodsItem) let goodsImg = UIImageView() goodsImg.configureLayout { (layout) in layout.isEnabled = true layout.width = YGValue((kScreenW - 70)/3) layout.height = YGValue((kScreenW - 70)/3) layout.marginBottom = 3 } var url : URL? if let imgUrl = item.itempic { url = URL(string: imgUrl)! } let placeholderImage = UIImage(named: "loading") goodsImg.af_setImage(withURL: url!, placeholderImage: placeholderImage) goodsItem.addSubview(goodsImg) let goodsInfo = UIView() goodsInfo.configureLayout { (layout) in layout.isEnabled = true layout.width = YGValue((kScreenW - 70)/3) } goodsItem.addSubview(goodsInfo) let goodsTitle = UILabel() goodsTitle.text = item.itemtitle! goodsTitle.font = FontSize(14) goodsTitle.textColor = kMainTextColor goodsTitle.configureLayout { (layout) in layout.isEnabled = true layout.width = YGValue((kScreenW - 70)/3) } goodsInfo.addSubview(goodsTitle) // 价格 let goodsPrice = UIView() goodsPrice.configureLayout { (layout) in layout.isEnabled = true layout.flexDirection = .row layout.justifyContent = .spaceBetween layout.width = YGValue((kScreenW - 70)/3) } goodsInfo.addSubview(goodsPrice) // 优惠价 let nowPrice = UILabel() nowPrice.text = "\(item.itemendprice!)元" nowPrice.font = FontSize(12) nowPrice.textColor = kLowOrangeColor nowPrice.configureLayout { (layout) in layout.isEnabled = true } goodsPrice.addSubview(nowPrice) // 原价 let oldPrice = UILabel() oldPrice.font = FontSize(12) oldPrice.textColor = kLowGrayColor oldPrice.configureLayout { (layout) in layout.isEnabled = true } let priceString = NSMutableAttributedString.init(string: "¥\(item.itemprice!)") priceString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSNumber.init(value: 1), range: NSRange(location: 0, length: priceString.length)) oldPrice.attributedText = priceString goodsPrice.addSubview(oldPrice) } self.yoga.applyLayout(preservingOrigin: true) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func toDetail (_ btn : UIButton) { detailId = btn.tag self.navC!.pushViewController(DetailController(), animated: true) } @objc func toGoodsList (_ btn : UIButton) { brandId = btn.tag self.navC?.pushViewController(BrandGoodsListController(), animated: true) } }
// // SolverTests.swift // SolverTests // // Created by KO on 2018/09/20. // Copyright © 2018年 KO. All rights reserved. // import XCTest @testable import Slither2 class SolverTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testBasic() { // 5ms -> B:3ms, A:3ms, A+O:10ms, C:10ms var lines: [String] = [] lines.append("5 5") lines.append("2 1 1") lines.append("2 2 ") lines.append(" 3 12") lines.append("2 3 ") lines.append("2 2 ") let solver = Solver(board: Board(lines: lines)) var option = SolveOption() option.doAreaCheck = false option.tryOneStepMaxExtent = 100 option.useCache = true option.doColorCheck = true option.doGateCheck = true option.maxGuessLevel = 120 option.elapsedSec = 3600.0 let result = solver.solve(option: option) print(String(format: "Basic:Elapsed: %.0f ms", result.elapsed * 1000)) print(" Max Level:\(result.maxLevel)") XCTAssertTrue(result.solved) } func testHard1() { // 1330ms -> B:671ms, A:2282ms, A+O:593ms, C:514ms var lines: [String] = [] lines.append("21 14") lines.append("12 2 232 0222 3 ") lines.append("2 22 2 1 2 221 ") lines.append("2 2222323 21 32 3 3") lines.append(" 122 21 11 2 ") lines.append("2 2 12 3 22 21 33 1 ") lines.append("1 2 1 22 23 211 3") lines.append(" 131 12 2 1 2") lines.append("12 1 2212 3 3 3 ") lines.append("01 212 3 3 1 21 ") lines.append(" 22 2 1 111 2322") lines.append(" 0 1 3 1 0 ") lines.append("23 20 3 1 2 0 1 ") lines.append(" 202 2 2132 1 ") lines.append("3 1 232 2 23 0 00") let solver = Solver(board: Board(lines: lines)) var option = SolveOption() option.doAreaCheck = false option.tryOneStepMaxExtent = 100 option.useCache = true option.doColorCheck = true option.doGateCheck = true option.maxGuessLevel = 120 option.elapsedSec = 3600.0 let result = solver.solve(option: option) print(String(format: "Hard1:Elapsed: %.0f ms", result.elapsed * 1000)) print(" Max Level:\(result.maxLevel)") XCTAssertTrue(result.solved) } func testHard2() { // 347ms -> B:51ms, A:116ms, A+O:40ms, C:44ms var lines: [String] = [] lines.append("14 24") lines.append(" 3 3 2011 ") lines.append(" 3 23 2 01") lines.append(" 3 23 2") lines.append(" 2 13 32 2") lines.append(" 2 13 0 1") lines.append(" 2 22 ") lines.append(" 331 3 ") lines.append(" 1 32 32302 1 ") lines.append(" 23") lines.append("213 1 1 2") lines.append("2 2 202 2 3 ") lines.append("0 231 ") lines.append(" 332 1") lines.append(" 2 3 202 1 3") lines.append("1 2 3 223") lines.append("31 ") lines.append(" 3 02133 23 0 ") lines.append(" 1 112 ") lines.append(" 12 0 ") lines.append("1 3 33 0 ") lines.append("3 21 20 1 ") lines.append("1 21 0 ") lines.append("01 2 10 3 ") lines.append(" 3331 2 2 ") let solver = Solver(board: Board(lines: lines)) var option = SolveOption() option.doAreaCheck = false option.tryOneStepMaxExtent = 100 option.useCache = true option.doColorCheck = true option.doGateCheck = true option.maxGuessLevel = 120 option.elapsedSec = 3600.0 let result = solver.solve(option: option) print(String(format: "Hard2:Elapsed: %.0f ms", result.elapsed * 1000)) print(" Max Level:\(result.maxLevel)") XCTAssertTrue(result.solved) } func testBug1() { // 976ms -> B:79ms, A:127ms, A+O:60ms, C:105ms var lines: [String] = [] lines.append("14 24") lines.append(" 1 1 10 3 1 ") lines.append("0 3 0 2 2 12 ") lines.append(" ") lines.append(" 0101010101031") lines.append(" ") lines.append(" 3 2 1 20 ") lines.append("2 3 1 2 122") lines.append(" ") lines.append("1301010101010 ") lines.append(" 2") lines.append(" 3 3 1 0 121") lines.append("22 2 2 1 ") lines.append(" 1 2 2 20") lines.append("111 2 1 1 3 ") lines.append("1 ") lines.append(" 0101010101031") lines.append(" ") lines.append("120 0 1 1 3") lines.append(" 13 2 2 3 ") lines.append(" ") lines.append("1301010101010 ") lines.append(" ") lines.append(" 11 2 1 0 1 2") lines.append(" 1 1 10 1 1 ") let solver = Solver(board: Board(lines: lines)) var option = SolveOption() option.doAreaCheck = false option.tryOneStepMaxExtent = 100 option.useCache = true option.doColorCheck = true option.doGateCheck = true option.maxGuessLevel = 120 option.elapsedSec = 3600.0 let result = solver.solve(option: option) print(String(format: "Bug1:Elapsed: %.0f ms", result.elapsed * 1000)) print(" Max Level:\(result.maxLevel)") XCTAssertTrue(result.solved) } }
// // SelectAreaViewXib.swift // Project // // Created by 张凯强 on 2018/3/16. // Copyright © 2018年 HHCSZGD. All rights reserved. // import UIKit class SelectAreaViewXib: UIView, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet var selectBtn: UIButton! @IBOutlet var streetBtn: UIButton! @IBOutlet var areaBtn: UIButton! @IBOutlet var cityBtn: UIButton! @IBOutlet var province: UIButton! var provinceArr: [AreaModel] = [AreaModel]() var cityArr: [AreaModel] = [AreaModel]() var areaArr: [AreaModel] = [AreaModel]() var streetArr: [AreaModel] = [AreaModel]() func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.numberItem } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: AreaSelectColCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AreaSelectColCell", for: indexPath) as! AreaSelectColCell cell.cellBlock = { [weak self](model) in self?.selectIndexBtn(model: model) } switch indexPath.item { case 0: cell.dataArr = self.provinceArr case 1: cell.dataArr = self.cityArr case 2: cell.dataArr = self.areaArr case 3: cell.dataArr = self.streetArr default: break } return cell } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == self.collectionView { } } func selectIndexBtn(model: AreaModel) { } @IBOutlet var topView: UIScrollView! @IBOutlet var flowLayout: UICollectionViewFlowLayout! @IBOutlet var collectionView: UICollectionView! @IBAction func sureAction(_ sender: UIButton) { } override init(frame: CGRect) { super.init(frame: frame) } ///构造方法 var type: Int? var url: String? var containerView: UIView! init(frame: CGRect, type: Int, url: String) { super.init(frame: frame) if let subView = Bundle.main.loadNibNamed("SelectAreaViewXib", owner: self, options: nil)?.last as? UIView { self.containerView = subView self.addSubview(containerView) self.collectionView.register(UINib.init(nibName: "AreaSelectColCell", bundle: Bundle.main), forCellWithReuseIdentifier: "AreaSelectColCell") self.type = type self.url = url self.requestData(parentid: nil) { (model) in if let arr = model?.data { self.numberItem = 1 self.provinceArr = arr }else { self.numberItem = 0 } self.collectionView.reloadData() } } } var numberItem: Int = 0 override func layoutSubviews() { super.layoutSubviews() self.containerView.frame = self.bounds self.flowLayout.itemSize = self.collectionView.bounds.size } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension SelectAreaViewXib { ///请求数据 func requestData(parentid: String?, success: @escaping ((BaseModelForArr<AreaModel>?) -> ())) { let token = DDAccount.share.token ?? "" let id = DDAccount.share.id ?? "" var paramete = ["token": token] as [String: Any] if self.type != 0 { paramete["type"] = self.type ?? 0 } if let fatherid = parentid { paramete["parent_id"] = fatherid } var router: Router? if url == nil { router = Router.get("member/\(id)/shop/area", .api, paramete) }else { router = Router.get(url!, .api, paramete) } let _ = NetWork.manager.requestData(router: router!).subscribe(onNext: { (dict) in let model = BaseModelForArr<AreaModel>.deserialize(from: dict) success(model) }, onError: { (error) in }, onCompleted: { mylog("完成") }) { mylog("回收") } } }
// // ViewController.swift // Code Name Inception // // Created by Michael Arpasi on 3/30/20. // Copyright © 2020 Michael Arpasi. All rights reserved. // import UIKit class ViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var TopNoteField: UITextView! override func viewDidLoad() { super.viewDidLoad() TopNoteField.delegate = self // Do any additional setup after loading the view. } }
// // ColorInterfaceController.swift // VBCounter // // Created by Ian McCallum on 3/25/17. // Copyright © 2017 com.jandm-design. All rights reserved. // import WatchKit import Foundation class MatchInterfaceController: WKInterfaceController { var currentMatch: MatchModel @IBOutlet var visitorButton: WKInterfaceButton! @IBOutlet var homeButton: WKInterfaceButton! @IBOutlet var visitorGames: WKInterfaceLabel! @IBOutlet var homeGames: WKInterfaceLabel! override init() { currentMatch = MatchModel() super.init() } override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func visitorButtonPressed() { currentMatch.addPoint(side: "visitor") visitorGames.setText(String(currentMatch.visitorGames)) visitorButton.setTitle(String(currentMatch.visitorPoints)) homeButton.setTitle(String(currentMatch.homePoints)) } @IBAction func homeButtonPressed() { currentMatch.addPoint(side: "home") homeGames.setText(String(currentMatch.homeGames)) visitorButton.setTitle(String(currentMatch.visitorPoints)) homeButton.setTitle(String(currentMatch.homePoints)) } }
// // Created by milkavian on 5/9/20. // Copyright (c) 2020 milonmusk. All rights reserved. // import Foundation class Bot { let welcomeText = """ Я - бот-ласточка и я помогу тебе поиграть в спортивное ЧГК в условиях самоизоляции в максимально привычном формате. Что для этого нужно? 1) Чат со мной для Ведущего и групповой или приватный чат со мной для каждой из команд-участниц. 2) Ведущему необходимо создать одну большую видеоконференцию со всеми участниками игры таким образом, чтобы войс был только у Ведущего - чтобы все участники видели друг друга, но слышали только Ведущего, ну а Ведущий просто видит всех - как в обычном ЧГК. 3) Каждой команде при этом нужно также создать видеоконференцию для участников, где команда будет обсуждать вопросы, а также командный или приватный icq-чат со мной - я буду принимать ответы и помогать с проведением игры. 4) Чтобы создать новую игру, Ведущему в беседе со мной нужно нажать на кнопку "начать игру" или воспользоваться командой /startgame. После этого Ведущий получит id игры, который нужно раздать капитанам команд для присоединения к сессии игры. 5) Команда присоединяется к игре, нажав на кнопку "присоединиться к игре" или вызвав в чате команду "/join id название", где id - идентификатор игры, полученный от Ведущего, название - название вашей команды. 6) Ведущий получает от меня сообщения о том, какие команды зарегистрировались. 7) Когда все в сборе, Ведущий зачитывает первый вопрос, ПОСЛЕ чего нажимает на кнопку "Задать первый вопрос". Нумерация вопросов начинается с 1. Через 50 секунд я напомню игрокам о необходимости отправить ответ. После этого напоминания у команд есть 20 секунд (10 секунд до конца вопроса и 10 секунд на сбор ответов), чтобы отправить ответ. Команды могут ответить через команду "/answer ответ". 8) Ведущий получит от меня ответы всех команд в формате "номер вопроса - название команды - ответ" 9) Для окончания игры Ведущему необходимо нажать на кнопку "закончить игру" или вызвать команду /finish. Обязательно завершайте игровые сессии. """ let startgameButton = Button(text: "Новая игра", callbackData: .start) let joinButton = Button(text: "Присоединиться к игре", callbackData: .join) let finishButton = Button(text: "Закончить игру", callbackData: .finish) let helpButton = Button(text: "Помощь", callbackData: .help) let rulesButton = Button(text: "Правила", callbackData: .rules) let teamsReadyButton = Button(text: "Задать первый вопрос", callbackData: .teamsready) let setQuestionTimerButton = Button(text: "Следующий вопрос", callbackData: .setquestiontimer) let answerButton = Button(text: "Помощь по команде /answer", callbackData: .answer) let fbButton = Button(text: "Оставить отзыв", callbackData: .fb) let finishForceButton = Button(text: "Ага", callbackData: .finishforce) var lastEventId = 0 let apiHandler: IcqApiHandler! let gameModel: GameModel! init() { apiHandler = IcqApiHandler() gameModel = GameModel() } func run() { fetchEvents() } private func handleEvent(event: Event) { // dump(event.payload) switch event.payload { case .newMessage(let data): let text = splitStringIntoCommandAndArguments(text: data.text, argumentCount: 2) if let parts = data.parts { parts.forEach { if $0.type == "mention" { sendMessage(chatId: data.chat.chatId, text: "Я тут, я тут!", buttons: [helpButton]) } } } else { handleCommand(chatId: data.chat.chatId, command: text[0], arguments: text.count < 2 ? nil : text[1], chatData: data) } case .callbackQuery(let data): apiHandler.callbackAnswer(queryId: data.queryId) { result in switch result { case .success: print("NETWORK: button callback answer sent") case .failure(let error): print("NETWORK ERROR: failed to send a callback answer, error: \(error.localizedDescription)") return } } let chatData = data.message.chat switch data.callbackData { case .rules: sendMessage(chatId: chatData.chatId, text: "\(welcomeText)", buttons: [startgameButton, joinButton,helpButton]) case .start: if gameModel.hasActiveGame(userId: data.from.userId) { sendMessage(chatId: chatData.chatId, text: """ Похоже, у тебя есть незавершенная игра. Пожалуйста, заверши ее перед тем, как создавать новую или присоединяться к игре """, buttons: [finishButton]) print("LOGIC: userid \(chatData.chatId) tried to start a new game without quitting the active one") } else { let gameNumber = gameModel.randomString(length: 9) gameModel.createGame(ownerId: data.from.userId, gameNumber: gameNumber) sendMessage(chatId: chatData.chatId, text: """ Игра создана! ID новой игры: \(gameNumber), ее нужно передать капитанам. Я сообщу тебе, когда команды начнут присоединяться к игре. После того, как все команды соберутся, читай первый вопрос, после чего жми "Задать первый вопрос" - я начну отсчет до окончания времени вопроса". """, buttons: [teamsReadyButton, finishButton]) } case .finish: if !gameModel.hasActiveGame(userId: data.from.userId) { sendMessage(chatId: data.from.userId, text: "Похоже, у тебя нет активных игр. Чтобы что-то завершить, нужно что-то начать!", buttons: [startgameButton, joinButton]) print("LOGIC: no game to finish for userid \(chatData.chatId)") } else { sendMessage(chatId: data.from.userId, text: "Действительно завершить игру?", buttons: [finishForceButton]) } case .join: sendMessage(chatId: chatData.chatId, text: #""" Для присоединения к игре выполните в чате команду "/join id teamName" (без кавычек) где вместо id укажите присланный Ведущим id игры, а вместо teamName - название команды без кавычек, например /join l337ftw Любимый Кальмар Коздимы """#, buttons: [helpButton]) case .teamsready, .setquestiontimer: if gameModel.hasActiveGame(userId: chatData.chatId) { let teamsToNotify = gameModel.teamsToNotify(ownerId: data.from.userId) let question = gameModel.getCurrentQuestion(userId: data.from.userId) gameModel.incrementQuestionNumber(userId: data.from.userId) self.sendMessage(chatId: chatData.chatId, text: "Вопрос \(question). Таймер запущен. Через 50 секунд я напомню командам о необходимости ответа.") DispatchQueue.main.async { let _ = Timer.scheduledTimer(withTimeInterval: 50.0, repeats: false) { _ in for team in teamsToNotify { self.sendMessage(chatId: team, text: """ До сбора ответов сталось 10 секунд. Для отправки ответа выполните команду /answer ответ """, buttons: [self.answerButton]) } self.sendMessage(chatId: chatData.chatId, text: "Вопрос \(question). До конца таймера вопроса 10 секунд. На написание и отправку ответа команде дается еще 10 секунд.") } let _ = Timer.scheduledTimer(withTimeInterval: 70.0, repeats: false) { _ in self.sendMessage(chatId: chatData.chatId, text: """ Время на отправку ответов на вопрос \(question) закончено. Команды все еще могут их отправить, решение по ним принимает Ведущий. Если игра закончена - не забудьте нажать "завершить игру"! """, buttons: [self.setQuestionTimerButton, self.finishButton]) } } } else { sendMessage(chatId: chatData.chatId, text: """ Ой-ой, у тебя нет активной игры. Начни игру, чтоб задавать вопросы или присоединись к игре, чтоб отвечать на вопросы! """, buttons: [startgameButton, joinButton]) print("LOGIC: no game to finish for userid \(chatData.chatId)") } case .help: sendMessage(chatId: chatData.chatId, text: """ /start - эта команда запускает меня /stop - а эта останавливает /startgame - создает новую игру с уникальным id /join id имя команды - присоединиться к активной игре по ее id с именем команды (может состоять из нескольких слов), пример: /join 5ycIfmdD Салатные листья с Плутона /answer ваш ответ - ответить на текущий вопрос, пример: /answer котята. Допускается несколько слов в аргументе. /finish - закончить активную игру, выполняется от имени создателя игры. Пожалуйста, не забывайте завершать свои активные игры! /help - показать этот мануал /rules - показать правила карантинного ЧГК /fb текст отзыва - отправить отзыв обо мне или предложение, например "/fb ботик - котик" """) case .answer: sendMessage(chatId: chatData.chatId, text: """ Для ответа вызовите команду /answer ответ, например /answer Танос Разрешается передавать в аргументы несколько слов """) case .fb: sendMessage(chatId: chatData.chatId, text: #"Для отправки отзыва или предложения, пожалуйста, напишите команду "/fb отзыв", без кавычек. Я передам пожелания и предложения разработчику."#) case .finishforce: let usersToNotify = gameModel.finishGame(forOwnerId: data.from.userId) for user in usersToNotify { sendMessage(chatId: user, text: "Игра успешно закончена. Похлопаем Ведущему и ласточке - и можно играть заново!", buttons: [startgameButton, joinButton]) } default: sendMessage(chatId: chatData.chatId, text: #"42, потому что 404 - это слишком избито. Если вы попали сюда, нажав кнопку, которая выглядит работающей, пожалуйста, дайте знать разработчику, вызвав в чате команду \fb с описанием проблемы"#) } default: break } } private func sendMessage(chatId: String, text: String, buttons: [Button]? = nil ) { if let buttons = buttons { var buttonData: [Button] = [] for button in buttons { buttonData += [button] } let buttonsInside = buttons.chunked(into: 2) sendMessageToUser(message:TextMessage(text: text, buttons: buttonsInside, chatId: chatId)) return } sendMessageToUser(message:TextMessage(text: text, buttons: [], chatId: chatId)) } private func sendMessageToUser(message: TextMessage) { apiHandler.sendText( message: message, completion: { result in switch result { case .success(let data): let data = String(decoding: data, as: UTF8.self) print("NETWORK SENT MESSAGE TO USER, message: \(message.text), data: \(data)") case .failure (let error): print("NETWORK SEND MESSAGE TO USER ERROR", error.localizedDescription) } } ) } private func fetchEvents() { apiHandler.getEvents(lastEventId: lastEventId, completion: { result in switch result { case .success(let events): if let latestEvent = events.last { self.lastEventId = latestEvent.id events.forEach(self.handleEvent) } self.fetchEvents() case .failure(let error): print("NETWORK ERROR: failed to fetch events, error: \(error.localizedDescription)") // по таймеру перезапрашиваем, если не удалось распарсить json DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: { self.fetchEvents() }) } }) } private func splitStringIntoCommandAndArguments(text: String, argumentCount: Int) -> [String] { text.split(separator: " ", maxSplits: (argumentCount - 1)).map(String.init) } private func handleCommand(chatId: String, command: String, arguments: String?, chatData: NewMessagePayload? = nil) { let command = BotCommands(rawValue: command) switch command { case .start: sendMessage(chatId: chatId, text: "Привет! Создай игру или присоединись к существующей! Полные правила игры смотри по кнопке Правила.", buttons: [startgameButton, joinButton, rulesButton, helpButton, fbButton]) case .startgame: if gameModel.hasActiveGame(userId: chatId) { sendMessage(chatId: chatId, text: """ Похоже, у тебя есть незавершенная игра. Пожалуйста, заверши ее перед тем, как создавать новую или присоединяться к игре """, buttons: [finishButton]) print("LOGIC: userid \(chatId) tried to start a new game without quitting the active one") } else { let gameNumber = gameModel.randomString(length: 9) gameModel.createGame(ownerId: chatId, gameNumber: gameNumber) sendMessage(chatId: chatId, text: """ Игра создана! ID новой игры: \(gameNumber), ее нужно передать капитанам. Я сообщу тебе, когда команды начнут присоединяться к игре. После того, как все команды соберутся, читай первый вопрос, после чего жми "Задать первый вопрос - я начну отсчет до окончания времени вопроса.". """, buttons: [teamsReadyButton, finishButton]) } case .join: guard let arguments = arguments else { sendMessage(chatId: chatId, text: """ Для команды /join требуются два аргумента - id игры и название команды, например /join l337ftw Любимый Кальмар Коздимы """) return } let args = splitStringIntoCommandAndArguments(text: arguments, argumentCount: 2) guard args.count > 1 else { sendMessage(chatId: chatId, text: """ Для команды /join требуются два аргумента - id игры и название команды, например /join l337ftw Любимый Кальмар Коздимы """) return } guard let team = gameModel.addTeamToTheGame(gameId: args[0], teamId: chatId, teamName: args[1]) else { sendMessage(chatId: chatId, text: "Не удалось добавить вас к игре: игры с таким id не существует или она завершена") print("LOGIC: failed to add user \(chatId) to game \(args[0]), as the game doesn't exist") return } sendMessage(chatId: chatId, text: "Вы в игре! Как только все команды соберутся, ведущий зачитает первый вопрос, а я помогу собрать ответы.") sendMessage(chatId: gameModel.getOwnerById(gameId: args[0])!, text: "Команда \(team.name) вступила в игру", buttons: [teamsReadyButton, finishButton]) case .finish: if gameModel.hasActiveGame(userId: chatId) { sendMessage(chatId: chatId, text: "Действительно завершить игру?", buttons: [finishForceButton]) } else { sendMessage(chatId: chatId, text: "Похоже, у тебя нет активных игр. Чтобы что-то завершить, нужно что-то начать!", buttons: [startgameButton, joinButton]) print("LOGIC: no game to finish for userid \(chatId)") } case .answer: guard let arguments = arguments else { sendMessage(chatId: chatId, text: """ Для команды /answer требуется аргумент, например /answer Танос Разрешается передавать в аргументы несколько слов """) return } let args = splitStringIntoCommandAndArguments(text: arguments, argumentCount: 1) guard let currentGame = gameModel.getTeamGame(teamId: chatId) else { sendMessage(chatId: chatId, text: "Не удалось найти вашу активную игру. Возможно, вы не вступали в игровую сессию или игра была завершена") print("LOGIC: failed to fetch user's \(chatId) active game to send answers to") return } sendMessage(chatId: currentGame.owner, text: "Вопрос \(currentGame.question - 1) - \(currentGame.teams.filter { $0.id == chatId }.map { $0.name } ) - \(args[0])") sendMessage(chatId: chatId, text: #"Вы ответили "\#(args[0])" на вопрос \#(currentGame.question - 1). Отправлено."#) case .fb: guard let arguments = arguments else { sendMessage(chatId: chatId, text: "Я не могу отправить пустой отзыв :(") return } let args = splitStringIntoCommandAndArguments(text: arguments, argumentCount: 1) guard let chatData = chatData, let firstName = chatData.from.firstName else { sendMessage(chatId: "752532504", text: "Отзыв от UID \(chatId): \(args[0])") return } sendMessage(chatId: "752532504", text: "Отзыв от UID \(chatData.from.userId) (\(firstName)): \(args[0])") sendMessage(chatId: chatId, text: "Отзыв отправлен. Спасибо! Если я понадоблюсь - просто вызовите команду /start или упомяните меня в чате.") case .help: sendMessage(chatId: chatId, text: """ Команды, которые я поддерживаю: /start - эта команда запускает меня /stop - а эта останавливает /startgame - создает новую игру с уникальным id /join id имя команды - присоединиться к активной игре по ее id с именем команды (может состоять из нескольких слов), пример: /join 5ycIfmdD Салатные листья с Плутона /answer ваш ответ - ответить на текущий вопрос, пример: /answer котята. Допускается несколько слов в аргументе. /finish - закончить активную игру, выполняется от имени создателя игры. Пожалуйста, не забывайте завершать свои активные игры! /help - показать этот мануал /rules - показать правила карантинного ЧГК /fb arg1 - отправить отзыв обо мне или предложение, например "/fb ботик - котик" """) case .rules: sendMessage(chatId: chatId, text: "\(welcomeText)", buttons: [startgameButton, joinButton,helpButton]) default: sendMessage(chatId: chatId, text: "Неизвестная команда :(", buttons: [helpButton, rulesButton]) return } } }
import UIKit @IBDesignable class NibViewInitializer: UIView { @IBOutlet var contentView: UIView! override init(frame: CGRect) { super.init(frame: frame) loadNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) if subviews.isEmpty { loadNib() } } private func loadNib() { let ttt = type(of: self) let classString = String(describing: ttt) let bundle = Bundle(for: ttt) if UINib(nibName: classString, bundle: bundle).instantiate( withOwner: self, options: nil).first as? UIView != nil { awakeFromNib() addSubview(contentView) contentView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ contentView.topAnchor.constraint(equalTo: topAnchor), contentView.leadingAnchor.constraint(equalTo: leadingAnchor), contentView.bottomAnchor.constraint(equalTo: bottomAnchor), contentView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) } viewLoaded() } func viewLoaded() { // custom implementation } }
// // UserController.swift // Timeline // // Created by Taylor Mott on 11/3/15. // Copyright © 2015 DevMountain. All rights reserved. // import Foundation class UserController { private let kUser = "userKey" var currentUser: User! { get { guard let uid = FirebaseController.base.authData?.uid, let userDictionary = NSUserDefaults.standardUserDefaults().valueForKey(kUser) as? [String: AnyObject] else { return nil } return User(json: userDictionary, identifier: uid) } set { if let newValue = newValue { NSUserDefaults.standardUserDefaults().setValue(newValue.jsonValue, forKey: kUser) NSUserDefaults.standardUserDefaults().synchronize() } else { NSUserDefaults.standardUserDefaults().removeObjectForKey(kUser) NSUserDefaults.standardUserDefaults().synchronize() } } } static let sharedController = UserController() static func userForIdentifier(identifier: String, completion: (user: User?) -> Void) { FirebaseController.dataAtEndpoint("users/\(identifier)") { (data) -> Void in if let json = data as? [String: AnyObject] { let user = User(json: json, identifier: identifier) completion(user: user) } else { completion(user: nil) } } } static func fetchAllUsers(completion: (users: [User]) -> Void) { FirebaseController.dataAtEndpoint("users") { (data) -> Void in if let json = data as? [String: AnyObject] { let users = json.flatMap({User(json: $0.1 as! [String : AnyObject], identifier: $0.0)}) completion(users: users) } else { completion(users: []) } } } static func followUser(user: User, completion: (success: Bool) -> Void) { FirebaseController.base.childByAppendingPath("/users/\(sharedController.currentUser.identifier!)/follows/\(user.identifier!)").setValue(true) completion(success: true) } static func unfollowUser(user: User, completion: (success: Bool) -> Void) { FirebaseController.base.childByAppendingPath("/users/\(sharedController.currentUser.identifier!)/follows/\(user.identifier!)").removeValue() completion(success: true) } static func userFollowsUser(user: User, followsUser: User, completion: (follows: Bool) -> Void ) { FirebaseController.dataAtEndpoint("/users/\(user.identifier!)/follows/\(followsUser.identifier!)") { (data) -> Void in if let _ = data { completion(follows: true) } else { completion(follows: false) } } } static func followedByUser(user: User, completion: (followed: [User]?) -> Void) { FirebaseController.dataAtEndpoint("/users/\(user.identifier!)/follows/") { (data) -> Void in if let json = data as? [String: AnyObject] { var users: [User] = [] for userJson in json { userForIdentifier(userJson.0, completion: { (user) -> Void in if let user = user { users.append(user) completion(followed: users) } }) } } else { completion(followed: []) } } } static func authenticateUser(email: String, password: String, completion: (success: Bool, user: User?) -> Void) { FirebaseController.base.authUser(email, password: password) { (error, response) -> Void in if error != nil { print("Unsuccessful login attempt.") completion(success: false, user: nil) } else { print("User ID: \(response.uid) authenticated successfully.") UserController.userForIdentifier(response.uid, completion: { (user) -> Void in if let user = user { sharedController.currentUser = user } completion(success: true, user: user) }) } } } static func createUser(email: String, username: String, password: String, bio: String?, url: String?, completion: (success: Bool, user: User?) -> Void) { FirebaseController.base.createUser(email, password: password) { (error, response) -> Void in if let uid = response["uid"] as? String { var user = User(username: username, uid: uid, bio: bio, url: url) user.save() authenticateUser(email, password: password, completion: { (success, user) -> Void in completion(success: success, user: user) }) } else { completion(success: false, user: nil) } } } static func updateUser(user: User, username: String, bio: String?, url: String?, completion: (success: Bool, user: User?) -> Void) { var updatedUser = User(username: user.username, uid: user.identifier!, bio: bio, url: url) updatedUser.save() UserController.userForIdentifier(user.identifier!) { (user) -> Void in if let user = user { sharedController.currentUser = user completion(success: true, user: user) } else { completion(success: false, user: nil) } } } static func logoutCurrentUser() { FirebaseController.base.unauth() UserController.sharedController.currentUser = nil } static func mockUsers() -> [User] { let user1 = User(username: "hansolo", uid: "1234") let user2 = User(username: "ob1kenob", uid: "2356") let user3 = User(username: "3po", uid: "3456") let user4 = User(username: "leia", uid: "4567", bio: "Princess", url: "myspace.com") return [user1, user2, user3, user4] } }
// // FirstViewController.swift // Lesson02 // // Created by Rudd Taylor on 9/28/14. // Copyright (c) 2014 General Assembly. All rights reserved. // import UIKit class FirstViewController: UIViewController { var name: String? var age: String? @IBOutlet weak var nameField: UITextField! @IBOutlet weak var ageField: UITextField! @IBOutlet weak var generateTextButton: UIButton! @IBOutlet weak var textToReplaceLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() ageField.keyboardType = .NumberPad nameField.keyboardType = .ASCIICapable } /* TODO one: hook up a button in interface builder to a new function (to be written) in this class. Also hook up the label to this class. When the button is clicked, the function to be written must make a label say ‘hello world!’ TODO two: Connect the ‘name’ and ‘age’ text boxes to this class. Hook up the button to a NEW function (in addition to the function previously defined). That function must look at the string entered in the text box and print out “Hello {name}, you are {age} years old!” TODO three: Hook up the button to a NEW function (in addition to the two above). Print “You can drink” below the above text if the user is above 21. If they are above 18, print “you can vote”. If they are above 16, print “You can drive” TODO four: Hook up the button to a NEW function (in additino to the three above). Print “you can drive” if the user is above 16 but below 18. It should print “You can drive and vote” if the user is above 18 but below 21. If the user is above 21, it should print “you can drive, vote and drink (but not at the same time!”. */ // This isn't the prettiest, but it works @IBAction func generateTextAction(sender: UIButton) { if nameField.text == "" && ageField.text == "" { textToReplaceLabel.text = sayHelloWorld() } else if nameField.text == "" && ageField.text != "" { textToReplaceLabel.text = sayHelloWorld() + sayWhatCanYouDo(ageField.text) + sayEverythingYouCanDo(ageField.text) } else { textToReplaceLabel.text = sayHelloWorld() + sayHelloNameAge(name: nameField.text, age: ageField.text) + sayWhatCanYouDo(ageField.text) + sayEverythingYouCanDo(ageField.text) } } /* I used multiple carriage returns here instead of a new label as, depending on the input, there could be different edge case outputs...not sure if its what you wanted, let me know! */ func sayHelloWorld() -> String { return "hello world!" + "\r" } func sayHelloNameAge(#name: String, age: String) -> String { return "Hello \(name), you are \(age) years old!" + "\r" } func sayWhatCanYouDo(age: String) -> String { let ageInt = age.toInt() var response: String = "" if ageInt! > 20 { response = "You can drink" + "\r" } else if ageInt! > 17 { response = "You can vote" + "\r" } else if ageInt! > 15 { response = "You can drive" + "\r" } else { response = "You can't do anything, did you enter an age?" + "\r" } return response } func sayEverythingYouCanDo(age: String) -> String { let ageInt = age.toInt() var response: String = "" let drive = "You can drive", vote = " and vote", drink = " and drink (but not at the same time" if ageInt! > 20 { response = drive + vote + drink } else if ageInt! > 17 { response = drive + vote } else if ageInt! > 15 { response = drive } else { response = "You can't do anything, did you enter an age?" } return response } }
// // OrderBigCell.swift // hecApp-iOS // // Created by Asianark on 3/2/2016. // Copyright © 2016 Asianark. All rights reserved. // import UIKit class OrderBigCell: UITableViewCell{ @IBOutlet weak var Day: UILabel! @IBOutlet weak var Month: UILabel! @IBOutlet weak var lotteryType: UILabel! @IBOutlet weak var noteMoney: UILabel! @IBOutlet weak var playTypeName: UILabel! @IBOutlet weak var winMoney: UILabel! @IBOutlet weak var status: UILabel! @IBOutlet weak var statusImg: UIImageView! @IBOutlet weak var longSeperateLine: UIView! @IBOutlet weak var shortSeperateLine: UIView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // cURLTests.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 8/2/15. // Copyright © 2015 PureSwift. All rights reserved. // import XCTest import CcURL @testable import SwiftFoundation class cURLTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: - Live Tests func testGetStatusCode() { let curl = cURL() let testStatusCode = 200 try! curl.setOption(CURLOPT_VERBOSE, true) try! curl.setOption(CURLOPT_URL, "http://httpbin.org/status/\(testStatusCode)") try! curl.setOption(CURLOPT_TIMEOUT, 5) do { try curl.perform() } catch { XCTFail("Error executing cURL request: \(error)"); return } let responseCode: cURL.Long = try! curl.getInfo(CURLINFO_RESPONSE_CODE) XCTAssert(responseCode == testStatusCode, "\(responseCode) == \(testStatusCode)") } func testPostField() { let curl = cURL() let url = "http://httpbin.org/post" try! curl.setOption(CURLOPT_VERBOSE, true) try! curl.setOption(CURLOPT_URL, url) let effectiveURL = try! curl.getInfo(CURLINFO_EFFECTIVE_URL) as String XCTAssert(url == effectiveURL) try! curl.setOption(CURLOPT_TIMEOUT, 10) try! curl.setOption(CURLOPT_POST, true) let data: Data = [0x54, 0x65, 0x73, 0x74] // "Test" try! curl.setOption(CURLOPT_POSTFIELDS, data) try! curl.setOption(CURLOPT_POSTFIELDSIZE, data.count) do { try curl.perform() } catch { XCTFail("Error executing cURL request: \(error)"); return } let responseCode = try! curl.getInfo(CURLINFO_RESPONSE_CODE) as Int XCTAssert(responseCode == 200, "\(responseCode) == 200") } func testReadFunction() { let curl = cURL() try! curl.setOption(CURLOPT_VERBOSE, true) try! curl.setOption(CURLOPT_URL, "http://httpbin.org/post") try! curl.setOption(CURLOPT_TIMEOUT, 5) try! curl.setOption(CURLOPT_POST, true) let data: Data = [0x54, 0x65, 0x73, 0x74] // "Test" try! curl.setOption(CURLOPT_POSTFIELDSIZE, data.count) let dataStorage = cURL.ReadFunctionStorage(data: data) try! curl.setOption(CURLOPT_READDATA, unsafeBitCast(dataStorage, UnsafePointer<UInt8>.self)) let pointer = unsafeBitCast(curlReadFunction as curl_read_callback, UnsafePointer<UInt8>.self) try! curl.setOption(CURLOPT_READFUNCTION, pointer) do { try curl.perform() } catch { print("Error executing cURL request: \(error)") } let responseCode = try! curl.getInfo(CURLINFO_RESPONSE_CODE) as Int XCTAssert(responseCode == 200, "\(responseCode) == 200") } func testWriteFunction() { let curl = cURL() try! curl.setOption(CURLOPT_VERBOSE, true) let url = "http://httpbin.org/image/jpeg" try! curl.setOption(CURLOPT_URL, url) try! curl.setOption(CURLOPT_TIMEOUT, 60) let storage = cURL.WriteFunctionStorage() try! curl.setOption(CURLOPT_WRITEDATA, unsafeBitCast(storage, UnsafeMutablePointer<UInt8>.self)) try! curl.setOption(CURLOPT_WRITEFUNCTION, unsafeBitCast(cURL.WriteFunction, UnsafeMutablePointer<UInt8>.self)) do { try curl.perform() } catch { print("Error executing cURL request: \(error)") } let responseCode = try! curl.getInfo(CURLINFO_RESPONSE_CODE) as Int XCTAssert(responseCode == 200, "\(responseCode) == 200") XCTAssert(NSData(bytes: unsafeBitCast(storage.data, Data.self)) == NSData(contentsOfURL: NSURL(string: url)!)) } func testHeaderWriteFunction() { let curl = cURL() try! curl.setOption(CURLOPT_VERBOSE, true) let url = "http://httpbin.org" try! curl.setOption(CURLOPT_URL, url) try! curl.setOption(CURLOPT_TIMEOUT, 5) let storage = cURL.WriteFunctionStorage() try! curl.setOption(CURLOPT_HEADERDATA, unsafeBitCast(storage, UnsafeMutablePointer<UInt8>.self)) try! curl.setOption(CURLOPT_HEADERFUNCTION, unsafeBitCast(cURL.WriteFunction, UnsafeMutablePointer<UInt8>.self)) do { try curl.perform() } catch { print("Error executing cURL request: \(error)") } let responseCode = try! curl.getInfo(CURLINFO_RESPONSE_CODE) as Int XCTAssert(responseCode == 200, "\(responseCode) == 200") print("Header:\n\(String.fromCString(storage.data)!)") } func testSetHeaderOption() { var curl: cURL! = cURL() try! curl.setOption(CURLOPT_VERBOSE, true) let url = "http://httpbin.org/headers" try! curl.setOption(CURLOPT_URL, url) let header = "Header" let headerValue = "Value" try! curl.setOption(CURLOPT_HTTPHEADER, [header + ": " + headerValue]) let storage = cURL.WriteFunctionStorage() try! curl.setOption(CURLOPT_WRITEDATA, unsafeBitCast(storage, UnsafeMutablePointer<UInt8>.self)) try! curl.setOption(CURLOPT_WRITEFUNCTION, unsafeBitCast(curlWriteFunction as curl_write_callback, UnsafeMutablePointer<UInt8>.self)) do { try curl.perform() } catch { print("Error executing cURL request: \(error)") } let responseCode = try! curl.getInfo(CURLINFO_RESPONSE_CODE) as Int XCTAssert(responseCode == 200, "\(responseCode) == 200") guard let json = try! NSJSONSerialization.JSONObjectWithData(NSData(bytes: unsafeBitCast(storage.data, Data.self)), options: NSJSONReadingOptions()) as? [String: [String: String]] else { XCTFail("Invalid JSON response"); return } guard let headersJSON = json["headers"] else { XCTFail("Invalid JSON response: \(json)"); return } XCTAssert(headersJSON[header] == headerValue) // invoke deinit curl = nil } }
// // GroupEditViewController.swift // Spoint // // Created by kalyan on 25/04/18. // Copyright © 2018 Personal. All rights reserved. // import UIKit class UserSelectionObject: NSObject { var selected:Bool var userInfo:User init(selected:Bool, user:User) { self.selected = selected self.userInfo = user } } class GroupEditViewController: UIViewController, UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet var backButton:UIButton! var groupVc:GroupsViewController! var editList:GroupsInfo? { didSet{ if let users = editList?.ids { print(users) let filter = FireBaseContants.firebaseConstant.userList.filter {(users.contains($0.id))} filter.forEach({ (userinfo) in let follow = FollowUser(userinfo: userinfo, locationstatus: true, timelinestatus: true, notificationstatus: true, requeststatus: 2, messageStatus: true) let checkinuser = CheckinUser(selected: true, follower: follow) self.checkinUsers.append(checkinuser) }) } } } var checkinUsers = [CheckinUser]() @IBOutlet var tableview:UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableview.register(FriendsTableViewCell.self) self.tableview.allowsMultipleSelection = true self.showLoaderWithMessage(message: "Loading") let userIDs = self.checkinUsers.compactMap { (checkinfo) -> String? in return checkinfo.follower.userInfo.id } FireBaseContants.firebaseConstant.getFriendsObserver({ (user) in DispatchQueue.main.async { self.dismissLoader() if let userinfo = user?.follower.userInfo, !userIDs.contains(userinfo.id) { print(userIDs, userIDs.contains(userinfo.id), userinfo.id) self.checkinUsers.append(user!) } self.tableview.reloadData() } }) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = true self.navigationController?.interactivePopGestureRecognizer?.delegate = self } @IBAction func backButtonAction(){ self.navigationController?.popViewController(animated: true) } @IBAction func doneButtonAction() { let filterlist = checkinUsers.filter({ (user) -> Bool in return user.selected }) groupVc.selectedUsers(users: filterlist) self.navigationController?.popViewController(animated: true) } //MARK: Gestures Delegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool { return (otherGestureRecognizer is UIScreenEdgePanGestureRecognizer) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if checkinUsers.count == 0{ self.showEmptyMessage(message: "No data available", tableview: tableView) return 0 }else{ tableView.backgroundView = nil return checkinUsers.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FriendsTableViewCell") as! FriendsTableViewCell cell.titleLabel?.text = self.checkinUsers[indexPath.item].follower.userInfo.name.capitalized cell.imageview?.kf.setImage(with: self.checkinUsers[indexPath.item].follower.userInfo.profilePic) if self.checkinUsers[indexPath.item].selected { cell.checkmarkButton.isSelected = true }else{ cell.checkmarkButton.isSelected = false } /* self.checkinUsers[indexPath.item].selected = cell.checkmarkButton.isSelected ? true : false if cell.checkmarkButton.isSelected { cell.checkmarkButton.isSelected = true }else{ cell.checkmarkButton.isSelected = false } cell.accessoryType = cell.isSelected ? .checkmark : .none*/ cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCell = tableView.cellForRow(at: indexPath)! as! FriendsTableViewCell if selectedCell.checkmarkButton.isSelected == true { selectedCell.checkmarkButton.isSelected = false self.checkinUsers[indexPath.item].selected = false }else{ selectedCell.checkmarkButton.isSelected = true self.checkinUsers[indexPath.item].selected = true } tableView.reloadData() } /* func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let deselectedCell = tableView.cellForRow(at: indexPath)! as! FriendsTableViewCell deselectedCell.checkmarkButton.isSelected = false self.checkinUsers[indexPath.item].selected = false }*/ 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. } */ }
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 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 Swift project authors */ import Basic import PackageModel protocol Buildable { var targetName: String { get } var isTest: Bool { get } } extension Module: Buildable { var targetName: String { return "<\(name).module>" } } extension Product: Buildable { var isTest: Bool { if case .test = type { return true } return false } var targetName: String { switch type { case .library(.dynamic): return "<\(name).dylib>" case .test: return "<\(name).test>" case .library(.static): return "<\(name).a>" case .executable: return "<\(name).exe>" } } }
// // Colors.swift // Transactions // // Created by Thiago Santiago on 1/18/19. // Copyright © 2019 Thiago Santiago. All rights reserved. // import UIKit struct Colors { static let pink = UIColor(red: 198/255.0, green: 59/255.0, blue: 240/255.0, alpha: 1.0) static let blue = UIColor(red: 36/255.0, green: 45/255.0, blue: 236/255.0, alpha: 1.0) static let debitColor = UIColor.red static let creditColor = UIColor.blue }
// // Blockchain.swift // // // Created by Daniel Sanabria on 15/10/21. // import Foundation import Vapor final class Blockchain: Content { private (set) var blocks: [Block] = [] private (set) var smartContracts: [SmartContract] = [] init(genisBlock: Block) { addBlock(genisBlock) addSmartContracts() } private enum CodingKeys: CodingKey { case blocks } func addSmartContracts() { smartContracts.append(TransactionTypeSmartContract()) } func addBlock(_ block: Block) { if self.blocks.isEmpty { block.previousHash = "000000000000000" block.hash = generateHash(for: block) } self.smartContracts.forEach { contract in block.transactions.forEach { transaction in contract.apply(transaction: transaction) } } self.blocks.append(block) } func generateHash(for block: Block) -> String { var hash = block.key.sha1Hash() while(!hash.hasPrefix("00")) { block.nonce += 1 hash = block.key.sha1Hash() } return hash } func getNextBlock(transactions: [Transaction]) -> Block { let block = Block() transactions.forEach { transaction in block.addTransaction(transaction: transaction) } let previousBlock = getPreviousBlock() block.index = self.blocks.count block.previousHash = previousBlock.hash block.hash = generateHash(for: block) return block } func getPreviousBlock() -> Block { return self.blocks[self.blocks.count - 1] } }
// // GBTextView.swift // FloatingTextField // // Created by Apple on 25/10/18. // Copyright © 2018 Batth. All rights reserved. // import UIKit @IBDesignable public class GBFloatingTextView: UITextView { @IBInspectable public var isFloatingLabel: Bool = false{ didSet{ if isFloatingLabel{ self.placeholderLabel.isHidden = false self.addFloatingLabel() if constraintPlaceholderLabelTop != nil{ constraintPlaceholderLabelTop.constant = 15 } if self.text.count > 0{ self.refreshPlaceholder() } } } } @IBInspectable public var placeholder: String?{ didSet{ self.setPlaceholderLabel() #if swift(>=4.2) let UITextViewTextDidChange = UITextView.textDidChangeNotification let UITextViewTextBeginEditing = UITextView.textDidBeginEditingNotification let UITextViewTextEndEditing = UITextView.textDidEndEditingNotification #else let UITextViewTextDidChange = NSNotification.Name.UITextViewTextDidChange let UITextViewTextBeginEditing = NSNotification.Name.UITextViewTextDidBeginEditing let UITextViewTextEndEditing = NSNotification.Name.UITextViewTextDidEndEditing #endif NotificationCenter.default.addObserver(self, selector: #selector(self.refreshPlaceholder), name:UITextViewTextDidChange, object: self) NotificationCenter.default.addObserver(self, selector: #selector(self.beginEditing), name:UITextViewTextBeginEditing, object: self) NotificationCenter.default.addObserver(self, selector: #selector(self.textEndEditing), name:UITextViewTextEndEditing, object: self) } } @IBInspectable public var placeholderColor: UIColor? = .lightGray{ didSet{ placeholderLabel.textColor = placeholderColor if topPlaceholderColor == nil{ self.topPlaceholderColor = placeholderColor } } } @IBInspectable public var topPlaceholderColor: UIColor? = .lightGray{ didSet{ if self.selectedColor == nil{ self.selectedColor = topPlaceholderColor } } } @IBInspectable public var selectedColor: UIColor? @IBInspectable public var cornerRadius: CGFloat = 0{ didSet{ self.layer.cornerRadius = cornerRadius } } @IBInspectable public var borderColor: UIColor = .lightGray{ didSet{ self.layer.borderColor = borderColor.cgColor } } @IBInspectable public var borderWidth: CGFloat = 0{ didSet{ self.layer.borderWidth = borderWidth } } public init(frame: CGRect, superView: UIView) { super.init(frame: frame, textContainer: nil) superView.addSubview(self) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK:-  Private Properties private var constraintPlaceholderLabelTop: NSLayoutConstraint! var isSetupPlaceholder:Bool = false //MARK:-  Private Functions private lazy var placeholderLabel: UILabel = { let lbl = UILabel() lbl.translatesAutoresizingMaskIntoConstraints = false lbl.numberOfLines = 0 lbl.font = self.font return lbl }() private func setPlaceholderLabel(){ self.isSetupPlaceholder = true print(self.text) placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor ?? .lightGray placeholderLabel.textAlignment = self.textAlignment self.superview?.addSubview(placeholderLabel) placeholderLabel.font = self.font if self.font == nil{ placeholderLabel.font = UIFont.systemFont(ofSize: 14) } constraintPlaceholderLabelTop = placeholderLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 8) constraintPlaceholderLabelTop.isActive = true if isFloatingLabel{ constraintPlaceholderLabelTop.constant = 15 } placeholderLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 5).isActive = true placeholderLabel.widthAnchor.constraint(equalTo: self.widthAnchor, constant: -10).isActive = true if self.text.count > 0{ if !isFloatingLabel{ self.placeholderLabel.isHidden = true } self.refreshPlaceholder() } } private func addFloatingLabel(){ #if swift(>=4.2) self.textContainerInset = UIEdgeInsets(top: 15, left: 5, bottom: 15, right: 10) #else self.textContainerInset = UIEdgeInsets.init(top: 15, left: 5, bottom: 15, right: 10) #endif self.layoutIfNeeded() } //MARK:-  Notification @objc func refreshPlaceholder(){ if self.text.count > 0{ if isFloatingLabel{ if self.constraintPlaceholderLabelTop.constant != 0{ self.placeholderLabel.animate(font: UIFont(name: self.font?.fontName ?? "Helvetica-Neue", size: 12) ?? UIFont.boldSystemFont(ofSize: 12), duration: 0.3) self.constraintPlaceholderLabelTop.constant = 0 self.placeholderLabel.backgroundColor = .clear UIView.animate(withDuration: 0.3, animations: { self.superview?.layoutIfNeeded() }) DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { self.placeholderLabel.backgroundColor = self.backgroundColor if self.selectedColor == nil{ self.selectedColor = self.topPlaceholderColor } if self.isFirstResponder{ self.placeholderLabel.textColor = self.selectedColor }else{ self.placeholderLabel.textColor = self.topPlaceholderColor } } } }else{ self.placeholderLabel.isHidden = true } }else{ if isFloatingLabel{ self.placeholderLabel.animate(font: self.font ?? UIFont.systemFont(ofSize: 17), duration: 0.3) self.constraintPlaceholderLabelTop.constant = 15 self.placeholderLabel.backgroundColor = .clear UIView.animate(withDuration: 0.3) { self.superview?.layoutIfNeeded() self.placeholderLabel.textColor = self.placeholderColor } }else{ self.placeholderLabel.textColor = self.placeholderColor self.placeholderLabel.isHidden = false } } } @objc func beginEditing(){ if text.count > 0{ self.placeholderLabel.textColor = selectedColor } } @objc func textEndEditing(){ if text.count > 0{ self.placeholderLabel.textColor = topPlaceholderColor }else{ self.placeholderLabel.textColor = placeholderColor } } }
// // RestaurantMenuViewController.swift // AGLViperProject // // Created by Раис Аглиуллов on 01.10.2020. // Copyright (c) 2020 ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol RestaurantMenuDisplayLogic: class { func displayRestaurantMenuFetchedData(viewModel: RestaurantMenuModel.FetchRestaurantMenuData.ViewModel) func displayRestaurantMenuChangeControllerMode(viewModel: RestaurantMenuModel.ChangeControllerMode.ViewModel) func displayRestaurantMenuOpenDetails(viewModel: RestaurantMenuModel.OpenRestaurantMenuDetails.ViewModel) } class RestaurantMenuViewController: UIViewController { var interactor: RestaurantMenuBusinessLogic? var router: (NSObjectProtocol & RestaurantMenuRoutingLogic & RestaurantMenuDataPassing)? var mutableHomeScreenData: [HomeScreenData] = [] private var homeScreenData: [HomeScreenData] = [] private var mode: ControllerMode = .viewing private var displayedSections: [RestaurantMenuModel.DisplayedSection] = [] let collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() let size = UIScreen.main.bounds.size.width / 2 - 10 // layout.estimatedItemSize = CGSize(width: UIScreen.main.bounds.size.width / 2, height: UIScreen.main.bounds.size.height / 2) layout.itemSize = CGSize(width: size, height: size) // layout.sectionInset = UIEdgeInsets(top: 4.0, left: 4.0, bottom: 4.0, right: 4.0) let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.backgroundColor = UIColor.secondarySystemBackground collectionView.register(TitleCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: String(describing: TitleCollectionViewCell.self)) collectionView.register(DetailsCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: DetailsCollectionViewCell.self)) return collectionView }() private let activityIndicator: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView() indicator.translatesAutoresizingMaskIntoConstraints = false indicator.color = UIColor.blue indicator.startAnimating() return indicator }() // MARK: Object lifecycle override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } // MARK: Setup private func setup() { let viewController = self let interactor = RestaurantMenuInteractor() let presenter = RestaurantMenuPresenter() let router = RestaurantMenuRouter() viewController.interactor = interactor viewController.router = router interactor.presenter = presenter presenter.viewController = viewController router.viewController = viewController router.dataStore = interactor } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) collectionView.frame = view.bounds collectionView.delegate = self collectionView.dataSource = self titleTextAttribute() fetchOptions() } private func titleTextAttribute() { self.title = "Наше меню" navigationController?.navigationBar.titleTextAttributes = ColorHelper.shared.titleTextAttribute() navigationItem.setRightBarButton(UIBarButtonItem(image: UIImage(systemName: "square.and.arrow.down"), style: .done, target: self, action: #selector(openAndDataFromBasketVC)), animated: true) } @objc private func openAndDataFromBasketVC() { self.router?.routeToBasketVC() } private func fetchOptions() { let request = RestaurantMenuModel.FetchRestaurantMenuData.Request() interactor?.fetchRestaurantMenuData(request: request) } private func updateNavigationItem() { switch mode { case .viewing: navigationItem.setRightBarButton(nil, animated: true) case .editing:() case .updating: let rightItem = UIBarButtonItem(customView: activityIndicator) navigationItem.setRightBarButton(rightItem, animated: true) } } private func openRestaurantDetailsViewController(index: Int) { let request = RestaurantMenuModel.OpenRestaurantMenuDetails.Request(index: index) interactor?.openRestaurantMenuDetails(request: request) } } extension RestaurantMenuViewController: RestaurantMenuDisplayLogic { func displayRestaurantMenuFetchedData(viewModel: RestaurantMenuModel.FetchRestaurantMenuData.ViewModel) { self.displayedSections = viewModel.displayedSection collectionView.reloadData() } func displayRestaurantMenuChangeControllerMode(viewModel: RestaurantMenuModel.ChangeControllerMode.ViewModel) { mode = viewModel.mode updateNavigationItem() } func displayRestaurantMenuOpenDetails(viewModel: RestaurantMenuModel.OpenRestaurantMenuDetails.ViewModel) { self.router?.routeToRestaurantDetails(index: viewModel.index) } } extension RestaurantMenuViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { openRestaurantDetailsViewController(index: indexPath.item) collectionView.deselectItem(at: indexPath, animated: true) } } extension RestaurantMenuViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return displayedSections.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return displayedSections[section].cells.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let displayedSection = displayedSections[indexPath.section] let cellType = displayedSection.cells[indexPath.row].type switch cellType { case .description(let title, let imageName, let descriptionText, let price, let priceText): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: DetailsCollectionViewCell.self), for: indexPath) as! DetailsCollectionViewCell cell.setupValue(titleText: title, imageName: imageName, descriptionText: descriptionText,price: price, priceText: priceText) return cell } } } extension RestaurantMenuViewController: DetailsStructChange { func detailsValueDidChange(details: [HomeScreenData]?) { guard let details = details else { return } mutableHomeScreenData = details } } extension RestaurantMenuViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { if section == 0 { return UIEdgeInsets(top: 8.0, left: 4.0, bottom: 8.0, right: 4.0) } else { return UIEdgeInsets() } } } // Use for Unit tests extension RestaurantMenuViewController { func setSections(sections: [RestaurantMenuModel.DisplayedSection]) { self.displayedSections = sections self.collectionView.reloadData() } }
// // PrivateAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation import Alamofire open class PrivateAPI { /** * enum for parameter currency */ public enum Currency_privateAddToAddressBookGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter type */ public enum ModelType_privateAddToAddressBookGet: String { case transfer = "transfer" case withdrawal = "withdrawal" } /** Adds new entry to address book of given type - parameter currency: (query) The currency symbol - parameter type: (query) Address book type - parameter address: (query) Address in currency format, it must be in address book - parameter name: (query) Name of address book entry - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateAddToAddressBookGet(currency: Currency_privateAddToAddressBookGet, type: ModelType_privateAddToAddressBookGet, address: String, name: String, tfa: String? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateAddToAddressBookGetWithRequestBuilder(currency: currency, type: type, address: address, name: name, tfa: tfa).execute { (response, error) -> Void in completion(response?.body, error) } } /** Adds new entry to address book of given type - GET /private/add_to_address_book - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter type: (query) Address book type - parameter address: (query) Address in currency format, it must be in address book - parameter name: (query) Name of address book entry - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - returns: RequestBuilder<Any> */ open class func privateAddToAddressBookGetWithRequestBuilder(currency: Currency_privateAddToAddressBookGet, type: ModelType_privateAddToAddressBookGet, address: String, name: String, tfa: String? = nil) -> RequestBuilder<Any> { let path = "/private/add_to_address_book" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "type": type.rawValue, "address": address, "name": name, "tfa": tfa ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter type */ public enum ModelType_privateBuyGet: String { case limit = "limit" case stopLimit = "stop_limit" case market = "market" case stopMarket = "stop_market" } /** * enum for parameter timeInForce */ public enum TimeInForce_privateBuyGet: String { case goodTilCancelled = "good_til_cancelled" case fillOrKill = "fill_or_kill" case immediateOrCancel = "immediate_or_cancel" } /** * enum for parameter trigger */ public enum Trigger_privateBuyGet: String { case indexPrice = "index_price" case markPrice = "mark_price" case lastPrice = "last_price" } /** * enum for parameter advanced */ public enum Advanced_privateBuyGet: String { case usd = "usd" case implv = "implv" } /** Places a buy order for an instrument. - parameter instrumentName: (query) Instrument name - parameter amount: (query) It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH - parameter type: (query) The order type, default: &#x60;\&quot;limit\&quot;&#x60; (optional) - parameter label: (query) user defined label for the order (maximum 32 characters) (optional) - parameter price: (query) &lt;p&gt;The order price in base currency (Only for limit and stop_limit orders)&lt;/p&gt; &lt;p&gt;When adding order with advanced&#x3D;usd, the field price should be the option price value in USD.&lt;/p&gt; &lt;p&gt;When adding order with advanced&#x3D;implv, the field price should be a value of implied volatility in percentages. For example, price&#x3D;100, means implied volatility of 100%&lt;/p&gt; (optional) - parameter timeInForce: (query) &lt;p&gt;Specifies how long the order remains in effect. Default &#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&#x60;\&quot;good_til_cancelled\&quot;&#x60; - unfilled order remains in order book until cancelled&lt;/li&gt; &lt;li&gt;&#x60;\&quot;fill_or_kill\&quot;&#x60; - execute a transaction immediately and completely or not at all&lt;/li&gt; &lt;li&gt;&#x60;\&quot;immediate_or_cancel\&quot;&#x60; - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled&lt;/li&gt; &lt;/ul&gt; (optional, default to .good_til_cancelled) - parameter maxShow: (query) Maximum amount within an order to be shown to other customers, &#x60;0&#x60; for invisible order (optional, default to 1) - parameter postOnly: (query) &lt;p&gt;If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.&lt;/p&gt; &lt;p&gt;Only valid in combination with time_in_force&#x3D;&#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; (optional, default to true) - parameter reduceOnly: (query) If &#x60;true&#x60;, the order is considered reduce-only which is intended to only reduce a current position (optional, default to false) - parameter stopPrice: (query) Stop price, required for stop limit orders (Only for stop orders) (optional) - parameter trigger: (query) Defines trigger type, required for &#x60;\&quot;stop_limit\&quot;&#x60; order type (optional) - parameter advanced: (query) Advanced option order type. (Only for options) (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateBuyGet(instrumentName: String, amount: Double, type: ModelType_privateBuyGet? = nil, label: String? = nil, price: Double? = nil, timeInForce: TimeInForce_privateBuyGet? = nil, maxShow: Double? = nil, postOnly: Bool? = nil, reduceOnly: Bool? = nil, stopPrice: Double? = nil, trigger: Trigger_privateBuyGet? = nil, advanced: Advanced_privateBuyGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateBuyGetWithRequestBuilder(instrumentName: instrumentName, amount: amount, type: type, label: label, price: price, timeInForce: timeInForce, maxShow: maxShow, postOnly: postOnly, reduceOnly: reduceOnly, stopPrice: stopPrice, trigger: trigger, advanced: advanced).execute { (response, error) -> Void in completion(response?.body, error) } } /** Places a buy order for an instrument. - GET /private/buy - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter amount: (query) It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH - parameter type: (query) The order type, default: &#x60;\&quot;limit\&quot;&#x60; (optional) - parameter label: (query) user defined label for the order (maximum 32 characters) (optional) - parameter price: (query) &lt;p&gt;The order price in base currency (Only for limit and stop_limit orders)&lt;/p&gt; &lt;p&gt;When adding order with advanced&#x3D;usd, the field price should be the option price value in USD.&lt;/p&gt; &lt;p&gt;When adding order with advanced&#x3D;implv, the field price should be a value of implied volatility in percentages. For example, price&#x3D;100, means implied volatility of 100%&lt;/p&gt; (optional) - parameter timeInForce: (query) &lt;p&gt;Specifies how long the order remains in effect. Default &#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&#x60;\&quot;good_til_cancelled\&quot;&#x60; - unfilled order remains in order book until cancelled&lt;/li&gt; &lt;li&gt;&#x60;\&quot;fill_or_kill\&quot;&#x60; - execute a transaction immediately and completely or not at all&lt;/li&gt; &lt;li&gt;&#x60;\&quot;immediate_or_cancel\&quot;&#x60; - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled&lt;/li&gt; &lt;/ul&gt; (optional, default to .good_til_cancelled) - parameter maxShow: (query) Maximum amount within an order to be shown to other customers, &#x60;0&#x60; for invisible order (optional, default to 1) - parameter postOnly: (query) &lt;p&gt;If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.&lt;/p&gt; &lt;p&gt;Only valid in combination with time_in_force&#x3D;&#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; (optional, default to true) - parameter reduceOnly: (query) If &#x60;true&#x60;, the order is considered reduce-only which is intended to only reduce a current position (optional, default to false) - parameter stopPrice: (query) Stop price, required for stop limit orders (Only for stop orders) (optional) - parameter trigger: (query) Defines trigger type, required for &#x60;\&quot;stop_limit\&quot;&#x60; order type (optional) - parameter advanced: (query) Advanced option order type. (Only for options) (optional) - returns: RequestBuilder<Any> */ open class func privateBuyGetWithRequestBuilder(instrumentName: String, amount: Double, type: ModelType_privateBuyGet? = nil, label: String? = nil, price: Double? = nil, timeInForce: TimeInForce_privateBuyGet? = nil, maxShow: Double? = nil, postOnly: Bool? = nil, reduceOnly: Bool? = nil, stopPrice: Double? = nil, trigger: Trigger_privateBuyGet? = nil, advanced: Advanced_privateBuyGet? = nil) -> RequestBuilder<Any> { let path = "/private/buy" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "amount": amount, "type": type?.rawValue, "label": label, "price": price, "time_in_force": timeInForce?.rawValue, "max_show": maxShow, "post_only": postOnly, "reduce_only": reduceOnly, "stop_price": stopPrice, "trigger": trigger?.rawValue, "advanced": advanced?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateCancelAllByCurrencyGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter kind */ public enum Kind_privateCancelAllByCurrencyGet: String { case future = "future" case option = "option" } /** * enum for parameter type */ public enum ModelType_privateCancelAllByCurrencyGet: String { case all = "all" case limit = "limit" case stop = "stop" } /** Cancels all orders by currency, optionally filtered by instrument kind and/or order type. - parameter currency: (query) The currency symbol - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter type: (query) Order type - limit, stop or all, default - &#x60;all&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateCancelAllByCurrencyGet(currency: Currency_privateCancelAllByCurrencyGet, kind: Kind_privateCancelAllByCurrencyGet? = nil, type: ModelType_privateCancelAllByCurrencyGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateCancelAllByCurrencyGetWithRequestBuilder(currency: currency, kind: kind, type: type).execute { (response, error) -> Void in completion(response?.body, error) } } /** Cancels all orders by currency, optionally filtered by instrument kind and/or order type. - GET /private/cancel_all_by_currency - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter type: (query) Order type - limit, stop or all, default - &#x60;all&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateCancelAllByCurrencyGetWithRequestBuilder(currency: Currency_privateCancelAllByCurrencyGet, kind: Kind_privateCancelAllByCurrencyGet? = nil, type: ModelType_privateCancelAllByCurrencyGet? = nil) -> RequestBuilder<Any> { let path = "/private/cancel_all_by_currency" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "kind": kind?.rawValue, "type": type?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter type */ public enum ModelType_privateCancelAllByInstrumentGet: String { case all = "all" case limit = "limit" case stop = "stop" } /** Cancels all orders by instrument, optionally filtered by order type. - parameter instrumentName: (query) Instrument name - parameter type: (query) Order type - limit, stop or all, default - &#x60;all&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateCancelAllByInstrumentGet(instrumentName: String, type: ModelType_privateCancelAllByInstrumentGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateCancelAllByInstrumentGetWithRequestBuilder(instrumentName: instrumentName, type: type).execute { (response, error) -> Void in completion(response?.body, error) } } /** Cancels all orders by instrument, optionally filtered by order type. - GET /private/cancel_all_by_instrument - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter type: (query) Order type - limit, stop or all, default - &#x60;all&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateCancelAllByInstrumentGetWithRequestBuilder(instrumentName: String, type: ModelType_privateCancelAllByInstrumentGet? = nil) -> RequestBuilder<Any> { let path = "/private/cancel_all_by_instrument" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "type": type?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** This method cancels all users orders and stop orders within all currencies and instrument kinds. - parameter completion: completion handler to receive the data and the error objects */ open class func privateCancelAllGet(completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateCancelAllGetWithRequestBuilder().execute { (response, error) -> Void in completion(response?.body, error) } } /** This method cancels all users orders and stop orders within all currencies and instrument kinds. - GET /private/cancel_all - BASIC: - type: http - name: bearerAuth - returns: RequestBuilder<Any> */ open class func privateCancelAllGetWithRequestBuilder() -> RequestBuilder<Any> { let path = "/private/cancel_all" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Cancel an order, specified by order id - parameter orderId: (query) The order id - parameter completion: completion handler to receive the data and the error objects */ open class func privateCancelGet(orderId: String, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateCancelGetWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in completion(response?.body, error) } } /** Cancel an order, specified by order id - GET /private/cancel - BASIC: - type: http - name: bearerAuth - parameter orderId: (query) The order id - returns: RequestBuilder<Any> */ open class func privateCancelGetWithRequestBuilder(orderId: String) -> RequestBuilder<Any> { let path = "/private/cancel" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "order_id": orderId ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateCancelTransferByIdGet: String { case btc = "BTC" case eth = "ETH" } /** Cancel transfer - parameter currency: (query) The currency symbol - parameter id: (query) Id of transfer - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateCancelTransferByIdGet(currency: Currency_privateCancelTransferByIdGet, id: Int, tfa: String? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateCancelTransferByIdGetWithRequestBuilder(currency: currency, id: id, tfa: tfa).execute { (response, error) -> Void in completion(response?.body, error) } } /** Cancel transfer - GET /private/cancel_transfer_by_id - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter id: (query) Id of transfer - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - returns: RequestBuilder<Any> */ open class func privateCancelTransferByIdGetWithRequestBuilder(currency: Currency_privateCancelTransferByIdGet, id: Int, tfa: String? = nil) -> RequestBuilder<Any> { let path = "/private/cancel_transfer_by_id" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "id": id.encodeToJSON(), "tfa": tfa ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateCancelWithdrawalGet: String { case btc = "BTC" case eth = "ETH" } /** Cancels withdrawal request - parameter currency: (query) The currency symbol - parameter id: (query) The withdrawal id - parameter completion: completion handler to receive the data and the error objects */ open class func privateCancelWithdrawalGet(currency: Currency_privateCancelWithdrawalGet, id: Double, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateCancelWithdrawalGetWithRequestBuilder(currency: currency, id: id).execute { (response, error) -> Void in completion(response?.body, error) } } /** Cancels withdrawal request - GET /private/cancel_withdrawal - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter id: (query) The withdrawal id - returns: RequestBuilder<Any> */ open class func privateCancelWithdrawalGetWithRequestBuilder(currency: Currency_privateCancelWithdrawalGet, id: Double) -> RequestBuilder<Any> { let path = "/private/cancel_withdrawal" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "id": id ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Change the user name for a subaccount - parameter sid: (query) The user id for the subaccount - parameter name: (query) The new user name - parameter completion: completion handler to receive the data and the error objects */ open class func privateChangeSubaccountNameGet(sid: Int, name: String, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateChangeSubaccountNameGetWithRequestBuilder(sid: sid, name: name).execute { (response, error) -> Void in completion(response?.body, error) } } /** Change the user name for a subaccount - GET /private/change_subaccount_name - BASIC: - type: http - name: bearerAuth - parameter sid: (query) The user id for the subaccount - parameter name: (query) The new user name - returns: RequestBuilder<Any> */ open class func privateChangeSubaccountNameGetWithRequestBuilder(sid: Int, name: String) -> RequestBuilder<Any> { let path = "/private/change_subaccount_name" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "sid": sid.encodeToJSON(), "name": name ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter type */ public enum ModelType_privateClosePositionGet: String { case limit = "limit" case market = "market" } /** Makes closing position reduce only order . - parameter instrumentName: (query) Instrument name - parameter type: (query) The order type - parameter price: (query) Optional price for limit order. (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateClosePositionGet(instrumentName: String, type: ModelType_privateClosePositionGet, price: Double? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateClosePositionGetWithRequestBuilder(instrumentName: instrumentName, type: type, price: price).execute { (response, error) -> Void in completion(response?.body, error) } } /** Makes closing position reduce only order . - GET /private/close_position - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter type: (query) The order type - parameter price: (query) Optional price for limit order. (optional) - returns: RequestBuilder<Any> */ open class func privateClosePositionGetWithRequestBuilder(instrumentName: String, type: ModelType_privateClosePositionGet, price: Double? = nil) -> RequestBuilder<Any> { let path = "/private/close_position" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "type": type.rawValue, "price": price ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateCreateDepositAddressGet: String { case btc = "BTC" case eth = "ETH" } /** Creates deposit address in currency - parameter currency: (query) The currency symbol - parameter completion: completion handler to receive the data and the error objects */ open class func privateCreateDepositAddressGet(currency: Currency_privateCreateDepositAddressGet, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateCreateDepositAddressGetWithRequestBuilder(currency: currency).execute { (response, error) -> Void in completion(response?.body, error) } } /** Creates deposit address in currency - GET /private/create_deposit_address - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - returns: RequestBuilder<Any> */ open class func privateCreateDepositAddressGetWithRequestBuilder(currency: Currency_privateCreateDepositAddressGet) -> RequestBuilder<Any> { let path = "/private/create_deposit_address" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Create a new subaccount - parameter completion: completion handler to receive the data and the error objects */ open class func privateCreateSubaccountGet(completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateCreateSubaccountGetWithRequestBuilder().execute { (response, error) -> Void in completion(response?.body, error) } } /** Create a new subaccount - GET /private/create_subaccount - BASIC: - type: http - name: bearerAuth - returns: RequestBuilder<Any> */ open class func privateCreateSubaccountGetWithRequestBuilder() -> RequestBuilder<Any> { let path = "/private/create_subaccount" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Disable two factor authentication for a subaccount. - parameter sid: (query) The user id for the subaccount - parameter completion: completion handler to receive the data and the error objects */ open class func privateDisableTfaForSubaccountGet(sid: Int, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateDisableTfaForSubaccountGetWithRequestBuilder(sid: sid).execute { (response, error) -> Void in completion(response?.body, error) } } /** Disable two factor authentication for a subaccount. - GET /private/disable_tfa_for_subaccount - BASIC: - type: http - name: bearerAuth - parameter sid: (query) The user id for the subaccount - returns: RequestBuilder<Any> */ open class func privateDisableTfaForSubaccountGetWithRequestBuilder(sid: Int) -> RequestBuilder<Any> { let path = "/private/disable_tfa_for_subaccount" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "sid": sid.encodeToJSON() ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Disables TFA with one time recovery code - parameter password: (query) The password for the subaccount - parameter code: (query) One time recovery code - parameter completion: completion handler to receive the data and the error objects */ open class func privateDisableTfaWithRecoveryCodeGet(password: String, code: String, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateDisableTfaWithRecoveryCodeGetWithRequestBuilder(password: password, code: code).execute { (response, error) -> Void in completion(response?.body, error) } } /** Disables TFA with one time recovery code - GET /private/disable_tfa_with_recovery_code - BASIC: - type: http - name: bearerAuth - parameter password: (query) The password for the subaccount - parameter code: (query) One time recovery code - returns: RequestBuilder<Any> */ open class func privateDisableTfaWithRecoveryCodeGetWithRequestBuilder(password: String, code: String) -> RequestBuilder<Any> { let path = "/private/disable_tfa_with_recovery_code" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "password": password, "code": code ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter advanced */ public enum Advanced_privateEditGet: String { case usd = "usd" case implv = "implv" } /** Change price, amount and/or other properties of an order. - parameter orderId: (query) The order id - parameter amount: (query) It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH - parameter price: (query) &lt;p&gt;The order price in base currency.&lt;/p&gt; &lt;p&gt;When editing an option order with advanced&#x3D;usd, the field price should be the option price value in USD.&lt;/p&gt; &lt;p&gt;When editing an option order with advanced&#x3D;implv, the field price should be a value of implied volatility in percentages. For example, price&#x3D;100, means implied volatility of 100%&lt;/p&gt; - parameter postOnly: (query) &lt;p&gt;If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.&lt;/p&gt; &lt;p&gt;Only valid in combination with time_in_force&#x3D;&#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; (optional, default to true) - parameter advanced: (query) Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) (optional) - parameter stopPrice: (query) Stop price, required for stop limit orders (Only for stop orders) (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateEditGet(orderId: String, amount: Double, price: Double, postOnly: Bool? = nil, advanced: Advanced_privateEditGet? = nil, stopPrice: Double? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateEditGetWithRequestBuilder(orderId: orderId, amount: amount, price: price, postOnly: postOnly, advanced: advanced, stopPrice: stopPrice).execute { (response, error) -> Void in completion(response?.body, error) } } /** Change price, amount and/or other properties of an order. - GET /private/edit - BASIC: - type: http - name: bearerAuth - parameter orderId: (query) The order id - parameter amount: (query) It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH - parameter price: (query) &lt;p&gt;The order price in base currency.&lt;/p&gt; &lt;p&gt;When editing an option order with advanced&#x3D;usd, the field price should be the option price value in USD.&lt;/p&gt; &lt;p&gt;When editing an option order with advanced&#x3D;implv, the field price should be a value of implied volatility in percentages. For example, price&#x3D;100, means implied volatility of 100%&lt;/p&gt; - parameter postOnly: (query) &lt;p&gt;If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.&lt;/p&gt; &lt;p&gt;Only valid in combination with time_in_force&#x3D;&#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; (optional, default to true) - parameter advanced: (query) Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) (optional) - parameter stopPrice: (query) Stop price, required for stop limit orders (Only for stop orders) (optional) - returns: RequestBuilder<Any> */ open class func privateEditGetWithRequestBuilder(orderId: String, amount: Double, price: Double, postOnly: Bool? = nil, advanced: Advanced_privateEditGet? = nil, stopPrice: Double? = nil) -> RequestBuilder<Any> { let path = "/private/edit" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "order_id": orderId, "amount": amount, "price": price, "post_only": postOnly, "advanced": advanced?.rawValue, "stop_price": stopPrice ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetAccountSummaryGet: String { case btc = "BTC" case eth = "ETH" } /** Retrieves user account summary. - parameter currency: (query) The currency symbol - parameter extended: (query) Include additional fields (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetAccountSummaryGet(currency: Currency_privateGetAccountSummaryGet, extended: Bool? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetAccountSummaryGetWithRequestBuilder(currency: currency, extended: extended).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves user account summary. - GET /private/get_account_summary - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter extended: (query) Include additional fields (optional) - returns: RequestBuilder<Any> */ open class func privateGetAccountSummaryGetWithRequestBuilder(currency: Currency_privateGetAccountSummaryGet, extended: Bool? = nil) -> RequestBuilder<Any> { let path = "/private/get_account_summary" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "extended": extended ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetAddressBookGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter type */ public enum ModelType_privateGetAddressBookGet: String { case transfer = "transfer" case withdrawal = "withdrawal" } /** Retrieves address book of given type - parameter currency: (query) The currency symbol - parameter type: (query) Address book type - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetAddressBookGet(currency: Currency_privateGetAddressBookGet, type: ModelType_privateGetAddressBookGet, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetAddressBookGetWithRequestBuilder(currency: currency, type: type).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves address book of given type - GET /private/get_address_book - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter type: (query) Address book type - returns: RequestBuilder<Any> */ open class func privateGetAddressBookGetWithRequestBuilder(currency: Currency_privateGetAddressBookGet, type: ModelType_privateGetAddressBookGet) -> RequestBuilder<Any> { let path = "/private/get_address_book" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "type": type.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetCurrentDepositAddressGet: String { case btc = "BTC" case eth = "ETH" } /** Retrieve deposit address for currency - parameter currency: (query) The currency symbol - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetCurrentDepositAddressGet(currency: Currency_privateGetCurrentDepositAddressGet, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetCurrentDepositAddressGetWithRequestBuilder(currency: currency).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve deposit address for currency - GET /private/get_current_deposit_address - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - returns: RequestBuilder<Any> */ open class func privateGetCurrentDepositAddressGetWithRequestBuilder(currency: Currency_privateGetCurrentDepositAddressGet) -> RequestBuilder<Any> { let path = "/private/get_current_deposit_address" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetDepositsGet: String { case btc = "BTC" case eth = "ETH" } /** Retrieve the latest users deposits - parameter currency: (query) The currency symbol - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetDepositsGet(currency: Currency_privateGetDepositsGet, count: Int? = nil, offset: Int? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetDepositsGetWithRequestBuilder(currency: currency, count: count, offset: offset).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve the latest users deposits - GET /private/get_deposits - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateGetDepositsGetWithRequestBuilder(currency: Currency_privateGetDepositsGet, count: Int? = nil, offset: Int? = nil) -> RequestBuilder<Any> { let path = "/private/get_deposits" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "count": count?.encodeToJSON(), "offset": offset?.encodeToJSON() ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Retrieves the language to be used for emails. - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetEmailLanguageGet(completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetEmailLanguageGetWithRequestBuilder().execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves the language to be used for emails. - GET /private/get_email_language - BASIC: - type: http - name: bearerAuth - returns: RequestBuilder<Any> */ open class func privateGetEmailLanguageGetWithRequestBuilder() -> RequestBuilder<Any> { let path = "/private/get_email_language" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Get margins for given instrument, amount and price. - parameter instrumentName: (query) Instrument name - parameter amount: (query) Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. - parameter price: (query) Price - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetMarginsGet(instrumentName: String, amount: Double, price: Double, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetMarginsGetWithRequestBuilder(instrumentName: instrumentName, amount: amount, price: price).execute { (response, error) -> Void in completion(response?.body, error) } } /** Get margins for given instrument, amount and price. - GET /private/get_margins - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter amount: (query) Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. - parameter price: (query) Price - returns: RequestBuilder<Any> */ open class func privateGetMarginsGetWithRequestBuilder(instrumentName: String, amount: Double, price: Double) -> RequestBuilder<Any> { let path = "/private/get_margins" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "amount": amount, "price": price ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Retrieves announcements that have not been marked read by the user. - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetNewAnnouncementsGet(completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetNewAnnouncementsGetWithRequestBuilder().execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves announcements that have not been marked read by the user. - GET /private/get_new_announcements - BASIC: - type: http - name: bearerAuth - returns: RequestBuilder<Any> */ open class func privateGetNewAnnouncementsGetWithRequestBuilder() -> RequestBuilder<Any> { let path = "/private/get_new_announcements" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetOpenOrdersByCurrencyGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter kind */ public enum Kind_privateGetOpenOrdersByCurrencyGet: String { case future = "future" case option = "option" } /** * enum for parameter type */ public enum ModelType_privateGetOpenOrdersByCurrencyGet: String { case all = "all" case limit = "limit" case stopAll = "stop_all" case stopLimit = "stop_limit" case stopMarket = "stop_market" } /** Retrieves list of user's open orders. - parameter currency: (query) The currency symbol - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter type: (query) Order type, default - &#x60;all&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetOpenOrdersByCurrencyGet(currency: Currency_privateGetOpenOrdersByCurrencyGet, kind: Kind_privateGetOpenOrdersByCurrencyGet? = nil, type: ModelType_privateGetOpenOrdersByCurrencyGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetOpenOrdersByCurrencyGetWithRequestBuilder(currency: currency, kind: kind, type: type).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves list of user's open orders. - GET /private/get_open_orders_by_currency - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter type: (query) Order type, default - &#x60;all&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateGetOpenOrdersByCurrencyGetWithRequestBuilder(currency: Currency_privateGetOpenOrdersByCurrencyGet, kind: Kind_privateGetOpenOrdersByCurrencyGet? = nil, type: ModelType_privateGetOpenOrdersByCurrencyGet? = nil) -> RequestBuilder<Any> { let path = "/private/get_open_orders_by_currency" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "kind": kind?.rawValue, "type": type?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter type */ public enum ModelType_privateGetOpenOrdersByInstrumentGet: String { case all = "all" case limit = "limit" case stopAll = "stop_all" case stopLimit = "stop_limit" case stopMarket = "stop_market" } /** Retrieves list of user's open orders within given Instrument. - parameter instrumentName: (query) Instrument name - parameter type: (query) Order type, default - &#x60;all&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetOpenOrdersByInstrumentGet(instrumentName: String, type: ModelType_privateGetOpenOrdersByInstrumentGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetOpenOrdersByInstrumentGetWithRequestBuilder(instrumentName: instrumentName, type: type).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves list of user's open orders within given Instrument. - GET /private/get_open_orders_by_instrument - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter type: (query) Order type, default - &#x60;all&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateGetOpenOrdersByInstrumentGetWithRequestBuilder(instrumentName: String, type: ModelType_privateGetOpenOrdersByInstrumentGet? = nil) -> RequestBuilder<Any> { let path = "/private/get_open_orders_by_instrument" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "type": type?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetOrderHistoryByCurrencyGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter kind */ public enum Kind_privateGetOrderHistoryByCurrencyGet: String { case future = "future" case option = "option" } /** Retrieves history of orders that have been partially or fully filled. - parameter currency: (query) The currency symbol - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter count: (query) Number of requested items, default - &#x60;20&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - parameter includeOld: (query) Include in result orders older than 2 days, default - &#x60;false&#x60; (optional) - parameter includeUnfilled: (query) Include in result fully unfilled closed orders, default - &#x60;false&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetOrderHistoryByCurrencyGet(currency: Currency_privateGetOrderHistoryByCurrencyGet, kind: Kind_privateGetOrderHistoryByCurrencyGet? = nil, count: Int? = nil, offset: Int? = nil, includeOld: Bool? = nil, includeUnfilled: Bool? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetOrderHistoryByCurrencyGetWithRequestBuilder(currency: currency, kind: kind, count: count, offset: offset, includeOld: includeOld, includeUnfilled: includeUnfilled).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves history of orders that have been partially or fully filled. - GET /private/get_order_history_by_currency - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter count: (query) Number of requested items, default - &#x60;20&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - parameter includeOld: (query) Include in result orders older than 2 days, default - &#x60;false&#x60; (optional) - parameter includeUnfilled: (query) Include in result fully unfilled closed orders, default - &#x60;false&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateGetOrderHistoryByCurrencyGetWithRequestBuilder(currency: Currency_privateGetOrderHistoryByCurrencyGet, kind: Kind_privateGetOrderHistoryByCurrencyGet? = nil, count: Int? = nil, offset: Int? = nil, includeOld: Bool? = nil, includeUnfilled: Bool? = nil) -> RequestBuilder<Any> { let path = "/private/get_order_history_by_currency" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "kind": kind?.rawValue, "count": count?.encodeToJSON(), "offset": offset?.encodeToJSON(), "include_old": includeOld, "include_unfilled": includeUnfilled ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Retrieves history of orders that have been partially or fully filled. - parameter instrumentName: (query) Instrument name - parameter count: (query) Number of requested items, default - &#x60;20&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - parameter includeOld: (query) Include in result orders older than 2 days, default - &#x60;false&#x60; (optional) - parameter includeUnfilled: (query) Include in result fully unfilled closed orders, default - &#x60;false&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetOrderHistoryByInstrumentGet(instrumentName: String, count: Int? = nil, offset: Int? = nil, includeOld: Bool? = nil, includeUnfilled: Bool? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetOrderHistoryByInstrumentGetWithRequestBuilder(instrumentName: instrumentName, count: count, offset: offset, includeOld: includeOld, includeUnfilled: includeUnfilled).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves history of orders that have been partially or fully filled. - GET /private/get_order_history_by_instrument - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter count: (query) Number of requested items, default - &#x60;20&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - parameter includeOld: (query) Include in result orders older than 2 days, default - &#x60;false&#x60; (optional) - parameter includeUnfilled: (query) Include in result fully unfilled closed orders, default - &#x60;false&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateGetOrderHistoryByInstrumentGetWithRequestBuilder(instrumentName: String, count: Int? = nil, offset: Int? = nil, includeOld: Bool? = nil, includeUnfilled: Bool? = nil) -> RequestBuilder<Any> { let path = "/private/get_order_history_by_instrument" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "count": count?.encodeToJSON(), "offset": offset?.encodeToJSON(), "include_old": includeOld, "include_unfilled": includeUnfilled ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Retrieves initial margins of given orders - parameter ids: (query) Ids of orders - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetOrderMarginByIdsGet(ids: [String], completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetOrderMarginByIdsGetWithRequestBuilder(ids: ids).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves initial margins of given orders - GET /private/get_order_margin_by_ids - BASIC: - type: http - name: bearerAuth - parameter ids: (query) Ids of orders - returns: RequestBuilder<Any> */ open class func privateGetOrderMarginByIdsGetWithRequestBuilder(ids: [String]) -> RequestBuilder<Any> { let path = "/private/get_order_margin_by_ids" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "ids": ids ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Retrieve the current state of an order. - parameter orderId: (query) The order id - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetOrderStateGet(orderId: String, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetOrderStateGetWithRequestBuilder(orderId: orderId).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve the current state of an order. - GET /private/get_order_state - BASIC: - type: http - name: bearerAuth - parameter orderId: (query) The order id - returns: RequestBuilder<Any> */ open class func privateGetOrderStateGetWithRequestBuilder(orderId: String) -> RequestBuilder<Any> { let path = "/private/get_order_state" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "order_id": orderId ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Retrieve user position. - parameter instrumentName: (query) Instrument name - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetPositionGet(instrumentName: String, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetPositionGetWithRequestBuilder(instrumentName: instrumentName).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve user position. - GET /private/get_position - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - returns: RequestBuilder<Any> */ open class func privateGetPositionGetWithRequestBuilder(instrumentName: String) -> RequestBuilder<Any> { let path = "/private/get_position" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetPositionsGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter kind */ public enum Kind_privateGetPositionsGet: String { case future = "future" case option = "option" } /** Retrieve user positions. - parameter currency: (query) - parameter kind: (query) Kind filter on positions (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetPositionsGet(currency: Currency_privateGetPositionsGet, kind: Kind_privateGetPositionsGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetPositionsGetWithRequestBuilder(currency: currency, kind: kind).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve user positions. - GET /private/get_positions - BASIC: - type: http - name: bearerAuth - parameter currency: (query) - parameter kind: (query) Kind filter on positions (optional) - returns: RequestBuilder<Any> */ open class func privateGetPositionsGetWithRequestBuilder(currency: Currency_privateGetPositionsGet, kind: Kind_privateGetPositionsGet? = nil) -> RequestBuilder<Any> { let path = "/private/get_positions" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "kind": kind?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetSettlementHistoryByCurrencyGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter type */ public enum ModelType_privateGetSettlementHistoryByCurrencyGet: String { case settlement = "settlement" case delivery = "delivery" case bankruptcy = "bankruptcy" } /** Retrieves settlement, delivery and bankruptcy events that have affected your account. - parameter currency: (query) The currency symbol - parameter type: (query) Settlement type (optional) - parameter count: (query) Number of requested items, default - &#x60;20&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetSettlementHistoryByCurrencyGet(currency: Currency_privateGetSettlementHistoryByCurrencyGet, type: ModelType_privateGetSettlementHistoryByCurrencyGet? = nil, count: Int? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetSettlementHistoryByCurrencyGetWithRequestBuilder(currency: currency, type: type, count: count).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves settlement, delivery and bankruptcy events that have affected your account. - GET /private/get_settlement_history_by_currency - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter type: (query) Settlement type (optional) - parameter count: (query) Number of requested items, default - &#x60;20&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateGetSettlementHistoryByCurrencyGetWithRequestBuilder(currency: Currency_privateGetSettlementHistoryByCurrencyGet, type: ModelType_privateGetSettlementHistoryByCurrencyGet? = nil, count: Int? = nil) -> RequestBuilder<Any> { let path = "/private/get_settlement_history_by_currency" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "type": type?.rawValue, "count": count?.encodeToJSON() ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter type */ public enum ModelType_privateGetSettlementHistoryByInstrumentGet: String { case settlement = "settlement" case delivery = "delivery" case bankruptcy = "bankruptcy" } /** Retrieves public settlement, delivery and bankruptcy events filtered by instrument name - parameter instrumentName: (query) Instrument name - parameter type: (query) Settlement type (optional) - parameter count: (query) Number of requested items, default - &#x60;20&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetSettlementHistoryByInstrumentGet(instrumentName: String, type: ModelType_privateGetSettlementHistoryByInstrumentGet? = nil, count: Int? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetSettlementHistoryByInstrumentGetWithRequestBuilder(instrumentName: instrumentName, type: type, count: count).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieves public settlement, delivery and bankruptcy events filtered by instrument name - GET /private/get_settlement_history_by_instrument - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter type: (query) Settlement type (optional) - parameter count: (query) Number of requested items, default - &#x60;20&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateGetSettlementHistoryByInstrumentGetWithRequestBuilder(instrumentName: String, type: ModelType_privateGetSettlementHistoryByInstrumentGet? = nil, count: Int? = nil) -> RequestBuilder<Any> { let path = "/private/get_settlement_history_by_instrument" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "type": type?.rawValue, "count": count?.encodeToJSON() ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Get information about subaccounts - parameter withPortfolio: (query) (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetSubaccountsGet(withPortfolio: Bool? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetSubaccountsGetWithRequestBuilder(withPortfolio: withPortfolio).execute { (response, error) -> Void in completion(response?.body, error) } } /** Get information about subaccounts - GET /private/get_subaccounts - BASIC: - type: http - name: bearerAuth - parameter withPortfolio: (query) (optional) - returns: RequestBuilder<Any> */ open class func privateGetSubaccountsGetWithRequestBuilder(withPortfolio: Bool? = nil) -> RequestBuilder<Any> { let path = "/private/get_subaccounts" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "with_portfolio": withPortfolio ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetTransfersGet: String { case btc = "BTC" case eth = "ETH" } /** Adds new entry to address book of given type - parameter currency: (query) The currency symbol - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetTransfersGet(currency: Currency_privateGetTransfersGet, count: Int? = nil, offset: Int? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetTransfersGetWithRequestBuilder(currency: currency, count: count, offset: offset).execute { (response, error) -> Void in completion(response?.body, error) } } /** Adds new entry to address book of given type - GET /private/get_transfers - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateGetTransfersGetWithRequestBuilder(currency: Currency_privateGetTransfersGet, count: Int? = nil, offset: Int? = nil) -> RequestBuilder<Any> { let path = "/private/get_transfers" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "count": count?.encodeToJSON(), "offset": offset?.encodeToJSON() ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetUserTradesByCurrencyAndTimeGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter kind */ public enum Kind_privateGetUserTradesByCurrencyAndTimeGet: String { case future = "future" case option = "option" } /** * enum for parameter sorting */ public enum Sorting_privateGetUserTradesByCurrencyAndTimeGet: String { case asc = "asc" case desc = "desc" case _default = "default" } /** Retrieve the latest user trades that have occurred for instruments in a specific currency symbol and within given time range. - parameter currency: (query) The currency symbol - parameter startTimestamp: (query) The earliest timestamp to return result for - parameter endTimestamp: (query) The most recent timestamp to return result for - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter includeOld: (query) Include trades older than 7 days, default - &#x60;false&#x60; (optional) - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetUserTradesByCurrencyAndTimeGet(currency: Currency_privateGetUserTradesByCurrencyAndTimeGet, startTimestamp: Int, endTimestamp: Int, kind: Kind_privateGetUserTradesByCurrencyAndTimeGet? = nil, count: Int? = nil, includeOld: Bool? = nil, sorting: Sorting_privateGetUserTradesByCurrencyAndTimeGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetUserTradesByCurrencyAndTimeGetWithRequestBuilder(currency: currency, startTimestamp: startTimestamp, endTimestamp: endTimestamp, kind: kind, count: count, includeOld: includeOld, sorting: sorting).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve the latest user trades that have occurred for instruments in a specific currency symbol and within given time range. - GET /private/get_user_trades_by_currency_and_time - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter startTimestamp: (query) The earliest timestamp to return result for - parameter endTimestamp: (query) The most recent timestamp to return result for - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter includeOld: (query) Include trades older than 7 days, default - &#x60;false&#x60; (optional) - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - returns: RequestBuilder<Any> */ open class func privateGetUserTradesByCurrencyAndTimeGetWithRequestBuilder(currency: Currency_privateGetUserTradesByCurrencyAndTimeGet, startTimestamp: Int, endTimestamp: Int, kind: Kind_privateGetUserTradesByCurrencyAndTimeGet? = nil, count: Int? = nil, includeOld: Bool? = nil, sorting: Sorting_privateGetUserTradesByCurrencyAndTimeGet? = nil) -> RequestBuilder<Any> { let path = "/private/get_user_trades_by_currency_and_time" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "kind": kind?.rawValue, "start_timestamp": startTimestamp.encodeToJSON(), "end_timestamp": endTimestamp.encodeToJSON(), "count": count?.encodeToJSON(), "include_old": includeOld, "sorting": sorting?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetUserTradesByCurrencyGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter kind */ public enum Kind_privateGetUserTradesByCurrencyGet: String { case future = "future" case option = "option" } /** * enum for parameter sorting */ public enum Sorting_privateGetUserTradesByCurrencyGet: String { case asc = "asc" case desc = "desc" case _default = "default" } /** Retrieve the latest user trades that have occurred for instruments in a specific currency symbol. - parameter currency: (query) The currency symbol - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter startId: (query) The ID number of the first trade to be returned (optional) - parameter endId: (query) The ID number of the last trade to be returned (optional) - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter includeOld: (query) Include trades older than 7 days, default - &#x60;false&#x60; (optional) - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetUserTradesByCurrencyGet(currency: Currency_privateGetUserTradesByCurrencyGet, kind: Kind_privateGetUserTradesByCurrencyGet? = nil, startId: String? = nil, endId: String? = nil, count: Int? = nil, includeOld: Bool? = nil, sorting: Sorting_privateGetUserTradesByCurrencyGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetUserTradesByCurrencyGetWithRequestBuilder(currency: currency, kind: kind, startId: startId, endId: endId, count: count, includeOld: includeOld, sorting: sorting).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve the latest user trades that have occurred for instruments in a specific currency symbol. - GET /private/get_user_trades_by_currency - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter kind: (query) Instrument kind, if not provided instruments of all kinds are considered (optional) - parameter startId: (query) The ID number of the first trade to be returned (optional) - parameter endId: (query) The ID number of the last trade to be returned (optional) - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter includeOld: (query) Include trades older than 7 days, default - &#x60;false&#x60; (optional) - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - returns: RequestBuilder<Any> */ open class func privateGetUserTradesByCurrencyGetWithRequestBuilder(currency: Currency_privateGetUserTradesByCurrencyGet, kind: Kind_privateGetUserTradesByCurrencyGet? = nil, startId: String? = nil, endId: String? = nil, count: Int? = nil, includeOld: Bool? = nil, sorting: Sorting_privateGetUserTradesByCurrencyGet? = nil) -> RequestBuilder<Any> { let path = "/private/get_user_trades_by_currency" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "kind": kind?.rawValue, "start_id": startId, "end_id": endId, "count": count?.encodeToJSON(), "include_old": includeOld, "sorting": sorting?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter sorting */ public enum Sorting_privateGetUserTradesByInstrumentAndTimeGet: String { case asc = "asc" case desc = "desc" case _default = "default" } /** Retrieve the latest user trades that have occurred for a specific instrument and within given time range. - parameter instrumentName: (query) Instrument name - parameter startTimestamp: (query) The earliest timestamp to return result for - parameter endTimestamp: (query) The most recent timestamp to return result for - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter includeOld: (query) Include trades older than 7 days, default - &#x60;false&#x60; (optional) - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetUserTradesByInstrumentAndTimeGet(instrumentName: String, startTimestamp: Int, endTimestamp: Int, count: Int? = nil, includeOld: Bool? = nil, sorting: Sorting_privateGetUserTradesByInstrumentAndTimeGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetUserTradesByInstrumentAndTimeGetWithRequestBuilder(instrumentName: instrumentName, startTimestamp: startTimestamp, endTimestamp: endTimestamp, count: count, includeOld: includeOld, sorting: sorting).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve the latest user trades that have occurred for a specific instrument and within given time range. - GET /private/get_user_trades_by_instrument_and_time - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter startTimestamp: (query) The earliest timestamp to return result for - parameter endTimestamp: (query) The most recent timestamp to return result for - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter includeOld: (query) Include trades older than 7 days, default - &#x60;false&#x60; (optional) - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - returns: RequestBuilder<Any> */ open class func privateGetUserTradesByInstrumentAndTimeGetWithRequestBuilder(instrumentName: String, startTimestamp: Int, endTimestamp: Int, count: Int? = nil, includeOld: Bool? = nil, sorting: Sorting_privateGetUserTradesByInstrumentAndTimeGet? = nil) -> RequestBuilder<Any> { let path = "/private/get_user_trades_by_instrument_and_time" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "start_timestamp": startTimestamp.encodeToJSON(), "end_timestamp": endTimestamp.encodeToJSON(), "count": count?.encodeToJSON(), "include_old": includeOld, "sorting": sorting?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter sorting */ public enum Sorting_privateGetUserTradesByInstrumentGet: String { case asc = "asc" case desc = "desc" case _default = "default" } /** Retrieve the latest user trades that have occurred for a specific instrument. - parameter instrumentName: (query) Instrument name - parameter startSeq: (query) The sequence number of the first trade to be returned (optional) - parameter endSeq: (query) The sequence number of the last trade to be returned (optional) - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter includeOld: (query) Include trades older than 7 days, default - &#x60;false&#x60; (optional) - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetUserTradesByInstrumentGet(instrumentName: String, startSeq: Int? = nil, endSeq: Int? = nil, count: Int? = nil, includeOld: Bool? = nil, sorting: Sorting_privateGetUserTradesByInstrumentGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetUserTradesByInstrumentGetWithRequestBuilder(instrumentName: instrumentName, startSeq: startSeq, endSeq: endSeq, count: count, includeOld: includeOld, sorting: sorting).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve the latest user trades that have occurred for a specific instrument. - GET /private/get_user_trades_by_instrument - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter startSeq: (query) The sequence number of the first trade to be returned (optional) - parameter endSeq: (query) The sequence number of the last trade to be returned (optional) - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter includeOld: (query) Include trades older than 7 days, default - &#x60;false&#x60; (optional) - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - returns: RequestBuilder<Any> */ open class func privateGetUserTradesByInstrumentGetWithRequestBuilder(instrumentName: String, startSeq: Int? = nil, endSeq: Int? = nil, count: Int? = nil, includeOld: Bool? = nil, sorting: Sorting_privateGetUserTradesByInstrumentGet? = nil) -> RequestBuilder<Any> { let path = "/private/get_user_trades_by_instrument" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "start_seq": startSeq?.encodeToJSON(), "end_seq": endSeq?.encodeToJSON(), "count": count?.encodeToJSON(), "include_old": includeOld, "sorting": sorting?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter sorting */ public enum Sorting_privateGetUserTradesByOrderGet: String { case asc = "asc" case desc = "desc" case _default = "default" } /** Retrieve the list of user trades that was created for given order - parameter orderId: (query) The order id - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetUserTradesByOrderGet(orderId: String, sorting: Sorting_privateGetUserTradesByOrderGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetUserTradesByOrderGetWithRequestBuilder(orderId: orderId, sorting: sorting).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve the list of user trades that was created for given order - GET /private/get_user_trades_by_order - BASIC: - type: http - name: bearerAuth - parameter orderId: (query) The order id - parameter sorting: (query) Direction of results sorting (&#x60;default&#x60; value means no sorting, results will be returned in order in which they left the database) (optional) - returns: RequestBuilder<Any> */ open class func privateGetUserTradesByOrderGetWithRequestBuilder(orderId: String, sorting: Sorting_privateGetUserTradesByOrderGet? = nil) -> RequestBuilder<Any> { let path = "/private/get_user_trades_by_order" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "order_id": orderId, "sorting": sorting?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateGetWithdrawalsGet: String { case btc = "BTC" case eth = "ETH" } /** Retrieve the latest users withdrawals - parameter currency: (query) The currency symbol - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateGetWithdrawalsGet(currency: Currency_privateGetWithdrawalsGet, count: Int? = nil, offset: Int? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateGetWithdrawalsGetWithRequestBuilder(currency: currency, count: count, offset: offset).execute { (response, error) -> Void in completion(response?.body, error) } } /** Retrieve the latest users withdrawals - GET /private/get_withdrawals - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter count: (query) Number of requested items, default - &#x60;10&#x60; (optional) - parameter offset: (query) The offset for pagination, default - &#x60;0&#x60; (optional) - returns: RequestBuilder<Any> */ open class func privateGetWithdrawalsGetWithRequestBuilder(currency: Currency_privateGetWithdrawalsGet, count: Int? = nil, offset: Int? = nil) -> RequestBuilder<Any> { let path = "/private/get_withdrawals" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "count": count?.encodeToJSON(), "offset": offset?.encodeToJSON() ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateRemoveFromAddressBookGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter type */ public enum ModelType_privateRemoveFromAddressBookGet: String { case transfer = "transfer" case withdrawal = "withdrawal" } /** Adds new entry to address book of given type - parameter currency: (query) The currency symbol - parameter type: (query) Address book type - parameter address: (query) Address in currency format, it must be in address book - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateRemoveFromAddressBookGet(currency: Currency_privateRemoveFromAddressBookGet, type: ModelType_privateRemoveFromAddressBookGet, address: String, tfa: String? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateRemoveFromAddressBookGetWithRequestBuilder(currency: currency, type: type, address: address, tfa: tfa).execute { (response, error) -> Void in completion(response?.body, error) } } /** Adds new entry to address book of given type - GET /private/remove_from_address_book - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter type: (query) Address book type - parameter address: (query) Address in currency format, it must be in address book - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - returns: RequestBuilder<Any> */ open class func privateRemoveFromAddressBookGetWithRequestBuilder(currency: Currency_privateRemoveFromAddressBookGet, type: ModelType_privateRemoveFromAddressBookGet, address: String, tfa: String? = nil) -> RequestBuilder<Any> { let path = "/private/remove_from_address_book" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "type": type.rawValue, "address": address, "tfa": tfa ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter type */ public enum ModelType_privateSellGet: String { case limit = "limit" case stopLimit = "stop_limit" case market = "market" case stopMarket = "stop_market" } /** * enum for parameter timeInForce */ public enum TimeInForce_privateSellGet: String { case goodTilCancelled = "good_til_cancelled" case fillOrKill = "fill_or_kill" case immediateOrCancel = "immediate_or_cancel" } /** * enum for parameter trigger */ public enum Trigger_privateSellGet: String { case indexPrice = "index_price" case markPrice = "mark_price" case lastPrice = "last_price" } /** * enum for parameter advanced */ public enum Advanced_privateSellGet: String { case usd = "usd" case implv = "implv" } /** Places a sell order for an instrument. - parameter instrumentName: (query) Instrument name - parameter amount: (query) It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH - parameter type: (query) The order type, default: &#x60;\&quot;limit\&quot;&#x60; (optional) - parameter label: (query) user defined label for the order (maximum 32 characters) (optional) - parameter price: (query) &lt;p&gt;The order price in base currency (Only for limit and stop_limit orders)&lt;/p&gt; &lt;p&gt;When adding order with advanced&#x3D;usd, the field price should be the option price value in USD.&lt;/p&gt; &lt;p&gt;When adding order with advanced&#x3D;implv, the field price should be a value of implied volatility in percentages. For example, price&#x3D;100, means implied volatility of 100%&lt;/p&gt; (optional) - parameter timeInForce: (query) &lt;p&gt;Specifies how long the order remains in effect. Default &#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&#x60;\&quot;good_til_cancelled\&quot;&#x60; - unfilled order remains in order book until cancelled&lt;/li&gt; &lt;li&gt;&#x60;\&quot;fill_or_kill\&quot;&#x60; - execute a transaction immediately and completely or not at all&lt;/li&gt; &lt;li&gt;&#x60;\&quot;immediate_or_cancel\&quot;&#x60; - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled&lt;/li&gt; &lt;/ul&gt; (optional, default to .good_til_cancelled) - parameter maxShow: (query) Maximum amount within an order to be shown to other customers, &#x60;0&#x60; for invisible order (optional, default to 1) - parameter postOnly: (query) &lt;p&gt;If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.&lt;/p&gt; &lt;p&gt;Only valid in combination with time_in_force&#x3D;&#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; (optional, default to true) - parameter reduceOnly: (query) If &#x60;true&#x60;, the order is considered reduce-only which is intended to only reduce a current position (optional, default to false) - parameter stopPrice: (query) Stop price, required for stop limit orders (Only for stop orders) (optional) - parameter trigger: (query) Defines trigger type, required for &#x60;\&quot;stop_limit\&quot;&#x60; order type (optional) - parameter advanced: (query) Advanced option order type. (Only for options) (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateSellGet(instrumentName: String, amount: Double, type: ModelType_privateSellGet? = nil, label: String? = nil, price: Double? = nil, timeInForce: TimeInForce_privateSellGet? = nil, maxShow: Double? = nil, postOnly: Bool? = nil, reduceOnly: Bool? = nil, stopPrice: Double? = nil, trigger: Trigger_privateSellGet? = nil, advanced: Advanced_privateSellGet? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateSellGetWithRequestBuilder(instrumentName: instrumentName, amount: amount, type: type, label: label, price: price, timeInForce: timeInForce, maxShow: maxShow, postOnly: postOnly, reduceOnly: reduceOnly, stopPrice: stopPrice, trigger: trigger, advanced: advanced).execute { (response, error) -> Void in completion(response?.body, error) } } /** Places a sell order for an instrument. - GET /private/sell - BASIC: - type: http - name: bearerAuth - parameter instrumentName: (query) Instrument name - parameter amount: (query) It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH - parameter type: (query) The order type, default: &#x60;\&quot;limit\&quot;&#x60; (optional) - parameter label: (query) user defined label for the order (maximum 32 characters) (optional) - parameter price: (query) &lt;p&gt;The order price in base currency (Only for limit and stop_limit orders)&lt;/p&gt; &lt;p&gt;When adding order with advanced&#x3D;usd, the field price should be the option price value in USD.&lt;/p&gt; &lt;p&gt;When adding order with advanced&#x3D;implv, the field price should be a value of implied volatility in percentages. For example, price&#x3D;100, means implied volatility of 100%&lt;/p&gt; (optional) - parameter timeInForce: (query) &lt;p&gt;Specifies how long the order remains in effect. Default &#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&#x60;\&quot;good_til_cancelled\&quot;&#x60; - unfilled order remains in order book until cancelled&lt;/li&gt; &lt;li&gt;&#x60;\&quot;fill_or_kill\&quot;&#x60; - execute a transaction immediately and completely or not at all&lt;/li&gt; &lt;li&gt;&#x60;\&quot;immediate_or_cancel\&quot;&#x60; - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled&lt;/li&gt; &lt;/ul&gt; (optional, default to .good_til_cancelled) - parameter maxShow: (query) Maximum amount within an order to be shown to other customers, &#x60;0&#x60; for invisible order (optional, default to 1) - parameter postOnly: (query) &lt;p&gt;If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.&lt;/p&gt; &lt;p&gt;Only valid in combination with time_in_force&#x3D;&#x60;\&quot;good_til_cancelled\&quot;&#x60;&lt;/p&gt; (optional, default to true) - parameter reduceOnly: (query) If &#x60;true&#x60;, the order is considered reduce-only which is intended to only reduce a current position (optional, default to false) - parameter stopPrice: (query) Stop price, required for stop limit orders (Only for stop orders) (optional) - parameter trigger: (query) Defines trigger type, required for &#x60;\&quot;stop_limit\&quot;&#x60; order type (optional) - parameter advanced: (query) Advanced option order type. (Only for options) (optional) - returns: RequestBuilder<Any> */ open class func privateSellGetWithRequestBuilder(instrumentName: String, amount: Double, type: ModelType_privateSellGet? = nil, label: String? = nil, price: Double? = nil, timeInForce: TimeInForce_privateSellGet? = nil, maxShow: Double? = nil, postOnly: Bool? = nil, reduceOnly: Bool? = nil, stopPrice: Double? = nil, trigger: Trigger_privateSellGet? = nil, advanced: Advanced_privateSellGet? = nil) -> RequestBuilder<Any> { let path = "/private/sell" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "instrument_name": instrumentName, "amount": amount, "type": type?.rawValue, "label": label, "price": price, "time_in_force": timeInForce?.rawValue, "max_show": maxShow, "post_only": postOnly, "reduce_only": reduceOnly, "stop_price": stopPrice, "trigger": trigger?.rawValue, "advanced": advanced?.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Marks an announcement as read, so it will not be shown in `get_new_announcements`. - parameter announcementId: (query) the ID of the announcement - parameter completion: completion handler to receive the data and the error objects */ open class func privateSetAnnouncementAsReadGet(announcementId: Double, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateSetAnnouncementAsReadGetWithRequestBuilder(announcementId: announcementId).execute { (response, error) -> Void in completion(response?.body, error) } } /** Marks an announcement as read, so it will not be shown in `get_new_announcements`. - GET /private/set_announcement_as_read - BASIC: - type: http - name: bearerAuth - parameter announcementId: (query) the ID of the announcement - returns: RequestBuilder<Any> */ open class func privateSetAnnouncementAsReadGetWithRequestBuilder(announcementId: Double) -> RequestBuilder<Any> { let path = "/private/set_announcement_as_read" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "announcement_id": announcementId ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Assign an email address to a subaccount. User will receive an email with confirmation link. - parameter sid: (query) The user id for the subaccount - parameter email: (query) The email address for the subaccount - parameter completion: completion handler to receive the data and the error objects */ open class func privateSetEmailForSubaccountGet(sid: Int, email: String, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateSetEmailForSubaccountGetWithRequestBuilder(sid: sid, email: email).execute { (response, error) -> Void in completion(response?.body, error) } } /** Assign an email address to a subaccount. User will receive an email with confirmation link. - GET /private/set_email_for_subaccount - BASIC: - type: http - name: bearerAuth - parameter sid: (query) The user id for the subaccount - parameter email: (query) The email address for the subaccount - returns: RequestBuilder<Any> */ open class func privateSetEmailForSubaccountGetWithRequestBuilder(sid: Int, email: String) -> RequestBuilder<Any> { let path = "/private/set_email_for_subaccount" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "sid": sid.encodeToJSON(), "email": email ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Changes the language to be used for emails. - parameter language: (query) The abbreviated language name. Valid values include &#x60;\&quot;en\&quot;&#x60;, &#x60;\&quot;ko\&quot;&#x60;, &#x60;\&quot;zh\&quot;&#x60; - parameter completion: completion handler to receive the data and the error objects */ open class func privateSetEmailLanguageGet(language: String, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateSetEmailLanguageGetWithRequestBuilder(language: language).execute { (response, error) -> Void in completion(response?.body, error) } } /** Changes the language to be used for emails. - GET /private/set_email_language - BASIC: - type: http - name: bearerAuth - parameter language: (query) The abbreviated language name. Valid values include &#x60;\&quot;en\&quot;&#x60;, &#x60;\&quot;ko\&quot;&#x60;, &#x60;\&quot;zh\&quot;&#x60; - returns: RequestBuilder<Any> */ open class func privateSetEmailLanguageGetWithRequestBuilder(language: String) -> RequestBuilder<Any> { let path = "/private/set_email_language" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "language": language ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Set the password for the subaccount - parameter sid: (query) The user id for the subaccount - parameter password: (query) The password for the subaccount - parameter completion: completion handler to receive the data and the error objects */ open class func privateSetPasswordForSubaccountGet(sid: Int, password: String, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateSetPasswordForSubaccountGetWithRequestBuilder(sid: sid, password: password).execute { (response, error) -> Void in completion(response?.body, error) } } /** Set the password for the subaccount - GET /private/set_password_for_subaccount - BASIC: - type: http - name: bearerAuth - parameter sid: (query) The user id for the subaccount - parameter password: (query) The password for the subaccount - returns: RequestBuilder<Any> */ open class func privateSetPasswordForSubaccountGetWithRequestBuilder(sid: Int, password: String) -> RequestBuilder<Any> { let path = "/private/set_password_for_subaccount" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "sid": sid.encodeToJSON(), "password": password ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateSubmitTransferToSubaccountGet: String { case btc = "BTC" case eth = "ETH" } /** Transfer funds to a subaccount. - parameter currency: (query) The currency symbol - parameter amount: (query) Amount of funds to be transferred - parameter destination: (query) Id of destination subaccount - parameter completion: completion handler to receive the data and the error objects */ open class func privateSubmitTransferToSubaccountGet(currency: Currency_privateSubmitTransferToSubaccountGet, amount: Double, destination: Int, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateSubmitTransferToSubaccountGetWithRequestBuilder(currency: currency, amount: amount, destination: destination).execute { (response, error) -> Void in completion(response?.body, error) } } /** Transfer funds to a subaccount. - GET /private/submit_transfer_to_subaccount - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter amount: (query) Amount of funds to be transferred - parameter destination: (query) Id of destination subaccount - returns: RequestBuilder<Any> */ open class func privateSubmitTransferToSubaccountGetWithRequestBuilder(currency: Currency_privateSubmitTransferToSubaccountGet, amount: Double, destination: Int) -> RequestBuilder<Any> { let path = "/private/submit_transfer_to_subaccount" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "amount": amount, "destination": destination.encodeToJSON() ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateSubmitTransferToUserGet: String { case btc = "BTC" case eth = "ETH" } /** Transfer funds to a another user. - parameter currency: (query) The currency symbol - parameter amount: (query) Amount of funds to be transferred - parameter destination: (query) Destination address from address book - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateSubmitTransferToUserGet(currency: Currency_privateSubmitTransferToUserGet, amount: Double, destination: String, tfa: String? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateSubmitTransferToUserGetWithRequestBuilder(currency: currency, amount: amount, destination: destination, tfa: tfa).execute { (response, error) -> Void in completion(response?.body, error) } } /** Transfer funds to a another user. - GET /private/submit_transfer_to_user - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter amount: (query) Amount of funds to be transferred - parameter destination: (query) Destination address from address book - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - returns: RequestBuilder<Any> */ open class func privateSubmitTransferToUserGetWithRequestBuilder(currency: Currency_privateSubmitTransferToUserGet, amount: Double, destination: String, tfa: String? = nil) -> RequestBuilder<Any> { let path = "/private/submit_transfer_to_user" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "amount": amount, "destination": destination, "tfa": tfa ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateToggleDepositAddressCreationGet: String { case btc = "BTC" case eth = "ETH" } /** Enable or disable deposit address creation - parameter currency: (query) The currency symbol - parameter state: (query) - parameter completion: completion handler to receive the data and the error objects */ open class func privateToggleDepositAddressCreationGet(currency: Currency_privateToggleDepositAddressCreationGet, state: Bool, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateToggleDepositAddressCreationGetWithRequestBuilder(currency: currency, state: state).execute { (response, error) -> Void in completion(response?.body, error) } } /** Enable or disable deposit address creation - GET /private/toggle_deposit_address_creation - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter state: (query) - returns: RequestBuilder<Any> */ open class func privateToggleDepositAddressCreationGetWithRequestBuilder(currency: Currency_privateToggleDepositAddressCreationGet, state: Bool) -> RequestBuilder<Any> { let path = "/private/toggle_deposit_address_creation" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "state": state ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** Enable or disable sending of notifications for the subaccount. - parameter sid: (query) The user id for the subaccount - parameter state: (query) enable (&#x60;true&#x60;) or disable (&#x60;false&#x60;) notifications - parameter completion: completion handler to receive the data and the error objects */ open class func privateToggleNotificationsFromSubaccountGet(sid: Int, state: Bool, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateToggleNotificationsFromSubaccountGetWithRequestBuilder(sid: sid, state: state).execute { (response, error) -> Void in completion(response?.body, error) } } /** Enable or disable sending of notifications for the subaccount. - GET /private/toggle_notifications_from_subaccount - BASIC: - type: http - name: bearerAuth - parameter sid: (query) The user id for the subaccount - parameter state: (query) enable (&#x60;true&#x60;) or disable (&#x60;false&#x60;) notifications - returns: RequestBuilder<Any> */ open class func privateToggleNotificationsFromSubaccountGetWithRequestBuilder(sid: Int, state: Bool) -> RequestBuilder<Any> { let path = "/private/toggle_notifications_from_subaccount" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "sid": sid.encodeToJSON(), "state": state ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter state */ public enum State_privateToggleSubaccountLoginGet: String { case enable = "enable" case disable = "disable" } /** Enable or disable login for a subaccount. If login is disabled and a session for the subaccount exists, this session will be terminated. - parameter sid: (query) The user id for the subaccount - parameter state: (query) enable or disable login. - parameter completion: completion handler to receive the data and the error objects */ open class func privateToggleSubaccountLoginGet(sid: Int, state: State_privateToggleSubaccountLoginGet, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateToggleSubaccountLoginGetWithRequestBuilder(sid: sid, state: state).execute { (response, error) -> Void in completion(response?.body, error) } } /** Enable or disable login for a subaccount. If login is disabled and a session for the subaccount exists, this session will be terminated. - GET /private/toggle_subaccount_login - BASIC: - type: http - name: bearerAuth - parameter sid: (query) The user id for the subaccount - parameter state: (query) enable or disable login. - returns: RequestBuilder<Any> */ open class func privateToggleSubaccountLoginGetWithRequestBuilder(sid: Int, state: State_privateToggleSubaccountLoginGet) -> RequestBuilder<Any> { let path = "/private/toggle_subaccount_login" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "sid": sid.encodeToJSON(), "state": state.rawValue ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** * enum for parameter currency */ public enum Currency_privateWithdrawGet: String { case btc = "BTC" case eth = "ETH" } /** * enum for parameter priority */ public enum Priority_privateWithdrawGet: String { case insane = "insane" case extremeHigh = "extreme_high" case veryHigh = "very_high" case high = "high" case mid = "mid" case low = "low" case veryLow = "very_low" } /** Creates a new withdrawal request - parameter currency: (query) The currency symbol - parameter address: (query) Address in currency format, it must be in address book - parameter amount: (query) Amount of funds to be withdrawn - parameter priority: (query) Withdrawal priority, optional for BTC, default: &#x60;high&#x60; (optional) - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - parameter completion: completion handler to receive the data and the error objects */ open class func privateWithdrawGet(currency: Currency_privateWithdrawGet, address: String, amount: Double, priority: Priority_privateWithdrawGet? = nil, tfa: String? = nil, completion: @escaping ((_ data: Any?,_ error: Error?) -> Void)) { privateWithdrawGetWithRequestBuilder(currency: currency, address: address, amount: amount, priority: priority, tfa: tfa).execute { (response, error) -> Void in completion(response?.body, error) } } /** Creates a new withdrawal request - GET /private/withdraw - BASIC: - type: http - name: bearerAuth - parameter currency: (query) The currency symbol - parameter address: (query) Address in currency format, it must be in address book - parameter amount: (query) Amount of funds to be withdrawn - parameter priority: (query) Withdrawal priority, optional for BTC, default: &#x60;high&#x60; (optional) - parameter tfa: (query) TFA code, required when TFA is enabled for current account (optional) - returns: RequestBuilder<Any> */ open class func privateWithdrawGetWithRequestBuilder(currency: Currency_privateWithdrawGet, address: String, amount: Double, priority: Priority_privateWithdrawGet? = nil, tfa: String? = nil) -> RequestBuilder<Any> { let path = "/private/withdraw" let URLString = OpenAPIClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "currency": currency.rawValue, "address": address, "amount": amount, "priority": priority?.rawValue, "tfa": tfa ]) let requestBuilder: RequestBuilder<Any>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } }
// // ViewController.swift // PepBuck // // Created by Stephen Casella on 8/19/15. // Copyright (c) 2015 Stephen Casella. All rights reserved. // import UIKit var payRate = 0.00 class SetupController: UIViewController { var payToggle = false @IBOutlet var welcomeLabel: SpringLabel! @IBOutlet var pepBuckLabel: SpringLabel! @IBOutlet var entryField: UITextField! @IBOutlet var whatIsLabel: SpringLabel! @IBOutlet var submitButton: SpringButton! @IBOutlet var nameLabel: SpringLabel! @IBOutlet var whatIsHourLabel: SpringLabel! @IBOutlet var calcIcon: UIButton! @IBAction func submitTap(sender: AnyObject) { if payToggle == false { if entryField.text != "" { var name = entryField.text name.replaceRange(name.startIndex...name.startIndex, with: String(name[name.startIndex]).capitalizedString) welcomeLabel.hidden = true pepBuckLabel.hidden = true nameLabel.text = "Hi, \(name)" nameLabel.hidden = false nameLabel.animation = "fadeIn" nameLabel.duration = 1.0 nameLabel.animate() whatIsLabel.x = -1000 whatIsLabel.animateTo() whatIsHourLabel.hidden = false whatIsHourLabel.animation = "slideLeft" whatIsHourLabel.duration = 1.75 whatIsHourLabel.animate() entryField.text = "" calcIcon.hidden = false entryField.keyboardType = UIKeyboardType.DecimalPad entryField.resignFirstResponder() entryField.becomeFirstResponder() payToggle = true } } else { if entryField.text != "" { payRate = (entryField.text as NSString).doubleValue NSUserDefaults.standardUserDefaults().setObject(payRate, forKey: "payRate") performSegueWithIdentifier("toMain", sender: self) } } } override func viewDidLoad() { super.viewDidLoad() welcomeLabel.animateNext { self.welcomeLabel.animation = "squeezeRight" self.welcomeLabel.duration = 1.5 self.welcomeLabel.animate() } pepBuckLabel.animateNext { self.pepBuckLabel.animation = "squeezeLeft" self.pepBuckLabel.delay = 0.2 self.pepBuckLabel.duration = 1.5 self.pepBuckLabel.animate() self.pepBuckLabel.animateNext { entryField.becomeFirstResponder() } } whatIsLabel.animateNext { self.whatIsLabel.animation = "fadeIn" self.whatIsLabel.delay = 1.0 self.whatIsLabel.duration = 3.0 self.whatIsLabel.animate() } // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // StandardButton.swift // HamHumApp // // Created by ALEMDAR on 16.08.2021. // import UIKit class StandardButton: UIButton { private let labelTitle: UILabel = { let label = UILabel() label.textColor = .white label.font = UIFont(name: Font.CenturyGothic.bold, size: 21) return label }() override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } private func commonInit(){ setupUI() layout() } private func setupUI(){ backgroundColor = Color.primary.red layer.cornerRadius = 75/2 } func configure(with model: StandardButtonUIModel){ labelTitle.text = model.title } private func layout(){ snp.makeConstraints { (make) in make.height.equalTo(75) } addSubview(labelTitle) labelTitle.snp.makeConstraints { (make) in make.centerX.centerY.equalToSuperview() } } }
// // OuterSettingsVCViewController.swift // LSystem01 // // Created by Jeff Holtzkener on 4/15/16. // Copyright © 2016 Jeff Holtzkener. All rights reserved. // import UIKit class OuterSettingsVCViewController: UIViewController { @IBOutlet weak var nodeView0: NodeExtensionView! @IBOutlet weak var nodeView1: NodeExtensionView! @IBOutlet weak var nodeView2: NodeExtensionView! @IBOutlet weak var nodeView3: NodeExtensionView! @IBOutlet weak var nodeView4: NodeExtensionView! var nodeViews: [NodeExtensionView]! override func viewDidLoad() { super.viewDidLoad() nodeViews = [nodeView0,nodeView1,nodeView2,nodeView3,nodeView4] for nodeView in nodeViews { nodeView.getSizes() nodeView.setUpExtensions() } if (self.view.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Unspecified) { } else { print(" not regular horizontak") } print(self.view.traitCollection.horizontalSizeClass) view.userInteractionEnabled = true } func tapped(sender: UITapGestureRecognizer) { print(" VC toucjed") } override func overrideTraitCollectionForChildViewController(childViewController: UIViewController) -> UITraitCollection { print("called") if view.bounds.width > view.bounds.height { return UITraitCollection(verticalSizeClass: .Compact) } else { return UITraitCollection(verticalSizeClass: .Regular) } } }
// // ForthVC.swift // RaindropsDemo // // Created by bach on 2017/1/10. // Copyright © 2017年 bach. All rights reserved. // import UIKit class ForthView: UIView { var customTabBar: RdCustomTabBar! override init(frame: CGRect) { super.init(frame: frame) loadUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func loadUI() { self.backgroundColor = UIColor(red: 0.00, green: 0.80, blue: 0.00, alpha: 1.00) customTabBar = RdCustomTabBar() customTabBar.backgroundColor = UIColor(red: 0.29, green: 0.71, blue: 0.93, alpha: 1.00) customTabBar.selectedIndex = 3 self.addSubview(customTabBar) } override func layoutSubviews() { super.layoutSubviews() let bounds = self.bounds let tabBarFrame = CGRect(x: 0, y: bounds.size.height - 49, width: bounds.size.width, height: 49) customTabBar.frame = tabBarFrame } } class ForthVC: UIViewController, TabBarDataSource, TabBarDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. loadUI() } private func loadUI() { let forthView = ForthView(frame: self.view.frame) forthView.customTabBar.notificationsName = NotificationNames forthView.customTabBar.datasource = self forthView.customTabBar.delegate = self self.view = forthView } func tabBar(_ tabBar: RdCustomTabBar, cellForItemAt index: Int) -> RdCustomBarItem { let item = RdCustomBarItem(style: CustomBarItemStyle.Default) item.titleLabel.text = TabBarModuleNames[index] item.titleLabel.textColor = UIColor.black item.imageView.image = UIImage(named: "index_\(index)_normal") item.imageView.highlightedImage = UIImage(named: "index_\(index)_selected") return item } func tabBarInsetsOfTop(_ tabBar: RdCustomTabBar, cellForItemAt index: Int) -> CGFloat { return 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // Gallery.swift // ETBAROON // // Created by imac on 10/15/17. // Copyright © 2017 IAS. All rights reserved. // import UIKit class Gallery: NSObject { var imgUrl : String! }
import UIKit class ResetViewController: UIViewController, Presentable { var store: Store! static var storyboardName = "Reset" override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) store.dispatch(InitStateAction()) } }
// // ZDebugController.swift // Seriously // // Created by Jonathan Sand on 2/18/21. // Copyright © 2021 Zones. All rights reserved. // import Foundation #if os(OSX) import Cocoa #elseif os(iOS) import UIKit #endif enum ZDebugID: Int { case dRegistry case dTotal case dZones case dValid case dProgeny case dTrash case dFavorites case dRecents case dLost case dTraits case dDestroy case dDuplicates case dEnd var title: String { return "\(self)".lowercased().substring(fromInclusive: 1) } } enum ZDebugThingID: Int { case tBoxes case tAngles var title: String { return "\(self)".lowercased().substring(fromInclusive: 1) } } class ZDebugController: ZGenericTableController { override var controllerID : ZControllerID { return .idDebug } var rows : Int { return ZDebugID.dEnd.rawValue } override func awakeFromNib() { super.awakeFromNib() genericTableView?.delegate = self } override func shouldHandle(_ kind: ZSignalKind) -> Bool { return super.shouldHandle(kind) && gDebugInfo } #if os(OSX) override func numberOfRows(in tableView: ZTableView) -> Int { return gDebugInfo ? rows : 0 } func tableView(_ tableView: ZTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { if let columnTitle = tableColumn?.title, let debugID = ZDebugID(rawValue: row) { var string : String? = nil switch columnTitle { case "title": string = debugID.title case "value": string = "\(gRecords.debugValue(for: debugID) ?? 0)" default: break } return string } return nil } func thing(for row: Int) -> ZControl? { if let thingID = ZDebugThingID(rawValue: row) { let rect = CGRect(origin: .zero, size: CGSize(width: 40.0, height: 18.0)) let button = ZButton(frame: rect) button .action = #selector(handleThingAction) button .state = state(for: thingID) button .tag = thingID.rawValue button .title = thingID.title button .font = gMicroFont button.isBordered = false button .target = self button.setButtonType(.toggle) return button } return nil } func tableView(_ tableView: ZTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if tableColumn?.title == "thing" { return thing(for: row) } else if let string = self.tableView(tableView, objectValueFor: tableColumn, row: row) as? String { let text = ZTextField(labelWithString: string) text .font = gMicroFont text .isBordered = false return text } return nil } func state(for thingID: ZDebugThingID) -> NSControl.StateValue { var flag = false switch thingID { case .tBoxes: flag = gDebugDraw case .tAngles: flag = gDebugAngles } return flag ? .on : .off } @objc func handleThingAction(_ thing: ZControl?) { if let tag = thing?.tag, let thingID = ZDebugThingID(rawValue: tag) { switch thingID { case .tBoxes: gToggleDebugMode(.dDebugDraw) case .tAngles: gToggleDebugMode(.dDebugAngles); gSignal([.spMain]) } gRelayoutMaps() } } #endif }
// // Items.swift // Todoey // // Created by Jiyoung on 30/04/2019. // Copyright © 2019 Jiyoung Kim. All rights reserved. // import Foundation class Items { var title : String = "" var done : Bool = false }
// // NewTaskViewController.swift // TODO-App // // Created by Ashis Laha on 23/05/20. // Copyright © 2020 Ashis Laha. All rights reserved. // import UIKit import TODOKit import Intents class NewTaskViewController: UIViewController { // MARK:- Private variables private var currentTask: PrimaryTaskType = .none { didSet { taskTypeResult?.text = currentTask.getTitle() subTaskButtonOutlet.setTitle(currentTask.getSubTaskTitle(), for: .normal) } } private var secondaryTask: SecondaryTaskType? private var timePicker: UIDatePicker! private var chooseTime: Date? // MARK:- Outlets @IBOutlet weak var taskButtonOutlet: UIButton! { didSet { taskButtonOutlet.layer.masksToBounds = true taskButtonOutlet.layer.cornerRadius = 10 } } @IBOutlet weak var taskTypeResult: UILabel! { didSet { taskTypeResult.text = "" } } @IBOutlet weak var subTaskButtonOutlet: UIButton! { didSet { subTaskButtonOutlet.layer.masksToBounds = true subTaskButtonOutlet.layer.cornerRadius = 10 } } @IBOutlet weak var secondaryTaskTypeResult: UILabel! { didSet { secondaryTaskTypeResult.text = "" } } @IBOutlet weak var chooseTimeOutlet: UIButton! { didSet { chooseTimeOutlet.layer.masksToBounds = true chooseTimeOutlet.layer.cornerRadius = 10 } } @IBOutlet weak var timeLabel: UILabel! { didSet { timeLabel.text = "" } } // MARK:- Actions @IBAction func tapChooseTask(_ sender: UIButton) { showActionSheet(taskType: .primary, primaryTypes: TaskManager.shared.taskList) } @IBAction func tapSubTask(_ sender: UIButton) { guard currentTask != PrimaryTaskType.none else { self.showAlert(title: "Choose Primary First") return } switch currentTask { case .coding(let languages): showActionSheet(taskType: .secondary, secondaryOptions: languages) case .listening(let albums): showActionSheet(taskType: .secondary, secondaryOptions: albums) case .playing(let games): showActionSheet(taskType: .secondary, secondaryOptions: games) case .studying(let authors): showActionSheet(taskType: .secondary, secondaryOptions: authors) default: break } } @IBAction func tapChooseTime(_ sender: UIButton) { guard currentTask != PrimaryTaskType.none else { self.showAlert(title: "Choose Primary Task first") return } let height: CGFloat = 200 timePicker = UIDatePicker(frame: CGRect(x: view.frame.midX - 100, y: view.frame.maxY - height, width: view.frame.size.width - 200, height: height)) timePicker.layer.masksToBounds = true timePicker.layer.cornerRadius = 20 timePicker.datePickerMode = .time timePicker.backgroundColor = UIColor(red: 46/255.0, green: 204/255.0, blue: 113/255.0, alpha: 1.0) // https://flatuicolors.com/palette/defo view.addSubview(timePicker) timePicker.addTarget(self, action: #selector(saveTime), for: .valueChanged) } @objc func saveTime() { guard let timePicker = timePicker else { return } chooseTime = timePicker.date let formatter = DateFormatter() formatter.timeStyle = .short timeLabel.text = formatter.string(from: timePicker.date) timePicker.removeFromSuperview() } @IBAction func tapDoneButton(_ sender: UIBarButtonItem) { guard currentTask != .none else { self.showAlert(title: "Choose Primary Task first") return } guard let secondary = secondaryTask else { self.showAlert(title: "Choose Secondary Task") return } guard let chooseTime = chooseTime else { self.showAlert(title: "Choose a time") return } // create a new task with primary task, secondary task and date & time let task = Task(primary: currentTask, secondary: secondary, createTime: Date(), performTime: chooseTime, primaryDescription: currentTask.getTitle(), secondaryDescription: secondary.getTitle()) TaskManager.shared.addTask(task: task) // Donate an interaction to the system let interaction = INInteraction(intent: task.intent, response: nil) interaction.donate { (error) in if let error = error { print("failed to donate: \(error.localizedDescription)") } } navigationController?.popViewController(animated: true) } // MARK:- Private methods private func showActionSheet(taskType: TaskType, primaryTypes: [PrimaryTaskType] = [], secondaryOptions: [SecondaryTaskType] = []) { let title = taskType == .primary ? "Choose a task": "Choose a sub-task" let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) if taskType == .primary { for primaryTask in primaryTypes { let actionTitle = primaryTask.getTitle() let alertAction = UIAlertAction(title: actionTitle, style: .default) { (action) in self.currentTask = primaryTask } alertController.addAction(alertAction) } } else { // secondary for each in secondaryOptions { let alertAction = UIAlertAction(title: each.getTitle(), style: .default) { (action) in self.secondaryTaskTypeResult.text = each.getTitle() self.secondaryTask = each } alertController.addAction(alertAction) } } let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } private func showAlert(title: String) { let alertController = UIAlertController(title: title, message: nil, preferredStyle: .alert) let okayAction = UIAlertAction(title: "Okay", style: .default) { (action) in alertController.dismiss(animated: true, completion: nil) } alertController.addAction(okayAction) self.present(alertController, animated: true, completion: nil) } }
// // PathExtractor.swift // Basic // // Created by Rob Saunders on 20/04/2019. // import SwiftSyntax class PathExtractor : SyntaxVisitor { var baseUrl: String? = nil override func visit(_ node: PatternBindingSyntax) -> SyntaxVisitorContinueKind { var key: String? var value: String? for child in node.children { switch type(of: child) { case is IdentifierPatternSyntax.Type: key = "\(child)".trimmingCharacters(in: .whitespaces) case is InitializerClauseSyntax.Type: for child in child.children { if type(of: child) == StringLiteralExprSyntax.self { value = "\(child)".trimmingCharacters(in: .whitespaces) } } default: () } } if key == Optional("baseUrl") { if let baseUrl = value { self.baseUrl = baseUrl } } return .skipChildren } }
// // ViewController.swift // GraphTest // // Created by Josh Henry on 8/17/15. // Copyright (c) 2015 Josh Henry. All rights reserved. // import UIKit import Charts class ViewController: UIViewController, ChartViewDelegate { @IBOutlet weak var testLineChartView: LineChartView! override func viewDidLoad() { super.viewDidLoad() testLineChartView.delegate = self //testLineChartView.descriptionText = "Test, yo!" //testLineChartView.noDataText = "Doy?" testLineChartView.xAxis.enabled = true testLineChartView.xAxis.labelPosition = .Bottom //chartView.animate(xAxisDuration: 1) testLineChartView.rightAxis.drawLabelsEnabled = false var allLineChartDataSets: [LineChartDataSet] = [LineChartDataSet]() var dataEntries: [ChartDataEntry] = [] let dataPoints = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"] let values = [18.0, 4.0, 6.0, 3.0, 12.0, 16.0, 30] for i in 0..<dataPoints.count { let dataEntry = ChartDataEntry(value: values[i], xIndex: i) dataEntries.append(dataEntry) println(dataPoints[i]) } //let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Units Sold") //let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet) //testLineChartView.data = lineChartData let lineChartDataSet1: LineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Temperature") allLineChartDataSets.append(lineChartDataSet1) var dataEntries2: [ChartDataEntry] = [] let dataPoints2 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Aug"] let values2 = [21.0, 5.0, 7.0, 10.0, 11.0, 18.0, 20] /*for i in 0..<dataPoints2.count { let dataEntry2 = ChartDataEntry(value: values2[i], xIndex: i) dataEntries2.append(dataEntry2) println(dataPoints2[i]) }*/ dataEntries2.append(ChartDataEntry(value: values2[0], xIndex: 0)) dataEntries2.append(ChartDataEntry(value: values2[1], xIndex: 1)) dataEntries2.append(ChartDataEntry(value: values2[2], xIndex: 2)) dataEntries2.append(ChartDataEntry(value: values2[3], xIndex: 3)) dataEntries2.append(ChartDataEntry(value: values2[4], xIndex: 4)) dataEntries2.append(ChartDataEntry(value: values2[5], xIndex: 5)) dataEntries2.append(ChartDataEntry(value: values2[6], xIndex: 7)) let lineChartDataSet2 = LineChartDataSet(yVals: dataEntries2, label: "Units Sold") lineChartDataSet2.setColor(UIColor.redColor()) lineChartDataSet2.setCircleColor(UIColor.redColor()) allLineChartDataSets.append(lineChartDataSet2) let allDataPoints: [String] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug"] //let lineChartData = LineChartData(xVals: dataPoints, dataSets: allLineChartDataSets) let lineChartData = LineChartData(xVals: allDataPoints, dataSets: allLineChartDataSets) testLineChartView.data = lineChartData /* //TESTING TWO LINES ON ONE CHART WITH DIFF NUMB OF DATA POINTS //values for datainput Dataset1 at your axisone positions dataEntries.append(<#newElement: T#>) ArrayList<Entry> dataset1 = new ArrayList<Entry>(); dataset1.add(new Entry(1f, 0)); dataset1.add(new Entry(2f, 1)); dataset1.add(new Entry(3f, 2)); dataset1.add(new Entry(4f, 3)); dataset1.add(new Entry(5f, 4)); dataset1.add(new Entry(6f, 5)); dataset1.add(new Entry(7f, 6)); //values for datainput Dataset2 at your axisone positions ArrayList<Entry> dataset2 = new ArrayList<Entry>(); dataset2.add(new Entry(3f, 0)); dataset2.add(new Entry(4f, 2)); dataset2.add(new Entry(5f, 4)); dataset2.add(new Entry(6f, 5)); dataset2.add(new Entry(7f, 6)); dataset2.add(new Entry(8f, 7)); dataset2.add(new Entry(9f, 8)); // Union from xAxisOne and xAxisTwo xAxis: [String] = ["0", "1", "2", "3", "4", "5", "6", "8", "9"] ArrayList<LineDataSet> lines = new ArrayList<LineDataSet> (); LineDataSet lDataSet1 = new LineDataSet(dataset1, "DataSet1"); lDataSet1.setColor(Color.RED); lDataSet1.setCircleColor(Color.RED); lines.add(lDataSet1); lines.add(new LineDataSet(dataset2, "DataSet2")); LineChart chart = (LineChart) getView().findViewById(R.id.chart); chart.setData(new LineData(xAxis, lines)); */ //THIS WORKS GREAT FOR A BAR CHART. ONLY NEED TO CHANGE THE CLASS OF THE VIEW AND OFF YOU GO /* let xVals: [String] = ["1", "2", "3", "4", "5"] var yVals: [BarChartDataEntry] = [] yVals.append(BarChartDataEntry(value: Double(5), xIndex: 0)) yVals.append(BarChartDataEntry(value: Double(8), xIndex: 1)) yVals.append(BarChartDataEntry(value: Double(2), xIndex: 2)) yVals.append(BarChartDataEntry(value: Double(5), xIndex: 3)) yVals.append(BarChartDataEntry(value: Double(1), xIndex: 4)) //var yVals:[Int] = [1, 2, 3, 4, 5] //for idx in 0...6 { // yVals.append(BarChartDataEntry(value: Float(self.stepsTaken[idx]), xIndex: idx)) //} //println("Days :\(self.days)") //println("Steps :\(self.stepsTaken)") let set1 = BarChartDataSet(yVals: yVals, label: "Steps Taken") set1.barSpace = 0.25 let data = BarChartData(xVals: xVals, dataSet: set1) data.setValueFont(UIFont(name: "Avenir", size: 12)) testLineChartView.data = data self.view.reloadInputViews() */ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // Story.swift // hackernews // // Created by Daniel Grech on 12/10/2015. // Copyright © 2015 DGSD. All rights reserved. // import Foundation enum StoryType { case Story case Job case Poll case Poll_Answer } struct Story { var id: Int64 = -1 var time: Int64 = -1 var type: StoryType = StoryType.Story var parentId: Int64 = -1 var author: String? = nil var title: String? = nil var text: String? = nil var url: String? = nil var commentCount: Int32 = -1 var score: Int32 = -1 var pollAnswers: [Int64] = [] var commentIds: [Int64] = [] var comments: [Comment] = [] var deleted: Bool var dead: Bool var dateRetrieved: Int64 = NSDate.currentTimeInMillis() func hasComments() -> Bool { return !commentIds.isEmpty } func hasCommentsToLoad() -> Bool { return hasComments() && comments.isEmpty } }
// // ContactDetailController.swift // AdressListWithSwift2 // // Created by caixiasun on 16/9/7. // Copyright © 2016年 yatou. All rights reserved. // import UIKit class ContactDetailController: UIViewController, UITableViewDelegate,UITableViewDataSource{ @IBOutlet weak var headImg: UIImageView! @IBOutlet weak var nameLab: UILabel! @IBOutlet weak var headImgTapBtn: UIButton! @IBOutlet weak var tablView: UITableView! let cellIdentifier = "ContactDetailCell" var dataSource:NSDictionary? var userModel:UserModel? override func viewDidLoad() { super.viewDidLoad() self.initSubviews() //模拟请求 self.getData() } //MARK:- init method func initSubviews() { self.view.backgroundColor = WhiteColor self.initNaviBar() tablView.registerNib(UINib(nibName: cellIdentifier, bundle: nil), forCellReuseIdentifier: cellIdentifier) dataSource = NSDictionary() } func initNaviBar() { self.navigationController?.navigationBar.barStyle = UIBarStyle.Default self.navigationController?.navigationBar.tintColor = WhiteColor let editBtn = ETDrawButton("Edit", TitleColor: WhiteColor, FontSize: kFontSize_navigationBar_button, Target: self, Action: #selector(ContactDetailController.itemAction(_:))) editBtn.tag = 1 self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: editBtn) } //MARK:- action method @IBAction func itemAction(sender:UIButton) { switch sender.tag { case 1: let controller = YTNavigationController(rootViewController: EditContactController()) controller.initNavigationBar() self.presentViewController(controller, animated: false, completion: nil) break case 2: break default: break } } //MARK:- UITableViewDelegate,UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return (userModel?.count)! }else{//发送信息 模块 return 2 } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0 }else{ return 50 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tablView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ContactDetailCell if indexPath.section == 0 { cell.telLab.hidden = false switch indexPath.row { case 0: cell.titleLab.text = "电话号码" cell.telLab.text = userModel?.tel break case 1: cell.titleLab.text = "电子邮件" cell.telLab.text = userModel?.email break case 2: cell.titleLab.text = "出生日期" cell.telLab.text = userModel?.birthday break case 3: cell.titleLab.text = "家庭住址" cell.telLab.text = userModel?.address break default: break } }else{ cell.telLab.hidden = true if indexPath.row == 0 { cell.titleLab.text = "发送信息" }else{ cell.titleLab.text = "共享联系人" } } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) switch indexPath.row { case 0://拨打电话 let tel = "tel://" + ((dataSource?.objectForKey("tel"))! as! String) let url = NSURL(string: tel) if application.canOpenURL(url!) { application.openURL(url!) } break default: break } } func getData() { let dic1 = ["name":"丫头","tel":"15214141452","email":"","address":"中国香港","birthday":"1990.01.01"] userModel = UserModel.mj_objectWithKeyValues(dic1) as UserModel nameLab.text = userModel?.name userModel?.count = dic1.count - 1 tablView.reloadData() } }
// // BMCManager.swift // // Created by François Boulais on 30/06/2020. // Copyright © 2020 App Craft Studio. All rights reserved. // #if !os(macOS) import UIKit #endif import SafariServices public final class BMCManager: NSObject { public static let shared = BMCManager() /// The view controller used to present donation flow public var presentingViewController: UIViewController? /// The username you've chosen on www.buymeacoffee.com public var username = "appcraftstudio" private var url: URL? { URL(string: "https://www.buymeacoffee.com/".appending(username)) } private override init() { } /// Start the donation flow on presenting view controller @objc public func start() { guard let presentingViewController = presentingViewController else { fatalError("presentingViewController must be set.") } if let url = url { let viewController = SFSafariViewController(url: url) viewController.preferredControlTintColor = BMCColor.default.background viewController.modalPresentationStyle = .formSheet presentingViewController.present(viewController, animated: true) } } }
// // ColorView.swift // CustomView // // Created by Quynh on 2/15/20. // Copyright © 2020 Quynh. All rights reserved. // import UIKit class ColorView: UIView { // sử dụng keyword convenience trước init để bên trong hàm init này có thể gọi đến một hàm init khác convenience init(color: UIColor) { self.init(frame: .zero) self.backgroundColor = color } }
// // SigninViewController.swift // fitness fifteen // // Created by Hao Tang on 10/26/16. // Copyright © 2016 Hao Tang. All rights reserved. // import UIKit import Firebase import FirebaseAuth import FacebookCore import FacebookLogin class SigninViewController: UIViewController { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func btnLoginPressed(_ sender: UIButton) { emailField.text = "" passwordField.text = "" dismiss(animated: true, completion: nil) } @IBAction func btnRegisterPressed(_ sender: UIButton) { let email = emailField.text let password = passwordField.text FIRAuth.auth()!.createUser(withEmail: email!, password: password!) { user, error in if error == nil { FIRAuth.auth()!.signIn(withEmail: email!,password: password!) } else { print("Login with \(error)") } } let loginManager = LoginManager() loginManager.logOut() loginManager.logIn([ .publicProfile, .userFriends ], viewController: self) { loginResult in switch loginResult { case .failed(let error): print(error) case .cancelled: print("User cancelled login.") case .success(let grantedPermissions, let declinedPermissions, let accessToken): let credential = FIRFacebookAuthProvider.credential(withAccessToken: (AccessToken.current?.authenticationToken)!) print("GRANTED PERMISSIONS: \(grantedPermissions)") print("DECLINED PERMISSIONS: \(declinedPermissions)") print("ACCESS TOKEN \(accessToken)") FIRAuth.auth()?.currentUser?.link(with: credential) { (user, error) in if(error != nil){ print("You have logined with same facebook acount") let user = FIRAuth.auth()?.currentUser user?.delete() //regenerate sign in view return } } self.dismiss(animated: true, completion: nil) let tabvc = TabBarController() let appdelegate = UIApplication.shared.delegate as! AppDelegate appdelegate.window!.rootViewController = tabvc } } } }
// // LilyTests.swift // LilyTests // // Created by kukushi on 3/27/15. // Copyright (c) 2015 kukushi. All rights reserved. // import UIKit import XCTest import Lily class LilyTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testExample() { // This is an example of a functional test case. MemoryCache["1"] = 1 MemoryCache["1", "Another"] = 2 XCTAssert(MemoryCache["1"].int == 1, "1") XCTAssert(MemoryCache["1", "Another"].int == 2, "2") } }
// // ViewController.swift // mapViewPrototype // // Created by xclusiveSoft on 6/19/15. // Copyright (c) 2015 Collage App Tech. All rights reserved. // import UIKit import CoreLocation import MapKit class ViewController: UIViewController , UISearchBarDelegate, UITableViewDataSource , UITableViewDelegate{ @IBOutlet weak var progressIn: UIView! @IBOutlet weak var progressOut: UIView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var longL: UILabel! @IBOutlet weak var latL: UILabel! @IBOutlet weak var addressL: UILabel! var results : [MKMapItem] = [] var userAnnotL : mapAnnot? override func viewDidLoad() { super.viewDidLoad() searchBar.placeholder = "Search Cities ..." progressOut.layer.cornerRadius = progressOut.bounds.size.height / 2 progressOut.layer.borderColor = UIColor.lightGrayColor().CGColor progressOut.layer.borderWidth = 1 progressOut.layer.masksToBounds = true self.progressIn.backgroundColor = UIColor(red: CGFloat(236/255.0), green: CGFloat(28/255.0), blue: CGFloat(36/255.0), alpha: 1.0) } func searchBarSearchButtonClicked(searchBar: UISearchBar) { var request = MKLocalSearchRequest() request.naturalLanguageQuery = searchBar.text var search = MKLocalSearch(request: request) search.startWithCompletionHandler({ response , error in if error != nil { println("Error Searching for Location . \(error)") }else if response.mapItems.count == 0 { println("No Matches Found") }else if response.mapItems.count > 0 { var i: Int = 0 self.results.removeAll(keepCapacity: true) for result in response.mapItems { var topResult : MKMapItem = result as! MKMapItem if topResult.placemark.addressDictionary["Name"] as? String == topResult.placemark.addressDictionary["City"] as? String { self.results.append(topResult) println(topResult.placemark.addressDictionary) } } self.tableView.reloadData() } }) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier( "searchRes", forIndexPath: indexPath) as! UITableViewCell //Configure the cell... cell.textLabel?.text = (results[indexPath.row].placemark.addressDictionary["Name"] as? String)! + ", " + (results[indexPath.row].placemark.addressDictionary["Country"] as? String)! return cell } override func viewDidAppear(animated: Bool) { var flr : Float = 255 var flg : Float = 0 var flb : Float = 0 // for var i = 0 ; i < 255 ; i++ { // progressIn.bounds.size.width += 1.345 // println(progressIn.bounds.width) // self.view.setNeedsDisplay() // NSThread.sleepForTimeInterval(0.1) // } self.progressIn.frame.origin.x = self.progressOut.bounds.origin.x // UIView.animateWithDuration(5, animations: { // self.progressIn.bounds.size.width = self.progressOut.bounds.size.width / 2 // self.progressIn.frame.origin.x = self.progressOut.bounds.origin.x //// self.progressIn.backgroundColor = UIColor(red: CGFloat(flr/255.0), green: CGFloat(flg/255.0), blue: CGFloat(flb/255.0), alpha: 1.0) // self.progressIn.backgroundColor = UIColor.blueColor() // }) UIView.animateWithDuration(2.5, animations: { self.progressIn.bounds.size.width = self.progressOut.bounds.size.width / 2 self.progressIn.frame.origin.x = self.progressOut.bounds.origin.x self.progressIn.backgroundColor = UIColor(red: CGFloat(38/255.0), green: CGFloat(169/255.0), blue: CGFloat(224/255.0), alpha: 1.0) // self.progressIn.backgroundColor = UIColor.blueColor() }, completion: { completed in if(completed){ UIView.animateWithDuration(2.5, animations: { self.progressIn.bounds.size.width = self.progressOut.bounds.size.width self.progressIn.frame.origin.x = self.progressOut.bounds.origin.x self.progressIn.backgroundColor = UIColor(red: CGFloat(100/255.0), green: CGFloat(197/255.0), blue: CGFloat(63/255.0), alpha: 1.0) }) } }) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results.count } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { addressL.text = "Address : " + (results[indexPath.row].placemark.addressDictionary["Name"] as? String)! + ", " + (results[indexPath.row].placemark.addressDictionary["Country"] as? String)! latL.text = "Latitude : \(results[indexPath.row].placemark.location.coordinate.latitude)" longL.text = "Longitude : \(results[indexPath.row].placemark.location.coordinate.longitude)" } }
// // DisposeBag.swift // SignInWithAppleDemo // // Created by Virender Dall on 30/10/20. // Copyright © 2020 Developer Insider. All rights reserved. // import Foundation class DisposeBag { private var disposables: [Disposable] = [] func append(_ disposable: Disposable) { disposables.append(disposable) } }
// // AnimableDataView.swift // Drawing // // Created by Giovanni Gaffé on 2021/10/27. // import SwiftUI struct Trapezoid: Shape { var insetAmount: CGFloat var animatableData: CGFloat { get { insetAmount } set { self.insetAmount = newValue } } func path(in rect: CGRect) -> Path { var path = Path() path.move(to: CGPoint(x: 0, y: rect.maxY)) path.addLine(to: CGPoint(x: insetAmount, y: rect.minY)) path.addLine(to: CGPoint(x: rect.maxX - insetAmount, y: rect.minY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) path.addLine(to: CGPoint(x: 0, y: rect.maxY)) return path } } struct AnimableDataView: View { @State private var insetAmount: CGFloat = 0.0 var body: some View { VStack { Trapezoid(insetAmount: insetAmount) .frame(width: 200, height: 100) .onTapGesture { withAnimation { self.insetAmount = CGFloat.random(in: 10...90) } } } } } struct AnimableDataView_Previews: PreviewProvider { static var previews: some View { AnimableDataView() } }
// // LoginRequest.swift // GALiveApp // // Created by 陆广庆 on 16/2/29. // Copyright © 2016年 luguangqing. All rights reserved. // import UIKit import Async class LoginRequest: BaseHttpRequest { override init(callerId: String, listener: BaseHttpRequestListener) { super.init(callerId: callerId, listener: listener) messageID = .Login } func makeParameters(username: String, password: String) -> LoginRequest { parameters["username"] = username parameters["password"] = password return self } func doRequest() { Async.main(block: { () -> Void in self.listener?.httpRequestPreRequest() }) Async.background(after: 1) { () -> Void in let resp = LoginResponse(callerId: self.callerId, messageID: self.messageID) resp.ret_code = .Success resp.ret_msg = "请求成功" resp.user = User.testData()[0] self.sendBroadcast(resp) Async.main(block: { () -> Void in self.listener?.httpRequestAfterRequest() }) } } }
import Foundation /** * An object that displays a secured text area in your interface. */ class PasswordField: TextField { override init(label: String, placeholder: String?, value: String?) { super.init(label: label, placeholder: placeholder, value: value) innerTextField.isSecureTextEntry = true } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // MainViewController.swift // iApp // // Created by 融商科技 on 2017/11/28. // Copyright © 2017年 Eric. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupUI() // Do any additional setup after loading the view. } fileprivate func setupUI() { self.view.backgroundColor = UIColor.baseColor() self.view.addSubview(MAColorView.xib(name: "MAColorView")) } } extension UITabBarController { fileprivate func addChildViewController(SBName: String) { } }
// // DetailViewController.swift // Elephant // // Created by Caelan Dailey on 2/20/18. // Copyright © 2018 Caelan Dailey. All rights reserved. // // THIS CLASS also has a copy: NewAlarmViewController // Easier to just copy them and have 2 // The EditAlarmView is created when an existing alarm is selected. // Must fill view you current existing info // The New Alarm View doesnt need to // // import UIKit class EditAlarmViewController: UIViewController, AlarmDatasetDelegate { private let index: Int // Custom delegate let delegateID: String = UIDevice.current.identifierForVendor!.uuidString private var alarmView: ViewHolder { return view as! ViewHolder } func datasetUpdated() { let entry = AlarmDataset.entry(atIndex: index) alarmView.alarmName = entry.name alarmView.alarmTime = entry.time alarmView.alarmDuration = entry.duration alarmView.currentDays = entry.days alarmView.currentRepeater = entry.repeater alarmView.currentZone = entry.zone } init(withIndex: Int) { index = withIndex super.init(nibName: nil, bundle: nil) AlarmDataset.registerDelegate(self) // MAKES IT SO IT DOESNT GO UNDER TAB BARS or NAVIGATION BARS self.edgesForExtendedLayout = [] self.extendedLayoutIncludesOpaqueBars = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { view = ViewHolder() print("Detail view load") } override func viewDidLoad() { datasetUpdated() } // We left the edit view so save everything that we edited!! override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("edit alarm viewDidDisappear") let entry = AlarmDataset.Entry( name: alarmView.alarmName, days: alarmView.currentDays, repeater: alarmView.currentRepeater, zone: alarmView.currentZone, duration: alarmView.alarmDuration, time: alarmView.alarmTime ) AlarmDataset.editEntry(atIndex: index, newEntry: entry) } }
// // EMCodable.swift // Euromsg // // Created by Muhammed ARAFA on 6.04.2020. // Copyright © 2020 Muhammed ARAFA. All rights reserved. // import UIKit public protocol EMCodable: Codable {} public extension EMCodable { var encoded: String { guard let data = try? JSONEncoder().encode(self) else { return "" } return String(data: data, encoding: .utf8) ?? "" } }
// // GraphicInspector.swift // ArsNovis // // Created by Matt Brandt on 1/29/15. // Copyright (c) 2015 WalkingDog Design. All rights reserved. // import Cocoa enum InspectionType: Int { case distance, angle, string, count, float, bool, literal, point, color } struct InspectionInfo { var label: String var key: String var type: InspectionType } class GraphicsInspector: NSView, NSTextFieldDelegate { @IBOutlet var drawingView: DrawingView? { willSet { drawingView?.removeObserver(self, forKeyPath: "selection") } didSet { drawingView?.addObserver(self, forKeyPath: "selection", options: NSKeyValueObservingOptions.new, context: nil) } } var selection: [Graphic] = [] { didSet { setupBindings() } } var fieldInfo: [(NSControl, Graphic, InspectionInfo)] = [] var fieldConstraints: [NSLayoutConstraint] = [] override func observeValue(forKeyPath keyPath: String?, of object: AnyObject?, change: [NSKeyValueChangeKey : AnyObject]?, context: UnsafeMutablePointer<Void>?) { selection = drawingView?.selection ?? [] } @IBAction func fieldChanged(_ sender: AnyObject) { NSLog("field changed: \(sender)\n") for (field, graphic, info) in fieldInfo { if let control = sender as? NSControl where control == field { if let pcontext = drawingView?.parametricContext, let oldValue = graphic.value(forKey: info.key) as? NSValue where selection.count == 1 && info.type != .float { let parser = ParametricParser(context: pcontext, string: field.stringValue, defaultValue: oldValue, type: graphic.typeForKey(info.key)) if parser.expression.isVariable { pcontext.assign(graphic, property: info.key, expression: parser.expression) } let val = parser.value drawingView?.setNeedsDisplay(graphic.bounds) graphic.setValue(val, forKey: info.key) drawingView?.setNeedsDisplay(graphic.bounds) } else { switch info.type { case .bool: graphic.setValue(control.intValue != 0, forKey: info.key) case .distance: let v = DistanceTransformer().reverseTransformedValue(control.stringValue) graphic.setValue(v, forKey: info.key) case .angle: let ang = AngleTransformer().reverseTransformedValue(control.stringValue) graphic.setValue(ang, forKey: info.key) case .float: let v = control.doubleValue graphic.setValue(v, forKey: info.key) default: break } } break } } drawingView?.needsDisplay = true } @IBAction func colorChanged(_ sender: NSColorWell) { for (field, graphic, info) in fieldInfo { if sender == field { let colorValue = sender.color graphic.setValue(colorValue, forKey: info.key) break } } } func setupBindings() { for subview in subviews { subview.removeFromSuperview() } removeConstraints(fieldConstraints) fieldInfo = [] var selected: Graphic if selection.count == 0 { return } if selection.count == 1 { selected = selection[0] } else { selected = GroupGraphic(contents: selection) } let firstLabel = NSTextField(frame: CGRect(x: 10, y: 10, width: 30, height: 10)) firstLabel.stringValue = selected.inspectionName firstLabel.isBordered = false firstLabel.isEditable = false firstLabel.isSelectable = false firstLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(firstLabel) let firstLabelHConstraint = NSLayoutConstraint(item: firstLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 10) let firstLabelVConstraint = NSLayoutConstraint(item: firstLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 10) fieldConstraints = [firstLabelHConstraint, firstLabelVConstraint] addConstraints(fieldConstraints) var lastLabel = firstLabel var firstField: NSTextField? var lastField: NSTextField? for info in selected.inspectionInfo { let label = NSTextField(frame: CGRect(x: 10, y: 10, width: 30, height: 10)) label.stringValue = info.label + ":" label.isEnabled = true label.isEditable = false label.isSelectable = false label.isBordered = false label.translatesAutoresizingMaskIntoConstraints = false addSubview(label) let labelHConstraint = NSLayoutConstraint(item: label, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 10) let labelVConstraint = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: lastLabel, attribute: .bottom, multiplier: 1.0, constant: 10) addConstraints([labelHConstraint, labelVConstraint]) fieldConstraints += [labelHConstraint, labelVConstraint] if lastLabel != firstLabel { let labelWidthConstraint = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: lastLabel, attribute: .width, multiplier: 1.0, constant: 0) addConstraint(labelWidthConstraint) fieldConstraints.append(labelWidthConstraint) } lastLabel = label var additionalConstraints: [NSLayoutConstraint] = [] var field: NSControl? switch info.type { case .bool: let button = NSButton(frame: CGRect(x: 10, y: 10, width: 30, height: 10)) button.setButtonType(.switchButton) button.title = "" button.isEnabled = true button.bind("intValue", to: selected, withKeyPath: info.key, options: [NSContinuouslyUpdatesValueBindingOption: true]) field = button case .color: let colorWell = NSColorWell(frame: CGRect(x: 10, y: 10, width: 30, height: 30)) colorWell.isEnabled = true colorWell.bind("color", to: selected, withKeyPath: info.key, options: [NSContinuouslyUpdatesValueBindingOption: true]) colorWell.target = self colorWell.action = #selector(colorChanged) colorWell.isContinuous = true let widthConstraint = NSLayoutConstraint(item: colorWell, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 24) let heightConstraint = NSLayoutConstraint(item: colorWell, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 24) additionalConstraints = [widthConstraint, heightConstraint] field = colorWell case .angle: let textField = NSTextField(frame: CGRect(x: 10, y: 10, width: 30, height: 10)) textField.bind("stringValue", to: selected, withKeyPath: info.key, options: [NSValueTransformerBindingOption: AngleTransformer(), NSContinuouslyUpdatesValueBindingOption: true]) field = textField case .count: let textField = NSTextField(frame: CGRect(x: 10, y: 10, width: 30, height: 10)) textField.bind("integerValue", to: selected, withKeyPath: info.key, options: [NSContinuouslyUpdatesValueBindingOption: true]) field = textField case .distance: let textField = NSTextField(frame: CGRect(x: 10, y: 10, width: 30, height: 10)) textField.bind("stringValue", to: selected, withKeyPath: info.key, options: [NSValueTransformerBindingOption: DistanceTransformer(), NSContinuouslyUpdatesValueBindingOption: true]) field = textField case .float: let textField = NSTextField(frame: CGRect(x: 10, y: 10, width: 30, height: 10)) textField.bind("doubleValue", to: selected, withKeyPath: info.key, options: [NSContinuouslyUpdatesValueBindingOption: true]) field = textField case .string: let textField = NSTextField(frame: CGRect(x: 10, y: 10, width: 30, height: 10)) textField.bind("stringValue", to: selected, withKeyPath: info.key, options: [NSContinuouslyUpdatesValueBindingOption: true]) field = textField case .literal, .point: field = nil } if let field = field { fieldInfo.append((field, selected, info)) field.translatesAutoresizingMaskIntoConstraints = false addSubview(field) let vConstraint = NSLayoutConstraint(item: field, attribute: .lastBaseline, relatedBy: .equal, toItem: lastLabel, attribute: .lastBaseline, multiplier: 1.0, constant: 0.0) let hConstraint = NSLayoutConstraint(item: field, attribute: .left, relatedBy: .equal, toItem: lastLabel, attribute: .right, multiplier: 1.0, constant: 10.0) addConstraints([hConstraint, vConstraint] + additionalConstraints) fieldConstraints += [hConstraint, vConstraint] + additionalConstraints } if let field = field as? NSTextField { firstField = firstField ?? field lastField?.nextKeyView = field lastField = field field.isEditable = info.type != .count field.isSelectable = true field.isEnabled = true field.isBordered = info.type != .count let rConstraint = NSLayoutConstraint(item: field, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: -10.0) addConstraint(rConstraint) fieldConstraints.append(rConstraint) field.target = self field.action = #selector(fieldChanged) } } lastField?.nextKeyView = firstField } override func draw(_ dirtyRect: NSRect) { let context = NSGraphicsContext.current()?.cgContext NSColor.white().set() context?.fill(dirtyRect) } func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool { fieldChanged(control) return true } func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { if commandSelector == #selector(NSResponder.insertNewline(_:)) { window?.makeFirstResponder(drawingView) return true } return false } } class GraphicInspector: NSView, NSTextFieldDelegate { var view: DrawingView? var selection: Graphic? var info: [String:(NSTextField, ValueTransformer, NSTextField)] = [:] var defaultField: NSTextField? override func draw(_ dirtyRect: CGRect) { NSEraseRect(dirtyRect) } func removeAllSubviews() { for key in info.keys { if let (field, _, label) = info[key] { label.removeFromSuperview() field.removeFromSuperview() } } info = [:] } @IBAction func fieldChanged(_ sender: AnyObject) { NSLog("field changed: \(sender)\n") for (key, (field, xfrm, _)) in info { if let textfield = sender as? NSTextField { if field == textfield { if let pcontext = view?.parametricContext, let g = selection, let oldValue = g.value(forKey: key) as? NSValue { let parser = ParametricParser(context: pcontext, string: field.stringValue, defaultValue: oldValue, type: g.typeForKey(key)) if parser.expression.isVariable { pcontext.assign(g, property: key, expression: parser.expression) } let val = parser.value view?.setNeedsDisplay(g.bounds) g.setValue(val, forKey: key) view?.setNeedsDisplay(g.bounds) } else if let val = xfrm.reverseTransformedValue(field.stringValue) as? NSNumber { if let g = selection { view?.setNeedsDisplay(g.bounds) g.setValue(val, forKey: key) view?.setNeedsDisplay(g.bounds) } } } } } } func beginEditing() { defaultField?.selectText(self) } func beginInspection(_ graphic: Graphic) { self.selection = graphic let keys = graphic.inspectionKeys let defaultKey = graphic.defaultInspectionKey removeAllSubviews() var location = CGPoint(x: 10, y: 3) var lastField: NSTextField? = nil var firstField: NSTextField? = nil for key in keys { let aKey = AttributedString(string: key) var labelSize = aKey.size() labelSize.width += 10 let label = NSTextField(frame: CGRect(origin: location, size: labelSize)) label.stringValue = key + ":" label.isEditable = false label.isSelectable = false label.isBordered = false self.addSubview(label) location.x += labelSize.width + 5 let field = NSTextField(frame: CGRect(origin: location, size: NSSize(width: 80, height: 16))) field.isBordered = true field.isEditable = true field.target = self field.delegate = self field.action = #selector(GraphicInspector.fieldChanged(_:)) lastField?.nextKeyView = field lastField = field if firstField == nil { firstField = field } self.addSubview(field) let transformer = graphic.transformerForKey(key) info[key] = (field, transformer, label) location.x += 100 field.bind("stringValue", to: graphic, withKeyPath: key, options: [NSValueTransformerBindingOption: transformer, NSContinuouslyUpdatesValueBindingOption: true]) if key == defaultKey { defaultField = field } } lastField?.nextKeyView = firstField } func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool { fieldChanged(control) return true } func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { if commandSelector == #selector(NSResponder.insertNewline(_:)) { //fieldChanged(control) window?.makeFirstResponder(view) return true } return false } }
// // EventsDelegate.swift // Fusion // // Created by Charles Imperato on 12/19/18. // Copyright © 2018 Wind Valley Software. All rights reserved. // import Foundation import wvslib protocol EventsDelegate: Waitable { // - Notify the view that the events loaded successfully func eventsLoaded(_ events: [ViewEvent]) // - Notify the view that the events failed to load func eventsLoadFailed(_ message: String) // - Handle the map request func openMaps(_ appleMap: URL?, _ googleMap: URL?) // - Handle the share action func shareEvent(_ body: String, _ subject: String, data: Data, mimeType: String) // - Schedule a local notification func scheduleReminder(_ date: String, _ location: String) // - Show the action view func showActions(_ presenter: EventActionsPresenter) // - Shows a banner func showBanner(_ message: String) }
// // SettingsViewController.swift // CardinalHealth // // Created by Volkov Alexander on 25.06.15. // Modified by Volkov Alexander on 16.07.15. // Modified by Volkov Alexander on 22.09.15. // Copyright (c) 2015 Topcoder. All rights reserved. // import UIKit /** * Settings screen * * @author Alexander Volkov * @version 1.1 * changes: * 1.1: * - alternative screen closure implemented * 1.2: * - keyboard issue fix */ class SettingsViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var showWelcomScreen: UISwitch! /* Optional callback that will be used to remove the screen. If not specified, then the view controller will be popped from the navigation view controller */ var closeCallbackAfterSave: (()->())? override func viewDidLoad() { super.viewDidLoad() emailField.delegate = self initNavigation() showWelcomScreen.setOn(isAlwaysShowWelcomeScreen(), animated: false) } @IBAction func showWelcomeScreenAction(sender: AnyObject) { setAlwaysShowWelcomeScreen(showWelcomScreen.on) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) initNavigation() emailField.becomeFirstResponder() emailField.text = LastUserInfo?.email ?? "" } /** Initialize navigation bar */ func initNavigation() { initNavigationBarTitle("SETTINGS".localized().uppercaseString) self.navigationItem.rightBarButtonItems = [UIBarButtonItem(title: "Save".localized(), style: UIBarButtonItemStyle.Plain, target: self, action: "saveEmail:")] if closeCallbackAfterSave == nil { initBackButtonFromChild() } } /** Dismiss the keyboard - parameter textField: the textField - returns: true */ func textFieldShouldReturn(textField: UITextField) -> Bool { emailField.resignFirstResponder() return true } /** Validate and save email - parameter sender: the button */ func saveEmail(sender: AnyObject) { let email = emailField.text! if email.trim() == "" { showAlert("EMAIL_REQUIRED".localized(), message: "EMAIL_EMPTY".localized()) return } if !ValidationUtils.validateEmail(email, { (error: RestError, res: RestResponse?) -> () in error.showError() }) { return } NSUserDefaults.standardUserDefaults().setObject(email, forKey: kUserEmail) NSUserDefaults.standardUserDefaults().synchronize() // Save email if LastUserInfo == nil { LastUserInfo = UserInfo(userName: email) } LastUserInfo?.email = email LastUserInfo?.userName = email // TODO Remove. This is just for demonstration. IdeasListViewControllerNeedToReload = true if let callback = closeCallbackAfterSave { callback() } else { self.navigationController?.popViewControllerAnimated(true) } } /** Validate and save email - parameter sender: dismiss keyboard event */ override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) self.view.endEditing(true) } }
// // ViewController.swift // DiceGame // // Created by AW on 9/16/21. // import UIKit class ViewController: UIViewController { var score = 0 @IBOutlet weak var dice1pic: UIImageView! @IBOutlet weak var dice2pic: UIImageView! @IBOutlet weak var scoreLbl: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func abvPressed(_ sender: UIButton) { let dice1 = Int.random(in: (1...6)) let dice2 = Int.random(in: (1...6)) let imgName1 = "Dice\(dice1)" let imgName2 = "Dice\(dice2)" dice1pic.image = UIImage(named: imgName1) dice2pic.image = UIImage(named: imgName2) if dice1+dice2 > 7 { score+=1 } else { score-=1 } scoreLbl.text = "Score = \(score)" } @IBAction func lucky7Pressed(_ sender: UIButton) { let dice1 = Int.random(in: (1...6)) let dice2 = Int.random(in: (1...6)) let imgName1 = "Dice\(dice1)" let imgName2 = "Dice\(dice2)" dice1pic.image = UIImage(named: imgName1) dice2pic.image = UIImage(named: imgName2) if dice1+dice2 == 7 { score+=7 } else { score-=1 } scoreLbl.text = "Score = \(score)" } @IBAction func belowPressed(_ sender: UIButton) { let dice1 = Int.random(in: (1...6)) let dice2 = Int.random(in: (1...6)) let imgName1 = "Dice\(dice1)" let imgName2 = "Dice\(dice2)" dice1pic.image = UIImage(named: imgName1) dice2pic.image = UIImage(named: imgName2) if dice1+dice2 < 7 { score+=1 } else { score-=1 } scoreLbl.text = "Score = \(score)" } }
// // TitlesTableViewController.swift // RSSFeed // // Created by Ivan Pavlov on 11/13/15. // Copyright © 2015 FreshThinking. All rights reserved. // import UIKit class TitlesTableViewController: UITableViewController, XMLParserDelegate { static var feedTitle : String! var xmlParser : XMLParser! var feedURL : NSURL! var refreshController : UIRefreshControl! @IBOutlet weak var tableTitle: UINavigationItem! func parsingWasFinished() { self.tableView.reloadData() } // Fetching HTML from url into a string and saving it as a html file to Documents directory //Reminder: Probably not the best to fetch data everytime user pulls-to-refresh. func backupCurrentFeed() { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { for dic in self.xmlParser.arrParsedData { let fm = NSFileManager() let url = NSURL(string: dic["link"]!) let htmlData = NSData(contentsOfURL: url!) let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [NSString] let documentsDirectory = paths[0] // Creating specific folder in Documents dir let RSSFolderPath = documentsDirectory.stringByAppendingPathComponent("/\(TitlesTableViewController.feedTitle)") as NSString do { try fm.createDirectoryAtPath(RSSFolderPath as String, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { print(error.localizedDescription); } let htmlFilePath = RSSFolderPath.stringByAppendingPathComponent("\(dic["title"]!).html") htmlData?.writeToFile(htmlFilePath, atomically: true) // print(htmlFilePath) } dispatch_async(dispatch_get_main_queue()) { // update some UI } } } func updateParsingRSSTitles() { let url = feedURL xmlParser = XMLParser() xmlParser.delegate = self xmlParser.startParsingWithContentsOfURL(url!) self.tableView.reloadData() self.backupCurrentFeed() } func refresh(sender:AnyObject) { refreshBegin("Refresh", refreshEnd: {(x:Int) -> () in self.updateParsingRSSTitles() self.refreshController.endRefreshing() } ) } func refreshBegin(newtext:String, refreshEnd:(Int) -> ()) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { sleep(2) dispatch_async(dispatch_get_main_queue()) { refreshEnd(0) } } } override func viewDidLoad() { super.viewDidLoad() tableTitle.title = TitlesTableViewController.feedTitle let timer = NSTimer.scheduledTimerWithTimeInterval(180, target: self, selector: "updateParsingRSSTitles", userInfo: nil, repeats: true) timer.fire() refreshController = UIRefreshControl() refreshController.attributedTitle = NSAttributedString(string: "Refreshing...") refreshController.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) tableView.addSubview(refreshController!) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if xmlParser.arrParsedData.count > 0 { return xmlParser.arrParsedData.count } else { let defaults = NSUserDefaults.standardUserDefaults() //MARK: - Checking if added RSS url is valid and if it was added offline. // Reminder: Add additional check to AddRSSViewController for adding non-rss urls. if defaults.objectForKey("\(TitlesTableViewController.feedTitle)arrParsedData") == nil { return 0 } let rowCount = defaults.objectForKey("\(TitlesTableViewController.feedTitle)arrParsedData")!.count return rowCount } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("idFeedTitleCell", forIndexPath: indexPath) as UITableViewCell var currentDictionary = Dictionary<String, String>() if !xmlParser.arrParsedData.isEmpty { currentDictionary = xmlParser.arrParsedData[indexPath.row] as Dictionary<String, String> } // If there is no connection if currentDictionary.isEmpty { let defaults = NSUserDefaults.standardUserDefaults() currentDictionary = defaults.objectForKey("\(TitlesTableViewController.feedTitle)arrParsedData")![indexPath.row] as! Dictionary<String, String> } cell.textLabel?.text = currentDictionary["title"] return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if !xmlParser.arrParsedData.isEmpty { let dictionary = xmlParser.arrParsedData[indexPath.row] as Dictionary<String, String> let contentLink = dictionary["link"] let contentViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("idContentViewController") as! ContentViewController contentViewController.contentURL = NSURL(string: contentLink!) showDetailViewController(contentViewController, sender: self) } else { // show offline let defaults = NSUserDefaults.standardUserDefaults() let dictionary = defaults.objectForKey("\(TitlesTableViewController.feedTitle)arrParsedData")![indexPath.row] as! Dictionary<String, String> let contentTitle = dictionary["title"]! as String let contentViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("idContentViewController") as! ContentViewController contentViewController.contentTitle = contentTitle showDetailViewController(contentViewController, sender: self) } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // DefaultWaiting.swift // CLXToast // // Created by chen liangxiu on 2018/1/25. // import Foundation final class DefaultWating: ToastContent, DefaultWaitingExport, DefaultCurrentWaitingExport { weak var toast: Toast! //为了链式语法,直接一步到位show出来 @discardableResult public func show(in container: UIView, with layout: ((Toast) -> Void)?, animated: Bool, completion: (() -> Void)?) -> Toast { return self.toast!.show(in: container, with: layout, animated: animated, completion: completion); } @discardableResult public func show(animated: Bool = true, with completion: (() -> Void)? = nil) -> Toast { return self.toast!.show(animated: animated, with: completion) } var contentInset: UIEdgeInsets = UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8) @discardableResult public func contentInset(_ inset: UIEdgeInsets) -> DefaultWating { contentInset = inset return self } var _activity: UIActivityIndicatorView! //菊花,如果为空,组件自己会创建,默认样式为白色(waiting模式) public func activityView(_ newValue: UIActivityIndicatorView?) -> DefaultWating { _activity = newValue return self } var _promptLabel: UILabel? //菊花提示(waiting模式) @discardableResult public func prompt(_ newValue: String?) -> DefaultWating {//菊花提示的链式快捷方式(waiting模式) if _promptLabel == nil { _promptLabel = UILabel() _promptLabel!.font = UIFont.systemFont(ofSize: 15.0) _promptLabel!.textColor = UIColor.white _promptLabel!.preferredMaxLayoutWidth = UIScreen.main.bounds.width * 0.8 _promptLabel!.numberOfLines = 0 } _promptLabel!.text = newValue if let toast = self.toast,let transaction = toast.myTransaction { if transaction.isExecuting { self.toast.setNeedsUpdateConstraints() } } return self } @discardableResult public func promptLabel(_ newValue: UILabel?) -> DefaultWating { _promptLabel = newValue return self } var _space: CGFloat = 4 @discardableResult public func interitemSpacing(_ space: CGFloat) -> DefaultWating { _space = max(space, 0.0) return self } init() { super.init(style: .waiting) } func dismiss() { self.dismiss(animated: true) } func dismiss(animated: Bool) { toast.dismiss() } override func addSubviews(to contentView: UIView) { if _activity == nil { _activity = UIActivityIndicatorView() _activity.hidesWhenStopped = false } if _activity.superview != contentView { contentView.addSubview(_activity) } _activity.startAnimating() let empty = _promptLabel?.text?.isEmpty ?? true if !empty && _promptLabel?.superview != contentView { contentView.addSubview(_promptLabel!) } } override func layoutSubviews(at contentView: UIView) { _activity.translatesAutoresizingMaskIntoConstraints = false let empty = _promptLabel?.text?.isEmpty ?? true if empty { let activityLeading = NSLayoutConstraint(item: _activity as Any, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: contentInset.left) let activityTop = NSLayoutConstraint(item: _activity as Any, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: contentInset.top) let activityTrailing = NSLayoutConstraint(item: _activity as Any, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -contentInset.right) let activityBottom = NSLayoutConstraint(item: _activity as Any, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: -contentInset.bottom) contentView.addConstraints([activityLeading, activityTop, activityTrailing, activityBottom]) } else { let activityLeading = NSLayoutConstraint(item: _activity as Any, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .leading, multiplier: 1, constant: contentInset.left) let activityTop = NSLayoutConstraint(item: _activity as Any, attribute: .top, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .top, multiplier: 1, constant: contentInset.top) let activityTrailing = NSLayoutConstraint(item: _activity as Any, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -contentInset.right) contentView.addConstraints([activityLeading, activityTop, activityTrailing]) //布局promptLabel _promptLabel!.translatesAutoresizingMaskIntoConstraints = false let promptLeading = NSLayoutConstraint(item: _promptLabel!, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .leading, multiplier: 1, constant: contentInset.left) let promptTop = NSLayoutConstraint(item: _promptLabel!, attribute: .top, relatedBy: .equal, toItem: _activity, attribute: .bottom, multiplier: 1, constant: _space / 2.0) let promptTrailing = NSLayoutConstraint(item: _promptLabel!, attribute: .trailing, relatedBy: .lessThanOrEqual, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -contentInset.right) let promptBottom = NSLayoutConstraint(item: _promptLabel!, attribute: .bottom, relatedBy: .lessThanOrEqual, toItem: contentView, attribute: .bottom, multiplier: 1, constant: -contentInset.bottom) contentView.addConstraints([promptLeading, promptTop, promptTrailing, promptBottom]) let activityCenterX = NSLayoutConstraint(item: _activity as Any, attribute: .centerX, relatedBy: .equal, toItem: _promptLabel!, attribute: .centerX, multiplier: 1, constant: 0) contentView.addConstraint(activityCenterX) } } }
// // ListView.VisibleContent.swift // ListableUI // // Created by Kyle Van Essen on 5/17/20. // import Foundation extension ListView { final class VisibleContent { private(set) var headerFooters : Set<HeaderFooter> = Set() private(set) var items : Set<Item> = Set() func update(with view : ListView) { let (newItems, newHeaderFooters) = self.calculateVisibleContent(in: view) // Find which items are newly visible (or are no longer visible). let removed = self.items.subtracting(newItems) let added = newItems.subtracting(self.items) removed.forEach { $0.item.setAndPerform(isDisplayed: false) } added.forEach { $0.item.setAndPerform(isDisplayed: true) } self.items = newItems self.headerFooters = newHeaderFooters // Inform any state reader callbacks of the changes. let callStateReader = removed.isEmpty == false || added.isEmpty == false if callStateReader { ListStateObserver.perform(view.stateObserver.onVisibilityChanged, "Visibility Changed", with: view) { actions in ListStateObserver.VisibilityChanged( actions: actions, positionInfo: view.scrollPositionInfo, displayed: added.map { $0.item.anyModel }, endedDisplay: removed.map { $0.item.anyModel } ) } } } var info : Info { Info( headerFooters: Set(self.headerFooters.map { Info.HeaderFooter(kind: $0.kind, indexPath: $0.indexPath) }), items: Set(self.items.map { Info.Item(identifier: $0.item.anyModel.anyIdentifier, indexPath: $0.indexPath) }) ) } private func calculateVisibleContent(in view : ListView) -> (Set<Item>, Set<HeaderFooter>) { let visibleFrame = view.collectionView.bounds let visibleAttributes = view.collectionViewLayout.visibleLayoutAttributesForElements(in: visibleFrame) ?? [] var items : Set<Item> = [] var headerFooters : Set<HeaderFooter> = [] for item in visibleAttributes { switch item.representedElementCategory { case .cell: items.insert(Item( indexPath: item.indexPath, item: view.storage.presentationState.item(at: item.indexPath) )) case .supplementaryView: let kind = SupplementaryKind(rawValue: item.representedElementKind!)! headerFooters.insert(HeaderFooter( kind: kind, indexPath: item.indexPath, headerFooter: view.storage.presentationState.headerFooter(of: kind, in: item.indexPath.section) )) case .decorationView: fatalError() @unknown default: assertionFailure("Unknown representedElementCategory type.") } } return (items, headerFooters) } } } extension ListView.VisibleContent { struct HeaderFooter : Hashable { let kind : SupplementaryKind let indexPath : IndexPath let headerFooter : PresentationState.HeaderFooterViewStatePair static func == (lhs : Self, rhs : Self) -> Bool { lhs.kind == rhs.kind && lhs.indexPath == rhs.indexPath && lhs.headerFooter === rhs.headerFooter } func hash(into hasher: inout Hasher) { hasher.combine(self.kind) hasher.combine(self.indexPath) hasher.combine(ObjectIdentifier(self.headerFooter)) } } struct Item : Hashable { let indexPath : IndexPath let item : AnyPresentationItemState static func == (lhs : Self, rhs : Self) -> Bool { lhs.indexPath == rhs.indexPath && lhs.item === rhs.item } func hash(into hasher: inout Hasher) { hasher.combine(self.indexPath) hasher.combine(ObjectIdentifier(self.item)) } } /// Note: Because this type exposes index paths and the internal `SupplementaryKind`, /// it is intended for internal usage or unit testing purposes only. /// Public consumers and APIs should utilize `ListScrollPositionInfo`. struct Info : Equatable { var headerFooters : Set<HeaderFooter> var items : Set<Item> struct HeaderFooter : Hashable { var kind : SupplementaryKind var indexPath : IndexPath } struct Item : Hashable { var identifier : AnyIdentifier var indexPath : IndexPath } } }
// // SwipeTableViewController.swift // Todoey // // Created by Donal on 7/27/19. // Copyright © 2019 Donal MacCoon. All rights reserved. // import UIKit import SwipeCellKit class SwipeTableViewController: UITableViewController, SwipeTableViewCellDelegate { override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 80.0 // Tells us approximately where our data is saved though the sqlite db is not in documents but instead under library/application support print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)) } // TableView Datasource Methods override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SwipeTableViewCell cell.delegate = self return cell } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? { guard orientation == .right else { return nil } let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in // handle action by updating model with deletion self.updateModel(at: indexPath) } // customize the action appearance deleteAction.image = UIImage(named: "delete-icon") return [deleteAction] } // This swipe to delete functionality crashes the app. func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions { var options = SwipeOptions() options.expansionStyle = .destructive return options } func updateModel (at indexPath : IndexPath) { // Update data model. } }
// // Profile.swift // Audio Capture and Playback // // Created by Kyle Moore on 3/20/19. // Copyright © 2019 kylemoore. All rights reserved. // import Foundation struct profile{ let title: String let body: [String : Any] let filename: String init(title: String, body: [String : Any], filename: String){ self.title = title self.body = body self.filename = filename } }
import UIKit //class SomeClass { // var number = 1 //} // //let classReference1 = SomeClass() //classReference1.number = 2 // //let classReference2 = SomeClass() //classReference2.number = 3 // //print("A1- \(classReference1.number), A2- \(classReference2.number)") // 1 class SomeClass { var number = 1 deinit { } } // 2 let classInstance1 = SomeClass() classInstance1.number = 2 // 3 let classInstance2 = classInstance1 classInstance2.number = 3 // 4 print("classInstance1- \(classInstance1.number), classInstance2- \(classInstance2.number)") // output is - classInstance1- 3, classInstance2- 3 // 1 struct SomeStruct { var number = 1 } // 2 var structInstance1 = SomeStruct() structInstance1.number = 2 // 3 var structInstance2 = structInstance1 structInstance2.number = 3 // 4 print("structInstance1- \(structInstance1.number), structInstance2- \(structInstance2.number)") // output is - structInstance1- 2, structInstance2- 3
// // CreateGroupController.swift // witOrbit // // Created by Gul Mehru on 2/19/18. // Copyright © 2018 Gul Mehru. All rights reserved. // import UIKit import CoreData class CreateGroupController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate ,UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate { var image: UIImage? let openButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(imagePicker), for: .touchUpInside) button.setFAIcon(icon: .FAUserPlus, iconSize: 55, forState: .normal) button.setFATitleColor(color: UIColor(red: 14/255 , green: 116/255 , blue: 130/255 , alpha: 1), forState: .normal) // button.layer.cornerRadius = button.frame.width / 2 return button }() override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } @objc func imagePicker() { let imagePicker = UIImagePickerController() imagePicker.delegate = self let actionSheet = UIAlertController(title: "Photo Source", message: "Choose Source", preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (UIAlertAction) in imagePicker.sourceType = .camera self.present(imagePicker, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (UIAlertAction) in imagePicker.sourceType = .photoLibrary self.present(imagePicker, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel ", style: .cancel, handler: nil)) self.present(actionSheet, animated: true, completion: nil) } let nameLabel: UILabel = { let label = UILabel() label.text = "Group Name" label.textAlignment = .left label.textColor = UIColor.lightGray label.font = label.font.withSize(16) return label }() let nameTextView: UITextField = { let text = HoshiTextField() text.layer.masksToBounds = true text.borderInactiveColor = UIColor.darkGray text.borderActiveColor = UIColor(red: 14/255 , green: 116/255 , blue: 130/255 , alpha: 1) text.textAlignment = .left text.font = text.font?.withSize(16) text.keyboardType = UIKeyboardType.default return text }() let descriptionLabel: UILabel = { let label = UILabel() label.text = "Description" label.textAlignment = .left label.textColor = UIColor.lightGray label.font = label.font.withSize(16) return label }() let descriptionTextView: UITextField = { let text = HoshiTextField() text.layer.masksToBounds = true text.borderInactiveColor = UIColor.darkGray text.borderActiveColor = UIColor(red: 14/255 , green: 116/255 , blue: 130/255 , alpha: 1) text.textAlignment = .left text.font = text.font?.withSize(16) text.keyboardType = UIKeyboardType.default return text }() let universityLabel: UILabel = { let label = UILabel() label.text = "University" label.textAlignment = .left label.textColor = UIColor.lightGray label.font = label.font.withSize(16) return label }() let universityTextView: UITextField = { let text = HoshiTextField() text.layer.masksToBounds = true text.borderInactiveColor = UIColor.darkGray text.borderActiveColor = UIColor(red: 14/255 , green: 116/255 , blue: 130/255 , alpha: 1) text.textAlignment = .left text.font = text.font?.withSize(16) text.keyboardType = UIKeyboardType.default return text }() let departmentLabel: UILabel = { let label = UILabel() label.text = "Department" label.textAlignment = .left label.textColor = UIColor.lightGray label.font = label.font.withSize(16) return label }() let departmentTextView: UITextField = { let text = HoshiTextField() text.layer.masksToBounds = true text.borderInactiveColor = UIColor.darkGray text.borderActiveColor = UIColor(red: 14/255 , green: 116/255 , blue: 130/255 , alpha: 1) text.textAlignment = .left text.font = text.font?.withSize(16) text.keyboardType = UIKeyboardType.default return text }() let lowerView: UIView = { let view = UIView() view.backgroundColor = UIColor(red: 14/255 , green: 116/255 , blue: 130/255 , alpha: 1) view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var createButton: UIButton = { let button = UIButton() // button.titleLabel?.text = "CREATE" button.setTitle("Create", for: .normal) button.addTarget(self, action: #selector(insertData), for: .touchUpInside) return button }() func fetchData() { do { let data = try context.fetch(Groups.fetchRequest()) numberOfGroups = data as! [Groups] } catch { } } var uni = ["FAST National University", "University of Agriculture, Faisalabad", "Government College University, Faisalabad", "Government College Women University (Faisalabad)"] var dept = ["Computing", "Engineering", "Management Sciences", "Sciences & Humanities"] var uniPickerView = UIPickerView() var deptPickerView = UIPickerView() func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { var countRows : Int = uni.count if pickerView == deptPickerView { countRows = self.dept.count } return countRows } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickerView == uniPickerView{ self.universityTextView.text = self.uni[row] // self.uniPickerView.isHidden = true } else if pickerView == deptPickerView { self.departmentTextView.text = self.dept[row] // self.deptPickerView.isHidden = true } universityTextView.text = uni[row] } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if pickerView == uniPickerView { let titleRow = uni[row] return titleRow } else if pickerView == deptPickerView { let titleRow = dept[row] return titleRow } return "" } func textFieldDidBeginEditing(_ textField: UITextField) { if (textField == self.universityTextView) { self.uniPickerView.isHidden = false } else if (textField == self.departmentTextView) { self.deptPickerView.isHidden = false } } var numberOfGroups = [Groups]() @objc func insertData() { let delegate = UIApplication.shared.delegate as? AppDelegate print(numberOfGroups.count) if (nameTextView.text?.isNotEmpty)! && (descriptionTextView.text?.isNotEmpty)! { if let context = delegate?.persistentContainer.viewContext{ let steve = NSEntityDescription.insertNewObject(forEntityName: "Groups", into: context) as! Groups steve.group_name = nameTextView.text if image == nil { image = #imageLiteral(resourceName: "itempire-web") } else { let imageData = UIImageJPEGRepresentation( image!, 1) steve.img_link = imageData as! Data } if numberOfGroups.count == 0{ steve.group_id = 1 } else{ steve.group_id = Int16(numberOfGroups.count) + 1 } steve.created_date = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: DateFormatter.Style.medium, timeStyle: DateFormatter.Style.short) } do{ try(context.save()) }catch let error{ print(error) } // self.dismiss(animated: true, completion: nil) // let layout = UICollectionViewFlowLayout() // let controller = GroupsController(collectionViewLayout: layout) navigationController?.pushViewController(GroupLinkController(), animated: true) } else{ let alert = UIAlertController(title: "Sorry", message: "Fill all required fields (*) .", preferredStyle: UIAlertControllerStyle.alert) // add an action (button) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) // show the alert self.present(alert, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white let title = UILabel() title.text = "Create Groups" title.textColor = UIColor.white navigationItem.titleView = title uniPickerView.delegate = self uniPickerView.dataSource = self deptPickerView.delegate = self deptPickerView.dataSource = self fetchData() print(numberOfGroups.count) view.addSubview(openButton) view.addSubview(nameLabel) view.addSubview(nameTextView) view.addSubview(descriptionLabel) view.addSubview(descriptionTextView) view.addSubview(universityLabel) view.addSubview(universityTextView) view.addSubview(departmentLabel) view.addSubview(departmentTextView) view.addSubview(lowerView) view.addSubview(createButton) universityTextView.inputView = uniPickerView departmentTextView.inputView = deptPickerView openButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true view.addConstraintsWithFormat(format: "V:|-70-[v0(120)]", views: openButton) view.addConstraintsWithFormat(format: "H:[v0(120)]", views: openButton) // openButton.layer.cornerRadius = 40 view.addConstraintsWithFormat(format: "H:|-10-[v0]", views: nameLabel) view.addConstraintsWithFormat(format: "H:|-10-[v0]-10-|", views: nameTextView) view.addConstraintsWithFormat(format: "H:|-10-[v0]", views: descriptionLabel) view.addConstraintsWithFormat(format: "H:|-10-[v0]-10-|", views: descriptionTextView) view.addConstraintsWithFormat(format: "H:|-10-[v0]", views: universityLabel) view.addConstraintsWithFormat(format: "H:|-10-[v0]-10-|", views: universityTextView) view.addConstraintsWithFormat(format: "H:|-10-[v0]", views: departmentLabel) view.addConstraintsWithFormat(format: "H:|-10-[v0]-10-|", views: departmentTextView) view.addConstraintsWithFormat(format: "V:|-250-[v0]-10-[v1(25)]-10-[v2]-10-[v3(25)]-10-[v4]-10-[v5(25)]-10-[v6]-10-[v7(25)]", views: nameLabel, nameTextView, descriptionLabel, descriptionTextView, universityLabel, universityTextView, departmentLabel, departmentTextView) view.addConstraintsWithFormat(format: "H:|[v0]|", views: lowerView) view.addConstraintsWithFormat(format: "V:[v0(\(self.view.frame.height / 10))]|", views: lowerView) view.addConstraintsWithFormat(format: "H:[v0(70)]", views: createButton) view.addConstraintsWithFormat(format: "V:[v0(30)]", views: createButton) createButton.centerXAnchor.constraint(equalTo: lowerView.centerXAnchor).isActive = true createButton.centerYAnchor.constraint(equalTo: lowerView.centerYAnchor).isActive = true } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){ image = info[UIImagePickerControllerOriginalImage] as! UIImage openButton.setImage(image, for: .normal) // openButton.imageView?.heightAnchor.constraint(equalToConstant: 120).isActive = true // openButton.imageView?.widthAnchor.constraint(equalToConstant: 120).isActive = true openButton.imageView?.layer.cornerRadius = 60 picker.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil ) } }
// // TTScrollView.swift // AnimationTransition // // Created by TAO on 2018/1/8. // Copyright © 2018年 ShaggyT. All rights reserved. // import UIKit class TTScrollView: UIScrollView { /// 重写手势, 如果是 左滑, 则禁止 scrollView 自带手势 override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) { let pan = gestureRecognizer as! UIPanGestureRecognizer print("\(pan.translation(in: self).x) -- \(self.contentOffset.x)") if pan.translation(in: self).x > 0, self.contentOffset.x == 0 { print("左滑手势") return false } if pan.translation(in: self).x < 0, self.contentSize.width - self.contentOffset.x <= self.bounds.width { print("右滑手势") return false } } return super.gestureRecognizerShouldBegin(gestureRecognizer) } }
import SwiftCheck import Bow public class EquatableLaws<A: Equatable & Arbitrary> { public static func check() { identity() commutativity() transitivity() } private static func identity() { property("Identity: Every object is equal to itself") <~ forAll { (a: A) in a == a } } private static func commutativity() { property("Equality is commutative") <~ forAll { (a: A, b: A) in (a == b) == (b == a) } } private static func transitivity() { property("Equality is transitive") <~ forAll { (a: A, b: A, c: A) in // (a == b) && (b == c) --> (a == c) not((a == b) && (b == c)) || (a == c) } } }
// // NavController.swift // JobSpot-iOS // // Created by Marlow Fernandez on 10/18/17. // Copyright © 2017 JobSpot. All rights reserved. // import Foundation import UIKit class NavController: UINavigationController { override func viewDidLoad() { if UIDevice.current.userInterfaceIdiom == .pad { debugPrint("Hello this is an ipad") // this code will be executed if the device is an iPad func supportedInterfaceOrientations() -> Int { return UIInterfaceOrientation.landscapeLeft.rawValue } func shouldAutorotate() -> Bool { return false } } if UIDevice.current.userInterfaceIdiom == .phone { debugPrint("Hello this is an iphone") // this code will be executed if the device is an iPad func supportedInterfaceOrientations() -> Int { return UIInterfaceOrientation.portrait.rawValue } func shouldAutorotate() -> Bool { return false } } } }
import Foundation protocol ThrottlerDelegate: class { func throttler(_ throttler: Throttler, didExecuteJobAt lastExecutionDate: Date?) /** when the timer has exceeded from last execution */ func throttlerDidFinishCycle(_ throttler: Throttler) } class Throttler { var job: DispatchWorkItem! var isCanceled: Bool { return job.isCancelled } var maxInterval: Int private var cycleTimer: Timer? private var previousRun: Date? { didSet { self.cycleTimer?.invalidate() self.cycleTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(maxInterval), repeats: false, block: { (_) in self.delegate?.throttlerDidFinishCycle(self) }) } } var queue: DispatchQueue weak var delegate: ThrottlerDelegate? init(maxInterval: Int, queue: DispatchQueue = DispatchQueue.main, delegate: ThrottlerDelegate?) { self.maxInterval = maxInterval self.queue = queue self.delegate = delegate } func invoke(block: @escaping () -> Void) { guard self.previousRun == nil else { return } self.job = DispatchWorkItem(block: { self.previousRun = Date() block() }) job.notify(queue: queue) { self.delegate?.throttler(self, didExecuteJobAt: self.previousRun) } queue.async(execute: self.job) } } class PostThrottler: Throttler { private var firstInvoke: Date? override func invoke(block: @escaping () -> Void) { let delay: Int //is there a previous invoke scheduled? if let firstInvoke = self.firstInvoke { self.job.cancel() delay = self.maxInterval - Date.seconds(from: firstInvoke) //store the first invoke } else { delay = self.maxInterval self.firstInvoke = Date() } self.job = DispatchWorkItem(block: { self.firstInvoke = Date() block() }) job.notify(queue: queue) { self.delegate?.throttler(self, didExecuteJobAt: self.firstInvoke) } self.queue.asyncAfter(deadline: .now() + Double(delay), execute: self.job) } } class ContinuousThrottler: Throttler { private var cycleTimer: Timer? private var mostRecentInvoke: Date? { didSet { self.cycleTimer?.invalidate() self.cycleTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(maxInterval), repeats: false, block: { (_) in self.delegate?.throttlerDidFinishCycle(self) }) } } override func invoke(block: @escaping () -> Void) { if self.mostRecentInvoke != nil { self.job.cancel() } self.mostRecentInvoke = Date() let delay = self.maxInterval self.job = DispatchWorkItem(block: { block() }) job.notify(queue: queue) { self.delegate?.throttler(self, didExecuteJobAt: self.mostRecentInvoke) } self.queue.asyncAfter(deadline: .now() + Double(delay), execute: self.job) } } class ThrottleSingleton: ThrottlerDelegate { static var shared = ThrottleSingleton() private var throttles: [String: Throttler] = [:] subscript(_ identifier: String) -> Throttler? { set { throttles[identifier] = newValue } get { return throttles[identifier] } } private init() { } // MARK: - RETURN VALUES // MARK: - VOID METHODS func throttler(_ throttler: Throttler, didExecuteJobAt lastExecutionDate: Date?) { } func throttlerDidFinishCycle(_ throttler: Throttler) { if let indexToRemove = throttles.index(where: { keyValuePair in keyValuePair.value === throttler }) { throttles.remove(at: indexToRemove) } } // MARK: - IBACTIONS // MARK: - LIFE CYCLE } public func throttle(for seconds: Int, identifier: String = #function, block: @escaping () -> Void) { let manager = ThrottleSingleton.shared guard manager[identifier] == nil else { return } let throttler = Throttler(maxInterval: seconds, delegate: manager) manager[identifier] = throttler throttler.invoke(block: block) } public func postThrottle(for seconds: Int, identifier: String = #function, block: @escaping () -> Void) { let manager = ThrottleSingleton.shared let throttler: Throttler if let exisitingThrottler = manager[identifier] { throttler = exisitingThrottler } else { throttler = PostThrottler(maxInterval: seconds, delegate: manager) manager[identifier] = throttler } throttler.invoke(block: block) } public func continuousThrottle(for seconds: Int, identifier: String = #function, block: @escaping () -> Void) { let manager = ThrottleSingleton.shared let throttler: Throttler if let exisitingThrottler = manager[identifier] { throttler = exisitingThrottler } else { throttler = ContinuousThrottler(maxInterval: seconds, delegate: manager) manager[identifier] = throttler } throttler.invoke(block: block) } private extension Date { static func seconds(from referenceDate: Date) -> Int { return Int(Date().timeIntervalSince(referenceDate).rounded()) } }
// // Ordering.swift // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// Ordering represents a single ordering component in the query ORDER BY clause. public protocol OrderingProtocol { } @available(*, deprecated, message: "Please use QuerySortOrder") typealias SortOrder = QuerySortOrder /// SortOrder allows to specify the ordering direction which is ascending or /// descending order. The default ordering is the ascending order. public protocol QuerySortOrder: OrderingProtocol { /// Specifies ascending order. /// /// - Returns: The ascending Ordering object. func ascending() -> OrderingProtocol /// Specifies descending order. /// /// - Returns: The descending Ordering object. func descending() -> OrderingProtocol } /// Ordering factory. public final class Ordering { /// Create an Ordering instance with the given property name. /// /// - Parameter property: The property name. /// - Returns: The SortOrder object used for specifying the sort order, /// ascending or descending order. public static func property(_ property: String) -> QuerySortOrder { return expression(Expression.property(property)) } /// Create an Ordering instance with the given expression. /// /// - Parameter expression: The Expression object. /// - Returns: The SortOrder object used for specifying the sort order, /// ascending or descending order. public static func expression(_ expression: ExpressionProtocol) -> QuerySortOrder { let sortOrder = CBLQueryOrdering.expression(expression.toImpl()) return _QuerySortOrder(impl: sortOrder) } } /* internal */ class QueryOrdering : OrderingProtocol { let impl: CBLQueryOrdering init(impl: CBLQueryOrdering) { self.impl = impl } func toImpl() -> CBLQueryOrdering { return self.impl } static func toImpl(orderings: [OrderingProtocol]) -> [CBLQueryOrdering] { var impls: [CBLQueryOrdering] = [] for o in orderings { impls.append(o.toImpl()) } return impls; } } /* internal */ class _QuerySortOrder: QueryOrdering, QuerySortOrder { public func ascending() -> OrderingProtocol { let o = self.impl as! CBLQuerySortOrder return QueryOrdering(impl: o.ascending()) } public func descending() -> OrderingProtocol { let o = self.impl as! CBLQuerySortOrder return QueryOrdering(impl: o.descending()) } } extension OrderingProtocol { func toImpl() -> CBLQueryOrdering { if let o = self as? QueryOrdering { return o.toImpl() } fatalError("Unsupported ordering.") } }
// // LevelUnit.swift // TZ-Olimob // // Created by MAC on 28.08.2020. // Copyright © 2020 Gera Volobuev. All rights reserved. // import Foundation import SpriteKit class LevelUnit:SKNode { var imageName:String = "" var backgroundSprite:SKSpriteNode = SKSpriteNode() var levelUnitWidth:CGFloat = 0 var levelUnitHeight:CGFloat = 0 var theType:LevelType = LevelType.ground var xAmount:CGFloat = 1 //essentially this is our speed var direction:CGFloat = 1 //will be saved as either 1 or -1 var numberOfObjectsInLevel:UInt32 = 0 var offscreenCounter:Int = 0 //anytime an object goes offscreen we add to this, for resetting speed purposes var topSpeedgrass:UInt32 = 5 var topSpeedWater:UInt32 = 2 var maxObjectsInLevelUnit:UInt32 = 2 var isFirstUnit:Bool = false required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init () { super.init() } func setUpLevel(){ let diceRoll = arc4random_uniform(5) if (diceRoll == 0) { imageName = "Wild_West_Background1" } else if (diceRoll == 1) { imageName = "Wild_West_Background2" } else if (diceRoll == 2) { imageName = "Wild_West_Background1" } else if (diceRoll == 3) { imageName = "Wild_West_Background2" } else if (diceRoll == 4) { if (isFirstUnit == false) { imageName = "Wild_West_Background3" theType = LevelType.water } else { imageName = "Wild_West_Background2" } } let theSize:CGSize = CGSize(width: levelUnitWidth, height: levelUnitHeight) let tex:SKTexture = SKTexture(imageNamed: imageName) backgroundSprite = SKSpriteNode(texture: tex, color: SKColor.clear, size: theSize) self.addChild(backgroundSprite) self.name = "levelUnit" self.position = CGPoint(x: backgroundSprite.size.width / 2, y: 0) backgroundSprite.physicsBody = SKPhysicsBody(rectangleOf: backgroundSprite.size, center:CGPoint(x: 0, y: -backgroundSprite.size.height * 0.88)) backgroundSprite.physicsBody!.isDynamic = false backgroundSprite.physicsBody!.restitution = 0 if (theType == LevelType.water) { backgroundSprite.physicsBody!.categoryBitMask = BodyType.water.rawValue backgroundSprite.physicsBody!.contactTestBitMask = BodyType.water.rawValue self.zPosition = 400 } else if (theType == LevelType.ground){ backgroundSprite.physicsBody!.categoryBitMask = BodyType.ground.rawValue backgroundSprite.physicsBody!.contactTestBitMask = BodyType.ground.rawValue } if ( isFirstUnit == false ) { createObstacle() } } func createObstacle() { numberOfObjectsInLevel = arc4random_uniform(maxObjectsInLevelUnit) numberOfObjectsInLevel = numberOfObjectsInLevel + 1 // so it can't be 0 //was // for (var i = 0; i < Int(numberOfObjectsInLevel); i++) { for _ in 0 ..< Int(numberOfObjectsInLevel) { let obstacle:Object = Object() obstacle.theType = theType obstacle.levelUnitWidth = levelUnitWidth obstacle.levelUnitHeight = levelUnitHeight obstacle.createObject() addChild(obstacle) } } }
// // ItemResponse.swift // tiki-demo // // Created by Tom on 2/20/19. // Copyright © 2019 A Strange Studio. All rights reserved. // import Foundation struct ItemResponse { var items = [Item]() } extension ItemResponse { private enum Keys: String, SerializationKey { case keywords } init(serialization: Serialization) { if let serial: [Serialization] = serialization.value(forKey: Keys.keywords) { items = serial.map({ (keywordSerial) -> Item in return Item(serialization: keywordSerial) }) } } }
// // CustomerRegisterViewController.swift // QNO // // Created by Xinhong LIU on 15/1/2016. // Copyright © 2016 September. All rights reserved. // import UIKit import PKHUD class CustomerRegisterViewController: MasterViewController { @IBOutlet weak var accountTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var mobileTextField: UITextField! @IBOutlet weak var addressTextField: UITextField! override func viewDidLoad() { self.isLoginPage = true super.viewDidLoad() } // return error, nil if no error func validateForm() -> String? { let account = accountTextField.text guard account != nil && account != "" else { return "Your account cannot be blank" } return nil } @IBAction func register(sender: AnyObject) { let error = validateForm() let account = accountTextField.text! let email = emailTextField.text let mobile = mobileTextField.text let address = addressTextField.text guard error == nil else { let alertController = UIAlertController(title: "Invalid inputs", message: error, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) return } PKHUD.sharedHUD.contentView = PKHUDProgressView() PKHUD.sharedHUD.show() let api = QNOAPI() do { try api.addCustomer(account, email: email, mobile: mobile, address: address, callback: { (errorMessage) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in PKHUD.sharedHUD.hide() }) if errorMessage == nil { let alertController = UIAlertController(title: "Account has been created", message: "You can login now", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (UIAlertAction) -> Void in QNOStorage.setCustomerId(account) })) self.presentViewController(alertController, animated: true, completion: nil) } else { let alertController = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } }) } catch QNOAPIRuntimeError.InvalidOperation { NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in PKHUD.sharedHUD.hide() }) let alertController = UIAlertController(title: "Invalid operation", message: "The operation is not permitted.", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) return } catch { NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in PKHUD.sharedHUD.hide() }) print("Unknown error") } } }
// // ContentView.swift // CardListDemo // // Created by Robin on 2019/11/27. // Copyright © 2019 RobinChao. All rights reserved. // import SwiftUI private let dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium return dateFormatter }() struct ContentView: View { let cardDatas: [CardData] = { var datas: [CardData] = [] datas.append(CardData(id: 1, image: "swiftui-button", category: "SwiftUI", heading: "使用SwiftUI绘制视图的圆角边框", author: "Written by Robin Chao")) datas.append(CardData(id: 2, image: "natural-language-api", category: "MachineLearning", heading: "教程 : 如何使用Google提供的NLP接口实现聊天机器人程序", author: "Written by Robin Chao")) datas.append(CardData(id: 3, image: "macos-programming", category: "MacOS", heading: "开始使用Swift构建MacOS应用软件", author: "Written by Robin Chao")) datas.append(CardData(id: 4, image: "flutter-app", category: "Flutter", heading: "使用Flutter构建漂亮的本地化应用", author: "Written by Robin Chao")) return datas }() var currentDate = Date() var body: some View { VStack(alignment: .leading) { ScrollView(.vertical, showsIndicators: true){ Spacer() HStack { VStack(alignment: .leading) { Text("\(currentDate, formatter: dateFormatter)") .font(.headline) .foregroundColor(.secondary) Text("Your Reading") .font(.title) .fontWeight(.black) .foregroundColor(.primary) } .padding(.leading, 15) Spacer() Image("mona-heart-hug-facebook") .resizable() .scaledToFill() .clipShape(Circle()) .overlay(Circle().stroke(Color.gray, lineWidth: 1)) .frame(width: 45, height: 45) .padding(.trailing, 15) } .padding(.bottom, -10) ForEach(self.cardDatas) { card in CardView(card: card) } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
import UIKit open class ImageAttachmentCell: AttachmentCell { // MARK: - Properties open override class var reuseIdentifier: String { return "ImageAttachmentCell" } public let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill return imageView }() // MARK: - Initialization public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } open override func prepareForReuse() { super.prepareForReuse() imageView.image = nil } // MARK: - Setup private func setup() { containerView.addSubview(imageView) imageView.fillSuperview() } }